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/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).
#jq
jq
  # jq optimizes the recursive call of _gcd in the following: def gcd(a;b): def _gcd: if .[1] != 0 then [.[1], .[0] % .[1]] | _gcd else .[0] end; [a,b] | _gcd ;   def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;    
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).
#Julia
Julia
using Primes   function ekgsequence(n, limit) ekg::Array{Int,1} = [1, n] while length(ekg) < limit for i in 2:2<<18 if all(j -> j != i, ekg) && gcd(ekg[end], i) > 1 push!(ekg, i) break end end end ekg end   function convergeat(n, m, max = 100) ekgn = ekgsequence(n, max) ekgm = ekgsequence(m, max) for i in 3:max if ekgn[i] == ekgm[i] && sum(ekgn[1:i+1]) == sum(ekgm[1:i+1]) return i end end warn("no converge in $max terms") end   [println(rpad("EKG($i): ", 9), join(ekgsequence(i, 30), " ")) for i in [2, 5, 7, 9, 10]] println("EKGs of 5 & 7 converge at term ", convergeat(5, 7))  
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
#Scheme
Scheme
(define empty-string "") (define (string-null? s) (string=? "" s)) (define (string-not-null? s) (string<? "" s))
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
#Seed7
Seed7
# assign empty string to a variable s := ""   # check that string is empty s = ""   # check that string is not empty s <> ""
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#PL.2FSQL
PL/SQL
BEGIN NULL; END;
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Plain_English
Plain English
To run: Start up. Shut down.
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Plain_TeX
Plain TeX
\bye
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
#Phix
Phix
function emHalf(integer n) return floor(n/2) end function function emDouble(integer n) return n*2 end function function emIsEven(integer n) return (remainder(n,2)=0) end function function emMultiply(integer a, integer b) integer sum = 0 while a!=0 do if not emIsEven(a) then sum += b end if a = emHalf(a) b = emDouble(b) end while return sum end function printf(1,"emMultiply(%d,%d) = %d\n",{17,34,emMultiply(17,34)})
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
#Sisal
Sisal
define main   function main(x : integer returns integer)   for a in 1, x returns value of product a end for   end function
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.
#S-BASIC
S-BASIC
  rem - return true (-1) if even, otherwise false (0) function even(i = integer) = integer var one = integer rem - both operands must be variables one = 1 end = ((i and one) = 0)   rem - exercise the function var i = integer for i = 1 to 10 step 3 print i; " is "; if even(i) then print "even" else print "odd" next   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.
#Scala
Scala
def isEven( v:Int ) : Boolean = v % 2 == 0 def isOdd( v:Int ) : Boolean = v % 2 != 0
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.
#BaCon
BaCon
OPEN "localhost:12321" FOR SERVER AS echo WHILE TRUE fd = ACCEPT(echo) PRINT "Incoming connection from: ", GETPEER$(fd) RECEIVE data$ FROM fd SEND data$ & CR$ & NL$ TO fd CLOSE SERVER fd WEND
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.
#C.2B.2B
C++
  #include <iostream> #include <iomanip> #include <string>   class oo { public: void evolve( int l, int rule ) { std::string cells = "O"; std::cout << " Rule #" << rule << ":\n"; for( int x = 0; x < l; x++ ) { addNoCells( cells ); std::cout << std::setw( 40 + ( static_cast<int>( cells.length() ) >> 1 ) ) << cells << "\n"; step( cells, rule ); } } private: void step( std::string& cells, int rule ) { int bin; std::string newCells; for( size_t i = 0; i < cells.length() - 2; i++ ) { bin = 0; for( size_t n = i, b = 2; n < i + 3; n++, b >>= 1 ) { bin += ( ( cells[n] == 'O' ? 1 : 0 ) << b ); } newCells.append( 1, rule & ( 1 << bin ) ? 'O' : '.' ); } cells = newCells; } void addNoCells( std::string& s ) { char l = s.at( 0 ) == 'O' ? '.' : 'O', r = s.at( s.length() - 1 ) == 'O' ? '.' : 'O'; s = l + s + r; s = l + s + r; } }; int main( int argc, char* argv[] ) { oo o; o.evolve( 35, 90 ); std::cout << "\n"; return 0; }  
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).
#Kotlin
Kotlin
// Version 1.2.60   fun gcd(a: Int, b: Int): Int { var aa = a var bb = b while (aa != bb) { if (aa > bb) aa -= bb else bb -= aa } return aa }   const val LIMIT = 100   fun main(args: Array<String>) { val starts = listOf(2, 5, 7, 9, 10) val ekg = Array(5) { IntArray(LIMIT) }   for ((s, start) in starts.withIndex()) { ekg[s][0] = 1 ekg[s][1] = start for (n in 2 until 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].slice(0 until n).contains(i) && gcd(ekg[s][n - 1], i) > 1) { ekg[s][n] = i break } i++ } } System.out.printf("EKG(%2d): %s\n", start, ekg[s].slice(0 until 30)) }   // now compare EKG5 and EKG7 for convergence for (i in 2 until LIMIT) { if (ekg[1][i] == ekg[2][i] && ekg[1].slice(0 until i).sorted() == ekg[2].slice(0 until i).sorted()) { 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/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
#Self
Self
  "Put an empty string in a slot called 'str'" str: ''.   "Check that string is empty" str isEmpty.   "Check that string is not empty" str isEmpty not.
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
#SenseTalk
SenseTalk
  set emptyString to ""   put emptyString   put emptyString is empty   put emptyString is not empty  
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Pony
Pony
actor Main new create(e: Env) => ""
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Pop11
Pop11
;;; This is a valid Pop11 program that does absolutely nothing.
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#PostScript
PostScript
%!PS
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
#PHP
PHP
<?php function halve($x) { return floor($x/2); }   function double($x) { return $x*2; }   function iseven($x) { return !($x & 0x1); }   function ethiopicmult($plier, $plicand, $tutor) { if ($tutor) echo "ethiopic multiplication of $plier and $plicand\n"; $r = 0; while($plier >= 1) { if ( !iseven($plier) ) $r += $plicand; if ($tutor) echo "$plier, $plicand ", (iseven($plier) ? "struck" : "kept"), "\n"; $plier = halve($plier); $plicand = double($plicand); } return $r; }   echo ethiopicmult(17, 34, true), "\n";   ?>
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
#Slate
Slate
n@(Integer traits) factorial "The standard recursive definition." [ n isNegative ifTrue: [error: 'Negative inputs to factorial are invalid.']. n <= 1 ifTrue: [1] ifFalse: [n * ((n - 1) 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.
#Scheme
Scheme
> (even? 5) #f > (even? 42) #t > (odd? 5) #t > (odd? 42) #f
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.
#Seed7
Seed7
odd(aNumber)
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.
#BBC_BASIC
BBC BASIC
INSTALL @lib$+"SOCKLIB" PROC_initsockets   maxSess% = 8 DIM sock%(maxSess%-1), rcvd$(maxSess%-1), Buffer% 255   ON ERROR PRINT REPORT$ : PROC_exitsockets : END ON CLOSE PROC_exitsockets : QUIT   crlf$ = CHR$13 + CHR$10 port$ = "12321" host$ = FN_gethostname PRINT "Host name is " host$   listen% = FN_tcplisten(host$, port$) PRINT "Listening on port ";port$   REPEAT socket% = FN_check_connection(listen%) IF socket% THEN FOR i% = 0 TO maxSess%-1 IF sock%(i%) = 0 THEN sock%(i%) = socket% rcvd$(i%) = "" PRINT "Connection on socket "; sock%(i%) " opened" EXIT FOR ENDIF NEXT i% listen% = FN_tcplisten(host$, port$) ENDIF   FOR i% = 0 TO maxSess%-1 IF sock%(i%) THEN res% = FN_readsocket(sock%(i%), Buffer%, 256) IF res% >= 0 THEN Buffer%?res% = 0 rcvd$(i%) += $$Buffer% crlf% = INSTR(rcvd$(i%), crlf$) IF crlf% THEN echo$ = LEFT$(rcvd$(i%), crlf%-1) res% = FN_writelinesocket(sock%(i%), echo$) rcvd$(i%) = MID$(rcvd$(i%), crlf%+2) ENDIF ELSE PROC_closesocket(sock%(i%)) PRINT "Connection on socket " ; sock%(i%) " closed" sock%(i%) = 0 ENDIF ENDIF NEXT i%   WAIT 0 UNTIL FALSE 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.
#D
D
import std.stdio, std.array, std.range, std.typecons, std.string, std.conv, std.algorithm; alias R = replicate;   void main() { enum nLines = 25; enum notCell = (in char c) pure => (c == '1') ? "0" : "1";   foreach (immutable rule; [90, 30]) { writeln("\nRule: ", rule); immutable ruleBits = "%08b".format(rule).retro.text; const neighs2next = 8.iota .map!(n => tuple("%03b".format(n), [ruleBits[n]])) .assocArray;   string C = "1"; foreach (immutable i; 0 .. nLines) { writefln("%2d: %s%s", i, " ".R(nLines - i), C.tr("01", ".#")); C = notCell(C[0]).R(2) ~ C ~ notCell(C[$ - 1]).R(2); C = iota(1, C.length - 1) .map!(i => neighs2next[C[i - 1 .. i + 2]]) .join; } } }
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.
#Elixir
Elixir
  defmodule Elementary_cellular_automaton do def infinite(cell, rule, times) do each(cell, rule_pattern(rule), times) end   defp each(_, _, 0), do: :ok defp each(cells, rules, times) do IO.write String.duplicate(" ", times) IO.puts String.replace(cells, "0", ".") |> String.replace("1", "#") c = not_cell(String.first(cells)) <> cells <> not_cell(String.last(cells)) next_cells = Enum.map_join(0..String.length(cells)+1, fn i -> Map.get(rules, String.slice(c, i, 3)) end) each(next_cells, rules, times-1) end   defp not_cell("0"), do: "11" defp not_cell("1"), do: "00"   defp rule_pattern(rule) do list = Integer.to_string(rule, 2) |> String.pad_leading(8, "0") |> String.codepoints |> Enum.reverse Enum.map(0..7, fn i -> Integer.to_string(i, 2) |> String.pad_leading(3, "0") end) |> Enum.zip(list) |> Map.new end end   Enum.each([18, 30], fn rule -> IO.puts "\nRule : #{rule}" Elementary_cellular_automaton.infinite("1", rule, 25) 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).
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
ClearAll[NextInSequence, EKGSequence] NextInSequence[seq_List] := Module[{last, new = 1, holes, max, sel, found, i}, last = Last[seq]; max = Max[seq]; holes = Complement[Range[max], seq]; sel = SelectFirst[holes, Not[CoprimeQ[last, #]] &]; If[MissingQ[sel], i = max; found = False; While[! found, i++; If[Not[CoprimeQ[last, i]], found = True ] ]; Append[seq, i] , Append[seq, sel] ] ] EKGSequence[start_Integer, n_] := Nest[NextInSequence, {1, start}, n - 2]   Table[EKGSequence[s, 10], {s, {2, 5, 7, 9, 10}}] // Grid   s = Reverse[Transpose[{EKGSequence[5, 1000], EKGSequence[7, 1000]}]]; len = LengthWhile[s, Apply[Equal]]; s //= Reverse[Drop[#, len]] &; Length[s] + 1
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).
#Nim
Nim
import algorithm, math, sets, strformat, strutils   #---------------------------------------------------------------------------------------------------   iterator ekg(n, limit: Positive): (int, int) = var values: HashSet[int] doAssert n >= 2 yield (1, 1) yield (2, n) values.incl(n) var i = 3 var prev = n while i <= limit: var val = 2 while true: if val notin values and gcd(val, prev) != 1: values.incl(val) yield (i, val) prev = val break inc val inc i   #---------------------------------------------------------------------------------------------------   for n in [2, 5, 7, 9, 10]: var result: array[1..10, int] for i, val in ekg(n, 10): result[i] = val let title = fmt"EKG({n}):" echo fmt"{title:8} {result.join("", "")}"   var ekg5, ekg7: array[1..100, int] for i, val in ekg(5, 100): ekg5[i] = val for i, val in ekg(7, 100): ekg7[i] = val var convIndex = 0 for i in 2..100: if ekg5[i] == ekg7[i] and sorted(ekg5[1..<i]) == sorted(ekg7[1..<i]): convIndex = i break if convIndex > 0: echo fmt"EKG(5) and EKG(7) converge at index {convIndex}." else: echo "No convergence found in the first {convIndex} 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
#Sidef
Sidef
var s = ""; var s = String.new;
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
#Smalltalk
Smalltalk
"Assign empty string to a variable" str := ''.   "Check that string is empty" str isEmpty.   "Check that string is not empty" str isEmpty not. "alternatives:" str notEmpty str size = 0 str = ''
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#PowerShell
PowerShell
  &{}  
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Processing
Processing
 
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#ProDOS
ProDOS
IGNORELINE
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
#Picat
Picat
ethiopian(Multiplier, Multiplicand) = ethiopian(Multiplier, Multiplicand,false).   ethiopian(Multiplier, Multiplicand,Tutor) = Result => if Tutor then printf("\n%d * %d:\n",Multiplier, Multiplicand) end, Result1 = 0, while (Multiplier >= 1) OldResult = Result1, if not even(Multiplier) then Result1 := Result1 + Multiplicand end, if Tutor then printf("%6d  % 8s\n",Multiplier,cond(OldResult=Result1,"--",Multiplicand.to_string())) end, Multiplier := halve(Multiplier), Multiplicand := double(Multiplicand) end, if Tutor then println(" ======="), printf("  %8s\n",Result1.to_string()), nl end, Result = Result1.
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
#Smalltalk
Smalltalk
Number extend [ my_factorial [ (self < 2) ifTrue: [ ^1 ] ifFalse: [ ^ (2 to: self) fold: [ :a :b | a * b ] ] ] ].   7 factorial printNl. 7 my_factorial printNl.
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.
#SenseTalk
SenseTalk
  set num to random of 100 -- start with a random number from 1 to 100   // use the 'is a' operator to test the value if num is an odd number then put num & " is odd"   // see if num is divisible by 2 if num is divisible by 2 then put num & " is even (is divisible by 2)"   // check to see if the remainder is 0 when dividing by 2 if num rem 2 is 0 then put num & " is even (zero remainder)"  
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.
#SequenceL
SequenceL
even(x) := x mod 2 = 0; odd(x) := x mod 2 = 1;
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.
#C
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <unistd.h> #include <sys/wait.h> #include <signal.h>   #define MAX_ENQUEUED 20 #define BUF_LEN 256 #define PORT_STR "12321"   /* ------------------------------------------------------------ */ /* How to clean up after dead child processes */ /* ------------------------------------------------------------ */   void wait_for_zombie(int s) { while(waitpid(-1, NULL, WNOHANG) > 0) ; }   /* ------------------------------------------------------------ */ /* Core of implementation of a child process */ /* ------------------------------------------------------------ */   void echo_lines(int csock) { char buf[BUF_LEN]; int r;   while( (r = read(csock, buf, BUF_LEN)) > 0 ) { (void)write(csock, buf, r); } exit(EXIT_SUCCESS); }   /* ------------------------------------------------------------ */ /* Core of implementation of the parent process */ /* ------------------------------------------------------------ */   void take_connections_forever(int ssock) { for(;;) { struct sockaddr addr; socklen_t addr_size = sizeof(addr); int csock;   /* Block until we take one connection to the server socket */ csock = accept(ssock, &addr, &addr_size);   /* If it was a successful connection, spawn a worker process to service it */ if ( csock == -1 ) { perror("accept"); } else if ( fork() == 0 ) { close(ssock); echo_lines(csock); } else { close(csock); } } }   /* ------------------------------------------------------------ */ /* The server process's one-off setup code */ /* ------------------------------------------------------------ */   int main() { struct addrinfo hints, *res; struct sigaction sa; int sock;   /* Look up the address to bind to */ memset(&hints, 0, sizeof(struct addrinfo)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; if ( getaddrinfo(NULL, PORT_STR, &hints, &res) != 0 ) { perror("getaddrinfo"); exit(EXIT_FAILURE); }   /* Make a socket */ if ( (sock = socket(res->ai_family, res->ai_socktype, res->ai_protocol)) == -1 ) { perror("socket"); exit(EXIT_FAILURE); }   /* Arrange to clean up child processes (the workers) */ sa.sa_handler = wait_for_zombie; sigemptyset(&sa.sa_mask); sa.sa_flags = SA_RESTART; if ( sigaction(SIGCHLD, &sa, NULL) == -1 ) { perror("sigaction"); exit(EXIT_FAILURE); }   /* Associate the socket with its address */ if ( bind(sock, res->ai_addr, res->ai_addrlen) != 0 ) { perror("bind"); exit(EXIT_FAILURE); }   freeaddrinfo(res);   /* State that we've opened a server socket and are listening for connections */ if ( listen(sock, MAX_ENQUEUED) != 0 ) { perror("listen"); exit(EXIT_FAILURE); }   /* Serve the listening socket until killed */ take_connections_forever(sock); return EXIT_SUCCESS; }
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.
#Go
Go
package main   import ( "fmt" "strings" )   func btoi(b bool) int { if b { return 1 } return 0 }   func evolve(l, rule int) { fmt.Printf(" Rule #%d:\n", rule) cells := "O" for x := 0; x < l; x++ { cells = addNoCells(cells) width := 40 + (len(cells) >> 1) fmt.Printf("%*s\n", width, cells) cells = step(cells, rule) } }   func step(cells string, rule int) string { newCells := new(strings.Builder) for i := 0; i < len(cells)-2; i++ { bin := 0 b := uint(2) for n := i; n < i+3; n++ { bin += btoi(cells[n] == 'O') << b b >>= 1 } a := '.' if rule&(1<<uint(bin)) != 0 { a = 'O' } newCells.WriteRune(a) } return newCells.String() }   func addNoCells(cells string) string { l, r := "O", "O" if cells[0] == 'O' { l = "." } if cells[len(cells)-1] == 'O' { r = "." } cells = l + cells + r cells = l + cells + r return cells }   func main() { for _, r := range []int{90, 30} { evolve(25, r) fmt.Println() } }
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).
#Perl
Perl
use List::Util qw(none sum);   sub gcd { my ($u,$v) = @_; $v ? gcd($v, $u%$v) : abs($u) } sub shares_divisors_with { gcd( $_[0], $_[1]) > 1 }   sub EKG { my($n,$limit) = @_; my @ekg = (1, $n); while (@ekg < $limit) { for my $i (2..1e18) { next unless none { $_ == $i } @ekg and shares_divisors_with($ekg[-1], $i); push(@ekg, $i) and last; } } @ekg; }   sub converge_at { my($n1,$n2) = @_; my $max = 100; my @ekg1 = EKG($n1,$max); my @ekg2 = EKG($n2,$max); do { return $_+1 if $ekg1[$_] == $ekg2[$_] && sum(@ekg1[0..$_]) == sum(@ekg2[0..$_])} for 2..$max; return "(no convergence in $max terms)"; }   print "EKG($_): " . join(' ', EKG($_,10)) . "\n" for 2, 5, 7, 9, 10; print "EKGs of 5 & 7 converge at term " . converge_at(5, 7) . "\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
#SNOBOL4
SNOBOL4
* ASSIGN THE NULL STRING TO X X = * CHECK THAT X IS INDEED NULL EQ(X, NULL)  :S(YES) OUTPUT = 'NOT NULL' :(END) YES OUTPUT = 'NULL' 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
#Standard_ML
Standard ML
(* Assign empty string to a variable *) val s = "" (* Check that a string is empty*) s = "" (* Check that a string is nonempty *) s <> ""
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Programming_Language
Programming Language
 
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#PSQL
PSQL
EXECUTE BLOCK AS BEGIN END
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#PureBasic
PureBasic
 
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.
#11l
11l
T Node Int length Int suffix [Char = Int] edges   F (length, suffix = 0) .length = length .suffix = suffix   -V oddRoot = 1   F eertree(s) V tree = [Node(0, :oddRoot), Node(-1, :oddRoot)] V suffix = :oddRoot L(c) s V i = L.index V n = suffix Int k L k = tree[n].length V b = i - k - 1 I b >= 0 & s[b] == c L.break n = tree[n].suffix   V? edge = tree[n].edges.find(c) I edge != N suffix = edge L.continue   suffix = tree.len tree [+]= Node(k + 2) tree[n].edges[c] = suffix I tree[suffix].length == 1 tree[suffix].suffix = 0 L.continue   L n = tree[n].suffix V b = i - tree[n].length - 1 I b >= 0 & s[b] == c L.break   tree[suffix].suffix = tree[n].edges[c]   R tree   F subPalindromes(tree) [String] s   F children(Int n, String =p) -> N L(c, n) @tree[n].edges p = c‘’p‘’c @s [+]= p @children(n, p)   children(0, ‘’) L(c, n) tree[1].edges s [+]= c children(n, c)   R s   V tree = eertree(‘eertree’) print(subPalindromes(tree))
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
#PicoLisp
PicoLisp
(de halve (N) (/ N 2) )   (de double (N) (* N 2) )   (de even? (N) (not (bit? 1 N)) )   (de ethiopian (X Y) (let R 0 (while (>= X 1) (or (even? X) (inc 'R Y)) (setq X (halve X) Y (double Y) ) ) R ) )
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)
#11l
11l
V SIZE = 32 V LINES = SIZE I/ 2 V RULE = 90   F ruleTest(x) R I :RULE [&] (1 << (7 [&] x)) != 0 {1} E 0   F bitVal(s, bit) R I (s >> bit) [&] 1 != 0 {1} E 0   F evolve(&s) V t = 0 t [|]= ruleTest((bitVal(s, 0) << 2) [|] (bitVal(s, :SIZE - 1) << 1) [|] bitVal(s, :SIZE - 2)) << (:SIZE - 1) t [|]= ruleTest((bitVal(s, 1) << 2) [|] (bitVal(s, 0) << 1) [|] bitVal(s, :SIZE - 1)) L(i) 1 .< :SIZE - 1 t [|]= ruleTest((bitVal(s, i + 1) << 2) [|] (bitVal(s, i) << 1) [|] bitVal(s, i - 1)) << i s = t   F show(state) L(i) (:SIZE - 1 .. 0).step(-1) print(‘ *’[bitVal(state, i)], end' ‘’) print()   V state = 1 << LINES print(‘Rule ’RULE) L 1..LINES show(state) evolve(&state)
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
#SNOBOL4
SNOBOL4
define('rfact(n)') :(rfact_end) rfact rfact = le(n,0) 1 :s(return) rfact = n * rfact(n - 1) :(return) rfact_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.
#SETL
SETL
xs := {1..10}; evens := {x in xs | even( x )}; odds := {x in xs | odd( x )}; print( evens ); print( odds );
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.
#Shen
Shen
(define even? 0 -> true X -> (odd? (- X 1)))   (define odd? 0 -> false X -> (even? (- X 1)))
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.
#C.23
C#
using System.Net.Sockets; using System.Threading;   namespace ConsoleApplication1 { class Program { static TcpListener listen; static Thread serverthread;   static void Main(string[] args) { listen = new TcpListener(System.Net.IPAddress.Parse("127.0.0.1"), 12321); serverthread = new Thread(new ThreadStart(DoListen)); serverthread.Start(); }   private static void DoListen() { // Listen listen.Start(); Console.WriteLine("Server: Started server");   while (true) { Console.WriteLine("Server: Waiting..."); TcpClient client = listen.AcceptTcpClient(); Console.WriteLine("Server: Waited");   // New thread with client Thread clientThread = new Thread(new ParameterizedThreadStart(DoClient)); clientThread.Start(client); } }   private static void DoClient(object client) { // Read data TcpClient tClient = (TcpClient)client;   Console.WriteLine("Client (Thread: {0}): Connected!", Thread.CurrentThread.ManagedThreadId); do { if (!tClient.Connected) { tClient.Close(); Thread.CurrentThread.Abort(); // Kill thread. }   if (tClient.Available > 0) { // Resend byte pByte = (byte)tClient.GetStream().ReadByte(); Console.WriteLine("Client (Thread: {0}): Data {1}", Thread.CurrentThread.ManagedThreadId, pByte); tClient.GetStream().WriteByte(pByte); }   // Pause Thread.Sleep(100); } while (true); } } }
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.
#Haskell
Haskell
{-# LANGUAGE DeriveFunctor #-}   import Control.Comonad import Data.InfList (InfList (..), (+++)) import qualified Data.InfList as Inf   data Cells a = Cells (InfList a) a (InfList a) deriving Functor   view n (Cells l x r) = reverse (Inf.take n l) ++ [x] ++ (Inf.take n r)   fromList [] = fromList [0] fromList (x:xs) = let zeros = Inf.repeat 0 in Cells zeros x (xs +++ zeros)
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.
#J
J
ext9=: (9#1-{.!.1),],9#1-{:!.1 trim=: |.@(}.~ ] i. 1-{.)^:2 next=: trim@(((8$2) #: [) {~ 2 #. 1 - [: |: |.~"1 0&_1 0 1@]) ext9
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.
#jq
jq
  def lpad($len; $fill): tostring | ($len - length) as $l | ($fill * $l)[:$l] + .;   def lpad($len): lpad($len; " ");   # Like *ix `tr` but it is as though $to is padded with blanks def tr($from;$to): explode as $s | ($from | explode) as $f | ($to | explode) as $t | reduce range(0;length) as $i ([]; ($f | index($s[$i])) as $ix | if $ix then . + [$t[$ix] // " "] else . + [$s[$i]] end ) | implode;   # Input: a non-negative integer # Output: the corresponding stream of bits (0s and 1s), # least significant digit first, with a final 0 def stream: recurse(if . > 0 then ./2|floor else empty end) | . % 2 ;   # input: an array, e.g. as produced by [7|stream] # output: the corresponding binary string def to_b: reverse | map(tostring) | join("") | sub("^0";"");
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).
#Phix
Phix
with javascript_semantics constant LIMIT = 100 constant starts = {2, 5, 7, 9, 10} sequence ekg = {} string fmt = "EKG(%2d): ["&join(repeat("%d",min(LIMIT,30))," ")&"]\n" for s=1 to length(starts) do ekg = append(ekg,{1,starts[s]}&repeat(0,LIMIT-2)) for n=3 to LIMIT do -- a potential sequence member cannot already have been used -- and must have a factor in common with previous member integer i = 2 while find(i,ekg[s]) or gcd(ekg[s][n-1],i)<=1 do i += 1 end while ekg[s][n] = i end for printf(1,fmt,starts[s]&ekg[s][1..min(LIMIT,30)]) end for -- now compare EKG5 and EKG7 for convergence constant EKG5 = find(5,starts), EKG7 = find(7,starts) string msg = sprintf("do not converge within %d terms", LIMIT) for i=3 to LIMIT do if ekg[EKG5][i]=ekg[EKG7][i] and sort(ekg[EKG5][1..i-1])=sort(ekg[EKG7][1..i-1]) then msg = sprintf("converge at term %d", i) exit end if end for printf(1,"\nEKG5(5) and EKG(7) %s\n", msg)
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
#Stata
Stata
scalar s=""   display s==""   * Alternatively, check the length display length(s)==0
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
#Swift
Swift
var s = "" if s.isEmpty { // alternately, s == "" println("s is empty") } else { println("s is not empty") }
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Python
Python
1 QUIT
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#QUACKASM
QUACKASM
1 QUIT
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Quackery
Quackery
 
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.
#C.23
C#
using System; using System.Collections.Generic;   namespace Eertree { class Node { public Node(int length) { this.Length = length; // empty or this.Edges = new Dictionary<char, int>(); }   public Node(int length, Dictionary<char, int> edges, int suffix) { this.Length = length; this.Edges = edges; this.Suffix = suffix; }   public int Length { get; set; } public Dictionary<char, int> Edges { get; set; } public int Suffix { get; set; } }   class Program { const int EVEN_ROOT = 0; const int ODD_ROOT = 1;   static List<Node> Eertree(string s) { List<Node> tree = new List<Node> { //new Node(0, null, ODD_ROOT), or new Node(0, new Dictionary<char, int>(), ODD_ROOT), //new Node(-1, null, ODD_ROOT) or new Node(-1, new Dictionary<char, int>(), ODD_ROOT) }; int suffix = ODD_ROOT; int n, k; for (int i = 0; i < s.Length; i++) { char c = s[i]; for (n = suffix; ; n = tree[n].Suffix) { k = tree[n].Length; int b = i - k - 1; if (b >= 0 && s[b] == c) { break; } } if (tree[n].Edges.ContainsKey(c)) { suffix = tree[n].Edges[c]; continue; } suffix = tree.Count; tree.Add(new Node(k + 2)); tree[n].Edges[c] = suffix; if (tree[suffix].Length == 1) { tree[suffix].Suffix = 0; continue; } while (true) { n = tree[n].Suffix; int b = i - tree[n].Length - 1; if (b >= 0 && s[b] == c) { break; } } tree[suffix].Suffix = tree[n].Edges[c]; } return tree; }   static List<string> SubPalindromes(List<Node> tree) { List<string> s = new List<string>(); SubPalindromes_children(0, "", tree, s); foreach (var c in tree[1].Edges.Keys) { int m = tree[1].Edges[c]; string ct = c.ToString(); s.Add(ct); SubPalindromes_children(m, ct, tree, s); } return s; }   static void SubPalindromes_children(int n, string p, List<Node> tree, List<string> s) { foreach (var c in tree[n].Edges.Keys) { int m = tree[n].Edges[c]; string p1 = c + p + c; s.Add(p1); SubPalindromes_children(m, p1, tree, s); } }   static void Main(string[] args) { List<Node> tree = Eertree("eertree"); List<string> result = SubPalindromes(tree); string listStr = string.Join(", ", result); Console.WriteLine("[{0}]", listStr); } } }
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
#Pike
Pike
int ethopian_multiply(int l, int r) { int halve(int n) { return n/2; }; int double(int n) { return n*2; }; int(0..1) evenp(int n) { return !(n%2); };   int product = 0; do { write("%5d %5d\n", l, r); if (!evenp(l)) product += r; l = halve(l); r = double(r); } while(l); return 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)
#Action.21
Action!
DEFINE ROW_LEN="320" DEFINE MAX_COL="319" DEFINE MAX_ROW="191"   PROC GenerateMask(BYTE rule BYTE ARRAY mask) BYTE i   FOR i=0 TO 7 DO mask(i)=rule&1 rule==RSH 1 OD RETURN   PROC InitRow(BYTE ARRAY row) INT c   FOR c=0 TO MAX_COL DO row(c)=0 OD row(ROW_LEN RSH 1)=1 RETURN   PROC DrawRow(BYTE ARRAY row BYTE y) INT c   FOR c=0 TO MAX_COL DO Color=row(c) Plot(c,y) OD RETURN   PROC CalcNextRow(BYTE ARRAY currRow,nextRow,mask) INT c BYTE v   v=currRow(MAX_COL) LSH 2 v==%currRow(0) LSH 1 v==%currRow(1) nextRow(0)=mask(v) FOR c=1 TO MAX_COL-1 DO v==&3 v==LSH 1 v==%currRow(c+1) nextRow(c)=mask(v) OD v==&3 v==LSH 1 v==%currRow(0) nextRow(MAX_COL)=mask(v) RETURN   PROC DrawRule(BYTE rule) BYTE ARRAY row1(ROW_LEN),row2(ROW_LEN),mask(8) BYTE ARRAY currRow,nextRow,tmp BYTE y   GenerateMask(rule,mask) currRow=row1 nextRow=row2 InitRow(currRow) y=0 WHILE y<=MAX_ROW DO DrawRow(currRow,y) CalcNextRow(currRow,nextRow,mask) tmp=currRow currRow=nextRow nextRow=tmp y==+1 OD RETURN   PROC Main() BYTE CH=$02FC,COLOR1=$02C5,COLOR2=$02C6   Graphics(8+16) Color=1 COLOR1=$0C COLOR2=$02   DrawRule(30)   DO UNTIL CH#$FF OD CH=$FF RETURN
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)
#Ada
Ada
with Ada.Text_IO; procedure Elementary_Cellular_Automaton is   type t_Rule is new Integer range 0..2**8-1; type t_State is array (Integer range <>) of Boolean;   Cell_Image : constant array (Boolean) of Character := ('.', '#');   function Image (State : in t_State) return String is (Cell_Image(State(State'First)) & (if State'Length <= 1 then "" else Image(State(State'First+1..State'Last))));   -- More convenient representation of the rule type t_RuleA is array (Boolean, Boolean, Boolean) of Boolean;   function Translate (Rule : in t_Rule) return t_RuleA is -- Better not use Pack attribute and Unchecked_Conversion -- because it would not be endianness independent... Remain : t_Rule := Rule; begin return Answer : t_RuleA do for K in Boolean loop for J in Boolean loop for I in Boolean loop Answer(I,J,K) := (Remain mod 2 = 1); Remain := Remain / 2; end loop; end loop; end loop; end return; end Translate;   procedure Show_Automaton (Rule  : in t_Rule; Initial  : in t_State; Generations : in Positive) is RuleA : constant t_RuleA  := Translate(Rule); Width : constant Positive := Initial'Length; -- More convenient indices for neighbor wraparound with "mod" subtype t_State0 is t_State (0..Width-1); State  : t_State0 := Initial; New_State : t_State0; begin Ada.Text_IO.Put_Line ("Rule" & t_Rule'Image(Rule) & " :"); for Generation in 1..Generations loop Ada.Text_IO.Put_Line (Image(State)); for Cell in State'Range loop New_State(Cell) := RuleA(State((Cell-1) mod Width), State(Cell), State((Cell+1) mod Width)); end loop; State := New_State; end loop; end Show_Automaton;   begin Show_Automaton (Rule => 90, Initial => (-10..-1 => False, 0 => True, 1..10 => False), Generations => 15); Show_Automaton (Rule => 30, Initial => (-15..-1 => False, 0 => True, 1..15 => False), Generations => 20); Show_Automaton (Rule => 122, Initial => (-12..-1 => False, 0 => True, 1..12 => False), Generations => 25); end Elementary_Cellular_Automaton;  
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
#Spin
Spin
con _clkmode = xtal1 + pll16x _clkfreq = 80_000_000   obj ser : "FullDuplexSerial.spin"   pub main | i ser.start(31, 30, 0, 115200)   repeat i from 0 to 10 ser.dec(fac(i)) ser.tx(32)   waitcnt(_clkfreq + cnt) ser.stop cogstop(0)   pub fac(n) : f f := 1 repeat while n > 0 f *= n 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.
#Sidef
Sidef
var n = 42; say n.is_odd; # false say n.is_even; # true
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.
#Smalltalk
Smalltalk
5 even 5 odd
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.
#Clojure
Clojure
(use '[clojure.contrib.server-socket :only (create-server)]) (use '[clojure.contrib.duck-streams :only (read-lines write-lines)])   (defn echo [input output] (write-lines (java.io.PrintWriter. output true) (read-lines input)))   (create-server 12321 echo)
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.
#Julia
Julia
function ecainfinite(cells, rule, n) notcell(cell) = (cell == '1') ? '0' : '1' rulebits = reverse(string(rule, base = 2, pad = 8)) neighbors2next = Dict(string(n - 1, base=2, pad=3) => rulebits[n] for n in 1:8) ret = String[] for i in 1:n push!(ret, cells) cells = notcell(cells[1])^2 * cells * notcell(cells[end])^2 # Extend/pad ends cells = join([neighbors2next[cells[i:i+2]] for i in 1:length(cells)-2], "") end ret end   function testinfcells(lines::Integer) for rule in [90, 30] println("\nRule: $rule ($(string(rule, base = 2, pad = 8)))") s = ecainfinite("1", rule, lines) for i in 1:lines println("$i: ", " "^(lines - i), replace(replace(s[i], "0" => "."), "1" => "#")) end end end   testinfcells(25)  
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.
#Kotlin
Kotlin
// version 1.1.51   fun evolve(l: Int, rule: Int) { println(" Rule #$rule:") var cells = StringBuilder("*") for (x in 0 until l) { addNoCells(cells) val width = 40 + (cells.length shr 1) println(cells.padStart(width)) cells = step(cells, rule) } }   fun step(cells: StringBuilder, rule: Int): StringBuilder { val newCells = StringBuilder() for (i in 0 until cells.length - 2) { var bin = 0 var b = 2 for (n in i until i + 3) { bin += (if (cells[n] == '*') 1 else 0) shl b b = b shr 1 } val a = if ((rule and (1 shl bin)) != 0) '*' else '.' newCells.append(a) } return newCells }   fun addNoCells(s: StringBuilder) { val l = if (s[0] == '*') '.' else '*' val r = if (s[s.length - 1] == '*') '.' else '*' repeat(2) { s.insert(0, l) s.append(r) } }   fun main(args: Array<String>) { evolve(35, 90) println() }
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).
#Python
Python
from itertools import count, islice, takewhile from math import gcd   def EKG_gen(start=2): """\ Generate the next term of the EKG together with the minimum cache of numbers left in its production; (the "state" of the generator). Using math.gcd """ c = count(start + 1) last, so_far = start, list(range(2, start)) yield 1, [] yield last, [] while True: for index, sf in enumerate(so_far): if gcd(last, sf) > 1: last = so_far.pop(index) yield last, so_far[::] break else: so_far.append(next(c))   def find_convergence(ekgs=(5,7)): "Returns the convergence point or zero if not found within the limit" ekg = [EKG_gen(n) for n in ekgs] for e in ekg: next(e) # skip initial 1 in each sequence return 2 + len(list(takewhile(lambda state: not all(state[0] == s for s in state[1:]), zip(*ekg))))   if __name__ == '__main__': for start in 2, 5, 7, 9, 10: print(f"EKG({start}):", str([n[0] for n in islice(EKG_gen(start), 10)])[1: -1]) print(f"\nEKG(5) and EKG(7) converge at term {find_convergence(ekgs=(5,7))}!")
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
#Tcl
Tcl
set s "" if {$s eq ""} {puts "s contains an empty string"} if {$s ne ""} {puts "s contains a non-empty string"}
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
#TorqueScript
TorqueScript
$empty = "";
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Quite_BASIC
Quite BASIC
 
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#R
R
  #lang racket  
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Racket
Racket
  #lang racket  
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.
#C.2B.2B
C++
#include <iostream> #include <functional> #include <map> #include <vector>   struct Node { int length; std::map<char, int> edges; int suffix;   Node(int l) : length(l), suffix(0) { /* empty */ }   Node(int l, const std::map<char, int>& m, int s) : length(l), edges(m), suffix(s) { /* empty */ } };   constexpr int evenRoot = 0; constexpr int oddRoot = 1;   std::vector<Node> eertree(const std::string& s) { std::vector<Node> tree = { Node(0, {}, oddRoot), Node(-1, {}, oddRoot) }; int suffix = oddRoot; int n, k;   for (size_t i = 0; i < s.length(); ++i) { char c = s[i]; for (n = suffix; ; n = tree[n].suffix) { k = tree[n].length; int b = i - k - 1; if (b >= 0 && s[b] == c) { break; } }   auto it = tree[n].edges.find(c); auto end = tree[n].edges.end(); if (it != end) { suffix = it->second; continue; } suffix = tree.size(); tree.push_back(Node(k + 2)); tree[n].edges[c] = suffix; if (tree[suffix].length == 1) { tree[suffix].suffix = 0; continue; } while (true) { n = tree[n].suffix; int b = i - tree[n].length - 1; if (b >= 0 && s[b] == c) { break; } } tree[suffix].suffix = tree[n].edges[c]; }   return tree; }   std::vector<std::string> subPalindromes(const std::vector<Node>& tree) { std::vector<std::string> s;   std::function<void(int, std::string)> children; children = [&children, &tree, &s](int n, std::string p) { auto it = tree[n].edges.cbegin(); auto end = tree[n].edges.cend(); for (; it != end; it = std::next(it)) { auto c = it->first; auto m = it->second;   std::string pl = c + p + c; s.push_back(pl); children(m, pl); } }; children(0, "");   auto it = tree[1].edges.cbegin(); auto end = tree[1].edges.cend(); for (; it != end; it = std::next(it)) { auto c = it->first; auto n = it->second;   std::string ct(1, c); s.push_back(ct);   children(n, ct); }   return s; }   int main() { using namespace std;   auto tree = eertree("eertree"); auto pal = subPalindromes(tree);   auto it = pal.cbegin(); auto end = pal.cend();   cout << "["; if (it != end) { cout << it->c_str(); it++; } while (it != end) { cout << ", " << it->c_str(); it++; } cout << "]" << endl;   return 0; }
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
#PL.2FI
PL/I
  declare (L(30), R(30)) fixed binary; declare (i, s) fixed binary;   L, R = 0; put skip list ('Hello, please type two values and I will print their product:'); get list (L(1), R(1)); put edit ('The product of ', trim(L(1)), ' and ', trim(R(1)), ' is ') (a); do i = 1 by 1 while (L(i) ^= 0); L(i+1) = halve(L(i)); R(i+1) = double(R(i)); end; s = 0; do i = 1 by 1 while (L(i) > 0); if odd(L(i)) then s = s + R(i); end; put edit (trim(s)) (a);   halve: procedure (k) returns (fixed binary); declare k fixed binary; return (k/2); end halve; double: procedure (k) returns (fixed binary); declare k fixed binary; return (2*k); end; odd: procedure (k) returns (bit (1)); return (iand(k, 1) ^= 0); end odd;
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)
#ALGOL_68
ALGOL 68
BEGIN # elementary cellular automaton # COMMENT returns the next state from state using rule; s must be at least 2 characters long and consist of # and - only COMMENT PROC next state = ( STRING state, INT rule )STRING: BEGIN COMMENT returns 1 or 0 depending on whether c = # or not COMMENT OP TOINT = ( CHAR c )INT: IF c = "#" THEN 1 ELSE 0 FI; # construct the state with additional extra elements to allow wrap-around # STRING s = state[ UPB state ] + state + state[ LWB state : LWB state + 1 ]; COMMENT convert rule to a string of # or - depending on whether the bits of r are on or off COMMENT STRING r := ""; INT v := rule; FOR i TO 8 DO r +:= IF ODD v THEN "#" ELSE "-" FI; v OVERAB 2 OD; STRING new state := ""; FOR i FROM LWB s TO UPB s - 3 DO CHAR c1 = s[ i ]; CHAR c2 = s[ i + 1 ]; CHAR c3 = s[ i + 2 ]; INT pos := ( ( ( TOINT c1 * 2 ) + TOINT c2 ) * 2 ) + TOINT c3; new state +:= r[ pos + 1 ] OD; new state END # next state # ; # evolve state until the next state = the current state or 10 iterations have occured # PROC test = ( STRING state, INT rule )VOID: BEGIN print( ( "Rule ", whole( rule, 0 ), newline ) ); STRING curr := state; print( ( " 0: ", curr, newline ) ); FOR i TO 10 WHILE STRING next = next state( curr, rule ); next /= curr DO print( ( whole( i, -2 ), ": ", next, newline ) ); curr := next OD END # test # ; # tests # test( "---------#---------", 30 ); test( "---------#---------", 60 ); test( "---------#---------", 90 ) END
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
#SPL
SPL
fact(n)=  ? n!>1, <=1 <= n*fact(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.
#SNOBOL4
SNOBOL4
DEFINE('even(n)')  :(even_end) even even = (EQ(REMDR(n, 2), 0) 'even', 'odd') :(RETURN) even_end   OUTPUT = "-2 is " even(-2) OUTPUT = "-1 is " even(-1) OUTPUT = "0 is " even(0) OUTPUT = "1 is " even(1) OUTPUT = "2 is " even(2) 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.
#SNUSP
SNUSP
  $====!/?\==even# - - #odd==\?/  
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.
#CoffeeScript
CoffeeScript
  net = require("net") server = net.createServer (conn) -> console.log "Connection from #{conn.remoteAddress} on port #{conn.remotePort}" conn.setEncoding "utf8" buffer = "" conn.on "data", (data) -> i = 0   while i <= data.length char = data.charAt(i) buffer += char if char is "\n" conn.write buffer buffer = "" i++   server.listen 12321, "localhost"  
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.
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
CellularAutomaton[18, {{1}, 0}, 15] // ArrayPlot CellularAutomaton[30, {{1}, 0}, 15] // ArrayPlot
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.
#Nim
Nim
import strutils     func step(cells: string; rule: int): string = for i in 0..(cells.len - 3): var bin = 0 var b = 2 for n in i..(i + 2): inc bin, ord(cells[n] == '*') shl b b = b shr 1 let a = if (rule and 1 shl bin) != 0: '*' else: '.' result.add(a)     func addNoCells(cells: var string) = let left = if cells[0] == '*': "." else: "*" let right = if cells[^1] == '*': "." else: "*" cells.insert(left) cells.add(right) cells.insert(left) cells.add(right)     proc evolve(limit, rule: int) = echo "Rule #", rule var cells = "*" for _ in 0..<limit: cells.addNoCells() let width = 40 + cells.len shr 1 echo cells.align(width) cells = cells.step(rule)     evolve(35, 90)
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.
#Perl
Perl
sub evolve { my ($rule, $pattern) = @_; my $offset = 0;   while (1) { my ($l, $r, $st); $pattern =~ s/^((.)\g2*)/$2$2/ and $l = $2, $offset -= length($2); $pattern =~ s/(.)\g1*$/$1$1/ and $r = $1;   $st = $pattern;   $pattern =~ tr/01/.#/; printf "%5d| %s%s\n", $offset, ' ' x (40 + $offset), $pattern;   $pattern = join '', map(1 & ($rule>>oct "0b$_"), $l x 3, map(substr($st, $_, 3), 0 .. length($st)-3), $r x 3); } }   evolve(90, "010");
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).
#Raku
Raku
sub infix:<shares-divisors-with> { ($^a gcd $^b) > 1 }   sub next-EKG ( *@s ) { return first { @s ∌ $_ and @s.tail shares-divisors-with $_ }, 2..*; }   sub EKG ( Int $start ) { 1, $start, &next-EKG … * }   sub converge-at ( @ints ) { my @ekgs = @ints.map: &EKG;   return (2 .. *).first: -> $i { [==] @ekgs.map( *.[$i] ) and [===] @ekgs.map( *.head($i).Set ) } }   say "EKG($_): ", .&EKG.head(10) for 2, 5, 7, 9, 10;   for [5, 7], [2, 5, 7, 9, 10] -> @ints { say "EKGs of (@ints[]) converge at term {$_+1}" with converge-at(@ints); }
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
#TUSCRIPT
TUSCRIPT
  $$ MODE TUSCRIPT s="" IF (s=="") PRINT "s is an empty string" IF (s!="") PRINT "s is a non-empty string"  
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
#TXR
TXR
@(bind a "")
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Raku
Raku
 
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Raven
Raven
rebol []
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#REBOL
REBOL
rebol []
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.
#Ada
Ada
with Ada.Text_IO, Matrix_Scalar;   procedure Scalar_Ops is   subtype T is Integer range 1 .. 3;   package M is new Matrix_Scalar(T, T, Integer);   -- the functions to solve the task function "+" is new M.Func("+"); function "-" is new M.Func("-"); function "*" is new M.Func("*"); function "/" is new M.Func("/"); function "**" is new M.Func("**"); function "mod" is new M.Func("mod");   -- for output purposes, we need a Matrix->String conversion function Image is new M.Image(Integer'Image);   A: M.Matrix := ((1,2,3),(4,5,6),(7,8,9)); -- something to begin with   begin Ada.Text_IO.Put_Line(" Initial M=" & Image(A)); Ada.Text_IO.Put_Line(" M+2=" & Image(A+2)); Ada.Text_IO.Put_Line(" M-2=" & Image(A-2)); Ada.Text_IO.Put_Line(" M*2=" & Image(A*2)); Ada.Text_IO.Put_Line(" M/2=" & Image(A/2)); Ada.Text_IO.Put_Line(" square(M)=" & Image(A ** 2)); Ada.Text_IO.Put_Line(" M mod 2=" & Image(A mod 2)); Ada.Text_IO.Put_Line("(M*2) mod 3=" & Image((A*2) mod 3)); end Scalar_Ops;
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.
#D
D
import std.array; import std.stdio;   void main() { auto tree = eertree("eertree"); writeln(subPalindromes(tree)); }   struct Node { int length; int[char] edges; int suffix; }   const evenRoot = 0; const oddRoot = 1;   Node[] eertree(string s) { Node[] tree = [ Node(0, null, oddRoot), Node(-1, null, oddRoot), ]; int suffix = oddRoot; int n, k; foreach (i, c; s) { for (n=suffix; ; n=tree[n].suffix) { k = tree[n].length; int b = i-k-1; if (b>=0 && s[b]==c) { break; } } if (c in tree[n].edges) { suffix = tree[n].edges[c]; continue; } suffix = tree.length; tree ~= Node(k+2); tree[n].edges[c] = suffix; if (tree[suffix].length == 1) { tree[suffix].suffix = 0; continue; } while (true) { n = tree[n].suffix; int b = i-tree[n].length-1; if (b>=0 && s[b]==c) { break; } } tree[suffix].suffix = tree[n].edges[c]; } return tree; }   auto subPalindromes(Node[] tree) { auto s = appender!(string[]); void children(int n, string p) { foreach (c, n; tree[n].edges) { p = c ~ p ~ c; s ~= p; children(n, p); } } children(0, ""); foreach (c, n; tree[1].edges) { string ct = [c].idup; s ~= ct; children(n, ct); } return s.data; }
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
#PL.2FSQL
PL/SQL
CREATE OR REPLACE PACKAGE ethiopian IS   FUNCTION multiply ( left IN INTEGER, right IN INTEGER) RETURN INTEGER;   END ethiopian; /   CREATE OR REPLACE PACKAGE BODY ethiopian IS   FUNCTION is_even(item IN INTEGER) RETURN BOOLEAN IS BEGIN RETURN item MOD 2 = 0; END is_even;   FUNCTION double(item IN INTEGER) RETURN INTEGER IS BEGIN RETURN item * 2; END double;   FUNCTION half(item IN INTEGER) RETURN INTEGER IS BEGIN RETURN TRUNC(item / 2); END half;   FUNCTION multiply ( left IN INTEGER, right IN INTEGER) RETURN INTEGER IS temp INTEGER := 0; plier INTEGER := left; plicand INTEGER := right; BEGIN   LOOP IF NOT is_even(plier) THEN temp := temp + plicand; END IF; EXIT WHEN plier <= 1; plier := half(plier); plicand := double(plicand); END LOOP;   RETURN temp;   END multiply;   END ethiopian; /   /* example call */ BEGIN DBMS_OUTPUT.put_line(ethiopian.multiply(17, 34)); END; /
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)
#AutoHotkey
AutoHotkey
state := StrSplit("0000000001000000000") rule := 90 output := "Rule: " rule Loop, 10 { output .= "`n" A_Index "`t" PrintState(state) state := NextState(state, rule) } Gui, Font,, Courier New Gui, Add, Text,, % output Gui, Show return   GuiClose: ExitApp   ; Returns the next state based on the current state and rule. NextState(state, rule) { r := ByteDigits(rule) result := {} for i, val in state { if (i = 1) ; The leftmost cell result.Insert(r[state[state.MaxIndex()] state.1 state.2]) else if (i = state.MaxIndex()) ; The rightmost cell result.Insert(r[state[i-1] val state.1]) else ; All cells between leftmost and rightmost result.Insert(r[state[i - 1] val state[i + 1]]) } return result }   ; Returns an array with each three digit sequence as a key corresponding to a value ; of true or false depending on the rule. ByteDigits(rule) { res := {} for i, val in ["000", "001", "010", "011", "100", "101", "110", "111"] { res[val] := Mod(rule, 2) rule >>= 1 } return res }   ; Converts 0 and 1 to . and # respectively and returns a string representing the state PrintState(state) { for i, val in state result .= val = 1 ? "#" : "." return result }
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
#SSEM
SSEM
11100000000000100000000000000000 0. -7 to c 10101000000000010000000000000000 1. Sub. 21 10100000000001100000000000000000 2. c to 5 10100000000000100000000000000000 3. -5 to c 10100000000001100000000000000000 4. c to 5 00000000000000000000000000000000 5. generated at run time 00000000000001110000000000000000 6. Stop 00010000000000100000000000000000 7. -8 to c 11111111111111111111111111111111 8. -1 11111111111111111111111111111111 9. -1 01111111111111111111111111111111 10. -2 01011111111111111111111111111111 11. -6 00010111111111111111111111111111 12. -24 00010001111111111111111111111111 13. -120 00001100101111111111111111111111 14. -720 00001010001101111111111111111111 15. -5040 00000001010001101111111111111111 16. -40320 00000001011011100101111111111111 17. -362880 00000000100001010001001111111111 18. -3628800 00000000110101110111100110111111 19. -39916800 00000000001000001100111011000111 20. -479001600 01010000000000000000000000000000 21. 10
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.
#SPL
SPL
> n, 0..9  ? #.even(n), #.output(n," even")  ? #.odd(n), #.output(n," odd") <
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.
#SQL
SQL
-- Setup a table with some integers CREATE TABLE ints(INT INTEGER); INSERT INTO ints VALUES (-1); INSERT INTO ints VALUES (0); INSERT INTO ints VALUES (1); INSERT INTO ints VALUES (2);   -- Are they even or odd? SELECT INT, CASE MOD(INT, 2) WHEN 0 THEN 'Even' ELSE 'Odd' END FROM ints;