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/Echo_server
Echo server
Create a network service that sits on TCP port 12321, which accepts connections on that port, and which echoes complete lines (using a carriage-return/line-feed sequence as line separator) back to clients. No error handling is required. For the purposes of testing, it is only necessary to support connections from localhost (127.0.0.1 or perhaps ::1). Logging of connection information to standard output is recommended. The implementation must be able to handle simultaneous connections from multiple clients. A multi-threaded or multi-process solution may be used. Each connection must be able to echo more than a single line. The implementation must not stop responding to other clients if one client sends a partial line or stops reading responses.
#Common_Lisp
Common Lisp
(ql:quickload (list :usocket)) (defpackage :echo (:use :cl :usocket)) (in-package :echo)   (defun read-all (stream) (loop for char = (read-char-no-hang stream nil :eof) until (or (null char) (eql char :eof)) collect char into msg finally (return (values msg char))))   (defun echo-server (port &optional (log-stream *standard-output*)) (let ((connections (list (socket-listen "127.0.0.1" port :reuse-address t)))) (unwind-protect (loop (loop for ready in (wait-for-input connections :ready-only t) do (if (typep ready 'stream-server-usocket) (push (socket-accept ready) connections) (let* ((stream (socket-stream ready)) (msg (concatenate 'string "You said: " (read-all stream)))) (format log-stream "Got message...~%") (write-string msg stream) (socket-close ready) (setf connections (remove ready connections)))))) (loop for c in connections do (loop while (socket-close c))))))   (echo-server 12321)  
http://rosettacode.org/wiki/Elementary_cellular_automaton/Infinite_length
Elementary cellular automaton/Infinite length
The purpose of this task is to create a version of an Elementary cellular automaton whose number of cells is only limited by the memory size of the computer. To be precise, consider the state of the automaton to be made of an infinite number of cells, but with a bounded support. In other words, to describe the state of the automaton, you need a finite number of adjacent cells, along with their individual state, and you then consider that the individual state of each of all other cells is the negation of the closest individual cell among the previously defined finite number of cells. Examples: 1 -> ..., 0, 0, 1, 0, 0, ... 0, 1 -> ..., 1, 1, 0, 1, 0, 0, ... 1, 0, 1 -> ..., 0, 0, 1, 0, 1, 0, 0, ... More complex methods can be imagined, provided it is possible to somehow encode the infinite sections. But for this task we will stick to this simple version.
#Phix
Phix
with javascript_semantics string s = ".#.", t=s, r = "........" integer rule = 18, k, l = length(s), w = 0 for i=1 to 8 do r[i] = iff(mod(rule,2)?'#':'.') rule = floor(rule/2) end for for i=0 to 25 do ?repeat(' ',floor((55-length(s))/2))&s for j=1 to l do k = (s[iff(j=1?l:j-1)]='#')*4 + (s[ j ]='#')*2 + (s[iff(j=l?1:j+1)]='#')+1 t[j] = r[k] end for if t[1]='#' then t = '.'&t end if if t[$]='#' then t = t&'.' end if l = length(t) s = t end for
http://rosettacode.org/wiki/EKG_sequence_convergence
EKG sequence convergence
The sequence is from the natural numbers and is defined by: a(1) = 1; a(2) = Start = 2; for n > 2, a(n) shares at least one prime factor with a(n-1) and is the smallest such natural number not already used. The sequence is called the EKG sequence (after its visual similarity to an electrocardiogram when graphed). Variants of the sequence can be generated starting 1, N where N is any natural number larger than one. For the purposes of this task let us call: The sequence described above , starting 1, 2, ... the EKG(2) sequence; the sequence starting 1, 3, ... the EKG(3) sequence; ... the sequence starting 1, N, ... the EKG(N) sequence. Convergence If an algorithm that keeps track of the minimum amount of numbers and their corresponding prime factors used to generate the next term is used, then this may be known as the generators essential state. Two EKG generators with differing starts can converge to produce the same sequence after initial differences. EKG(N1) and EKG(N2) are said to to have converged at and after generation a(c) if state_of(EKG(N1).a(c)) == state_of(EKG(N2).a(c)). Task Calculate and show here the first 10 members of EKG(2). Calculate and show here the first 10 members of EKG(5). Calculate and show here the first 10 members of EKG(7). Calculate and show here the first 10 members of EKG(9). Calculate and show here the first 10 members of EKG(10). Calculate and show here at which term EKG(5) and EKG(7) converge   (stretch goal). Related Tasks Greatest common divisor Sieve of Eratosthenes Reference The EKG Sequence and the Tree of Numbers. (Video).
#REXX
REXX
/*REXX program can generate and display several EKG sequences (with various starts).*/ parse arg nums start /*obtain optional arguments from the CL*/ if nums=='' | nums=="," then nums= 50 /*Not specified? Then use the default.*/ if start= '' | start= "," then start=2 5 7 9 10 /* " " " " " " */   do s=1 for words(start); $= /*step through the specified STARTs. */ second= word(start, s); say /*obtain the second integer in the seq.*/   do j=1 for nums if j<3 then do; #=1; if j==2 then #=second; end /*handle 1st & 2nd number*/ else #= ekg(#) $= $ right(#, max(2, length(#) ) ) /*append the EKG integer to the $ list.*/ end /*j*/ /* [↑] the RIGHT BIF aligns the numbers*/ say '(start' right(second, max(2, length(second) ) )"):"$ /*display EKG seq.*/ end /*s*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ add_: do while z//j == 0; z=z%j; _=_ j; w=w+1; end; return strip(_) /*──────────────────────────────────────────────────────────────────────────────────────*/ ekg: procedure expose $; parse arg x 1 z,,_ w=0 /*W: number of factors.*/ do k=1 to 11 by 2; j=k; if j==1 then j=2 /*divide by low primes. */ if j==9 then iterate; call add_ /*skip ÷ 9; add to list.*/ end /*k*/ /*↓ skips multiples of 3*/ do y=0 by 2; j= j + 2 + y//4 /*increment J by 2 or 4.*/ parse var j '' -1 r; if r==5 then iterate /*divisible by five ? */ if j*j>x | j>z then leave /*passed the sqrt(x) ? */ _= add_() /*add a factor to list. */ end /*y*/ j=z; if z\==1 then _= add_() /*Z¬=1? Then add──►list.*/ if _='' then _=x /*Null? Then use prime. */ do j=3; done=1 do k=1 for w if j // word(_, k)==0 then do; done=0; leave; end end /*k*/ if done then iterate if wordpos(j, $)==0 then return j /*return an EKG integer.*/ end /*j*/
http://rosettacode.org/wiki/Empty_string
Empty string
Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. 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
#UNIX_Shell
UNIX Shell
# assign an empty string to a variable s=""   # the "test" command can determine truth by examining the string itself if [ "$s" ]; then echo "not empty"; else echo "empty"; fi   # compare the string to the empty string if [ "$s" = "" ]; then echo "s is the empty string"; fi if [ "$s" != "" ]; then echo "s is not empty"; fi   # examine the length of the string if [ -z "$s" ]; then echo "the string has length zero: it is empty"; fi if [ -n "$s" ]; then echo "the string has length non-zero: it is not empty"; fi
http://rosettacode.org/wiki/Empty_string
Empty string
Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. 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
#Ursa
Ursa
decl string s set s ""   if (= s "") out "empty" endl console else out "not empty" endl console end if
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Retro
Retro
 
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#REXX
REXX
 
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Rhope
Rhope
Main(0,0) |: :|
http://rosettacode.org/wiki/Element-wise_operations
Element-wise operations
This task is similar to:   Matrix multiplication   Matrix transposition Task Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks. Implement:   addition   subtraction   multiplication   division   exponentiation Extend the task if necessary to include additional basic operations, which should not require their own specialised task.
#ALGOL_68
ALGOL 68
#!/usr/local/bin/a68g --script #   MODE SCALAR = REAL; FORMAT scalar fmt = $g(0, 2)$;   MODE MATRIX = [3, 3]SCALAR; FORMAT vector fmt = $"("n(2 UPB LOC MATRIX - 2 LWB LOC MATRIX)(f(scalar fmt)", ")f(scalar fmt)")"$; FORMAT matrix fmt = $"("n(1 UPB LOC MATRIX - 1 LWB LOC MATRIX)(f(vector fmt)","l" ")f(vector fmt)")"$;   PROC elementwise op = (PROC(SCALAR, SCALAR)SCALAR op, MATRIX a, UNION(SCALAR, MATRIX) b)MATRIX: ( [LWB a:UPB a, 2 LWB a:2 UPB a]SCALAR out; CASE b IN (SCALAR b): FOR i FROM LWB out TO UPB out DO FOR j FROM 2 LWB out TO 2 UPB out DO out[i, j]:=op(a[i, j], b) OD OD, (MATRIX b): FOR i FROM LWB out TO UPB out DO FOR j FROM 2 LWB out TO 2 UPB out DO out[i, j]:=op(a[i, j], b[i, j]) OD OD ESAC; out );   PROC plus = (SCALAR a, b)SCALAR: a+b, minus = (SCALAR a, b)SCALAR: a-b, times = (SCALAR a, b)SCALAR: a*b, div = (SCALAR a, b)SCALAR: a/b, pow = (SCALAR a, b)SCALAR: a**b;   main:( SCALAR scalar := 10; MATRIX matrix = (( 7, 11, 13), (17, 19, 23), (29, 31, 37));   printf(($f(matrix fmt)";"l$, elementwise op(plus, matrix, scalar), elementwise op(minus, matrix, scalar), elementwise op(times, matrix, scalar), elementwise op(div, matrix, scalar), elementwise op(pow, matrix, scalar),   elementwise op(plus, matrix, matrix), elementwise op(minus, matrix, matrix), elementwise op(times, matrix, matrix), elementwise op(div, matrix, matrix), elementwise op(pow, matrix, matrix) )) )
http://rosettacode.org/wiki/Egyptian_division
Egyptian division
Egyptian division is a method of dividing integers using addition and doubling that is similar to the algorithm of Ethiopian multiplication Algorithm: Given two numbers where the dividend is to be divided by the divisor: Start the construction of a table of two columns: powers_of_2, and doublings; by a first row of a 1 (i.e. 2^0) in the first column and 1 times the divisor in the first row second column. Create the second row with columns of 2 (i.e 2^1), and 2 * divisor in order. Continue with successive i’th rows of 2^i and 2^i * divisor. Stop adding rows, and keep only those rows, where 2^i * divisor is less than or equal to the dividend. We now assemble two separate sums that both start as zero, called here answer and accumulator Consider each row of the table, in the reverse order of its construction. If the current value of the accumulator added to the doublings cell would be less than or equal to the dividend then add it to the accumulator, as well as adding the powers_of_2 cell value to the answer. When the first row has been considered as above, then the integer division of dividend by divisor is given by answer. (And the remainder is given by the absolute value of accumulator - dividend). Example: 580 / 34 Table creation: powers_of_2 doublings 1 34 2 68 4 136 8 272 16 544 Initialization of sums: powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 0 0 Considering table rows, bottom-up: When a row is considered it is shown crossed out if it is not accumulated, or bold if the row causes summations. powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 4 136 16 544 8 272 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 16 544 4 136 8 272 16 544 powers_of_2 doublings answer accumulator 1 34 17 578 2 68 4 136 8 272 16 544 Answer So 580 divided by 34 using the Egyptian method is 17 remainder (578 - 580) or 2. Task The task is to create a function that does Egyptian division. The function should closely follow the description above in using a list/array of powers of two, and another of doublings. Functions should be clear interpretations of the algorithm. Use the function to divide 580 by 34 and show the answer here, on this page. Related tasks   Egyptian fractions References   Egyptian Number System
#11l
11l
F egyptian_divmod(dividend, divisor) assert(divisor != 0) V (pwrs, dbls) = ([1], [divisor]) L dbls.last <= dividend pwrs.append(pwrs.last * 2) dbls.append(pwrs.last * divisor) V (ans, accum) = (0, 0) L(pwr, dbl) zip(pwrs[((len)-2 ..).step(-1)], dbls[((len)-2 ..).step(-1)]) I accum + dbl <= dividend accum += dbl ans += pwr R (ans, abs(accum - dividend))   L(i, j) cart_product(0.<13, 1..12) assert(egyptian_divmod(i, j) == divmod(i, j)) V (i, j) = (580, 34) V (d, m) = egyptian_divmod(i, j) print(‘#. divided by #. using the Egyption method is #. remainder #.’.format(i, j, d, m))
http://rosettacode.org/wiki/Eertree
Eertree
An eertree is a data structure designed for efficient processing of certain palindrome tasks, for instance counting the number of sub-palindromes in an input string. The data structure has commonalities to both tries and suffix trees.   See links below. Task Construct an eertree for the string "eertree", then output all sub-palindromes by traversing the tree. See also   Wikipedia entry:   trie.   Wikipedia entry:   suffix tree   Cornell University Library, Computer Science, Data Structures and Algorithms ───► EERTREE: An Efficient Data Structure for Processing Palindromes in Strings.
#Go
Go
package main   import "fmt"   func main() { tree := eertree([]byte("eertree")) fmt.Println(subPalindromes(tree)) }   type edges map[byte]int   type node struct { length int edges suffix int }   const evenRoot = 0 const oddRoot = 1   func eertree(s []byte) []node { tree := []node{ evenRoot: {length: 0, suffix: oddRoot, edges: edges{}}, oddRoot: {length: -1, suffix: oddRoot, edges: edges{}}, } suffix := oddRoot var n, k int for i, c := range s { for n = suffix; ; n = tree[n].suffix { k = tree[n].length if b := i - k - 1; b >= 0 && s[b] == c { break } } if e, ok := tree[n].edges[c]; ok { suffix = e continue } suffix = len(tree) tree = append(tree, node{length: k + 2, edges: edges{}}) tree[n].edges[c] = suffix if tree[suffix].length == 1 { tree[suffix].suffix = 0 continue } for { n = tree[n].suffix if b := i - tree[n].length - 1; b >= 0 && s[b] == c { break } } tree[suffix].suffix = tree[n].edges[c] } return tree }   func subPalindromes(tree []node) (s []string) { var children func(int, string) children = func(n int, p string) { for c, n := range tree[n].edges { c := string(c) p := c + p + c s = append(s, p) children(n, p) } } children(0, "") for c, n := range tree[1].edges { c := string(c) s = append(s, c) children(n, c) } return }
http://rosettacode.org/wiki/Ethiopian_multiplication
Ethiopian multiplication
Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last in the same column, until you write a value of 1. In the right-hand column repeatedly double the last number and write the result below. stop when you add a result in the same row as where the left hand column shows 1. Examine the table produced and discard any row where the value in the left column is even. Sum the values in the right-hand column that remain to produce the result of multiplying the original two numbers together For example:   17 × 34 17 34 Halving the first column: 17 34 8 4 2 1 Doubling the second column: 17 34 8 68 4 136 2 272 1 544 Strike-out rows whose first cell is even: 17 34 8 68 4 136 2 272 1 544 Sum the remaining numbers in the right-hand column: 17 34 8 -- 4 --- 2 --- 1 544 ==== 578 So 17 multiplied by 34, by the Ethiopian method is 578. Task The task is to define three named functions/methods/procedures/subroutines: one to halve an integer, one to double an integer, and one to state if an integer is even. Use these functions to create a function that does Ethiopian multiplication. References Ethiopian multiplication explained (BBC Video clip) A Night Of Numbers - Go Forth And Multiply (Video) Russian Peasant Multiplication Programming Praxis: Russian Peasant Multiplication
#Plain_English
Plain English
\All required helper routines already exist in Plain English: \ \To cut a number in half: \Divide the number by 2. \ \To double a number: \Add the number to the number. \ \To decide if a number is odd: \Privatize the number. \Bitwise and the number with 1. \If the number is 0, say no. \Say yes.   To run: Start up. Put 17 into a number. Multiply the number by 34 (Ethiopian). Convert the number to a string. Write the string to the console. Wait for the escape key. Shut down.   To multiply a number by another number (Ethiopian): Put 0 into a sum number. Loop. If the number is 0, break. If the number is odd, add the other number to the sum. Cut the number in half. Double the other number. Repeat. Put the sum into the number.
http://rosettacode.org/wiki/Elementary_cellular_automaton
Elementary cellular automaton
An elementary cellular automaton is a one-dimensional cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors. Those three values can be encoded with three bits. The rules of evolution are then encoded with eight bits indicating the outcome of each of the eight possibilities 111, 110, 101, 100, 011, 010, 001 and 000 in this order. Thus for instance the rule 13 means that a state is updated to 1 only in the cases 011, 010 and 000, since 13 in binary is 0b00001101. Task Create a subroutine, program or function that allows to create and visualize the evolution of any of the 256 possible elementary cellular automaton of arbitrary space length and for any given initial state. You can demonstrate your solution with any automaton of your choice. The space state should wrap: this means that the left-most cell should be considered as the right neighbor of the right-most cell, and reciprocally. This task is basically a generalization of one-dimensional cellular automata. See also Cellular automata (natureofcode.com)
#C
C
#include <stdio.h> #include <limits.h>   typedef unsigned long long ull; #define N (sizeof(ull) * CHAR_BIT) #define B(x) (1ULL << (x))   void evolve(ull state, int rule) { int i; ull st;   printf("Rule %d:\n", rule); do { st = state; for (i = N; i--; ) putchar(st & B(i) ? '#' : '.'); putchar('\n');   for (state = i = 0; i < N; i++) if (rule & B(7 & (st>>(i-1) | st<<(N+1-i)))) state |= B(i); } while (st != state); }   int main(int argc, char **argv) { evolve(B(N/2), 90); evolve(B(N/4)|B(N - N/4), 30); // well, enjoy the fireworks   return 0; }
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterative or recursive. Support for trapping negative   n   errors is optional. Related task   Primorial numbers
#Standard_ML
Standard ML
fun factorial n = if n <= 0 then 1 else n * factorial (n-1)
http://rosettacode.org/wiki/Even_or_odd
Even or odd
Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Divide i by 2. The remainder equals 0 iff i is even. The remainder equals +1 or -1 iff i is odd. Use modular congruences: i ≡ 0 (mod 2) iff i is even. i ≡ 1 (mod 2) iff i is odd.
#SSEM
SSEM
11110000000000100000000000000000 0. -15 to c 00000000000000110000000000000000 1. Test 11110000000001100000000000000000 2. c to 15 11110000000000100000000000000000 3. -15 to c 00001000000001100000000000000000 4. c to 16 00001000000000100000000000000000 5. -16 to c 01110000000000010000000000000000 6. Sub. 14 11110000000001100000000000000000 7. c to 15 10110000000000010000000000000000 8. Sub. 13 00000000000000110000000000000000 9. Test 01110000000000000000000000000000 10. 14 to CI 11110000000000100000000000000000 11. -15 to c 00000000000001110000000000000000 12. Stop 10000000000000000000000000000000 13. 1 01000000000000000000000000000000 14. 2
http://rosettacode.org/wiki/Even_or_odd
Even or odd
Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Divide i by 2. The remainder equals 0 iff i is even. The remainder equals +1 or -1 iff i is odd. Use modular congruences: i ≡ 0 (mod 2) iff i is even. i ≡ 1 (mod 2) iff i is odd.
#Standard_ML
Standard ML
fun even n = n mod 2 = 0;   fun odd n = n mod 2 <> 0;   (* bitwise and *)   type werd = Word.word;   fun evenbitw(w: werd) = Word.andb(w, 0w2) = 0w0;   fun oddbitw(w: werd) = Word.andb(w, 0w2) <> 0w0;
http://rosettacode.org/wiki/Echo_server
Echo server
Create a network service that sits on TCP port 12321, which accepts connections on that port, and which echoes complete lines (using a carriage-return/line-feed sequence as line separator) back to clients. No error handling is required. For the purposes of testing, it is only necessary to support connections from localhost (127.0.0.1 or perhaps ::1). Logging of connection information to standard output is recommended. The implementation must be able to handle simultaneous connections from multiple clients. A multi-threaded or multi-process solution may be used. Each connection must be able to echo more than a single line. The implementation must not stop responding to other clients if one client sends a partial line or stops reading responses.
#D
D
import std.array, std.socket;   void main() { auto listener = new TcpSocket; assert(listener.isAlive); listener.bind(new InternetAddress(12321)); listener.listen(10);   Socket currSock; uint bytesRead; ubyte[1] buff;   while (true) { currSock = listener.accept(); while ((bytesRead = currSock.receive(buff)) > 0) currSock.send(buff); currSock.close(); buff.clear(); } }
http://rosettacode.org/wiki/Elementary_cellular_automaton/Infinite_length
Elementary cellular automaton/Infinite length
The purpose of this task is to create a version of an Elementary cellular automaton whose number of cells is only limited by the memory size of the computer. To be precise, consider the state of the automaton to be made of an infinite number of cells, but with a bounded support. In other words, to describe the state of the automaton, you need a finite number of adjacent cells, along with their individual state, and you then consider that the individual state of each of all other cells is the negation of the closest individual cell among the previously defined finite number of cells. Examples: 1 -> ..., 0, 0, 1, 0, 0, ... 0, 1 -> ..., 1, 1, 0, 1, 0, 0, ... 1, 0, 1 -> ..., 0, 0, 1, 0, 1, 0, 0, ... More complex methods can be imagined, provided it is possible to somehow encode the infinite sections. But for this task we will stick to this simple version.
#Python
Python
def _notcell(c): return '0' if c == '1' else '1'   def eca_infinite(cells, rule): lencells = len(cells) rulebits = '{0:08b}'.format(rule) neighbours2next = {'{0:03b}'.format(n):rulebits[::-1][n] for n in range(8)} c = cells while True: yield c c = _notcell(c[0])*2 + c + _notcell(c[-1])*2 # Extend and pad the ends   c = ''.join(neighbours2next[c[i-1:i+2]] for i in range(1,len(c) - 1)) #yield c[1:-1]   if __name__ == '__main__': lines = 25 for rule in (90, 30): print('\nRule: %i' % rule) for i, c in zip(range(lines), eca_infinite('1', rule)): print('%2i: %s%s' % (i, ' '*(lines - i), c.replace('0', '.').replace('1', '#')))
http://rosettacode.org/wiki/Elementary_cellular_automaton/Infinite_length
Elementary cellular automaton/Infinite length
The purpose of this task is to create a version of an Elementary cellular automaton whose number of cells is only limited by the memory size of the computer. To be precise, consider the state of the automaton to be made of an infinite number of cells, but with a bounded support. In other words, to describe the state of the automaton, you need a finite number of adjacent cells, along with their individual state, and you then consider that the individual state of each of all other cells is the negation of the closest individual cell among the previously defined finite number of cells. Examples: 1 -> ..., 0, 0, 1, 0, 0, ... 0, 1 -> ..., 1, 1, 0, 1, 0, 0, ... 1, 0, 1 -> ..., 0, 0, 1, 0, 1, 0, 0, ... More complex methods can be imagined, provided it is possible to somehow encode the infinite sections. But for this task we will stick to this simple version.
#Racket
Racket
#lang racket ; below is the code from the parent task (require "Elementary_cellular_automata.rkt") (require racket/fixnum)   (define (wrap-rule-infinite v-in vl-1 offset) (define l-bit-set? (bitwise-bit-set? (fxvector-ref v-in 0) usable-bits/fixnum-1)) (define r-bit-set? (bitwise-bit-set? (fxvector-ref v-in vl-1) 0))  ;; if we need to extend left offset is reduced by 1 (define l-pad-words (if l-bit-set? 1 0)) (define r-pad-words (if r-bit-set? 1 0)) (define new-words (fx+ l-pad-words r-pad-words)) (cond [(fx= 0 new-words) (values v-in vl-1 offset)] ; nothing changes [else (define offset- (if l-bit-set? (fx- offset 1) offset)) (define l-sequence (if l-bit-set? (in-value 0) (in-sequences))) (define vl-1+ (fx+ vl-1 (fx+ l-pad-words r-pad-words))) (define v-out (for/fxvector #:length (fx+ vl-1+ 1) #:fill 0 ; right padding ([f (in-sequences l-sequence (in-fxvector v-in))]) f)) (values v-out vl-1+ offset-)]))   (module+ main (define ng/90/infinite (CA-next-generation 90 #:wrap-rule wrap-rule-infinite)) (for/fold ([v (fxvector #b10000000000000000000)] [o 1]) ; start by pushing output right by one ([step (in-range 40)]) (show-automaton v #:step step #:push-right o) (newline) (ng/90/infinite v o)))
http://rosettacode.org/wiki/EKG_sequence_convergence
EKG sequence convergence
The sequence is from the natural numbers and is defined by: a(1) = 1; a(2) = Start = 2; for n > 2, a(n) shares at least one prime factor with a(n-1) and is the smallest such natural number not already used. The sequence is called the EKG sequence (after its visual similarity to an electrocardiogram when graphed). Variants of the sequence can be generated starting 1, N where N is any natural number larger than one. For the purposes of this task let us call: The sequence described above , starting 1, 2, ... the EKG(2) sequence; the sequence starting 1, 3, ... the EKG(3) sequence; ... the sequence starting 1, N, ... the EKG(N) sequence. Convergence If an algorithm that keeps track of the minimum amount of numbers and their corresponding prime factors used to generate the next term is used, then this may be known as the generators essential state. Two EKG generators with differing starts can converge to produce the same sequence after initial differences. EKG(N1) and EKG(N2) are said to to have converged at and after generation a(c) if state_of(EKG(N1).a(c)) == state_of(EKG(N2).a(c)). Task Calculate and show here the first 10 members of EKG(2). Calculate and show here the first 10 members of EKG(5). Calculate and show here the first 10 members of EKG(7). Calculate and show here the first 10 members of EKG(9). Calculate and show here the first 10 members of EKG(10). Calculate and show here at which term EKG(5) and EKG(7) converge   (stretch goal). Related Tasks Greatest common divisor Sieve of Eratosthenes Reference The EKG Sequence and the Tree of Numbers. (Video).
#Sidef
Sidef
class Seq(terms, callback) { method next { terms += callback(terms) }   method nth(n) { while (terms.len < n) { self.next } terms[n-1] }   method first(n) { while (terms.len < n) { self.next } terms.first(n) } }   func next_EKG (s) { 2..Inf -> first {|k|  !(s.contains(k) || s[-1].is_coprime(k)) } }   func EKG (start) { Seq([1, start], next_EKG) }   func converge_at(ints) { var ekgs = ints.map(EKG)   2..Inf -> first {|k| (ekgs.map { .nth(k) }.uniq.len == 1) && (ekgs.map { .first(k).sort }.uniq.len == 1) } }   for k in [2, 5, 7, 9, 10] { say "EKG(#{k}) = #{EKG(k).first(10)}" }   for arr in [[5,7], [2, 5, 7, 9, 10]] { var c = converge_at(arr) say "EKGs of #{arr} converge at term #{c}" }
http://rosettacode.org/wiki/Empty_string
Empty string
Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. 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
#VAX_Assembly
VAX Assembly
desc: .ascid "not empty"  ;descriptor (len+addr) and text .entry empty, ^m<> tstw desc  ;check length field beql is_empty  ;... not empty clrw desc  ;set length to zero -> empty is_empty:  ;... empty ret .end empty
http://rosettacode.org/wiki/Empty_string
Empty string
Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. 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
#VBA
VBA
  dim s as string   ' assign an empty string to a variable (six bytes): s = "" ' assign null string pointer to a variable (zero bytes, according to RubberduckVBA): s = vbNullString ' if your VBA code interacts with non-VBA code, this difference may become significant! ' test if a string is empty: if s = "" then Debug.Print "empty!" ' or: if Len(s) = 0 then Debug.Print "still empty!"   'test if a string is not empty: if s <> "" then Debug.Print "not an empty string" 'or: if Len(s) > 0 then Debug.Print "not empty."  
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Ring
Ring
 
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Robotic
Robotic
 
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Ruby
Ruby
#!/usr/bin/env ruby
http://rosettacode.org/wiki/Element-wise_operations
Element-wise operations
This task is similar to:   Matrix multiplication   Matrix transposition Task Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks. Implement:   addition   subtraction   multiplication   division   exponentiation Extend the task if necessary to include additional basic operations, which should not require their own specialised task.
#Amazing_Hopper
Amazing Hopper
  #include <hopper.h>   main: /* create an integer random array */ A=-1,{10}rand array(A), mulby(10), ceil, mov(A) {","}tok sep {"\ENF","ORIGINAL ARRAY :",A,"\OFF\n","="}reply(90), println {"Increment :\t"}, ++A,{A} println {"Decrement :\t"}, --A,{A} println {"post Increment: "}, A++, println {*"\t",A} println {"post Decrement: "}, A--, println {*"\t",A} println {"A + 5 :\t\t"}, {A} plus (5), println {"5 + A :\t\t"}, {5} plus (A), println {"A - 5 :\t\t"}, {A} minus (5), println {"5 - A :\t\t"}, {5} minus (A), println {"A * 5 :\t\t"}, {A} mul by (5), println {"5 * A :\t\t"}, {5} mul by (A), println {"A / 5 :\t\t"}, {A} div by (5), println {"5 / A :\t\t"}, {5} div by (A), println {"A \ 5 :\t\t"}, {A} idiv by (5), println {"5 \ A :\t\t"}, {5} idiv by (A), println {"A ^ 5 :\t\t"}, {A} pow by (5), println {"5 ^ A :\t\t"}, {5} pow by (A), println {"A % 5 :\t\t"}, {A} module (5), println {"5 % A :\t\t"}, {5} module (A), println {"SQRT(A) + 5:\t"}, {A} sqrt, plus(5), tmp=0,cpy(tmp), println {"--> CEIL :\t"} {tmp},ceil, println {"--> FLOOR :\t"} {tmp},floor, println {"A + A :\t\t"}, {A} plus (A), println {"A - A :\t\t"}, {A} minus (A), println {"A * A :\t\t"}, {A} mulby (A), println {"A / A :\t\t"}, {A} div by (A), println {"A \ A :\t\t"}, {A} idiv by (A), println {"A ^ A :\t\t"}, {A} pow by (A), println {"A % A :\t\t"}, {A} module (A), println {"Etcetera...\n"}, println exit(0)  
http://rosettacode.org/wiki/Egyptian_division
Egyptian division
Egyptian division is a method of dividing integers using addition and doubling that is similar to the algorithm of Ethiopian multiplication Algorithm: Given two numbers where the dividend is to be divided by the divisor: Start the construction of a table of two columns: powers_of_2, and doublings; by a first row of a 1 (i.e. 2^0) in the first column and 1 times the divisor in the first row second column. Create the second row with columns of 2 (i.e 2^1), and 2 * divisor in order. Continue with successive i’th rows of 2^i and 2^i * divisor. Stop adding rows, and keep only those rows, where 2^i * divisor is less than or equal to the dividend. We now assemble two separate sums that both start as zero, called here answer and accumulator Consider each row of the table, in the reverse order of its construction. If the current value of the accumulator added to the doublings cell would be less than or equal to the dividend then add it to the accumulator, as well as adding the powers_of_2 cell value to the answer. When the first row has been considered as above, then the integer division of dividend by divisor is given by answer. (And the remainder is given by the absolute value of accumulator - dividend). Example: 580 / 34 Table creation: powers_of_2 doublings 1 34 2 68 4 136 8 272 16 544 Initialization of sums: powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 0 0 Considering table rows, bottom-up: When a row is considered it is shown crossed out if it is not accumulated, or bold if the row causes summations. powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 4 136 16 544 8 272 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 16 544 4 136 8 272 16 544 powers_of_2 doublings answer accumulator 1 34 17 578 2 68 4 136 8 272 16 544 Answer So 580 divided by 34 using the Egyptian method is 17 remainder (578 - 580) or 2. Task The task is to create a function that does Egyptian division. The function should closely follow the description above in using a list/array of powers of two, and another of doublings. Functions should be clear interpretations of the algorithm. Use the function to divide 580 by 34 and show the answer here, on this page. Related tasks   Egyptian fractions References   Egyptian Number System
#Action.21
Action!
TYPE Answer=[CARD result,reminder]   PROC EgyptianDivision(CARD dividend,divisor Answer POINTER res) DEFINE SIZE="16" CARD ARRAY powers(SIZE),doublings(SIZE) CARD power,doubling,accumulator INT i,count   count=0 power=1 doubling=divisor WHILE count<SIZE AND doubling<=dividend DO powers(count)=power doublings(count)=doubling count==+1 power==LSH 1 doubling==LSH 1 OD   i=count-1 res.result=0 accumulator=0 WHILE i>=0 DO IF accumulator+doublings(i)<=dividend THEN accumulator==+doublings(i) res.result==+powers(i) FI i==-1 OD res.reminder=dividend-accumulator RETURN   PROC Main() CARD dividend=[580],divisor=[34] Answer res   EgyptianDivision(dividend,divisor,res) PrintF("%U / %U = %U reminder %U",dividend,divisor,res.result,res.reminder) RETURN
http://rosettacode.org/wiki/Egyptian_division
Egyptian division
Egyptian division is a method of dividing integers using addition and doubling that is similar to the algorithm of Ethiopian multiplication Algorithm: Given two numbers where the dividend is to be divided by the divisor: Start the construction of a table of two columns: powers_of_2, and doublings; by a first row of a 1 (i.e. 2^0) in the first column and 1 times the divisor in the first row second column. Create the second row with columns of 2 (i.e 2^1), and 2 * divisor in order. Continue with successive i’th rows of 2^i and 2^i * divisor. Stop adding rows, and keep only those rows, where 2^i * divisor is less than or equal to the dividend. We now assemble two separate sums that both start as zero, called here answer and accumulator Consider each row of the table, in the reverse order of its construction. If the current value of the accumulator added to the doublings cell would be less than or equal to the dividend then add it to the accumulator, as well as adding the powers_of_2 cell value to the answer. When the first row has been considered as above, then the integer division of dividend by divisor is given by answer. (And the remainder is given by the absolute value of accumulator - dividend). Example: 580 / 34 Table creation: powers_of_2 doublings 1 34 2 68 4 136 8 272 16 544 Initialization of sums: powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 0 0 Considering table rows, bottom-up: When a row is considered it is shown crossed out if it is not accumulated, or bold if the row causes summations. powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 4 136 16 544 8 272 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 16 544 4 136 8 272 16 544 powers_of_2 doublings answer accumulator 1 34 17 578 2 68 4 136 8 272 16 544 Answer So 580 divided by 34 using the Egyptian method is 17 remainder (578 - 580) or 2. Task The task is to create a function that does Egyptian division. The function should closely follow the description above in using a list/array of powers of two, and another of doublings. Functions should be clear interpretations of the algorithm. Use the function to divide 580 by 34 and show the answer here, on this page. Related tasks   Egyptian fractions References   Egyptian Number System
#Ada
Ada
  with Ada.Text_IO;   procedure Egyptian_Division is   procedure Divide (a : Natural; b : Positive; q, r : out Natural) is doublings : array (0..31) of Natural; -- The natural type holds values < 2^32 so no need going beyond m, sum, last_index_touched : Natural := 0; begin for i in doublings'Range loop m := b * 2**i; exit when m > a ; doublings (i) := m; last_index_touched := i; end loop; q := 0; for i in reverse doublings'First .. last_index_touched loop m := sum + doublings (i); if m <= a then sum := m; q := q + 2**i; end if; end loop; r := a -sum; end Divide;   q, r : Natural; begin Divide (580,34, q, r); Ada.Text_IO.put_line ("Quotient="&q'Img & " Remainder="&r'img); end Egyptian_Division;  
http://rosettacode.org/wiki/Eertree
Eertree
An eertree is a data structure designed for efficient processing of certain palindrome tasks, for instance counting the number of sub-palindromes in an input string. The data structure has commonalities to both tries and suffix trees.   See links below. Task Construct an eertree for the string "eertree", then output all sub-palindromes by traversing the tree. See also   Wikipedia entry:   trie.   Wikipedia entry:   suffix tree   Cornell University Library, Computer Science, Data Structures and Algorithms ───► EERTREE: An Efficient Data Structure for Processing Palindromes in Strings.
#Java
Java
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;   public class Eertree { public static void main(String[] args) { List<Node> tree = eertree("eertree"); List<String> result = subPalindromes(tree); System.out.println(result); }   private static class Node { int length; Map<Character, Integer> edges = new HashMap<>(); int suffix;   public Node(int length) { this.length = length; }   public Node(int length, Map<Character, Integer> edges, int suffix) { this.length = length; this.edges = edges != null ? edges : new HashMap<>(); this.suffix = suffix; } }   private static final int EVEN_ROOT = 0; private static final int ODD_ROOT = 1;   private static List<Node> eertree(String s) { List<Node> tree = new ArrayList<>(); tree.add(new Node(0, null, ODD_ROOT)); tree.add(new Node(-1, null, ODD_ROOT)); int suffix = ODD_ROOT; int n, k; for (int i = 0; i < s.length(); ++i) { char c = s.charAt(i); for (n = suffix; ; n = tree.get(n).suffix) { k = tree.get(n).length; int b = i - k - 1; if (b >= 0 && s.charAt(b) == c) { break; } } if (tree.get(n).edges.containsKey(c)) { suffix = tree.get(n).edges.get(c); continue; } suffix = tree.size(); tree.add(new Node(k + 2)); tree.get(n).edges.put(c, suffix); if (tree.get(suffix).length == 1) { tree.get(suffix).suffix = 0; continue; } while (true) { n = tree.get(n).suffix; int b = i - tree.get(n).length - 1; if (b >= 0 && s.charAt(b) == c) { break; } } tree.get(suffix).suffix = tree.get(n).edges.get(c); } return tree; }   private static List<String> subPalindromes(List<Node> tree) { List<String> s = new ArrayList<>(); subPalindromes_children(0, "", tree, s); for (Map.Entry<Character, Integer> cm : tree.get(1).edges.entrySet()) { String ct = String.valueOf(cm.getKey()); s.add(ct); subPalindromes_children(cm.getValue(), ct, tree, s); } return s; }   // nested methods are a pain, even if lambdas make that possible for Java private static void subPalindromes_children(final int n, final String p, final List<Node> tree, List<String> s) { for (Map.Entry<Character, Integer> cm : tree.get(n).edges.entrySet()) { Character c = cm.getKey(); Integer m = cm.getValue(); String pl = c + p + c; s.add(pl); subPalindromes_children(m, pl, tree, s); } } }
http://rosettacode.org/wiki/Ethiopian_multiplication
Ethiopian multiplication
Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last in the same column, until you write a value of 1. In the right-hand column repeatedly double the last number and write the result below. stop when you add a result in the same row as where the left hand column shows 1. Examine the table produced and discard any row where the value in the left column is even. Sum the values in the right-hand column that remain to produce the result of multiplying the original two numbers together For example:   17 × 34 17 34 Halving the first column: 17 34 8 4 2 1 Doubling the second column: 17 34 8 68 4 136 2 272 1 544 Strike-out rows whose first cell is even: 17 34 8 68 4 136 2 272 1 544 Sum the remaining numbers in the right-hand column: 17 34 8 -- 4 --- 2 --- 1 544 ==== 578 So 17 multiplied by 34, by the Ethiopian method is 578. Task The task is to define three named functions/methods/procedures/subroutines: one to halve an integer, one to double an integer, and one to state if an integer is even. Use these functions to create a function that does Ethiopian multiplication. References Ethiopian multiplication explained (BBC Video clip) A Night Of Numbers - Go Forth And Multiply (Video) Russian Peasant Multiplication Programming Praxis: Russian Peasant Multiplication
#Powerbuilder
Powerbuilder
public function boolean wf_iseven (long al_arg);return mod(al_arg, 2 ) = 0 end function   public function long wf_halve (long al_arg);RETURN int(al_arg / 2) end function   public function long wf_double (long al_arg);RETURN al_arg * 2 end function   public function long wf_ethiopianmultiplication (long al_multiplicand, long al_multiplier);// calculate result long ll_product   DO WHILE al_multiplicand >= 1 IF wf_iseven(al_multiplicand) THEN // do nothing ELSE ll_product += al_multiplier END IF al_multiplicand = wf_halve(al_multiplicand) al_multiplier = wf_double(al_multiplier) LOOP   return ll_product end function   // example call long ll_answer ll_answer = wf_ethiopianmultiplication(17,34)
http://rosettacode.org/wiki/Elementary_cellular_automaton
Elementary cellular automaton
An elementary cellular automaton is a one-dimensional cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors. Those three values can be encoded with three bits. The rules of evolution are then encoded with eight bits indicating the outcome of each of the eight possibilities 111, 110, 101, 100, 011, 010, 001 and 000 in this order. Thus for instance the rule 13 means that a state is updated to 1 only in the cases 011, 010 and 000, since 13 in binary is 0b00001101. Task Create a subroutine, program or function that allows to create and visualize the evolution of any of the 256 possible elementary cellular automaton of arbitrary space length and for any given initial state. You can demonstrate your solution with any automaton of your choice. The space state should wrap: this means that the left-most cell should be considered as the right neighbor of the right-most cell, and reciprocally. This task is basically a generalization of one-dimensional cellular automata. See also Cellular automata (natureofcode.com)
#C.23
C#
  using System; using System.Collections; namespace ElementaryCellularAutomaton { class Automata { BitArray cells, ncells; const int MAX_CELLS = 19;   public void run() { cells = new BitArray(MAX_CELLS); ncells = new BitArray(MAX_CELLS); while (true) { Console.Clear(); Console.WriteLine("What Rule do you want to visualize"); doRule(int.Parse(Console.ReadLine())); Console.WriteLine("Press any key to continue..."); Console.ReadKey(); } }   private byte getCells(int index) { byte b; int i1 = index - 1, i2 = index, i3 = index + 1;   if (i1 < 0) i1 = MAX_CELLS - 1; if (i3 >= MAX_CELLS) i3 -= MAX_CELLS;   b = Convert.ToByte( 4 * Convert.ToByte(cells.Get(i1)) + 2 * Convert.ToByte(cells.Get(i2)) + Convert.ToByte(cells.Get(i3))); return b; }   private string getBase2(int i) { string s = Convert.ToString(i, 2); while (s.Length < 8) { s = "0" + s; } return s; }   private void doRule(int rule) { Console.Clear(); string rl = getBase2(rule); cells.SetAll(false); ncells.SetAll(false); cells.Set(MAX_CELLS / 2, true);   Console.WriteLine("Rule: " + rule + "\n----------\n");   for (int gen = 0; gen < 51; gen++) { Console.Write("{0, 4}", gen + ": ");   foreach (bool b in cells) Console.Write(b ? "#" : ".");   Console.WriteLine("");   int i = 0; while (true) { byte b = getCells(i); ncells[i] = '1' == rl[7 - b] ? true : false; if (++i == MAX_CELLS) break; }   i = 0; foreach (bool b in ncells) cells[i++] = b; } Console.WriteLine(""); }   }; class Program { static void Main(string[] args) { Automata t = new Automata(); t.run(); } } }  
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterative or recursive. Support for trapping negative   n   errors is optional. Related task   Primorial numbers
#Stata
Stata
mata real scalar function fact1(real scalar n) { if (n<2) return(1) else return(fact1(n-1)*n) }   real scalar function fact2(real scalar n) { a=1 for (i=2;i<=n;i++) a=a*i return(a) }   printf("%f\n",fact1(8)) printf("%f\n",fact2(8)) printf("%f\n",factorial(8))
http://rosettacode.org/wiki/Even_or_odd
Even or odd
Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Divide i by 2. The remainder equals 0 iff i is even. The remainder equals +1 or -1 iff i is odd. Use modular congruences: i ≡ 0 (mod 2) iff i is even. i ≡ 1 (mod 2) iff i is odd.
#Stata
Stata
mata function iseven(n) { return(mod(n,2)==0) }   function isodd(n) { return(mod(n,2)==1) } end
http://rosettacode.org/wiki/Even_or_odd
Even or odd
Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Divide i by 2. The remainder equals 0 iff i is even. The remainder equals +1 or -1 iff i is odd. Use modular congruences: i ≡ 0 (mod 2) iff i is even. i ≡ 1 (mod 2) iff i is odd.
#Swift
Swift
func isEven(n:Int) -> Bool {   // Bitwise check if (n & 1 != 0) { return false }   // Mod check if (n % 2 != 0) { return false } return true }
http://rosettacode.org/wiki/Echo_server
Echo server
Create a network service that sits on TCP port 12321, which accepts connections on that port, and which echoes complete lines (using a carriage-return/line-feed sequence as line separator) back to clients. No error handling is required. For the purposes of testing, it is only necessary to support connections from localhost (127.0.0.1 or perhaps ::1). Logging of connection information to standard output is recommended. The implementation must be able to handle simultaneous connections from multiple clients. A multi-threaded or multi-process solution may be used. Each connection must be able to echo more than a single line. The implementation must not stop responding to other clients if one client sends a partial line or stops reading responses.
#Delphi
Delphi
program EchoServer;   {$APPTYPE CONSOLE}   uses SysUtils, IdContext, IdTCPServer;   type TEchoServer = class private FTCPServer: TIdTCPServer; public constructor Create; destructor Destroy; override; procedure TCPServerExecute(AContext: TIdContext); end;   constructor TEchoServer.Create; begin FTCPServer := TIdTCPServer.Create(nil); FTCPServer.DefaultPort := 12321; FTCPServer.OnExecute := TCPServerExecute; FTCPServer.Active := True; end;   destructor TEchoServer.Destroy; begin FTCPServer.Active := False; FTCPServer.Free; inherited Destroy; end;   procedure TEchoServer.TCPServerExecute(AContext: TIdContext); var lCmdLine: string; begin lCmdLine := AContext.Connection.IOHandler.ReadLn; Writeln('>' + lCmdLine); AContext.Connection.IOHandler.Writeln('>' + lCmdLine);   if SameText(lCmdLine, 'QUIT') then begin AContext.Connection.IOHandler.Writeln('Disconnecting'); AContext.Connection.Disconnect; end; end;   var lEchoServer: TEchoServer; begin lEchoServer := TEchoServer.Create; try Writeln('Delphi Echo Server'); Writeln('Press Enter to quit'); Readln; finally lEchoServer.Free; end; end.
http://rosettacode.org/wiki/Elementary_cellular_automaton/Infinite_length
Elementary cellular automaton/Infinite length
The purpose of this task is to create a version of an Elementary cellular automaton whose number of cells is only limited by the memory size of the computer. To be precise, consider the state of the automaton to be made of an infinite number of cells, but with a bounded support. In other words, to describe the state of the automaton, you need a finite number of adjacent cells, along with their individual state, and you then consider that the individual state of each of all other cells is the negation of the closest individual cell among the previously defined finite number of cells. Examples: 1 -> ..., 0, 0, 1, 0, 0, ... 0, 1 -> ..., 1, 1, 0, 1, 0, 0, ... 1, 0, 1 -> ..., 0, 0, 1, 0, 1, 0, 0, ... More complex methods can be imagined, provided it is possible to somehow encode the infinite sections. But for this task we will stick to this simple version.
#Raku
Raku
class Automaton { has $.rule; has @.cells; has @.code = $!rule.fmt('%08b').flip.comb».Int;   method gist { @!cells.map({+$_ ?? '▲' !! '░'}).join }   method succ { self.new: :$!rule, :@!code, :cells( ' ', |@!code[ 4 «*« @!cells.rotate(-1)  »+« 2 «*« @!cells  »+«  @!cells.rotate(1) ], ' ' ) } }   my Automaton $a .= new: :rule(90), :cells(flat '010'.comb);   # display the first 20 rows say $a++ for ^20;   # then calculate the other infinite number of rows, (may take a while) $a++ for ^Inf;
http://rosettacode.org/wiki/Elementary_cellular_automaton/Infinite_length
Elementary cellular automaton/Infinite length
The purpose of this task is to create a version of an Elementary cellular automaton whose number of cells is only limited by the memory size of the computer. To be precise, consider the state of the automaton to be made of an infinite number of cells, but with a bounded support. In other words, to describe the state of the automaton, you need a finite number of adjacent cells, along with their individual state, and you then consider that the individual state of each of all other cells is the negation of the closest individual cell among the previously defined finite number of cells. Examples: 1 -> ..., 0, 0, 1, 0, 0, ... 0, 1 -> ..., 1, 1, 0, 1, 0, 0, ... 1, 0, 1 -> ..., 0, 0, 1, 0, 1, 0, 0, ... More complex methods can be imagined, provided it is possible to somehow encode the infinite sections. But for this task we will stick to this simple version.
#Ruby
Ruby
def notcell(c) c.tr('01','10') end   def eca_infinite(cells, rule) neighbours2next = Hash[8.times.map{|i|["%03b"%i, "01"[rule[i]]]}] c = cells Enumerator.new do |y| loop do y << c c = notcell(c[0])*2 + c + notcell(c[-1])*2 # Extend and pad the ends c = (1..c.size-2).map{|i| neighbours2next[c[i-1..i+1]]}.join end end end   if __FILE__ == $0 lines = 25 for rule in [90, 30] puts "\nRule: %i" % rule for i, c in (0...lines).zip(eca_infinite('1', rule)) puts '%2i: %s%s' % [i, ' '*(lines - i), c.tr('01', '.#')] end end end
http://rosettacode.org/wiki/EKG_sequence_convergence
EKG sequence convergence
The sequence is from the natural numbers and is defined by: a(1) = 1; a(2) = Start = 2; for n > 2, a(n) shares at least one prime factor with a(n-1) and is the smallest such natural number not already used. The sequence is called the EKG sequence (after its visual similarity to an electrocardiogram when graphed). Variants of the sequence can be generated starting 1, N where N is any natural number larger than one. For the purposes of this task let us call: The sequence described above , starting 1, 2, ... the EKG(2) sequence; the sequence starting 1, 3, ... the EKG(3) sequence; ... the sequence starting 1, N, ... the EKG(N) sequence. Convergence If an algorithm that keeps track of the minimum amount of numbers and their corresponding prime factors used to generate the next term is used, then this may be known as the generators essential state. Two EKG generators with differing starts can converge to produce the same sequence after initial differences. EKG(N1) and EKG(N2) are said to to have converged at and after generation a(c) if state_of(EKG(N1).a(c)) == state_of(EKG(N2).a(c)). Task Calculate and show here the first 10 members of EKG(2). Calculate and show here the first 10 members of EKG(5). Calculate and show here the first 10 members of EKG(7). Calculate and show here the first 10 members of EKG(9). Calculate and show here the first 10 members of EKG(10). Calculate and show here at which term EKG(5) and EKG(7) converge   (stretch goal). Related Tasks Greatest common divisor Sieve of Eratosthenes Reference The EKG Sequence and the Tree of Numbers. (Video).
#.7B.7Bheader.7CVlang.7D
{{header|Vlang}
fn gcd(aa int, bb int) int { mut a,mut b:=aa,bb for a != b { if a > b { a -= b } else { b -= a } } return a }   fn are_same(ss []int, tt []int) bool { mut s,mut t:=ss.clone(),tt.clone() le := s.len if le != t.len { return false } s.sort() t.sort() for i in 0..le { if s[i] != t[i] { return false } } return true } const limit = 100 fn main() { starts := [2, 5, 7, 9, 10] mut ekg := [5][limit]int{}   for s, start in starts { ekg[s][0] = 1 ekg[s][1] = start for n in 2..limit { for i := 2; ; i++ { // a potential sequence member cannot already have been used // and must have a factor in common with previous member if !ekg[s][..n].contains(i) && gcd(ekg[s][n-1], i) > 1 { ekg[s][n] = i break } } } println("EKG(${start:2}): ${ekg[s][..30]}") }   // now compare EKG5 and EKG7 for convergence for i in 2..limit { if ekg[1][i] == ekg[2][i] && are_same(ekg[1][..i], ekg[2][..i]) { println("\nEKG(5) and EKG(7) converge at term ${i+1}") return } } println("\nEKG5(5) and EKG(7) do not converge within $limit terms") }
http://rosettacode.org/wiki/EKG_sequence_convergence
EKG sequence convergence
The sequence is from the natural numbers and is defined by: a(1) = 1; a(2) = Start = 2; for n > 2, a(n) shares at least one prime factor with a(n-1) and is the smallest such natural number not already used. The sequence is called the EKG sequence (after its visual similarity to an electrocardiogram when graphed). Variants of the sequence can be generated starting 1, N where N is any natural number larger than one. For the purposes of this task let us call: The sequence described above , starting 1, 2, ... the EKG(2) sequence; the sequence starting 1, 3, ... the EKG(3) sequence; ... the sequence starting 1, N, ... the EKG(N) sequence. Convergence If an algorithm that keeps track of the minimum amount of numbers and their corresponding prime factors used to generate the next term is used, then this may be known as the generators essential state. Two EKG generators with differing starts can converge to produce the same sequence after initial differences. EKG(N1) and EKG(N2) are said to to have converged at and after generation a(c) if state_of(EKG(N1).a(c)) == state_of(EKG(N2).a(c)). Task Calculate and show here the first 10 members of EKG(2). Calculate and show here the first 10 members of EKG(5). Calculate and show here the first 10 members of EKG(7). Calculate and show here the first 10 members of EKG(9). Calculate and show here the first 10 members of EKG(10). Calculate and show here at which term EKG(5) and EKG(7) converge   (stretch goal). Related Tasks Greatest common divisor Sieve of Eratosthenes Reference The EKG Sequence and the Tree of Numbers. (Video).
#Wren
Wren
import "/sort" for Sort import "/math" for Int import "/fmt" for Fmt   var areSame = Fn.new { |s, t| var le = s.count if (le != t.count) return false Sort.quick(s) Sort.quick(t) for (i in 0...le) if (s[i] != t[i]) return false return true }   var limit = 100 var starts = [2, 5, 7, 9, 10] var ekg = List.filled(5, null) for (i in 0..4) ekg[i] = List.filled(limit, 0) var s = 0 for (start in starts) { ekg[s][0] = 1 ekg[s][1] = start for (n in 2...limit) { var i = 2 while (true) { // a potential sequence member cannot already have been used // and must have a factor in common with previous member if (!ekg[s].take(n).contains(i) && Int.gcd(ekg[s][n-1], i) > 1) { ekg[s][n] = i break } i = i + 1 } } Fmt.print("EKG($2d): $2d", start, ekg[s].take(30).toList) s = s + 1 }   // now compare EKG5 and EKG7 for convergence for (i in 2...limit) { if (ekg[1][i] == ekg[2][i] && areSame.call(ekg[1][0...i], ekg[2][0...i])) { System.print("\nEKG(5) and EKG(7) converge at term %(i+1).") return } } System.print("\nEKG5(5) and EKG(7) do not converge within %(limit) terms.")
http://rosettacode.org/wiki/Empty_string
Empty string
Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. 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
#VBScript
VBScript
Dim s As String   ' Assign empty string: s = "" ' or s = String.Empty   ' Check for empty string only (false if s is null): If s IsNot Nothing AndAlso s.Length = 0 Then End If   ' Check for null or empty (more idiomatic in .NET): If String.IsNullOrEmpty(s) Then End If
http://rosettacode.org/wiki/Empty_string
Empty string
Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. 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
#Visual_Basic
Visual Basic
Dim s As String   ' Assign empty string: s = "" ' or s = String.Empty   ' Check for empty string only (false if s is null): If s IsNot Nothing AndAlso s.Length = 0 Then End If   ' Check for null or empty (more idiomatic in .NET): If String.IsNullOrEmpty(s) Then End If
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Run_BASIC
Run BASIC
end ' actually a blank is ok
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Rust
Rust
fn main(){}
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Scala
Scala
object emptyProgram extends App {}
http://rosettacode.org/wiki/Earliest_difference_between_prime_gaps
Earliest difference between prime gaps
When calculating prime numbers > 2, the difference between adjacent primes is always an even number. This difference, also referred to as the gap, varies in an random pattern; at least, no pattern has ever been discovered, and it is strongly conjectured that no pattern exists. However, it is also conjectured that between some two adjacent primes will be a gap corresponding to every positive even integer. gap minimal starting prime ending prime 2 3 5 4 7 11 6 23 29 8 89 97 10 139 149 12 199 211 14 113 127 16 1831 1847 18 523 541 20 887 907 22 1129 1151 24 1669 1693 26 2477 2503 28 2971 2999 30 4297 4327 This task involves locating the minimal primes corresponding to those gaps. Though every gap value exists, they don't seem to come in any particular order. For example, this table shows the gaps and minimum starting value primes for 2 through 30: For the purposes of this task, considering only primes greater than 2, consider prime gaps that differ by exactly two to be adjacent. Task For each order of magnitude m from 10¹ through 10⁶: Find the first two sets of adjacent minimum prime gaps where the absolute value of the difference between the prime gap start values is greater than m. E.G. For an m of 10¹; The start value of gap 2 is 3, the start value of gap 4 is 7, the difference is 7 - 3 or 4. 4 < 10¹ so keep going. The start value of gap 4 is 7, the start value of gap 6 is 23, the difference is 23 - 7, or 16. 16 > 10¹ so this the earliest adjacent gap difference > 10¹. Stretch goal Do the same for 10⁷ and 10⁸ (and higher?) orders of magnitude Note: the earliest value found for each order of magnitude may not be unique, in fact, is not unique; also, with the gaps in ascending order, the minimal starting values are not strictly ascending.
#C.2B.2B
C++
#include <iostream> #include <locale> #include <unordered_map>   #include <primesieve.hpp>   class prime_gaps { public: prime_gaps() { last_prime_ = iterator_.next_prime(); } uint64_t find_gap_start(uint64_t gap); private: primesieve::iterator iterator_; uint64_t last_prime_; std::unordered_map<uint64_t, uint64_t> gap_starts_; };   uint64_t prime_gaps::find_gap_start(uint64_t gap) { auto i = gap_starts_.find(gap); if (i != gap_starts_.end()) return i->second; for (;;) { uint64_t prev = last_prime_; last_prime_ = iterator_.next_prime(); uint64_t diff = last_prime_ - prev; gap_starts_.emplace(diff, prev); if (gap == diff) return prev; } }   int main() { std::cout.imbue(std::locale("")); const uint64_t limit = 100000000000; prime_gaps pg; for (uint64_t pm = 10, gap1 = 2;;) { uint64_t start1 = pg.find_gap_start(gap1); uint64_t gap2 = gap1 + 2; uint64_t start2 = pg.find_gap_start(gap2); uint64_t diff = start2 > start1 ? start2 - start1 : start1 - start2; if (diff > pm) { std::cout << "Earliest difference > " << pm << " between adjacent prime gap starting primes:\n" << "Gap " << gap1 << " starts at " << start1 << ", gap " << gap2 << " starts at " << start2 << ", difference is " << diff << ".\n\n"; if (pm == limit) break; pm *= 10; } else { gap1 = gap2; } } }
http://rosettacode.org/wiki/Element-wise_operations
Element-wise operations
This task is similar to:   Matrix multiplication   Matrix transposition Task Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks. Implement:   addition   subtraction   multiplication   division   exponentiation Extend the task if necessary to include additional basic operations, which should not require their own specialised task.
#AutoHotkey
AutoHotkey
ElementWise(M, operation, Val){ A := Obj_Copy(M), for r, obj in A for c, v in obj { V := IsObject(Val) ? Val[r, c] : Val switch, operation { case "+": A[r, c] := A[r, c] + V case "-": A[r, c] := A[r, c] - V case "*": A[r, c] := A[r, c] * V case "/": A[r, c] := A[r, c] / V case "Mod": A[r, c] := Mod(A[r, c], V) case "^": A[r, c] := A[r, c] ** V } } return A }
http://rosettacode.org/wiki/Egyptian_division
Egyptian division
Egyptian division is a method of dividing integers using addition and doubling that is similar to the algorithm of Ethiopian multiplication Algorithm: Given two numbers where the dividend is to be divided by the divisor: Start the construction of a table of two columns: powers_of_2, and doublings; by a first row of a 1 (i.e. 2^0) in the first column and 1 times the divisor in the first row second column. Create the second row with columns of 2 (i.e 2^1), and 2 * divisor in order. Continue with successive i’th rows of 2^i and 2^i * divisor. Stop adding rows, and keep only those rows, where 2^i * divisor is less than or equal to the dividend. We now assemble two separate sums that both start as zero, called here answer and accumulator Consider each row of the table, in the reverse order of its construction. If the current value of the accumulator added to the doublings cell would be less than or equal to the dividend then add it to the accumulator, as well as adding the powers_of_2 cell value to the answer. When the first row has been considered as above, then the integer division of dividend by divisor is given by answer. (And the remainder is given by the absolute value of accumulator - dividend). Example: 580 / 34 Table creation: powers_of_2 doublings 1 34 2 68 4 136 8 272 16 544 Initialization of sums: powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 0 0 Considering table rows, bottom-up: When a row is considered it is shown crossed out if it is not accumulated, or bold if the row causes summations. powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 4 136 16 544 8 272 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 16 544 4 136 8 272 16 544 powers_of_2 doublings answer accumulator 1 34 17 578 2 68 4 136 8 272 16 544 Answer So 580 divided by 34 using the Egyptian method is 17 remainder (578 - 580) or 2. Task The task is to create a function that does Egyptian division. The function should closely follow the description above in using a list/array of powers of two, and another of doublings. Functions should be clear interpretations of the algorithm. Use the function to divide 580 by 34 and show the answer here, on this page. Related tasks   Egyptian fractions References   Egyptian Number System
#ALGOL_68
ALGOL 68
BEGIN # performs Egyptian division of dividend by divisor, setting quotient and remainder # # this uses 32 bit numbers, so a table of 32 powers of 2 should be sufficient # # ( divisors > 2^30 will probably overflow - this is not checked here ) # PROC egyptian division = ( INT dividend, divisor, REF INT quotient, remainder )VOID: BEGIN [ 1 : 32 ]INT powers of 2, doublings; # initialise the powers of 2 and doublings tables # powers of 2[ 1 ] := 1; doublings [ 1 ] := divisor; INT table pos := 1; WHILE table pos +:= 1; powers of 2[ table pos ] := powers of 2[ table pos - 1 ] * 2; doublings [ table pos ] := doublings [ table pos - 1 ] * 2; doublings[ table pos ] <= dividend DO SKIP OD; # construct the accumulator and answer # INT accumulator := 0, answer := 0; WHILE table pos >=1 DO IF ( accumulator + doublings[ table pos ] ) <= dividend THEN accumulator +:= doublings [ table pos ]; answer +:= powers of 2[ table pos ] FI; table pos -:= 1 OD; quotient := answer; remainder := ABS ( accumulator - dividend ) END # egyptian division # ;   # task test case # INT quotient, remainder; egyptian division( 580, 34, quotient, remainder ); print( ( "580 divided by 34 is: ", whole( quotient, 0 ), " remainder: ", whole( remainder, 0 ), newline ) ) END
http://rosettacode.org/wiki/Eertree
Eertree
An eertree is a data structure designed for efficient processing of certain palindrome tasks, for instance counting the number of sub-palindromes in an input string. The data structure has commonalities to both tries and suffix trees.   See links below. Task Construct an eertree for the string "eertree", then output all sub-palindromes by traversing the tree. See also   Wikipedia entry:   trie.   Wikipedia entry:   suffix tree   Cornell University Library, Computer Science, Data Structures and Algorithms ───► EERTREE: An Efficient Data Structure for Processing Palindromes in Strings.
#Julia
Julia
mutable struct Node edges::Dict{Char, Node} link::Union{Node, Missing} sz::Int Node() = new(Dict(), missing, 0) end   sizednode(x) = (n = Node(); n.sz = x; n)   function eertree(str) nodes = Vector{Node}() oddroot = sizednode(-1) evenroot = sizednode(0) oddroot.link = evenroot evenroot.link = oddroot S = "0" maxsuffix = evenroot   function maxsuffixpal(startnode,a::Char) # Traverse the suffix-palindromes of tree looking for equality with a u = startnode i = length(S) k = u.sz while u !== oddroot && S[i - k] != a if u === u.link throw("circular reference above oddroot") end u = u.link k = u.sz end u end   function addchar(a::Char) Q = maxsuffixpal(maxsuffix, a) creatednode = !haskey(Q.edges, a) if creatednode P = sizednode(Q.sz + 2) push!(nodes, P) if P.sz == 1 P.link = evenroot else P.link = maxsuffixpal(Q.link, a).edges[a] end Q.edges[a] = P # adds edge (Q, P) end maxsuffix = Q.edges[a] # P becomes the new maxsuffix S *= string(a) creatednode end   function getsubpalindromes() result = Vector{String}() getsubpalindromes(oddroot, [oddroot], "", result) getsubpalindromes(evenroot, [evenroot], "", result) result end   function getsubpalindromes(nd, nodestohere, charstohere, result) for (lnkname, nd2) in nd.edges getsubpalindromes(nd2, vcat(nodestohere, nd2), charstohere * lnkname, result) end if nd !== oddroot && nd !== evenroot assembled = reverse(charstohere) * (nodestohere[1] === evenroot ? charstohere : charstohere[2:end]) push!(result, assembled) end end   println("Results of processing string \"$str\":") for c in str addchar(c) end println("Number of sub-palindromes: ", length(nodes)) println("Sub-palindromes: ", getsubpalindromes()) end   eertree("eertree")  
http://rosettacode.org/wiki/Eertree
Eertree
An eertree is a data structure designed for efficient processing of certain palindrome tasks, for instance counting the number of sub-palindromes in an input string. The data structure has commonalities to both tries and suffix trees.   See links below. Task Construct an eertree for the string "eertree", then output all sub-palindromes by traversing the tree. See also   Wikipedia entry:   trie.   Wikipedia entry:   suffix tree   Cornell University Library, Computer Science, Data Structures and Algorithms ───► EERTREE: An Efficient Data Structure for Processing Palindromes in Strings.
#Kotlin
Kotlin
// version 1.1.4   class Node { val edges = mutableMapOf<Char, Node>() // edges (or forward links) var link: Node? = null // suffix link (backward links) var len = 0 // the length of the node }   class Eertree(str: String) { val nodes = mutableListOf<Node>()   private val rto = Node() // odd length root node, or node -1 private val rte = Node() // even length root node, or node 0 private val s = StringBuilder("0") // accumulated input string, T = S[1..i] private var maxSufT = rte // maximum suffix of tree T   init { // Initialize and build the tree rte.link = rto rto.link = rte rto.len = -1 rte.len = 0 for (ch in str) add(ch) }   private fun getMaxSuffixPal(startNode: Node, a: Char): Node { // We traverse the suffix-palindromes of T in the order of decreasing length. // For each palindrome we read its length k and compare T[i-k] against a // until we get an equality or arrive at the -1 node. var u = startNode val i = s.length var k = u.len while (u !== rto && s[i - k - 1] != a) { if (u === u.link!!) throw RuntimeException("Infinite loop detected") u = u.link!! k = u.len } return u }   private fun add(a: Char): Boolean { // We need to find the maximum suffix-palindrome P of Ta // Start by finding maximum suffix-palindrome Q of T. // To do this, we traverse the suffix-palindromes of T // in the order of decreasing length, starting with maxSuf(T) val q = getMaxSuffixPal(maxSufT, a)   // We check Q to see whether it has an outgoing edge labeled by a. val createANewNode = a !in q.edges.keys   if (createANewNode) { // We create the node P of length Q + 2 val p = Node() nodes.add(p) p.len = q.len + 2 if (p.len == 1) { // if P = a, create the suffix link (P, 0) p.link = rte } else { // It remains to create the suffix link from P if |P|>1. Just // continue traversing suffix-palindromes of T starting with the // the suffix link of Q. p.link = getMaxSuffixPal(q.link!!, a).edges[a] }   // create the edge (Q, P) q.edges[a] = p }   // P becomes the new maxSufT maxSufT = q.edges[a]!!   // Store accumulated input string s.append(a)   return createANewNode }   fun getSubPalindromes(): List<String> { // Traverse tree to find sub-palindromes val result = mutableListOf<String>() // Odd length words getSubPalindromes(rto, listOf(rto), "", result) // Even length words getSubPalindromes(rte, listOf(rte), "", result) return result }   private fun getSubPalindromes(nd: Node, nodesToHere: List<Node>, charsToHere: String, result: MutableList<String>) { // Each node represents a palindrome, which can be reconstructed // by the path from the root node to each non-root node.   // Traverse all edges, since they represent other palindromes for ((lnkName, nd2) in nd.edges) { getSubPalindromes(nd2, nodesToHere + nd2, charsToHere + lnkName, result) }   // Reconstruct based on charsToHere characters. if (nd !== rto && nd !== rte) { // Don't print for root nodes val assembled = charsToHere.reversed() + if (nodesToHere[0] === rte) // Even string charsToHere else // Odd string charsToHere.drop(1) result.add(assembled) } } }   fun main(args: Array<String>) { val str = "eertree" println("Processing string '$str'") val eertree = Eertree(str) println("Number of sub-palindromes: ${eertree.nodes.size}") val result = eertree.getSubPalindromes() println("Sub-palindromes: $result") }
http://rosettacode.org/wiki/Ethiopian_multiplication
Ethiopian multiplication
Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last in the same column, until you write a value of 1. In the right-hand column repeatedly double the last number and write the result below. stop when you add a result in the same row as where the left hand column shows 1. Examine the table produced and discard any row where the value in the left column is even. Sum the values in the right-hand column that remain to produce the result of multiplying the original two numbers together For example:   17 × 34 17 34 Halving the first column: 17 34 8 4 2 1 Doubling the second column: 17 34 8 68 4 136 2 272 1 544 Strike-out rows whose first cell is even: 17 34 8 68 4 136 2 272 1 544 Sum the remaining numbers in the right-hand column: 17 34 8 -- 4 --- 2 --- 1 544 ==== 578 So 17 multiplied by 34, by the Ethiopian method is 578. Task The task is to define three named functions/methods/procedures/subroutines: one to halve an integer, one to double an integer, and one to state if an integer is even. Use these functions to create a function that does Ethiopian multiplication. References Ethiopian multiplication explained (BBC Video clip) A Night Of Numbers - Go Forth And Multiply (Video) Russian Peasant Multiplication Programming Praxis: Russian Peasant Multiplication
#PowerShell
PowerShell
function isEven { param ([int]$value) return [bool]($value % 2 -eq 0) }   function doubleValue { param ([int]$value) return [int]($value * 2) }   function halveValue { param ([int]$value) return [int]($value / 2) }   function multiplyValues { param ( [int]$plier, [int]$plicand, [int]$temp = 0 )   while ($plier -ge 1) { if (!(isEven $plier)) { $temp += $plicand } $plier = halveValue $plier $plicand = doubleValue $plicand }   return $temp }   multiplyValues 17 34
http://rosettacode.org/wiki/Elementary_cellular_automaton
Elementary cellular automaton
An elementary cellular automaton is a one-dimensional cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors. Those three values can be encoded with three bits. The rules of evolution are then encoded with eight bits indicating the outcome of each of the eight possibilities 111, 110, 101, 100, 011, 010, 001 and 000 in this order. Thus for instance the rule 13 means that a state is updated to 1 only in the cases 011, 010 and 000, since 13 in binary is 0b00001101. Task Create a subroutine, program or function that allows to create and visualize the evolution of any of the 256 possible elementary cellular automaton of arbitrary space length and for any given initial state. You can demonstrate your solution with any automaton of your choice. The space state should wrap: this means that the left-most cell should be considered as the right neighbor of the right-most cell, and reciprocally. This task is basically a generalization of one-dimensional cellular automata. See also Cellular automata (natureofcode.com)
#C.2B.2B
C++
#include <bitset> #include <stdio.h>   #define SIZE 80 #define RULE 30 #define RULE_TEST(x) (RULE & 1 << (7 & (x)))   void evolve(std::bitset<SIZE> &s) { int i; std::bitset<SIZE> t(0); t[SIZE-1] = RULE_TEST( s[0] << 2 | s[SIZE-1] << 1 | s[SIZE-2] ); t[ 0] = RULE_TEST( s[1] << 2 | s[ 0] << 1 | s[SIZE-1] ); for (i = 1; i < SIZE-1; i++) t[i] = RULE_TEST( s[i+1] << 2 | s[i] << 1 | s[i-1] ); for (i = 0; i < SIZE; i++) s[i] = t[i]; } void show(std::bitset<SIZE> s) { int i; for (i = SIZE; --i; ) printf("%c", s[i] ? '#' : ' '); printf("\n"); } int main() { int i; std::bitset<SIZE> state(1); state <<= SIZE / 2; for (i=0; i<10; i++) { show(state); evolve(state); } return 0; }
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterative or recursive. Support for trapping negative   n   errors is optional. Related task   Primorial numbers
#Swift
Swift
func factorial(_ n: Int) -> Int { return n < 2 ? 1 : (2...n).reduce(1, *) }
http://rosettacode.org/wiki/Even_or_odd
Even or odd
Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Divide i by 2. The remainder equals 0 iff i is even. The remainder equals +1 or -1 iff i is odd. Use modular congruences: i ≡ 0 (mod 2) iff i is even. i ≡ 1 (mod 2) iff i is odd.
#Symsyn
Symsyn
  n : 23   if n bit 0 'n is odd' [] else 'n is even' []  
http://rosettacode.org/wiki/Even_or_odd
Even or odd
Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Divide i by 2. The remainder equals 0 iff i is even. The remainder equals +1 or -1 iff i is odd. Use modular congruences: i ≡ 0 (mod 2) iff i is even. i ≡ 1 (mod 2) iff i is odd.
#Tcl
Tcl
package require Tcl 8.5   # Bitwise test is the most efficient proc tcl::mathfunc::isOdd x { expr {$x & 1} } proc tcl::mathfunc::isEven x { expr {!($x & 1)} }   puts " # O E" puts 24:[expr isOdd(24)],[expr isEven(24)] puts 49:[expr isOdd(49)],[expr isEven(49)]
http://rosettacode.org/wiki/Echo_server
Echo server
Create a network service that sits on TCP port 12321, which accepts connections on that port, and which echoes complete lines (using a carriage-return/line-feed sequence as line separator) back to clients. No error handling is required. For the purposes of testing, it is only necessary to support connections from localhost (127.0.0.1 or perhaps ::1). Logging of connection information to standard output is recommended. The implementation must be able to handle simultaneous connections from multiple clients. A multi-threaded or multi-process solution may be used. Each connection must be able to echo more than a single line. The implementation must not stop responding to other clients if one client sends a partial line or stops reading responses.
#Erlang
Erlang
-module(echo). -export([start/0]).   start() -> spawn(fun () -> {ok, Sock} = gen_tcp:listen(12321, [{packet, line}]), echo_loop(Sock) end).   echo_loop(Sock) -> {ok, Conn} = gen_tcp:accept(Sock), io:format("Got connection: ~p~n", [Conn]), Handler = spawn(fun () -> handle(Conn) end), gen_tcp:controlling_process(Conn, Handler), echo_loop(Sock).   handle(Conn) -> receive {tcp, Conn, Data} -> gen_tcp:send(Conn, Data), handle(Conn); {tcp_closed, Conn} -> io:format("Connection closed: ~p~n", [Conn]) end.
http://rosettacode.org/wiki/Elementary_cellular_automaton/Infinite_length
Elementary cellular automaton/Infinite length
The purpose of this task is to create a version of an Elementary cellular automaton whose number of cells is only limited by the memory size of the computer. To be precise, consider the state of the automaton to be made of an infinite number of cells, but with a bounded support. In other words, to describe the state of the automaton, you need a finite number of adjacent cells, along with their individual state, and you then consider that the individual state of each of all other cells is the negation of the closest individual cell among the previously defined finite number of cells. Examples: 1 -> ..., 0, 0, 1, 0, 0, ... 0, 1 -> ..., 1, 1, 0, 1, 0, 0, ... 1, 0, 1 -> ..., 0, 0, 1, 0, 1, 0, 0, ... More complex methods can be imagined, provided it is possible to somehow encode the infinite sections. But for this task we will stick to this simple version.
#Sidef
Sidef
func evolve(rule, bin) { var offset = 0 var (l='', r='') Inf.times { bin.sub!(/^((.)\g2*)/, {|_s1, s2| l = s2; offset -= s2.len; s2*2 }) bin.sub!(/(.)\g1*$/, {|s1| r = s1; s1*2 }) printf("%5d| %s%s\n", offset, ' ' * (40 + offset), bin.tr('01','.#')) bin = [l*3, 0.to(bin.len-3).map{|i| bin.substr(i, 3) }..., r*3 ].map { |t| 1 & (rule >> t.bin) }.join } }   evolve(90, "010")
http://rosettacode.org/wiki/Elementary_cellular_automaton/Infinite_length
Elementary cellular automaton/Infinite length
The purpose of this task is to create a version of an Elementary cellular automaton whose number of cells is only limited by the memory size of the computer. To be precise, consider the state of the automaton to be made of an infinite number of cells, but with a bounded support. In other words, to describe the state of the automaton, you need a finite number of adjacent cells, along with their individual state, and you then consider that the individual state of each of all other cells is the negation of the closest individual cell among the previously defined finite number of cells. Examples: 1 -> ..., 0, 0, 1, 0, 0, ... 0, 1 -> ..., 1, 1, 0, 1, 0, 0, ... 1, 0, 1 -> ..., 0, 0, 1, 0, 1, 0, 0, ... More complex methods can be imagined, provided it is possible to somehow encode the infinite sections. But for this task we will stick to this simple version.
#Tcl
Tcl
package require Tcl 8.6   oo::class create InfiniteElementaryAutomaton { variable rules # Decode the rule number to get a collection of state mapping rules. # In effect, "compiles" the rule number constructor {ruleNumber} { set ins {111 110 101 100 011 010 001 000} set bits [split [string range [format %08b $ruleNumber] end-7 end] ""] foreach input {111 110 101 100 011 010 001 000} state $bits { dict set rules $input $state } }   # Apply the rule to an automaton state to get a new automaton state. # We wrap the edges; the state space is circular. method evolve {left state right} { set state [list $left {*}$state $right] set len [llength $state] for {set i -1;set j 0;set k 1} {$j < $len} {incr i;incr j;incr k} { set a [expr {$i<0 ? $left : [lindex $state $i]}] set b [lindex $state $j] set c [expr {$k==$len ? $right : [lindex $state $k]}] lappend result [dict get $rules $a$b$c] } return $result }   method evolveEnd {endState} { return [dict get $rules $endState$endState$endState] }   # Simple driver method; omit the initial state to get a centred dot method run {steps {initialState "010"}} { set cap [string repeat "\u2026" $steps] set s [split [string map ". 0 # 1" $initialState] ""] set left [lindex $s 0] set right [lindex $s end] set s [lrange $s 1 end-1] for {set i 0} {$i < $steps} {incr i} { puts $cap[string map "0 . 1 #" $left[join $s ""]$right]$cap set s [my evolve $left $s $right] set left [my evolveEnd $left] set right [my evolveEnd $right] set cap [string range $cap 1 end] } puts $cap[string map "0 . 1 #" $left[join $s ""]$right]$cap } }   foreach num {90 30} { puts "Rule ${num}:" set rule [InfiniteElementaryAutomaton new $num] $rule run 25 $rule destroy }
http://rosettacode.org/wiki/EKG_sequence_convergence
EKG sequence convergence
The sequence is from the natural numbers and is defined by: a(1) = 1; a(2) = Start = 2; for n > 2, a(n) shares at least one prime factor with a(n-1) and is the smallest such natural number not already used. The sequence is called the EKG sequence (after its visual similarity to an electrocardiogram when graphed). Variants of the sequence can be generated starting 1, N where N is any natural number larger than one. For the purposes of this task let us call: The sequence described above , starting 1, 2, ... the EKG(2) sequence; the sequence starting 1, 3, ... the EKG(3) sequence; ... the sequence starting 1, N, ... the EKG(N) sequence. Convergence If an algorithm that keeps track of the minimum amount of numbers and their corresponding prime factors used to generate the next term is used, then this may be known as the generators essential state. Two EKG generators with differing starts can converge to produce the same sequence after initial differences. EKG(N1) and EKG(N2) are said to to have converged at and after generation a(c) if state_of(EKG(N1).a(c)) == state_of(EKG(N2).a(c)). Task Calculate and show here the first 10 members of EKG(2). Calculate and show here the first 10 members of EKG(5). Calculate and show here the first 10 members of EKG(7). Calculate and show here the first 10 members of EKG(9). Calculate and show here the first 10 members of EKG(10). Calculate and show here at which term EKG(5) and EKG(7) converge   (stretch goal). Related Tasks Greatest common divisor Sieve of Eratosthenes Reference The EKG Sequence and the Tree of Numbers. (Video).
#XPL0
XPL0
int N, A(1+30);   func Used; int M; \Return 'true' if M is in array A int I; [for I:= 1 to N-1 do if M = A(I) then return true; return false; ];   func MinFactor; int Num; \Return minimum unused factor int Fac, Val, Min; [Fac:= 2; Min:= -1>>1; repeat if rem(Num/Fac) = 0 then \found a factor [Val:= Fac; loop [if Used(Val) then Val:= Val+Fac else [if Val<Min then Min:= Val; quit; ]; ]; Num:= Num/Fac; ] else Fac:= Fac+1; until Fac > Num; return Min; ];   proc EKG; int M; \Calculate and show EKG sequence [A(1):= 1; A(2):= M; for N:= 3 to 30 do A(N):= MinFactor(A(N-1)); Format(2, 0); Text(0, "EKG("); RlOut(0, float(M)); Text(0, "):"); Format(3, 0); for N:= 1 to 30 do RlOut(0, float(A(N))); CrLf(0); ];   int Tbl, I; [Tbl:= [2, 5, 7, 9, 10]; for I:= 0 to 4 do EKG(Tbl(I)); ]
http://rosettacode.org/wiki/EKG_sequence_convergence
EKG sequence convergence
The sequence is from the natural numbers and is defined by: a(1) = 1; a(2) = Start = 2; for n > 2, a(n) shares at least one prime factor with a(n-1) and is the smallest such natural number not already used. The sequence is called the EKG sequence (after its visual similarity to an electrocardiogram when graphed). Variants of the sequence can be generated starting 1, N where N is any natural number larger than one. For the purposes of this task let us call: The sequence described above , starting 1, 2, ... the EKG(2) sequence; the sequence starting 1, 3, ... the EKG(3) sequence; ... the sequence starting 1, N, ... the EKG(N) sequence. Convergence If an algorithm that keeps track of the minimum amount of numbers and their corresponding prime factors used to generate the next term is used, then this may be known as the generators essential state. Two EKG generators with differing starts can converge to produce the same sequence after initial differences. EKG(N1) and EKG(N2) are said to to have converged at and after generation a(c) if state_of(EKG(N1).a(c)) == state_of(EKG(N2).a(c)). Task Calculate and show here the first 10 members of EKG(2). Calculate and show here the first 10 members of EKG(5). Calculate and show here the first 10 members of EKG(7). Calculate and show here the first 10 members of EKG(9). Calculate and show here the first 10 members of EKG(10). Calculate and show here at which term EKG(5) and EKG(7) converge   (stretch goal). Related Tasks Greatest common divisor Sieve of Eratosthenes Reference The EKG Sequence and the Tree of Numbers. (Video).
#zkl
zkl
fcn ekgW(N){ // --> iterator Walker.tweak(fcn(rp,buf,w){ foreach n in (w){ if(rp.value.gcd(n)>1) { rp.set(n); w.push(buf.xplode()); buf.clear(); return(n); } buf.append(n); // save small numbers not used yet } }.fp(Ref(N),List(),Walker.chain([2..N-1],[N+1..]))).push(1,N) }
http://rosettacode.org/wiki/Empty_string
Empty string
Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. 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
#Visual_Basic_.NET
Visual Basic .NET
Dim s As String   ' Assign empty string: s = "" ' or s = String.Empty   ' Check for empty string only (false if s is null): If s IsNot Nothing AndAlso s.Length = 0 Then End If   ' Check for null or empty (more idiomatic in .NET): If String.IsNullOrEmpty(s) Then End If
http://rosettacode.org/wiki/Empty_string
Empty string
Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. 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
#Vlang
Vlang
// define and initialize an empty string mut s := ""   // assign an empty string to a variable s = ""   // check that a string is empty, any of: s == "" s.len() == 0   // check that a string is not empty, any of: s != "" s.len() != 0 // or > 0
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Scheme
Scheme
 
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Scilab
Scilab
 
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#ScratchScript
ScratchScript
//
http://rosettacode.org/wiki/Earliest_difference_between_prime_gaps
Earliest difference between prime gaps
When calculating prime numbers > 2, the difference between adjacent primes is always an even number. This difference, also referred to as the gap, varies in an random pattern; at least, no pattern has ever been discovered, and it is strongly conjectured that no pattern exists. However, it is also conjectured that between some two adjacent primes will be a gap corresponding to every positive even integer. gap minimal starting prime ending prime 2 3 5 4 7 11 6 23 29 8 89 97 10 139 149 12 199 211 14 113 127 16 1831 1847 18 523 541 20 887 907 22 1129 1151 24 1669 1693 26 2477 2503 28 2971 2999 30 4297 4327 This task involves locating the minimal primes corresponding to those gaps. Though every gap value exists, they don't seem to come in any particular order. For example, this table shows the gaps and minimum starting value primes for 2 through 30: For the purposes of this task, considering only primes greater than 2, consider prime gaps that differ by exactly two to be adjacent. Task For each order of magnitude m from 10¹ through 10⁶: Find the first two sets of adjacent minimum prime gaps where the absolute value of the difference between the prime gap start values is greater than m. E.G. For an m of 10¹; The start value of gap 2 is 3, the start value of gap 4 is 7, the difference is 7 - 3 or 4. 4 < 10¹ so keep going. The start value of gap 4 is 7, the start value of gap 6 is 23, the difference is 23 - 7, or 16. 16 > 10¹ so this the earliest adjacent gap difference > 10¹. Stretch goal Do the same for 10⁷ and 10⁸ (and higher?) orders of magnitude Note: the earliest value found for each order of magnitude may not be unique, in fact, is not unique; also, with the gaps in ascending order, the minimal starting values are not strictly ascending.
#F.23
F#
  // Earliest difference between prime gaps. Nigel Galloway: December 1st., 2021 let fN y=let i=System.Collections.Generic.SortedDictionary<int64,int64>() let fN()=i|>Seq.pairwise|>Seq.takeWhile(fun(n,g)->g.Key=n.Key+2L)|>Seq.tryFind(fun(n,g)->abs(n.Value-g.Value)>y) (fun(n,g)->let e=g-n in match i.TryGetValue(e) with (false,_)->i.Add(e,n); fN() |_->None) [1..9]|>List.iter(fun g->let fN=fN(pown 10 g) in let n,i=(primes64()|>Seq.skip 1|>Seq.pairwise|>Seq.map fN|>Seq.find Option.isSome).Value printfn $"%10d{pown 10 g} -> distance between start of gap %d{n.Key}=%d{n.Value} and start of gap %d{i.Key}=%d{i.Value} is %d{abs((n.Value)-(i.Value))}")  
http://rosettacode.org/wiki/Earliest_difference_between_prime_gaps
Earliest difference between prime gaps
When calculating prime numbers > 2, the difference between adjacent primes is always an even number. This difference, also referred to as the gap, varies in an random pattern; at least, no pattern has ever been discovered, and it is strongly conjectured that no pattern exists. However, it is also conjectured that between some two adjacent primes will be a gap corresponding to every positive even integer. gap minimal starting prime ending prime 2 3 5 4 7 11 6 23 29 8 89 97 10 139 149 12 199 211 14 113 127 16 1831 1847 18 523 541 20 887 907 22 1129 1151 24 1669 1693 26 2477 2503 28 2971 2999 30 4297 4327 This task involves locating the minimal primes corresponding to those gaps. Though every gap value exists, they don't seem to come in any particular order. For example, this table shows the gaps and minimum starting value primes for 2 through 30: For the purposes of this task, considering only primes greater than 2, consider prime gaps that differ by exactly two to be adjacent. Task For each order of magnitude m from 10¹ through 10⁶: Find the first two sets of adjacent minimum prime gaps where the absolute value of the difference between the prime gap start values is greater than m. E.G. For an m of 10¹; The start value of gap 2 is 3, the start value of gap 4 is 7, the difference is 7 - 3 or 4. 4 < 10¹ so keep going. The start value of gap 4 is 7, the start value of gap 6 is 23, the difference is 23 - 7, or 16. 16 > 10¹ so this the earliest adjacent gap difference > 10¹. Stretch goal Do the same for 10⁷ and 10⁸ (and higher?) orders of magnitude Note: the earliest value found for each order of magnitude may not be unique, in fact, is not unique; also, with the gaps in ascending order, the minimal starting values are not strictly ascending.
#Go
Go
package main   import ( "fmt" "rcu" )   func main() { limit := int(1e9) gapStarts := make(map[int]int) primes := rcu.Primes(limit * 5) for i := 1; i < len(primes); i++ { gap := primes[i] - primes[i-1] if _, ok := gapStarts[gap]; !ok { gapStarts[gap] = primes[i-1] } } pm := 10 gap1 := 2 for { for _, ok := gapStarts[gap1]; !ok; { gap1 += 2 } start1 := gapStarts[gap1] gap2 := gap1 + 2 if _, ok := gapStarts[gap2]; !ok { gap1 = gap2 + 2 continue } start2 := gapStarts[gap2] diff := start2 - start1 if diff < 0 { diff = -diff } if diff > pm { cpm := rcu.Commatize(pm) cst1 := rcu.Commatize(start1) cst2 := rcu.Commatize(start2) cd := rcu.Commatize(diff) fmt.Printf("Earliest difference > %s between adjacent prime gap starting primes:\n", cpm) fmt.Printf("Gap %d starts at %s, gap %d starts at %s, difference is %s.\n\n", gap1, cst1, gap2, cst2, cd) if pm == limit { break } pm *= 10 } else { gap1 = gap2 } } }
http://rosettacode.org/wiki/Element-wise_operations
Element-wise operations
This task is similar to:   Matrix multiplication   Matrix transposition Task Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks. Implement:   addition   subtraction   multiplication   division   exponentiation Extend the task if necessary to include additional basic operations, which should not require their own specialised task.
#BBC_BASIC
BBC BASIC
DIM a(1,2), b(1,2), c(1,2) a() = 7, 8, 7, 4, 0, 9 : b() = 4, 5, 1, 6, 2, 1   REM Matrix-Matrix: c() = a() + b() : PRINT FNshowmm(a(), "+", b(), c()) c() = a() - b() : PRINT FNshowmm(a(), "-", b(), c()) c() = a() * b() : PRINT FNshowmm(a(), "*", b(), c()) c() = a() / b() : PRINT FNshowmm(a(), "/", b(), c()) PROCpowmm(a(), b(), c()) : PRINT FNshowmm(a(), "^", b(), c()) '   REM Matrix-Scalar: c() = a() + 3 : PRINT FNshowms(a(), "+", 3, c()) c() = a() - 3 : PRINT FNshowms(a(), "-", 3, c()) c() = a() * 3 : PRINT FNshowms(a(), "*", 3, c()) c() = a() / 3 : PRINT FNshowms(a(), "/", 3, c()) PROCpowms(a(), 3, c()) : PRINT FNshowms(a(), "^", 3, c()) END   DEF PROCpowmm(a(), b(), c()) LOCAL i%, j% FOR i% = 0 TO DIM(a(),1) FOR j% = 0 TO DIM(a(),2) c(i%,j%) = a(i%,j%) ^ b(i%,j%) NEXT NEXT ENDPROC   DEF PROCpowms(a(), b, c()) LOCAL i%, j% FOR i% = 0 TO DIM(a(),1) FOR j% = 0 TO DIM(a(),2) c(i%,j%) = a(i%,j%) ^ b NEXT NEXT ENDPROC   DEF FNshowmm(a(), op$, b(), c()) = FNlist(a()) + " " + op$ + " " + FNlist(b()) + " = " + FNlist(c())   DEF FNshowms(a(), op$, b, c()) = FNlist(a()) + " " + op$ + " " + STR$(b) + " = " + FNlist(c())   DEF FNlist(a()) LOCAL i%, j%, a$ a$ = "[" FOR i% = 0 TO DIM(a(),1) a$ += "[" FOR j% = 0 TO DIM(a(),2) a$ += STR$(a(i%,j%)) + ", " NEXT a$ = LEFT$(LEFT$(a$)) + "]" NEXT = a$ + "]"
http://rosettacode.org/wiki/Egyptian_division
Egyptian division
Egyptian division is a method of dividing integers using addition and doubling that is similar to the algorithm of Ethiopian multiplication Algorithm: Given two numbers where the dividend is to be divided by the divisor: Start the construction of a table of two columns: powers_of_2, and doublings; by a first row of a 1 (i.e. 2^0) in the first column and 1 times the divisor in the first row second column. Create the second row with columns of 2 (i.e 2^1), and 2 * divisor in order. Continue with successive i’th rows of 2^i and 2^i * divisor. Stop adding rows, and keep only those rows, where 2^i * divisor is less than or equal to the dividend. We now assemble two separate sums that both start as zero, called here answer and accumulator Consider each row of the table, in the reverse order of its construction. If the current value of the accumulator added to the doublings cell would be less than or equal to the dividend then add it to the accumulator, as well as adding the powers_of_2 cell value to the answer. When the first row has been considered as above, then the integer division of dividend by divisor is given by answer. (And the remainder is given by the absolute value of accumulator - dividend). Example: 580 / 34 Table creation: powers_of_2 doublings 1 34 2 68 4 136 8 272 16 544 Initialization of sums: powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 0 0 Considering table rows, bottom-up: When a row is considered it is shown crossed out if it is not accumulated, or bold if the row causes summations. powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 4 136 16 544 8 272 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 16 544 4 136 8 272 16 544 powers_of_2 doublings answer accumulator 1 34 17 578 2 68 4 136 8 272 16 544 Answer So 580 divided by 34 using the Egyptian method is 17 remainder (578 - 580) or 2. Task The task is to create a function that does Egyptian division. The function should closely follow the description above in using a list/array of powers of two, and another of doublings. Functions should be clear interpretations of the algorithm. Use the function to divide 580 by 34 and show the answer here, on this page. Related tasks   Egyptian fractions References   Egyptian Number System
#AppleScript
AppleScript
-- EGYPTIAN DIVISION ------------------------------------   -- eqyptianQuotRem :: Int -> Int -> (Int, Int) on egyptianQuotRem(m, n) script expansion on |λ|(ix) set {i, x} to ix if x > m then Nothing() else Just({ix, {i + i, x + x}}) end if end |λ| end script   script collapse on |λ|(ix, qr) set {i, x} to ix set {q, r} to qr if x < r then {q + i, r - x} else qr end if end |λ| end script   return foldr(collapse, {0, m}, ¬ unfoldr(expansion, {1, n})) end egyptianQuotRem     -- TEST ------------------------------------------------- on run egyptianQuotRem(580, 34) end run   -- GENERIC FUNCTIONS ------------------------------------   -- Just :: a -> Maybe a on Just(x) {type:"Maybe", Nothing:false, Just:x} end Just   -- Nothing :: Maybe a on Nothing() {type:"Maybe", Nothing:true} end Nothing   -- foldr :: (a -> b -> b) -> b -> [a] -> b on foldr(f, startValue, xs) tell mReturn(f) set v to startValue set lng to length of xs repeat with i from lng to 1 by -1 set v to |λ|(item i of xs, v, i, xs) end repeat return v end tell end foldr   -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: First-class m => (a -> b) -> m (a -> b) on mReturn(f) if class of f is script then f else script property |λ| : f end script end if end mReturn   -- > unfoldr (\b -> if b == 0 then Nothing else Just (b, b-1)) 10 -- > [10,9,8,7,6,5,4,3,2,1] -- unfoldr :: (b -> Maybe (a, b)) -> b -> [a] on unfoldr(f, v) set xr to {v, v} -- (value, remainder) set xs to {} tell mReturn(f) repeat -- Function applied to remainder. set mb to |λ|(item 2 of xr) if Nothing of mb then exit repeat else -- New (value, remainder) tuple, set xr to Just of mb -- and value appended to output list. set end of xs to item 1 of xr end if end repeat end tell return xs end unfoldr
http://rosettacode.org/wiki/Egyptian_fractions
Egyptian fractions
An   Egyptian fraction   is the sum of distinct unit fractions such as: 1 2 + 1 3 + 1 16 ( = 43 48 ) {\displaystyle {\tfrac {1}{2}}+{\tfrac {1}{3}}+{\tfrac {1}{16}}\,(={\tfrac {43}{48}})} Each fraction in the expression has a numerator equal to   1   (unity)   and a denominator that is a positive integer,   and all the denominators are distinct   (i.e., no repetitions). Fibonacci's   Greedy algorithm for Egyptian fractions   expands the fraction   x y {\displaystyle {\tfrac {x}{y}}}   to be represented by repeatedly performing the replacement x y = 1 ⌈ y / x ⌉ + ( − y ) mod x y ⌈ y / x ⌉ {\displaystyle {\frac {x}{y}}={\frac {1}{\lceil y/x\rceil }}+{\frac {(-y)\!\!\!\!\mod x}{y\lceil y/x\rceil }}} (simplifying the 2nd term in this replacement as necessary, and where   ⌈ x ⌉ {\displaystyle \lceil x\rceil }   is the   ceiling   function). For this task,   Proper and improper fractions   must be able to be expressed. Proper  fractions   are of the form   a b {\displaystyle {\tfrac {a}{b}}}   where   a {\displaystyle a}   and   b {\displaystyle b}   are positive integers, such that   a < b {\displaystyle a<b} ,     and improper fractions are of the form   a b {\displaystyle {\tfrac {a}{b}}}   where   a {\displaystyle a}   and   b {\displaystyle b}   are positive integers, such that   a ≥ b. (See the REXX programming example to view one method of expressing the whole number part of an improper fraction.) For improper fractions, the integer part of any improper fraction should be first isolated and shown preceding the Egyptian unit fractions, and be surrounded by square brackets [n]. Task requirements   show the Egyptian fractions for: 43 48 {\displaystyle {\tfrac {43}{48}}} and 5 121 {\displaystyle {\tfrac {5}{121}}} and 2014 59 {\displaystyle {\tfrac {2014}{59}}}   for all proper fractions,   a b {\displaystyle {\tfrac {a}{b}}}   where   a {\displaystyle a}   and   b {\displaystyle b}   are positive one-or two-digit (decimal) integers, find and show an Egyptian fraction that has:   the largest number of terms,   the largest denominator.   for all one-, two-, and three-digit integers,   find and show (as above).     {extra credit} Also see   Wolfram MathWorld™ entry: Egyptian fraction
#ALGOL_68
ALGOL 68
BEGIN # compute some Egytian fractions # PR precision 2000 PR # set the number of digits for LONG LONG INT # PROC gcd = ( LONG LONG INT a, b )LONG LONG INT: IF b = 0 THEN IF a < 0 THEN - a ELSE a FI ELSE gcd( b, a MOD b ) FI ; # gcd # MODE RATIONAL = STRUCT( LONG LONG INT num, den ); MODE LISTOFRATIONAL = STRUCT( RATIONAL element, REF LISTOFRATIONAL next ); REF LISTOFRATIONAL nil list of rational = NIL; OP TOSTRING = ( INT a )STRING: whole( a, 0 ); OP TOSTRING = ( LONG INT a )STRING: whole( a, 0 ); OP TOSTRING = ( LONG LONG INT a )STRING: whole( a, 0 ); OP TOSTRING = ( RATIONAL a )STRING: IF den OF a = 1 THEN TOSTRING num OF a ELSE TOSTRING num OF a + "/" + TOSTRING den OF a FI ; # TOSTRING # OP TOSTRING = ( REF LISTOFRATIONAL lr )STRING: BEGIN REF LISTOFRATIONAL p := lr; STRING result := "["; WHILE p ISNT nil list of rational DO result +:= TOSTRING element OF p; IF next OF p IS nil list of rational THEN p := NIL ELSE p := next OF p; result +:= " + " FI OD; result + "]" END ; # TOSTRING # OP CEIL = ( LONG LONG REAL v )LONG LONG INT: IF LONG LONG INT result := ENTIER v; ABS v > ABS result THEN result + 1 ELSE result FI ; # CEIL # OP EGYPTIAN = ( RATIONAL rp )REF LISTOFRATIONAL: IF RATIONAL r := rp; num OF r = 0 OR num OF r = 1 THEN HEAP LISTOFRATIONAL := ( r, nil list of rational ) ELSE REF LISTOFRATIONAL result := nil list of rational; REF LISTOFRATIONAL end result := nil list of rational; PROC add = ( RATIONAL r )VOID: IF end result IS nil list of rational THEN result := HEAP LISTOFRATIONAL := ( r, nil list of rational ); end result := result ELSE next OF end result := HEAP LISTOFRATIONAL := ( r, nil list of rational ); end result := next OF end result FI ; # add # IF num OF r > den OF r THEN add( RATIONAL( num OF r OVER den OF r, 1 ) ); r := ( num OF r MOD den OF r, den OF r ) FI; PROC mod func = ( LONG LONG INT m, n )LONG LONG INT: ( ( m MOD n ) + n ) MOD n; WHILE num OF r /= 0 DO LONG LONG INT q = CEIL( den OF r / num OF r ); add( RATIONAL( 1, q ) ); r := RATIONAL( mod func( - ( den OF r ), num OF r ), ( den OF r ) * q ) OD; result FI ; # EGYPTIAN # BEGIN # task test cases # []RATIONAL test cases = ( RATIONAL( 43, 48 ), RATIONAL( 5, 121 ), RATIONAL( 2014, 59 ) ); FOR r pos FROM LWB test cases TO UPB test cases DO print( ( TOSTRING test cases[ r pos ], " -> ", TOSTRING EGYPTIAN test cases[ r pos ], newline ) ) OD; # find the fractions with the most terms and the largest denominator # print( ( "For rationals with numerator and denominator in 1..99:", newline ) ); RATIONAL largest denominator := ( 0, 1 ); REF LISTOFRATIONAL max denominator list := nil list of rational; LONG LONG INT max denominator := 0; RATIONAL most terms := ( 0, 1 ); REF LISTOFRATIONAL most terms list := nil list of rational; INT max terms := 0; FOR num TO 99 DO FOR den TO 99 DO RATIONAL r = RATIONAL( num, den ); REF LISTOFRATIONAL e := EGYPTIAN r; REF LISTOFRATIONAL p := e; INT terms := 0; WHILE p ISNT nil list of rational DO terms +:= 1; IF den OF element OF p > max denominator THEN largest denominator := r; max denominator := den OF element OF p; max denominator list := e FI; p := next OF p OD; IF terms > max terms THEN most terms := r; max terms := terms; most terms list := e FI OD OD; print( ( " ", TOSTRING most terms, " has the most terms: ", TOSTRING max terms, newline , " ", TOSTRING most terms list, newline ) ); print( ( " ", TOSTRING largest denominator, " has the largest denominator:", newline , " ", TOSTRING max denominator list, newline ) ) END END
http://rosettacode.org/wiki/Eertree
Eertree
An eertree is a data structure designed for efficient processing of certain palindrome tasks, for instance counting the number of sub-palindromes in an input string. The data structure has commonalities to both tries and suffix trees.   See links below. Task Construct an eertree for the string "eertree", then output all sub-palindromes by traversing the tree. See also   Wikipedia entry:   trie.   Wikipedia entry:   suffix tree   Cornell University Library, Computer Science, Data Structures and Algorithms ───► EERTREE: An Efficient Data Structure for Processing Palindromes in Strings.
#M2000_Interpreter
M2000 Interpreter
  If Version<9.5 Then exit If Version=9.5 And Revision<2 Then Exit Class Node { inventory myedges length, suffix=0 Function edges(s$) { =-1 : if exist(.myedges, s$) then =eval(.myedges) } Module edges_append (a$, where) { Append .myedges, a$:=where } Class: Module Node(.length) { Read ? .suffix, .myedges } } function eertree(s$) { Const evenRoot=0, oddRoot=1 Inventory Tree= oddRoot:=Node(-1,1),evenRoot:=Node(0,1) k=0 suffix=oddRoot for i=0 to len(s$)-1 { c$=mid$(s$,i+1,1) n=suffix Do { k=tree(n).length b=i-k-1 if b>=0 then if mid$(s$,b+1,1)=c$ Then exit n =tree(n).suffix } Always e=tree(n).edges(c$) if e>=0 then suffix=e :continue suffix=len(Tree)   Append Tree, len(Tree):=Node(k+2) Tree(n).edges_append c$, suffix If tree(suffix).length=1 then tree(suffix).suffix=0 : continue Do { n=tree(n).suffix b=i-tree(n).length-1 if b>0 Then If mid$(s$, b+1,1)=c$ then exit } Always e=tree(n).edges(c$) if e>=0 then tree(suffix).suffix=e   } =tree } children=lambda (s, tree, n, root$="")->{ L=Len(tree(n).myEdges) if L=0 then =s : exit L-- For i=0 to L { c=tree(n).myEdges c$=Eval$(c, i) ' read keys at position i nxt=c(i!) ' read value using position p$ = if$(n=1 -> c$, c$+root$+c$) append s, (p$,) \\ better use lambda() and not children() \\ for recursion when we copy this lambda to other identifier. s = lambda(s, tree, nxt, p$) } = s } aString=Lambda ->{ Push Quote$(Letter$) } aLine=Lambda ->{ Shift 2 ' swap two top stack items if stackitem$()="" then { Drop} Else Push letter$+", "+Letter$ } Palindromes$=Lambda$ children, aString, aLine (Tree)-> { ="("+children(children((,), Tree, 0), Tree, 1)#Map(aString)#Fold$(aline,"")+")" }   Print Palindromes$(eertree("eertree"))  
http://rosettacode.org/wiki/Eertree
Eertree
An eertree is a data structure designed for efficient processing of certain palindrome tasks, for instance counting the number of sub-palindromes in an input string. The data structure has commonalities to both tries and suffix trees.   See links below. Task Construct an eertree for the string "eertree", then output all sub-palindromes by traversing the tree. See also   Wikipedia entry:   trie.   Wikipedia entry:   suffix tree   Cornell University Library, Computer Science, Data Structures and Algorithms ───► EERTREE: An Efficient Data Structure for Processing Palindromes in Strings.
#Nim
Nim
import algorithm, strformat, strutils, tables   type   Node = ref object edges: Table[char, Node] # Edges (forward links). link: Node # Suffix link (backward link). len: int # Length of the node.   Eertree = object nodes: seq[Node] rto: Node # Odd length root node or node -1. rte: Node # Even length root node or node 0.Node str: string # Accumulated input string. maxSuf: Node # Maximum suffix.   #---------------------------------------------------------------------------------------------------   func initEertree(): Eertree = ## Create and initialize an eertree. result = Eertree(rto: Node(len: - 1), rte: Node(len: 0)) result.rto.link = result.rto result.rte.link = result.rto result.str = "0" result.maxSuf = result.rte   #---------------------------------------------------------------------------------------------------   func getMaxSuffixPal(tree: Eertree; startNode: Node; ch: char): Node = ## We traverse the suffix-palindromes of "tree" in the order of decreasing length. ## For each palindrome we read its length "k" and compare "tree[i-k]" against "ch" ## until we get an equality or arrive at the -1 node.   result = startNode let i = tree.str.high while result != tree.rto and tree.str[i - result.len] != ch: doAssert(result != result.link, "circular reference above odd root") result = result.link   #---------------------------------------------------------------------------------------------------   func add(tree: var Eertree; ch: char): bool = ## We need to find the maximum suffix-palindrome P of Ta. ## Start by finding maximum suffix-palindrome Q of T. ## To do this, we traverse the suffix-palindromes of T ## in the order of decreasing length, starting with maxSuf(T).   let q = tree.getMaxSuffixPal(tree.maxSuf, ch)   # We check "q" to see whether it has an outgoing edge labeled by "ch". result = ch notin q.edges   if result: # We create the node "p" of length "q.len + 2" let p = Node() tree.nodes.add(p) p.len = q.len + 2 if p.len == 1: # If p = ch, create the suffix link (p, 0). p.link = tree.rte else: # It remains to create the suffix link from "p" if "|p|>1". Just continue # traversing suffix-palindromes of T starting with the suffix link of "q". p.link = tree.getMaxSuffixPal(q.link, ch).edges[ch] # Create the edge "(q, p)". q.edges[ch] = p   # "p" becomes the new maxSuf. tree.maxSuf = q.edges[ch]   # Store accumulated input string. tree.str.add(ch)   #---------------------------------------------------------------------------------------------------   func getSubPalindromes(tree: Eertree; node: Node; nodesToHere: seq[Node]; charsToHere: string; result: var seq[string]) = ## Each node represents a palindrome, which can be reconstructed ## by the path from the root node to each non-root node.   # Traverse all edges, since they represent other palindromes. for linkName, node2 in node.edges.pairs: tree.getSubPalindromes(node2, nodesToHere & node2, charsToHere & linkName, result)   # Reconstruct based on charsToHere characters. if node notin [tree.rto, tree.rte]: # Don’t print for root nodes. let assembled = reversed(charsTohere).join() & (if nodesToHere[0] == tree.rte: charsToHere else: charsToHere[1..^1]) result.add(assembled)   #---------------------------------------------------------------------------------------------------   func getSubPalindromes(tree: Eertree): seq[string] = ## Traverse tree to find sub-palindromes.   # Odd length words tree.getSubPalindromes(tree.rto, @[tree.rto], "", result) # Even length words tree.getSubPalindromes(tree.rte, @[tree.rte], "", result)   #———————————————————————————————————————————————————————————————————————————————————————————————————   when isMainModule: const Str = "eertree" echo fmt"Processing string: '{Str}'" var eertree = initEertree() for ch in Str: discard eertree.add(ch) echo fmt"Number of sub-palindromes: {eertree.nodes.len}" let result = eertree.getSubPalindromes() echo fmt"Sub-palindromes: {result.join("", "")}"
http://rosettacode.org/wiki/Ethiopian_multiplication
Ethiopian multiplication
Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last in the same column, until you write a value of 1. In the right-hand column repeatedly double the last number and write the result below. stop when you add a result in the same row as where the left hand column shows 1. Examine the table produced and discard any row where the value in the left column is even. Sum the values in the right-hand column that remain to produce the result of multiplying the original two numbers together For example:   17 × 34 17 34 Halving the first column: 17 34 8 4 2 1 Doubling the second column: 17 34 8 68 4 136 2 272 1 544 Strike-out rows whose first cell is even: 17 34 8 68 4 136 2 272 1 544 Sum the remaining numbers in the right-hand column: 17 34 8 -- 4 --- 2 --- 1 544 ==== 578 So 17 multiplied by 34, by the Ethiopian method is 578. Task The task is to define three named functions/methods/procedures/subroutines: one to halve an integer, one to double an integer, and one to state if an integer is even. Use these functions to create a function that does Ethiopian multiplication. References Ethiopian multiplication explained (BBC Video clip) A Night Of Numbers - Go Forth And Multiply (Video) Russian Peasant Multiplication Programming Praxis: Russian Peasant Multiplication
#Prolog
Prolog
halve(X,Y) :- Y is X // 2. double(X,Y) :- Y is 2*X. is_even(X) :- 0 is X mod 2.   % columns(First,Second,Left,Right) is true if integers First and Second % expand into the columns Left and Right, respectively columns(1,Second,[1],[Second]). columns(First,Second,[First|Left],[Second|Right]) :- halve(First,Halved), double(Second,Doubled), columns(Halved,Doubled,Left,Right).   % contribution(Left,Right,Amount) is true if integers Left and Right, % from their respective columns contribute Amount to the final sum. contribution(Left,_Right,0) :- is_even(Left). contribution(Left,Right,Right) :- \+ is_even(Left).   ethiopian(First,Second,Product) :- columns(First,Second,Left,Right), maplist(contribution,Left,Right,Contributions), sumlist(Contributions,Product).
http://rosettacode.org/wiki/Elementary_cellular_automaton
Elementary cellular automaton
An elementary cellular automaton is a one-dimensional cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors. Those three values can be encoded with three bits. The rules of evolution are then encoded with eight bits indicating the outcome of each of the eight possibilities 111, 110, 101, 100, 011, 010, 001 and 000 in this order. Thus for instance the rule 13 means that a state is updated to 1 only in the cases 011, 010 and 000, since 13 in binary is 0b00001101. Task Create a subroutine, program or function that allows to create and visualize the evolution of any of the 256 possible elementary cellular automaton of arbitrary space length and for any given initial state. You can demonstrate your solution with any automaton of your choice. The space state should wrap: this means that the left-most cell should be considered as the right neighbor of the right-most cell, and reciprocally. This task is basically a generalization of one-dimensional cellular automata. See also Cellular automata (natureofcode.com)
#Ceylon
Ceylon
class Rule(number) satisfies Correspondence<Boolean[3], Boolean> {   shared Byte number;   "all 3 bit patterns will return a value so this is always true" shared actual Boolean defines(Boolean[3] key) => true;   shared actual Boolean? get(Boolean[3] key) => number.get((key[0] then 4 else 0) + (key[1] then 2 else 0) + (key[2] then 1 else 0));   function binaryString(Integer integer, Integer maxPadding) => Integer.format(integer, 2).padLeading(maxPadding, '0');   string => let (digits = binaryString(number.unsigned, 8)) "Rule #``number`` ``" | ".join { for (pattern in $111..0) binaryString(pattern, 3) }`` ``" | ".join(digits.map((Character element) => element.string.pad(3)))``"; }   class ElementaryAutomaton {   shared static ElementaryAutomaton|ParseException parse(Rule rule, String cells, Character aliveChar, Character deadChar) { if (!cells.every((Character element) => element == aliveChar || element == deadChar)) { return ParseException("the string was not a valid automaton"); } return ElementaryAutomaton(rule, cells.map((Character element) => element == aliveChar)); }   shared Rule rule;   Array<Boolean> cells;   shared new(Rule rule, {Boolean*} initialCells) { this.rule = rule; this.cells = Array { *initialCells }; }   shared Boolean evolve() {   if (cells.empty) { return false; }   function left(Integer index) { assert (exists cell = cells[index - 1] else cells.last); return cell; }   function right(Integer index) { assert (exists cell = cells[index + 1] else cells.first); return cell; }   value newCells = Array.ofSize(cells.size, false); for (index->cell in cells.indexed) { value neighbourhood = [left(index), cell, right(index)]; assert (exists newCell = rule[neighbourhood]); newCells[index] = newCell; }   if (newCells == cells) { return false; }   newCells.copyTo(cells); return true; }   shared void display(Character aliveChar = '#', Character deadChar = ' ') { print("".join(cells.map((Boolean element) => element then aliveChar else deadChar))); } }   shared void run() { value rule = Rule(90.byte); print(rule);   value automaton = ElementaryAutomaton.parse(rule, " # ", '#', ' '); assert (is ElementaryAutomaton automaton);   for (generation in 0..10) { automaton.display(); automaton.evolve(); } }
http://rosettacode.org/wiki/Elementary_cellular_automaton
Elementary cellular automaton
An elementary cellular automaton is a one-dimensional cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors. Those three values can be encoded with three bits. The rules of evolution are then encoded with eight bits indicating the outcome of each of the eight possibilities 111, 110, 101, 100, 011, 010, 001 and 000 in this order. Thus for instance the rule 13 means that a state is updated to 1 only in the cases 011, 010 and 000, since 13 in binary is 0b00001101. Task Create a subroutine, program or function that allows to create and visualize the evolution of any of the 256 possible elementary cellular automaton of arbitrary space length and for any given initial state. You can demonstrate your solution with any automaton of your choice. The space state should wrap: this means that the left-most cell should be considered as the right neighbor of the right-most cell, and reciprocally. This task is basically a generalization of one-dimensional cellular automata. See also Cellular automata (natureofcode.com)
#Common_Lisp
Common Lisp
(defun automaton (init rule &optional (stop 10)) (labels ((next-gen (cells) (mapcar #'new-cell (cons (car (last cells)) cells) cells (append (cdr cells) (list (car cells)))))   (new-cell (left current right) (let ((shift (+ (* left 4) (* current 2) right))) (if (logtest rule (ash 1 shift)) 1 0)))   (pretty-print (cells) (format T "~{~a~}~%" (mapcar (lambda (x) (if (zerop x) #\. #\#)) cells))))   (loop for cells = init then (next-gen cells) for i below stop do (pretty-print cells))))   (automaton '(0 0 0 0 0 0 1 0 0 0 0 0 0) 90)
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterative or recursive. Support for trapping negative   n   errors is optional. Related task   Primorial numbers
#Symsyn
Symsyn
  fact if n < 1 return endif * n fn fn - n call fact return   start   if i < 20 1 fn i n call fact fn [] + i goif endif  
http://rosettacode.org/wiki/Even_or_odd
Even or odd
Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Divide i by 2. The remainder equals 0 iff i is even. The remainder equals +1 or -1 iff i is odd. Use modular congruences: i ≡ 0 (mod 2) iff i is even. i ≡ 1 (mod 2) iff i is odd.
#TI-83_BASIC
TI-83 BASIC
  If fPart(.5Ans Then Disp "ODD Else Disp "EVEN End  
http://rosettacode.org/wiki/Even_or_odd
Even or odd
Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Divide i by 2. The remainder equals 0 iff i is even. The remainder equals +1 or -1 iff i is odd. Use modular congruences: i ≡ 0 (mod 2) iff i is even. i ≡ 1 (mod 2) iff i is odd.
#TUSCRIPT
TUSCRIPT
$$ MODE TUSCRIPT LOOP n=-5,5 x=MOD(n,2) SELECT x CASE 0 PRINT n," is even" DEFAULT PRINT n," is odd" ENDSELECT ENDLOOP
http://rosettacode.org/wiki/Echo_server
Echo server
Create a network service that sits on TCP port 12321, which accepts connections on that port, and which echoes complete lines (using a carriage-return/line-feed sequence as line separator) back to clients. No error handling is required. For the purposes of testing, it is only necessary to support connections from localhost (127.0.0.1 or perhaps ::1). Logging of connection information to standard output is recommended. The implementation must be able to handle simultaneous connections from multiple clients. A multi-threaded or multi-process solution may be used. Each connection must be able to echo more than a single line. The implementation must not stop responding to other clients if one client sends a partial line or stops reading responses.
#Elixir
Elixir
defmodule Echo.Server do def start(port) do tcp_options = [:binary, {:packet, 0}, {:active, false}] {:ok, socket} = :gen_tcp.listen(port, tcp_options) listen(socket) end defp listen(socket) do {:ok, conn} = :gen_tcp.accept(socket) spawn(fn -> recv(conn) end) listen(socket) end defp recv(conn) do case :gen_tcp.recv(conn, 0) do {:ok, data} ->  :gen_tcp.send(conn, data) recv(conn) {:error, :closed} ->  :ok end end end
http://rosettacode.org/wiki/Elementary_cellular_automaton/Infinite_length
Elementary cellular automaton/Infinite length
The purpose of this task is to create a version of an Elementary cellular automaton whose number of cells is only limited by the memory size of the computer. To be precise, consider the state of the automaton to be made of an infinite number of cells, but with a bounded support. In other words, to describe the state of the automaton, you need a finite number of adjacent cells, along with their individual state, and you then consider that the individual state of each of all other cells is the negation of the closest individual cell among the previously defined finite number of cells. Examples: 1 -> ..., 0, 0, 1, 0, 0, ... 0, 1 -> ..., 1, 1, 0, 1, 0, 0, ... 1, 0, 1 -> ..., 0, 0, 1, 0, 1, 0, 0, ... More complex methods can be imagined, provided it is possible to somehow encode the infinite sections. But for this task we will stick to this simple version.
#Wren
Wren
import "/fmt" for Fmt   var addNoCells = Fn.new { |s| var l = (s[0] == "*") ? "." : "*" var r = (s[-1] == "*") ? "." : "*" for (i in 0..1) { s.insert(0, l) s.add(r) } }   var step = Fn.new { |cells, rule| var newCells = [] for (i in 0...cells.count - 2) { var bin = 0 var b = 2 for (n in i...i + 3) { bin = bin + (((cells[n] == "*") ? 1 : 0) << b) b = b >> 1 } var a = ((rule & (1 << bin)) != 0) ? "*" : "." newCells.add(a) } return newCells }   var evolve = Fn.new { |l, rule| System.print(" Rule #%(rule):") var cells = ["*"] for (x in 0...l) { addNoCells.call(cells) var width = 40 + (cells.count >> 1) Fmt.print("$*s", width, cells.join()) cells = step.call(cells, rule) } }   evolve.call(35, 90) System.print()
http://rosettacode.org/wiki/Empty_string
Empty string
Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. 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
#Wee_Basic
Wee Basic
let string$="" if string$="" print 1 "The string is empty." elseif string$<>"" print 1 "The string is not empty." endif end
http://rosettacode.org/wiki/Empty_string
Empty string
Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. 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
#Wren
Wren
var isEmpty = Fn.new { |s| s == "" }   var s = "" var t = "0" System.print("'s' is empty? %(isEmpty.call(s))") System.print("'t' is empty? %(isEmpty.call(t))")
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Seed7
Seed7
$ include "seed7_05.s7i";   const proc: main is noop;
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Set_lang
Set lang
 
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Sidef
Sidef
 
http://rosettacode.org/wiki/Earliest_difference_between_prime_gaps
Earliest difference between prime gaps
When calculating prime numbers > 2, the difference between adjacent primes is always an even number. This difference, also referred to as the gap, varies in an random pattern; at least, no pattern has ever been discovered, and it is strongly conjectured that no pattern exists. However, it is also conjectured that between some two adjacent primes will be a gap corresponding to every positive even integer. gap minimal starting prime ending prime 2 3 5 4 7 11 6 23 29 8 89 97 10 139 149 12 199 211 14 113 127 16 1831 1847 18 523 541 20 887 907 22 1129 1151 24 1669 1693 26 2477 2503 28 2971 2999 30 4297 4327 This task involves locating the minimal primes corresponding to those gaps. Though every gap value exists, they don't seem to come in any particular order. For example, this table shows the gaps and minimum starting value primes for 2 through 30: For the purposes of this task, considering only primes greater than 2, consider prime gaps that differ by exactly two to be adjacent. Task For each order of magnitude m from 10¹ through 10⁶: Find the first two sets of adjacent minimum prime gaps where the absolute value of the difference between the prime gap start values is greater than m. E.G. For an m of 10¹; The start value of gap 2 is 3, the start value of gap 4 is 7, the difference is 7 - 3 or 4. 4 < 10¹ so keep going. The start value of gap 4 is 7, the start value of gap 6 is 23, the difference is 23 - 7, or 16. 16 > 10¹ so this the earliest adjacent gap difference > 10¹. Stretch goal Do the same for 10⁷ and 10⁸ (and higher?) orders of magnitude Note: the earliest value found for each order of magnitude may not be unique, in fact, is not unique; also, with the gaps in ascending order, the minimal starting values are not strictly ascending.
#Java
Java
import java.util.HashMap; import java.util.Map;   public class PrimeGaps { private Map<Integer, Integer> gapStarts = new HashMap<>(); private int lastPrime; private PrimeGenerator primeGenerator = new PrimeGenerator(1000, 500000);   public static void main(String[] args) { final int limit = 100000000; PrimeGaps pg = new PrimeGaps(); for (int pm = 10, gap1 = 2;;) { int start1 = pg.findGapStart(gap1); int gap2 = gap1 + 2; int start2 = pg.findGapStart(gap2); int diff = start2 > start1 ? start2 - start1 : start1 - start2; if (diff > pm) { System.out.printf( "Earliest difference > %,d between adjacent prime gap starting primes:\n" + "Gap %,d starts at %,d, gap %,d starts at %,d, difference is %,d.\n\n", pm, gap1, start1, gap2, start2, diff); if (pm == limit) break; pm *= 10; } else { gap1 = gap2; } } }   private int findGapStart(int gap) { Integer start = gapStarts.get(gap); if (start != null) return start; for (;;) { int prev = lastPrime; lastPrime = primeGenerator.nextPrime(); int diff = lastPrime - prev; gapStarts.putIfAbsent(diff, prev); if (diff == gap) return prev; } } }
http://rosettacode.org/wiki/Earliest_difference_between_prime_gaps
Earliest difference between prime gaps
When calculating prime numbers > 2, the difference between adjacent primes is always an even number. This difference, also referred to as the gap, varies in an random pattern; at least, no pattern has ever been discovered, and it is strongly conjectured that no pattern exists. However, it is also conjectured that between some two adjacent primes will be a gap corresponding to every positive even integer. gap minimal starting prime ending prime 2 3 5 4 7 11 6 23 29 8 89 97 10 139 149 12 199 211 14 113 127 16 1831 1847 18 523 541 20 887 907 22 1129 1151 24 1669 1693 26 2477 2503 28 2971 2999 30 4297 4327 This task involves locating the minimal primes corresponding to those gaps. Though every gap value exists, they don't seem to come in any particular order. For example, this table shows the gaps and minimum starting value primes for 2 through 30: For the purposes of this task, considering only primes greater than 2, consider prime gaps that differ by exactly two to be adjacent. Task For each order of magnitude m from 10¹ through 10⁶: Find the first two sets of adjacent minimum prime gaps where the absolute value of the difference between the prime gap start values is greater than m. E.G. For an m of 10¹; The start value of gap 2 is 3, the start value of gap 4 is 7, the difference is 7 - 3 or 4. 4 < 10¹ so keep going. The start value of gap 4 is 7, the start value of gap 6 is 23, the difference is 23 - 7, or 16. 16 > 10¹ so this the earliest adjacent gap difference > 10¹. Stretch goal Do the same for 10⁷ and 10⁸ (and higher?) orders of magnitude Note: the earliest value found for each order of magnitude may not be unique, in fact, is not unique; also, with the gaps in ascending order, the minimal starting values are not strictly ascending.
#Julia
Julia
using Formatting using Primes   function primegaps(limit = 10^9) c(n) = format(n, commas=true) pri = primes(limit * 5) gapstarts = Dict{Int, Int}() for i in 2:length(pri) get!(gapstarts, pri[i] - pri[i - 1], pri[i - 1]) end pm, gap1 = 10, 2 while true while !haskey(gapstarts, gap1) gap1 += 2 end start1 = gapstarts[gap1] gap2 = gap1 + 2 if !haskey(gapstarts, gap2) gap1 = gap2 + 2 continue end start2 = gapstarts[gap2] if ((diff = abs(start2 - start1)) > pm) println("Earliest difference > $(c(pm)) between adjacent prime gap starting primes:") println("Gap $gap1 starts at $(c(start1)), gap $(c(gap2)) starts at $(c(start2)), difference is $(c(diff)).\n") pm == limit && break pm *= 10 else gap1 = gap2 end end end   primegaps()  
http://rosettacode.org/wiki/Element-wise_operations
Element-wise operations
This task is similar to:   Matrix multiplication   Matrix transposition Task Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks. Implement:   addition   subtraction   multiplication   division   exponentiation Extend the task if necessary to include additional basic operations, which should not require their own specialised task.
#C
C
#include <math.h>   #define for_i for(i = 0; i < h; i++) #define for_j for(j = 0; j < w; j++) #define _M double** #define OPM(name, _op_) \ void eop_##name(_M a, _M b, _M c, int w, int h){int i,j;\ for_i for_j c[i][j] = a[i][j] _op_ b[i][j];} OPM(add, +);OPM(sub, -);OPM(mul, *);OPM(div, /);   #define OPS(name, res) \ void eop_s_##name(_M a, double s, _M b, int w, int h) {double x;int i,j;\ for_i for_j {x = a[i][j]; b[i][j] = res;}} OPS(mul, x*s);OPS(div, x/s);OPS(add, x+s);OPS(sub, x-s);OPS(pow, pow(x, s));
http://rosettacode.org/wiki/Egyptian_division
Egyptian division
Egyptian division is a method of dividing integers using addition and doubling that is similar to the algorithm of Ethiopian multiplication Algorithm: Given two numbers where the dividend is to be divided by the divisor: Start the construction of a table of two columns: powers_of_2, and doublings; by a first row of a 1 (i.e. 2^0) in the first column and 1 times the divisor in the first row second column. Create the second row with columns of 2 (i.e 2^1), and 2 * divisor in order. Continue with successive i’th rows of 2^i and 2^i * divisor. Stop adding rows, and keep only those rows, where 2^i * divisor is less than or equal to the dividend. We now assemble two separate sums that both start as zero, called here answer and accumulator Consider each row of the table, in the reverse order of its construction. If the current value of the accumulator added to the doublings cell would be less than or equal to the dividend then add it to the accumulator, as well as adding the powers_of_2 cell value to the answer. When the first row has been considered as above, then the integer division of dividend by divisor is given by answer. (And the remainder is given by the absolute value of accumulator - dividend). Example: 580 / 34 Table creation: powers_of_2 doublings 1 34 2 68 4 136 8 272 16 544 Initialization of sums: powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 0 0 Considering table rows, bottom-up: When a row is considered it is shown crossed out if it is not accumulated, or bold if the row causes summations. powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 4 136 8 272 16 544 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 4 136 16 544 8 272 16 544 powers_of_2 doublings answer accumulator 1 34 2 68 16 544 4 136 8 272 16 544 powers_of_2 doublings answer accumulator 1 34 17 578 2 68 4 136 8 272 16 544 Answer So 580 divided by 34 using the Egyptian method is 17 remainder (578 - 580) or 2. Task The task is to create a function that does Egyptian division. The function should closely follow the description above in using a list/array of powers of two, and another of doublings. Functions should be clear interpretations of the algorithm. Use the function to divide 580 by 34 and show the answer here, on this page. Related tasks   Egyptian fractions References   Egyptian Number System
#Arturo
Arturo
egyptianDiv: function [dividend, divisor][ ensure -> and? dividend >= 0 divisor > 0   if dividend < divisor -> return @[0, dividend]   powersOfTwo: new [1] doublings: new @[divisor] d: divisor   while [true][ d: 2 * d if d > dividend -> break 'powersOfTwo ++ 2 * last powersOfTwo 'doublings ++ d ]   answer: 0 accumulator: 0   loop (dec size doublings)..0 'i [ if dividend >= accumulator + doublings\[i] [ accumulator: accumulator + doublings\[i] answer: answer + powersOfTwo\[i] if accumulator = dividend -> break ] ]   return @[answer, dividend - accumulator] ]   dividend: 580 divisor: 34   [quotient, remainder]: egyptianDiv dividend divisor   print [dividend "divided by" divisor "is" quotient "with remainder" remainder]
http://rosettacode.org/wiki/Egyptian_fractions
Egyptian fractions
An   Egyptian fraction   is the sum of distinct unit fractions such as: 1 2 + 1 3 + 1 16 ( = 43 48 ) {\displaystyle {\tfrac {1}{2}}+{\tfrac {1}{3}}+{\tfrac {1}{16}}\,(={\tfrac {43}{48}})} Each fraction in the expression has a numerator equal to   1   (unity)   and a denominator that is a positive integer,   and all the denominators are distinct   (i.e., no repetitions). Fibonacci's   Greedy algorithm for Egyptian fractions   expands the fraction   x y {\displaystyle {\tfrac {x}{y}}}   to be represented by repeatedly performing the replacement x y = 1 ⌈ y / x ⌉ + ( − y ) mod x y ⌈ y / x ⌉ {\displaystyle {\frac {x}{y}}={\frac {1}{\lceil y/x\rceil }}+{\frac {(-y)\!\!\!\!\mod x}{y\lceil y/x\rceil }}} (simplifying the 2nd term in this replacement as necessary, and where   ⌈ x ⌉ {\displaystyle \lceil x\rceil }   is the   ceiling   function). For this task,   Proper and improper fractions   must be able to be expressed. Proper  fractions   are of the form   a b {\displaystyle {\tfrac {a}{b}}}   where   a {\displaystyle a}   and   b {\displaystyle b}   are positive integers, such that   a < b {\displaystyle a<b} ,     and improper fractions are of the form   a b {\displaystyle {\tfrac {a}{b}}}   where   a {\displaystyle a}   and   b {\displaystyle b}   are positive integers, such that   a ≥ b. (See the REXX programming example to view one method of expressing the whole number part of an improper fraction.) For improper fractions, the integer part of any improper fraction should be first isolated and shown preceding the Egyptian unit fractions, and be surrounded by square brackets [n]. Task requirements   show the Egyptian fractions for: 43 48 {\displaystyle {\tfrac {43}{48}}} and 5 121 {\displaystyle {\tfrac {5}{121}}} and 2014 59 {\displaystyle {\tfrac {2014}{59}}}   for all proper fractions,   a b {\displaystyle {\tfrac {a}{b}}}   where   a {\displaystyle a}   and   b {\displaystyle b}   are positive one-or two-digit (decimal) integers, find and show an Egyptian fraction that has:   the largest number of terms,   the largest denominator.   for all one-, two-, and three-digit integers,   find and show (as above).     {extra credit} Also see   Wolfram MathWorld™ entry: Egyptian fraction
#C
C
#include <stdbool.h> #include <stdint.h> #include <stdio.h>   typedef int64_t integer;   struct Pair { integer md; int tc; };   integer mod(integer x, integer y) { return ((x % y) + y) % y; }   integer gcd(integer a, integer b) { if (0 == a) return b; if (0 == b) return a; if (a == b) return a; if (a > b) return gcd(a - b, b); return gcd(a, b - a); }   void write0(bool show, char *str) { if (show) { printf(str); } }   void write1(bool show, char *format, integer a) { if (show) { printf(format, a); } }   void write2(bool show, char *format, integer a, integer b) { if (show) { printf(format, a, b); } }   struct Pair egyptian(integer x, integer y, bool show) { struct Pair ret; integer acc = 0; bool first = true;   ret.tc = 0; ret.md = 0;   write2(show, "Egyptian fraction for %lld/%lld: ", x, y); while (x > 0) { integer z = (y + x - 1) / x; if (z == 1) { acc++; } else { if (acc > 0) { write1(show, "%lld + ", acc); first = false; acc = 0; ret.tc++; } else if (first) { first = false; } else { write0(show, " + "); } if (z > ret.md) { ret.md = z; } write1(show, "1/%lld", z); ret.tc++; } x = mod(-y, x); y = y * z; } if (acc > 0) { write1(show, "%lld", acc); ret.tc++; } write0(show, "\n");   return ret; }   int main() { struct Pair p; integer nm = 0, dm = 0, dmn = 0, dmd = 0, den = 0;; int tm, i, j;   egyptian(43, 48, true); egyptian(5, 121, true); // final term cannot be represented correctly egyptian(2014, 59, true);   tm = 0; for (i = 1; i < 100; i++) { for (j = 1; j < 100; j++) { p = egyptian(i, j, false); if (p.tc > tm) { tm = p.tc; nm = i; dm = j; } if (p.md > den) { den = p.md; dmn = i; dmd = j; } } } printf("Term max is %lld/%lld with %d terms.\n", nm, dm, tm); // term max is correct printf("Denominator max is %lld/%lld\n", dmn, dmd); // denominator max is not correct egyptian(dmn, dmd, true); // enough digits cannot be represented without bigint   return 0; }
http://rosettacode.org/wiki/Eertree
Eertree
An eertree is a data structure designed for efficient processing of certain palindrome tasks, for instance counting the number of sub-palindromes in an input string. The data structure has commonalities to both tries and suffix trees.   See links below. Task Construct an eertree for the string "eertree", then output all sub-palindromes by traversing the tree. See also   Wikipedia entry:   trie.   Wikipedia entry:   suffix tree   Cornell University Library, Computer Science, Data Structures and Algorithms ───► EERTREE: An Efficient Data Structure for Processing Palindromes in Strings.
#Objeck
Objeck
use Collection.Generic;   class Eertree { function : Main(args : String[]) ~ Nil { tree := GetEertree("eertree"); Show(SubPalindromes(tree)); }   function : GetEertree(s : String) ~ Vector<Node> { tree := Vector->New()<Node>; tree->AddBack(Node->New(0, Nil, 1)); tree->AddBack(Node->New(-1, Nil, 1)); suffix := 1;   n : Int; k : Int; for(i := 0; i < s->Size(); ++i;) { c := s->Get(i);   done := false; for (j := suffix; <>done; j := tree->Get(j)->GetSuffix();) { k := tree->Get(j)->GetLength(); b := i - k - 1; if (b >= 0 & s->Get(b) = c) { n := j; done := true; }; }; skip := false; if (tree->Get(n)->GetEdges()->Has(c)) { suffix := tree->Get(n)->GetEdges()->Find(c)->Get(); skip := true; };   if(<>skip) { suffix := tree->Size(); tree->AddBack(Node->New(k + 2)); tree->Get(n)->GetEdges()->Insert(c, suffix); if (tree->Get(suffix)->GetLength() = 1) { tree->Get(suffix)->SetSuffix(0); skip := true; };   if(<>skip) { done := false; while (<>done) { n := tree->Get(n)->GetSuffix(); b := i - tree->Get(n)->GetLength() - 1; if (b >= 0 & s->Get(b) = c) { done := true; }; }; tree->Get(suffix)->SetSuffix(tree->Get(n)->GetEdges()->Find(c)->Get()); }; }; };   return tree; }   function : SubPalindromes(tree : Vector<Node>) ~ Vector<String> { s := Vector->New()<String>; SubPalindromesChildren(0, "", tree, s);   keys := tree->Get(1)->GetEdges()->GetKeys()<CharHolder>; each(k : keys) { key := keys->Get(k); str := key->Get()->ToString(); s->AddBack(str); value := tree->Get(1)->GetEdges()->Find(key)->As(IntHolder)->Get(); SubPalindromesChildren(value, str, tree, s); };   return s; }   function : SubPalindromesChildren(n : Int, p : String, tree : Vector<Node>, s : Vector<String>) ~ Nil { keys := tree->Get(n)->GetEdges()->GetKeys()<CharHolder>; each(k : keys) { key := keys->Get(k); c := key->Get(); value := tree->Get(n)->GetEdges()->Find(key)->As(IntHolder)->Get(); str := ""; str += c; str += p; str += c; s->AddBack(str); SubPalindromesChildren(value, str, tree, s); }; }   function : Show(result : Vector<String>) ~ Nil { out := "["; each(i : result) { out += result->Get(i); if(i + 1 < result->Size()) { out += ", "; }; }; out += "]"; out->PrintLine(); } }   class Node { @length : Int; @edges : Map<CharHolder, IntHolder>; @suffix : Int;   New(length : Int, edges : Map<CharHolder, IntHolder>, suffix : Int) { @length := length; @edges := edges <> Nil ? edges : Map->New()<CharHolder, IntHolder>; @suffix := suffix; }   New(length : Int) { @length := length; @edges := Map->New()<CharHolder, IntHolder>; }   method : public : GetLength() ~ Int { return @length; }   method : public : GetSuffix() ~ Int { return @suffix; }   method : public : SetSuffix(suffix : Int) ~ Nil { @suffix := suffix; }   method : public : GetEdges() ~ Map<CharHolder, IntHolder> { return @edges; } }
http://rosettacode.org/wiki/Ethiopian_multiplication
Ethiopian multiplication
Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last in the same column, until you write a value of 1. In the right-hand column repeatedly double the last number and write the result below. stop when you add a result in the same row as where the left hand column shows 1. Examine the table produced and discard any row where the value in the left column is even. Sum the values in the right-hand column that remain to produce the result of multiplying the original two numbers together For example:   17 × 34 17 34 Halving the first column: 17 34 8 4 2 1 Doubling the second column: 17 34 8 68 4 136 2 272 1 544 Strike-out rows whose first cell is even: 17 34 8 68 4 136 2 272 1 544 Sum the remaining numbers in the right-hand column: 17 34 8 -- 4 --- 2 --- 1 544 ==== 578 So 17 multiplied by 34, by the Ethiopian method is 578. Task The task is to define three named functions/methods/procedures/subroutines: one to halve an integer, one to double an integer, and one to state if an integer is even. Use these functions to create a function that does Ethiopian multiplication. References Ethiopian multiplication explained (BBC Video clip) A Night Of Numbers - Go Forth And Multiply (Video) Russian Peasant Multiplication Programming Praxis: Russian Peasant Multiplication
#Python
Python
tutor = True   def halve(x): return x // 2   def double(x): return x * 2   def even(x): return not x % 2   def ethiopian(multiplier, multiplicand): if tutor: print("Ethiopian multiplication of %i and %i" % (multiplier, multiplicand)) result = 0 while multiplier >= 1: if even(multiplier): if tutor: print("%4i %6i STRUCK" % (multiplier, multiplicand)) else: if tutor: print("%4i %6i KEPT" % (multiplier, multiplicand)) result += multiplicand multiplier = halve(multiplier) multiplicand = double(multiplicand) if tutor: print() return result
http://rosettacode.org/wiki/Elementary_cellular_automaton
Elementary cellular automaton
An elementary cellular automaton is a one-dimensional cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors. Those three values can be encoded with three bits. The rules of evolution are then encoded with eight bits indicating the outcome of each of the eight possibilities 111, 110, 101, 100, 011, 010, 001 and 000 in this order. Thus for instance the rule 13 means that a state is updated to 1 only in the cases 011, 010 and 000, since 13 in binary is 0b00001101. Task Create a subroutine, program or function that allows to create and visualize the evolution of any of the 256 possible elementary cellular automaton of arbitrary space length and for any given initial state. You can demonstrate your solution with any automaton of your choice. The space state should wrap: this means that the left-most cell should be considered as the right neighbor of the right-most cell, and reciprocally. This task is basically a generalization of one-dimensional cellular automata. See also Cellular automata (natureofcode.com)
#D
D
import std.stdio, std.string, std.conv, std.range, std.algorithm, std.typecons;   enum mod = (in int n, in int m) pure nothrow @safe @nogc => ((n % m) + m) % m;   struct ECAwrap { public string front; public enum bool empty = false; private immutable const(char)[string] next;   this(in string cells_, in uint rule) pure @safe { this.front = cells_; immutable ruleBits = "%08b".format(rule).retro.text; next = 8.iota.map!(n => tuple("%03b".format(n), char(ruleBits[n]))).assocArray; }   void popFront() pure @safe { alias c = front; c = iota(c.length) .map!(i => next[[c[(i - 1).mod($)], c[i], c[(i + 1) % $]]]) .text; } }   void main() @safe { enum nLines = 50; immutable string start = "0000000001000000000"; immutable uint[] rules = [90, 30, 122]; writeln("Rules: ", rules); auto ecas = rules.map!(rule => ECAwrap(start, rule)).array;   foreach (immutable i; 0 .. nLines) { writefln("%2d: %-(%s  %)", i, ecas.map!(eca => eca.front.tr("01", ".#"))); foreach (ref eca; ecas) eca.popFront; } }
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterative or recursive. Support for trapping negative   n   errors is optional. Related task   Primorial numbers
#Tailspin
Tailspin
  templates factorial when <0..> do @: 1; 1..$ -> @: $@ * $; $@ ! end factorial  
http://rosettacode.org/wiki/Even_or_odd
Even or odd
Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Divide i by 2. The remainder equals 0 iff i is even. The remainder equals +1 or -1 iff i is odd. Use modular congruences: i ≡ 0 (mod 2) iff i is even. i ≡ 1 (mod 2) iff i is odd.
#UNIX_Shell
UNIX Shell
iseven() { [[ $(($1%2)) -eq 0 ]] && return 0 return 1 }
http://rosettacode.org/wiki/Even_or_odd
Even or odd
Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Divide i by 2. The remainder equals 0 iff i is even. The remainder equals +1 or -1 iff i is odd. Use modular congruences: i ≡ 0 (mod 2) iff i is even. i ≡ 1 (mod 2) iff i is odd.
#Ursa
Ursa
decl int input set input (in int console) if (= (mod input 2) 1) out "odd" endl console else out "even" endl console end if
http://rosettacode.org/wiki/Echo_server
Echo server
Create a network service that sits on TCP port 12321, which accepts connections on that port, and which echoes complete lines (using a carriage-return/line-feed sequence as line separator) back to clients. No error handling is required. For the purposes of testing, it is only necessary to support connections from localhost (127.0.0.1 or perhaps ::1). Logging of connection information to standard output is recommended. The implementation must be able to handle simultaneous connections from multiple clients. A multi-threaded or multi-process solution may be used. Each connection must be able to echo more than a single line. The implementation must not stop responding to other clients if one client sends a partial line or stops reading responses.
#F.23
F#
open System.IO open System.Net open System.Net.Sockets   let service (client:TcpClient) = use stream = client.GetStream() use out = new StreamWriter(stream, AutoFlush = true) use inp = new StreamReader(stream) while not inp.EndOfStream do match inp.ReadLine() with | line -> printfn "< %s" line out.WriteLine(line) printfn "closed %A" client.Client.RemoteEndPoint client.Close |> ignore   let EchoService = let socket = new TcpListener(IPAddress.Loopback, 12321) do socket.Start() printfn "echo service listening on %A" socket.Server.LocalEndPoint while true do let client = socket.AcceptTcpClient() printfn "connect from %A" client.Client.RemoteEndPoint let job = async { use c = client in try service client with _ -> () } Async.Start job   [<EntryPoint>] let main _ = EchoService 0
http://rosettacode.org/wiki/Elementary_cellular_automaton/Infinite_length
Elementary cellular automaton/Infinite length
The purpose of this task is to create a version of an Elementary cellular automaton whose number of cells is only limited by the memory size of the computer. To be precise, consider the state of the automaton to be made of an infinite number of cells, but with a bounded support. In other words, to describe the state of the automaton, you need a finite number of adjacent cells, along with their individual state, and you then consider that the individual state of each of all other cells is the negation of the closest individual cell among the previously defined finite number of cells. Examples: 1 -> ..., 0, 0, 1, 0, 0, ... 0, 1 -> ..., 1, 1, 0, 1, 0, 0, ... 1, 0, 1 -> ..., 0, 0, 1, 0, 1, 0, 0, ... More complex methods can be imagined, provided it is possible to somehow encode the infinite sections. But for this task we will stick to this simple version.
#zkl
zkl
nLines,flipCell := 25, fcn(c){ (c=="1") and "0" or "1" }; foreach rule in (T(90,30)){ println("\nRule: ", rule); ruleBits:="%08.2B".fmt(rule); // eg 90-->"01011010" neighs2next:=(8).pump(Dictionary(), 'wrap(n){ T("%03.2B".fmt(n), ruleBits.reverse()[n]) }); C:="1"; // C is "1"s and "0"s, I'll auto cast to Int as needed foreach i in (nLines){ println("%2d: %s%s".fmt(i," "*(nLines - i), C.translate("01",".#"))); C=String(flipCell(C[0])*2, C, flipCell(C[-1])*2); C=[1..C.len()-2].pump(String,'wrap(n){ neighs2next[C[n-1,3]] }); } }
http://rosettacode.org/wiki/Empty_string
Empty string
Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. 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
#X86-64_Assembly
X86-64 Assembly
  option casemap:none   printf proto :qword, :VARARG exit proto :dword   .data e_str db 1 dup (0)   .code main proc xor rcx, rcx lea rax, e_str cmp byte ptr [rax+rcx],0 ;; Is e_str[0] equal to 0? je _isempty ;; Yes so goto isEmpty jne _notempty ;; No, got notEmpty jmp _exit ;; Neither condition is met, so exit.   _isempty: invoke printf, CSTR("e_str is empty",10) lea rax, e_str mov byte ptr [rax+0], 's' ;; Copy a char into e_str[0] jmp main ;; Test again..   _notempty: invoke printf, CSTR("e_str is NOT empty",10) ;; Fall though to exit here.. _exit: xor rsi, rsi call exit ret main endp end  
http://rosettacode.org/wiki/Empty_string
Empty string
Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. 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
#XLISP
XLISP
[1] (define my-empty-string "") ;; assign an empty string to a variable   MY-EMPTY-STRING [2] (string-null? my-empty-string)   #T [3] (string-null? "A non-empty string")   ()
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#SimpleCode
SimpleCode