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/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.23
C#
  public class SubtractiveGenerator { public static int MAX = 1000000000; private int[] state; private int pos;   private int mod(int n) { return ((n % MAX) + MAX) % MAX; }   public SubtractiveGenerator(int seed) { state = new int[55];   int[] temp = new int[55]; temp[0] = mod(seed); temp[1] = 1; for(int i = 2; i < 55; ++i) temp[i] = mod(temp[i - 2] - temp[i - 1]);   for(int i = 0; i < 55; ++i) state[i] = temp[(34 * (i + 1)) % 55];   pos = 54; for(int i = 55; i < 220; ++i) next(); }   public int next() { int temp = mod(state[(pos + 1) % 55] - state[(pos + 32) % 55]); pos = (pos + 1) % 55; state[pos] = temp; return temp; }   static void Main(string[] args) { SubtractiveGenerator gen = new SubtractiveGenerator(292929); for(int i = 220; i < 230; ++i) Console.WriteLine(i.ToString() + ": " + gen.next().ToString()); } }  
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
#J
J
keysubst=: [`(a.i.])`(a."_)} key=: 'Taehist' keysubst '!@#$%^&' enc=: a. {~ key i. ] dec=: key {~ a. i. ]   enc 'This is a test.' !$%^ %^ @ &#^&. dec '!$%^ %^ @ &#^&.' This is a test.
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
#Java
Java
public class SubstitutionCipher {   final static String key = "]kYV}(!7P$n5_0i R:?jOWtF/=-pe'AD&@r6%ZXs\"v*N" + "[#wSl9zq2^+g;LoB`aGh{3.HIu4fbK)mU8|dMET><,Qc\\C1yxJ";   static 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.";   public static void main(String[] args) { String enc = encode(text); System.out.println("Encoded: " + enc); System.out.println("\nDecoded: " + decode(enc)); }   static String encode(String s) { StringBuilder sb = new StringBuilder(s.length());   for (char c : s.toCharArray()) sb.append(key.charAt((int) c - 32));   return sb.toString(); }   static String decode(String s) { StringBuilder sb = new StringBuilder(s.length());   for (char c : s.toCharArray()) sb.append((char) (key.indexOf((int) c) + 32));   return sb.toString(); } }
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.
#CoffeeScript
CoffeeScript
  sum = (array) -> array.reduce (x, y) -> x + y   product = (array) -> array.reduce (x, y) -> x * y  
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.
#ColdFusion
ColdFusion
<cfset Variables.myArray = [1,2,3,4,5,6,7,8,9,10]> <cfoutput>#ArraySum(Variables.myArray)#</cfoutput>
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.
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. sum-of-series.   DATA DIVISION. WORKING-STORAGE SECTION. 78 N VALUE 1000.   01 series-term USAGE FLOAT-LONG. 01 i PIC 9(4).   PROCEDURE DIVISION. PERFORM VARYING i FROM 1 BY 1 UNTIL N < i COMPUTE series-term = series-term + (1 / i ** 2) END-PERFORM   DISPLAY series-term   GOBACK .
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).
#Go
Go
package main   import ( "fmt" "sort" )   const pow3_8 = 3 * 3 * 3 * 3 * 3 * 3 * 3 * 3 // 3^8 const pow3_9 = 3 * pow3_8 // 3^9 const maxExprs = 2 * pow3_8 // not 3^9 since first op can't be Join   type op uint8   const ( Add op = iota // insert a "+" Sub // or a "-" Join // or just join together )   // code is an encoding of [9]op, the nine "operations" // we do on each each digit. The op for 1 is in // the highest bits, the op for 9 in the lowest. type code uint16   // evaluate 123456789 with + - or "" prepended to each as indicated by `c`. func (c code) evaluate() (sum int) { num, pow := 0, 1 for k := 9; k >= 1; k-- { num += pow * k switch op(c % 3) { case Add: sum += num num, pow = 0, 1 case Sub: sum -= num num, pow = 0, 1 case Join: pow *= 10 } c /= 3 } return sum }   func (c code) String() string { buf := make([]byte, 0, 18) a, b := code(pow3_9), code(pow3_8) for k := 1; k <= 9; k++ { switch op((c % a) / b) { case Add: if k > 1 { buf = append(buf, '+') } case Sub: buf = append(buf, '-') } buf = append(buf, '0'+byte(k)) a, b = b, b/3 } return string(buf) }   type sumCode struct { sum int code code } type sumCodes []sumCode   type sumCount struct { sum int count int } type sumCounts []sumCount   // For sorting (could also use sort.Slice with just Less). func (p sumCodes) Len() int { return len(p) } func (p sumCodes) Swap(i, j int) { p[i], p[j] = p[j], p[i] } func (p sumCodes) Less(i, j int) bool { return p[i].sum < p[j].sum } func (p sumCounts) Len() int { return len(p) } func (p sumCounts) Swap(i, j int) { p[i], p[j] = p[j], p[i] } func (p sumCounts) Less(i, j int) bool { return p[i].count > p[j].count }   // For printing. func (sc sumCode) String() string { return fmt.Sprintf("% 10d = %v", sc.sum, sc.code) } func (sc sumCount) String() string { return fmt.Sprintf("% 10d has %d solutions", sc.sum, sc.count) }   func main() { // Evaluate all expressions. expressions := make(sumCodes, 0, maxExprs/2) counts := make(sumCounts, 0, 1715) for c := code(0); c < maxExprs; c++ { // All negative sums are exactly like their positive // counterpart with all +/- switched, we don't need to // keep track of them. sum := c.evaluate() if sum >= 0 { expressions = append(expressions, sumCode{sum, c}) } } sort.Sort(expressions)   // Count all unique sums sc := sumCount{expressions[0].sum, 1} for _, e := range expressions[1:] { if e.sum == sc.sum { sc.count++ } else { counts = append(counts, sc) sc = sumCount{e.sum, 1} } } counts = append(counts, sc) sort.Sort(counts)   // Extract required results   fmt.Println("All solutions that sum to 100:") i := sort.Search(len(expressions), func(i int) bool { return expressions[i].sum >= 100 }) for _, e := range expressions[i:] { if e.sum != 100 { break } fmt.Println(e) }   fmt.Println("\nThe positive sum with maximum number of solutions:") fmt.Println(counts[0])   fmt.Println("\nThe lowest positive number that can't be expressed:") s := 1 for _, e := range expressions { if e.sum == s { s++ } else if e.sum > s { fmt.Printf("% 10d\n", s) break } }   fmt.Println("\nThe ten highest numbers that can be expressed:") for _, e := range expressions[len(expressions)-10:] { fmt.Println(e) } }
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.
#dc
dc
[ Sm Sn lm 1 - d ln % - d sm ln / ln lm + * 0k 2 / Ss Lm sx Ln sx Ls ]sm   [ d d d 3 r lmx r 5 r lmx + r 15 r lmx - ]ss   [ 27 P 91 P 65 P 27 P 91 P 50 P 50 P 67 P ]su   [ ll p lsx lux p ll 10 * d sl 1000000000000000000000 >d]sd   1 sl ldx
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
#Dc
Dc
[ I ~ S! d 0!=S L! + ] sS   1 lS x p 1234 lS x p 16 i FE lS x p F0E lS x p
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
#Emacs_Lisp
Emacs Lisp
(defun sum-of-squares (numbers) (apply #'+ (mapcar (lambda (k) (* k k)) numbers)))   (sum-of-squares (number-sequence 0 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
#Erlang
Erlang
lists:foldl(fun(X, Sum) -> X*X + Sum end, 0, [3,1,4,1,5,9]).
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.
#8th
8th
  \ \ Simple iterative backtracking Sudoku solver for 8th \ needs array/each-slice   [ 00, 00, 00, 03, 03, 03, 06, 06, 06, 00, 00, 00, 03, 03, 03, 06, 06, 06, 00, 00, 00, 03, 03, 03, 06, 06, 06, 27, 27, 27, 30, 30, 30, 33, 33, 33, 27, 27, 27, 30, 30, 30, 33, 33, 33, 27, 27, 27, 30, 30, 30, 33, 33, 33, 54, 54, 54, 57, 57, 57, 60, 60, 60, 54, 54, 54, 57, 57, 57, 60, 60, 60, 54, 54, 54, 57, 57, 57, 60, 60, 60 ] constant top-left-cell   \ Bit number presentations a:new 2 b:new b:clear a:push ( 2 b:new b:clear swap 1 b:bit! a:push ) 0 8 loop constant posbit   : posbit? \ n -- s posbit swap a:@ nip ;   : search \ b -- n null swap ( dup -rot b:bit@ if rot drop break else nip then ) 0 8 loop swap ;   : b-or \ b b -- b ' n:bor b:op ;   : b-and \ b b -- b ' n:band b:op ;   : b-xor \ b b -- b b:xor [ xff, x01 ] b:new b-and ;   : b-not \ b -- b xff b:xor [ xff, x01 ] b:new b-and ;   : b-any \ a -- b ' b-or 0 posbit? a:reduce ;   : row \ a row -- a 9 n:* 9 a:slice ;   : col \ a col -- a -1 9 a:slice+ ;   \ For testing sub boards : sub \ a n -- a top-left-cell swap a:@ nip over over 3 a:slice -rot 9 n:+ 2dup 3 a:slice -rot 9 n:+ 3 a:slice a:+ a:+ ;   a:new 0 args "Give Sudoku text file as param" thrownull f:slurp "Cannot read file" thrownull >s "" s:/ ' >n a:map ( posbit? a:push ) a:each! drop constant board   : display-board board ( search nip -1 ?: n:1+ ) a:map "+-----+-----+-----+\n" "|%d %d %d|%d %d %d|%d %d %d|\n" s:+ "|%d %d %d|%d %d %d|%d %d %d|\n" s:+ "|%d %d %d|%d %d %d|%d %d %d|\n" s:+ "+-----+-----+-----+\n" s:+ "|%d %d %d|%d %d %d|%d %d %d|\n" s:+ "|%d %d %d|%d %d %d|%d %d %d|\n" s:+ "|%d %d %d|%d %d %d|%d %d %d|\n" s:+ "+-----+-----+-----+\n" s:+ "|%d %d %d|%d %d %d|%d %d %d|\n" s:+ "|%d %d %d|%d %d %d|%d %d %d|\n" s:+ "|%d %d %d|%d %d %d|%d %d %d|\n" s:+ "+-----+-----+-----+\n" s:+ s:strfmt . ;   \ Store move history a:new constant history   \ Possible numbers for a cell : candidates? \ n -- s dup dup 9 n:/ n:int swap 9 n:mod \ row col board swap col b-any board rot row b-any b-or board rot sub b-any b-or b-not ;   \ If found: -- n T \ If not found: -- T : find-free-cell false board ( 0 posbit? b:= if nip true break else drop then ) a:each drop ;   : validate true board ( dup -rot a:@ swap 2 pick 0 posbit? a:! 2 pick candidates? 2 pick b:= if -rot a:! else 2drop drop false swap break then ) 0 80 loop drop ;   : solve repeat find-free-cell if dup candidates? repeat search null? if drop board -rot a:! drop history a:len 0 n:= if drop false ;; then a:pop nip a:open else n:1+ posbit? dup board 4 pick rot a:! drop b-xor 2 a:close history swap a:push drop break then again else validate break then again ;   : app:main "Sudoku puzzle:\n" . display-board cr solve if "Sudoku solved:\n" . display-board else "No solution!\n" . then ;  
http://rosettacode.org/wiki/Subleq
Subleq
Subleq is an example of a One-Instruction Set Computer (OISC). It is named after its only instruction, which is SUbtract and Branch if Less than or EQual to zero. Task Your task is to create an interpreter which emulates a SUBLEQ machine. The machine's memory consists of an array of signed integers.   These integers may be interpreted in three ways:   simple numeric values   memory addresses   characters for input or output Any reasonable word size that accommodates all three of the above uses is fine. The program should load the initial contents of the emulated machine's memory, set the instruction pointer to the first address (which is defined to be address 0), and begin emulating the machine, which works as follows:   Let A be the value in the memory location identified by the instruction pointer;   let B and C be the values stored in the next two consecutive addresses in memory.   Advance the instruction pointer three words, to point at the address after the address containing C.   If A is   -1   (negative unity),   then a character is read from the machine's input and its numeric value stored in the address given by B.   C is unused.   If B is   -1   (negative unity),   then the number contained in the address given by A is interpreted as a character and written to the machine's output.   C is unused.   Otherwise, both A and B are treated as addresses.   The number contained in address A is subtracted from the number in address B (and the difference left in address B).   If the result is positive, execution continues uninterrupted; if the result is zero or negative, the number in C becomes the new instruction pointer.   If the instruction pointer becomes negative, execution halts. Your solution may initialize the emulated machine's memory in any convenient manner, but if you accept it as input, it should be a separate input stream from the one fed to the emulated machine once it is running. And if fed as text input, it should be in the form of raw subleq "machine code" - whitespace-separated decimal numbers, with no symbolic names or other assembly-level extensions, to be loaded into memory starting at address   0   (zero). For purposes of this task, show the output of your solution when fed the below   "Hello, world!"   program. As written, this example assumes ASCII or a superset of it, such as any of the Latin-N character sets or Unicode;   you may translate the numbers representing characters (starting with 72=ASCII 'H') into another character set if your implementation runs in a non-ASCII-compatible environment. If 0 is not an appropriate terminator in your character set, the program logic will need some adjustment as well. 15 17 -1 17 -1 -1 16 1 -1 16 3 -1 15 15 0 0 -1 72 101 108 108 111 44 32 119 111 114 108 100 33 10 0 The above "machine code" corresponds to something like this in a hypothetical assembler language for a signed 8-bit version of the machine: start: 0f 11 ff subleq (zero), (message), -1 11 ff ff subleq (message), -1, -1  ; output character at message 10 01 ff subleq (neg1), (start+1), -1 10 03 ff subleq (neg1), (start+3), -1 0f 0f 00 subleq (zero), (zero), start ; useful constants zero: 00 .data 0 neg1: ff .data -1 ; the message to print message: .data "Hello, world!\n\0" 48 65 6c 6c 6f 2c 20 77 6f 72 6c 64 21 0a 00
#11l
11l
F subleq(&a) V i = 0 L i >= 0 I a[i] == -1 a[a[i + 1]] = :stdin.read(1).code E I a[i + 1] == -1 print(Char(code' a[a[i]]), end' ‘’) E a[a[i + 1]] -= a[a[i]] I a[a[i + 1]] <= 0 i = a[i + 2] L.continue i += 3   subleq(&[15, 17, -1, 17, -1, -1, 16, 1, -1, 16, 3, -1, 15, 15, 0, 0, -1, 72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33, 10, 0])
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
#C
C
#include <stdbool.h> #include <stdint.h> #include <stdio.h>   #define PRIME_COUNT 100000 int64_t PRIMES[PRIME_COUNT]; size_t primeSize = 0;   bool isPrime(int n) { size_t i = 0;   for (i = 0; i < primeSize; i++) { int64_t p = PRIMES[i]; if (n == p) { return true; } if (n % p == 0) { return false; } if (p * p > n) { break; } }   return true; }   void initialize() { int i;   PRIMES[primeSize++] = 2; PRIMES[primeSize++] = 3; PRIMES[primeSize++] = 5; PRIMES[primeSize++] = 7; PRIMES[primeSize++] = 11; PRIMES[primeSize++] = 13; PRIMES[primeSize++] = 17; PRIMES[primeSize++] = 19;   for (i = 21; primeSize < PRIME_COUNT;) { if (isPrime(i)) { PRIMES[primeSize++] = i; } i += 2;   if (primeSize < PRIME_COUNT && isPrime(i)) { PRIMES[primeSize++] = i; } i += 2; } }   void diff1(size_t diff) { int64_t pm0, pm1; int64_t fg1 = 0, fg2 = 0, lg1 = 0, lg2 = 0; size_t pos, count = 0;   if (diff == 0) { return; }   pm0 = PRIMES[0]; for (pos = 1; pos < PRIME_COUNT; pos++) { pm1 = pm0; pm0 = PRIMES[pos]; if (pm0 > 1000000) { break; } if (pm0 - pm1 == diff) { count++; if (fg1 == 0) { fg1 = pm1; fg2 = pm0; } lg1 = pm1; lg2 = pm0; } }   printf("%ld|%d|%lld %lld|%lld %lld|\n", diff, count, fg1, fg2, lg1, lg2); }   void diff2(size_t d0, size_t d1) { int64_t pm0, pm1, pm2; int64_t fg1 = 0, fg2, fg3, lg1, lg2, lg3; size_t pos, count = 0;   if (d0 == 0 || d1 == 0) { return; }   pm1 = PRIMES[0]; pm0 = PRIMES[1]; for (pos = 2; pos < PRIME_COUNT; pos++) { pm2 = pm1; pm1 = pm0; pm0 = PRIMES[pos]; if (pm0 > 1000000) { break; } if (pm1 - pm2 == d0 && pm0 - pm1 == d1) { count++; if (fg1 == 0) { fg1 = pm2; fg2 = pm1; fg3 = pm0; } lg1 = pm2; lg2 = pm1; lg3 = pm0; } }   printf("%d %d|%d|%lld %lld %lld|%lld %lld %lld|\n", d0, d1, count, fg1, fg2, fg3, lg1, lg2, lg3); }   void diff3(size_t d0, size_t d1, size_t d2) { int64_t pm0, pm1, pm2, pm3; int64_t fg1 = 0, fg2, fg3, fg4, lg1, lg2, lg3, lg4; size_t pos, count = 0;   if (d0 == 0 || d1 == 0 || d2 == 0) { return; }   pm2 = PRIMES[0]; pm1 = PRIMES[1]; pm0 = PRIMES[2]; for (pos = 3; pos < PRIME_COUNT; pos++) { pm3 = pm2; pm2 = pm1; pm1 = pm0; pm0 = PRIMES[pos]; if (pm0 > 1000000) { break; } if (pm2 - pm3 == d0 && pm1 - pm2 == d1 && pm0 - pm1 == d2) { count++; if (fg1 == 0) { fg1 = pm3; fg2 = pm2; fg3 = pm1; fg4 = pm0; } lg1 = pm3; lg2 = pm2; lg3 = pm1; lg4 = pm0; } }   printf("%d %d %d|%d|%lld %lld %lld %lld|%lld %lld %lld %lld|\n", d0, d1, d2, count, fg1, fg2, fg3, fg4, lg1, lg2, lg3, lg4); }   int main() { initialize();   printf("differences|count|first group|last group\n");   diff1(2); diff1(1);   diff2(2, 2); diff2(2, 4); diff2(4, 2);   diff3(6, 4, 2);   return 0; }
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
#Apex
Apex
  String strOrig = 'brooms'; String str1 = strOrig.substring(1, strOrig.length()); system.debug(str1); String str2 = strOrig.substring(0, strOrig.length()-1); system.debug(str2); String str3 = strOrig.substring(1, strOrig.length()-1); system.debug(str3);   // Regular Expressions approach String strOrig = 'brooms'; String str1 = strOrig.replaceAll( '^.', '' ); system.debug(str1); String str2 = strOrig.replaceAll( '.$', '' ) ; system.debug(str2); String str3 = strOrig.replaceAll( '^.|.$', '' ); system.debug(str3);  
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.2B.2B
C++
  // written for clarity not efficiency.   #include <iostream> using std::cout; using std::endl;   #include <boost/array.hpp> #include <boost/circular_buffer.hpp>   class Subtractive_generator { private: static const int param_i = 55; static const int param_j = 24; static const int initial_load = 219; static const int mod = 1e9; boost::circular_buffer<int> r; public: Subtractive_generator(int seed); int next(); int operator()(){return next();} };   Subtractive_generator::Subtractive_generator(int seed) :r(param_i) { boost::array<int, param_i> s; s[0] = seed; s[1] = 1; for(int n = 2; n < param_i; ++n){ int t = s[n-2]-s[n-1]; if (t < 0 ) t+= mod; s[n] = t; }   for(int n = 0; n < param_i; ++n){ int i = (34 * (n+1)) % param_i; r.push_back(s[i]); } for(int n = param_i; n <= initial_load; ++n) next(); }   int Subtractive_generator::next() { int t = r[0]-r[31]; if (t < 0) t += mod; r.push_back(t); return r[param_i-1]; }   int main() { Subtractive_generator rg(292929);   cout << "result = " << rg() << endl; cout << "result = " << rg() << endl; cout << "result = " << rg() << endl; cout << "result = " << rg() << endl; cout << "result = " << rg() << endl; cout << "result = " << rg() << endl; cout << "result = " << rg() << 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
#jq
jq
def key: "]kYV}(!7P$n5_0i R:?jOWtF/=-pe'AD&@r6%ZXs\"v*N[#wSl9zq2^+g;LoB`aGh{3.HIu4fbK)mU8|dMET><,Qc\\C1yxJ";   def encode: (key|explode) as $key | explode as $exploded | reduce range(0;length) as $i ([]; . + [$key[ $exploded[$i] - 32]] ) | implode;   def decode: (key|explode) as $key | explode as $exploded | reduce range(0;length) as $i ([]; $exploded[$i] as $c | . + [ $key | index($c) + 32] ) | implode ;   def task: "The quick brown fox jumps over the lazy dog, who barks VERY loudly!" | encode as $encoded |"Encoded: \($encoded)", "Decoded: \($encoded|decode)" ;   task
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
#Julia
Julia
module SubstitutionCiphers   using Compat   const key = "]kYV}(!7P\$n5_0i R:?jOWtF/=-pe'AD&@r6%ZXs\"v*N[#wSl9zq2^+g;LoB`aGh{3.HIu4fbK)mU8|dMET><,Qc\\C1yxJ"   function encode(s::AbstractString) buf = IOBuffer() for c in s print(buf, key[Int(c) - 31]) end return String(take!(buf)) end   function decode(s::AbstractString) buf = IOBuffer() for c in s print(buf, Char(findfirst(==(c), key) + 31)) end return String(take!(buf)) end   end # module SubstitutionCiphers
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
#Klingphix
Klingphix
include ..\Utilitys.tlhy   " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" " VsciBjedgrzyHalvXZKtUPumGfIwJxqOCFRApnDhQWobLkESYMTN" "A simple example"   :Encode %mode !mode  %i %t $mode not [rot rot swap rot] if len [  !i $i get swap !t rot swap find rot swap get $t swap $i set ] for $mode not [rot rot swap rot] if ;   dup ? true Encode dup ? false Encode ?   " " input
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.
#Common_Lisp
Common Lisp
(let ((data #(1 2 3 4 5))) ; the array (values (reduce #'+ data) ; sum (reduce #'* data))) ; product
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.
#CoffeeScript
CoffeeScript
  console.log [1..1000].reduce((acc, x) -> acc + (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).
#Haskell
Haskell
import Control.Monad (replicateM) import Data.Char (intToDigit) import Data.List ( find, group, intercalate, nub, sort, sortBy, ) import Data.Monoid ((<>)) import Data.Ord (comparing)   data Sign = Unsigned | Plus | Minus deriving (Eq, Show)   ------------------------ SUM TO 100 ----------------------   universe :: [[(Int, Sign)]] universe = zip [1 .. 9] <$> filter ((/= Plus) . head) (replicateM 9 [Unsigned, Plus, Minus])   allNonNegativeSums :: [Int] allNonNegativeSums = sort $ filter (>= 0) (asSum <$> universe)   uniqueNonNegativeSums :: [Int] uniqueNonNegativeSums = nub allNonNegativeSums   asSum :: [(Int, Sign)] -> Int asSum xs = n + ( case s of [] -> 0 _ -> read s :: Int ) where (n, s) = foldr readSign (0, []) xs readSign :: (Int, Sign) -> (Int, String) -> (Int, String) readSign (i, x) (n, s) | x == Unsigned = (n, intToDigit i : s) | otherwise = ( ( case x of Plus -> (+) _ -> (-) ) n (read (show i <> s) :: Int), [] )   asString :: [(Int, Sign)] -> String asString = foldr signedDigit [] where signedDigit (i, x) s | x == Unsigned = intToDigit i : s | otherwise = ( case x of Plus -> " +" _ -> " -" ) <> [intToDigit i] <> s   --------------------------- TEST ------------------------- main :: IO () main = putStrLn $ unlines [ "Sums to 100:", unlines (asString <$> filter ((100 ==) . asSum) universe), "\n10 commonest sums (sum, number of routes to it):", show ( ((,) <$> head <*> length) <$> take 10 ( sortBy (flip (comparing length)) (group allNonNegativeSums) ) ), "\nFirst positive integer not expressible " <> "as a sum of this kind:", maybeReport ( find (uncurry (/=)) (zip [0 ..] uniqueNonNegativeSums) ), "\n10 largest sums:", show ( take 10 ( sortBy (flip compare) uniqueNonNegativeSums ) ) ] where maybeReport :: Show a => Maybe (a, b) -> String maybeReport (Just (x, _)) = show x maybeReport _ = "No gaps found"
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.
#Delphi
Delphi
program sum35;   {$APPTYPE CONSOLE}   var sum: integer; i: integer;   function isMultipleOf(aNumber, aDivisor: integer): boolean; begin result := aNumber mod aDivisor = 0 end;   begin sum := 0; for i := 3 to 999 do begin if isMultipleOf(i, 3) or isMultipleOf(i, 5) then sum := sum + i; end; writeln(sum); end.
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
#Dyalect
Dyalect
func digits(num, bas = 10) { while num != 0 { let (n, digit) = (num / bas, num % bas) num = n yield digit } }   func Iterator.Sum(acc = 0) { for x in this { acc += x } return acc }   func sumOfDigits(num, bas = 10) => digits(num, bas).Sum()   for e in [ (num: 1, bas: 10), (num: 12345, bas: 10), (num: 123045, bas:10), (num: 0xfe, bas: 16), (num: 0xf0e, bas: 16) ] { print(sumOfDigits(e.num, e.bas)) }
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
#Euphoria
Euphoria
function SumOfSquares(sequence v) atom sum sum = 0 for i = 1 to length(v) do sum += v[i]*v[i] end for return sum end function
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
#Excel
Excel
  =SUMSQ(A1:A10)  
http://rosettacode.org/wiki/Strong_and_weak_primes
Strong and weak primes
Definitions   (as per number theory)   The   prime(p)   is the   pth   prime.   prime(1)   is   2   prime(4)   is   7   A   strong   prime   is when     prime(p)   is   >   [prime(p-1) + prime(p+1)] ÷ 2   A     weak    prime   is when     prime(p)   is   <   [prime(p-1) + prime(p+1)] ÷ 2 Note that the definition for   strong primes   is different when used in the context of   cryptography. Task   Find and display (on one line) the first   36   strong primes.   Find and display the   count   of the strong primes below   1,000,000.   Find and display the   count   of the strong primes below 10,000,000.   Find and display (on one line) the first   37   weak primes.   Find and display the   count   of the weak primes below   1,000,000.   Find and display the   count   of the weak primes below 10,000,000.   (Optional)   display the   counts   and   "below numbers"   with commas. Show all output here. Related Task   Safe primes and unsafe primes. Also see   The OEIS article A051634: strong primes.   The OEIS article A051635: weak primes.
#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)   V p = primes_upto(10'000'000) [Int] s, w, b L(i) 1 .< p.len - 1 I p[i] > (p[i - 1] + p[i + 1]) * 0.5 s [+]= p[i] E I p[i] < (p[i - 1] + p[i + 1]) * 0.5 w [+]= p[i] E b [+]= p[i]   print(‘The first 36 strong primes: ’s[0.<36]) print(‘The count of the strong primes below 1,000,000: ’sum(s.filter(p -> p < 1'000'000).map(p -> 1))) print(‘The count of the strong primes below 10,000,000: ’s.len) print("\nThe first 37 weak primes: "w[0.<37]) print(‘The count of the weak primes below 1,000,000: ’sum(w.filter(p -> p < 1'000'000).map(p -> 1))) print(‘The count of the weak primes below 10,000,000: ’w.len) print("\n\nThe first 10 balanced primes: "b[0.<10]) print(‘The count of balanced primes below 1,000,000: ’sum(b.filter(p -> p < 1'000'000).map(p -> 1))) print(‘The count of balanced primes below 10,000,000: ’b.len) print("\nTOTAL primes below 1,000,000: "sum(p.filter(pr -> pr < 1'000'000).map(pr -> 1))) print(‘TOTAL primes below 10,000,000: ’p.len)
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.
#Ada
Ada
  with Ada.Text_IO;   procedure Sudoku is type sudoku_ar_t is array ( integer range 0..80 ) of integer range 0..9; FINISH_EXCEPTION : exception;   procedure prettyprint(sudoku_ar: sudoku_ar_t); function checkValidity( val : integer; x : integer; y : integer; sudoku_ar: in sudoku_ar_t) return Boolean; procedure placeNumber(pos: Integer; sudoku_ar: in out sudoku_ar_t); procedure solve(sudoku_ar: in out sudoku_ar_t);     function checkValidity( val : integer; x : integer; y : integer; sudoku_ar: in sudoku_ar_t) return Boolean is begin for i in 0..8 loop   if ( sudoku_ar( y * 9 + i ) = val or sudoku_ar( i * 9 + x ) = val ) then return False; end if; end loop;   declare startX : constant integer := ( x / 3 ) * 3; startY : constant integer := ( y / 3 ) * 3; begin for i in startY..startY+2 loop for j in startX..startX+2 loop if ( sudoku_ar( i * 9 +j ) = val ) then return False; end if; end loop; end loop; return True; end; end checkValidity;       procedure placeNumber(pos: Integer; sudoku_ar: in out sudoku_ar_t) is begin if ( pos = 81 ) then raise FINISH_EXCEPTION; end if; if ( sudoku_ar(pos) > 0 ) then placeNumber(pos+1, sudoku_ar); return; end if; for n in 1..9 loop if( checkValidity( n, pos mod 9, pos / 9 , sudoku_ar ) ) then sudoku_ar(pos) := n; placeNumber(pos + 1, sudoku_ar ); sudoku_ar(pos) := 0; end if; end loop; end placeNumber;     procedure solve(sudoku_ar: in out sudoku_ar_t) is begin placeNumber( 0, sudoku_ar ); Ada.Text_IO.Put_Line("Unresolvable !"); exception when FINISH_EXCEPTION => Ada.Text_IO.Put_Line("Finished !"); prettyprint(sudoku_ar); end solve;         procedure prettyprint(sudoku_ar: sudoku_ar_t) is line_sep  : constant String  := "------+------+------"; begin for i in sudoku_ar'Range loop Ada.Text_IO.Put(sudoku_ar(i)'Image); if (i+1) mod 3 = 0 and not((i+1) mod 9 = 0) then Ada.Text_IO.Put("|"); end if; if (i+1) mod 9 = 0 then Ada.Text_IO.Put_Line(""); end if; if (i+1) mod 27 = 0 then Ada.Text_IO.Put_Line(line_sep); end if; end loop; end prettyprint;     sudoku_ar : sudoku_ar_t := ( 8,5,0,0,0,2,4,0,0, 7,2,0,0,0,0,0,0,9, 0,0,4,0,0,0,0,0,0, 0,0,0,1,0,7,0,0,2, 3,0,5,0,0,0,9,0,0, 0,4,0,0,0,0,0,0,0, 0,0,0,0,8,0,0,7,0, 0,1,7,0,0,0,0,0,0, 0,0,0,0,3,6,0,4,0 );   begin solve( sudoku_ar ); end Sudoku;  
http://rosettacode.org/wiki/Subleq
Subleq
Subleq is an example of a One-Instruction Set Computer (OISC). It is named after its only instruction, which is SUbtract and Branch if Less than or EQual to zero. Task Your task is to create an interpreter which emulates a SUBLEQ machine. The machine's memory consists of an array of signed integers.   These integers may be interpreted in three ways:   simple numeric values   memory addresses   characters for input or output Any reasonable word size that accommodates all three of the above uses is fine. The program should load the initial contents of the emulated machine's memory, set the instruction pointer to the first address (which is defined to be address 0), and begin emulating the machine, which works as follows:   Let A be the value in the memory location identified by the instruction pointer;   let B and C be the values stored in the next two consecutive addresses in memory.   Advance the instruction pointer three words, to point at the address after the address containing C.   If A is   -1   (negative unity),   then a character is read from the machine's input and its numeric value stored in the address given by B.   C is unused.   If B is   -1   (negative unity),   then the number contained in the address given by A is interpreted as a character and written to the machine's output.   C is unused.   Otherwise, both A and B are treated as addresses.   The number contained in address A is subtracted from the number in address B (and the difference left in address B).   If the result is positive, execution continues uninterrupted; if the result is zero or negative, the number in C becomes the new instruction pointer.   If the instruction pointer becomes negative, execution halts. Your solution may initialize the emulated machine's memory in any convenient manner, but if you accept it as input, it should be a separate input stream from the one fed to the emulated machine once it is running. And if fed as text input, it should be in the form of raw subleq "machine code" - whitespace-separated decimal numbers, with no symbolic names or other assembly-level extensions, to be loaded into memory starting at address   0   (zero). For purposes of this task, show the output of your solution when fed the below   "Hello, world!"   program. As written, this example assumes ASCII or a superset of it, such as any of the Latin-N character sets or Unicode;   you may translate the numbers representing characters (starting with 72=ASCII 'H') into another character set if your implementation runs in a non-ASCII-compatible environment. If 0 is not an appropriate terminator in your character set, the program logic will need some adjustment as well. 15 17 -1 17 -1 -1 16 1 -1 16 3 -1 15 15 0 0 -1 72 101 108 108 111 44 32 119 111 114 108 100 33 10 0 The above "machine code" corresponds to something like this in a hypothetical assembler language for a signed 8-bit version of the machine: start: 0f 11 ff subleq (zero), (message), -1 11 ff ff subleq (message), -1, -1  ; output character at message 10 01 ff subleq (neg1), (start+1), -1 10 03 ff subleq (neg1), (start+3), -1 0f 0f 00 subleq (zero), (zero), start ; useful constants zero: 00 .data 0 neg1: ff .data -1 ; the message to print message: .data "Hello, world!\n\0" 48 65 6c 6c 6f 2c 20 77 6f 72 6c 64 21 0a 00
#8080_Assembly
8080 Assembly
;;; --------------------------------------------------------------- ;;; SUBLEQ for CP/M. The word size is 16 bits, and the program ;;; is given 16 Kwords (32 KB) of memory. (If the system doesn't ;;; have enough, the program will not run.) ;;; I/O is via the console; since it cannot normally be redirected, ;;; CR/LF translation is on by default. It can be turned off with ;;; the 'R' switch. ;;; --------------------------------------------------------------- ;;; CP/M system calls getch: equ 1h putch: equ 2h puts: equ 9h fopen: equ 0Fh fread: equ 14h ;;; RAM locations fcb1: equ 5ch ; FCB 1 (automatically preloaded with 1st file name) fcb2: equ 6ch ; FCB 2 (we're abusing this one for the switch) dma: equ 80h ; default DMA is located at 80h bdos: equ 5h ; CP/M entry point memtop: equ 6h ; First reserved memory address (below this is ours) ;;; Constants CR: equ 13 ; CR and LF LF: equ 10 EOF: equ 26 ; EOF marker (as we don't have exact filesizes) MSTART: equ 2048 ; Reserve 2K of memory for this program + the stack MSIZE: equ 32768 ; Reserve 32K of memory (16Kwords) for the SUBLEQ code PB: equ 0C6h ; PUSH B opcode. org 100h ;;; -- Memory initialization -------------------------------------- ;;; The fastest way to zero out a whole bunch of memory on the 8080 ;;; is to push zeroes onto the stack. Since we need to do 32K, ;;; and it's slow already to begin with, let's do it that way. lxi d,MSTART+MSIZE ; Top address we need lhld memtop ; See if we even have enough memory call cmp16 ; Compare the two xchg ; Put top address in HL lxi d,emem ; Memory error message jnc die ; If there isn't enough memory, stop. sphl ; Set the stack pointer to the top of memory lxi b,0 ; 2 zero bytes to push xra a ; Zero out A. ;;; Each PUSH pushes 2 zeroes. 256 * 64 * 2 = 32768 zeroes. ;;; In the interests of "speedy" (ha!) execution, let's unroll this ;;; loop a bit. In the interest of the reader, let's not write out ;;; 64 lines of "PUSH B". 'PB' is set to the opcode for PUSH B, and ;;; 4*16=64. This costs some memory, but since we're basically ;;; assuming a baller >48K system anyway to run any non-trivial ;;; SUBLEQ code (ha!), we can spare the 64 bytes. memini: db PB,PB,PB,PB, PB,PB,PB,PB, PB,PB,PB,PB, PB,PB,PB,PB db PB,PB,PB,PB, PB,PB,PB,PB, PB,PB,PB,PB, PB,PB,PB,PB db PB,PB,PB,PB, PB,PB,PB,PB, PB,PB,PB,PB, PB,PB,PB,PB db PB,PB,PB,PB, PB,PB,PB,PB, PB,PB,PB,PB, PB,PB,PB,PB inr a ; This will loop around 256 times jnz memini push b ;;; This conveniently leaves SP pointing just below SUBLEQ memory. ;;; -- Check the raw switch --------------------------------------- ;;; CP/M conveniently parses the command line for us, under the ;;; assumption that there are two whitespace-separated filenames, ;;; which are also automatically made uppercase. ;;; We only have to see if the second filename starts with 'R'. lda fcb2+1 ; Filename starts at offset 1 in the FCB cpi 'R' ; Is it 'R'? jnz readfl ; If not, go read the file (in FCB1). lxi h,chiraw ; If so, rewrite the jumps to use the raw fns shld chin+1 lxi h,choraw shld chout+1 ;;; -- Parse the input file --------------------------------------- ;;; The input file should consist of signed integers written in ;;; decimal, separated by whitespace. (For simplicity, we'll call ;;; all control characters whitespace). CP/M can only read files ;;; 128 bytes at a time, so we'll process it 128 bytes at a time ;;; as well. readfl: lda fcb1+1 ; See if a file was given cpi ' ' ; If not, the filename will be empty (spaces) lxi d,eusage ; Print the usage string if that is the case jz die mvi c,fopen ; Otherwise, try to open the file. lxi d,fcb1 call bdos inr a ; FF is returned on error lxi d,efile ; Print 'file error' and stop. jz die ;;; Start parsing 16-bit numbers lxi h,MSTART ; Start of SUBLEQ memory push h ; Keep that on the stack skipws: call fgetc ; Get character from file jc rddone ; If EOF, we're done cpi ' '+1 ; Is it whitespace? jc skipws ; Then get next character rdnum: lxi h,0 ; H = accumulator to store the number mov b,h ; Set B if number should be negative. cpi '-' ; Did we read a minus sign? jnz rddgt ; If not, then this should be a digit. inr b ; But if so, set B, call fgetc ; and get the next character. jc rddone rddgt: sui '0' ; Make ASCII digit cpi 10 ; Which should now be less than 10 jnc fmterr ; Otherwise, print an error and stop mov d,h ; Set HL=HL*10 mov e,l ; DE = HL dad h ; HL *= 2 dad h ; HL *= 4 dad d ; HL *= 5 dad h ; HL *= 10 mvi d,0 ; Add in the digit mov e,a dad d call fgetc ; Get next character jc rdeof ; EOF while reading number cpi ' '+1 ; Is it whitespace? jnc rddgt ; If not, then it should be the next digit xchg ; If so, write the number to SUBLEQ memory pop h ; Number in DE and pointer in HL call wrnum ; Write the number push h ; Put the pointer back jmp skipws ; Then skip to next number and parse it rdeof: xchg ; EOF, but we still have a number to write pop h ; Number in DE and pointer in HL call wrnum ; Write the number push h rddone: pop h ; We're done, discard pointer ;;; -- Run the SUBLEQ code ---------------------------------------- lxi h,MSTART ; Initialize IP ;;; At the start of step, HL = IP (in system memory) step: mov e,m ; Load A into DE inx h mov d,m inx h mov c,m ; Load B into BC inx h mov b,m inx h mov a,e ; Check if A=-1 ana d inr a jz sbin ; If so, read input mov a,b ; Otherwise, check if B=-1 ana c inr a jz sbout ; If so, write output ;;; Perform the SUBLEQ instruction push h ; Store the IP (-2) on the stack mov a,d ; Obtain [A] (set DE=[DE]) ani 3Fh ; Make sure address is in 16K words mov d,a lxi h,MSTART ; Add to start address twice dad d ; (SUBLEQ addresses words, we're addressing dad d ; bytes) mov e,m ; Load low byte inx h mov d,m ; Load high byte mov a,b ; Obtain [B] (set BC=[BC]) ani 3Fh ; This adress should also be in the 16K words mov b,a lxi h,MSTART ; Add to start address twice, again dad b dad b mov c,m ; Load low byte inx h mov b,m ; Load high byte mov a,c ; BC (B) -= DE (A) sub e ; Subtract low bytes mov c,a mov a,b ; Subtract high bytes sbb d mov b,a mov m,b ; HL is still pointing to the high byte of [B] dcx h mov m,c ; Store the low byte back too pop h ; Restore IP ral ; Check sign bit of [B] (which is still in A) jc sujmp ; If set, it's negative, and we need to jump rar ora c ; If we're still here, it wasn't set. OR with jz sujmp ; low bit, if zero then we also need to jump inx h ; We don't need to jump, so we should ignore C; inx h ; increment the IP to advance past it. jmp step ; Next step sujmp: mov c,m ; We do need to jump, load BC=C inx h mov a,m ; High byte into A ral ; See if it is negative jc quit ; If so, stop rar ani 3Fh ; Don't jump outside the address space mov b,a ; High byte into B lxi h,MSTART ; Calculate new IP dad b dad b jmp step ; Do next step ;;; Input: A=-1 sbin: inx h ; Advance IP past C inx h xchg ; IP in DE mov a,b ; Calculate address for BC (B) ani 3Fh mov b,a lxi h,MSTART dad b dad b call chin ; Read character mov m,a ; Store in low byte inx h mvi m,0 ; Store zero in high byte xchg ; IP back in HL jmp step ; Next step ;;; Output: B=-1 sbout: inx h ; Advance IP past C inx h xchg ; IP in DE and A in HL mov a,h ; Calculate address for A ani 3Fh mov h,a dad h lxi b,MSTART dad b mov a,m ; Retrieve low byte (character) call chout ; Write character xchg ; IP back in HL jmp step ; Next step quit: rst 0 ;;; -- Write number to SUBLEQ memory ------------------------------ ;;; Assuming: DE holds the number, B=1 if number should be negated, ;;; HL holds the pointer to SUBLEQ memory. wrnum: dcr b ; Should the number be negated? jnz wrpos ; If not, just write it dcx d ; Otherwise, negate it: decrement, mov a,e ; Then complement low byte, cma mov e,a mov a,d ; Then complement high byte cma mov d,a ; And then write it wrpos: mov m,e ; Write low byte inx h ; Advance pointer mov m,d ; Write high byte inx h ; Advance pointer ret ;;; -- Read file byte by byte ------------------------------------- ;;; The next byte from the file in FCB1 is returned in A, and all ;;; other registers are preserved. When 128 bytes have been read, ;;; the next record is loaded automatically. Carry set on EOF. fgetc: push h ; Keep HL registers lda fgptr ; Where are we in the record? ana a jz nxtrec ; If at 0 (rollover), load new record. frecc: mvi h,0 ; HL = A mov l,a inr a ; Next A sta fgptr ; Write A back mov a,m ; Retrieve byte pop h ; Restore HL registers cpi EOF ; Is it EOF? rnz ; If not, we're done (ANA clears carry) stc ; But otherwise, set carry ret nxtrec: push d ; Keep the other registers too push b mvi c,fread ; Read record from file lxi d,fcb1 call bdos dcr a ; A=1 on EOF jz fgeof inr a ; A<>0 = error lxi d,efile jnz die mvi a,80h ; If we're still here, record read correctly sta fgptr ; Set pointer back to beginning of DMA. pop b ; Restore B and D pop d jmp frecc ; Get first character from the record. fgeof: stc ; On EOF (no more records), set carry jmp resbdh ; And restore the registers fgptr: db 0 ; Pointer (80h-FFh) into DMA area. Reload on 0. ;;; -- Compare DE to HL ------------------------------------------- cmp16: mov a,d ; Compare high bytes cmp h rnz ; If they are not equal, we know the ordering mov a,e ; If they are equal, compare lower bytes cmp l ret ;;; -- Register-preserving I/O routines --------------------------- chin: jmp chitr ; These are rewritten to jump to the raw I/O chout: jmp chotr ; instructions to turn translation off. ;;; -- Read character into A with translation --------------------- chitr: call chiraw ; Get raw character cpi CR ; Is it CR? rnz ; If not, return character unchanged mvi a,LF ; Otherwise, return LF (terminal sends only CR) ret ;;; -- Read character into A. ------------------------------------- chiraw: push h ; Save all registers except A push d push b mvi c,getch ; Get character from terminal call bdos ; Character ends up in A jmp resbdh ; Restore registers afterwards ;;; -- Write character in A to terminal with translation ---------- chotr: cpi LF ; Is it LF? jnz choraw ; If not, just print it mvi a,CR ; Otherwise, print a CR first, call choraw mvi a,LF ; And then a LF. (fall through) ;;; -- Write character in A to terminal --------------------------- choraw: push h ; Store all registers push d push b push psw mvi c,putch ; Write character to terminal mov e,a call bdos ;;; -- Restore registers ------------------------------------------ restor: pop psw ; Restore all registers resbdh: pop b ; Restore B D H pop d pop h ret ;;; -- Make parse error message and stop -------------------------- ;;; A should hold the offending character _after_ '0' has already ;;; been subtracted. fmterr: adi '0' ; Undo subtraction of ASCII 0 lxi h,eiloc ; Write the characters in the error message mov m,a inx h mvi b,4 ; Max. 4 more characters fmtelp: call fgetc ; Get next character jc fmtdne ; If EOF, stop mov m,a ; If not, store the character inx h ; Advance pointer dcr b ; Should we do more characters? jnz fmtelp ; If so, go get another fmtdne: lxi d,einv ; Print 'invalid integer' error message. ;;; -- Print an error message and stop ---------------------------- die: mvi c,puts call bdos rst 0 ;;; -- Error messages --------------------------------------------- eusage: db 'SUBLEQ <file> [R]: Run the SUBLEQ program in <file>.$' efile: db 'File error$' emem: db 'Memory error$' einv: db 'Invalid integer: ' eiloc: db ' $'
http://rosettacode.org/wiki/Subleq
Subleq
Subleq is an example of a One-Instruction Set Computer (OISC). It is named after its only instruction, which is SUbtract and Branch if Less than or EQual to zero. Task Your task is to create an interpreter which emulates a SUBLEQ machine. The machine's memory consists of an array of signed integers.   These integers may be interpreted in three ways:   simple numeric values   memory addresses   characters for input or output Any reasonable word size that accommodates all three of the above uses is fine. The program should load the initial contents of the emulated machine's memory, set the instruction pointer to the first address (which is defined to be address 0), and begin emulating the machine, which works as follows:   Let A be the value in the memory location identified by the instruction pointer;   let B and C be the values stored in the next two consecutive addresses in memory.   Advance the instruction pointer three words, to point at the address after the address containing C.   If A is   -1   (negative unity),   then a character is read from the machine's input and its numeric value stored in the address given by B.   C is unused.   If B is   -1   (negative unity),   then the number contained in the address given by A is interpreted as a character and written to the machine's output.   C is unused.   Otherwise, both A and B are treated as addresses.   The number contained in address A is subtracted from the number in address B (and the difference left in address B).   If the result is positive, execution continues uninterrupted; if the result is zero or negative, the number in C becomes the new instruction pointer.   If the instruction pointer becomes negative, execution halts. Your solution may initialize the emulated machine's memory in any convenient manner, but if you accept it as input, it should be a separate input stream from the one fed to the emulated machine once it is running. And if fed as text input, it should be in the form of raw subleq "machine code" - whitespace-separated decimal numbers, with no symbolic names or other assembly-level extensions, to be loaded into memory starting at address   0   (zero). For purposes of this task, show the output of your solution when fed the below   "Hello, world!"   program. As written, this example assumes ASCII or a superset of it, such as any of the Latin-N character sets or Unicode;   you may translate the numbers representing characters (starting with 72=ASCII 'H') into another character set if your implementation runs in a non-ASCII-compatible environment. If 0 is not an appropriate terminator in your character set, the program logic will need some adjustment as well. 15 17 -1 17 -1 -1 16 1 -1 16 3 -1 15 15 0 0 -1 72 101 108 108 111 44 32 119 111 114 108 100 33 10 0 The above "machine code" corresponds to something like this in a hypothetical assembler language for a signed 8-bit version of the machine: start: 0f 11 ff subleq (zero), (message), -1 11 ff ff subleq (message), -1, -1  ; output character at message 10 01 ff subleq (neg1), (start+1), -1 10 03 ff subleq (neg1), (start+3), -1 0f 0f 00 subleq (zero), (zero), start ; useful constants zero: 00 .data 0 neg1: ff .data -1 ; the message to print message: .data "Hello, world!\n\0" 48 65 6c 6c 6f 2c 20 77 6f 72 6c 64 21 0a 00
#8086_Assembly
8086 Assembly
;;; ------------------------------------------------------------- ;;; SUBLEQ interpreter that runs under MS-DOS. ;;; The word size is 16 bits, and the SUBLEQ program gets a 64KB ;;; (that is, 32K Subleq words) address space. ;;; The SUBLEQ program is read from a text file given on the ;;; command line, I/O is done via the console. ;;; Console I/O is normally raw, but with the /T parameter, ;;; line ending translation is done (CRLF <> LF). ;;; ------------------------------------------------------------- bits 16 cpu 8086 ;;; MS-DOS system calls getch: equ 1h ; Get character putch: equ 2h ; Print character puts: equ 9h ; Print string fopen: equ 3Dh ; Open file fclose: equ 3Eh ; Close file fread: equ 3Fh ; Read from file alloc: equ 48h ; Allocate memory block resize: equ 4Ah ; Change size of memory block exit: equ 4Ch ; Exit to DOS ;;; Constants RBUFSZ: equ 1024 ; 1K read buffer CR: equ 13 ; CR and LF LF: equ 10 ;;; RAM locations cmdlen: equ 80h ; Length of command line cmdlin: equ 81h ; Contents of command line org 100h section .text clc ; Make sure string instructions go forward ;;; -- Memory initialization ------------------------------------ ;;; This is a .COM file. This means MS-DOS gives us all available ;;; memory starting at CS:0, and CS=DS=ES=SS. This means in order ;;; to allocate a separate 64k segment for the SUBLEQ memory ;;; space, we will first need to free all memory we're not using. ;;; ------------------------------------------------------------- memini: mov sp,memtop ; Point SP into memory we will be keeping mov dx,emem ; Set up a pointer to the memory error msg mov ah,resize ; Reallocate current block mov bx,sp ; Size is in paragraphs (16 bytes), and the mov cl,4 ; assembler will not let me shift a label at shr bx,cl ; compile time, so we'll do it at runtime. inc bx ; BX=(memtop>>4)+1; memtop in last paragraph. int 21h jnc .alloc ; Carry not set = allocate memory jmp die ; Otherwise, error (jump > 128 bytes) ;;; Allocate a 64K block for the SUBLEQ program's address space .alloc: mov ah,alloc ; Allocate 64K (4096 paragraphs) for the mov bx,4096 ; SUBLEQ program. Because that is the size of int 21h ; an 8086 segment, we get free wraparound, jnc .zero ; and we don't have to worry about bounds jmp die ; checking. ;;; Zero out the memory we're given .zero: push ax ; Keep SUBLEQ segment on stack. mov es,ax ; Let ES point into our SUBLEQ segment. mov cx,32768 ; 32K words = 64K bytes to set to zero. xor ax,ax ; We don't have to care about where DI is, rep stosw ; since we're doing all of ES anyway. ;;; -- Parse the command line and open the file ----------------- ;;; A filename should be given on the command line, which should ;;; be a text file containing (possibly negative) integers ;;; written in base 10. For "efficiency", we read the file 1K ;;; at a time into a buffer, rather than character by character. ;;; We also handle the '/T' parameter here. ;;; ------------------------------------------------------------- rfile: mov dx,usage ; Print 'usage' message if no argument mov di,cmdlin ; 0-terminate command line for use with fopen xor bh,bh ; We'll use BX to index into the command line mov bl,[cmdlen] ; Length of command line test bl,bl ; If it's zero, no argument was given jnz .term ; If not zero, go ahead jmp die ; Otherwise, error (again, jump > 128 bytes) .term: mov [di+bx],bh ; Otherwise, 0-terminate mov ax,ds ; Let ES point into our data segment mov es,ax ; (in order to use SCASB). .skp: mov al,' ' ; Skip any preceding spaces mov cx,128 ; Max. command line length repe scasb dec di ; As usual, SCASB goes one byte too far mov al,[di] ; If we're at zero now, we don't have an test al,al ; argument either, so same error. jnz .parm ; (Again, jump > 128 bytes) jmp die .parm cmp al,'/' ; Input parameter? jne .open ; If not, this is the filename, open it inc di ; If so, is it 'T' or 't'? mov al,[di] inc di ; Skip past it mov dl,[di] ; And is the next one a space again? cmp dl,' ' je .testp ; If so, it's potentially valid .perr: mov dx,eparm ; If not, print error message jmp die .testp: or al,32 ; Make lowercase cmp al,'t' ; 'T'? jne .perr ; If not, print error message inc byte [trans] ; If so, turn translation on jmp .skp ; And then get the filename .open: mov ax,fopen<<8 ; Open file for reading (AL=0=O_RDONLY) mov dx,di ; 0-terminated path on the command line int 21h jnc .read ; Carry not set = file opened mov dx,efile ; Otherwise, file error (we don't much care jmp die ; which one, that's too much work.) .read: pop es ; Let ES be the SUBLEQ segment (which we xor di,di ; pushed earlier), and DI point to 1st word. mov bp,ax ; Keep the file handle in BP. xor cx,cx ; We have read no bytes yet. ;;; -- Read and parse the file ---------------------------------- ;;; We need to read 16-bit signed integers from the file, ;;; in decimal. The integers are separated by whitespace, which ;;; for simplicity's sake we'll say is ASCII space and _all_ ;;; control characters. BP, CX and SI are used as state to ;;; emulate character-based I/O, and so must be preserved; ;;; furthermore, DI is used as a pointer into the SUBLEQ memory. ;;; ------------------------------------------------------------- skipws: call fgetc ; Get next character jc fdone ; If we get EOF, we're done. cmp al,' ' ; Is it whitespace? (0 upto ' ' inclusive) jbe skipws ; Then keep skipping rdnum: xor dl,dl ; DL is set if number is negative xor bx,bx ; BX will keep the number cmp al,'-' ; Is first character a '-'? jne .dgt ; If not, it's positive inc dx ; Otherwise, set DL, call fgetc ; and get next character. jc fdone .dgt: mov dh,al ; Store character in DH sub dh,'0' ; Subtract '0' cmp dh,9 ; Digit is [0..9]? jbe .dgtok ; Then it is OK jmp fmterr ; Otherwise, format error (jump > 128) .dgtok: mov ax,bx ; BX *= 10 (without using MUL or SHL BX,CL; shl bx,1 ; since we can't spare the registers). shl bx,1 add bx,ax shl bx,1 mov al,dh ; Load digit into AL cbw ; Sign extend (in practice just sets AH=0) add bx,ax ; Add it into BX call fgetc ; Get next character jc dgteof ; EOF while reading num is special cmp al,' ' ; If it isn't whitespace, ja .dgt ; then it's the next digit. test dl,dl ; Otherwise, number is done. Was it negative? jz .wrnum ; If not, write it to SUBLEQ memory neg bx ; Otherwise, negate it .wrnum: mov ax,bx ; ...and _then_ write it. stosw jmp skipws ; Skip any other wspace and get next number dgteof: test dl,dl ; If we reached EOF while reading a number, jz .wrnum ; we need to do the same conditional negation neg bx ; and write out the number that was still in .wrnum: mov ax,bx ; BX. stosw fdone: mov ah,fclose ; When we're done, close the file. mov bx,bp ; (Not strictly necessary since we've only int 21h ; read, so we don't care about errors.) ;;; -- Run the SUBLEQ code -------------------------------------- ;;; SI = instruction pointer. An instruction A B C is loaded into ;;; BX DI AX respectively. Note that SUBLEQ addresses words, ;;; whereas the 8086 addresses bytes, so the addresses all need ;;; to be shifted left once before being used. ;;; ------------------------------------------------------------- subleq: xor si,si ; Start with IP=0 mov cl,[trans] ; CL = \r\n translation on or off mov ax,es ; Set DS=ES=SUBLEQ segment mov ds,ax ;;; Load instruction .step: lodsw ; Load A mov bx,ax ; BP = A lodsw ; Load B mov di,ax ; DI = B lodsw ; Load C (AX=C) ;;; Check for special cases inc bx ; BX=-1 = read byte jz .in ; If ++BP==0, then read character dec bx ; Restore BX inc di ; If ++DI==0, then write character jz .out dec di ; Restore DI ;;; Do the SUBLEQ instruction shl di,1 ; Addresses must be doubled since SUBLEQ shl bx,1 ; addresses words and we're addressing bytes mov dx,[di] ; Retrieve [B] sub dx,[bx] ; DX = [B] - [A] mov [di],dx ; [B] = DX jg .step ; If [B]>[A], (i.e. [B]-[A]>=0), do next step shl ax,1 ; Otherwise, AX*2 (C) becomes the new IP mov si,ax jnc .step ; If high bit was 0, next step mov ax,exit<<8 ; But otherwise, it was negative, so we stop int 21h ;;; Read a character from standard input .in: mov ah,getch ; Input: read character into AL int 21h cmp al,CR ; Is it CR? je .crin ; If not, just store the character .sto: xor ah,ah ; Character goes in low byte of word shl di,1 ; Word address to byte address mov [di],ax ; Store character in memory at B jmp .step ; And do next step ;;; Pressing enter only returns CR; not CR LF on two reads, ;;; therefore on CR we give LF instead when translation is on. .crin: test cl,cl ; Do we even want translation? jz .sto ; If not, just store the CR and leave it mov al,LF ; But if so, use LF instead jmp .sto ;;; Write a character to standard output .out: shl bx,1 ; Load character from [A] mov dl,[bx] ; We only need the low byte mov ah,putch ; Set AH to print the character cmp dl,LF ; Is it LF? je .lfo ; Then handle it separately .wr: int 21h jmp .step ; Do next step ;;; LF needs to be translated into CR LF, so we need to print the ;;; CR first and then the LF, if translation is on. .lfo: test cl,cl ; Do we even want translation? jz .wr ; If not, just print the LF mov dl,CR ; If so, print a CL first int 21h mov dl,LF ; And then a LF jmp .wr ;;; -- Subroutine: get byte from file buffer. -------------------- ;;; If the buffer is empty, fill with more bytes from file. ;;; On EOF, return with carry set. ;;; Input: BP = file handle, CX = bytes left in buffer, ;;; SI = current pointer into buffer. ;;; Output: AL = byte, CX and SI moved, other registers preserved ;;; ------------------------------------------------------------- fgetc: test cx,cx ; Bytes left? jz .read ; If not, read from file .buf: lodsb ; Otherwise, get byte from buffer dec cx ; One fewer byte left ret ; And we're done. (TEST clears carry, LODSB ; and DEC don't touch it, so it's clear.) .read: push ax ; Keep AX, BX, DX push bx push dx mov ah,fread ; Read from file, mov bx,bp ; BP = file handle, mov cx,RBUFSZ ; Fill up entire buffer if possible, mov dx,fbuf ; Starting at the start of buffer, mov si,dx ; Also start returning bytes from there. int 21h jc .err ; Carry set = read error mov cx,ax ; CX = amount of bytes read pop dx ; Restore AX, BX, DX pop bx pop ax test cx,cx ; If CX not zero, we now have data in buffer jnz .buf ; So get first byte from buffer stc ; But if not, EOF, so set carry and return ret .err: mov dx,efile ; On error, print the file error message jmp die ; and stop ;;; Parse error (invalid digit) --------------------------------- ;;; Invalid character is in AL. BP, CX, SI still set to read from ;;; file. fmterr: mov dx,ds ; Set ES=DS mov es,dx mov dl,5 ; Max. 5 characters mov di,eparse.dat ; DI = empty space in error message .wrch: stosb ; Store character in error message call fgetc ; Get next character jc .done ; No more chars = stop dec dl ; If room left, jnz .wrch ; write next character .done: mov dx,eparse ; Use error message with offender written in ; And fall through to stop the program ;;; Print the error message in [DS:DX] and terminate with ;;; errorlevel 2. die: mov ah,puts int 21h mov ax,exit<<8 | 2 int 21h section .data usage: db 'SUBLEQ [/T] <file> - Run the SUBLEQ program in <file>.$' efile: db 'Error reading file.$' eparm: db 'Invalid parameter.$' emem: db 'Memory allocation failure.$' eparse: db 'Invalid integer at: ' .dat: db ' $' ; Spaces to be filled in by error routine trans: db 0 ; Will be set if CRLF translation is on section .bss fbuf: resb RBUFSZ ; File buffer stack: resw 128 ; 128 words for main stack (should be enough) memtop: equ $
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
#C.23
C#
using System; using System.Collections.Generic; using static System.Linq.Enumerable;   public static class SuccessivePrimeDifferences {   public static void Main() { var primes = GeneratePrimes(1_000_000).ToList(); foreach (var d in new[] { new [] { 2 }, new [] { 1 }, new [] { 2, 2 }, new [] { 2, 4 }, new [] { 4, 2 }, new [] { 6, 4, 2 }, }) { IEnumerable<int> first = null, last = null; int count = 0; foreach (var grp in FindDifferenceGroups(d)) { if (first == null) first = grp; last = grp; count++; } Console.WriteLine($"{$"({string.Join(", ", first)})"}, {$"({string.Join(", ", last)})"}, {count}"); }   IEnumerable<IEnumerable<int>> FindDifferenceGroups(int[] diffs) { for (int pi = diffs.Length; pi < primes.Count; pi++) if (Range(0, diffs.Length).All(di => primes[pi-diffs.Length+di+1] - primes[pi-diffs.Length+di] == diffs[di])) yield return Range(pi - diffs.Length, diffs.Length + 1).Select(i => primes[i]); }   IEnumerable<int> GeneratePrimes(int lmt) { bool[] comps = new bool[lmt + 1]; comps[0] = comps[1] = true; yield return 2; yield return 3; for (int j = 4; j <= lmt; j += 2) comps[j] = true; for (int j = 9; j <= lmt; j += 6) comps[j] = true; int i = 5, d = 4, rt = (int)Math.Sqrt(lmt); for ( ; i <= rt; i += (d = 6 - d)) if (!comps[i]) { yield return i; for (int j = i * i, k = i << 1; j <= lmt; j += k) comps[j] = true; } for ( ; i <= lmt; i += (d = 6 - d)) if (!comps[i]) yield return i; } } }
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
#AppleScript
AppleScript
set aString to "This is some text"   set stringLength to (count aString) -- The number of characters in the text.   -- AppleScript indices are 1-based. Ranges can be specified in several different ways. if (stringLength > 1) then set substring1 to text 2 thru stringLength of aString -- set substring1 to text 2 thru -1 of aString -- set substring1 to text 2 thru end of aString -- set substring1 to text from character 2 to character stringLength of aString -- set substring1 to aString's text from 2 to -1 -- Some combination of the above. else set substring1 to "" end if   if (stringLength > 1) then set substring2 to text 1 thru -2 of aString else set substring2 to "" end if   if (stringLength > 2) then set substring3 to text 2 thru -2 of aString else set substring3 to "" end if   return substring1 & linefeed & substring2 & linefeed & substring3
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.
#Clojure
Clojure
(defn xpat2-with-seed "produces an xpat2 function initialized from seed" [seed] (let [e9 1000000000 fs (fn [[i j]] [j (mod (- i j) e9)]) s (->> [seed 1] (iterate fs) (map first) (take 55) vec) rinit (map #(-> % inc (* 34) (mod 55) s) (range 55)) r-atom (atom [54 (int-array rinit)]) update (fn [[nprev r]] (let [n (-> nprev inc (mod 55)) rx #(get r (-> n (- %) (mod 55))) rn (-> (rx 55) (- (rx 24)) (mod e9)) _ (aset-int r n rn)] [n r])) xpat2 #(let [[n r] (swap! r-atom update)] (get r n)) _ (dotimes [_ 165] (xpat2))] xpat2))   (def xpat2 (xpat2-with-seed 292929))   (println (xpat2) (xpat2) (xpat2)) ; prints: 467478574 512932792 539453717  
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
#Kotlin
Kotlin
// version 1.0.6   object SubstitutionCipher { val key = "]kYV}(!7P\$n5_0i R:?jOWtF/=-pe'AD&@r6%ZXs\"v*N[#wSl9zq2^+g;LoB`aGh{3.HIu4fbK)mU8|dMET><,Qc\\C1yxJ"   fun encode(s: String): String { val sb = StringBuilder() for (c in s) sb.append(key[c.toInt() - 32]) return sb.toString() }   fun decode(s: String): String { val sb = StringBuilder() for (c in s) sb.append((key.indexOf(c) + 32).toChar()) return sb.toString() } }   fun main(args: Array<String>) { val s = "The quick brown fox jumps over the lazy dog, who barks VERY loudly!" val enc = SubstitutionCipher.encode(s) println("Encoded: $enc") println("Decoded: ${SubstitutionCipher.decode(enc)}") }
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
#Lambdatalk
Lambdatalk
    {def small_ascii {S.map fromCharCode {S.serie 33 122}}} -> small_ascii   {S.length {small_ascii}} = 90   {def substitution   {def substitution.r {lambda {:w :n :s :i} {if {> :i :n} then else {let { {:s :s} {:c {W.char2code {A.get :i :w}}} } {if {and {>= :c 33} {<= :c 122}} then {W.code2char {+ 33 {% {+ :c {- :s 33}} 90}}} else {if {= :c 248} then :c else}} }{substitution.r :w :n :s {+ :i 1}} }}}   {lambda {:s :w} {let { {:s :s} {:w {S.replace \s by ` in :w}} } {S.replace ` by space in {substitution.r {A.split :w} {- {W.length :w} 1}  :s 0}} }}} -> substitution   1) intitial text:   {def txt Veni, Vidi, Vici is a Latin phrase popularly attributed to Julius Caesar who, according to Appian, used the phrase in a letter to the Roman Senate around 47 BC after he had achieved a quick victory in his short war against Pharnaces II of Pontus at the Battle of Zela. } -> txt   2) choose the shift:   {def shift 13} -> shift // valid in [0...90] except 5 10 15 29 30 50 53 70 74   3) encoding the text   {substitution {shift} {txt}} -> cr!v9mcvqv9mcvpvmv&mnmYn'v!m#u%n&rm#"#(yn%y,mn''%vo('rqm'"mW(yv(&mPnr&n%m*u"9mnpp"%qv!tm'"mN##vn!9m(&rqm'urm#u%n&rmv!mnmyr''r%m'"m'urm_"zn!m r!n'rmn%" (!qmADmOPmns'r%murmunqmnpuvr)rqmnm$(vpxm)vp'"%,mv!muv&m&u"%'m*n%mntnv!&'m]un%!npr&mVVm"sm]"!'(&mn'm'urmOn''yrm"smgryn;   4) decoding the text   {substitution {- 90 {shift}} {substitution {shift} {txt}}} -> Veni, Vidi, Vici is a Latin phrase popularly attributed to Julius Caesar who, according to Appian, used the phrase in a letter to the Roman Senate around 47 BC after he had achieved a quick victory in his short war against Pharnaces II of Pontus at the Battle of Zela.  
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.
#Crystal
Crystal
  def sum_product(a) { a.sum(), a.product() } end  
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.
#Common_Lisp
Common Lisp
(loop for x from 1 to 1000 summing (expt x -2))
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).
#J
J
  p =: ,"2".>(#: (+ i.)2^8) <;.1 '123456789' m =. (9$_1x)^"1#:i.2^9 s =. 131072 9 $ ,m *"1/ p s2 =: (~: (10x^i._9)#.s)#s ss =: +/"1 s2 '100=';<'bp<+>' 8!:2 (I.100=ss){s2 pos =: (0<ss)#ss =: /:~ss ({.;'times';{:)>{.\:~(#,{.) each </.~ ss 'Ten largest:';,.(->:i.10){ss 'First not expressible:';>:pos{~ 1 i.~ 1<|2-/\pos  
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.C3.A9j.C3.A0_Vu
Déjà Vu
sum-divisible n: 0 for i range 1 -- n: if or = 0 % i 3 = 0 % i 5: + i   !. sum-divisible 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
#Delphi
Delphi
defmodule RC do def sumDigits(n, base\\10) def sumDigits(n, base) when is_integer(n) do Integer.digits(n, base) |> Enum.sum end def sumDigits(n, base) when is_binary(n) do String.codepoints(n) |> Enum.map(&String.to_integer(&1, base)) |> Enum.sum end end   Enum.each([{1, 10}, {1234, 10}, {0xfe, 16}, {0xf0e, 16}], fn {n,base} -> IO.puts "#{Integer.to_string(n,base)}(#{base}) sums to #{ RC.sumDigits(n,base) }" end) IO.puts "" Enum.each([{"1", 10}, {"1234", 10}, {"fe", 16}, {"f0e", 16}], fn {n,base} -> IO.puts "#{n}(#{base}) sums to #{ RC.sumDigits(n,base) }" end)
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
#F.23
F#
[1 .. 10] |> List.fold (fun a x -> a + x * x) 0 [|1 .. 10|] |> Array.fold (fun a x -> a + x * x) 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
#Factor
Factor
USE: math sequences ;   : sum-of-squares ( seq -- n ) [ sq ] map-sum ;   { 1.0 2.0 4.0 8.0 16.0 } sum-of-squares
http://rosettacode.org/wiki/Strong_and_weak_primes
Strong and weak primes
Definitions   (as per number theory)   The   prime(p)   is the   pth   prime.   prime(1)   is   2   prime(4)   is   7   A   strong   prime   is when     prime(p)   is   >   [prime(p-1) + prime(p+1)] ÷ 2   A     weak    prime   is when     prime(p)   is   <   [prime(p-1) + prime(p+1)] ÷ 2 Note that the definition for   strong primes   is different when used in the context of   cryptography. Task   Find and display (on one line) the first   36   strong primes.   Find and display the   count   of the strong primes below   1,000,000.   Find and display the   count   of the strong primes below 10,000,000.   Find and display (on one line) the first   37   weak primes.   Find and display the   count   of the weak primes below   1,000,000.   Find and display the   count   of the weak primes below 10,000,000.   (Optional)   display the   counts   and   "below numbers"   with commas. Show all output here. Related Task   Safe primes and unsafe primes. Also see   The OEIS article A051634: strong primes.   The OEIS article A051635: weak primes.
#ALGOL_68
ALGOL 68
# find and count strong and weak primes # PR heap=128M PR # set heap memory size for Algol 68G # # returns a string representation of n with commas # PROC commatise = ( INT n )STRING: BEGIN STRING result := ""; STRING unformatted = whole( n, 0 ); INT ch count := 0; FOR c FROM UPB unformatted BY -1 TO LWB unformatted DO IF ch count <= 2 THEN ch count +:= 1 ELSE ch count := 1; "," +=: result FI; unformatted[ c ] +=: result OD; result END # commatise # ; # sieve values # CHAR prime = "P"; # unclassified/average prime # CHAR strong = "S"; # strong prime # CHAR weak = "W"; # weak prime # CHAR composite = "C"; # non-prime # # sieve of Eratosthenes: sets s[i] to prime if i is a prime, # # composite otherwise # PROC sieve = ( REF[]CHAR s )VOID: BEGIN # start with everything flagged as prime # FOR i TO UPB s DO s[ i ] := prime OD; # sieve out the non-primes # s[ 1 ] := composite; FOR i FROM 2 TO ENTIER sqrt( UPB s ) DO IF s[ i ] = prime THEN FOR p FROM i * i BY i TO UPB s DO s[ p ] := composite OD FI OD END # sieve # ;   INT max number = 10 000 000; # construct a sieve of primes up to slightly more than the maximum number # # required for the task, as we may need an extra prime for the classification # [ 1 : max number + 1 000 ]CHAR primes; sieve( primes ); # classify the primes # # find the first three primes # INT prev prime := 0; INT curr prime := 0; INT next prime := 0; FOR p FROM 2 WHILE prev prime = 0 DO IF primes[ p ] = prime THEN prev prime := curr prime; curr prime := next prime; next prime := p FI OD; # 2 is the only even prime so the first three primes are the only case where # # the average of prev prime and next prime is not an integer # IF REAL avg = ( prev prime + next prime ) / 2; curr prime > avg THEN primes[ curr prime ] := strong ELIF curr prime < avg THEN primes[ curr prime ] := weak FI; # classify the rest of the primes # FOR p FROM next prime + 1 WHILE curr prime <= max number DO IF primes[ p ] = prime THEN prev prime := curr prime; curr prime := next prime; next prime := p; IF INT avg = ( prev prime + next prime ) OVER 2; curr prime > avg THEN primes[ curr prime ] := strong ELIF curr prime < avg THEN primes[ curr prime ] := weak FI FI OD; INT strong1 := 0, strong10 := 0; INT weak1 := 0, weak10 := 0; FOR p WHILE p < 10 000 000 DO IF primes[ p ] = strong THEN strong10 +:= 1; IF p < 1 000 000 THEN strong1 +:= 1 FI ELIF primes[ p ] = weak THEN weak10 +:= 1; IF p < 1 000 000 THEN weak1 +:= 1 FI FI OD; INT strong count := 0; print( ( "first 36 strong primes:", newline ) ); FOR p WHILE strong count < 36 DO IF primes[ p ] = strong THEN print( ( " ", whole( p, 0 ) ) ); strong count +:= 1 FI OD; print( ( newline ) ); print( ( "strong primes below 1,000,000: ", commatise( strong1 ), newline ) ); print( ( "strong primes below 10,000,000: ", commatise( strong10 ), newline ) ); print( ( "first 37 weak primes:", newline ) ); INT weak count := 0; FOR p WHILE weak count < 37 DO IF primes[ p ] = weak THEN print( ( " ", whole( p, 0 ) ) ); weak count +:= 1 FI OD; print( ( newline ) ); print( ( " weak primes below 1,000,000: ", commatise( weak1 ), newline ) ); print( ( " weak primes below 10,000,000: ", commatise( weak10 ), newline ) )
http://rosettacode.org/wiki/Substring
Substring
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Display a substring:   starting from   n   characters in and of   m   length;   starting from   n   characters in,   up to the end of the string;   whole string minus the last character;   starting from a known   character   within the string and of   m   length;   starting from a known   substring   within the string and of   m   length. 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
V s = ‘abcdefgh’ V n = 2 V m = 3 V char = ‘d’ V chars = ‘cd’ print(s[n - 1 .+ m]) // starting from n=2 characters in and m=3 in length print(s[n - 1 ..]) // starting from n characters in, up to the end of the string print(s[0 .< (len)-1]) // whole string minus last character print(s[s.index(char) .+ m]) // starting from a known character char="d" within the string and of m length print(s[s.index(chars) .+ m]) // starting from a known substring chars="cd" within the string and of m length
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.
#ALGOL_68
ALGOL 68
MODE AVAIL = [9]BOOL; MODE BOX = [3, 3]CHAR;   FORMAT row fmt = $"|"3(" "3(g" ")"|")l$; FORMAT line = $"+"3(7"-","+")l$; FORMAT puzzle fmt = $f(line)3(3(f(row fmt))f(line))$;   AVAIL gen full = (TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE);   OP REPR = (AVAIL avail)STRING: ( STRING out := ""; FOR i FROM LWB avail TO UPB avail DO IF avail[i] THEN out +:= REPR(ABS "0" + i) FI OD; out );   CHAR empty = "_";   OP -:= = (REF AVAIL set, CHAR index)VOID: ( set[ABS index - ABS "0"]:=FALSE );   # these two functions assume that the number has not already been found # PROC avail slice = (REF[]CHAR slice, REF AVAIL available)REF AVAIL:( FOR ele FROM LWB slice TO UPB slice DO IF slice[ele] /= empty THEN available-:=slice[ele] FI OD; available );   PROC avail box = (INT x, y, REF AVAIL available)REF AVAIL:( # x designates row, y designates column # # get a base index for the boxes # INT bx := x - (x-1) MOD 3; INT by := y - (y-1) MOD 3; REF BOX box = puzzle[bx:bx+2, by:by+2]; FOR i FROM LWB box TO UPB box DO FOR j FROM 2 LWB box TO 2 UPB box DO IF box[i, j] /= empty THEN available-:=box[i, j] FI OD OD; available );   [9, 9]CHAR puzzle; PROC solve = ([,]CHAR in puzzle)VOID:( puzzle := in puzzle; TO UPB puzzle UP 2 DO BOOL done := TRUE; FOR i FROM LWB puzzle TO UPB puzzle DO FOR j FROM 2 LWB puzzle TO 2 UPB puzzle DO CHAR ele := puzzle[i, j]; IF ele = empty THEN # poke at the elements that are "_" # AVAIL remaining := avail box(i, j, avail slice(puzzle[i, ], avail slice(puzzle[, j], LOC AVAIL := gen full))); STRING s = REPR remaining; IF UPB s = 1 THEN puzzle[i, j] := s[LWB s] ELSE done := FALSE FI FI OD OD; IF done THEN break FI OD; break: # write out completed puzzle # printf(($gl$, "Completed puzzle:")); printf((puzzle fmt, puzzle)) ); main:( solve(("394__267_", "___3__4__", "5__69__2_", "_45___9__", "6_______7", "__7___58_", "_1__67__8", "__9__8___", "_264__735")) CO # note: This codes/algorithm does not [yet] solve: # solve(("9__2__5__", "_4__6__3_", "__3_____6", "___9__2__", "____5__8_", "__7__4__3", "7_____1__", "_5__2__4_", "__1__6__9")) END CO )
http://rosettacode.org/wiki/Subleq
Subleq
Subleq is an example of a One-Instruction Set Computer (OISC). It is named after its only instruction, which is SUbtract and Branch if Less than or EQual to zero. Task Your task is to create an interpreter which emulates a SUBLEQ machine. The machine's memory consists of an array of signed integers.   These integers may be interpreted in three ways:   simple numeric values   memory addresses   characters for input or output Any reasonable word size that accommodates all three of the above uses is fine. The program should load the initial contents of the emulated machine's memory, set the instruction pointer to the first address (which is defined to be address 0), and begin emulating the machine, which works as follows:   Let A be the value in the memory location identified by the instruction pointer;   let B and C be the values stored in the next two consecutive addresses in memory.   Advance the instruction pointer three words, to point at the address after the address containing C.   If A is   -1   (negative unity),   then a character is read from the machine's input and its numeric value stored in the address given by B.   C is unused.   If B is   -1   (negative unity),   then the number contained in the address given by A is interpreted as a character and written to the machine's output.   C is unused.   Otherwise, both A and B are treated as addresses.   The number contained in address A is subtracted from the number in address B (and the difference left in address B).   If the result is positive, execution continues uninterrupted; if the result is zero or negative, the number in C becomes the new instruction pointer.   If the instruction pointer becomes negative, execution halts. Your solution may initialize the emulated machine's memory in any convenient manner, but if you accept it as input, it should be a separate input stream from the one fed to the emulated machine once it is running. And if fed as text input, it should be in the form of raw subleq "machine code" - whitespace-separated decimal numbers, with no symbolic names or other assembly-level extensions, to be loaded into memory starting at address   0   (zero). For purposes of this task, show the output of your solution when fed the below   "Hello, world!"   program. As written, this example assumes ASCII or a superset of it, such as any of the Latin-N character sets or Unicode;   you may translate the numbers representing characters (starting with 72=ASCII 'H') into another character set if your implementation runs in a non-ASCII-compatible environment. If 0 is not an appropriate terminator in your character set, the program logic will need some adjustment as well. 15 17 -1 17 -1 -1 16 1 -1 16 3 -1 15 15 0 0 -1 72 101 108 108 111 44 32 119 111 114 108 100 33 10 0 The above "machine code" corresponds to something like this in a hypothetical assembler language for a signed 8-bit version of the machine: start: 0f 11 ff subleq (zero), (message), -1 11 ff ff subleq (message), -1, -1  ; output character at message 10 01 ff subleq (neg1), (start+1), -1 10 03 ff subleq (neg1), (start+3), -1 0f 0f 00 subleq (zero), (zero), start ; useful constants zero: 00 .data 0 neg1: ff .data -1 ; the message to print message: .data "Hello, world!\n\0" 48 65 6c 6c 6f 2c 20 77 6f 72 6c 64 21 0a 00
#Ada
Ada
with Ada.Text_IO;   procedure Subleq is   Storage_Size: constant Positive := 2**8; -- increase or decrease memory Steps: Natural := 999; -- "emergency exit" to stop endless loops   subtype Address is Integer range -1 .. (Storage_Size-1); subtype Memory_Location is Address range 0 .. Address'Last;   type Storage is array(Memory_Location) of Integer;   package TIO renames Ada.Text_IO; package IIO is new TIO.Integer_IO(Integer);   procedure Read_Program(Mem: out Storage) is Idx: Memory_Location := 0; begin while not TIO.End_Of_Line loop IIO.Get(Mem(Idx)); Idx := Idx + 1; end loop; exception when others => TIO.Put_Line("Reading program: Something went wrong!"); end Read_Program;   procedure Execute_Program(Mem: in out Storage) is PC: Integer := 0; -- program counter function Source return Integer is (Mem(PC)); function Dest return Integer is (Mem(PC+1)); function Branch return Integer is (Mem(PC+2)); function Next return Integer is (PC+3); begin while PC >= 0 and Steps >= 0 loop Steps := Steps -1; if Source = -1 then -- read input declare Char: Character; begin TIO.Get (Char); Mem(Dest) := Character'Pos (Char); end; PC := Next; elsif Dest = -1 then -- write output TIO.Put(Character'Val(Mem(Source))); PC := Next; else -- subtract and branch if less or equal Mem(Dest) := Mem(Dest) - Mem(Source); if Mem(Dest) <= 0 then PC := Branch; else PC := Next; end if; end if; end loop; TIO.Put_Line(if PC >= 0 then "Emergency exit: program stopped!" else ""); exception when others => TIO.Put_Line("Failure when executing Program"); end Execute_Program;   Memory: Storage := (others => 0); -- no initial "junk" in memory!   begin   Read_Program(Memory); Execute_Program(Memory);   end Subleq;
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
#C.2B.2B
C++
#include <iostream> #include <cstdint> #include <vector> #include "prime_sieve.hpp"   using integer = uint32_t; using vector = std::vector<integer>;   void print_vector(const vector& vec) { if (!vec.empty()) { auto i = vec.begin(); std::cout << '(' << *i; for (++i; i != vec.end(); ++i) std::cout << ", " << *i; std::cout << ')'; } }   class diffs { public: diffs(std::initializer_list<integer> list) : diffs_(list) {} diffs(const vector& vec) : diffs_(vec) {} void test_group(const vector&); size_t size() const { return diffs_.size(); } void print(std::ostream&); private: vector diffs_; vector first_; vector last_; integer count_ = 0; };   void diffs::test_group(const vector& vec) { if (vec.size() < size() + 1) return; size_t start = vec.size() - size() - 1; for (size_t i = 0, j = start + 1; i < size(); ++i, ++j) { if (vec[j] - vec[j - 1] != diffs_[i]) return; } vector group(vec.begin() + start, vec.end()); if (count_ == 0) first_ = group; last_ = group; ++count_; }   void diffs::print(std::ostream& out) { print_vector(diffs_); out << ": first group = "; print_vector(first_); out << ", last group = "; print_vector(last_); out << ", count = " << count_ << '\n'; }   int main() { const integer limit = 1000000; const size_t max_group_size = 4; prime_sieve sieve(limit); diffs d[] = { {2}, {1}, {2, 2}, {2, 4}, {4, 2}, {6, 4, 2} }; vector group; for (integer p = 0; p < limit; ++p) { if (!sieve.is_prime(p)) continue; if (group.size() >= max_group_size) group.erase(group.begin()); group.push_back(p); for (auto&& diff : d) { diff.test_group(group); } } for (auto&& diff : d) { diff.print(std::cout); } return 0; }
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
#Arturo
Arturo
knight: "knight" socks: "socks" brooms: "brooms"   print drop knight 1 ; strip first character print slice knight 1 (size knight)-1 ; alternate way to strip first character   print chop socks ; strip last character print take socks (size socks)-1 ; alternate way to strip last character print slice socks 0 (size socks)-2 ; yet another way to strip last character   print chop drop brooms 1 ; strip both first and last characters print slice brooms 1 (size brooms)-2 ; alternate way to strip both first and last 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.
#Common_Lisp
Common Lisp
(defun sub-rand (state) (let ((x (last state)) (y (last state 25))) ;; I take "circular buffer" very seriously (until some guru ;; points out it's utterly wrong thing to do) (setf (cdr x) state) (lambda () (setf x (cdr x) y (cdr y) (car x) (mod (- (car x) (car y)) (expt 10 9))))))   ;; returns an RNG with Bentley seeding (defun bentley-clever (seed) (let ((s (list 1 seed)) f) (dotimes (i 53) (push (mod (- (cadr s) (car s)) (expt 10 9)) s)) (setf f (sub-rand (loop for i from 1 to 55 collect (elt s (- 54 (mod (* 34 i) 55)))))) (dotimes (x 165) (funcall f)) f))   ;; test it (output same as everyone else's) (let ((f (bentley-clever 292929))) (dotimes (x 10) (format t "~a~%" (funcall f))))
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
#Lua
Lua
-- Generate a random substitution cipher for ASCII characters 65 to 122 function randomCipher () local cipher, rnd = {plain = {}, encoded = {}} for ascii = 65, 122 do table.insert(cipher.plain, string.char(ascii)) table.insert(cipher.encoded, string.char(ascii)) end for i = 1, #cipher.encoded do rnd = math.random(#cipher.encoded) cipher.encoded[i], cipher.encoded[rnd] = cipher.encoded[rnd], cipher.encoded[i] end return cipher end   -- Encipher text using cipher. Decipher if decode is true. function encode (text, cipher, decode) local output, letter, found, source, dest = "" if decode then source, dest = cipher.encoded, cipher.plain else source, dest = cipher.plain, cipher.encoded end for pos = 1, #text do letter = text:sub(pos, pos) found = false for k, v in pairs(source) do if letter == v then output = output .. dest[k] found = true break end end if not found then output = output .. letter end end return output end   -- Main procedure math.randomseed(os.time()) local subCipher = randomCipher() print("Cipher generated:") print("\tPlain:", table.concat(subCipher.plain)) print("\tCoded:", table.concat(subCipher.encoded)) local inFile = io.open("C:\\ulua\\taskDescription.txt", "r") local input = inFile:read("*all") inFile:close() local encoded = encode(input, subCipher) print("\nEncoded file contents:") print("\t" .. encoded) print("\nAbove text deciphers to: ") print("\t" .. encode(encoded, subCipher, true))
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.
#D
D
import std.stdio;   void main() { immutable array = [1, 2, 3, 4, 5];   int sum = 0; int prod = 1;   foreach (x; array) { sum += x; prod *= x; }   writeln("Sum: ", sum); writeln("Product: ", prod); }
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.
#Crystal
Crystal
puts (1..1000).sum{ |x| 1.0 / x ** 2 } puts (1..5000).sum{ |x| 1.0 / x ** 2 } puts (1..9999).sum{ |x| 1.0 / x ** 2 } puts Math::PI ** 2 / 6
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).
#Java
Java
/* * RossetaCode: Sum to 100, Java 8. * * Find solutions to the "sum to one hundred" puzzle. */ package rosettacode;   import java.io.PrintStream; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set;   public class SumTo100 implements Runnable {   public static void main(String[] args) { new SumTo100().run(); }   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(); } } }   void comment(String commentString) { System.out.println(); System.out.println(commentString); System.out.println(); }   @Override public void run() { final Stat stat = new Stat();   comment("Show all solutions that sum to 100"); final int givenSum = 100; print(givenSum);   comment("Show the sum that has the maximum number of solutions"); final int maxCount = Collections.max(stat.sumCount.keySet()); int maxSum; Iterator<Integer> it = stat.sumCount.get(maxCount).iterator(); do { maxSum = it.next(); } while (maxSum < 0); System.out.println(maxSum + " has " + maxCount + " solutions");   comment("Show the lowest positive number that can't be expressed"); int value = 0; while (stat.countSum.containsKey(value)) { value++; } System.out.println(value);   comment("Show the ten highest numbers that can be expressed"); final int n = stat.countSum.keySet().size(); final Integer[] sums = stat.countSum.keySet().toArray(new Integer[n]); Arrays.sort(sums); for (int i = n - 1; i >= n - 10; i--) { print(sums[i]); } }   private static class Expression {   private final static int NUMBER_OF_DIGITS = 9; private final static byte ADD = 0; private final static byte SUB = 1; private final static byte JOIN = 2;   final byte[] code = new byte[NUMBER_OF_DIGITS]; final static int NUMBER_OF_EXPRESSIONS = 2 * 3 * 3 * 3 * 3 * 3 * 3 * 3 * 3;   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; } } return value + sign * number; }   @Override public String toString() { StringBuilder s = new StringBuilder(2 * NUMBER_OF_DIGITS + 1); for (int digit = 1; digit <= NUMBER_OF_DIGITS; digit++) { switch (code[NUMBER_OF_DIGITS - digit]) { case ADD: if (digit > 1) { s.append('+'); } break; case SUB: s.append('-'); break; } s.append(digit); } return s.toString(); }   void print() { print(System.out); }   void print(PrintStream printStream) { printStream.format("%9d", this.toInt()); printStream.println(" = " + this); } }   private static class Stat {   final Map<Integer, Integer> countSum = new HashMap<>(); final Map<Integer, Set<Integer>> sumCount = new HashMap<>();   Stat() { Expression expression = new Expression(); for (int i = 0; i < Expression.NUMBER_OF_EXPRESSIONS; i++, expression.next()) { int sum = expression.toInt(); countSum.put(sum, countSum.getOrDefault(sum, 0) + 1); } for (Map.Entry<Integer, Integer> entry : countSum.entrySet()) { Set<Integer> set; if (sumCount.containsKey(entry.getValue())) { set = sumCount.get(entry.getValue()); } else { set = new HashSet<>(); } set.add(entry.getKey()); sumCount.put(entry.getValue(), 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.
#EchoLisp
EchoLisp
  (lib 'math) ;; divides? (lib 'sequences) ;; sum/when   (define (task n (k 3) (p 5 )) (when (!= (gcd k p) 1) (error "expected coprimes" (list k p))) (- (+ (sum/mults n k) (sum/mults n p)) ;; add multiples of k , multiples of p (sum/mults n (* k p)))) ;; remove multiples of k * p   ;; using sequences ;; sum of multiples of k < n   (define (sum/mults n k) (sum/when (rcurry divides? k) [1 .. n]))   (task 1000 3 5) → 233168   ;; using simple arithmetic - 🎩 young Gauss formula ;; sum of multiples of k < n = ;; k*m*(m+1)/2 where m = floor(n/k) (lib 'bigint)   (define (sum/mults n k) (set! n (quotient (1- n) k)) (/ (* k n (1+ n )) 2))   (task 1e20 3 5) → 2333333333333333333316666666666666666668   (task 1000 42 666) ❌ error: expected coprimes (42 666)    
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
#Elixir
Elixir
defmodule RC do def sumDigits(n, base\\10) def sumDigits(n, base) when is_integer(n) do Integer.digits(n, base) |> Enum.sum end def sumDigits(n, base) when is_binary(n) do String.codepoints(n) |> Enum.map(&String.to_integer(&1, base)) |> Enum.sum end end   Enum.each([{1, 10}, {1234, 10}, {0xfe, 16}, {0xf0e, 16}], fn {n,base} -> IO.puts "#{Integer.to_string(n,base)}(#{base}) sums to #{ RC.sumDigits(n,base) }" end) IO.puts "" Enum.each([{"1", 10}, {"1234", 10}, {"fe", 16}, {"f0e", 16}], fn {n,base} -> IO.puts "#{n}(#{base}) sums to #{ RC.sumDigits(n,base) }" end)
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
#FALSE
FALSE
  0 3 1 4 1 5 9$*\ [$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
#Fantom
Fantom
  class SumSquares { static Int sumSquares (Int[] numbers) { Int sum := 0 numbers.each |n| { sum += n * n } return sum }   public static Void main () { Int[] n := [,] echo ("Sum of squares of $n = ${sumSquares(n)}") n = [1,2,3,4,5] echo ("Sum of squares of $n = ${sumSquares(n)}") } }  
http://rosettacode.org/wiki/Strong_and_weak_primes
Strong and weak primes
Definitions   (as per number theory)   The   prime(p)   is the   pth   prime.   prime(1)   is   2   prime(4)   is   7   A   strong   prime   is when     prime(p)   is   >   [prime(p-1) + prime(p+1)] ÷ 2   A     weak    prime   is when     prime(p)   is   <   [prime(p-1) + prime(p+1)] ÷ 2 Note that the definition for   strong primes   is different when used in the context of   cryptography. Task   Find and display (on one line) the first   36   strong primes.   Find and display the   count   of the strong primes below   1,000,000.   Find and display the   count   of the strong primes below 10,000,000.   Find and display (on one line) the first   37   weak primes.   Find and display the   count   of the weak primes below   1,000,000.   Find and display the   count   of the weak primes below 10,000,000.   (Optional)   display the   counts   and   "below numbers"   with commas. Show all output here. Related Task   Safe primes and unsafe primes. Also see   The OEIS article A051634: strong primes.   The OEIS article A051635: weak primes.
#AWK
AWK
  # syntax: GAWK -f STRONG_AND_WEAK_PRIMES.AWK BEGIN { for (i=1; i<1E7; i++) { if (is_prime(i)) { arr[++n] = i } } # strong: stop1 = 36 ; stop2 = 1E6 ; stop3 = 1E7 count1 = count2 = count3 = 0 printf("The first %d strong primes:",stop1) for (i=2; count1<stop1; i++) { if (arr[i] > (arr[i-1] + arr[i+1]) / 2) { count1++ printf(" %d",arr[i]) } } printf("\n") for (i=2; i<stop3; i++) { if (arr[i] > (arr[i-1] + arr[i+1]) / 2) { count3++ if (arr[i] < stop2) { count2++ } } } printf("Number below %d: %d\n",stop2,count2) printf("Number below %d: %d\n",stop3,count3) # weak: stop1 = 37 ; stop2 = 1E6 ; stop3 = 1E7 count1 = count2 = count3 = 0 printf("The first %d weak primes:",stop1) for (i=2; count1<stop1; i++) { if (arr[i] < (arr[i-1] + arr[i+1]) / 2) { count1++ printf(" %d",arr[i]) } } printf("\n") for (i=2; i<stop3; i++) { if (arr[i] < (arr[i-1] + arr[i+1]) / 2) { count3++ if (arr[i] < stop2) { count2++ } } } printf("Number below %d: %d\n",stop2,count2) printf("Number below %d: %d\n",stop3,count3) exit(0) } function is_prime(n, d) { d = 5 if (n < 2) { return(0) } if (n % 2 == 0) { return(n == 2) } if (n % 3 == 0) { return(n == 3) } while (d*d <= n) { if (n % d == 0) { return(0) } d += 2 if (n % d == 0) { return(0) } d += 4 } return(1) }  
http://rosettacode.org/wiki/Substring
Substring
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Display a substring:   starting from   n   characters in and of   m   length;   starting from   n   characters in,   up to the end of the string;   whole string minus the last character;   starting from a known   character   within the string and of   m   length;   starting from a known   substring   within the string and of   m   length. 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
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program subString64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesARM64.inc"   /*******************************************/ /* Initialized data */ /*******************************************/ .data szMessString: .asciz "Result : " szString1: .asciz "abcdefghijklmnopqrstuvwxyz" szStringStart: .asciz "abcdefg" szCarriageReturn: .asciz "\n" /*******************************************/ /* UnInitialized data */ /*******************************************/ .bss szSubString: .skip 500 // buffer result   /*******************************************/ /* code section */ /*******************************************/ .text .global main main:   ldr x0,qAdrszString1 // address input string ldr x1,qAdrszSubString // address output string mov x2,22 // location mov x3,4 // length bl subStringNbChar // starting from n characters in and of m length ldr x0,qAdrszMessString // display message bl affichageMess ldr x0,qAdrszSubString // display substring result bl affichageMess ldr x0,qAdrszCarriageReturn // display line return bl affichageMess // ldr x0,qAdrszString1 ldr x1,qAdrszSubString mov x2,15 // location bl subStringEnd //starting from n characters in, up to the end of the string ldr x0,qAdrszMessString // display message bl affichageMess ldr x0,qAdrszSubString bl affichageMess ldr x0,qAdrszCarriageReturn // display line return bl affichageMess // ldr x0,qAdrszString1 ldr x1,qAdrszSubString bl subStringMinus // whole string minus last character ldr x0,qAdrszMessString // display message bl affichageMess ldr x0,qAdrszSubString bl affichageMess ldr x0,qAdrszCarriageReturn // display line return bl affichageMess // ldr x0,qAdrszString1 ldr x1,qAdrszSubString mov x2,'c' // start character mov x3,5 // length bl subStringStChar //starting from a known character within the string and of m length cmp x0,-1 // error ? beq 2f ldr x0,qAdrszMessString // display message bl affichageMess ldr x0,qAdrszSubString bl affichageMess ldr x0,qAdrszCarriageReturn // display line return bl affichageMess // 2: ldr x0,qAdrszString1 ldr x1,qAdrszSubString ldr x2,qAdrszStringStart // sub string to start mov x3,10 // length bl subStringStString // starting from a known substring within the string and of m length cmp x0,-1 // error ? beq 3f ldr x0,qAdrszMessString // display message bl affichageMess ldr x0,qAdrszSubString bl affichageMess ldr x0,qAdrszCarriageReturn // display line return bl affichageMess 3: 100: // standard end of the program mov x0,0 // return code mov x8,EXIT // request to exit program svc 0 // perform system call qAdrszMessString: .quad szMessString qAdrszString1: .quad szString1 qAdrszSubString: .quad szSubString qAdrszStringStart: .quad szStringStart qAdrszCarriageReturn: .quad szCarriageReturn /******************************************************************/ /* sub strings index start number of characters */ /******************************************************************/ /* x0 contains the address of the input string */ /* x1 contains the address of the output string */ /* x2 contains the start index */ /* x3 contains numbers of characters to extract */ /* x0 returns number of characters or -1 if error */ subStringNbChar: stp x1,lr,[sp,-16]! // save registers mov x14,#0 // counter byte output string 1: ldrb w15,[x0,x2] // load byte string input cbz x15,2f // zero final ? strb w15,[x1,x14] // store byte output string add x2,x2,1 // increment counter add x14,x14,1 cmp x14,x3 // end ? blt 1b // no -> loop 2: strb wzr,[x1,x14] // store final zero byte string 2 mov x0,x14 100: ldp x1,lr,[sp],16 // restaur 2 registers ret // return to address lr x30 /******************************************************************/ /* sub strings index start at end of string */ /******************************************************************/ /* x0 contains the address of the input string */ /* x1 contains the address of the output string */ /* x2 contains the start index */ /* x0 returns number of characters or -1 if error */ subStringEnd: stp x2,lr,[sp,-16]! // save registers mov x14,0 // counter byte output string 1: ldrb w15,[x0,x2] // load byte string 1 cbz x15,2f // zero final ? strb w15,[x1,x14] add x2,x2,1 add x14,x14,1 b 1b // loop 2: strb wzr,[x1,x14] // store final zero byte string 2 mov x0,x14 100:   ldp x2,lr,[sp],16 // restaur 2 registers ret // return to address lr x30 /******************************************************************/ /* whole string minus last character */ /******************************************************************/ /* x0 contains the address of the input string */ /* x1 contains the address of the output string */ /* x0 returns number of characters or -1 if error */ subStringMinus: stp x1,lr,[sp,-16]! // save registers mov x12,0 // counter byte input string mov x14,0 // counter byte output string 1: ldrb w15,[x0,x12] // load byte string cbz x15,2f // zero final ? strb w15,[x1,x14] add x12,x12,1 add x14,x14,1 b 1b // loop 2: sub x14,x14,1 strb wzr,[x1,x14] // store final zero byte string 2 mov x0,x14 100: ldp x1,lr,[sp],16 // restaur 2 registers ret // return to address lr x30 /******************************************************************/ /* starting from a known character within the string and of m length */ /******************************************************************/ /* x0 contains the address of the input string */ /* x1 contains the address of the output string */ /* x2 contains the character */ /* x3 contains the length /* x0 returns number of characters or -1 if error */ subStringStChar: stp x1,lr,[sp,-16]! // save registers mov x16,0 // counter byte input string mov x14,0 // counter byte output string 1: ldrb w15,[x0,x16] // load byte string cbz x15,4f // zero final ? cmp x15,x2 // character find ? beq 2f // yes add x16,x16,1 // no -> increment indice b 1b // loop 2: strb w15,[x1,x14] add x16,x16,1 add x14,x14,1 cmp x14,x3 bge 3f ldrb w15,[x0,x16] // load byte string cbnz x15,2b // loop if no zero final 3: strb wzr,[x1,x14] // store final zero byte string 2 mov x0,x14 b 100f 4: strb w15,[x1,x14] mov x0,#-1 100: ldp x1,lr,[sp],16 // restaur 2 registers ret // return to address lr x30 /******************************************************************/ /* starting from a known substring within the string and of m length */ /******************************************************************/ /* x0 contains the address of the input string */ /* x1 contains the address of the output string */ /* x2 contains the address of string to start */ /* x3 contains the length /* x0 returns number of characters or -1 if error */ subStringStString: stp x1,lr,[sp,-16]! // save registers stp x20,x21,[sp,-16]! // save registers mov x20,x0 // save address mov x21,x1 // save address output string mov x1,x2 bl searchSubString cmp x0,-1 // not found ? beq 100f mov x16,x0 // counter byte input string mov x14,0 1: ldrb w15,[x20,x16] // load byte string strb w15,[x21,x14] cmp x15,#0 // zero final ? csel x0,x14,x0,eq beq 100f add x14,x14,1 cmp x14,x3 add x15,x16,1 csel x16,x15,x16,lt blt 1b // loop strb wzr,[x21,x14] mov x0,x14 // return indice 100: ldp x20,x21,[sp],16 // restaur 2 registers ldp x1,lr,[sp],16 // restaur 2 registers ret // return to address lr x30 /******************************************************************/ /* search a substring in the string */ /******************************************************************/ /* x0 contains the address of the input string */ /* x1 contains the address of substring */ /* x0 returns index of substring in string or -1 if not found */ searchSubString: stp x1,lr,[sp,-16]! // save registers mov x12,0 // counter byte input string mov x13,0 // counter byte string mov x16,-1 // index found ldrb w14,[x1,x13] 1: ldrb w15,[x0,x12] // load byte string cbz x15,4f // zero final ? cmp x15,x14 // compare character beq 2f mov x16,-1 // no equals - > raz index mov x13,0 // and raz counter byte add x12,x12,1 // and increment counter byte b 1b // and loop 2: // characters equals cmp x16,-1 // first characters equals ? csel x16,x12,x16,eq // moveq x6,x2 // yes -> index begin in x6 add x13,x13,1 // increment counter substring ldrb w14,[x1,x13] // and load next byte cbz x14,3f // zero final ? yes -> end search add x12,x12,1 // else increment counter string b 1b // and loop 3: mov x0,x16 // return indice b 100f 4: mov x0,#-1 // yes returns error 100: ldp x1,lr,[sp],16 // restaur 2 registers ret // return to address lr x30 /********************************************************/ /* File Include fonctions */ /********************************************************/ /* for this file see task include a file in language AArch64 assembly */ .include "../includeARM64.inc"  
http://rosettacode.org/wiki/Substring
Substring
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Display a substring:   starting from   n   characters in and of   m   length;   starting from   n   characters in,   up to the end of the string;   whole string minus the last character;   starting from a known   character   within the string and of   m   length;   starting from a known   substring   within the string and of   m   length. 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!
BYTE FUNC FindC(CHAR ARRAY text CHAR c) BYTE i   i=1 WHILE i<=text(0) DO IF text(i)=c THEN RETURN (i) FI i==+1 OD RETURN (0)   BYTE FUNC FindS(CHAR ARRAY text,sub) BYTE i,j,found   i=1 WHILE i<=text(0)-sub(0)+1 DO found=0 FOR j=1 TO sub(0) DO IF text(i+j-1)#sub(j) THEN found=0 EXIT ELSE found=1 FI OD IF found THEN RETURN (i) FI i==+1 OD RETURN (0)   PROC Main() CHAR ARRAY text="qwertyuiop" CHAR ARRAY sub="tyu" CHAR ARRAY res(20) BYTE n,m CHAR c   PrintF("Original string:%E ""%S""%E%E",text)   n=3 m=5 SCopyS(res,text,n,n+m-1) PrintF("Substring start from %B and length %B:%E ""%S""%E%E",n,m,res)   n=4 SCopyS(res,text,n,text(0)) PrintF("Substring start from %B up to the end:%E ""%S""%E%E",n,res)   SCopyS(res,text,1,text(0)-1) PrintF("Whole string without the last char:%E ""%S""%E%E",res)   c='w m=4 n=FindC(text,c) IF n=0 THEN PrintF("Character '%C' not found in string%E%E",c) ELSE SCopyS(res,text,n,n+m-1) PrintF("Substring start from '%C' and len %B:%E ""%S""%E%E",c,m,res) FI   n=FindS(text,sub) m=6 IF n=0 THEN PrintF("String ""%S"" not found in string%E%E",sub) ELSE SCopyS(res,text,n,n+m-1) PrintF("Substring start from '%S' and len %B: ""%S""%E%E",sub,m,res) FI RETURN
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.
#AutoHotkey
AutoHotkey
#SingleInstance, Force SetBatchLines, -1 SetTitleMatchMode, 3   Loop 9 { r := A_Index, y := r*17-8 + (A_Index >= 7 ? 4 : A_Index >= 4 ? 2 : 0) Loop 9 { c := A_Index, x := c*17+5 + (A_Index >= 7 ? 4 : A_Index >= 4 ? 2 : 0) Gui, Add, Edit, x%x% y%y% w17 h17 v%r%_%c% Center Number Limit1 gNext } } Gui, Add, Button, vButton gSolve w175 x10 Center, Solve Gui, Add, Text, vMsg r3, Enter Sudoku puzzle and click Solve Gui, Show,, Sudoku Solver Return   Solve: Gui, Submit, NoHide Loop 9 { r := A_Index Loop 9 If (%r%_%A_Index% = "") puzzle .= "@" Else puzzle .= %r%_%A_Index% } s := A_TickCount answer := Sudoku(puzzle) iterations := ErrorLevel e := A_TickCount seconds := (e-s)/1000 StringSplit, a, answer, | Loop 9 { r := A_Index Loop 9 { b := (r*9)+A_Index-9 GuiControl,, %r%_%A_Index%, % a%b% GuiControl, +ReadOnly, %r%_%A_Index% } } if answer GuiControl,, Msg, Solved!`nTime: %seconds%s`nIterations: %iterations% else GuiControl,, Msg, Failed! :(`nTime: %seconds%s`nIterations: %iterations% GuiControl,, Button, Again! GuiControl, +gAgain, Button return   GuiClose: ExitApp   Again: Reload   #IfWinActive, Sudoku Solver ~*Enter::GoSub % GetKeyState( "Shift", "P" ) ? "~Up" : "~Down" ~Up:: GuiControlGet, f, focus StringTrimLeft, f, f, 4 f := ((f >= 1 && f <= 9) ? f+72 : f-9) GuiControl, Focus, Edit%f% return ~Down:: GuiControlGet, f, focus StringTrimLeft, f, f, 4 f := ((f >= 73 && f <= 81) ? f-72 : f + 9) GuiControl, Focus, Edit%f% return ~Left:: GuiControlGet, f, focus StringTrimLeft, f, f, 4 f := Mod(f + 79, 81) + 1 GuiControl, Focus, Edit%f% return Next: ~Right:: GuiControlGet, f, focus StringTrimLeft, f, f, 4 f := Mod(f, 81) + 1 GuiControl, Focus, Edit%f% return #IfWinActive   ; Functions Start here   Sudoku( p ) { ;ErrorLevel contains the number of iterations p := RegExReplace(p, "[^1-9@]"), ErrorLevel := 0 ;format puzzle as single line string return Sudoku_Display(Sudoku_Solve(p)) }   Sudoku_Solve( p, d = 0 ) { ;d is 0-based ; http://www.autohotkey.com/forum/topic46679.html ; p: 81 character puzzle string ; (concat all 9 rows of 9 chars each) ; givens represented as chars 1-9 ; fill-ins as any non-null, non 1-9 char ; d: used internally. omit on initial call ; ; returns: 81 char string with non-givens replaced with valid solution ; If (d >= 81), ErrorLevel++ return p ;this is 82nd iteration, so it has successfully finished iteration 81 If InStr( "123456789", SubStr(p, d+1, 1) ) ;this depth is a given, skip through return Sudoku_Solve(p, d+1) m := Sudoku_Constraints(p,d) ;a string of this level's constraints. ; (these will not change for all 9 loops) Loop 9 { If InStr(m, A_Index) Continue NumPut(Asc(A_Index), p, d, "Char") If r := Sudoku_Solve(p, d+1) return r } return 0 }   Sudoku_Constraints( ByRef p, d ) { ; returns a string of the constraints for a particular position c := Mod(d,9) , r := (d - c) // 9 , b := r//3*27 + c//3*3 + 1 ;convert to 1-based , c++ return "" ; row: . SubStr(p, r * 9 + 1, 9) ; column: . SubStr(p,c ,1) SubStr(p,c+9 ,1) SubStr(p,c+18,1) . SubStr(p,c+27,1) SubStr(p,c+36,1) SubStr(p,c+45,1) . SubStr(p,c+54,1) SubStr(p,c+63,1) SubStr(p,c+72,1) ;box . SubStr(p, b, 3) SubStr(p, b+9, 3) SubStr(p, b+18, 3) }   Sudoku_Display( p ) { If StrLen(p) = 81 loop 81 r .= SubStr(p, A_Index, 1) . "|" return r }
http://rosettacode.org/wiki/Subleq
Subleq
Subleq is an example of a One-Instruction Set Computer (OISC). It is named after its only instruction, which is SUbtract and Branch if Less than or EQual to zero. Task Your task is to create an interpreter which emulates a SUBLEQ machine. The machine's memory consists of an array of signed integers.   These integers may be interpreted in three ways:   simple numeric values   memory addresses   characters for input or output Any reasonable word size that accommodates all three of the above uses is fine. The program should load the initial contents of the emulated machine's memory, set the instruction pointer to the first address (which is defined to be address 0), and begin emulating the machine, which works as follows:   Let A be the value in the memory location identified by the instruction pointer;   let B and C be the values stored in the next two consecutive addresses in memory.   Advance the instruction pointer three words, to point at the address after the address containing C.   If A is   -1   (negative unity),   then a character is read from the machine's input and its numeric value stored in the address given by B.   C is unused.   If B is   -1   (negative unity),   then the number contained in the address given by A is interpreted as a character and written to the machine's output.   C is unused.   Otherwise, both A and B are treated as addresses.   The number contained in address A is subtracted from the number in address B (and the difference left in address B).   If the result is positive, execution continues uninterrupted; if the result is zero or negative, the number in C becomes the new instruction pointer.   If the instruction pointer becomes negative, execution halts. Your solution may initialize the emulated machine's memory in any convenient manner, but if you accept it as input, it should be a separate input stream from the one fed to the emulated machine once it is running. And if fed as text input, it should be in the form of raw subleq "machine code" - whitespace-separated decimal numbers, with no symbolic names or other assembly-level extensions, to be loaded into memory starting at address   0   (zero). For purposes of this task, show the output of your solution when fed the below   "Hello, world!"   program. As written, this example assumes ASCII or a superset of it, such as any of the Latin-N character sets or Unicode;   you may translate the numbers representing characters (starting with 72=ASCII 'H') into another character set if your implementation runs in a non-ASCII-compatible environment. If 0 is not an appropriate terminator in your character set, the program logic will need some adjustment as well. 15 17 -1 17 -1 -1 16 1 -1 16 3 -1 15 15 0 0 -1 72 101 108 108 111 44 32 119 111 114 108 100 33 10 0 The above "machine code" corresponds to something like this in a hypothetical assembler language for a signed 8-bit version of the machine: start: 0f 11 ff subleq (zero), (message), -1 11 ff ff subleq (message), -1, -1  ; output character at message 10 01 ff subleq (neg1), (start+1), -1 10 03 ff subleq (neg1), (start+3), -1 0f 0f 00 subleq (zero), (zero), start ; useful constants zero: 00 .data 0 neg1: ff .data -1 ; the message to print message: .data "Hello, world!\n\0" 48 65 6c 6c 6f 2c 20 77 6f 72 6c 64 21 0a 00
#ALGOL_68
ALGOL 68
# Subleq program interpreter # # executes the program specified in code, stops when the instruction pointer # # becomes negative # PROC run subleq = ( []INT code )VOID: BEGIN INT max memory = 3 * 1024; [ 0 : max memory - 1 ]INT memory; # load the program into memory # # a slice yields a row with LWB 1... # memory[ 0 : UPB code - LWB code ] := code[ AT 1 ]; # start at instruction 0 # INT ip := 0; # execute the instructions until ip is < 0 # WHILE ip >= 0 DO # get three words at ip and advance ip past them # INT a := memory[ ip ]; INT b := memory[ ip + 1 ]; INT c := memory[ ip + 2 ]; ip +:= 3; # execute according to a, b and c # IF a = -1 THEN # input a character to b # CHAR input; get( stand in, ( input ) ); memory[ b ] := ABS input ELIF b = -1 THEN # output character from a # print( ( REPR memory[ a ] ) ) ELSE # subtract and branch if le 0 # memory[ b ] -:= memory[ a ]; IF memory[ b ] <= 0 THEN ip := c FI FI OD END # run subleq # ;   # test the interpreter with the hello-world program specified in the task # run subleq( ( 15, 17, -1, 17, -1, -1 , 16, 1, -1, 16, 3, -1 , 15, 15, 0, 0, -1, 72 , 101, 108, 108, 111, 44, 32 , 119, 111, 114, 108, 100, 33 , 10, 0 ) )  
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
#D
D
import std.algorithm; import std.array; import std.range; import std.stdio;   immutable PRIMES = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091, 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151, 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213, 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277, 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307, 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399, 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451, 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, 1499, 1511, 1523, 1531, 1543, 1549, 1553, 1559, 1567, 1571, 1579, 1583, 1597, 1601, 1607, 1609, 1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667, 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733, 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789, 1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871, 1873, 1877, 1879, 1889, 1901, 1907, 1913, 1931, 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997, 1999, 2003, 2011, 2017, 2027, 2029, 2039, 2053, 2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111, 2113, 2129, 2131, 2137, 2141, 2143, 2153, 2161, 2179, 2203, 2207, 2213, 2221, 2237, 2239, 2243, 2251, 2267, 2269, 2273, 2281, 2287, 2293, 2297, 2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357, 2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411, 2417, 2423, 2437, 2441, 2447, 2459, 2467, 2473, 2477, 2503, 2521, 2531, 2539, 2543, 2549, 2551, 2557, 2579, 2591, 2593, 2609, 2617, 2621, 2633, 2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687, 2689, 2693, 2699, 2707, 2711, 2713, 2719, 2729, 2731, 2741, 2749, 2753, 2767, 2777, 2789, 2791, 2797, 2801, 2803, 2819, 2833, 2837, 2843, 2851, 2857, 2861, 2879, 2887, 2897, 2903, 2909, 2917, 2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999, 3001, 3011, 3019, 3023, 3037, 3041, 3049, 3061, 3067, 3079, 3083, 3089, 3109, 3119, 3121, 3137, 3163, 3167, 3169, 3181, 3187, 3191, 3203, 3209, 3217, 3221, 3229, 3251, 3253, 3257, 3259, 3271, 3299, 3301, 3307, 3313, 3319, 3323, 3329, 3331, 3343, 3347, 3359, 3361, 3371, 3373, 3389, 3391, 3407, 3413, 3433, 3449, 3457, 3461, 3463, 3467, 3469, 3491, 3499, 3511, 3517, 3527, 3529, 3533, 3539, 3541, 3547, 3557, 3559, 3571, 3581, 3583, 3593, 3607, 3613, 3617, 3623, 3631, 3637, 3643, 3659, 3671, 3673, 3677, 3691, 3697, 3701, 3709, 3719, 3727, 3733, 3739, 3761, 3767, 3769, 3779, 3793, 3797, 3803, 3821, 3823, 3833, 3847, 3851, 3853, 3863, 3877, 3881, 3889, 3907, 3911, 3917, 3919, 3923, 3929, 3931, 3943, 3947, 3967, 3989, 4001, 4003, 4007, 4013, 4019, 4021, 4027, 4049, 4051, 4057, 4073, 4079, 4091, 4093, 4099, 4111, 4127, 4129, 4133, 4139, 4153, 4157, 4159, 4177, 4201, 4211, 4217, 4219, 4229, 4231, 4241, 4243, 4253, 4259, 4261, 4271, 4273, 4283, 4289, 4297, 4327, 4337, 4339, 4349, 4357, 4363, 4373, 4391, 4397, 4409, 4421, 4423, 4441, 4447, 4451, 4457, 4463, 4481, 4483, 4493, 4507, 4513, 4517, 4519, 4523, 4547, 4549, 4561, 4567, 4583, 4591, 4597, 4603, 4621, 4637, 4639, 4643, 4649, 4651, 4657, 4663, 4673, 4679, 4691, 4703, 4721, 4723, 4729, 4733, 4751, 4759, 4783, 4787, 4789, 4793, 4799, 4801, 4813, 4817, 4831, 4861, 4871, 4877, 4889, 4903, 4909, 4919, 4931, 4933, 4937, 4943, 4951, 4957, 4967, 4969, 4973, 4987, 4993, 4999, 5003, 5009, 5011, 5021, 5023, 5039, 5051, 5059, 5077, 5081, 5087, 5099, 5101, 5107, 5113, 5119, 5147, 5153, 5167, 5171, 5179, 5189, 5197, 5209, 5227, 5231, 5233, 5237, 5261, 5273, 5279, 5281, 5297, 5303, 5309, 5323, 5333, 5347, 5351, 5381, 5387, 5393, 5399, 5407, 5413, 5417, 5419, 5431, 5437, 5441, 5443, 5449, 5471, 5477, 5479, 5483, 5501, 5503, 5507, 5519, 5521, 5527, 5531, 5557, 5563, 5569, 5573, 5581, 5591, 5623, 5639, 5641, 5647, 5651, 5653, 5657, 5659, 5669, 5683, 5689, 5693, 5701, 5711, 5717, 5737, 5741, 5743, 5749, 5779, 5783, 5791, 5801, 5807, 5813, 5821, 5827, 5839, 5843, 5849, 5851, 5857, 5861, 5867, 5869, 5879, 5881, 5897, 5903, 5923, 5927, 5939, 5953, 5981, 5987, 6007, 6011, 6029, 6037, 6043, 6047, 6053, 6067, 6073, 6079, 6089, 6091, 6101, 6113, 6121, 6131, 6133, 6143, 6151, 6163, 6173, 6197, 6199, 6203, 6211, 6217, 6221, 6229, 6247, 6257, 6263, 6269, 6271, 6277, 6287, 6299, 6301, 6311, 6317, 6323, 6329, 6337, 6343, 6353, 6359, 6361, 6367, 6373, 6379, 6389, 6397, 6421, 6427, 6449, 6451, 6469, 6473, 6481, 6491, 6521, 6529, 6547, 6551, 6553, 6563, 6569, 6571, 6577, 6581, 6599, 6607, 6619, 6637, 6653, 6659, 6661, 6673, 6679, 6689, 6691, 6701, 6703, 6709, 6719, 6733, 6737, 6761, 6763, 6779, 6781, 6791, 6793, 6803, 6823, 6827, 6829, 6833, 6841, 6857, 6863, 6869, 6871, 6883, 6899, 6907, 6911, 6917, 6947, 6949, 6959, 6961, 6967, 6971, 6977, 6983, 6991, 6997, 7001, 7013, 7019, 7027, 7039, 7043, 7057, 7069, 7079, 7103, 7109, 7121, 7127, 7129, 7151, 7159, 7177, 7187, 7193, 7207, 7211, 7213, 7219, 7229, 7237, 7243, 7247, 7253, 7283, 7297, 7307, 7309, 7321, 7331, 7333, 7349, 7351, 7369, 7393, 7411, 7417, 7433, 7451, 7457, 7459, 7477, 7481, 7487, 7489, 7499, 7507, 7517, 7523, 7529, 7537, 7541, 7547, 7549, 7559, 7561, 7573, 7577, 7583, 7589, 7591, 7603, 7607, 7621, 7639, 7643, 7649, 7669, 7673, 7681, 7687, 7691, 7699, 7703, 7717, 7723, 7727, 7741, 7753, 7757, 7759, 7789, 7793, 7817, 7823, 7829, 7841, 7853, 7867, 7873, 7877, 7879, 7883, 7901, 7907, 7919, 7927, 7933, 7937, 7949, 7951, 7963, 7993, 8009, 8011, 8017, 8039, 8053, 8059, 8069, 8081, 8087, 8089, 8093, 8101, 8111, 8117, 8123, 8147, 8161, 8167, 8171, 8179, 8191, 8209, 8219, 8221, 8231, 8233, 8237, 8243, 8263, 8269, 8273, 8287, 8291, 8293, 8297, 8311, 8317, 8329, 8353, 8363, 8369, 8377, 8387, 8389, 8419, 8423, 8429, 8431, 8443, 8447, 8461, 8467, 8501, 8513, 8521, 8527, 8537, 8539, 8543, 8563, 8573, 8581, 8597, 8599, 8609, 8623, 8627, 8629, 8641, 8647, 8663, 8669, 8677, 8681, 8689, 8693, 8699, 8707, 8713, 8719, 8731, 8737, 8741, 8747, 8753, 8761, 8779, 8783, 8803, 8807, 8819, 8821, 8831, 8837, 8839, 8849, 8861, 8863, 8867, 8887, 8893, 8923, 8929, 8933, 8941, 8951, 8963, 8969, 8971, 8999, 9001, 9007, 9011, 9013, 9029, 9041, 9043, 9049, 9059, 9067, 9091, 9103, 9109, 9127, 9133, 9137, 9151, 9157, 9161, 9173, 9181, 9187, 9199, 9203, 9209, 9221, 9227, 9239, 9241, 9257, 9277, 9281, 9283, 9293, 9311, 9319, 9323, 9337, 9341, 9343, 9349, 9371, 9377, 9391, 9397, 9403, 9413, 9419, 9421, 9431, 9433, 9437, 9439, 9461, 9463, 9467, 9473, 9479, 9491, 9497, 9511, 9521, 9533, 9539, 9547, 9551, 9587, 9601, 9613, 9619, 9623, 9629, 9631, 9643, 9649, 9661, 9677, 9679, 9689, 9697, 9719, 9721, 9733, 9739, 9743, 9749, 9767, 9769, 9781, 9787, 9791, 9803, 9811, 9817, 9829, 9833, 9839, 9851, 9857, 9859, 9871, 9883, 9887, 9901, 9907, 9923, 9929, 9931, 9941, 9949, 9967, 9973, ];   bool isPrime(int n) { if (n < 2) { return false; }   foreach (prime; PRIMES) { if (n == prime) { return true; } if (n % prime == 0) { return false; } if (n < prime * prime) { if (n > PRIMES[$-1] * PRIMES[$-1]) { assert(false, "Out of pre-computed primes."); } break; } }   return true; }   int[][] successivePrimes(int[] primes, int[] diffs) { int[][] results; auto dl = diffs.length;   outer: for (int i = 0; i < primes.length - dl; i++) { auto group = uninitializedArray!(int[])(dl + 1); group[0] = primes[i]; for (int j = i; j < i + dl; j++) { if (primes[j + 1] - primes[j] != diffs[j - i]) { continue outer; } group[j - i + 1] = primes[j + 1]; } results ~= group; }   return results; }   void main() { auto primeList = iota(2, 1_000_000).filter!isPrime.array; auto diffsList = [[2], [1], [2, 2], [2, 4], [4, 2], [6, 4, 2]]; writeln("For primes less than 1,000,000:-"); foreach (diffs; diffsList) { writefln(" For differences of %s ->", diffs); auto sp = successivePrimes(primeList, diffs); if (sp.length == 0) { writeln(" No groups found"); continue; } writeln(" First group = ", sp[0]); writeln(" Last group = ", sp[$ - 1]); writeln(" Number found = ", sp.length); 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
#AutoHotkey
AutoHotkey
myString := "knights" MsgBox % SubStr(MyString, 2) MsgBox % SubStr(MyString, 1, StrLen(MyString)-1) MsgBox % SubStr(MyString, 2, StrLen(MyString)-2)
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.
#D
D
import std.stdio;   struct Subtractive { enum MOD = 1_000_000_000; private int[55] state; private int si, sj;   this(in int p1) pure nothrow { subrandSeed(p1); }   void subrandSeed(int p1) pure nothrow { int p2 = 1;   state[0] = p1 % MOD; for (int 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; foreach (i; 0 .. 165) subrand(); }   int subrand() pure nothrow { if (si == sj) subrandSeed(0);   if (!si--) si = 54; if (!sj--) sj = 54;   int x = state[si] - state[sj]; if (x < 0) x += MOD;   return state[si] = x; } }   void main() { auto gen = Subtractive(292_929); foreach (i; 0 .. 10) writeln(gen.subrand()); }
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
#MiniScript
MiniScript
alphabet = "abcdefghijklmnopqrstuvwxyz".split("") cipher = alphabet[0:] cipher.shuffle encode = {} decode = {} for i in alphabet.indexes encode[alphabet[i]] = cipher[i] decode[cipher[i]] = alphabet[i] encode[alphabet[i].upper] = cipher[i].upper decode[cipher[i].upper] = alphabet[i].upper end for   apply = function(map, s) chars = s.split("") for i in chars.indexes if map.hasIndex(chars[i]) then chars[i] = map[chars[i]] end for return chars.join("") end function   msg = "Now is the time for all good men (and women) to come together." secretCode = apply(encode, msg) print secretCode print apply(decode, secretCode)
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
#Nim
Nim
import sequtils, strutils   proc encrypt(key: seq[char]; msg: string): string = result.setLen(msg.len) for i, c in msg: result[i] = key[ord(c) - 32]   proc decrypt(key: seq[char]; msg: string): string = result.setLen(msg.len) for i, c in msg: result[i] = chr(key.find(c) + 32)   when isMainModule:   import random randomize()   # Build a random key. var key = toSeq(32..126).mapIt(chr(it)) # All printable characters. key.shuffle()   const Message = "The quick brown fox jumps over the lazy dog, who barks VERY loudly!" let encrypted = key.encrypt(Message) let decrypted = key.decrypt(encrypted)   echo "Key = “$#”" % key.join() echo "Message = “$#”" % Message echo "Encrypted = “$#”" % encrypted echo "Decrypted = “$#”" % decrypted
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.
#dc
dc
1 3 5 7 9 11 13 0ss1sp[dls+sslp*spz0!=a]dsax[Sum: ]Plsp[Product: ]Plpp Sum: 49 Product: 135135
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.
#D
D
import std.stdio, std.traits;   ReturnType!TF series(TF)(TF func, int end, int start=1) pure nothrow @safe @nogc { typeof(return) sum = 0; foreach (immutable i; start .. end + 1) sum += func(i); return sum; }   void main() { writeln("Sum: ", series((in int n) => 1.0L / (n ^^ 2), 1_000)); }
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).
#JavaScript
JavaScript
(function () { 'use strict';   // GENERIC FUNCTIONS ----------------------------------------------------   // permutationsWithRepetition :: Int -> [a] -> [[a]] var permutationsWithRepetition = function (n, as) { return as.length > 0 ? foldl1(curry(cartesianProduct)(as), replicate(n, as)) : []; };   // cartesianProduct :: [a] -> [b] -> [[a, b]] var cartesianProduct = function (xs, ys) { return [].concat.apply([], xs.map(function (x) { return [].concat.apply([], ys.map(function (y) { return [ [x].concat(y) ]; })); })); };   // curry :: ((a, b) -> c) -> a -> b -> c var curry = function (f) { return function (a) { return function (b) { return f(a, b); }; }; };   // flip :: (a -> b -> c) -> b -> a -> c var flip = function (f) { return function (a, b) { return f.apply(null, [b, a]); }; };   // foldl1 :: (a -> a -> a) -> [a] -> a var foldl1 = function (f, xs) { return xs.length > 0 ? xs.slice(1) .reduce(f, xs[0]) : []; };   // replicate :: Int -> a -> [a] var replicate = function (n, a) { var v = [a], o = []; if (n < 1) return o; while (n > 1) { if (n & 1) o = o.concat(v); n >>= 1; v = v.concat(v); } return o.concat(v); };   // group :: Eq a => [a] -> [[a]] var group = function (xs) { return groupBy(function (a, b) { return a === b; }, xs); };   // groupBy :: (a -> a -> Bool) -> [a] -> [[a]] var groupBy = function (f, xs) { var dct = xs.slice(1) .reduce(function (a, x) { var h = a.active.length > 0 ? a.active[0] : undefined, blnGroup = h !== undefined && f(h, x);   return { active: blnGroup ? a.active.concat(x) : [x], sofar: blnGroup ? a.sofar : a.sofar.concat([a.active]) }; }, { active: xs.length > 0 ? [xs[0]] : [], sofar: [] }); return dct.sofar.concat(dct.active.length > 0 ? [dct.active] : []); };   // compare :: a -> a -> Ordering var compare = function (a, b) { return a < b ? -1 : a > b ? 1 : 0; };   // on :: (b -> b -> c) -> (a -> b) -> a -> a -> c var on = function (f, g) { return function (a, b) { return f(g(a), g(b)); }; };   // nub :: [a] -> [a] var nub = function (xs) { return nubBy(function (a, b) { return a === b; }, xs); };   // nubBy :: (a -> a -> Bool) -> [a] -> [a] var nubBy = function (p, xs) { var x = xs.length ? xs[0] : undefined;   return x !== undefined ? [x].concat(nubBy(p, xs.slice(1) .filter(function (y) { return !p(x, y); }))) : []; };   // find :: (a -> Bool) -> [a] -> Maybe a var find = function (f, xs) { for (var i = 0, lng = xs.length; i < lng; i++) { if (f(xs[i], i)) return xs[i]; } return undefined; };   // Int -> [a] -> [a] var take = function (n, xs) { return xs.slice(0, n); };   // unlines :: [String] -> String var unlines = function (xs) { return xs.join('\n'); };   // show :: a -> String var show = function (x) { return JSON.stringify(x); }; //, null, 2);   // head :: [a] -> a var head = function (xs) { return xs.length ? xs[0] : undefined; };   // tail :: [a] -> [a] var tail = function (xs) { return xs.length ? xs.slice(1) : undefined; };   // length :: [a] -> Int var length = function (xs) { return xs.length; };   // SIGNED DIGIT SEQUENCES (mapped to sums and to strings)   // data Sign :: [ 0 | 1 | -1 ] = ( Unsigned | Plus | Minus ) // asSum :: [Sign] -> Int var asSum = function (xs) { var dct = xs.reduceRight(function (a, sign, i) { var d = i + 1; // zero-based index to [1-9] positions if (sign !== 0) { // Sum increased, digits cleared return { digits: [], n: a.n + sign * parseInt([d].concat(a.digits) .join(''), 10) }; } else return { // Digits extended, sum unchanged digits: [d].concat(a.digits), n: a.n }; }, { digits: [], n: 0 }); return dct.n + ( dct.digits.length > 0 ? parseInt(dct.digits.join(''), 10) : 0 ); };   // data Sign :: [ 0 | 1 | -1 ] = ( Unsigned | Plus | Minus ) // asString :: [Sign] -> String var asString = function (xs) { var ns = xs.reduce(function (a, sign, i) { var d = (i + 1) .toString(); return sign === 0 ? a + d : a + (sign > 0 ? ' +' : ' -') + d; }, '');   return ns[0] === '+' ? tail(ns) : ns; };   // SUM T0 100 ------------------------------------------------------------   // universe :: [[Sign]] var universe = permutationsWithRepetition(9, [0, 1, -1]) .filter(function (x) { return x[0] !== 1; });   // allNonNegativeSums :: [Int] var allNonNegativeSums = universe.map(asSum) .filter(function (x) { return x >= 0; }) .sort();   // uniqueNonNegativeSums :: [Int] var uniqueNonNegativeSums = nub(allNonNegativeSums);   return ["Sums to 100:\n", unlines(universe.filter(function (x) { return asSum(x) === 100; }) .map(asString)),   "\n\n10 commonest sums (sum, followed by number of routes to it):\n", show(take(10, group(allNonNegativeSums) .sort(on(flip(compare), length)) .map(function (xs) { return [xs[0], xs.length]; }))),   "\n\nFirst positive integer not expressible as a sum of this kind:\n", show(find(function (x, i) { return x !== i; }, uniqueNonNegativeSums.sort(compare)) - 1), // zero-based index   "\n10 largest sums:\n", show(take(10, uniqueNonNegativeSums.sort(flip(compare)))) ].join('\n') + '\n'; })();
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.
#Eiffel
Eiffel
    class APPLICATION   create make   feature {NONE}   make do io.put_integer (sum_multiples (1000)) end   sum_multiples (n: INTEGER): INTEGER -- Sum of all positive multiples of 3 or 5 below 'n'. do across 1 |..| (n - 1) as c loop if c.item \\ 3 = 0 or c.item \\ 5 = 0 then Result := Result + c.item end end end   end    
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
#Emacs_Lisp
Emacs Lisp
(defun digit-sum (n) (apply #'+ (mapcar (lambda (c) (- c ?0)) (string-to-list "123"))))   (digit-sum 1234) ;=> 10
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
#Fish
Fish
v \0& >l?!v:*&+& >&n;
http://rosettacode.org/wiki/Strip_whitespace_from_a_string/Top_and_tail
Strip whitespace from a string/Top and tail
Task Demonstrate how to strip leading and trailing whitespace from a string. The solution should demonstrate how to achieve the following three results: String with leading whitespace removed String with trailing whitespace removed String with both leading and trailing whitespace removed For the purposes of this task whitespace includes non printable characters such as the space character, the tab character, and other such characters that have no corresponding graphical representation. 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
V s = " \t \r \n String with spaces \t \r \n " print(s.ltrim((‘ ’, "\t", "\r", "\n")).len) print(s.rtrim((‘ ’, "\t", "\r", "\n")).len) print(s.trim((‘ ’, "\t", "\r", "\n")).len)
http://rosettacode.org/wiki/Strong_and_weak_primes
Strong and weak primes
Definitions   (as per number theory)   The   prime(p)   is the   pth   prime.   prime(1)   is   2   prime(4)   is   7   A   strong   prime   is when     prime(p)   is   >   [prime(p-1) + prime(p+1)] ÷ 2   A     weak    prime   is when     prime(p)   is   <   [prime(p-1) + prime(p+1)] ÷ 2 Note that the definition for   strong primes   is different when used in the context of   cryptography. Task   Find and display (on one line) the first   36   strong primes.   Find and display the   count   of the strong primes below   1,000,000.   Find and display the   count   of the strong primes below 10,000,000.   Find and display (on one line) the first   37   weak primes.   Find and display the   count   of the weak primes below   1,000,000.   Find and display the   count   of the weak primes below 10,000,000.   (Optional)   display the   counts   and   "below numbers"   with commas. Show all output here. Related Task   Safe primes and unsafe primes. Also see   The OEIS article A051634: strong primes.   The OEIS article A051635: weak primes.
#C
C
#include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h>   const int PRIMES[] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091, 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151, 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213, 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277, 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307, 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399, 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451, 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, 1499, 1511, 1523, 1531, 1543, 1549, 1553, 1559, 1567, 1571, 1579, 1583, 1597, 1601, 1607, 1609, 1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667, 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733, 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789, 1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871, 1873, 1877, 1879, 1889, 1901, 1907, 1913, 1931, 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997, 1999, 2003, 2011, 2017, 2027, 2029, 2039, 2053, 2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111, 2113, 2129, 2131, 2137, 2141, 2143, 2153, 2161, 2179, 2203, 2207, 2213, 2221, 2237, 2239, 2243, 2251, 2267, 2269, 2273, 2281, 2287, 2293, 2297, 2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357, 2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411, 2417, 2423, 2437, 2441, 2447, 2459, 2467, 2473, 2477, 2503, 2521, 2531, 2539, 2543, 2549, 2551, 2557, 2579, 2591, 2593, 2609, 2617, 2621, 2633, 2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687, 2689, 2693, 2699, 2707, 2711, 2713, 2719, 2729, 2731, 2741, 2749, 2753, 2767, 2777, 2789, 2791, 2797, 2801, 2803, 2819, 2833, 2837, 2843, 2851, 2857, 2861, 2879, 2887, 2897, 2903, 2909, 2917, 2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999, 3001, 3011, 3019, 3023, 3037, 3041, 3049, 3061, 3067, 3079, 3083, 3089, 3109, 3119, 3121, 3137, 3163 }; #define PRIME_LENGTH (sizeof(PRIMES) / sizeof(int))   bool isPrime(int n) { int i;   if (n < 2) { return false; }   for (i = 0; i < PRIME_LENGTH; ++i) { if (n == PRIMES[i]) { return true; } if (n % PRIMES[i] == 0) { return false; } if (n < PRIMES[i] * PRIMES[i]) { break; } }   return true; }   int main() { const int MAX_LENGTH = 700000; int i, n, c1, c2;   int *primePtr = calloc(MAX_LENGTH, sizeof(int)); if (primePtr == 0) { return EXIT_FAILURE; }   for (i = 0; i < PRIME_LENGTH; i++) { primePtr[i] = PRIMES[i]; }   i--; for (n = PRIMES[i] + 4; n < 10000100;) { if (isPrime(n)) { primePtr[i++] = n; } n += 2;   if (isPrime(n)) { primePtr[i++] = n; } n += 4;   if (i >= MAX_LENGTH) { printf("Allocate more memory."); return EXIT_FAILURE; } }   ///////////////////////////////////////////////////////////// printf("First 36 strong primes:"); c1 = 0; c2 = 0; for (n = 0, i = 1; i < MAX_LENGTH - 1; i++) { if (2 * primePtr[i] > primePtr[i - 1] + primePtr[i + 1]) { if (n < 36) { printf("  %d", primePtr[i]); n++; } if (primePtr[i] < 1000000) { c1++; c2++; } else if (primePtr[i] < 10000000) { c2++; } else break; } } printf("\nThere are %d strong primes below 1,000,000", c1); printf("\nThere are %d strong primes below 10,000,000\n\n", c2);   ///////////////////////////////////////////////////////////// printf("First 37 weak primes:"); c1 = 0; c2 = 0; for (n = 0, i = 1; i < MAX_LENGTH - 1; i++) { if (2 * primePtr[i] < primePtr[i - 1] + primePtr[i + 1]) { if (n < 37) { printf("  %d", primePtr[i]); n++; } if (primePtr[i] < 1000000) { c1++; c2++; } else if (primePtr[i] < 10000000) { c2++; } else break; } } printf("\nThere are %d weak primes below 1,000,000", c1); printf("\nThere are %d weak primes below 10,000,000\n\n", c2);   free(primePtr); return EXIT_SUCCESS; }
http://rosettacode.org/wiki/Substring
Substring
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Display a substring:   starting from   n   characters in and of   m   length;   starting from   n   characters in,   up to the end of the string;   whole string minus the last character;   starting from a known   character   within the string and of   m   length;   starting from a known   substring   within the string and of   m   length. 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
type String is array (Positive range <>) of Character;
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.
#AWK
AWK
  # syntax: GAWK -f SUDOKU_RC.AWK BEGIN { # row1 row2 row3 row4 row5 row6 row7 row8 row9 # puzzle = "111111111 111111111 111111111 111111111 111111111 111111111 111111111 111111111 111111111" # NG duplicate hints # puzzle = "1........ ..274.... ...5....4 .3....... 75....... .....96.. .4...6... .......71 .....1.30" # NG can't use zero # puzzle = "1........ ..274.... ...5....4 .3....... 75....... .....96.. .4...6... .......71 .....1.39" # no solution # puzzle = "1........ ..274.... ...5....4 .3....... 75....... .....96.. .4...6... .......71 .....1.3." # OK puzzle = "123456789 456789123 789123456 ......... ......... ......... ......... ......... ........." # OK gsub(/ /,"",puzzle) if (length(puzzle) != 81) { error("length of puzzle is not 81") } if (puzzle !~ /^[1-9\.]+$/) { error("only 1-9 and . are valid") } if (gsub(/[1-9]/,"&",puzzle) < 17) { error("too few hints") } if (errors > 0) { exit(1) } plot(puzzle,"unsolved") if (dup_hints_check(puzzle) == 1) { if (solve(puzzle) == 1) { dup_hints_check(sos) plot(sos,"solved") printf("\nbef: %s\naft: %s\n",puzzle,sos) exit(0) } else { error("no solution") } } exit(1) } function dup_hints_check(ss, esf,msg,Rarr,Carr,Barr,i,r_row,r_col,r_pos,r_hint,c_row,c_col,c_pos,c_hint,box) { esf = errors # errors so far for (i=0; i<81; i++) { # row r_row = int(i/9) + 1 # determine row: 1..9 r_col = i%9 + 1 # determine column: 1..9 r_pos = i + 1 # determine hint position: 1..81 r_hint = substr(ss,r_pos,1) # extract 1 character; the hint Rarr[r_row,r_hint]++ # save row # column c_row = i%9 + 1 # determine row: 1..9 c_col = int(i/9) + 1 # determine column: 1..9 c_pos = (c_row-1) * 9 + c_col # determine hint position: 1..81 c_hint = substr(ss,c_pos,1) # extract 1 character; the hint Carr[c_col,c_hint]++ # save column # box (there has to be a better way) if ((r_row r_col) ~ /[123][123]/) { box = 1 } else if ((r_row r_col) ~ /[123][456]/) { box = 2 } else if ((r_row r_col) ~ /[123][789]/) { box = 3 } else if ((r_row r_col) ~ /[456][123]/) { box = 4 } else if ((r_row r_col) ~ /[456][456]/) { box = 5 } else if ((r_row r_col) ~ /[456][789]/) { box = 6 } else if ((r_row r_col) ~ /[789][123]/) { box = 7 } else if ((r_row r_col) ~ /[789][456]/) { box = 8 } else if ((r_row r_col) ~ /[789][789]/) { box = 9 } else { box = 0 } Barr[box,r_hint]++ # save box } dup_hints_print(Rarr,"row") dup_hints_print(Carr,"column") dup_hints_print(Barr,"box") return((errors == esf) ? 1 : 0) } function dup_hints_print(arr,rcb, hint,i) { # rcb - Row Column Box for (i=1; i<=9; i++) { # "i" is either the row, column, or box for (hint=1; hint<=9; hint++) { # 1..9 only; don't care about "." place holder if (arr[i,hint]+0 > 1) { # was a digit specified more than once error(sprintf("duplicate hint in %s %d",rcb,i)) } } } } function plot(ss,text1,text2, a,b,c,d,ou) { # 1st call prints the unsolved puzzle. # 2nd call prints the solved puzzle printf("| - - - + - - - + - - - | %s\n",text1) for (a=0; a<3; a++) { for (b=0; b<3; b++) { ou = "|" for (c=0; c<3; c++) { for (d=0; d<3; d++) { ou = sprintf("%s %1s",ou,substr(ss,1+d+3*c+9*b+27*a,1)) } ou = ou " |" } print(ou) } printf("| - - - + - - - + - - - | %s\n",(a==2)?text2:"") } } function solve(ss, a,b,c,d,e,r,co,ro,bi,bl,nss) { i = 0 # first, use some simple logic to fill grid as much as possible do { i++ didit = 0 delete nr delete nc delete nb delete ca for (a=0; a<81; a++) { b = substr(ss,a+1,1) if (b == ".") { # construct row, column and block at cell c = a % 9 r = int(a/9) ro = substr(ss,r*9+1,9) co = "" for (d=0; d<9; d++) { co = co substr(ss,d*9+c+1,1) } bi = int(c/3)*3+(int(r/3)*3)*9+1 bl = "" for (d=0; d<3; d++) { bl = bl substr(ss,bi+d*9,3) } e = 0 # count non-occurrences of digits 1-9 in combined row, column and block, per row, column and block, and flag cell/digit as candidate for (d=1; d<10; d++) { if (index(ro co bl, d) == 0) { e++ nr[r,d]++ nc[c,d]++ nb[bi,d]++ ca[c,r,d] = bi } } if (e == 0) { # in case no candidate is available, give up return(0) } } } # go through all cell/digit candidates # hidden singles for (crd in ca) { # a candidate may have been deleted after the loop started if (ca[crd] != "") { split(crd,spl,SUBSEP) c = spl[1] r = spl[2] d = spl[3] bi = ca[crd] a = c + r * 9 # unique solution if at least one non-occurrence counter is exactly 1 if ((nr[r,d] == 1) || (nc[c,d] == 1) || (nb[bi,d] == 1)) { ss = substr(ss,1,a) d substr(ss,a+2,length(ss)) didit = 1 # remove candidates from current row, column, block for (e=0; e<9; e++) { delete ca[c,e,d] delete ca[e,r,d] } for (e=0; e<3; e++) { for (b=0; b<3; b++) { delete ca[int(c/3)*3+b,int(r/3)*3+e,d] } } } } } } while (didit == 1) # second, pick a viable solution for the next empty cell and see if it leads to a solution a = index(ss,".")-1 if (a == -1) { # no more empty cells, done sos = ss return(1) } else { c = a % 9 r = int(a/9) # concatenate current row, column and block # row co = substr(ss,r*9+1,9) # column for (d=0; d<9; d++) { co = co substr(ss,d*9+c+1,1) } # block c = int(c/3)*3+(int(r/3)*3)*9+1 for (d=0; d<3; d++) { co = co substr(ss,c+d*9,3) } for (b=1; b<10; b++) { # get a viable digit if (index(co,b) == 0) { # check if candidate digit already exists # is viable, put in cell nss = substr(ss,1,a) b substr(ss,a+2,length(ss)) d = solve(nss) # try to solve if (d == 1) { # if successful, return return(1) } } } } return(0) # no digits viable, no solution } function error(message) { printf("error: %s\n",message) ; errors++ }  
http://rosettacode.org/wiki/Subleq
Subleq
Subleq is an example of a One-Instruction Set Computer (OISC). It is named after its only instruction, which is SUbtract and Branch if Less than or EQual to zero. Task Your task is to create an interpreter which emulates a SUBLEQ machine. The machine's memory consists of an array of signed integers.   These integers may be interpreted in three ways:   simple numeric values   memory addresses   characters for input or output Any reasonable word size that accommodates all three of the above uses is fine. The program should load the initial contents of the emulated machine's memory, set the instruction pointer to the first address (which is defined to be address 0), and begin emulating the machine, which works as follows:   Let A be the value in the memory location identified by the instruction pointer;   let B and C be the values stored in the next two consecutive addresses in memory.   Advance the instruction pointer three words, to point at the address after the address containing C.   If A is   -1   (negative unity),   then a character is read from the machine's input and its numeric value stored in the address given by B.   C is unused.   If B is   -1   (negative unity),   then the number contained in the address given by A is interpreted as a character and written to the machine's output.   C is unused.   Otherwise, both A and B are treated as addresses.   The number contained in address A is subtracted from the number in address B (and the difference left in address B).   If the result is positive, execution continues uninterrupted; if the result is zero or negative, the number in C becomes the new instruction pointer.   If the instruction pointer becomes negative, execution halts. Your solution may initialize the emulated machine's memory in any convenient manner, but if you accept it as input, it should be a separate input stream from the one fed to the emulated machine once it is running. And if fed as text input, it should be in the form of raw subleq "machine code" - whitespace-separated decimal numbers, with no symbolic names or other assembly-level extensions, to be loaded into memory starting at address   0   (zero). For purposes of this task, show the output of your solution when fed the below   "Hello, world!"   program. As written, this example assumes ASCII or a superset of it, such as any of the Latin-N character sets or Unicode;   you may translate the numbers representing characters (starting with 72=ASCII 'H') into another character set if your implementation runs in a non-ASCII-compatible environment. If 0 is not an appropriate terminator in your character set, the program logic will need some adjustment as well. 15 17 -1 17 -1 -1 16 1 -1 16 3 -1 15 15 0 0 -1 72 101 108 108 111 44 32 119 111 114 108 100 33 10 0 The above "machine code" corresponds to something like this in a hypothetical assembler language for a signed 8-bit version of the machine: start: 0f 11 ff subleq (zero), (message), -1 11 ff ff subleq (message), -1, -1  ; output character at message 10 01 ff subleq (neg1), (start+1), -1 10 03 ff subleq (neg1), (start+3), -1 0f 0f 00 subleq (zero), (zero), start ; useful constants zero: 00 .data 0 neg1: ff .data -1 ; the message to print message: .data "Hello, world!\n\0" 48 65 6c 6c 6f 2c 20 77 6f 72 6c 64 21 0a 00
#ALGOL_W
ALGOL W
% Subleq program interpreter  % begin    % executes the program specified in scode, stops when the instruction  %  % pointer becomes negative  % procedure runSubleq ( integer array scode( * )  ; integer value codeLength ) ; begin integer maxMemory; maxMemory := 3 * 1024; begin integer array memory ( 0 :: maxMemory - 1 ); integer ip, a, b, c; for i := 0 until maxMemory - 1 do memory( i ) := 0;  % load the program into memory  % for i := 0 until codeLength do memory( i ) := scode( i );    % start at instruction 0  % ip := 0;  % execute the instructions until ip is < 0  % while ip >= 0 do begin  % get three words at ip and advance ip past them  % a  := memory( ip ); b  := memory( ip + 1 ); c  := memory( ip + 2 ); ip := ip + 3;  % execute according to a, b and c  % if a = -1 then begin  % input a character to b  % string(1) input; read( input ); memory( b ) := decode( input ) end else if b = -1 then begin  % output character from a  % writeon( code( memory( a ) ) ) end else begin  % subtract and branch if le 0  % memory( b ) := memory( b ) - memory( a ); if memory( b ) <= 0 then ip := c end end % while-do % end end % runSubleq % ;    % test the interpreter with the hello-world program specified in the task % begin integer array code ( 0 :: 31 ); integer codePos; codePos := 0; for i := 15, 17, -1, 17, -1, -1 , 16, 1, -1, 16, 3, -1 , 15, 15, 0, 0, -1, 72 , 101, 108, 108, 111, 44, 32 , 119, 111, 114, 108, 100, 33 , 10, 0 do begin code( codePos ) := i; codePos := codePos + 1; end; runSubleq( code, 31 ) 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
#Delphi
Delphi
  program Successive_prime_differences;     {$APPTYPE CONSOLE}   {$R *.res}   uses System.SysUtils, System.Generics.Collections;   function IsPrime(a: UInt64): Boolean; var d: UInt64; begin if (a < 2) then exit(False);   if (a mod 2) = 0 then exit(a = 2);   if (a mod 3) = 0 then exit(a = 3);   d := 5;   while (d * d <= a) do begin if (a mod d = 0) then Exit(false); inc(d, 2);   if (a mod d = 0) then Exit(false); inc(d, 4); end;   Result := True; end;   function Primes(const limit: UInt64): TArray<UInt64>; var i: UInt64;   procedure Add(const value: UInt64); begin SetLength(result, Length(result) + 1); Result[Length(result) - 1] := value; end;   begin if limit < 2 then exit;   // 2 is the only even prime Add(2);   i := 3; while i <= limit do begin if IsPrime(i) then Add(i); inc(i, 2); end; end;   function Commatize(const n: UInt64): string; var str: string; digits: Integer; i: Integer; begin Result := ''; str := n.ToString; digits := str.Length;   for i := 1 to digits do begin if ((i > 1) and (((i - 1) mod 3) = (digits mod 3))) then Result := Result + ','; Result := Result + str[i]; end; end;   function CheckScan(index: Integer; p: TArray<UInt64>; pattern: array of Integer): Boolean; var i, last: Integer; begin last := Length(pattern) - 1; for i := 0 to last do if p[index - last + i - 1] + pattern[i] <> p[index - last + i] then exit(False); Result := True; end;   const GroupLabel: array[1..6] of string = ('(2)', '(1)', '(2, 2)', '(2, 4)', '(4, 2)', '(6, 4, 2)');   var limit, start: UInt64; c: TArray<UInt64>; i, j: UInt64; Group: array[1..6] of Tlist<string>;   begin for i := 1 to 6 do Group[i] := Tlist<string>.Create;   limit := Trunc(1e6 - 1); c := Primes(limit);   for j := 1 to High(c) do begin if CheckScan(j, c, [2]) then Group[1].Add(format('(%d,%d)', [c[j - 1], c[j]]));   if CheckScan(j, c, [1]) then Group[2].Add(format('(%d,%d)', [c[j - 1], c[j]]));   if j > 1 then begin if CheckScan(j, c, [2, 2]) then Group[3].Add(format('(%d,%d,%d)', [c[j - 2], c[j - 1], c[j]]));   if CheckScan(j, c, [2, 4]) then Group[4].Add(format('(%d,%d,%d)', [c[j - 2], c[j - 1], c[j]]));   if CheckScan(j, c, [4, 2]) then Group[5].Add(format('(%d,%d,%d)', [c[j - 2], c[j - 1], c[j]])); end;   if j > 2 then if CheckScan(j, c, [6, 4, 2]) then Group[6].Add(format('(%d,%d,%d,%d)', [c[j - 3], c[j - 2], c[j - 1], c[j]]));   end;   for i := 1 to 6 do begin Write(GroupLabel[i], ': first group = ', Group[i].First); Writeln(', last group = ', Group[i].last, ', count = ', Group[i].Count); Group[i].free; end;   readln; 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
#AWK
AWK
BEGIN { mystring="knights" print substr(mystring,2) # remove the first letter print substr(mystring,1,length(mystring)-1) # remove the last character print substr(mystring,2,length(mystring)-2) # remove both the first and last character }
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.
#dc
dc
[* * (seed) lsx -- * Seeds the subtractive generator. * Uses register R to hold the state. *]sz [ [* Fill ring buffer R[0] to R[54]. *]sz d 54:R SA [A = R[54] = seed]sz 1 d 33:R SB [B = R[33] = 1]sz 12 SC [C = index 12, into array R.]sz [55 -]SI [ [Loop until C is 54:]sz lA lB - d lC:R [R[C] = A - B]sz lB sA sB [Parallel let A = B and B = A - B]sz lC 34 + d 55 !>I d sC [C += 34 (mod 55)]sz 54 !=L ]d SL x [* Point R[55] and R[56] into ring buffer. *]sz 0 55:R [R[55] = index 0, of 55th last number.]sz 31 56:R [R[56] = index 31, of 24th last number.]sz [* Stir ring buffer. *]sz 165 [ [Loop 165 times:]sz 55;R;R 56;R;R - 55;R:R [Discard a random number.]sz 55;R 1 + d 55 !>I 55:R [R[55] += 1 (mod 55)]sz 56;R 1 + d 55 !>I 56:R [R[56] += 1 (mod 55)]sz 1 - d 0 <L ]d sL x LAsz LBsz LCsz LIsz LLsz ]ss   [* * lrx -- (random number from 0 to 10^9 - 1) * Returns the next number from the subtractive generator. * Uses register R, seeded by lsx. *]sz [ 55;R;R 56;R;R - [R[R[55]] - R[R[56]] is next random number.]sz d 55;R:R [Put it in R[R[55]]. Also leave it on stack.]sz [55 -]SI 55;R 1 + d 55 !>I 55:R [R[55] += 1 (mod 55)]sz 56;R 1 + d 55 !>I 56:R [R[56] += 1 (mod 55)]sz [1000000000 +]sI 1000000000 % d 0 >I [Random number = it (mod 10^9)]sz LIsz ]sr     [* Seed with 292929 and print first three random numbers. *]sz 292929 lsx lrx psz lrx psz lrx psz
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
#Perl
Perl
sub encode { my $source = shift; my $key = shift; my $out = q();   @ka = split //, $key; foreach $ch (split //, $source) { $idx = ord($ch) - 32; $out .= $ka[$idx]; }   return $out; }   sub decode { my $source = shift; my $key = shift; my $out = q();   foreach $ch (split //, $source) { $idx = index $key, $ch; $val = chr($idx + 32); $out .= $val; }   return $out; }   my $key = q(]kYV}(!7P$n5_0i R:?jOWtF/=-pe'AD&@r6%ZXs"v*N[#wSl9zq2^+g;LoB`aGh{3.HIu4fbK)mU8|dMET><,Qc\C1yxJ); my $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.";   my $ct = encode($text, $key); print "Encoded: $ct\n";   my $pt = decode($ct, $key); print "Decoded: $pt\n";
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.
#Delphi
Delphi
program SumAndProductOfArray;   {$APPTYPE CONSOLE}   var i: integer; lIntArray: array [1 .. 5] of integer = (1, 2, 3, 4, 5); lSum: integer = 0; lProduct: integer = 1; begin for i := 1 to length(lIntArray) do begin Inc(lSum, lIntArray[i]); lProduct := lProduct * lIntArray[i] end;   Write('Sum: '); Writeln(lSum); Write('Product: '); Writeln(lProduct); end.
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.
#Dart
Dart
main() { var list = new List<int>.generate(1000, (i) => i + 1);   num sum = 0;   (list.map((x) => 1.0 / (x * x))).forEach((num e) { sum += e; }); print(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).
#jq
jq
# Generate a "sum" in the form: [I, 1, X, 2, X, 3, ..., X, n] where I is "-" or "", and X is "+", "-", or "" def generate(n): def pm: ["+"], ["-"], [""];   if n == 1 then (["-"], [""]) + [1] else generate(n-1) + pm + [n] end;   # The numerical value of a "sum" def addup: reduce .[] as $x ({sum:0, previous: "0"}; if $x == "+" then .sum += (.previous|tonumber) | .previous = "" elif $x == "-" then .sum += (.previous|tonumber) | .previous = "-" elif $x == "" then . else .previous += ($x|tostring) end) | .sum + (.previous | tonumber) ;   # Pretty-print a "sum", e.g. ["",1,"+", 2] => 1 + 2 def pp: map(if . == "+" or . == "-" then " " + . else tostring end) | join("");  
http://rosettacode.org/wiki/Strip_control_codes_and_extended_characters_from_a_string
Strip control codes and extended characters from a string
Task Strip control codes and extended characters from a string. The solution should demonstrate how to achieve each of the following results:   a string with control codes stripped (but extended characters not stripped)   a string with control codes and extended characters stripped In ASCII, the control codes have decimal codes 0 through to 31 and 127. On an ASCII based system, if the control codes are stripped, the resultant string would have all of its characters within the range of 32 to 126 decimal on the ASCII table. On a non-ASCII based system, we consider characters that do not have a corresponding glyph on the ASCII table (within the ASCII range of 32 to 126 decimal) to be an extended character for the purpose of this task. 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
F stripped(s) R s.filter(i -> Int(i.code) C 32..126).join(‘’)   print(stripped("\ba\u0000b\n\rc\fd\xc3"))
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.
#Elixir
Elixir
iex(1)> Enum.filter(0..1000-1, fn x -> rem(x,3)==0 or rem(x,5)==0 end) |> Enum.sum 233168
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
#Erlang
Erlang
  -module(sum_digits). -export([sum_digits/2, sum_digits/1]).   sum_digits(N) -> sum_digits(N,10).   sum_digits(N,B) -> sum_digits(N,B,0).   sum_digits(0,_,Acc) -> Acc; sum_digits(N,B,Acc) when N < B -> Acc+N; sum_digits(N,B,Acc) -> sum_digits(N div B, B, Acc + (N rem B)).  
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
#Forth
Forth
: fsum**2 ( addr n -- f ) 0e dup 0= if 2drop exit then floats bounds do i f@ fdup f* f+ 1 floats +loop ;   create test 3e f, 1e f, 4e f, 1e f, 5e f, 9e f, test 6 fsum**2 f. \ 133.
http://rosettacode.org/wiki/Strip_whitespace_from_a_string/Top_and_tail
Strip whitespace from a string/Top and tail
Task Demonstrate how to strip leading and trailing whitespace from a string. The solution should demonstrate how to achieve the following three results: String with leading whitespace removed String with trailing whitespace removed String with both leading and trailing whitespace removed For the purposes of this task whitespace includes non printable characters such as the space character, the tab character, and other such characters that have no corresponding graphical representation. 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!
DEFINE SPACE="32" DEFINE TAB="127" DEFINE NEWLINE="155"   BYTE FUNC IsWhitespace(CHAR c) IF c=SPACE OR c=TAB OR c=NEWLINE THEN RETURN (1) FI RETURN (0)   PROC Strip(CHAR ARRAY src,dst BYTE head,tail) BYTE i,first,last   first=1 last=src(0)   IF head THEN WHILE first<=last DO IF IsWhitespace(src(first))=0 THEN EXIT FI first==+1 OD FI   IF tail THEN WHILE last>=first DO IF IsWhitespace(src(last))=0 THEN EXIT FI last==-1 OD FI   IF first>last THEN dst(0)=0 ELSE SCopyS(dst,src,first,last) FI RETURN   PROC Main() CHAR ARRAY src=" Action! ",dst(20)   src(2)=NEWLINE src(13)=TAB   PrintF("Original string:%E""%S""%E%E",src) Strip(src,dst,1,0) PrintF("Trim leading whitespaces:%E""%S""%E%E",dst) Strip(src,dst,0,1) PrintF("Trim trailing whitespaces:%E""%S""%E%E",dst) Strip(src,dst,1,1) PrintF("Trim leading and trailing whitespaces:""%S""%E%E",dst) RETURN
http://rosettacode.org/wiki/Strong_and_weak_primes
Strong and weak primes
Definitions   (as per number theory)   The   prime(p)   is the   pth   prime.   prime(1)   is   2   prime(4)   is   7   A   strong   prime   is when     prime(p)   is   >   [prime(p-1) + prime(p+1)] ÷ 2   A     weak    prime   is when     prime(p)   is   <   [prime(p-1) + prime(p+1)] ÷ 2 Note that the definition for   strong primes   is different when used in the context of   cryptography. Task   Find and display (on one line) the first   36   strong primes.   Find and display the   count   of the strong primes below   1,000,000.   Find and display the   count   of the strong primes below 10,000,000.   Find and display (on one line) the first   37   weak primes.   Find and display the   count   of the weak primes below   1,000,000.   Find and display the   count   of the weak primes below 10,000,000.   (Optional)   display the   counts   and   "below numbers"   with commas. Show all output here. Related Task   Safe primes and unsafe primes. Also see   The OEIS article A051634: strong primes.   The OEIS article A051635: weak primes.
#C.23
C#
using static System.Console; using static System.Linq.Enumerable; using System;   public static class StrongAndWeakPrimes { public static void Main() { var primes = PrimeGenerator(10_000_100).ToList(); var strongPrimes = from i in Range(1, primes.Count - 2) where primes[i] > (primes[i-1] + primes[i+1]) / 2 select primes[i]; var weakPrimes = from i in Range(1, primes.Count - 2) where primes[i] < (primes[i-1] + primes[i+1]) / 2.0 select primes[i]; WriteLine($"First 36 strong primes: {string.Join(", ", strongPrimes.Take(36))}"); WriteLine($"There are {strongPrimes.TakeWhile(p => p < 1_000_000).Count():N0} strong primes below {1_000_000:N0}"); WriteLine($"There are {strongPrimes.TakeWhile(p => p < 10_000_000).Count():N0} strong primes below {10_000_000:N0}"); WriteLine($"First 37 weak primes: {string.Join(", ", weakPrimes.Take(37))}"); WriteLine($"There are {weakPrimes.TakeWhile(p => p < 1_000_000).Count():N0} weak primes below {1_000_000:N0}"); WriteLine($"There are {weakPrimes.TakeWhile(p => p < 10_000_000).Count():N0} weak primes below {1_000_000:N0}"); }   }
http://rosettacode.org/wiki/Substring
Substring
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Display a substring:   starting from   n   characters in and of   m   length;   starting from   n   characters in,   up to the end of the string;   whole string minus the last character;   starting from a known   character   within the string and of   m   length;   starting from a known   substring   within the string and of   m   length. 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
#Aikido
Aikido
  const str = "abcdefg" var n = 2 var m = 3   println (str[n:n+m-1]) // pos 2 length 3 println (str[n:]) // pos 2 to end println (str >> 1) // remove last character var p = find (str, 'c') println (str[p:p+m-1]) // from pos of p length 3   var s = find (str, "bc") println (str[s, s+m-1]) // pos of bc length 3  
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.
#BBC_BASIC
BBC BASIC
VDU 23,22,453;453;8,20,16,128 *FONT Arial,28   DIM Board%(8,8) Board%() = %111111111   FOR L% = 0 TO 9:P% = L%*100 LINE 2,P%+2,902,P%+2 IF (L% MOD 3)=0 LINE 2,P%,902,P% : LINE 2,P%+4,902,P%+4 LINE P%+2,2,P%+2,902 IF (L% MOD 3)=0 LINE P%,2,P%,902 : LINE P%+4,2,P%+4,902 NEXT   DATA " 4 5 6 " DATA " 6 1 8 9" DATA "3 7 " DATA " 8 5 " DATA " 4 3 " DATA " 6 7 " DATA " 2 6" DATA "1 5 4 3 " DATA " 2 7 1 "   FOR R% = 8 TO 0 STEP -1 READ A$ FOR C% = 0 TO 8 A% = ASCMID$(A$,C%+1) AND 15 IF A% Board%(R%,C%) = 1 << (A%-1) NEXT NEXT R%   GCOL 4 PROCshow WAIT 200 dummy% = FNsolve(Board%(), TRUE) GCOL 2 PROCshow REPEAT WAIT 1 : UNTIL FALSE END   DEF PROCshow LOCAL C%,P%,R% FOR C% = 0 TO 8 FOR R% = 0 TO 8 P% = Board%(R%,C%) IF (P% AND (P%-1)) = 0 THEN IF P% P% = LOGP%/LOG2+1.5 MOVE C%*100+30,R%*100+90 VDU 5,P%+48,4 ENDIF NEXT NEXT ENDPROC   DEF FNsolve(P%(),F%) LOCAL C%,D%,M%,N%,R%,X%,Y%,Q%() DIM Q%(8,8) REPEAT Q%() = P%() FOR R% = 0 TO 8 FOR C% = 0 TO 8 D% = P%(R%,C%) IF (D% AND (D%-1))=0 THEN M% = NOT D% FOR X% = 0 TO 8 IF X%<>C% P%(R%,X%) AND= M% IF X%<>R% P%(X%,C%) AND= M% NEXT FOR X% = C%DIV3*3 TO C%DIV3*3+2 FOR Y% = R%DIV3*3 TO R%DIV3*3+2 IF X%<>C% IF Y%<>R% P%(Y%,X%) AND= M% NEXT NEXT ENDIF NEXT NEXT Q%() -= P%() UNTIL SUMQ%()=0 M% = 10 FOR R% = 0 TO 8 FOR C% = 0 TO 8 D% = P%(R%,C%) IF D%=0 M% = 0 IF D% AND (D%-1) THEN N% = 0 REPEAT N% += D% AND 1 D% DIV= 2 UNTIL D% = 0 IF N%<M% M% = N% : X% = C% : Y% = R% ENDIF NEXT NEXT IF M%=0 THEN = 0 IF M%=10 THEN = 1 D% = 0 FOR M% = 0 TO 8 IF P%(Y%,X%) AND (2^M%) THEN Q%() = P%() Q%(Y%,X%) = 2^M% C% = FNsolve(Q%(),F%) D% += C% IF C% IF F% P%() = Q%() : = D% ENDIF NEXT = D%
http://rosettacode.org/wiki/Subleq
Subleq
Subleq is an example of a One-Instruction Set Computer (OISC). It is named after its only instruction, which is SUbtract and Branch if Less than or EQual to zero. Task Your task is to create an interpreter which emulates a SUBLEQ machine. The machine's memory consists of an array of signed integers.   These integers may be interpreted in three ways:   simple numeric values   memory addresses   characters for input or output Any reasonable word size that accommodates all three of the above uses is fine. The program should load the initial contents of the emulated machine's memory, set the instruction pointer to the first address (which is defined to be address 0), and begin emulating the machine, which works as follows:   Let A be the value in the memory location identified by the instruction pointer;   let B and C be the values stored in the next two consecutive addresses in memory.   Advance the instruction pointer three words, to point at the address after the address containing C.   If A is   -1   (negative unity),   then a character is read from the machine's input and its numeric value stored in the address given by B.   C is unused.   If B is   -1   (negative unity),   then the number contained in the address given by A is interpreted as a character and written to the machine's output.   C is unused.   Otherwise, both A and B are treated as addresses.   The number contained in address A is subtracted from the number in address B (and the difference left in address B).   If the result is positive, execution continues uninterrupted; if the result is zero or negative, the number in C becomes the new instruction pointer.   If the instruction pointer becomes negative, execution halts. Your solution may initialize the emulated machine's memory in any convenient manner, but if you accept it as input, it should be a separate input stream from the one fed to the emulated machine once it is running. And if fed as text input, it should be in the form of raw subleq "machine code" - whitespace-separated decimal numbers, with no symbolic names or other assembly-level extensions, to be loaded into memory starting at address   0   (zero). For purposes of this task, show the output of your solution when fed the below   "Hello, world!"   program. As written, this example assumes ASCII or a superset of it, such as any of the Latin-N character sets or Unicode;   you may translate the numbers representing characters (starting with 72=ASCII 'H') into another character set if your implementation runs in a non-ASCII-compatible environment. If 0 is not an appropriate terminator in your character set, the program logic will need some adjustment as well. 15 17 -1 17 -1 -1 16 1 -1 16 3 -1 15 15 0 0 -1 72 101 108 108 111 44 32 119 111 114 108 100 33 10 0 The above "machine code" corresponds to something like this in a hypothetical assembler language for a signed 8-bit version of the machine: start: 0f 11 ff subleq (zero), (message), -1 11 ff ff subleq (message), -1, -1  ; output character at message 10 01 ff subleq (neg1), (start+1), -1 10 03 ff subleq (neg1), (start+3), -1 0f 0f 00 subleq (zero), (zero), start ; useful constants zero: 00 .data 0 neg1: ff .data -1 ; the message to print message: .data "Hello, world!\n\0" 48 65 6c 6c 6f 2c 20 77 6f 72 6c 64 21 0a 00
#APL
APL
#!/usr/local/bin/apl -s -- ⎕IO←0 ⍝ Index origin 0 is more intuitive with 'pointers' ∇Subleq;fn;text;M;A;B;C;X →(5≠⍴⎕ARG)/usage ⍝ There should be one (additional) argument fn←⊃⎕ARG[4] ⍝ This argument should be the file name →(''≢0⍴text←⎕FIO[26]fn)/filerr ⍝ Load the file text[(text∊⎕TC)/⍳⍴text]←' ' ⍝ Control characters to spaces text[(text='-')/⍳⍴text]←'¯' ⍝ Negative numbers get high minus M←⍎text ⍝ The memory starts with the numbers in the text pc←0 ⍝ Program counter starts at PC   instr: (A B C)←3↑pc↓M ⍝ Read instruction M←'(1+A⌈B⌈C⌈⍴M)↑M'⎕EA'M⊣M[A,B,C]' ⍝ Extend the array if necessary pc←pc+3 ⍝ PC is incremented by 3 →(A=¯1)/in ⍝ If A=-1, read input →(B=¯1)/out ⍝ If B=-1, write output →(0<M[B]←M[B]-M[A])/instr ⍝ Do SUBLEQ instruction pc←C ⍝ Set PC if necessary →(C≥0)×instr ⍝ Next instruction if C≥0   in: X←(M[B]←1⎕FIO[41]1)⎕FIO[42]1 ⋄ →instr out: X←M[A]⎕FIO[42]1 ⋄ →instr   usage: 'subleq.apl <file> - Run the SUBLEQ program in <file>' ⋄ →0 filerr: 'Error loading: ',fn ⋄ →0 ∇   Subleq )OFF  
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
#F.23
F#
  // Successive primes. Nigel Galloway: May 6th., 2019 let sP n=let sP=pCache|>Seq.takeWhile(fun n->n<1000000)|>Seq.windowed(Array.length n+1)|>Seq.filter(fun g->g=(Array.scan(fun n g->n+g) g.[0] n)) printfn "sP %A\t-> Min element = %A Max element = %A of %d elements" n (Seq.head sP) (Seq.last sP) (Seq.length sP) List.iter sP [[|2|];[|1|];[|2;2|];[|2;4|];[|4;2|];[|6;4;2|]]  
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
#BASIC
BASIC
10 PRINT FN F$("KNIGHTS"): REM STRIP THE FIRST LETTER 20 PRINT FN L$("SOCKS"): REM STRIP THE LAST LETTER 30 PRINT FN B$("BROOMS"): REM STRIP BOTH THE FIRST AND LAST LETTER 100 END   9000 DEF FN F$(A$)=RIGHT$(A$,LEN(A$)-1) 9010 DEF FN L$(A$)=LEFT$(A$,LEN(A$)-1) 9020 DEF FN B$(A$)=FN L$(FN F$(A$))
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.
#Elixir
Elixir
defmodule Subtractive do def new(seed) when seed in 0..999_999_999 do s = Enum.reduce(1..53, [1, seed], fn _,[a,b|_]=acc -> [b-a | acc] end) |> Enum.reverse |> List.to_tuple state = for i <- 1..55, do: elem(s, rem(34*i, 55)) {:ok, _pid} = Agent.start_link(fn -> state end, name: :Subtractive) Enum.each(1..220, fn _ -> rand end) # Discard first 220 elements of sequence. end   def rand do state = Agent.get(:Subtractive, &(&1)) n = rem(Enum.at(state, -55) - Enum.at(state, -24) + 1_000_000_000, 1_000_000_000)  :ok = Agent.update(:Subtractive, fn _ -> tl(state) ++ [n] end) hd(state) end end   Subtractive.new(292929) for _ <- 1..10, do: IO.puts Subtractive.rand
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
#Phix
Phix
constant plain = tagset('Z','A')&tagset('z','a'), key = shuffle(plain) function encode(string s, integer decrypt=false) sequence {p,k} = iff(decrypt?{plain,key}:{key,plain}) for i=1 to length(s) do integer ki = find(s[i],p) if ki then s[i] = k[ki] end if end for return s end function string original = "A simple example.", encoded = encode(original), decoded = encode(encoded, true) printf(1,"original: %s\nencoded: %s\ndecoded: %s\n",{original,encoded,decoded})
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.
#E
E
pragma.enable("accumulator") accum 0 for x in [1,2,3,4,5] { _ + x } accum 1 for x in [1,2,3,4,5] { _ * x }
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.
#Delphi
Delphi
  unit Form_SumOfASeries_Unit;   interface   uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls;   type TFormSumOfASeries = class(TForm) M_Log: TMemo; B_Calc: TButton; procedure B_CalcClick(Sender: TObject); private { Private-Deklarationen } public { Public-Deklarationen } end;   var FormSumOfASeries: TFormSumOfASeries;   implementation   {$R *.dfm}   function Sum_Of_A_Series(_from,_to:int64):extended; begin result:=0; while _from<=_to do begin result:=result+1.0/(_from*_from); inc(_from); end; end;   procedure TFormSumOfASeries.B_CalcClick(Sender: TObject); begin try M_Log.Lines.Add(FloatToStr(Sum_Of_A_Series(1, 1000))); except M_Log.Lines.Add('Error'); end; end;   end.