task_url
stringlengths 30
116
| task_name
stringlengths 2
86
| task_description
stringlengths 0
14.4k
| language_url
stringlengths 2
53
| language_name
stringlengths 1
52
| code
stringlengths 0
61.9k
|
---|---|---|---|---|---|
http://rosettacode.org/wiki/Sum_multiples_of_3_and_5 | Sum multiples of 3 and 5 | Task
The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n.
Show output for n = 1000.
This is is the same as Project Euler problem 1.
Extra credit: do this efficiently for n = 1e20 or higher.
| #C | C | #include <stdio.h>
#include <stdlib.h>
unsigned long long sum35(unsigned long long limit)
{
unsigned long long sum = 0;
for (unsigned long long i = 0; i < limit; i++)
if (!(i % 3) || !(i % 5))
sum += i;
return sum;
}
int main(int argc, char **argv)
{
unsigned long long limit;
if (argc == 2)
limit = strtoull(argv[1], NULL, 10);
else
limit = 1000;
printf("%lld\n", sum35(limit));
return 0;
} |
http://rosettacode.org/wiki/Sum_digits_of_an_integer | Sum digits of an integer | Task
Take a Natural Number in a given base and return the sum of its digits:
110 sums to 1
123410 sums to 10
fe16 sums to 29
f0e16 sums to 29
| #Befunge | Befunge | " :rebmuN">:#,_&0v
|_,#!>#:<"Base: "<
<>10g+\00g/:v:p00&
v^\p01<%g00:_55+\>
>" :muS">:#,_$\.,@ |
http://rosettacode.org/wiki/Sum_of_squares | Sum of squares | Task
Write a program to find the sum of squares of a numeric vector.
The program should work on a zero-length vector (with an answer of 0).
Related task
Mean
| #C.2B.2B | C++ | #include <iostream>
#include <numeric>
#include <vector>
double add_square(double prev_sum, double new_val)
{
return prev_sum + new_val*new_val;
}
double vec_add_squares(std::vector<double>& v)
{
return std::accumulate(v.begin(), v.end(), 0.0, add_square);
}
int main()
{
// first, show that for empty vectors we indeed get 0
std::vector<double> v; // empty
std::cout << vec_add_squares(v) << std::endl;
// now, use some values
double data[] = { 0, 1, 3, 1.5, 42, 0.1, -4 };
v.assign(data, data+7);
std::cout << vec_add_squares(v) << std::endl;
return 0;
} |
http://rosettacode.org/wiki/Substitution_cipher | Substitution cipher | Substitution Cipher Implementation - File Encryption/Decryption
Task
Encrypt a input/source file by replacing every upper/lower case alphabets of the source file with another predetermined upper/lower case alphabets or symbols and save it into another output/encrypted file and then again convert that output/encrypted file into original/decrypted file.
This type of Encryption/Decryption scheme is often called a Substitution Cipher.
Related tasks
Caesar cipher
Rot-13
Vigenère Cipher/Cryptanalysis
See also
Wikipedia: Substitution cipher
| #Ada | Ada |
with Ada.Command_Line; use Ada.Command_Line;
with Ada.Sequential_IO;
with Ada.Strings.Maps; use Ada.Strings.Maps;
with Ada.Text_IO;
procedure Cipher is
package Char_IO is new Ada.Sequential_IO (Character);
use Char_IO;
Alphabet: constant String := "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
Key : constant String := "VsciBjedgrzyHalvXZKtUPumGfIwJxqOCFRApnDhQWobLkESYMTN";
My_Map : Character_Mapping;
Input, Output : File_Type;
Buffer : Character;
begin
declare
use Ada.Text_IO;
begin
if Argument_Count /= 1 then
Put_Line("Usage: " & Command_Name & " <encode|decode>");
else
if Argument(1) = "encode" then
My_Map := To_Mapping(From => Alphabet, To => Key);
elsif Argument(1) = "decode" then
My_Map := To_Mapping(From => Key, To => Alphabet);
else
Put_Line("Unrecognised Argument: " & Argument(1));
return;
end if;
end if;
end;
Open (File => Input, Mode => In_File, Name => "input.txt");
Create (File => Output, Mode => Out_File, Name => "output.txt");
loop
Read (File => Input, Item => Buffer);
Buffer := Value(Map => My_Map, Element => Buffer);
Write (File => Output, Item => Buffer);
end loop;
exception
when Char_IO.End_Error =>
if Is_Open(Input) then
Close (Input);
end if;
if Is_Open(Output) then
Close (Output);
end if;
end Cipher;
|
http://rosettacode.org/wiki/Substitution_cipher | Substitution cipher | Substitution Cipher Implementation - File Encryption/Decryption
Task
Encrypt a input/source file by replacing every upper/lower case alphabets of the source file with another predetermined upper/lower case alphabets or symbols and save it into another output/encrypted file and then again convert that output/encrypted file into original/decrypted file.
This type of Encryption/Decryption scheme is often called a Substitution Cipher.
Related tasks
Caesar cipher
Rot-13
Vigenère Cipher/Cryptanalysis
See also
Wikipedia: Substitution cipher
| #Arturo | Arturo | key: {:]kYV}(!7P$n5_0i R:?jOWtF/=-pe'AD&@r6%ZXs"v*N[#wSl9zq2^+g;LoB`aGh{3.HIu4fbK)mU8|dMET><,Qc\C1yxJ:}
encode: function [str][
bs: new []
loop split str 'ch ->
'bs ++ to :string key\[(to :integer to :char ch)-32]
return join bs
]
decode: function [str][
bs: new []
loop split str 'ch ->
'bs ++ to :string to :char (index key ch)+32
return join bs
]
s: "The quick brown fox jumps over the lazy dog, who barks VERY loudly!"
enc: encode s
print ["encoded:" enc]
print ["decoded:" decode enc] |
http://rosettacode.org/wiki/Sum_and_product_of_an_array | Sum and product of an array | Task
Compute the sum and product of an array of integers.
| #Babel | Babel | main: { [2 3 5 7 11 13] sp }
sum! : { <- 0 -> { + } eachar }
product!: { <- 1 -> { * } eachar }
sp!:
{ dup
sum %d cr <<
product %d cr << }
Result:
41
30030 |
http://rosettacode.org/wiki/Sum_and_product_of_an_array | Sum and product of an array | Task
Compute the sum and product of an array of integers.
| #BASIC | BASIC | dim array(5) as integer = { 1, 2, 3, 4, 5 }
dim sum as integer = 0
dim prod as integer = 1
for index as integer = lbound(array) to ubound(array)
sum += array(index)
prod *= array(index)
next |
http://rosettacode.org/wiki/Sum_of_a_series | Sum of a series | Compute the nth term of a series, i.e. the sum of the n first terms of the corresponding sequence.
Informally this value, or its limit when n tends to infinity, is also called the sum of the series, thus the title of this task.
For this task, use:
S
n
=
∑
k
=
1
n
1
k
2
{\displaystyle S_{n}=\sum _{k=1}^{n}{\frac {1}{k^{2}}}}
and compute
S
1000
{\displaystyle S_{1000}}
This approximates the zeta function for S=2, whose exact value
ζ
(
2
)
=
π
2
6
{\displaystyle \zeta (2)={\pi ^{2} \over 6}}
is the solution of the Basel problem.
| #BQN | BQN | +´÷√⁼1+↕1000
1.6439345666815597 |
http://rosettacode.org/wiki/Sum_to_100 | Sum to 100 | Task
Find solutions to the sum to one hundred puzzle.
Add (insert) the mathematical
operators + or - (plus
or minus) before any of the digits in the
decimal numeric string 123456789 such that the
resulting mathematical expression adds up to a
particular sum (in this iconic case, 100).
Example:
123 + 4 - 5 + 67 - 89 = 100
Show all output here.
Show all solutions that sum to 100
Show the sum that has the maximum number of solutions (from zero to infinity‡)
Show the lowest positive sum that can't be expressed (has no solutions), using the rules for this task
Show the ten highest numbers that can be expressed using the rules for this task (extra credit)
‡ (where infinity would be a relatively small 123,456,789)
An example of a sum that can't be expressed (within the rules of this task) is: 5074
(which, of course, isn't the lowest positive sum that can't be expressed).
| #Common_Lisp | Common Lisp | (defun f (lst &optional (sum 100) (so-far nil))
"Takes a list of digits as argument"
(if (null lst)
(cond ((= sum 0) (format t "~d = ~{~@d~}~%" (apply #'+ so-far) (reverse so-far)) 1)
(t 0) )
(let ((total 0)
(len (length lst)) )
(dotimes (i len total)
(let* ((str1 (butlast lst i))
(num1 (or (numlist-to-string str1) 0))
(rem (nthcdr (- len i) lst)) )
(incf total
(+ (f rem (- sum num1) (cons num1 so-far))
(f rem (+ sum num1) (cons (- num1) so-far)) )))))))
(defun numlist-to-string (lst)
"Convert a list of digits into an integer"
(when lst
(parse-integer (format nil "~{~d~}" lst)) ))
|
http://rosettacode.org/wiki/Sum_multiples_of_3_and_5 | Sum multiples of 3 and 5 | Task
The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n.
Show output for n = 1000.
This is is the same as Project Euler problem 1.
Extra credit: do this efficiently for n = 1e20 or higher.
| #C.23 | C# |
using System;
using System.Collections.Generic;
using System.Numerics;
namespace RosettaCode
{
class Program
{
static void Main()
{
List<BigInteger> candidates = new List<BigInteger>(new BigInteger[] { 1000, 100000, 10000000, 10000000000, 1000000000000000 });
candidates.Add(BigInteger.Parse("100000000000000000000"));
foreach (BigInteger candidate in candidates)
{
BigInteger c = candidate - 1;
BigInteger answer3 = GetSumOfNumbersDivisibleByN(c, 3);
BigInteger answer5 = GetSumOfNumbersDivisibleByN(c, 5);
BigInteger answer15 = GetSumOfNumbersDivisibleByN(c, 15);
Console.WriteLine("The sum of numbers divisible by 3 or 5 between 1 and {0} is {1}", c, answer3 + answer5 - answer15);
}
Console.ReadKey(true);
}
private static BigInteger GetSumOfNumbersDivisibleByN(BigInteger candidate, uint n)
{
BigInteger largest = candidate;
while (largest % n > 0)
largest--;
BigInteger totalCount = (largest / n);
BigInteger pairCount = totalCount / 2;
bool unpairedNumberOnFoldLine = (totalCount % 2 == 1);
BigInteger pairSum = largest + n;
return pairCount * pairSum + (unpairedNumberOnFoldLine ? pairSum / 2 : 0);
}
}
}
|
http://rosettacode.org/wiki/Sum_digits_of_an_integer | Sum digits of an integer | Task
Take a Natural Number in a given base and return the sum of its digits:
110 sums to 1
123410 sums to 10
fe16 sums to 29
f0e16 sums to 29
| #BQN | BQN | SumDigits ← {
𝕊 𝕩: 10 𝕊 𝕩;
𝕨 𝕊 0: 0;
(𝕨|𝕩)+𝕨𝕊⌊𝕩÷𝕨
}
•Show SumDigits 1
•Show SumDigits 1234
•Show 16 SumDigits 254 |
http://rosettacode.org/wiki/Sum_of_squares | Sum of squares | Task
Write a program to find the sum of squares of a numeric vector.
The program should work on a zero-length vector (with an answer of 0).
Related task
Mean
| #Chef | Chef | Sum of squares.
First input is length of vector, then rest of input is vector.
Ingredients.
1 g eggs
0 g bacon
Method.
Put bacon into the 1st mixing bowl.
Take eggs from refrigerator.
Square the eggs.
Take bacon from refrigerator.
Put bacon into 2nd mixing bowl.
Combine bacon into 2nd mixing bowl.
Fold bacon into 2nd mixing bowl.
Add the bacon into the 1st mixing bowl.
Ask the eggs until squared.
Pour contents of the 1st mixing bowl into the 1st baking dish.
Serves 1.
|
http://rosettacode.org/wiki/Sum_of_squares | Sum of squares | Task
Write a program to find the sum of squares of a numeric vector.
The program should work on a zero-length vector (with an answer of 0).
Related task
Mean
| #Clojure | Clojure | (defn sum-of-squares [v]
(reduce #(+ %1 (* %2 %2)) 0 v)) |
http://rosettacode.org/wiki/Substitution_cipher | Substitution cipher | Substitution Cipher Implementation - File Encryption/Decryption
Task
Encrypt a input/source file by replacing every upper/lower case alphabets of the source file with another predetermined upper/lower case alphabets or symbols and save it into another output/encrypted file and then again convert that output/encrypted file into original/decrypted file.
This type of Encryption/Decryption scheme is often called a Substitution Cipher.
Related tasks
Caesar cipher
Rot-13
Vigenère Cipher/Cryptanalysis
See also
Wikipedia: Substitution cipher
| #C | C |
#include<stdlib.h>
#include<stdio.h>
#include<wchar.h>
#define ENCRYPT 0
#define DECRYPT 1
#define ALPHA 33
#define OMEGA 126
int wideStrLen(wchar_t* str){
int i = 0;
while(str[i++]!=00);
return i;
}
void processFile(char* fileName,char plainKey, char cipherKey,int flag){
FILE* inpFile = fopen(fileName,"r");
FILE* outFile;
int i,len, diff = (flag==ENCRYPT)?(int)cipherKey - (int)plainKey:(int)plainKey - (int)cipherKey;
wchar_t str[1000], *outStr;
char* outFileName = (char*)malloc((strlen(fileName)+5)*sizeof(char));
sprintf(outFileName,"%s_%s",fileName,(flag==ENCRYPT)?"ENC":"DEC");
outFile = fopen(outFileName,"w");
while(fgetws(str,1000,inpFile)!=NULL){
len = wideStrLen(str);
outStr = (wchar_t*)malloc((len + 1)*sizeof(wchar_t));
for(i=0;i<len;i++){
if((int)str[i]>=ALPHA && (int)str[i]<=OMEGA && flag == ENCRYPT)
outStr[i] = (wchar_t)((int)str[i]+diff);
else if((int)str[i]-diff>=ALPHA && (int)str[i]-diff<=OMEGA && flag == DECRYPT)
outStr[i] = (wchar_t)((int)str[i]-diff);
else
outStr[i] = str[i];
}
outStr[i]=str[i];
fputws(outStr,outFile);
free(outStr);
}
fclose(inpFile);
fclose(outFile);
}
int main(int argC,char* argV[]){
if(argC!=5)
printf("Usage : %s <file name, plain key, cipher key, action (E)ncrypt or (D)ecrypt>",argV[0]);
else{
processFile(argV[1],argV[2][0],argV[3][0],(argV[4][0]=='E'||argV[4][0]=='e')?ENCRYPT:DECRYPT);
printf("File %s_%s has been written to the same location as input file.",argV[1],(argV[4][0]=='E'||argV[4][0]=='e')?"ENC":"DEC");
}
return 0;
}
|
http://rosettacode.org/wiki/Sum_and_product_of_an_array | Sum and product of an array | Task
Compute the sum and product of an array of integers.
| #BASIC256 | BASIC256 | arraybase 1
dim array(5)
array[1] = 1
array[2] = 2
array[3] = 3
array[4] = 4
array[5] = 5
sum = 0
prod = 1
for index = 1 to array[?]
sum += array[index]
prod *= array[index]
next index
print "The sum is "; sum #15
print "and the product is "; prod #120
end |
http://rosettacode.org/wiki/Sum_and_product_of_an_array | Sum and product of an array | Task
Compute the sum and product of an array of integers.
| #bc | bc | a[0] = 3.0
a[1] = 1
a[2] = 4.0
a[3] = 1.0
a[4] = 5
a[5] = 9.00
n = 6
p = 1
for (i = 0; i < n; i++) {
s += a[i]
p *= a[i]
}
"Sum: "; s
"Product: "; p |
http://rosettacode.org/wiki/Sum_of_a_series | Sum of a series | Compute the nth term of a series, i.e. the sum of the n first terms of the corresponding sequence.
Informally this value, or its limit when n tends to infinity, is also called the sum of the series, thus the title of this task.
For this task, use:
S
n
=
∑
k
=
1
n
1
k
2
{\displaystyle S_{n}=\sum _{k=1}^{n}{\frac {1}{k^{2}}}}
and compute
S
1000
{\displaystyle S_{1000}}
This approximates the zeta function for S=2, whose exact value
ζ
(
2
)
=
π
2
6
{\displaystyle \zeta (2)={\pi ^{2} \over 6}}
is the solution of the Basel problem.
| #Bracmat | Bracmat | ( 0:?i
& 0:?S
& whl'(1+!i:~>1000:?i&!i^-2+!S:?S)
& out$!S
& out$(flt$(!S,10))
); |
http://rosettacode.org/wiki/Sum_to_100 | Sum to 100 | Task
Find solutions to the sum to one hundred puzzle.
Add (insert) the mathematical
operators + or - (plus
or minus) before any of the digits in the
decimal numeric string 123456789 such that the
resulting mathematical expression adds up to a
particular sum (in this iconic case, 100).
Example:
123 + 4 - 5 + 67 - 89 = 100
Show all output here.
Show all solutions that sum to 100
Show the sum that has the maximum number of solutions (from zero to infinity‡)
Show the lowest positive sum that can't be expressed (has no solutions), using the rules for this task
Show the ten highest numbers that can be expressed using the rules for this task (extra credit)
‡ (where infinity would be a relatively small 123,456,789)
An example of a sum that can't be expressed (within the rules of this task) is: 5074
(which, of course, isn't the lowest positive sum that can't be expressed).
| #D | D | import std.stdio;
void main() {
import std.algorithm : each, max, reduce, sort;
import std.range : take;
Stat stat = new Stat();
comment("Show all solutions that sum to 100");
immutable givenSum = 100;
print(givenSum);
comment("Show the sum that has the maximum number of solutions");
const int maxCount = reduce!max(stat.sumCount.keys);
int maxSum;
foreach(key, entry; stat.sumCount[maxCount]) {
if (key >= 0) {
maxSum = key;
break;
}
}
writeln(maxSum, " has ", maxCount, " solutions");
comment("Show the lowest positive number that can't be expressed");
int value = 0;
while (value in stat.countSum) {
value++;
}
writeln(value);
comment("Show the ten highest numbers that can be expressed");
const int n = stat.countSum.keys.length;
auto sums = stat.countSum.keys;
sums.sort!"a>b"
.take(10)
.each!print;
}
void comment(string commentString) {
writeln();
writeln(commentString);
writeln();
}
void print(int givenSum) {
Expression expression = new Expression();
for (int i=0; i<Expression.NUMBER_OF_EXPRESSIONS; i++, expression.next()) {
if (expression.toInt() == givenSum) {
expression.print();
}
}
}
class Expression {
private enum NUMBER_OF_DIGITS = 9;
private enum ADD = 0;
private enum SUB = 1;
private enum JOIN = 2;
enum NUMBER_OF_EXPRESSIONS = 2 * 3 * 3 * 3 * 3 * 3 * 3 * 3 * 3;
byte[NUMBER_OF_DIGITS] code;
Expression next() {
for (int i=0; i<NUMBER_OF_DIGITS; i++) {
if (++code[i] > JOIN) {
code[i] = ADD;
} else {
break;
}
}
return this;
}
int toInt() {
int value = 0;
int number = 0;
int sign = (+1);
for (int digit=1; digit<=9; digit++) {
switch (code[NUMBER_OF_DIGITS - digit]) {
case ADD:
value += sign * number;
number = digit;
sign = (+1);
break;
case SUB:
value += sign * number;
number = digit;
sign = (-1);
break;
case JOIN:
number = 10 * number + digit;
break;
default:
assert(false);
}
}
return value + sign * number;
}
void toString(scope void delegate(const(char)[]) sink) const {
import std.conv : to;
import std.format : FormatSpec, formatValue;
import std.range : put;
auto fmt = FormatSpec!char("s");
for (int digit=1; digit<=NUMBER_OF_DIGITS; digit++) {
switch (code[NUMBER_OF_DIGITS - digit]) {
case ADD:
if (digit > 1) {
put(sink, '+');
}
break;
case SUB:
put(sink, '-');
break;
default:
break;
}
formatValue(sink, digit, fmt);
}
}
void print() {
print(stdout);
}
void print(File printStream) {
printStream.writefln("%9d = %s", toInt(), this);
}
}
class Stat {
int[int] countSum;
bool[int][int] sumCount;
this() {
Expression expression = new Expression();
for (int i=0; i<Expression.NUMBER_OF_EXPRESSIONS; i++, expression.next()) {
int sum = expression.toInt();
countSum[sum]++;
}
foreach (key, entry; countSum) {
bool[int] set;
if (entry in sumCount) {
set = sumCount[entry];
} else {
set.clear();
}
set[key] = true;
sumCount[entry] = set;
}
}
} |
http://rosettacode.org/wiki/Sum_multiples_of_3_and_5 | Sum multiples of 3 and 5 | Task
The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n.
Show output for n = 1000.
This is is the same as Project Euler problem 1.
Extra credit: do this efficiently for n = 1e20 or higher.
| #C.2B.2B | C++ |
#include <iostream>
//--------------------------------------------------------------------------------------------------
typedef unsigned long long bigInt;
using namespace std;
//--------------------------------------------------------------------------------------------------
class m35
{
public:
void doIt( bigInt i )
{
bigInt sum = 0;
for( bigInt a = 1; a < i; a++ )
if( !( a % 3 ) || !( a % 5 ) ) sum += a;
cout << "Sum is " << sum << " for n = " << i << endl << endl;
}
// this method uses less than half iterations than the first one
void doIt_b( bigInt i )
{
bigInt sum = 0;
for( bigInt a = 0; a < 28; a++ )
{
if( !( a % 3 ) || !( a % 5 ) )
{
sum += a;
for( bigInt s = 30; s < i; s += 30 )
if( a + s < i ) sum += ( a + s );
}
}
cout << "Sum is " << sum << " for n = " << i << endl << endl;
}
};
//--------------------------------------------------------------------------------------------------
int main( int argc, char* argv[] )
{
m35 m; m.doIt( 1000 );
return system( "pause" );
}
|
http://rosettacode.org/wiki/Sum_digits_of_an_integer | Sum digits of an integer | Task
Take a Natural Number in a given base and return the sum of its digits:
110 sums to 1
123410 sums to 10
fe16 sums to 29
f0e16 sums to 29
| #C | C | #include <stdio.h>
int SumDigits(unsigned long long n, const int base) {
int sum = 0;
for (; n; n /= base)
sum += n % base;
return sum;
}
int main() {
printf("%d %d %d %d %d\n",
SumDigits(1, 10),
SumDigits(12345, 10),
SumDigits(123045, 10),
SumDigits(0xfe, 16),
SumDigits(0xf0e, 16) );
return 0;
} |
http://rosettacode.org/wiki/Sum_of_squares | Sum of squares | Task
Write a program to find the sum of squares of a numeric vector.
The program should work on a zero-length vector (with an answer of 0).
Related task
Mean
| #CLU | CLU | sum_squares = proc (ns: sequence[int]) returns (int)
sum: int := 0
for n: int in sequence[int]$elements(ns) do
sum := sum + n ** 2
end
return(sum)
end sum_squares
start_up = proc ()
po: stream := stream$primary_output()
stream$putl(po, int$unparse(sum_squares(sequence[int]$[])))
stream$putl(po, int$unparse(sum_squares(sequence[int]$[1,2,3,4,5])))
stream$putl(po, int$unparse(sum_squares(sequence[int]$[42])))
end start_up |
http://rosettacode.org/wiki/Sum_of_squares | Sum of squares | Task
Write a program to find the sum of squares of a numeric vector.
The program should work on a zero-length vector (with an answer of 0).
Related task
Mean
| #CoffeeScript | CoffeeScript |
sumOfSquares = ( list ) ->
list.reduce (( sum, x ) -> sum + ( x * x )), 0
|
http://rosettacode.org/wiki/Substitution_cipher | Substitution cipher | Substitution Cipher Implementation - File Encryption/Decryption
Task
Encrypt a input/source file by replacing every upper/lower case alphabets of the source file with another predetermined upper/lower case alphabets or symbols and save it into another output/encrypted file and then again convert that output/encrypted file into original/decrypted file.
This type of Encryption/Decryption scheme is often called a Substitution Cipher.
Related tasks
Caesar cipher
Rot-13
Vigenère Cipher/Cryptanalysis
See also
Wikipedia: Substitution cipher
| #C.23 | C# | using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SubstitutionCipherProject
{
class SubstitutionCipher
{
static void Main(string[] args)
{
doEncDec("e:\\source.txt", "enc.txt", true);
doEncDec("enc.txt", "dec.txt", false);
Console.WriteLine("Done");
Console.ReadKey();
}
static void doEncDec(String source, String target, bool IsEncrypt)
{
ITransform trans;
if (IsEncrypt)
trans = new Encrypt();
else
trans = new Decrypt();
FileInfo sfi = new FileInfo(source);
FileStream sstream = sfi.OpenRead();
StreamReader sr = new StreamReader(sstream);
FileInfo tfi = new FileInfo(target);
FileStream tstream = tfi.OpenWrite();
TransformWriter tw = new TransformWriter(tstream, trans);
StreamWriter sw = new StreamWriter(tw);
String line;
while ((line = sr.ReadLine()) != null)
sw.WriteLine(line);
sw.Close();
}
}
public interface ITransform
{
byte transform(byte ch);
}
public class Encrypt : ITransform
{
const String str = "xyfagchbimpourvnqsdewtkjzl";
byte ITransform.transform(byte ch)
{
if (char.IsLower((char)ch))
ch = (byte)str[ch - (byte)'a'];
return ch;
}
}
class Decrypt : ITransform
{
const String str = "xyfagchbimpourvnqsdewtkjzl";
byte ITransform.transform(byte ch)
{
if (char.IsLower((char)ch))
ch = (byte)(str.IndexOf((char)ch) + 'a');
return ch;
}
}
class TransformWriter : Stream, IDisposable
{
private Stream outs;
private ITransform trans;
public TransformWriter(Stream s, ITransform t)
{
this.outs = s;
this.trans = t;
}
public override bool CanRead
{
get { return false; }
}
public override bool CanSeek
{
get { return false; }
}
public override bool CanWrite
{
get { return true; }
}
public override void Flush()
{
outs.Flush();
}
public override long Length
{
get { return outs.Length; }
}
public override long Position
{
get
{
return outs.Position;
}
set
{
outs.Position = value;
}
}
public override long Seek(long offset, SeekOrigin origin)
{
return outs.Seek(offset, origin);
}
public override void SetLength(long value)
{
outs.SetLength(value);
}
public override void Write(byte[] buf, int off, int len)
{
for (int i = off; i < off + len; i++)
buf[i] = trans.transform(buf[i]);
outs.Write(buf, off, len);
}
void IDisposable.Dispose()
{
outs.Dispose();
}
public override void Close()
{
outs.Close();
}
public override int Read(byte[] cbuf, int off, int count)
{
return outs.Read(cbuf, off, count);
}
}
} |
http://rosettacode.org/wiki/Sum_and_product_of_an_array | Sum and product of an array | Task
Compute the sum and product of an array of integers.
| #Befunge | Befunge | 0 &>: #v_ $. @
>1- \ & + \v
^ < |
http://rosettacode.org/wiki/Sum_and_product_of_an_array | Sum and product of an array | Task
Compute the sum and product of an array of integers.
| #BQN | BQN | SumProd ← +´⋈×´
+´⋈×´
SumProd 1‿2‿3‿4‿5
⟨ 15 120 ⟩ |
http://rosettacode.org/wiki/Sum_of_a_series | Sum of a series | Compute the nth term of a series, i.e. the sum of the n first terms of the corresponding sequence.
Informally this value, or its limit when n tends to infinity, is also called the sum of the series, thus the title of this task.
For this task, use:
S
n
=
∑
k
=
1
n
1
k
2
{\displaystyle S_{n}=\sum _{k=1}^{n}{\frac {1}{k^{2}}}}
and compute
S
1000
{\displaystyle S_{1000}}
This approximates the zeta function for S=2, whose exact value
ζ
(
2
)
=
π
2
6
{\displaystyle \zeta (2)={\pi ^{2} \over 6}}
is the solution of the Basel problem.
| #Brat | Brat | p 1.to(1000).reduce 0 { sum, x | sum + 1.0 / x ^ 2 } #Prints 1.6439345666816 |
http://rosettacode.org/wiki/Sum_to_100 | Sum to 100 | Task
Find solutions to the sum to one hundred puzzle.
Add (insert) the mathematical
operators + or - (plus
or minus) before any of the digits in the
decimal numeric string 123456789 such that the
resulting mathematical expression adds up to a
particular sum (in this iconic case, 100).
Example:
123 + 4 - 5 + 67 - 89 = 100
Show all output here.
Show all solutions that sum to 100
Show the sum that has the maximum number of solutions (from zero to infinity‡)
Show the lowest positive sum that can't be expressed (has no solutions), using the rules for this task
Show the ten highest numbers that can be expressed using the rules for this task (extra credit)
‡ (where infinity would be a relatively small 123,456,789)
An example of a sum that can't be expressed (within the rules of this task) is: 5074
(which, of course, isn't the lowest positive sum that can't be expressed).
| #Delphi | Delphi | defmodule Sum do
def to(val) do
generate
|> Enum.map(&{eval(&1), &1})
|> Enum.filter(fn {v, _s} -> v==val end)
|> Enum.each(&IO.inspect &1)
end
def max_solve do
generate
|> Enum.group_by(&eval &1)
|> Enum.filter_map(fn {k,_} -> k>=0 end, fn {k,v} -> {length(v),k} end)
|> Enum.max
|> fn {len,sum} -> IO.puts "sum of #{sum} has the maximum number of solutions : #{len}" end.()
end
def min_solve do
solve = generate |> Enum.group_by(&eval &1)
Stream.iterate(1, &(&1+1))
|> Enum.find(fn n -> solve[n]==nil end)
|> fn sum -> IO.puts "lowest positive sum that can't be expressed : #{sum}" end.()
end
def highest_sums(n\\10) do
IO.puts "highest sums :"
generate
|> Enum.map(&eval &1)
|> Enum.uniq
|> Enum.sort_by(fn sum -> -sum end)
|> Enum.take(n)
|> IO.inspect
end
defp generate do
x = ["+", "-", ""]
for a <- ["-", ""], b <- x, c <- x, d <- x, e <- x, f <- x, g <- x, h <- x, i <- x,
do: "#{a}1#{b}2#{c}3#{d}4#{e}5#{f}6#{g}7#{h}8#{i}9"
end
defp eval(str), do: Code.eval_string(str) |> elem(0)
end
Sum.to(100)
Sum.max_solve
Sum.min_solve
Sum.highest_sums |
http://rosettacode.org/wiki/Sum_multiples_of_3_and_5 | Sum multiples of 3 and 5 | Task
The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n.
Show output for n = 1000.
This is is the same as Project Euler problem 1.
Extra credit: do this efficiently for n = 1e20 or higher.
| #Clojure | Clojure | (defn sum-mults [n & mults]
(let [pred (apply some-fn
(map #(fn [x] (zero? (mod x %))) mults))]
(->> (range n) (filter pred) (reduce +))))
(println (sum-mults 1000 3 5)) |
http://rosettacode.org/wiki/Sum_digits_of_an_integer | Sum digits of an integer | Task
Take a Natural Number in a given base and return the sum of its digits:
110 sums to 1
123410 sums to 10
fe16 sums to 29
f0e16 sums to 29
| #C.23 | C# | namespace RosettaCode.SumDigitsOfAnInteger
{
using System;
using System.Collections.Generic;
using System.Linq;
internal static class Program
{
/// <summary>
/// Enumerates the digits of a number in a given base.
/// </summary>
/// <param name="number"> The number. </param>
/// <param name="base"> The base. </param>
/// <returns> The digits of the number in the given base. </returns>
/// <remarks>
/// The digits are enumerated from least to most significant.
/// </remarks>
private static IEnumerable<int> Digits(this int number, int @base = 10)
{
while (number != 0)
{
int digit;
number = Math.DivRem(number, @base, out digit);
yield return digit;
}
}
/// <summary>
/// Sums the digits of a number in a given base.
/// </summary>
/// <param name="number"> The number. </param>
/// <param name="base"> The base. </param>
/// <returns> The sum of the digits of the number in the given base. </returns>
private static int SumOfDigits(this int number, int @base = 10)
{
return number.Digits(@base).Sum();
}
/// <summary>
/// Demonstrates <see cref="SumOfDigits" />.
/// </summary>
private static void Main()
{
foreach (var example in
new[]
{
new {Number = 1, Base = 10},
new {Number = 12345, Base = 10},
new {Number = 123045, Base = 10},
new {Number = 0xfe, Base = 0x10},
new {Number = 0xf0e, Base = 0x10}
})
{
Console.WriteLine(example.Number.SumOfDigits(example.Base));
}
}
}
} |
http://rosettacode.org/wiki/Sum_of_squares | Sum of squares | Task
Write a program to find the sum of squares of a numeric vector.
The program should work on a zero-length vector (with an answer of 0).
Related task
Mean
| #Common_Lisp | Common Lisp | (defun sum-of-squares (vector)
(loop for x across vector sum (expt x 2))) |
http://rosettacode.org/wiki/Sum_of_squares | Sum of squares | Task
Write a program to find the sum of squares of a numeric vector.
The program should work on a zero-length vector (with an answer of 0).
Related task
Mean
| #Cowgol | Cowgol | include "cowgol.coh";
include "argv.coh";
# Sum of squares
sub sumsquare(vec: [int32], len: intptr): (out: uint32) is
out := 0;
while len > 0 loop
var cur := [vec];
# make positive first so we can use extra range of uint32
if cur < 0 then cur := -cur; end if;
out := out + cur as uint32 * cur as uint32;
vec := @next vec;
len := len - 1;
end loop;
end sub;
# Read array from command line, allowing empty line (giving 0)
var nums: int32[128];
var len: @indexof nums := 0;
ArgvInit();
loop
var argmt := ArgvNext(); # read number
if argmt == (0 as [uint8]) then
break; # stop when no more numbers
end if;
var dummy: [uint8];
(nums[len], dummy) := AToI(argmt);
len := len + 1;
end loop;
# Print sum of squares of numbers
print_i32(sumsquare(&nums[0], len as intptr));
print_nl(); |
http://rosettacode.org/wiki/Substitution_cipher | Substitution cipher | Substitution Cipher Implementation - File Encryption/Decryption
Task
Encrypt a input/source file by replacing every upper/lower case alphabets of the source file with another predetermined upper/lower case alphabets or symbols and save it into another output/encrypted file and then again convert that output/encrypted file into original/decrypted file.
This type of Encryption/Decryption scheme is often called a Substitution Cipher.
Related tasks
Caesar cipher
Rot-13
Vigenère Cipher/Cryptanalysis
See also
Wikipedia: Substitution cipher
| #C.2B.2B | C++ |
#include <iostream>
#include <string>
#include <fstream>
class cipher {
public:
bool work( std::string e, std::string f, std::string k ) {
if( e.length() < 1 ) return false;
fileBuffer = readFile( f );
if( "" == fileBuffer ) return false;
keyBuffer = readFile( k );
if( "" == keyBuffer ) return false;
outName = f;
outName.insert( outName.find_first_of( "." ), "_out" );
switch( e[0] ) {
case 'e': return encode();
case 'd': return decode();
}
return false;
}
private:
bool encode() {
size_t idx, len = keyBuffer.length() >> 1;
for( std::string::iterator i = fileBuffer.begin(); i != fileBuffer.end(); i++ ) {
idx = keyBuffer.find_first_of( *i );
if( idx < len ) outBuffer.append( 1, keyBuffer.at( idx + len ) );
else outBuffer.append( 1, *i );
}
return saveOutput();
}
bool decode() {
size_t idx, l = keyBuffer.length(), len = l >> 1;
for( std::string::iterator i = fileBuffer.begin(); i != fileBuffer.end(); i++ ) {
idx = keyBuffer.find_last_of( *i );
if( idx >= len && idx < l ) outBuffer.append( 1, keyBuffer.at( idx - len ) );
else outBuffer.append( 1, *i );
}
return saveOutput();
}
bool saveOutput() {
std::ofstream o( outName.c_str() );
o.write( outBuffer.c_str(), outBuffer.size() );
o.close();
return true;
}
std::string readFile( std::string fl ) {
std::string buffer = "";
std::ifstream f( fl.c_str(), std::ios_base::in );
if( f.good() ) {
buffer = std::string( ( std::istreambuf_iterator<char>( f ) ), std::istreambuf_iterator<char>() );
f.close();
}
return buffer;
}
std::string fileBuffer, keyBuffer, outBuffer, outName;
};
int main( int argc, char* argv[] ) {
if( argc < 4 ) {
std::cout << "<d or e>\tDecrypt or Encrypt\n<filename>\tInput file, the output file will have"
"'_out' added to it.\n<key>\t\tfile with the key to encode/decode\n\n";
} else {
cipher c;
if( c.work( argv[1], argv[2], argv[3] ) ) std::cout << "\nFile successfully saved!\n\n";
else std::cout << "Something went wrong!\n\n";
}
return 0;
}
|
http://rosettacode.org/wiki/Sum_and_product_of_an_array | Sum and product of an array | Task
Compute the sum and product of an array of integers.
| #Bracmat | Bracmat | ( ( sumprod
= sum prod num
. 0:?sum
& 1:?prod
& ( !arg
: ?
( #%?num ?
& !num+!sum:?sum
& !num*!prod:?prod
& ~
)
| (!sum.!prod)
)
)
& out$sumprod$(2 3 5 7 11 13 17 19)
); |
http://rosettacode.org/wiki/Sum_and_product_of_an_array | Sum and product of an array | Task
Compute the sum and product of an array of integers.
| #C | C | /* using pointer arithmetic (because we can, I guess) */
int arg[] = { 1,2,3,4,5 };
int arg_length = sizeof(arg)/sizeof(arg[0]);
int *end = arg+arg_length;
int sum = 0, prod = 1;
int *p;
for (p = arg; p!=end; ++p) {
sum += *p;
prod *= *p;
} |
http://rosettacode.org/wiki/Sum_of_a_series | Sum of a series | Compute the nth term of a series, i.e. the sum of the n first terms of the corresponding sequence.
Informally this value, or its limit when n tends to infinity, is also called the sum of the series, thus the title of this task.
For this task, use:
S
n
=
∑
k
=
1
n
1
k
2
{\displaystyle S_{n}=\sum _{k=1}^{n}{\frac {1}{k^{2}}}}
and compute
S
1000
{\displaystyle S_{1000}}
This approximates the zeta function for S=2, whose exact value
ζ
(
2
)
=
π
2
6
{\displaystyle \zeta (2)={\pi ^{2} \over 6}}
is the solution of the Basel problem.
| #C | C | #include <stdio.h>
double Invsqr(double n)
{
return 1 / (n*n);
}
int main (int argc, char *argv[])
{
int i, start = 1, end = 1000;
double sum = 0.0;
for( i = start; i <= end; i++)
sum += Invsqr((double)i);
printf("%16.14f\n", sum);
return 0;
} |
http://rosettacode.org/wiki/Sum_to_100 | Sum to 100 | Task
Find solutions to the sum to one hundred puzzle.
Add (insert) the mathematical
operators + or - (plus
or minus) before any of the digits in the
decimal numeric string 123456789 such that the
resulting mathematical expression adds up to a
particular sum (in this iconic case, 100).
Example:
123 + 4 - 5 + 67 - 89 = 100
Show all output here.
Show all solutions that sum to 100
Show the sum that has the maximum number of solutions (from zero to infinity‡)
Show the lowest positive sum that can't be expressed (has no solutions), using the rules for this task
Show the ten highest numbers that can be expressed using the rules for this task (extra credit)
‡ (where infinity would be a relatively small 123,456,789)
An example of a sum that can't be expressed (within the rules of this task) is: 5074
(which, of course, isn't the lowest positive sum that can't be expressed).
| #Elixir | Elixir | defmodule Sum do
def to(val) do
generate
|> Enum.map(&{eval(&1), &1})
|> Enum.filter(fn {v, _s} -> v==val end)
|> Enum.each(&IO.inspect &1)
end
def max_solve do
generate
|> Enum.group_by(&eval &1)
|> Enum.filter_map(fn {k,_} -> k>=0 end, fn {k,v} -> {length(v),k} end)
|> Enum.max
|> fn {len,sum} -> IO.puts "sum of #{sum} has the maximum number of solutions : #{len}" end.()
end
def min_solve do
solve = generate |> Enum.group_by(&eval &1)
Stream.iterate(1, &(&1+1))
|> Enum.find(fn n -> solve[n]==nil end)
|> fn sum -> IO.puts "lowest positive sum that can't be expressed : #{sum}" end.()
end
def highest_sums(n\\10) do
IO.puts "highest sums :"
generate
|> Enum.map(&eval &1)
|> Enum.uniq
|> Enum.sort_by(fn sum -> -sum end)
|> Enum.take(n)
|> IO.inspect
end
defp generate do
x = ["+", "-", ""]
for a <- ["-", ""], b <- x, c <- x, d <- x, e <- x, f <- x, g <- x, h <- x, i <- x,
do: "#{a}1#{b}2#{c}3#{d}4#{e}5#{f}6#{g}7#{h}8#{i}9"
end
defp eval(str), do: Code.eval_string(str) |> elem(0)
end
Sum.to(100)
Sum.max_solve
Sum.min_solve
Sum.highest_sums |
http://rosettacode.org/wiki/Sum_multiples_of_3_and_5 | Sum multiples of 3 and 5 | Task
The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n.
Show output for n = 1000.
This is is the same as Project Euler problem 1.
Extra credit: do this efficiently for n = 1e20 or higher.
| #COBOL | COBOL |
Identification division.
Program-id. three-five-sum.
Data division.
Working-storage section.
01 ws-the-limit pic 9(18) value 1000.
01 ws-the-number pic 9(18).
01 ws-the-sum pic 9(18).
01 ws-sum-out pic z(18).
Procedure division.
Main-program.
Perform Do-sum
varying ws-the-number from 1 by 1
until ws-the-number = ws-the-limit.
Move ws-the-sum to ws-sum-out.
Display "Sum = " ws-sum-out.
End-run.
Do-sum.
If function mod(ws-the-number, 3) = zero
or function mod(ws-the-number, 5) = zero
then add ws-the-number to ws-the-sum.
|
http://rosettacode.org/wiki/Sum_digits_of_an_integer | Sum digits of an integer | Task
Take a Natural Number in a given base and return the sum of its digits:
110 sums to 1
123410 sums to 10
fe16 sums to 29
f0e16 sums to 29
| #C.2B.2B | C++ | #include <iostream>
#include <cmath>
int SumDigits(const unsigned long long int digits, const int BASE = 10) {
int sum = 0;
unsigned long long int x = digits;
for (int i = log(digits)/log(BASE); i>0; i--){
const double z = std::pow(BASE,i);
const unsigned long long int t = x/z;
sum += t;
x -= t*z;
}
return x+sum;
}
int main() {
std::cout << SumDigits(1) << ' '
<< SumDigits(12345) << ' '
<< SumDigits(123045) << ' '
<< SumDigits(0xfe, 16) << ' '
<< SumDigits(0xf0e, 16) << std::endl;
return 0;
} |
http://rosettacode.org/wiki/Sum_of_squares | Sum of squares | Task
Write a program to find the sum of squares of a numeric vector.
The program should work on a zero-length vector (with an answer of 0).
Related task
Mean
| #Crystal | Crystal |
def sum_squares(a)
a.map{|e| e*e}.sum()
end
puts sum_squares([1, 2, 3])
# => 14
|
http://rosettacode.org/wiki/Sum_of_squares | Sum of squares | Task
Write a program to find the sum of squares of a numeric vector.
The program should work on a zero-length vector (with an answer of 0).
Related task
Mean
| #D | D | T sumSquares(T)(T[] a) pure nothrow @safe @nogc {
T sum = 0;
foreach (e; a)
sum += e ^^ 2;
return sum;
}
void main() {
import std.stdio: writeln;
[3.1, 1.0, 4.0, 1.0, 5.0, 9.0].sumSquares.writeln;
} |
http://rosettacode.org/wiki/Substring/Top_and_tail | Substring/Top and tail | The task is to demonstrate how to remove the first and last characters from a string.
The solution should demonstrate how to obtain the following results:
String with first character removed
String with last character removed
String with both the first and last characters removed
If the program uses UTF-8 or UTF-16, it must work on any valid Unicode code point, whether in the Basic Multilingual Plane or above it.
The program must reference logical characters (code points), not 8-bit code units for UTF-8 or 16-bit code units for UTF-16.
Programs for other encodings (such as 8-bit ASCII, or EUC-JP) are not required to handle all Unicode characters.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #11l | 11l | print(‘knight’[1..])
print(‘socks’[0 .< (len)-1])
print(‘brooms’[1 .< (len)-1]) |
http://rosettacode.org/wiki/Subtractive_generator | Subtractive generator | A subtractive generator calculates a sequence of random numbers, where each number is congruent to the subtraction of two previous numbers from the sequence.
The formula is
r
n
=
r
(
n
−
i
)
−
r
(
n
−
j
)
(
mod
m
)
{\displaystyle r_{n}=r_{(n-i)}-r_{(n-j)}{\pmod {m}}}
for some fixed values of
i
{\displaystyle i}
,
j
{\displaystyle j}
and
m
{\displaystyle m}
, all positive integers. Supposing that
i
>
j
{\displaystyle i>j}
, then the state of this generator is the list of the previous numbers from
r
n
−
i
{\displaystyle r_{n-i}}
to
r
n
−
1
{\displaystyle r_{n-1}}
. Many states generate uniform random integers from
0
{\displaystyle 0}
to
m
−
1
{\displaystyle m-1}
, but some states are bad. A state, filled with zeros, generates only zeros. If
m
{\displaystyle m}
is even, then a state, filled with even numbers, generates only even numbers. More generally, if
f
{\displaystyle f}
is a factor of
m
{\displaystyle m}
, then a state, filled with multiples of
f
{\displaystyle f}
, generates only multiples of
f
{\displaystyle f}
.
All subtractive generators have some weaknesses. The formula correlates
r
n
{\displaystyle r_{n}}
,
r
(
n
−
i
)
{\displaystyle r_{(n-i)}}
and
r
(
n
−
j
)
{\displaystyle r_{(n-j)}}
; these three numbers are not independent, as true random numbers would be. Anyone who observes
i
{\displaystyle i}
consecutive numbers can predict the next numbers, so the generator is not cryptographically secure. The authors of Freeciv (utility/rand.c) and xpat2 (src/testit2.c) knew another problem: the low bits are less random than the high bits.
The subtractive generator has a better reputation than the linear congruential generator, perhaps because it holds more state. A subtractive generator might never multiply numbers: this helps where multiplication is slow. A subtractive generator might also avoid division: the value of
r
(
n
−
i
)
−
r
(
n
−
j
)
{\displaystyle r_{(n-i)}-r_{(n-j)}}
is always between
−
m
{\displaystyle -m}
and
m
{\displaystyle m}
, so a program only needs to add
m
{\displaystyle m}
to negative numbers.
The choice of
i
{\displaystyle i}
and
j
{\displaystyle j}
affects the period of the generator. A popular choice is
i
=
55
{\displaystyle i=55}
and
j
=
24
{\displaystyle j=24}
, so the formula is
r
n
=
r
(
n
−
55
)
−
r
(
n
−
24
)
(
mod
m
)
{\displaystyle r_{n}=r_{(n-55)}-r_{(n-24)}{\pmod {m}}}
The subtractive generator from xpat2 uses
r
n
=
r
(
n
−
55
)
−
r
(
n
−
24
)
(
mod
10
9
)
{\displaystyle r_{n}=r_{(n-55)}-r_{(n-24)}{\pmod {10^{9}}}}
The implementation is by J. Bentley and comes from program_tools/universal.c of the DIMACS (netflow) archive at Rutgers University. It credits Knuth, TAOCP, Volume 2, Section 3.2.2 (Algorithm A).
Bentley uses this clever algorithm to seed the generator.
Start with a single
s
e
e
d
{\displaystyle seed}
in range
0
{\displaystyle 0}
to
10
9
−
1
{\displaystyle 10^{9}-1}
.
Set
s
0
=
s
e
e
d
{\displaystyle s_{0}=seed}
and
s
1
=
1
{\displaystyle s_{1}=1}
. The inclusion of
s
1
=
1
{\displaystyle s_{1}=1}
avoids some bad states (like all zeros, or all multiples of 10).
Compute
s
2
,
s
3
,
.
.
.
,
s
54
{\displaystyle s_{2},s_{3},...,s_{54}}
using the subtractive formula
s
n
=
s
(
n
−
2
)
−
s
(
n
−
1
)
(
mod
10
9
)
{\displaystyle s_{n}=s_{(n-2)}-s_{(n-1)}{\pmod {10^{9}}}}
.
Reorder these 55 values so
r
0
=
s
34
{\displaystyle r_{0}=s_{34}}
,
r
1
=
s
13
{\displaystyle r_{1}=s_{13}}
,
r
2
=
s
47
{\displaystyle r_{2}=s_{47}}
, ...,
r
n
=
s
(
34
∗
(
n
+
1
)
(
mod
55
)
)
{\displaystyle r_{n}=s_{(34*(n+1){\pmod {55}})}}
.
This is the same order as
s
0
=
r
54
{\displaystyle s_{0}=r_{54}}
,
s
1
=
r
33
{\displaystyle s_{1}=r_{33}}
,
s
2
=
r
12
{\displaystyle s_{2}=r_{12}}
, ...,
s
n
=
r
(
(
34
∗
n
)
−
1
(
mod
55
)
)
{\displaystyle s_{n}=r_{((34*n)-1{\pmod {55}})}}
.
This rearrangement exploits how 34 and 55 are relatively prime.
Compute the next 165 values
r
55
{\displaystyle r_{55}}
to
r
219
{\displaystyle r_{219}}
. Store the last 55 values.
This generator yields the sequence
r
220
{\displaystyle r_{220}}
,
r
221
{\displaystyle r_{221}}
,
r
222
{\displaystyle r_{222}}
and so on. For example, if the seed is 292929, then the sequence begins with
r
220
=
467478574
{\displaystyle r_{220}=467478574}
,
r
221
=
512932792
{\displaystyle r_{221}=512932792}
,
r
222
=
539453717
{\displaystyle r_{222}=539453717}
. By starting at
r
220
{\displaystyle r_{220}}
, this generator avoids a bias from the first numbers of the sequence. This generator must store the last 55 numbers of the sequence, so to compute the next
r
n
{\displaystyle r_{n}}
. Any array or list would work; a ring buffer is ideal but not necessary.
Implement a subtractive generator that replicates the sequences from xpat2.
| #11l | 11l | Deque[Int] s
V seed = 292929
s.append(seed)
s.append(1)
L(n) 2..54
s.append((s[n - 2] - s[n - 1]) % 10 ^ 9)
Deque[Int] r
L(n) 55
V i = (34 * (n + 1)) % 55
r.append(s[i])
F py_mod(a, b)
R ((a % b) + b) % b
F getnextr()
:r.append(py_mod((:r[0] - :r[31]), 10 ^ 9))
:r.pop_left()
R :r[54]
L 0 .< 219 - 54
getnextr()
L 5
print(‘result = ’getnextr()) |
http://rosettacode.org/wiki/Substitution_cipher | Substitution cipher | Substitution Cipher Implementation - File Encryption/Decryption
Task
Encrypt a input/source file by replacing every upper/lower case alphabets of the source file with another predetermined upper/lower case alphabets or symbols and save it into another output/encrypted file and then again convert that output/encrypted file into original/decrypted file.
This type of Encryption/Decryption scheme is often called a Substitution Cipher.
Related tasks
Caesar cipher
Rot-13
Vigenère Cipher/Cryptanalysis
See also
Wikipedia: Substitution cipher
| #D | D | import std.stdio;
import std.string;
import std.traits;
string text =
`Here we have to do is there will be a input/source
file in which we are going to Encrypt the file by replacing every
upper/lower case alphabets of the source file with another
predetermined upper/lower case alphabets or symbols and save
it into another output/encrypted file and then again convert
that output/encrypted file into original/decrypted file. This
type of Encryption/Decryption scheme is often called a
Substitution Cipher.`;
void main() {
auto enc = encode(text);
writeln("Encoded: ", enc);
writeln;
writeln("Decoded: ", decode(enc));
}
enum FORWARD = "A~B!C@D#E$F%G^H&I*J(K)L+M=N[O]P{Q}R<S>T/U?V:W;X.Y,Z a\tbcdefghijkl\nmnopqrstuvwxyz";
auto encode(string input) {
return tr(input, FORWARD, REVERSE);
}
enum REVERSE = "VsciBjedgrzy\nHalvXZKtUP um\tGf?I/w>J<x.q,OC:F;R{A]p}n[D+h=Q)W(o*b&L^k%E$S#Y@M!T~N";
auto decode(string input) {
return tr(input, REVERSE, FORWARD);
} |
http://rosettacode.org/wiki/Substitution_cipher | Substitution cipher | Substitution Cipher Implementation - File Encryption/Decryption
Task
Encrypt a input/source file by replacing every upper/lower case alphabets of the source file with another predetermined upper/lower case alphabets or symbols and save it into another output/encrypted file and then again convert that output/encrypted file into original/decrypted file.
This type of Encryption/Decryption scheme is often called a Substitution Cipher.
Related tasks
Caesar cipher
Rot-13
Vigenère Cipher/Cryptanalysis
See also
Wikipedia: Substitution cipher
| #Factor | Factor | USING: assocs combinators combinators.short-circuit command-line
hashtables io io.encodings.utf8 io.files kernel math.order
multiline namespaces qw sequences ;
IN: rosetta-code.substitution-cipher
CONSTANT: alphabet
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
CONSTANT: default-key
"VsciBjedgrzyHalvXZKtUPumGfIwJxqOCFRApnDhQWobLkESYMTN"
SYMBOL: key
STRING: usage
Usage:
substitution
<encode|decode>
input-file
output-file
[key-file] (Optional -- for custom alphabet keys.)
Example:
substitution encode my-poem.txt my-encoded-poem.txt
;
: check-args ( seq -- ? )
{
[ length 3 4 between? not ]
[ first qw{ encode decode } member? not ]
} 1|| [ usage print f ] [ t ] if ;
: init-key ( seq -- )
dup length 4 = [ last utf8 file-contents ]
[ drop default-key ] if key set ;
: >sub-map ( seq -- assoc )
[ alphabet key get ] dip first "encode" = [ swap ] unless
zip >hashtable ;
: encipher ( seq assoc -- newseq )
[ dupd at dup [ nip ] [ drop ] if ] curry { } map-as ;
: substitute ( seq -- )
{ [ init-key ] [ second ] [ >sub-map ] [ third ] } cleave
[ utf8 file-contents ] [ encipher ]
[ utf8 set-file-contents ] tri* ;
: main ( -- )
command-line get dup check-args [ substitute ] [ drop ] if ;
MAIN: main |
http://rosettacode.org/wiki/Sum_and_product_of_an_array | Sum and product of an array | Task
Compute the sum and product of an array of integers.
| #C.23 | C# | int sum = 0, prod = 1;
int[] arg = { 1, 2, 3, 4, 5 };
foreach (int value in arg) {
sum += value;
prod *= value;
} |
http://rosettacode.org/wiki/Sum_of_a_series | Sum of a series | Compute the nth term of a series, i.e. the sum of the n first terms of the corresponding sequence.
Informally this value, or its limit when n tends to infinity, is also called the sum of the series, thus the title of this task.
For this task, use:
S
n
=
∑
k
=
1
n
1
k
2
{\displaystyle S_{n}=\sum _{k=1}^{n}{\frac {1}{k^{2}}}}
and compute
S
1000
{\displaystyle S_{1000}}
This approximates the zeta function for S=2, whose exact value
ζ
(
2
)
=
π
2
6
{\displaystyle \zeta (2)={\pi ^{2} \over 6}}
is the solution of the Basel problem.
| #C.23 | C# | class Program
{
static void Main(string[] args)
{
// Create and fill a list of number 1 to 1000
List<double> myList = new List<double>();
for (double i = 1; i < 1001; i++)
{
myList.Add(i);
}
// Calculate the sum of 1/x^2
var sum = myList.Sum(x => 1/(x*x));
Console.WriteLine(sum);
Console.ReadLine();
}
} |
http://rosettacode.org/wiki/Sum_to_100 | Sum to 100 | Task
Find solutions to the sum to one hundred puzzle.
Add (insert) the mathematical
operators + or - (plus
or minus) before any of the digits in the
decimal numeric string 123456789 such that the
resulting mathematical expression adds up to a
particular sum (in this iconic case, 100).
Example:
123 + 4 - 5 + 67 - 89 = 100
Show all output here.
Show all solutions that sum to 100
Show the sum that has the maximum number of solutions (from zero to infinity‡)
Show the lowest positive sum that can't be expressed (has no solutions), using the rules for this task
Show the ten highest numbers that can be expressed using the rules for this task (extra credit)
‡ (where infinity would be a relatively small 123,456,789)
An example of a sum that can't be expressed (within the rules of this task) is: 5074
(which, of course, isn't the lowest positive sum that can't be expressed).
| #F.23 | F# |
(*
Generate the data set
Nigel Galloway February 22nd., 2017
*)
type N = {n:string; g:int}
let N = seq {
let rec fn n i g e l = seq {
match i with
|9 -> yield {n=l + "-9"; g=g+e-9}
yield {n=l + "+9"; g=g+e+9}
yield {n=l + "9"; g=g+e*10+9*n}
|_ -> yield! fn -1 (i+1) (g+e) -i (l + string -i)
yield! fn 1 (i+1) (g+e) i (l + "+" + string i)
yield! fn n (i+1) g (e*10+i*n) (l + string i)
}
yield! fn 1 2 0 1 "1"
yield! fn -1 2 0 -1 "-1"
}
|
http://rosettacode.org/wiki/Sum_multiples_of_3_and_5 | Sum multiples of 3 and 5 | Task
The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n.
Show output for n = 1000.
This is is the same as Project Euler problem 1.
Extra credit: do this efficiently for n = 1e20 or higher.
| #Common_Lisp | Common Lisp | (defun sum-3-5-slow (limit)
(loop for x below limit
when (or (zerop (rem x 3)) (zerop (rem x 5)))
sum x)) |
http://rosettacode.org/wiki/Sum_digits_of_an_integer | Sum digits of an integer | Task
Take a Natural Number in a given base and return the sum of its digits:
110 sums to 1
123410 sums to 10
fe16 sums to 29
f0e16 sums to 29
| #Clojure | Clojure | (defn sum-digits [n base]
(let [number (if-not (string? n) (Long/toString n base) n)]
(reduce + (map #(Long/valueOf (str %) base) number)))) |
http://rosettacode.org/wiki/Sum_of_squares | Sum of squares | Task
Write a program to find the sum of squares of a numeric vector.
The program should work on a zero-length vector (with an answer of 0).
Related task
Mean
| #Dart | Dart | sumOfSquares(list) {
var sum=0;
list.forEach((var n) { sum+=(n*n); });
return sum;
}
main() {
print(sumOfSquares([]));
print(sumOfSquares([1,2,3]));
print(sumOfSquares([10]));
} |
http://rosettacode.org/wiki/Substring/Top_and_tail | Substring/Top and tail | The task is to demonstrate how to remove the first and last characters from a string.
The solution should demonstrate how to obtain the following results:
String with first character removed
String with last character removed
String with both the first and last characters removed
If the program uses UTF-8 or UTF-16, it must work on any valid Unicode code point, whether in the Basic Multilingual Plane or above it.
The program must reference logical characters (code points), not 8-bit code units for UTF-8 or 16-bit code units for UTF-16.
Programs for other encodings (such as 8-bit ASCII, or EUC-JP) are not required to handle all Unicode characters.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #360_Assembly | 360 Assembly | * Substring/Top and tail 04/03/2017
SUBSTRTT CSECT
USING SUBSTRTT,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
STM R14,R12,12(R13) save previous context
ST R13,4(R15) link backward
ST R15,8(R13) link forward
LR R13,R15 set addressability
*
XPRNT S8,L'S8 print s8
MVC S7,S8+1 s7=substr(s8,2,7)
XPRNT S7,L'S7 print s7
MVC S7,S8 s7=substr(s8,1,7)
XPRNT S7,L'S7 print s7
MVC S6,S8+1 s6=substr(s8,2,6)
XPRNT S6,L'S6 print s6
*
L R13,4(0,R13) epilog
LM R14,R12,12(R13) restore previous context
XR R15,R15 rc=0
BR R14 exit
S8 DC CL8'12345678'
S7 DS CL7
S6 DS CL6
YREGS
END SUBSTRTT |
http://rosettacode.org/wiki/Substring/Top_and_tail | Substring/Top and tail | The task is to demonstrate how to remove the first and last characters from a string.
The solution should demonstrate how to obtain the following results:
String with first character removed
String with last character removed
String with both the first and last characters removed
If the program uses UTF-8 or UTF-16, it must work on any valid Unicode code point, whether in the Basic Multilingual Plane or above it.
The program must reference logical characters (code points), not 8-bit code units for UTF-8 or 16-bit code units for UTF-16.
Programs for other encodings (such as 8-bit ASCII, or EUC-JP) are not required to handle all Unicode characters.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #ACL2 | ACL2 | (defun str-rest (str)
(coerce (rest (coerce str 'list)) 'string))
(defun rdc (xs)
(if (endp (rest xs))
nil
(cons (first xs)
(rdc (rest xs)))))
(defun str-rdc (str)
(coerce (rdc (coerce str 'list)) 'string))
(str-rdc "string")
(str-rest "string")
(str-rest (str-rdc "string")) |
http://rosettacode.org/wiki/Subtractive_generator | Subtractive generator | A subtractive generator calculates a sequence of random numbers, where each number is congruent to the subtraction of two previous numbers from the sequence.
The formula is
r
n
=
r
(
n
−
i
)
−
r
(
n
−
j
)
(
mod
m
)
{\displaystyle r_{n}=r_{(n-i)}-r_{(n-j)}{\pmod {m}}}
for some fixed values of
i
{\displaystyle i}
,
j
{\displaystyle j}
and
m
{\displaystyle m}
, all positive integers. Supposing that
i
>
j
{\displaystyle i>j}
, then the state of this generator is the list of the previous numbers from
r
n
−
i
{\displaystyle r_{n-i}}
to
r
n
−
1
{\displaystyle r_{n-1}}
. Many states generate uniform random integers from
0
{\displaystyle 0}
to
m
−
1
{\displaystyle m-1}
, but some states are bad. A state, filled with zeros, generates only zeros. If
m
{\displaystyle m}
is even, then a state, filled with even numbers, generates only even numbers. More generally, if
f
{\displaystyle f}
is a factor of
m
{\displaystyle m}
, then a state, filled with multiples of
f
{\displaystyle f}
, generates only multiples of
f
{\displaystyle f}
.
All subtractive generators have some weaknesses. The formula correlates
r
n
{\displaystyle r_{n}}
,
r
(
n
−
i
)
{\displaystyle r_{(n-i)}}
and
r
(
n
−
j
)
{\displaystyle r_{(n-j)}}
; these three numbers are not independent, as true random numbers would be. Anyone who observes
i
{\displaystyle i}
consecutive numbers can predict the next numbers, so the generator is not cryptographically secure. The authors of Freeciv (utility/rand.c) and xpat2 (src/testit2.c) knew another problem: the low bits are less random than the high bits.
The subtractive generator has a better reputation than the linear congruential generator, perhaps because it holds more state. A subtractive generator might never multiply numbers: this helps where multiplication is slow. A subtractive generator might also avoid division: the value of
r
(
n
−
i
)
−
r
(
n
−
j
)
{\displaystyle r_{(n-i)}-r_{(n-j)}}
is always between
−
m
{\displaystyle -m}
and
m
{\displaystyle m}
, so a program only needs to add
m
{\displaystyle m}
to negative numbers.
The choice of
i
{\displaystyle i}
and
j
{\displaystyle j}
affects the period of the generator. A popular choice is
i
=
55
{\displaystyle i=55}
and
j
=
24
{\displaystyle j=24}
, so the formula is
r
n
=
r
(
n
−
55
)
−
r
(
n
−
24
)
(
mod
m
)
{\displaystyle r_{n}=r_{(n-55)}-r_{(n-24)}{\pmod {m}}}
The subtractive generator from xpat2 uses
r
n
=
r
(
n
−
55
)
−
r
(
n
−
24
)
(
mod
10
9
)
{\displaystyle r_{n}=r_{(n-55)}-r_{(n-24)}{\pmod {10^{9}}}}
The implementation is by J. Bentley and comes from program_tools/universal.c of the DIMACS (netflow) archive at Rutgers University. It credits Knuth, TAOCP, Volume 2, Section 3.2.2 (Algorithm A).
Bentley uses this clever algorithm to seed the generator.
Start with a single
s
e
e
d
{\displaystyle seed}
in range
0
{\displaystyle 0}
to
10
9
−
1
{\displaystyle 10^{9}-1}
.
Set
s
0
=
s
e
e
d
{\displaystyle s_{0}=seed}
and
s
1
=
1
{\displaystyle s_{1}=1}
. The inclusion of
s
1
=
1
{\displaystyle s_{1}=1}
avoids some bad states (like all zeros, or all multiples of 10).
Compute
s
2
,
s
3
,
.
.
.
,
s
54
{\displaystyle s_{2},s_{3},...,s_{54}}
using the subtractive formula
s
n
=
s
(
n
−
2
)
−
s
(
n
−
1
)
(
mod
10
9
)
{\displaystyle s_{n}=s_{(n-2)}-s_{(n-1)}{\pmod {10^{9}}}}
.
Reorder these 55 values so
r
0
=
s
34
{\displaystyle r_{0}=s_{34}}
,
r
1
=
s
13
{\displaystyle r_{1}=s_{13}}
,
r
2
=
s
47
{\displaystyle r_{2}=s_{47}}
, ...,
r
n
=
s
(
34
∗
(
n
+
1
)
(
mod
55
)
)
{\displaystyle r_{n}=s_{(34*(n+1){\pmod {55}})}}
.
This is the same order as
s
0
=
r
54
{\displaystyle s_{0}=r_{54}}
,
s
1
=
r
33
{\displaystyle s_{1}=r_{33}}
,
s
2
=
r
12
{\displaystyle s_{2}=r_{12}}
, ...,
s
n
=
r
(
(
34
∗
n
)
−
1
(
mod
55
)
)
{\displaystyle s_{n}=r_{((34*n)-1{\pmod {55}})}}
.
This rearrangement exploits how 34 and 55 are relatively prime.
Compute the next 165 values
r
55
{\displaystyle r_{55}}
to
r
219
{\displaystyle r_{219}}
. Store the last 55 values.
This generator yields the sequence
r
220
{\displaystyle r_{220}}
,
r
221
{\displaystyle r_{221}}
,
r
222
{\displaystyle r_{222}}
and so on. For example, if the seed is 292929, then the sequence begins with
r
220
=
467478574
{\displaystyle r_{220}=467478574}
,
r
221
=
512932792
{\displaystyle r_{221}=512932792}
,
r
222
=
539453717
{\displaystyle r_{222}=539453717}
. By starting at
r
220
{\displaystyle r_{220}}
, this generator avoids a bias from the first numbers of the sequence. This generator must store the last 55 numbers of the sequence, so to compute the next
r
n
{\displaystyle r_{n}}
. Any array or list would work; a ring buffer is ideal but not necessary.
Implement a subtractive generator that replicates the sequences from xpat2.
| #Ada | Ada | package Subtractive_Generator is
type State is private;
procedure Initialize (Generator : in out State; Seed : Natural);
procedure Next (Generator : in out State; N : out Natural);
private
type Number_Array is array (Natural range <>) of Natural;
type State is record
R : Number_Array (0 .. 54);
Last : Natural;
end record;
end Subtractive_Generator; |
http://rosettacode.org/wiki/Substitution_cipher | Substitution cipher | Substitution Cipher Implementation - File Encryption/Decryption
Task
Encrypt a input/source file by replacing every upper/lower case alphabets of the source file with another predetermined upper/lower case alphabets or symbols and save it into another output/encrypted file and then again convert that output/encrypted file into original/decrypted file.
This type of Encryption/Decryption scheme is often called a Substitution Cipher.
Related tasks
Caesar cipher
Rot-13
Vigenère Cipher/Cryptanalysis
See also
Wikipedia: Substitution cipher
| #Fortran | Fortran | program substitution
implicit none
integer, parameter :: len_max = 256
integer, parameter :: eof = -1
integer :: in_unit = 9, out_unit = 10, ios
character(len_max) :: line
open(in_unit, file="plain.txt", iostat=ios)
if (ios /= 0) then
write(*,*) "Error opening plain.txt file"
stop
end if
open(out_unit, file="encrypted.txt", iostat=ios)
if (ios /= 0) then
write(*,*) "Error opening encrypted.txt file"
stop
end if
! Encryption
do
read(in_unit, "(a)", iostat=ios) line
if (ios > 0) then
write(*,*) "Error reading plain.txt file"
stop
else if (ios == eof) then
exit
end if
call cipher(trim(line))
write(out_unit, "(a)", iostat=ios) trim(line)
if (ios /= 0) then
write(*,*) "Error writing encrypted.txt file"
stop
end if
end do
close(in_unit)
close(out_unit)
open(in_unit, file="encrypted.txt", iostat=ios)
if (ios /= 0) then
write(*,*) "Error opening encrypted.txt file"
stop
end if
open(out_unit, file="decrypted.txt", iostat=ios)
if (ios /= 0) then
write(*,*) "Error opening decrypted.txt file"
stop
end if
! Decryption
do
read(in_unit, "(a)", iostat=ios) line
if (ios > 0) then
write(*,*) "Error reading encrypted.txt file"
stop
else if (ios == eof) then
exit
end if
call cipher(trim(line))
write(out_unit, "(a)", iostat=ios) trim(line)
if (ios /= 0) then
write(*,*) "Error writing decrypted.txt file"
stop
end if
end do
close(in_unit)
close(out_unit)
contains
subroutine cipher(text)
character(*), intent(in out) :: text
integer :: i
! Substitutes A -> Z, B -> Y ... Y -> B, Z -> A and ditto for lower case
! works for both encryption and decryption
do i = 1, len(text)
select case(text(i:i))
case ('A':'Z')
text(i:i) = achar(155 - iachar(text(i:i)))
case ('a':'z')
text(i:i) = achar(219 - iachar(text(i:i)))
end select
end do
end subroutine
end program |
http://rosettacode.org/wiki/Sum_and_product_of_an_array | Sum and product of an array | Task
Compute the sum and product of an array of integers.
| #C.2B.2B | C++ | #include <numeric>
#include <functional>
int arg[] = { 1, 2, 3, 4, 5 };
int sum = std::accumulate(arg, arg+5, 0, std::plus<int>());
// or just
// std::accumulate(arg, arg + 5, 0);
// since plus() is the default functor for accumulate
int prod = std::accumulate(arg, arg+5, 1, std::multiplies<int>()); |
http://rosettacode.org/wiki/Sum_of_a_series | Sum of a series | Compute the nth term of a series, i.e. the sum of the n first terms of the corresponding sequence.
Informally this value, or its limit when n tends to infinity, is also called the sum of the series, thus the title of this task.
For this task, use:
S
n
=
∑
k
=
1
n
1
k
2
{\displaystyle S_{n}=\sum _{k=1}^{n}{\frac {1}{k^{2}}}}
and compute
S
1000
{\displaystyle S_{1000}}
This approximates the zeta function for S=2, whose exact value
ζ
(
2
)
=
π
2
6
{\displaystyle \zeta (2)={\pi ^{2} \over 6}}
is the solution of the Basel problem.
| #C.2B.2B | C++ | #include <iostream>
double f(double x);
int main()
{
unsigned int start = 1;
unsigned int end = 1000;
double sum = 0;
for( unsigned int x = start; x <= end; ++x )
{
sum += f(x);
}
std::cout << "Sum of f(x) from " << start << " to " << end << " is " << sum << std::endl;
return 0;
}
double f(double x)
{
return ( 1.0 / ( x * x ) );
} |
http://rosettacode.org/wiki/Sum_to_100 | Sum to 100 | Task
Find solutions to the sum to one hundred puzzle.
Add (insert) the mathematical
operators + or - (plus
or minus) before any of the digits in the
decimal numeric string 123456789 such that the
resulting mathematical expression adds up to a
particular sum (in this iconic case, 100).
Example:
123 + 4 - 5 + 67 - 89 = 100
Show all output here.
Show all solutions that sum to 100
Show the sum that has the maximum number of solutions (from zero to infinity‡)
Show the lowest positive sum that can't be expressed (has no solutions), using the rules for this task
Show the ten highest numbers that can be expressed using the rules for this task (extra credit)
‡ (where infinity would be a relatively small 123,456,789)
An example of a sum that can't be expressed (within the rules of this task) is: 5074
(which, of course, isn't the lowest positive sum that can't be expressed).
| #Forth | Forth | CREATE *OPS CHAR + C, CHAR - C, CHAR # C,
CREATE 0OPS CHAR - C, CHAR # C,
CREATE BUFF 43 C, 43 CHARS ALLOT
CREATE PTR CELL ALLOT
CREATE LIMITS 2 C, 3 C, 3 C, 3 C, 3 C, 3 C, 3 C, 3 C, 3 C,
CREATE INDX 0 C, 0 C, 0 C, 0 C, 0 C, 0 C, 0 C, 0 C, 0 C,
CREATE OPS 0OPS , *OPS , *OPS , *OPS , *OPS , *OPS , *OPS , *OPS , *OPS ,
: B0 BUFF 1+ dup PTR ! 43 blank ;
: B, ( c --) PTR @ C! 1 PTR +! ;
CREATE STATS 123456790 ALLOT STATS 123456790 ERASE
: inc ( c-addr c-lim u -- t|f)
1- tuck + >r swap dup rot + ( addr a-addr) ( R: l-addr)
BEGIN dup C@ 1+ dup r@ C@ =
IF drop 2dup =
IF 2drop FALSE rdrop EXIT \ no inc, contents invalid
ELSE 0 over C! 1- r> 1- >r \ reset and carry
THEN
ELSE swap C! drop TRUE rdrop EXIT
THEN
AGAIN ;
: INDX+ INDX LIMITS 9 inc 0= ;
: SYNTH B0 [CHAR] 0 B, 9 0 DO
INDX I + C@ OPS I CELLS + @ + C@
dup [CHAR] # <> IF BL B, B, BL B, ELSE drop THEN
I [CHAR] 1 + B,
LOOP BUFF COUNT ;
: .MOST cr ." Sum that has the maximum number of solutions" cr 4 spaces
STATS 0 STATS 1+ 123456789 bounds DO
dup I c@ < IF drop drop I I c@ THEN
LOOP swap STATS - . ." has " . ." solutions" ;
: .CANT cr ." Lowest positive sum that can't be expressed" cr 4 spaces
STATS 1+ ( 0 not positive) BEGIN dup c@ WHILE 1+ REPEAT STATS - . ;
: .BEST cr ." Ten highest numbers that can be expressed" cr 4 spaces
0 >r [ STATS 123456789 + ]L
BEGIN r@ 10 < over STATS >= and
WHILE dup c@ IF dup STATS - . r> 1+ >r THEN 1-
REPEAT r> drop ;
: . 0 <# #S #> TYPE ;
: .INFX cr 4 spaces 9 0 DO
INDX I + C@ OPS I cells + @ + C@
dup [char] # <> IF emit ELSE drop THEN I 1+ .
LOOP ;
: REPORT ( n) dup 100 = IF .INFX THEN
dup 0> IF STATS + dup c@ 1+ swap c! ELSE drop THEN ;
: >NUM 0. bl word count >number 2drop d>s ;
: # 10 * + ; \ numeric concatenation
: + >NUM + ; \ infix +
: - >NUM - ; \ infix -
: .SOLUTIONS cr ." Solutions that sum to 100:"
BEGIN SYNTH EVALUATE REPORT INDX+ UNTIL ;
: SUM100 .SOLUTIONS .MOST .CANT .BEST cr ; |
http://rosettacode.org/wiki/Sum_multiples_of_3_and_5 | Sum multiples of 3 and 5 | Task
The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n.
Show output for n = 1000.
This is is the same as Project Euler problem 1.
Extra credit: do this efficiently for n = 1e20 or higher.
| #Component_Pascal | Component Pascal |
MODULE Sum3_5;
IMPORT StdLog, Strings, Args;
PROCEDURE DoSum(n: INTEGER):INTEGER;
VAR
i,sum: INTEGER;
BEGIN
sum := 0;i := 0;
WHILE (i < n) DO
IF (i MOD 3 = 0) OR (i MOD 5 = 0) THEN INC(sum,i) END;
INC(i)
END;
RETURN sum
END DoSum;
PROCEDURE Compute*;
VAR
params: Args.Params;
i,n,res: INTEGER;
BEGIN
Args.Get(params);
Strings.StringToInt(params.args[0],n,res);
StdLog.String("Sum: ");StdLog.Int(DoSum(n)); StdLog.Ln
END Compute;
END Sum3_5.
|
http://rosettacode.org/wiki/Sum_digits_of_an_integer | Sum digits of an integer | Task
Take a Natural Number in a given base and return the sum of its digits:
110 sums to 1
123410 sums to 10
fe16 sums to 29
f0e16 sums to 29
| #Common_Lisp | Common Lisp | (defun sum-digits (number base)
(loop for n = number then q
for (q r) = (multiple-value-list (truncate n base))
sum r until (zerop q))) |
http://rosettacode.org/wiki/Sum_of_squares | Sum of squares | Task
Write a program to find the sum of squares of a numeric vector.
The program should work on a zero-length vector (with an answer of 0).
Related task
Mean
| #Delphi | Delphi | program SumOfSq;
{$APPTYPE CONSOLE}
uses Math;
type
TDblArray = array of Double;
var
A: TDblArray;
begin
Writeln(SumOfSquares([]):6:2); // 0.00
Writeln(SumOfSquares([1, 2, 3, 4]):6:2); // 30.00
A:= nil;
Writeln(SumOfSquares(A):6:2); // 0.00
A:= TDblArray.Create(1, 2, 3, 4);
Writeln(SumOfSquares(A):6:2); // 30.00
Readln;
end. |
http://rosettacode.org/wiki/Successive_prime_differences | Successive prime differences | The series of increasing prime numbers begins: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, ...
The task applies a filter to the series returning groups of successive primes, (s'primes), that differ from the next by a given value or values.
Example 1: Specifying that the difference between s'primes be 2 leads to the groups:
(3, 5), (5, 7), (11, 13), (17, 19), (29, 31), ...
(Known as Twin primes or Prime pairs)
Example 2: Specifying more than one difference between s'primes leads to groups of size one greater than the number of differences. Differences of 2, 4 leads to the groups:
(5, 7, 11), (11, 13, 17), (17, 19, 23), (41, 43, 47), ....
In the first group 7 is two more than 5 and 11 is four more than 7; as well as 5, 7, and 11 being successive primes.
Differences are checked in the order of the values given, (differences of 4, 2 would give different groups entirely).
Task
In each case use a list of primes less than 1_000_000
For the following Differences show the first and last group, as well as the number of groups found:
Differences of 2.
Differences of 1.
Differences of 2, 2.
Differences of 2, 4.
Differences of 4, 2.
Differences of 6, 4, 2.
Show output here.
Note: Generation of a list of primes is a secondary aspect of the task. Use of a built in function, well known library, or importing/use of prime generators from other Rosetta Code tasks is encouraged.
references
https://pdfs.semanticscholar.org/78a1/7349819304863ae061df88dbcb26b4908f03.pdf
https://www.primepuzzles.net/puzzles/puzz_011.htm
https://matheplanet.de/matheplanet/nuke/html/viewtopic.php?topic=232720&start=0 | #11l | 11l | F primes_upto(limit)
V is_prime = [0B] * 2 [+] [1B] * (limit - 1)
L(n) 0 .< Int(limit ^ 0.5 + 1.5)
I is_prime[n]
L(i) (n * n .< limit + 1).step(n)
is_prime[i] = 0B
R enumerate(is_prime).filter((i, prime) -> prime).map((i, prime) -> i)
F successive_primes(primes, diffs)
[[Int]] results
V dl = diffs.len
L(i) 0 .< primes.len - dl
V group = [0] * (dl + 1)
group[0] = primes[i]
L(j) i .+ dl
I primes[j + 1] - primes[j] != diffs[j - i]
L.break
group[j - i + 1] = primes[j + 1]
L.was_no_break
results [+]= group
R results
V prime_list = primes_upto(1'000'000)
print(‘For primes less than 1,000,000:-’)
L(diffs) [[2], [1], [2, 2], [2, 4], [4, 2], [6, 4, 2]]
print(‘ For differences of #. ->’.format(diffs))
V sp = successive_primes(prime_list, diffs)
print(‘ First group = ’sp[0])
print(‘ Last group = ’sp.last)
print(‘ Number found = ’sp.len)
print() |
http://rosettacode.org/wiki/Substring/Top_and_tail | Substring/Top and tail | The task is to demonstrate how to remove the first and last characters from a string.
The solution should demonstrate how to obtain the following results:
String with first character removed
String with last character removed
String with both the first and last characters removed
If the program uses UTF-8 or UTF-16, it must work on any valid Unicode code point, whether in the Basic Multilingual Plane or above it.
The program must reference logical characters (code points), not 8-bit code units for UTF-8 or 16-bit code units for UTF-16.
Programs for other encodings (such as 8-bit ASCII, or EUC-JP) are not required to handle all Unicode characters.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Action.21 | Action! | PROC Main()
CHAR ARRAY text="qwertyuiop"
CHAR ARRAY res(20)
BYTE n,m
PrintF("Original string:%E ""%S""%E%E",text)
SCopyS(res,text,2,text(0))
PrintF("String without the top:%E ""%S""%E%E",res)
SCopyS(res,text,1,text(0)-1)
PrintF("String without the tail:%E ""%S""%E%E",res)
SCopyS(res,text,2,text(0)-1)
PrintF("String without the top and the tail:%E ""%S""%E%E",res)
RETURN |
http://rosettacode.org/wiki/Substring/Top_and_tail | Substring/Top and tail | The task is to demonstrate how to remove the first and last characters from a string.
The solution should demonstrate how to obtain the following results:
String with first character removed
String with last character removed
String with both the first and last characters removed
If the program uses UTF-8 or UTF-16, it must work on any valid Unicode code point, whether in the Basic Multilingual Plane or above it.
The program must reference logical characters (code points), not 8-bit code units for UTF-8 or 16-bit code units for UTF-16.
Programs for other encodings (such as 8-bit ASCII, or EUC-JP) are not required to handle all Unicode characters.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Ada | Ada | with Ada.Text_IO;
procedure Remove_Characters is
S: String := "upraisers";
use Ada.Text_IO;
begin
Put_Line("Full String: """ & S & """");
Put_Line("Without_First: """ & S(S'First+1 .. S'Last) & """");
Put_Line("Without_Last: """ & S(S'First .. S'Last-1) & """");
Put_Line("Without_Both: """ & S(S'First+1 .. S'Last-1) & """");
end Remove_Characters; |
http://rosettacode.org/wiki/Subtractive_generator | Subtractive generator | A subtractive generator calculates a sequence of random numbers, where each number is congruent to the subtraction of two previous numbers from the sequence.
The formula is
r
n
=
r
(
n
−
i
)
−
r
(
n
−
j
)
(
mod
m
)
{\displaystyle r_{n}=r_{(n-i)}-r_{(n-j)}{\pmod {m}}}
for some fixed values of
i
{\displaystyle i}
,
j
{\displaystyle j}
and
m
{\displaystyle m}
, all positive integers. Supposing that
i
>
j
{\displaystyle i>j}
, then the state of this generator is the list of the previous numbers from
r
n
−
i
{\displaystyle r_{n-i}}
to
r
n
−
1
{\displaystyle r_{n-1}}
. Many states generate uniform random integers from
0
{\displaystyle 0}
to
m
−
1
{\displaystyle m-1}
, but some states are bad. A state, filled with zeros, generates only zeros. If
m
{\displaystyle m}
is even, then a state, filled with even numbers, generates only even numbers. More generally, if
f
{\displaystyle f}
is a factor of
m
{\displaystyle m}
, then a state, filled with multiples of
f
{\displaystyle f}
, generates only multiples of
f
{\displaystyle f}
.
All subtractive generators have some weaknesses. The formula correlates
r
n
{\displaystyle r_{n}}
,
r
(
n
−
i
)
{\displaystyle r_{(n-i)}}
and
r
(
n
−
j
)
{\displaystyle r_{(n-j)}}
; these three numbers are not independent, as true random numbers would be. Anyone who observes
i
{\displaystyle i}
consecutive numbers can predict the next numbers, so the generator is not cryptographically secure. The authors of Freeciv (utility/rand.c) and xpat2 (src/testit2.c) knew another problem: the low bits are less random than the high bits.
The subtractive generator has a better reputation than the linear congruential generator, perhaps because it holds more state. A subtractive generator might never multiply numbers: this helps where multiplication is slow. A subtractive generator might also avoid division: the value of
r
(
n
−
i
)
−
r
(
n
−
j
)
{\displaystyle r_{(n-i)}-r_{(n-j)}}
is always between
−
m
{\displaystyle -m}
and
m
{\displaystyle m}
, so a program only needs to add
m
{\displaystyle m}
to negative numbers.
The choice of
i
{\displaystyle i}
and
j
{\displaystyle j}
affects the period of the generator. A popular choice is
i
=
55
{\displaystyle i=55}
and
j
=
24
{\displaystyle j=24}
, so the formula is
r
n
=
r
(
n
−
55
)
−
r
(
n
−
24
)
(
mod
m
)
{\displaystyle r_{n}=r_{(n-55)}-r_{(n-24)}{\pmod {m}}}
The subtractive generator from xpat2 uses
r
n
=
r
(
n
−
55
)
−
r
(
n
−
24
)
(
mod
10
9
)
{\displaystyle r_{n}=r_{(n-55)}-r_{(n-24)}{\pmod {10^{9}}}}
The implementation is by J. Bentley and comes from program_tools/universal.c of the DIMACS (netflow) archive at Rutgers University. It credits Knuth, TAOCP, Volume 2, Section 3.2.2 (Algorithm A).
Bentley uses this clever algorithm to seed the generator.
Start with a single
s
e
e
d
{\displaystyle seed}
in range
0
{\displaystyle 0}
to
10
9
−
1
{\displaystyle 10^{9}-1}
.
Set
s
0
=
s
e
e
d
{\displaystyle s_{0}=seed}
and
s
1
=
1
{\displaystyle s_{1}=1}
. The inclusion of
s
1
=
1
{\displaystyle s_{1}=1}
avoids some bad states (like all zeros, or all multiples of 10).
Compute
s
2
,
s
3
,
.
.
.
,
s
54
{\displaystyle s_{2},s_{3},...,s_{54}}
using the subtractive formula
s
n
=
s
(
n
−
2
)
−
s
(
n
−
1
)
(
mod
10
9
)
{\displaystyle s_{n}=s_{(n-2)}-s_{(n-1)}{\pmod {10^{9}}}}
.
Reorder these 55 values so
r
0
=
s
34
{\displaystyle r_{0}=s_{34}}
,
r
1
=
s
13
{\displaystyle r_{1}=s_{13}}
,
r
2
=
s
47
{\displaystyle r_{2}=s_{47}}
, ...,
r
n
=
s
(
34
∗
(
n
+
1
)
(
mod
55
)
)
{\displaystyle r_{n}=s_{(34*(n+1){\pmod {55}})}}
.
This is the same order as
s
0
=
r
54
{\displaystyle s_{0}=r_{54}}
,
s
1
=
r
33
{\displaystyle s_{1}=r_{33}}
,
s
2
=
r
12
{\displaystyle s_{2}=r_{12}}
, ...,
s
n
=
r
(
(
34
∗
n
)
−
1
(
mod
55
)
)
{\displaystyle s_{n}=r_{((34*n)-1{\pmod {55}})}}
.
This rearrangement exploits how 34 and 55 are relatively prime.
Compute the next 165 values
r
55
{\displaystyle r_{55}}
to
r
219
{\displaystyle r_{219}}
. Store the last 55 values.
This generator yields the sequence
r
220
{\displaystyle r_{220}}
,
r
221
{\displaystyle r_{221}}
,
r
222
{\displaystyle r_{222}}
and so on. For example, if the seed is 292929, then the sequence begins with
r
220
=
467478574
{\displaystyle r_{220}=467478574}
,
r
221
=
512932792
{\displaystyle r_{221}=512932792}
,
r
222
=
539453717
{\displaystyle r_{222}=539453717}
. By starting at
r
220
{\displaystyle r_{220}}
, this generator avoids a bias from the first numbers of the sequence. This generator must store the last 55 numbers of the sequence, so to compute the next
r
n
{\displaystyle r_{n}}
. Any array or list would work; a ring buffer is ideal but not necessary.
Implement a subtractive generator that replicates the sequences from xpat2.
| #AutoHotkey | AutoHotkey | r := InitR(292929)
Loop, 10
Out .= (A_Index + 219) ":`t" GetRand(r) "`n"
MsgBox, % Out
GetRand(r) {
i := Mod(r["j"], 55)
, r[i] := Mod(r[i] - r[Mod(i + 31, 55)], r["m"])
, r["j"] += 1
return, (r[i] < 0 ? r[i] + r["m"] : r[i])
}
InitR(Seed) {
r := {"j": 0, "m": 10 ** 9}, s := {0: Seed, 1: 1}
Loop, 53
s[A_Index + 1] := Mod(s[A_Index - 1] - s[A_Index], r["m"])
Loop, 55
r[A_Index - 1] := s[Mod(34 * A_Index, 55)]
Loop, 165
i := Mod(A_Index + 54, 55)
, r[i] := Mod(r[i] - r[Mod(A_Index + 30, 55)], r["m"])
return, r
} |
http://rosettacode.org/wiki/Substitution_cipher | Substitution cipher | Substitution Cipher Implementation - File Encryption/Decryption
Task
Encrypt a input/source file by replacing every upper/lower case alphabets of the source file with another predetermined upper/lower case alphabets or symbols and save it into another output/encrypted file and then again convert that output/encrypted file into original/decrypted file.
This type of Encryption/Decryption scheme is often called a Substitution Cipher.
Related tasks
Caesar cipher
Rot-13
Vigenère Cipher/Cryptanalysis
See also
Wikipedia: Substitution cipher
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
' uses same alphabet and key as Ada language example
Const string1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
Const string2 = "VsciBjedgrzyHalvXZKtUPumGfIwJxqOCFRApnDhQWobLkESYMTN"
Sub process(inputFile As String, outputFile As String, encrypt As Boolean)
Open inputFile For Input As #1
If err > 0 Then
Print "Unable to open input file"
Sleep
End
End If
Dim As String alpha, key
If encrypt Then
alpha = string1 : key = string2
Else
alpha = string2 : key = string1
End If
Open outputFile For Output As #2
Dim s As String
Dim p As Integer
While Not Eof(1)
Line Input #1, s
For i As Integer = 0 To Len(s) - 1
If (s[i] >= 65 AndAlso s[i] <= 90) OrElse (s[i] >= 97 AndAlso s[i] <= 122) Then
p = Instr(alpha, Mid(s, i + 1, 1)) - 1
s[i] = key[p]
End If
Next
Print #2, s
Wend
Close #1 : Close #2
End Sub
process "plain.txt", "encrypted.txt", true
process "encrypted.txt", "decrypted.txt", false
Print
Print "Press any key to quit"
Sleep |
http://rosettacode.org/wiki/Sum_and_product_of_an_array | Sum and product of an array | Task
Compute the sum and product of an array of integers.
| #Chef | Chef | Sum and Product of Numbers as a Piece of Cake.
This recipe sums N given numbers.
Ingredients.
1 N
0 sum
1 product
1 number
Method.
Put sum into 1st mixing bowl.
Put product into 2nd mixing bowl.
Take N from refrigerator.
Chop N.
Take number from refrigerator.
Add number into 1st mixing bowl.
Combine number into 2nd mixing bowl.
Chop N until choped.
Pour contents of 2nd mixing bowl into the baking dish.
Pour contents of 1st mixing bowl into the baking dish.
Serves 1. |
http://rosettacode.org/wiki/Sum_and_product_of_an_array | Sum and product of an array | Task
Compute the sum and product of an array of integers.
| #Clean | Clean | array = {1, 2, 3, 4, 5}
Sum = sum [x \\ x <-: array]
Prod = foldl (*) 1 [x \\ x <-: array] |
http://rosettacode.org/wiki/Sum_of_a_series | Sum of a series | Compute the nth term of a series, i.e. the sum of the n first terms of the corresponding sequence.
Informally this value, or its limit when n tends to infinity, is also called the sum of the series, thus the title of this task.
For this task, use:
S
n
=
∑
k
=
1
n
1
k
2
{\displaystyle S_{n}=\sum _{k=1}^{n}{\frac {1}{k^{2}}}}
and compute
S
1000
{\displaystyle S_{1000}}
This approximates the zeta function for S=2, whose exact value
ζ
(
2
)
=
π
2
6
{\displaystyle \zeta (2)={\pi ^{2} \over 6}}
is the solution of the Basel problem.
| #CLIPS | CLIPS | (deffunction S (?x) (/ 1 (* ?x ?x)))
(deffunction partial-sum-S
(?start ?stop)
(bind ?sum 0)
(loop-for-count (?i ?start ?stop) do
(bind ?sum (+ ?sum (S ?i)))
)
(return ?sum)
) |
http://rosettacode.org/wiki/Sum_to_100 | Sum to 100 | Task
Find solutions to the sum to one hundred puzzle.
Add (insert) the mathematical
operators + or - (plus
or minus) before any of the digits in the
decimal numeric string 123456789 such that the
resulting mathematical expression adds up to a
particular sum (in this iconic case, 100).
Example:
123 + 4 - 5 + 67 - 89 = 100
Show all output here.
Show all solutions that sum to 100
Show the sum that has the maximum number of solutions (from zero to infinity‡)
Show the lowest positive sum that can't be expressed (has no solutions), using the rules for this task
Show the ten highest numbers that can be expressed using the rules for this task (extra credit)
‡ (where infinity would be a relatively small 123,456,789)
An example of a sum that can't be expressed (within the rules of this task) is: 5074
(which, of course, isn't the lowest positive sum that can't be expressed).
| #Fortran | Fortran | C ROSSETACODE: SUM TO 100, FORTRAN IV
C FIND SOLUTIONS TO THE "SUM TO ONE HUNDRED" PUZZLE
C =================================================
PROGRAM SUMTO100
DATA NEXPRM1/13121/
WRITE(6,110)
110 FORMAT(1X/1X,34HSHOW ALL SOLUTIONS THAT SUM TO 100/)
DO 10 I = 0,NEXPRM1
10 IF ( IEVAL(I) .EQ. 100 ) CALL PREXPR(I)
WRITE(6,120)
120 FORMAT(1X/1X,
153HSHOW THE SUM THAT HAS THE MAXIMUM NUMBER OF SOLUTIONS/)
NBEST = -1
DO 30 I = 0, NEXPRM1
ITEST = IEVAL(I)
IF ( ITEST .LT. 0 ) GOTO 30
NTEST = 0
DO 20 J = 0, NEXPRM1
20 IF ( IEVAL(J) .EQ. ITEST ) NTEST = NTEST + 1
IF ( NTEST .LE. NBEST ) GOTO 30
IBEST = ITEST
NBEST = NTEST
30 CONTINUE
WRITE(6,121) IBEST, NBEST
121 FORMAT(1X,I8,5H HAS ,I8,10H SOLUTIONS/)
WRITE(6,130)
130 FORMAT(1X/1X,
155HSHOW THE LOWEST POSITIVE NUMBER THAT CAN'T BE EXPRESSED/)
DO 50 I = 0,123456789
DO 40 J = 0,NEXPRM1
40 IF ( I .EQ. IEVAL(J) ) GOTO 50
GOTO 60
50 CONTINUE
60 WRITE(6,131) I
131 FORMAT(1X,I8)
WRITE(6,140)
140 FORMAT(1X/1X,
150HSHOW THE TEN HIGHEST NUMBERS THAT CAN BE EXPRESSED/)
ILIMIT = 123456789
DO 90 I = 1,10
IBEST = 0
DO 70 J = 0, NEXPRM1
ITEST = IEVAL(J)
70 IF( (ITEST .LE. ILIMIT) .AND. (ITEST .GT. IBEST)) IBEST = ITEST
DO 80 J = 0, NEXPRM1
80 IF ( IEVAL(J) .EQ. IBEST ) CALL PREXPR(J)
90 ILIMIT = IBEST - 1
END
C EVALUATE THE VALUE OF THE GIVEN ENCODED EXPRESSION
C --------------------------------------------------
FUNCTION IEVAL(ICODE)
IC = ICODE
IEVAL = 0
N = 0
IP = 1
DO 50 K = 9,1,-1
N = IP*K + N
GOTO (10,20,40,30) MOD(IC,3)+1
10 IEVAL = IEVAL + N
GOTO 30
20 IEVAL = IEVAL - N
30 N = 0
IP = 1
GOTO 50
40 IP = IP * 10
50 IC = IC / 3
END
C PRINT THE ENCODED EXPRESSION IN THE READABLE FORMAT
C ---------------------------------------------------
SUBROUTINE PREXPR(ICODE)
DIMENSION IH(9),IHPMJ(4)
DATA IHPMJ/1H+,1H-,1H ,1H?/
IA = 19683
IB = 6561
DO 10 K = 1,9
IH(K) = IHPMJ(MOD(ICODE,IA) / IB+1)
IA = IB
10 IB = IB / 3
IVALUE = IEVAL(ICODE)
WRITE(6,110) IVALUE, IH
110 FORMAT(I9,3H = 1A1,1H1,1A1,1H2,1A1,1H3,1A1,1H4,1A1,1H5,1A1,1H6,1A1
1,1H7,1A1,1H8,1A1,1H9)
END |
http://rosettacode.org/wiki/Sum_multiples_of_3_and_5 | Sum multiples of 3 and 5 | Task
The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n.
Show output for n = 1000.
This is is the same as Project Euler problem 1.
Extra credit: do this efficiently for n = 1e20 or higher.
| #Cowgol | Cowgol | include "cowgol.coh";
# sum multiples up to given input
interface SumMulTo(mul: uint32, to: uint32): (rslt: uint32);
# naive implementation
sub naiveSumMulTo implements SumMulTo is
rslt := 0;
var cur := mul;
while cur < to loop
rslt := rslt + cur;
cur := cur + mul;
end loop;
end sub;
# number theoretical implementation
sub fastSumMulTo implements SumMulTo is
to := (to - 1)/mul;
rslt := mul * to * (to + 1)/2;
end sub;
# sum multiples of 3 and 5 up to given number using given method
sub sum35(to: uint32, sum: SumMulTo): (rslt: uint32) is
rslt := sum(3, to) + sum(5, to) - sum(15, to);
end sub;
print("Naive method: "); print_i32(sum35(1000, naiveSumMulTo)); print_nl();
print("Fast method: "); print_i32(sum35(1000, fastSumMulTo)); print_nl();
|
http://rosettacode.org/wiki/Sum_digits_of_an_integer | Sum digits of an integer | Task
Take a Natural Number in a given base and return the sum of its digits:
110 sums to 1
123410 sums to 10
fe16 sums to 29
f0e16 sums to 29
| #Cowgol | Cowgol | include "cowgol.coh";
sub digitSum(n: uint32, base: uint32): (r: uint32) is
r := 0;
while n > 0 loop
r := r + n % base;
n := n / base;
end loop;
end sub;
print_i32(digitSum(1, 10)); # prints 1
print_nl();
print_i32(digitSum(1234, 10)); # prints 10
print_nl();
print_i32(digitSum(0xFE, 16)); # prints 29
print_nl();
print_i32(digitSum(0xF0E, 16)); # prints 29
print_nl(); |
http://rosettacode.org/wiki/Sum_of_squares | Sum of squares | Task
Write a program to find the sum of squares of a numeric vector.
The program should work on a zero-length vector (with an answer of 0).
Related task
Mean
| #Draco | Draco | proc nonrec sum_squares([*] int arr) ulong:
ulong sum, item;
word i, len;
sum := 0;
len := dim(arr,1);
if len>0 then
for i from 0 upto len-1 do
item := |arr[i];
sum := sum + item * item
od
fi;
sum
corp
proc nonrec main() void:
type A0 = [0] int,
A1 = [1] int,
A5 = [5] int;
writeln(sum_squares(A0()));
writeln(sum_squares(A1(42)));
writeln(sum_squares(A5(1,2,3,4,5)))
corp |
http://rosettacode.org/wiki/Sum_of_squares | Sum of squares | Task
Write a program to find the sum of squares of a numeric vector.
The program should work on a zero-length vector (with an answer of 0).
Related task
Mean
| #E | E | def sumOfSquares(numbers) {
var sum := 0
for x in numbers {
sum += x**2
}
return sum
} |
http://rosettacode.org/wiki/Successive_prime_differences | Successive prime differences | The series of increasing prime numbers begins: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, ...
The task applies a filter to the series returning groups of successive primes, (s'primes), that differ from the next by a given value or values.
Example 1: Specifying that the difference between s'primes be 2 leads to the groups:
(3, 5), (5, 7), (11, 13), (17, 19), (29, 31), ...
(Known as Twin primes or Prime pairs)
Example 2: Specifying more than one difference between s'primes leads to groups of size one greater than the number of differences. Differences of 2, 4 leads to the groups:
(5, 7, 11), (11, 13, 17), (17, 19, 23), (41, 43, 47), ....
In the first group 7 is two more than 5 and 11 is four more than 7; as well as 5, 7, and 11 being successive primes.
Differences are checked in the order of the values given, (differences of 4, 2 would give different groups entirely).
Task
In each case use a list of primes less than 1_000_000
For the following Differences show the first and last group, as well as the number of groups found:
Differences of 2.
Differences of 1.
Differences of 2, 2.
Differences of 2, 4.
Differences of 4, 2.
Differences of 6, 4, 2.
Show output here.
Note: Generation of a list of primes is a secondary aspect of the task. Use of a built in function, well known library, or importing/use of prime generators from other Rosetta Code tasks is encouraged.
references
https://pdfs.semanticscholar.org/78a1/7349819304863ae061df88dbcb26b4908f03.pdf
https://www.primepuzzles.net/puzzles/puzz_011.htm
https://matheplanet.de/matheplanet/nuke/html/viewtopic.php?topic=232720&start=0 | #ALGOL_68 | ALGOL 68 | BEGIN # find some sequences of primes where the gaps between the elements #
# follow specific patterns #
# reurns a list of primes up to n #
PROC prime list = ( INT n )[]INT:
BEGIN
# sieve the primes to n #
INT no = 0, yes = 1;
[ 1 : n ]INT p;
p[ 1 ] := no; p[ 2 ] := yes;
FOR i FROM 3 BY 2 TO n DO p[ i ] := yes OD;
FOR i FROM 4 BY 2 TO n DO p[ i ] := no OD;
FOR i FROM 3 BY 2 TO ENTIER sqrt( n ) DO
IF p[ i ] = yes THEN FOR s FROM i * i BY i + i TO n DO p[ s ] := no OD FI
OD;
# replace the sieve with a list #
INT p pos := 0;
FOR i TO n DO IF p[ i ] = yes THEN p[ p pos +:= 1 ] := i FI OD;
p[ 1 : p pos ]
END # prime list # ;
# prints the elements of list #
PROC print list = ( STRING name, []INT list )VOID:
BEGIN
print( ( name, "[" ) );
FOR i FROM LWB list TO UPB list DO print( ( " ", whole( list[ i ], 0 ) ) ) OD;
print( ( " ]" ) )
END # print list # ;
# attempts to find patterns in the differences of primes and prints the results #
PROC try differences = ( []INT primes, []INT pattern )VOID:
BEGIN
INT pattern length = ( UPB pattern - LWB pattern ) + 1;
[ 1 : pattern length + 1 ]INT first; FOR i TO UPB first DO first[ i ] := 0 OD;
[ 1 : pattern length + 1 ]INT last; FOR i TO UPB last DO last[ i ] := 0 OD;
INT count := 0;
FOR p FROM LWB primes + pattern length TO UPB primes DO
BOOL matched := TRUE;
INT e pos := LWB pattern;
FOR e FROM p - pattern length TO p - 1
WHILE matched := primes[ e + 1 ] - primes[ e ] = pattern[ e pos ]
DO
e pos +:= 1
OD;
IF matched THEN
# found a matching sequence #
count +:= 1;
last := primes[ p - pattern length : p @ 1 ];
IF count = 1 THEN first := last FI
FI
OD;
print( ( " Found ", whole( count, 0 ), " prime sequence(s) that differ by: " ) );
print list( "", pattern );
print( ( newline ) );
IF count > 0 THEN
# found at least one sequence #
print list( " first: ", first );
print list( " last: ", last );
print( ( newline ) )
FI;
print( ( newline ) )
END # try differences # ;
INT max number = 1 000 000;
[]INT p list = prime list( max number );
print( ( "For primes up to ", whole( max number, 0 ), "...", newline ) );
try differences( p list, ( 2 ) );try differences( p list, ( 1 ) );
try differences( p list, ( 2, 2 ) );try differences( p list, ( 2, 4 ) );
try differences( p list, ( 4, 2 ) );try differences( p list, ( 6, 4, 2 ) );
try differences( p list, ( 2, 4, 6, 8 ) );try differences( p list, ( 2, 4, 6, 8, 10 ) );
try differences( p list, ( 32, 16, 8, 4, 2 ) )
END |
http://rosettacode.org/wiki/Substring/Top_and_tail | Substring/Top and tail | The task is to demonstrate how to remove the first and last characters from a string.
The solution should demonstrate how to obtain the following results:
String with first character removed
String with last character removed
String with both the first and last characters removed
If the program uses UTF-8 or UTF-16, it must work on any valid Unicode code point, whether in the Basic Multilingual Plane or above it.
The program must reference logical characters (code points), not 8-bit code units for UTF-8 or 16-bit code units for UTF-16.
Programs for other encodings (such as 8-bit ASCII, or EUC-JP) are not required to handle all Unicode characters.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Aime | Aime | o_text(delete("knights", 0));
o_newline();
o_text(delete("knights", -1));
o_newline();
o_text(delete(delete("knights", 0), -1));
o_newline(); |
http://rosettacode.org/wiki/Subtractive_generator | Subtractive generator | A subtractive generator calculates a sequence of random numbers, where each number is congruent to the subtraction of two previous numbers from the sequence.
The formula is
r
n
=
r
(
n
−
i
)
−
r
(
n
−
j
)
(
mod
m
)
{\displaystyle r_{n}=r_{(n-i)}-r_{(n-j)}{\pmod {m}}}
for some fixed values of
i
{\displaystyle i}
,
j
{\displaystyle j}
and
m
{\displaystyle m}
, all positive integers. Supposing that
i
>
j
{\displaystyle i>j}
, then the state of this generator is the list of the previous numbers from
r
n
−
i
{\displaystyle r_{n-i}}
to
r
n
−
1
{\displaystyle r_{n-1}}
. Many states generate uniform random integers from
0
{\displaystyle 0}
to
m
−
1
{\displaystyle m-1}
, but some states are bad. A state, filled with zeros, generates only zeros. If
m
{\displaystyle m}
is even, then a state, filled with even numbers, generates only even numbers. More generally, if
f
{\displaystyle f}
is a factor of
m
{\displaystyle m}
, then a state, filled with multiples of
f
{\displaystyle f}
, generates only multiples of
f
{\displaystyle f}
.
All subtractive generators have some weaknesses. The formula correlates
r
n
{\displaystyle r_{n}}
,
r
(
n
−
i
)
{\displaystyle r_{(n-i)}}
and
r
(
n
−
j
)
{\displaystyle r_{(n-j)}}
; these three numbers are not independent, as true random numbers would be. Anyone who observes
i
{\displaystyle i}
consecutive numbers can predict the next numbers, so the generator is not cryptographically secure. The authors of Freeciv (utility/rand.c) and xpat2 (src/testit2.c) knew another problem: the low bits are less random than the high bits.
The subtractive generator has a better reputation than the linear congruential generator, perhaps because it holds more state. A subtractive generator might never multiply numbers: this helps where multiplication is slow. A subtractive generator might also avoid division: the value of
r
(
n
−
i
)
−
r
(
n
−
j
)
{\displaystyle r_{(n-i)}-r_{(n-j)}}
is always between
−
m
{\displaystyle -m}
and
m
{\displaystyle m}
, so a program only needs to add
m
{\displaystyle m}
to negative numbers.
The choice of
i
{\displaystyle i}
and
j
{\displaystyle j}
affects the period of the generator. A popular choice is
i
=
55
{\displaystyle i=55}
and
j
=
24
{\displaystyle j=24}
, so the formula is
r
n
=
r
(
n
−
55
)
−
r
(
n
−
24
)
(
mod
m
)
{\displaystyle r_{n}=r_{(n-55)}-r_{(n-24)}{\pmod {m}}}
The subtractive generator from xpat2 uses
r
n
=
r
(
n
−
55
)
−
r
(
n
−
24
)
(
mod
10
9
)
{\displaystyle r_{n}=r_{(n-55)}-r_{(n-24)}{\pmod {10^{9}}}}
The implementation is by J. Bentley and comes from program_tools/universal.c of the DIMACS (netflow) archive at Rutgers University. It credits Knuth, TAOCP, Volume 2, Section 3.2.2 (Algorithm A).
Bentley uses this clever algorithm to seed the generator.
Start with a single
s
e
e
d
{\displaystyle seed}
in range
0
{\displaystyle 0}
to
10
9
−
1
{\displaystyle 10^{9}-1}
.
Set
s
0
=
s
e
e
d
{\displaystyle s_{0}=seed}
and
s
1
=
1
{\displaystyle s_{1}=1}
. The inclusion of
s
1
=
1
{\displaystyle s_{1}=1}
avoids some bad states (like all zeros, or all multiples of 10).
Compute
s
2
,
s
3
,
.
.
.
,
s
54
{\displaystyle s_{2},s_{3},...,s_{54}}
using the subtractive formula
s
n
=
s
(
n
−
2
)
−
s
(
n
−
1
)
(
mod
10
9
)
{\displaystyle s_{n}=s_{(n-2)}-s_{(n-1)}{\pmod {10^{9}}}}
.
Reorder these 55 values so
r
0
=
s
34
{\displaystyle r_{0}=s_{34}}
,
r
1
=
s
13
{\displaystyle r_{1}=s_{13}}
,
r
2
=
s
47
{\displaystyle r_{2}=s_{47}}
, ...,
r
n
=
s
(
34
∗
(
n
+
1
)
(
mod
55
)
)
{\displaystyle r_{n}=s_{(34*(n+1){\pmod {55}})}}
.
This is the same order as
s
0
=
r
54
{\displaystyle s_{0}=r_{54}}
,
s
1
=
r
33
{\displaystyle s_{1}=r_{33}}
,
s
2
=
r
12
{\displaystyle s_{2}=r_{12}}
, ...,
s
n
=
r
(
(
34
∗
n
)
−
1
(
mod
55
)
)
{\displaystyle s_{n}=r_{((34*n)-1{\pmod {55}})}}
.
This rearrangement exploits how 34 and 55 are relatively prime.
Compute the next 165 values
r
55
{\displaystyle r_{55}}
to
r
219
{\displaystyle r_{219}}
. Store the last 55 values.
This generator yields the sequence
r
220
{\displaystyle r_{220}}
,
r
221
{\displaystyle r_{221}}
,
r
222
{\displaystyle r_{222}}
and so on. For example, if the seed is 292929, then the sequence begins with
r
220
=
467478574
{\displaystyle r_{220}=467478574}
,
r
221
=
512932792
{\displaystyle r_{221}=512932792}
,
r
222
=
539453717
{\displaystyle r_{222}=539453717}
. By starting at
r
220
{\displaystyle r_{220}}
, this generator avoids a bias from the first numbers of the sequence. This generator must store the last 55 numbers of the sequence, so to compute the next
r
n
{\displaystyle r_{n}}
. Any array or list would work; a ring buffer is ideal but not necessary.
Implement a subtractive generator that replicates the sequences from xpat2.
| #BBC_BASIC | BBC BASIC | dummy% = FNsubrand(292929)
FOR i% = 1 TO 10
PRINT FNsubrand(0)
NEXT
END
DEF FNsubrand(s%)
PRIVATE r%(), p% : DIM r%(54)
IF s% = 0 THEN
p% = (p% + 1) MOD 55
r%(p%) = r%(p%) - r%((p% + 31) MOD 55)
IF r%(p%) < 0 r%(p%) += 10^9
= r%(p%)
ENDIF
LOCAL i%
r%(54) = s% : r%(33) = 1
p% = 12
FOR i% = 2 TO 54
r%(p%) = r%((p%+42) MOD 55) - r%((p%+21) MOD 55)
IF r%(p%) < 0 r%(p%) += 10^9
p% = (p% + 34) MOD 55
NEXT
FOR i% = 55 TO 219
IF FNsubrand(0)
NEXT
= 0 |
http://rosettacode.org/wiki/Substitution_cipher | Substitution cipher | Substitution Cipher Implementation - File Encryption/Decryption
Task
Encrypt a input/source file by replacing every upper/lower case alphabets of the source file with another predetermined upper/lower case alphabets or symbols and save it into another output/encrypted file and then again convert that output/encrypted file into original/decrypted file.
This type of Encryption/Decryption scheme is often called a Substitution Cipher.
Related tasks
Caesar cipher
Rot-13
Vigenère Cipher/Cryptanalysis
See also
Wikipedia: Substitution cipher
| #Go | Go | package main
import (
"fmt"
"strings"
)
var key = "]kYV}(!7P$n5_0i R:?jOWtF/=-pe'AD&@r6%ZXs\"v*N[#wSl9zq2^+g;LoB`aGh{3.HIu4fbK)mU8|dMET><,Qc\\C1yxJ"
func encode(s string) string {
bs := []byte(s)
for i := 0; i < len(bs); i++ {
bs[i] = key[int(bs[i]) - 32]
}
return string(bs)
}
func decode(s string) string {
bs := []byte(s)
for i := 0; i < len(bs); i++ {
bs[i] = byte(strings.IndexByte(key, bs[i]) + 32)
}
return string(bs)
}
func main() {
s := "The quick brown fox jumps over the lazy dog, who barks VERY loudly!"
enc := encode(s)
fmt.Println("Encoded: ", enc)
fmt.Println("Decoded: ", decode(enc))
} |
http://rosettacode.org/wiki/Sum_and_product_of_an_array | Sum and product of an array | Task
Compute the sum and product of an array of integers.
| #Clojure | Clojure | (defn sum [vals] (reduce + vals))
(defn product [vals] (reduce * vals)) |
http://rosettacode.org/wiki/Sum_and_product_of_an_array | Sum and product of an array | Task
Compute the sum and product of an array of integers.
| #CLU | CLU | sum_and_product = proc (a: array[int]) returns (int,int) signals (overflow)
sum: int := 0
prod: int := 1
for i: int in array[int]$elements(a) do
sum := sum + i
prod := prod * i
end resignal overflow
return(sum, prod)
end sum_and_product
start_up = proc ()
arr: array[int] := array[int]$[1,2,3,4,5,6,7,8,9,10]
sum, prod: int := sum_and_product(arr)
po: stream := stream$primary_output()
stream$putl(po, "Sum = " || int$unparse(sum))
stream$putl(po, "Product = " || int$unparse(prod))
end start_up |
http://rosettacode.org/wiki/Sum_of_a_series | Sum of a series | Compute the nth term of a series, i.e. the sum of the n first terms of the corresponding sequence.
Informally this value, or its limit when n tends to infinity, is also called the sum of the series, thus the title of this task.
For this task, use:
S
n
=
∑
k
=
1
n
1
k
2
{\displaystyle S_{n}=\sum _{k=1}^{n}{\frac {1}{k^{2}}}}
and compute
S
1000
{\displaystyle S_{1000}}
This approximates the zeta function for S=2, whose exact value
ζ
(
2
)
=
π
2
6
{\displaystyle \zeta (2)={\pi ^{2} \over 6}}
is the solution of the Basel problem.
| #Clojure | Clojure | (reduce + (map #(/ 1.0 % %) (range 1 1001))) |
http://rosettacode.org/wiki/Sum_to_100 | Sum to 100 | Task
Find solutions to the sum to one hundred puzzle.
Add (insert) the mathematical
operators + or - (plus
or minus) before any of the digits in the
decimal numeric string 123456789 such that the
resulting mathematical expression adds up to a
particular sum (in this iconic case, 100).
Example:
123 + 4 - 5 + 67 - 89 = 100
Show all output here.
Show all solutions that sum to 100
Show the sum that has the maximum number of solutions (from zero to infinity‡)
Show the lowest positive sum that can't be expressed (has no solutions), using the rules for this task
Show the ten highest numbers that can be expressed using the rules for this task (extra credit)
‡ (where infinity would be a relatively small 123,456,789)
An example of a sum that can't be expressed (within the rules of this task) is: 5074
(which, of course, isn't the lowest positive sum that can't be expressed).
| #FreeBASIC | FreeBASIC |
#define PERM 13122
'Between any two adjacent digits there can be nothing, a plus, or a minus.
'And the first term can only be + or -
'This is equivalent to an eight-digit base 3 number. We therefore only need
'to consider 2*3^8=13122 possibilities
function ndig(n as uinteger) as uinteger
return 1+int(log(n+0.5)/log(10))
end function
function calculate( byval n as uinteger, outstr as string ) as integer
'calculates the sum given by one of the 13122 possibilities, as well as
'storing the equation itself as a string
outstr = "9"
dim as integer ret = 0, curr = 9
dim as boolean firstplus = n>=PERM/2
for i as integer = 8 to 1 step -1
select case n mod 3
case 0 'no symbol means we just prepend the next number
curr += i*10^(ndig(curr))
case 1 'addition: add the current term to the running sum, and clear the current term
ret += curr
curr = i
outstr = " + " + outstr
case 2 'subtraction: minus the current term from the running sum, and clear the current term
ret -= curr
curr = i
outstr = " - " + outstr
end select
outstr = str(i) + outstr 'prepend the previous digit to the string
n \= 3 'get next symbol
next i
if firstplus = 0 then
outstr = "-"+outstr
ret -= curr
else
ret += curr
end if
outstr = outstr + " = " + str(ret)
return ret
end function
'calculate and store all 13122 solutions
dim as string eqn
dim as integer n, sum(0 to PERM-1), curr
for n = 0 to PERM-1
curr = calculate(n, eqn)
sum(n) = curr
if curr = 100 then print eqn
next n
'what is the sum that has the most solutions?
dim as integer champ = 0, cnum = 0, i, j, acc
for i = 0 to PERM-1
acc = 0
for j = i to PERM-1
if sum(j) = sum(i) then acc+=1
next j
if acc>cnum then
champ = sum(i)
cnum=acc
end if
next i
print "The sum with the most occurrences is ";champ;", which shows up ";cnum;" times."
'what is the first nonnegative number that has no solution
for i = 0 to 123456788
for j = 0 to PERM-1
if sum(j)=i then goto nexti
next j
print "The first number that has no solution is ";i
exit for
nexti:
next i
'What are the ten highest numbers?
'this partially destroys the information in the array, but who cares?
'We're almost done and these excessive questionnaires are the worst
'and most boring part of Rosetta Code tasks
print "The ten highest numbers attainable are:"
champ = 0
for i = 1 to 10
for j = 0 to PERM-1
if sum(j)>sum(champ) then champ = j
next j
calculate(champ, eqn)
print eqn
sum(champ) = -9999 'overwrite to stop this being found a second time
next i |
http://rosettacode.org/wiki/Sum_multiples_of_3_and_5 | Sum multiples of 3 and 5 | Task
The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n.
Show output for n = 1000.
This is is the same as Project Euler problem 1.
Extra credit: do this efficiently for n = 1e20 or higher.
| #Crystal | Crystal | def sum_3_5_multiples(n)
(0...n).select { |i| i % 3 == 0 || i % 5 == 0 }.sum
end
puts sum_3_5_multiples(1000) |
http://rosettacode.org/wiki/Sum_digits_of_an_integer | Sum digits of an integer | Task
Take a Natural Number in a given base and return the sum of its digits:
110 sums to 1
123410 sums to 10
fe16 sums to 29
f0e16 sums to 29
| #Crystal | Crystal | class String
def sum_digits(base : Int) : Int32
self.chars.reduce(0) { |acc, c|
value = c.to_i(base)
acc += value
}
end
end
puts("1".sum_digits 10)
puts("1234".sum_digits 10)
puts("fe".sum_digits 16)
puts("f0e".sum_digits 16) |
http://rosettacode.org/wiki/Sum_of_squares | Sum of squares | Task
Write a program to find the sum of squares of a numeric vector.
The program should work on a zero-length vector (with an answer of 0).
Related task
Mean
| #Eiffel | Eiffel |
class
APPLICATION
create
make
feature -- Initialization
make
local
a: ARRAY [INTEGER]
do
a := <<1, -2, 3>>
print ("%NSquare sum of <<1, 2, 3>>: " + sum_of_square (a).out)
a := <<>>
print ("%NSquare sum of <<>>: " + sum_of_square (a).out)
end
feature -- Access
sum_of_square (a: ITERABLE [INTEGER]): NATURAL
-- sum of square of each items
do
Result := 0
across a as it loop
Result := Result + (it.item * it.item).as_natural_32
end
end
end
|
http://rosettacode.org/wiki/Successive_prime_differences | Successive prime differences | The series of increasing prime numbers begins: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, ...
The task applies a filter to the series returning groups of successive primes, (s'primes), that differ from the next by a given value or values.
Example 1: Specifying that the difference between s'primes be 2 leads to the groups:
(3, 5), (5, 7), (11, 13), (17, 19), (29, 31), ...
(Known as Twin primes or Prime pairs)
Example 2: Specifying more than one difference between s'primes leads to groups of size one greater than the number of differences. Differences of 2, 4 leads to the groups:
(5, 7, 11), (11, 13, 17), (17, 19, 23), (41, 43, 47), ....
In the first group 7 is two more than 5 and 11 is four more than 7; as well as 5, 7, and 11 being successive primes.
Differences are checked in the order of the values given, (differences of 4, 2 would give different groups entirely).
Task
In each case use a list of primes less than 1_000_000
For the following Differences show the first and last group, as well as the number of groups found:
Differences of 2.
Differences of 1.
Differences of 2, 2.
Differences of 2, 4.
Differences of 4, 2.
Differences of 6, 4, 2.
Show output here.
Note: Generation of a list of primes is a secondary aspect of the task. Use of a built in function, well known library, or importing/use of prime generators from other Rosetta Code tasks is encouraged.
references
https://pdfs.semanticscholar.org/78a1/7349819304863ae061df88dbcb26b4908f03.pdf
https://www.primepuzzles.net/puzzles/puzz_011.htm
https://matheplanet.de/matheplanet/nuke/html/viewtopic.php?topic=232720&start=0 | #Arturo | Arturo | LIM: 1000000
findDiffs: function [r][
if r=[1] -> return [[2 3]]
i: 3
tupled: map 0..dec size r 'x -> fold slice r 0 x [a b][a+b]
diffs: new []
while [i < LIM][
if prime? i [
prset: map tupled 't -> i + t
if every? prset 'elem -> prime? elem [
'diffs ++ @[@[i] ++ prset]
]
]
i: i + 2
]
diffs: filter diffs 'dd [
some? range (first dd)+1 (last dd)-1 'x -> and? [prime? x][not? contains? dd x]
]
return diffs
]
loop [[2] [1] [2 2] [2 4] [4 2] [6 4 2]] 'rng [
print ["Differences of" join.with:", " to [:string] rng]
diffs: findDiffs rng
print ["\tFirst: " join.with:" " to [:string] first diffs]
print ["\tLast: " join.with:" " to [:string] last diffs]
print ["\tCount: " size diffs]
] |
http://rosettacode.org/wiki/Substring/Top_and_tail | Substring/Top and tail | The task is to demonstrate how to remove the first and last characters from a string.
The solution should demonstrate how to obtain the following results:
String with first character removed
String with last character removed
String with both the first and last characters removed
If the program uses UTF-8 or UTF-16, it must work on any valid Unicode code point, whether in the Basic Multilingual Plane or above it.
The program must reference logical characters (code points), not 8-bit code units for UTF-8 or 16-bit code units for UTF-16.
Programs for other encodings (such as 8-bit ASCII, or EUC-JP) are not required to handle all Unicode characters.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #ALGOL_68 | ALGOL 68 | #!/usr/local/bin/a68g --script #
STRING str="upraisers";
printf(($gl$,
str, # remove no characters #
str[LWB str+1: ], # remove the first character #
str[ :UPB str-1], # remove the last character #
str[LWB str+1:UPB str-1], # remove both the first and last character #
str[LWB str+2: ], # remove the first 2 characters #
str[ :UPB str-2], # remove the last 2 characters #
str[LWB str+1:UPB str-2], # remove 1 before and 2 after #
str[LWB str+2:UPB str-1], # remove 2 before and one after #
str[LWB str+2:UPB str-2] # remove both the first and last 2 characters #
)) |
http://rosettacode.org/wiki/Subtractive_generator | Subtractive generator | A subtractive generator calculates a sequence of random numbers, where each number is congruent to the subtraction of two previous numbers from the sequence.
The formula is
r
n
=
r
(
n
−
i
)
−
r
(
n
−
j
)
(
mod
m
)
{\displaystyle r_{n}=r_{(n-i)}-r_{(n-j)}{\pmod {m}}}
for some fixed values of
i
{\displaystyle i}
,
j
{\displaystyle j}
and
m
{\displaystyle m}
, all positive integers. Supposing that
i
>
j
{\displaystyle i>j}
, then the state of this generator is the list of the previous numbers from
r
n
−
i
{\displaystyle r_{n-i}}
to
r
n
−
1
{\displaystyle r_{n-1}}
. Many states generate uniform random integers from
0
{\displaystyle 0}
to
m
−
1
{\displaystyle m-1}
, but some states are bad. A state, filled with zeros, generates only zeros. If
m
{\displaystyle m}
is even, then a state, filled with even numbers, generates only even numbers. More generally, if
f
{\displaystyle f}
is a factor of
m
{\displaystyle m}
, then a state, filled with multiples of
f
{\displaystyle f}
, generates only multiples of
f
{\displaystyle f}
.
All subtractive generators have some weaknesses. The formula correlates
r
n
{\displaystyle r_{n}}
,
r
(
n
−
i
)
{\displaystyle r_{(n-i)}}
and
r
(
n
−
j
)
{\displaystyle r_{(n-j)}}
; these three numbers are not independent, as true random numbers would be. Anyone who observes
i
{\displaystyle i}
consecutive numbers can predict the next numbers, so the generator is not cryptographically secure. The authors of Freeciv (utility/rand.c) and xpat2 (src/testit2.c) knew another problem: the low bits are less random than the high bits.
The subtractive generator has a better reputation than the linear congruential generator, perhaps because it holds more state. A subtractive generator might never multiply numbers: this helps where multiplication is slow. A subtractive generator might also avoid division: the value of
r
(
n
−
i
)
−
r
(
n
−
j
)
{\displaystyle r_{(n-i)}-r_{(n-j)}}
is always between
−
m
{\displaystyle -m}
and
m
{\displaystyle m}
, so a program only needs to add
m
{\displaystyle m}
to negative numbers.
The choice of
i
{\displaystyle i}
and
j
{\displaystyle j}
affects the period of the generator. A popular choice is
i
=
55
{\displaystyle i=55}
and
j
=
24
{\displaystyle j=24}
, so the formula is
r
n
=
r
(
n
−
55
)
−
r
(
n
−
24
)
(
mod
m
)
{\displaystyle r_{n}=r_{(n-55)}-r_{(n-24)}{\pmod {m}}}
The subtractive generator from xpat2 uses
r
n
=
r
(
n
−
55
)
−
r
(
n
−
24
)
(
mod
10
9
)
{\displaystyle r_{n}=r_{(n-55)}-r_{(n-24)}{\pmod {10^{9}}}}
The implementation is by J. Bentley and comes from program_tools/universal.c of the DIMACS (netflow) archive at Rutgers University. It credits Knuth, TAOCP, Volume 2, Section 3.2.2 (Algorithm A).
Bentley uses this clever algorithm to seed the generator.
Start with a single
s
e
e
d
{\displaystyle seed}
in range
0
{\displaystyle 0}
to
10
9
−
1
{\displaystyle 10^{9}-1}
.
Set
s
0
=
s
e
e
d
{\displaystyle s_{0}=seed}
and
s
1
=
1
{\displaystyle s_{1}=1}
. The inclusion of
s
1
=
1
{\displaystyle s_{1}=1}
avoids some bad states (like all zeros, or all multiples of 10).
Compute
s
2
,
s
3
,
.
.
.
,
s
54
{\displaystyle s_{2},s_{3},...,s_{54}}
using the subtractive formula
s
n
=
s
(
n
−
2
)
−
s
(
n
−
1
)
(
mod
10
9
)
{\displaystyle s_{n}=s_{(n-2)}-s_{(n-1)}{\pmod {10^{9}}}}
.
Reorder these 55 values so
r
0
=
s
34
{\displaystyle r_{0}=s_{34}}
,
r
1
=
s
13
{\displaystyle r_{1}=s_{13}}
,
r
2
=
s
47
{\displaystyle r_{2}=s_{47}}
, ...,
r
n
=
s
(
34
∗
(
n
+
1
)
(
mod
55
)
)
{\displaystyle r_{n}=s_{(34*(n+1){\pmod {55}})}}
.
This is the same order as
s
0
=
r
54
{\displaystyle s_{0}=r_{54}}
,
s
1
=
r
33
{\displaystyle s_{1}=r_{33}}
,
s
2
=
r
12
{\displaystyle s_{2}=r_{12}}
, ...,
s
n
=
r
(
(
34
∗
n
)
−
1
(
mod
55
)
)
{\displaystyle s_{n}=r_{((34*n)-1{\pmod {55}})}}
.
This rearrangement exploits how 34 and 55 are relatively prime.
Compute the next 165 values
r
55
{\displaystyle r_{55}}
to
r
219
{\displaystyle r_{219}}
. Store the last 55 values.
This generator yields the sequence
r
220
{\displaystyle r_{220}}
,
r
221
{\displaystyle r_{221}}
,
r
222
{\displaystyle r_{222}}
and so on. For example, if the seed is 292929, then the sequence begins with
r
220
=
467478574
{\displaystyle r_{220}=467478574}
,
r
221
=
512932792
{\displaystyle r_{221}=512932792}
,
r
222
=
539453717
{\displaystyle r_{222}=539453717}
. By starting at
r
220
{\displaystyle r_{220}}
, this generator avoids a bias from the first numbers of the sequence. This generator must store the last 55 numbers of the sequence, so to compute the next
r
n
{\displaystyle r_{n}}
. Any array or list would work; a ring buffer is ideal but not necessary.
Implement a subtractive generator that replicates the sequences from xpat2.
| #Bracmat | Bracmat | 1000000000:?MOD;
tbl$(state,55);
0:?si:?sj;
(subrand-seed=
i,j,p2
. 1:?p2
& mod$(!arg,!MOD):?(0$?state)
& 1:?i
& 21:?j
& whl
' ( !i:<55
& (!j:~<55&!j+-55:?j|)
& !p2:?(!j$?state)
& ( !arg+-1*!p2:?p2:<0
& !p2+!MOD:?p2
|
)
& !(!j$state):?arg
& !i+1:?i
& !j+21:?j
)
& 0:?s1:?i
& 24:?sj
& whl
' ( !i:<165
& subrand$
& !i+1:?i
));
(subrand=
x
. (!si:!sj&subrand-seed$0|)
& (!si:>0&!si+-1|54):?si
& (!sj:>0&!sj+-1|54):?sj
& ( !(!si$state)+-1*!(!sj$state):?x:<0
& !x+!MOD:?x
|
)
& !x:?(!si$?state));
(Main=
i
. subrand-seed$292929
& 0:?i
& whl
' ( !i:<10
& out$(subrand$)
& !i+1:?i
));
Main$; |
http://rosettacode.org/wiki/Subtractive_generator | Subtractive generator | A subtractive generator calculates a sequence of random numbers, where each number is congruent to the subtraction of two previous numbers from the sequence.
The formula is
r
n
=
r
(
n
−
i
)
−
r
(
n
−
j
)
(
mod
m
)
{\displaystyle r_{n}=r_{(n-i)}-r_{(n-j)}{\pmod {m}}}
for some fixed values of
i
{\displaystyle i}
,
j
{\displaystyle j}
and
m
{\displaystyle m}
, all positive integers. Supposing that
i
>
j
{\displaystyle i>j}
, then the state of this generator is the list of the previous numbers from
r
n
−
i
{\displaystyle r_{n-i}}
to
r
n
−
1
{\displaystyle r_{n-1}}
. Many states generate uniform random integers from
0
{\displaystyle 0}
to
m
−
1
{\displaystyle m-1}
, but some states are bad. A state, filled with zeros, generates only zeros. If
m
{\displaystyle m}
is even, then a state, filled with even numbers, generates only even numbers. More generally, if
f
{\displaystyle f}
is a factor of
m
{\displaystyle m}
, then a state, filled with multiples of
f
{\displaystyle f}
, generates only multiples of
f
{\displaystyle f}
.
All subtractive generators have some weaknesses. The formula correlates
r
n
{\displaystyle r_{n}}
,
r
(
n
−
i
)
{\displaystyle r_{(n-i)}}
and
r
(
n
−
j
)
{\displaystyle r_{(n-j)}}
; these three numbers are not independent, as true random numbers would be. Anyone who observes
i
{\displaystyle i}
consecutive numbers can predict the next numbers, so the generator is not cryptographically secure. The authors of Freeciv (utility/rand.c) and xpat2 (src/testit2.c) knew another problem: the low bits are less random than the high bits.
The subtractive generator has a better reputation than the linear congruential generator, perhaps because it holds more state. A subtractive generator might never multiply numbers: this helps where multiplication is slow. A subtractive generator might also avoid division: the value of
r
(
n
−
i
)
−
r
(
n
−
j
)
{\displaystyle r_{(n-i)}-r_{(n-j)}}
is always between
−
m
{\displaystyle -m}
and
m
{\displaystyle m}
, so a program only needs to add
m
{\displaystyle m}
to negative numbers.
The choice of
i
{\displaystyle i}
and
j
{\displaystyle j}
affects the period of the generator. A popular choice is
i
=
55
{\displaystyle i=55}
and
j
=
24
{\displaystyle j=24}
, so the formula is
r
n
=
r
(
n
−
55
)
−
r
(
n
−
24
)
(
mod
m
)
{\displaystyle r_{n}=r_{(n-55)}-r_{(n-24)}{\pmod {m}}}
The subtractive generator from xpat2 uses
r
n
=
r
(
n
−
55
)
−
r
(
n
−
24
)
(
mod
10
9
)
{\displaystyle r_{n}=r_{(n-55)}-r_{(n-24)}{\pmod {10^{9}}}}
The implementation is by J. Bentley and comes from program_tools/universal.c of the DIMACS (netflow) archive at Rutgers University. It credits Knuth, TAOCP, Volume 2, Section 3.2.2 (Algorithm A).
Bentley uses this clever algorithm to seed the generator.
Start with a single
s
e
e
d
{\displaystyle seed}
in range
0
{\displaystyle 0}
to
10
9
−
1
{\displaystyle 10^{9}-1}
.
Set
s
0
=
s
e
e
d
{\displaystyle s_{0}=seed}
and
s
1
=
1
{\displaystyle s_{1}=1}
. The inclusion of
s
1
=
1
{\displaystyle s_{1}=1}
avoids some bad states (like all zeros, or all multiples of 10).
Compute
s
2
,
s
3
,
.
.
.
,
s
54
{\displaystyle s_{2},s_{3},...,s_{54}}
using the subtractive formula
s
n
=
s
(
n
−
2
)
−
s
(
n
−
1
)
(
mod
10
9
)
{\displaystyle s_{n}=s_{(n-2)}-s_{(n-1)}{\pmod {10^{9}}}}
.
Reorder these 55 values so
r
0
=
s
34
{\displaystyle r_{0}=s_{34}}
,
r
1
=
s
13
{\displaystyle r_{1}=s_{13}}
,
r
2
=
s
47
{\displaystyle r_{2}=s_{47}}
, ...,
r
n
=
s
(
34
∗
(
n
+
1
)
(
mod
55
)
)
{\displaystyle r_{n}=s_{(34*(n+1){\pmod {55}})}}
.
This is the same order as
s
0
=
r
54
{\displaystyle s_{0}=r_{54}}
,
s
1
=
r
33
{\displaystyle s_{1}=r_{33}}
,
s
2
=
r
12
{\displaystyle s_{2}=r_{12}}
, ...,
s
n
=
r
(
(
34
∗
n
)
−
1
(
mod
55
)
)
{\displaystyle s_{n}=r_{((34*n)-1{\pmod {55}})}}
.
This rearrangement exploits how 34 and 55 are relatively prime.
Compute the next 165 values
r
55
{\displaystyle r_{55}}
to
r
219
{\displaystyle r_{219}}
. Store the last 55 values.
This generator yields the sequence
r
220
{\displaystyle r_{220}}
,
r
221
{\displaystyle r_{221}}
,
r
222
{\displaystyle r_{222}}
and so on. For example, if the seed is 292929, then the sequence begins with
r
220
=
467478574
{\displaystyle r_{220}=467478574}
,
r
221
=
512932792
{\displaystyle r_{221}=512932792}
,
r
222
=
539453717
{\displaystyle r_{222}=539453717}
. By starting at
r
220
{\displaystyle r_{220}}
, this generator avoids a bias from the first numbers of the sequence. This generator must store the last 55 numbers of the sequence, so to compute the next
r
n
{\displaystyle r_{n}}
. Any array or list would work; a ring buffer is ideal but not necessary.
Implement a subtractive generator that replicates the sequences from xpat2.
| #C | C | #include<stdio.h>
#define MOD 1000000000
int state[55], si = 0, sj = 0;
int subrand();
void subrand_seed(int p1)
{
int i, j, p2 = 1;
state[0] = p1 % MOD;
for (i = 1, j = 21; i < 55; i++, j += 21) {
if (j >= 55) j -= 55;
state[j] = p2;
if ((p2 = p1 - p2) < 0) p2 += MOD;
p1 = state[j];
}
si = 0;
sj = 24;
for (i = 0; i < 165; i++) subrand();
}
int subrand()
{
int x;
if (si == sj) subrand_seed(0);
if (!si--) si = 54;
if (!sj--) sj = 54;
if ((x = state[si] - state[sj]) < 0) x += MOD;
return state[si] = x;
}
int main()
{
subrand_seed(292929);
int i;
for (i = 0; i < 10; i++) printf("%d\n", subrand());
return 0;
} |
http://rosettacode.org/wiki/Substitution_cipher | Substitution cipher | Substitution Cipher Implementation - File Encryption/Decryption
Task
Encrypt a input/source file by replacing every upper/lower case alphabets of the source file with another predetermined upper/lower case alphabets or symbols and save it into another output/encrypted file and then again convert that output/encrypted file into original/decrypted file.
This type of Encryption/Decryption scheme is often called a Substitution Cipher.
Related tasks
Caesar cipher
Rot-13
Vigenère Cipher/Cryptanalysis
See also
Wikipedia: Substitution cipher
| #IS-BASIC | IS-BASIC | 100 PROGRAM "SuChiper.bas"
110 STRING ST$(1 TO 2)*52,K$*1
120 LET ST$(1)="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
130 LET ST$(2)="VsciBjedgrzyHalvXZKtUPumGfIwJxqOCFRApnDhQWobLkESYMTN"
140 CLEAR SCREEN:PRINT "1 - encode, 2 - decode"
150 DO
160 LET K$=INKEY$
170 LOOP UNTIL K$="1" OR K$="2"
180 IF K$="1" THEN
190 INPUT PROMPT "File name: ":NAME$
200 IF OPENFILE(NAME$) THEN CALL CHIPER(1)
210 ELSE
220 IF OPENFILE("Encrypte.txt") THEN CALL CHIPER(2)
230 END IF
240 DEF OPENFILE(N$)
250 LET OPENFILE=0
260 WHEN EXCEPTION USE OPENERROR
270 OPEN #1:N$
280 END WHEN
290 LET OPENFILE=-1
300 END DEF
310 DEF CHIPER(FUNC)
320 LET EOF=0
330 WHEN EXCEPTION USE OPENERROR
340 IF FUNC=1 THEN
350 OPEN #2:"Encrypte.txt" ACCESS OUTPUT
360 LET OUTP=2
370 ELSE
380 OPEN #2:"Decrypte.txt" ACCESS OUTPUT
390 LET OUTP=1
400 END IF
410 END WHEN
420 WHEN EXCEPTION USE IOERROR
430 DO
440 GET #1:K$
450 IF UCASE$(K$)>="A" AND UCASE$(K$)<="Z" THEN
460 PRINT #2:ST$(OUTP)(POS(ST$(FUNC),K$));
470 ELSE
480 PRINT #2:K$;
490 END IF
500 LOOP UNTIL EOF
510 END WHEN
520 HANDLER IOERROR
530 IF EXTYPE<>9228 THEN PRINT EXSTRING$(EXTYPE)
540 CLOSE #2
550 CLOSE #1
560 LET EOF=1
570 END HANDLER
580 END DEF
590 HANDLER OPENERROR
600 PRINT EXSTRING$(EXTYPE)
610 END
620 END HANDLER |
http://rosettacode.org/wiki/Substitution_cipher | Substitution cipher | Substitution Cipher Implementation - File Encryption/Decryption
Task
Encrypt a input/source file by replacing every upper/lower case alphabets of the source file with another predetermined upper/lower case alphabets or symbols and save it into another output/encrypted file and then again convert that output/encrypted file into original/decrypted file.
This type of Encryption/Decryption scheme is often called a Substitution Cipher.
Related tasks
Caesar cipher
Rot-13
Vigenère Cipher/Cryptanalysis
See also
Wikipedia: Substitution cipher
| #Haskell | Haskell | import Data.Char (chr)
import Data.Maybe (fromMaybe)
import Data.Tuple (swap)
import System.Environment (getArgs)
data Command = Cipher String | Decipher String | Invalid
alphabet :: String
alphabet = chr <$> [32..126]
cipherMap :: [(Char, Char)]
cipherMap = zip alphabet (shuffle 20 alphabet)
shuffle :: Int -> [a] -> [a]
shuffle n xs = iterate go xs !! n
where
go [] = []
go xs = go (drop 2 xs) <> take 2 xs
convert :: Eq a => [(a, a)] -> [a] -> [a]
convert m = map (\x -> fromMaybe x (lookup x m))
runCommand :: Command -> String
runCommand (Cipher s) = convert cipherMap s
runCommand (Decipher s) = convert (swap <$> cipherMap) s
runCommand Invalid = "Invalid arguments. Usage: simplecipher c|d <text>"
parseArgs :: [String] -> Command
parseArgs (x:y:xs)
| x == "c" = Cipher y
| x == "d" = Decipher y
| otherwise = Invalid
parseArgs _ = Invalid
main :: IO ()
main = parseArgs <$> getArgs >>= putStrLn . runCommand |
http://rosettacode.org/wiki/Sum_and_product_of_an_array | Sum and product of an array | Task
Compute the sum and product of an array of integers.
| #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. array-sum-and-product.
DATA DIVISION.
WORKING-STORAGE SECTION.
78 Array-Size VALUE 10.
01 array-area VALUE "01020304050607080910".
03 array PIC 99 OCCURS Array-Size TIMES.
01 array-sum PIC 9(8).
01 array-product PIC 9(10) VALUE 1.
01 i PIC 99.
PROCEDURE DIVISION.
PERFORM VARYING i FROM 1 BY 1 UNTIL Array-Size < i
ADD array (i) TO array-sum
MULTIPLY array (i) BY array-product
END-PERFORM
DISPLAY "Sum: " array-sum
DISPLAY "Product: " array-product
GOBACK
. |
http://rosettacode.org/wiki/Sum_of_a_series | Sum of a series | Compute the nth term of a series, i.e. the sum of the n first terms of the corresponding sequence.
Informally this value, or its limit when n tends to infinity, is also called the sum of the series, thus the title of this task.
For this task, use:
S
n
=
∑
k
=
1
n
1
k
2
{\displaystyle S_{n}=\sum _{k=1}^{n}{\frac {1}{k^{2}}}}
and compute
S
1000
{\displaystyle S_{1000}}
This approximates the zeta function for S=2, whose exact value
ζ
(
2
)
=
π
2
6
{\displaystyle \zeta (2)={\pi ^{2} \over 6}}
is the solution of the Basel problem.
| #CLU | CLU | series_sum = proc (from, to: int,
fn: proctype (real) returns (real))
returns (real)
sum: real := 0.0
for i: int in int$from_to(from, to) do
sum := sum + fn(real$i2r(i))
end
return(sum)
end series_sum
one_over_k_squared = proc (k: real) returns (real)
return(1.0 / (k * k))
end one_over_k_squared
start_up = proc ()
po: stream := stream$primary_output()
result: real := series_sum(1, 1000, one_over_k_squared)
stream$putl(po, f_form(result, 1, 6))
end start_up |
http://rosettacode.org/wiki/Sum_to_100 | Sum to 100 | Task
Find solutions to the sum to one hundred puzzle.
Add (insert) the mathematical
operators + or - (plus
or minus) before any of the digits in the
decimal numeric string 123456789 such that the
resulting mathematical expression adds up to a
particular sum (in this iconic case, 100).
Example:
123 + 4 - 5 + 67 - 89 = 100
Show all output here.
Show all solutions that sum to 100
Show the sum that has the maximum number of solutions (from zero to infinity‡)
Show the lowest positive sum that can't be expressed (has no solutions), using the rules for this task
Show the ten highest numbers that can be expressed using the rules for this task (extra credit)
‡ (where infinity would be a relatively small 123,456,789)
An example of a sum that can't be expressed (within the rules of this task) is: 5074
(which, of course, isn't the lowest positive sum that can't be expressed).
| #Frink | Frink |
digits = array[1 to 9]
opList = makeArray[[8], ["", " + ", " - "]]
opList.pushFirst[["", "-"]]
countDict = new dict
multifor ops = opList
{
str = ""
for d = rangeOf[digits]
str = str + ops@d + digits@d
e = eval[str]
countDict.increment[e, 1]
if e == 100
println[str]
}
println[]
// Find the sum that has the maximum number of solutions
freq = toArray[countDict]
sort[freq, {|a,b| -(a@1 <=> b@1)}]
max = freq@0@1
print["Maximum count is $max at: "]
n = 0
while freq@n@1 == max
{
print[freq@n@0 + " "]
n = n + 1
}
println[]
// Find the smallest non-representable positive sum
sort[freq, {|a,b| a@0 <=> b@0}]
last = 0
for [num, count] = freq
{
if num > 0 and last+1 != num
{
println["Lowest non-representable positive sum is " + (last+1)]
break
}
last = num
}
// Find highest 10 representable numbers
println["\nHighest representable numbers:"]
size = length[freq]
for i = size-10 to size-1
println[freq@i@0]
|
http://rosettacode.org/wiki/Sum_multiples_of_3_and_5 | Sum multiples of 3 and 5 | Task
The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n.
Show output for n = 1000.
This is is the same as Project Euler problem 1.
Extra credit: do this efficiently for n = 1e20 or higher.
| #D | D | import std.stdio, std.bigint;
BigInt sum35(in BigInt n) pure nothrow {
static BigInt sumMul(in BigInt n, in int f) pure nothrow {
immutable n1 = (f==n?n:(n - 1) ) / f;
return f * n1 * (n1 + 1) / 2;
}
return sumMul(n, 3) + sumMul(n, 5) - sumMul(n, 15);
}
void main() {
1.BigInt.sum35.writeln;
3.BigInt.sum35.writeln;
5.BigInt.sum35.writeln;
1000.BigInt.sum35.writeln;
(10.BigInt ^^ 20).sum35.writeln;
} |
http://rosettacode.org/wiki/Sum_digits_of_an_integer | Sum digits of an integer | Task
Take a Natural Number in a given base and return the sum of its digits:
110 sums to 1
123410 sums to 10
fe16 sums to 29
f0e16 sums to 29
| #D | D | import std.stdio, std.bigint;
uint sumDigits(T)(T n, in uint base=10) pure nothrow
in {
assert(base > 1);
} body {
typeof(return) total = 0;
for ( ; n; n /= base)
total += n % base;
return total;
}
void main() {
1.sumDigits.writeln;
1_234.sumDigits.writeln;
sumDigits(0xfe, 16).writeln;
sumDigits(0xf0e, 16).writeln;
1_234.BigInt.sumDigits.writeln;
} |
http://rosettacode.org/wiki/Sum_of_squares | Sum of squares | Task
Write a program to find the sum of squares of a numeric vector.
The program should work on a zero-length vector (with an answer of 0).
Related task
Mean
| #Elena | Elena | import system'routines;
import extensions;
SumOfSquares(list)
= list.selectBy:(x => x * x).summarize(new Integer());
public program()
{
console
.printLine(SumOfSquares(new int[]{4, 8, 15, 16, 23, 42}))
.printLine(SumOfSquares(new int[]{1, 2, 3, 4, 5}))
.printLine(SumOfSquares(Array.MinValue))
} |
http://rosettacode.org/wiki/Sum_of_squares | Sum of squares | Task
Write a program to find the sum of squares of a numeric vector.
The program should work on a zero-length vector (with an answer of 0).
Related task
Mean
| #Elixir | Elixir | iex(1)> Enum.reduce([3,1,4,1,5,9], 0, fn x,sum -> sum + x*x end)
133 |
http://rosettacode.org/wiki/Sudoku | Sudoku | Task
Solve a partially filled-in normal 9x9 Sudoku grid and display the result in a human-readable format.
references
Algorithmics of Sudoku may help implement this.
Python Sudoku Solver Computerphile video.
| #11l | 11l | T Sudoku
solved = 0B
grid = [0] * 81
F (rows)
assert(rows.len == 9 & all(rows.map(row -> row.len == 9)), ‘Grid must be 9 x 9’)
L(i) 9
L(j) 9
.grid[9 * i + j] = Int(rows[i][j])
F solve()
print("Starting grid:\n\n"(.))
.placeNumber(0)
print(I .solved {"Solution:\n\n"(.)} E ‘Unsolvable!’)
F placeNumber(pos)
I .solved
R
I pos == 81
.solved = 1B
R
I .grid[pos] > 0
.placeNumber(pos + 1)
R
L(n) 1..9
I .checkValidity(n, pos % 9, pos I/ 9)
.grid[pos] = n
.placeNumber(pos + 1)
I .solved
R
.grid[pos] = 0
F checkValidity(v, x, y)
L(i) 9
I .grid[y * 9 + i] == v |
.grid[i * 9 + x] == v
R 0B
V startX = (x I/ 3) * 3
V startY = (y I/ 3) * 3
L(i) startY .< startY + 3
L(j) startX .< startX + 3
I .grid[i * 9 + j] == v
R 0B
R 1B
F String()
V s = ‘’
L(i) 9
L(j) 9
s ‘’= .grid[i * 9 + j]‘ ’
I j C (2, 5)
s ‘’= ‘| ’
s ‘’= "\n"
I i C (2, 5)
s ‘’= "------+-------+------\n"
R s
V rows = [‘850002400’,
‘720000009’,
‘004000000’,
‘000107002’,
‘305000900’,
‘040000000’,
‘000080070’,
‘017000000’,
‘000036040’]
Sudoku(rows).solve() |
http://rosettacode.org/wiki/Successive_prime_differences | Successive prime differences | The series of increasing prime numbers begins: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, ...
The task applies a filter to the series returning groups of successive primes, (s'primes), that differ from the next by a given value or values.
Example 1: Specifying that the difference between s'primes be 2 leads to the groups:
(3, 5), (5, 7), (11, 13), (17, 19), (29, 31), ...
(Known as Twin primes or Prime pairs)
Example 2: Specifying more than one difference between s'primes leads to groups of size one greater than the number of differences. Differences of 2, 4 leads to the groups:
(5, 7, 11), (11, 13, 17), (17, 19, 23), (41, 43, 47), ....
In the first group 7 is two more than 5 and 11 is four more than 7; as well as 5, 7, and 11 being successive primes.
Differences are checked in the order of the values given, (differences of 4, 2 would give different groups entirely).
Task
In each case use a list of primes less than 1_000_000
For the following Differences show the first and last group, as well as the number of groups found:
Differences of 2.
Differences of 1.
Differences of 2, 2.
Differences of 2, 4.
Differences of 4, 2.
Differences of 6, 4, 2.
Show output here.
Note: Generation of a list of primes is a secondary aspect of the task. Use of a built in function, well known library, or importing/use of prime generators from other Rosetta Code tasks is encouraged.
references
https://pdfs.semanticscholar.org/78a1/7349819304863ae061df88dbcb26b4908f03.pdf
https://www.primepuzzles.net/puzzles/puzz_011.htm
https://matheplanet.de/matheplanet/nuke/html/viewtopic.php?topic=232720&start=0 | #AWK | AWK |
# syntax: GAWK -f SUCCESSIVE_PRIME_DIFFERENCES.AWK
BEGIN {
for (i=lo=0; i<=hi=1000000; i++) {
if (is_prime(i)) {
p_arr[++p] = i
}
}
printf("there are %d primes between %d - %d\n",p,lo,hi)
fmt = "%-11s %5s %-15s %s\n"
printf(fmt,"differences","count","first group","last group")
for (a=1; a<=split("2;1;2,2;2,4;4,2;6,4,2;2,4,6;100;112",diff_arr,";"); a++) {
diff_leng = split(diff_arr[a],tmp_arr,",")
first_set = last_set = ""
count = 0
for (b=1; b<=p; b++) {
str = ""
for (c=1; c<=diff_leng; c++) {
if (p_arr[b+c-1] + tmp_arr[c] == p_arr[b+c]) {
str = (str == "") ? (p_arr[b+c-1] "," p_arr[b+c]) : (str "," p_arr[b+c])
}
}
if (gsub(/,/,"&",str) == diff_leng) {
count++
if (first_set == "") {
first_set = str
}
last_set = str
}
}
printf(fmt,diff_arr[a],count,first_set,last_set)
}
exit(0)
}
function is_prime(x, i) {
if (x <= 1) {
return(0)
}
for (i=2; i<=int(sqrt(x)); i++) {
if (x % i == 0) {
return(0)
}
}
return(1)
}
|
http://rosettacode.org/wiki/Substring/Top_and_tail | Substring/Top and tail | The task is to demonstrate how to remove the first and last characters from a string.
The solution should demonstrate how to obtain the following results:
String with first character removed
String with last character removed
String with both the first and last characters removed
If the program uses UTF-8 or UTF-16, it must work on any valid Unicode code point, whether in the Basic Multilingual Plane or above it.
The program must reference logical characters (code points), not 8-bit code units for UTF-8 or 16-bit code units for UTF-16.
Programs for other encodings (such as 8-bit ASCII, or EUC-JP) are not required to handle all Unicode characters.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Amazing_Hopper | Amazing Hopper |
#include <hopper.h>
#proto showmessage(_X_)
main:
s="message", t=s
++s, _show message(s)
s=t
--s, _show message(s)
++s, _show message(s)
{0}return
.locals
showmessage(_S_)
{_S_,"\n"}print
back
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.