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/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#PowerShell
PowerShell
$i = 0 foreach ($s in $args) { Write-Host Argument (++$i) is $s }
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#Fortran
Fortran
C This would be some kind of comment C Usually one would avoid columns 2-6 even in a comment.
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   ' This a single line comment   REM This is another way of writing a single line comment   /' This is a multi-line comment '/   /' Multi-line comments /' can also be nested '/ like this '/
http://rosettacode.org/wiki/Conway%27s_Game_of_Life
Conway's Game of Life
The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead,   in an   m-by-m   (or m×m)   square array of cells. We calculate   N   - the sum of live cells in C's   eight-location neighbourhood,   then cell   C   is alive or dead in the next generation based on the following table: C N new C 1 0,1 -> 0 # Lonely 1 4,5,6,7,8 -> 0 # Overcrowded 1 2,3 -> 1 # Lives 0 3 -> 1 # It takes three to give birth! 0 0,1,2,4,5,6,7,8 -> 0 # Barren Assume cells beyond the boundary are always dead. The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players.   One interacts with the Game of Life by creating an initial configuration and observing how it evolves. Task Although you should test your implementation on more complex examples such as the   glider   in a larger universe,   show the action of the blinker   (three adjoining cells in a row all alive),   over three generations, in a 3 by 3 grid. References   Its creator John Conway, explains   the game of life.   Video from numberphile on youtube.   John Conway   Inventing Game of Life   - Numberphile video. Related task   Langton's ant   - another well known cellular automaton.
#Maxima
Maxima
life(A) := block( [p, q, B: zerofor(A), s], [p, q]: matrix_size(A), for i thru p do ( for j thru q do ( s: 0, if j > 1 then s: s + A[i, j - 1], if j < q then s: s + A[i, j + 1], if i > 1 then ( s: s + A[i - 1, j], if j > 1 then s: s + A[i - 1, j - 1], if j < q then s: s + A[i - 1, j + 1] ), if i < p then ( s: s + A[i + 1, j], if j > 1 then s: s + A[i + 1, j - 1], if j < q then s: s + A[i + 1, j + 1] ), B[i, j]: charfun(s = 3 or (s = 2 and A[i, j] = 1)) ) ), B )$     /* a glider */   L: matrix([0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])$   gen(A, n) := block(thru n do A: life(A), A)$   gen(L, 4); matrix([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include if-then-else and switch. Less common are arithmetic if, ternary operator and Hash-based conditionals. Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
#F.23
F#
  printfn "%s" (if 3<2 then "3 is less than 2" else "3 is not less than 2")  
http://rosettacode.org/wiki/Compare_a_list_of_strings
Compare a list of strings
Task Given a   list   of arbitrarily many strings, show how to:   test if they are all lexically equal   test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order) Each of those two tests should result in a single true or false value, which could be used as the condition of an   if   statement or similar. If the input list has less than two elements, the tests should always return true. There is no need to provide a complete program and output. Assume that the strings are already stored in an array/list/sequence/tuple variable (whatever is most idiomatic) with the name   strings,   and just show the expressions for performing those two tests on it (plus of course any includes and custom functions etc. that it needs),   with as little distractions as possible. Try to write your solution in a way that does not modify the original list,   but if it does then please add a note to make that clear to readers. If you need further guidance/clarification,   see #Perl and #Python for solutions that use implicit short-circuiting loops,   and #Raku for a solution that gets away with simply using a built-in language feature. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Vlang
Vlang
fn all_equal(strings []string) bool { for s in strings { if s != strings[0] { return false } } return true }   fn all_less_than(strings []string) bool { for i := 1; i < strings.len(); i++ { if !(strings[i - 1] < s) { return false } } return true }
http://rosettacode.org/wiki/Compare_a_list_of_strings
Compare a list of strings
Task Given a   list   of arbitrarily many strings, show how to:   test if they are all lexically equal   test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order) Each of those two tests should result in a single true or false value, which could be used as the condition of an   if   statement or similar. If the input list has less than two elements, the tests should always return true. There is no need to provide a complete program and output. Assume that the strings are already stored in an array/list/sequence/tuple variable (whatever is most idiomatic) with the name   strings,   and just show the expressions for performing those two tests on it (plus of course any includes and custom functions etc. that it needs),   with as little distractions as possible. Try to write your solution in a way that does not modify the original list,   but if it does then please add a note to make that clear to readers. If you need further guidance/clarification,   see #Perl and #Python for solutions that use implicit short-circuiting loops,   and #Raku for a solution that gets away with simply using a built-in language feature. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Wren
Wren
import "/sort" for Sort   var areEqual = Fn.new { |strings| if (strings.count < 2) return true return (1...strings.count).all { |i| strings[i] == strings[i-1] } }   var areAscending = Fn.new { |strings| Sort.isSorted(strings) }   var a = ["a", "a", "a"] var b = ["a", "b", "c"] var c = ["a", "a", "b"] var d = ["a", "d", "c"] System.print("%(a) are all equal : %(areEqual.call(a))") System.print("%(b) are ascending : %(areAscending.call(b))") System.print("%(c) are all equal : %(areEqual.call(c))") System.print("%(d) are ascending : %(areAscending.call(d))")
http://rosettacode.org/wiki/Comma_quibbling
Comma quibbling
Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}". An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}". An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}". An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}". Test your function with the following series of inputs showing your output here on this page: [] # (No input words). ["ABC"] ["ABC", "DEF"] ["ABC", "DEF", "G", "H"] Note: Assume words are non-empty strings of uppercase characters for this task.
#OCaml
OCaml
open Printf   let quibble list = let rec aux = function | a :: b :: c :: d :: rest -> a ^ ", " ^ aux (b :: c :: d :: rest) | [a; b; c] -> sprintf "%s, %s and %s}" a b c | [a; b] -> sprintf "%s and %s}" a b | [a] -> sprintf "%s}" a | [] -> "}" in "{" ^ aux list   let test () = [[]; ["ABC"]; ["ABC"; "DEF"]; ["ABC"; "DEF"; "G"; "H"]] |> List.iter (fun list -> print_endline (quibble list))
http://rosettacode.org/wiki/Combinations_with_repetitions
Combinations with repetitions
The set of combinations with repetitions is computed from a set, S {\displaystyle S} (of cardinality n {\displaystyle n} ), and a size of resulting selection, k {\displaystyle k} , by reporting the sets of cardinality k {\displaystyle k} where each member of those sets is chosen from S {\displaystyle S} . In the real world, it is about choosing sets where there is a “large” supply of each type of element and where the order of choice does not matter. For example: Q: How many ways can a person choose two doughnuts from a store selling three types of doughnut: iced, jam, and plain? (i.e., S {\displaystyle S} is { i c e d , j a m , p l a i n } {\displaystyle \{\mathrm {iced} ,\mathrm {jam} ,\mathrm {plain} \}} , | S | = 3 {\displaystyle |S|=3} , and k = 2 {\displaystyle k=2} .) A: 6: {iced, iced}; {iced, jam}; {iced, plain}; {jam, jam}; {jam, plain}; {plain, plain}. Note that both the order of items within a pair, and the order of the pairs given in the answer is not significant; the pairs represent multisets. Also note that doughnut can also be spelled donut. Task Write a function/program/routine/.. to generate all the combinations with repetitions of n {\displaystyle n} types of things taken k {\displaystyle k} at a time and use it to show an answer to the doughnut example above. For extra credit, use the function to compute and show just the number of ways of choosing three doughnuts from a choice of ten types of doughnut. Do not show the individual choices for this part. References k-combination with repetitions See also The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Unimportant Order Important Without replacement ( n k ) = n C k = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} Task: Combinations Task: Permutations With replacement ( n + k − 1 k ) = n + k − 1 C k = ( n + k − 1 ) ! ( n − 1 ) ! k ! {\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}} n k {\displaystyle n^{k}} Task: Combinations with repetitions Task: Permutations with repetitions
#TXR
TXR
txr -p "(rcomb '(iced jam plain) 2)"
http://rosettacode.org/wiki/Combinations_with_repetitions
Combinations with repetitions
The set of combinations with repetitions is computed from a set, S {\displaystyle S} (of cardinality n {\displaystyle n} ), and a size of resulting selection, k {\displaystyle k} , by reporting the sets of cardinality k {\displaystyle k} where each member of those sets is chosen from S {\displaystyle S} . In the real world, it is about choosing sets where there is a “large” supply of each type of element and where the order of choice does not matter. For example: Q: How many ways can a person choose two doughnuts from a store selling three types of doughnut: iced, jam, and plain? (i.e., S {\displaystyle S} is { i c e d , j a m , p l a i n } {\displaystyle \{\mathrm {iced} ,\mathrm {jam} ,\mathrm {plain} \}} , | S | = 3 {\displaystyle |S|=3} , and k = 2 {\displaystyle k=2} .) A: 6: {iced, iced}; {iced, jam}; {iced, plain}; {jam, jam}; {jam, plain}; {plain, plain}. Note that both the order of items within a pair, and the order of the pairs given in the answer is not significant; the pairs represent multisets. Also note that doughnut can also be spelled donut. Task Write a function/program/routine/.. to generate all the combinations with repetitions of n {\displaystyle n} types of things taken k {\displaystyle k} at a time and use it to show an answer to the doughnut example above. For extra credit, use the function to compute and show just the number of ways of choosing three doughnuts from a choice of ten types of doughnut. Do not show the individual choices for this part. References k-combination with repetitions See also The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Unimportant Order Important Without replacement ( n k ) = n C k = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} Task: Combinations Task: Permutations With replacement ( n + k − 1 k ) = n + k − 1 C k = ( n + k − 1 ) ! ( n − 1 ) ! k ! {\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}} n k {\displaystyle n^{k}} Task: Combinations with repetitions Task: Permutations with repetitions
#Ursala
Ursala
#import std #import nat   cwr = ~&s+ -<&*+ ~&K0=>&^|DlS/~& iota # takes a set and a selection size   #cast %gLSnX   main = ^|(~&,length) cwr~~/(<'iced','jam','plain'>,2) ('1234567890',3)
http://rosettacode.org/wiki/Compiler/lexical_analyzer
Compiler/lexical analyzer
Definition from Wikipedia: Lexical analysis is the process of converting a sequence of characters (such as in a computer program or web page) into a sequence of tokens (strings with an identified "meaning"). A program that performs lexical analysis may be called a lexer, tokenizer, or scanner (though "scanner" is also used to refer to the first stage of a lexer). Task[edit] Create a lexical analyzer for the simple programming language specified below. The program should read input from a file and/or stdin, and write output to a file and/or stdout. If the language being used has a lexer module/library/class, it would be great if two versions of the solution are provided: One without the lexer module, and one with. Input Specification The simple programming language to be analyzed is more or less a subset of C. It supports the following tokens: Operators Name Common name Character sequence Op_multiply multiply * Op_divide divide / Op_mod mod % Op_add plus + Op_subtract minus - Op_negate unary minus - Op_less less than < Op_lessequal less than or equal <= Op_greater greater than > Op_greaterequal greater than or equal >= Op_equal equal == Op_notequal not equal != Op_not unary not ! Op_assign assignment = Op_and logical and && Op_or logical or ¦¦ The - token should always be interpreted as Op_subtract by the lexer. Turning some Op_subtract into Op_negate will be the job of the syntax analyzer, which is not part of this task. Symbols Name Common name Character LeftParen left parenthesis ( RightParen right parenthesis ) LeftBrace left brace { RightBrace right brace } Semicolon semi-colon ; Comma comma , Keywords Name Character sequence Keyword_if if Keyword_else else Keyword_while while Keyword_print print Keyword_putc putc Identifiers and literals These differ from the the previous tokens, in that each occurrence of them has a value associated with it. Name Common name Format description Format regex Value Identifier identifier one or more letter/number/underscore characters, but not starting with a number [_a-zA-Z][_a-zA-Z0-9]* as is Integer integer literal one or more digits [0-9]+ as is, interpreted as a number Integer char literal exactly one character (anything except newline or single quote) or one of the allowed escape sequences, enclosed by single quotes '([^'\n]|\\n|\\\\)' the ASCII code point number of the character, e.g. 65 for 'A' and 10 for '\n' String string literal zero or more characters (anything except newline or double quote), enclosed by double quotes "[^"\n]*" the characters without the double quotes and with escape sequences converted For char and string literals, the \n escape sequence is supported to represent a new-line character. For char and string literals, to represent a backslash, use \\. No other special sequences are supported. This means that: Char literals cannot represent a single quote character (value 39). String literals cannot represent strings containing double quote characters. Zero-width tokens Name Location End_of_input when the end of the input stream is reached White space Zero or more whitespace characters, or comments enclosed in /* ... */, are allowed between any two tokens, with the exceptions noted below. "Longest token matching" is used to resolve conflicts (e.g., in order to match <= as a single token rather than the two tokens < and =). Whitespace is required between two tokens that have an alphanumeric character or underscore at the edge. This means: keywords, identifiers, and integer literals. e.g. ifprint is recognized as an identifier, instead of the keywords if and print. e.g. 42fred is invalid, and neither recognized as a number nor an identifier. Whitespace is not allowed inside of tokens (except for chars and strings where they are part of the value). e.g. & & is invalid, and not interpreted as the && operator. For example, the following two program fragments are equivalent, and should produce the same token stream except for the line and column positions: if ( p /* meaning n is prime */ ) { print ( n , " " ) ; count = count + 1 ; /* number of primes found so far */ } if(p){print(n," ");count=count+1;} Complete list of token names End_of_input Op_multiply Op_divide Op_mod Op_add Op_subtract Op_negate Op_not Op_less Op_lessequal Op_greater Op_greaterequal Op_equal Op_notequal Op_assign Op_and Op_or Keyword_if Keyword_else Keyword_while Keyword_print Keyword_putc LeftParen RightParen LeftBrace RightBrace Semicolon Comma Identifier Integer String Output Format The program output should be a sequence of lines, each consisting of the following whitespace-separated fields: the line number where the token starts the column number where the token starts the token name the token value (only for Identifier, Integer, and String tokens) the number of spaces between fields is up to you. Neatly aligned is nice, but not a requirement. This task is intended to be used as part of a pipeline, with the other compiler tasks - for example: lex < hello.t | parse | gen | vm Or possibly: lex hello.t lex.out parse lex.out parse.out gen parse.out gen.out vm gen.out This implies that the output of this task (the lexical analyzer) should be suitable as input to any of the Syntax Analyzer task programs. Diagnostics The following error conditions should be caught: Error Example Empty character constant '' Unknown escape sequence. \r Multi-character constant. 'xx' End-of-file in comment. Closing comment characters not found. End-of-file while scanning string literal. Closing string character not found. End-of-line while scanning string literal. Closing string character not found before end-of-line. Unrecognized character. | Invalid number. Starts like a number, but ends in non-numeric characters. 123abc Test Cases Input Output Test Case 1: /* Hello world */ print("Hello, World!\n"); 4 1 Keyword_print 4 6 LeftParen 4 7 String "Hello, World!\n" 4 24 RightParen 4 25 Semicolon 5 1 End_of_input Test Case 2: /* Show Ident and Integers */ phoenix_number = 142857; print(phoenix_number, "\n"); 4 1 Identifier phoenix_number 4 16 Op_assign 4 18 Integer 142857 4 24 Semicolon 5 1 Keyword_print 5 6 LeftParen 5 7 Identifier phoenix_number 5 21 Comma 5 23 String "\n" 5 27 RightParen 5 28 Semicolon 6 1 End_of_input Test Case 3: /* All lexical tokens - not syntactically correct, but that will have to wait until syntax analysis */ /* Print */ print /* Sub */ - /* Putc */ putc /* Lss */ < /* If */ if /* Gtr */ > /* Else */ else /* Leq */ <= /* While */ while /* Geq */ >= /* Lbrace */ { /* Eq */ == /* Rbrace */ } /* Neq */ != /* Lparen */ ( /* And */ && /* Rparen */ ) /* Or */ || /* Uminus */ - /* Semi */ ; /* Not */ ! /* Comma */ , /* Mul */ * /* Assign */ = /* Div */ / /* Integer */ 42 /* Mod */ % /* String */ "String literal" /* Add */ + /* Ident */ variable_name /* character literal */ '\n' /* character literal */ '\\' /* character literal */ ' ' 5 16 Keyword_print 5 40 Op_subtract 6 16 Keyword_putc 6 40 Op_less 7 16 Keyword_if 7 40 Op_greater 8 16 Keyword_else 8 40 Op_lessequal 9 16 Keyword_while 9 40 Op_greaterequal 10 16 LeftBrace 10 40 Op_equal 11 16 RightBrace 11 40 Op_notequal 12 16 LeftParen 12 40 Op_and 13 16 RightParen 13 40 Op_or 14 16 Op_subtract 14 40 Semicolon 15 16 Op_not 15 40 Comma 16 16 Op_multiply 16 40 Op_assign 17 16 Op_divide 17 40 Integer 42 18 16 Op_mod 18 40 String "String literal" 19 16 Op_add 19 40 Identifier variable_name 20 26 Integer 10 21 26 Integer 92 22 26 Integer 32 23 1 End_of_input Test Case 4: /*** test printing, embedded \n and comments with lots of '*' ***/ print(42); print("\nHello World\nGood Bye\nok\n"); print("Print a slash n - \\n.\n"); 2 1 Keyword_print 2 6 LeftParen 2 7 Integer 42 2 9 RightParen 2 10 Semicolon 3 1 Keyword_print 3 6 LeftParen 3 7 String "\nHello World\nGood Bye\nok\n" 3 38 RightParen 3 39 Semicolon 4 1 Keyword_print 4 6 LeftParen 4 7 String "Print a slash n - \\n.\n" 4 33 RightParen 4 34 Semicolon 5 1 End_of_input Additional examples Your solution should pass all the test cases above and the additional tests found Here. Reference The C and Python versions can be considered reference implementations. Related Tasks Syntax Analyzer task Code Generator task Virtual Machine Interpreter task AST Interpreter task
#Zig
Zig
  const std = @import("std");   pub const TokenType = enum { unknown, multiply, divide, mod, add, subtract, negate, less, less_equal, greater, greater_equal, equal, not_equal, not, assign, bool_and, bool_or, left_paren, right_paren, left_brace, right_brace, semicolon, comma, kw_if, kw_else, kw_while, kw_print, kw_putc, identifier, integer, string, eof,   // More efficient implementation can be done with `std.enums.directEnumArray`. pub fn toString(self: @This()) []const u8 { return switch (self) { .unknown => "UNKNOWN", .multiply => "Op_multiply", .divide => "Op_divide", .mod => "Op_mod", .add => "Op_add", .subtract => "Op_subtract", .negate => "Op_negate", .less => "Op_less", .less_equal => "Op_lessequal", .greater => "Op_greater", .greater_equal => "Op_greaterequal", .equal => "Op_equal", .not_equal => "Op_notequal", .not => "Op_not", .assign => "Op_assign", .bool_and => "Op_and", .bool_or => "Op_or", .left_paren => "LeftParen", .right_paren => "RightParen", .left_brace => "LeftBrace", .right_brace => "RightBrace", .semicolon => "Semicolon", .comma => "Comma", .kw_if => "Keyword_if", .kw_else => "Keyword_else", .kw_while => "Keyword_while", .kw_print => "Keyword_print", .kw_putc => "Keyword_putc", .identifier => "Identifier", .integer => "Integer", .string => "String", .eof => "End_of_input", }; } };   pub const TokenValue = union(enum) { intlit: i32, string: []const u8, };   pub const Token = struct { line: usize, col: usize, typ: TokenType = .unknown, value: ?TokenValue = null, };   // Error conditions described in the task. pub const LexerError = error{ EmptyCharacterConstant, UnknownEscapeSequence, MulticharacterConstant, EndOfFileInComment, EndOfFileInString, EndOfLineInString, UnrecognizedCharacter, InvalidNumber, };   pub const Lexer = struct { content: []const u8, line: usize, col: usize, offset: usize, start: bool,   const Self = @This();   pub fn init(content: []const u8) Lexer { return Lexer{ .content = content, .line = 1, .col = 1, .offset = 0, .start = true, }; }   pub fn buildToken(self: Self) Token { return Token{ .line = self.line, .col = self.col }; }   pub fn buildTokenT(self: Self, typ: TokenType) Token { return Token{ .line = self.line, .col = self.col, .typ = typ }; }   pub fn curr(self: Self) u8 { return self.content[self.offset]; }   // Alternative implementation is to return `Token` value from `next()` which is // arguably more idiomatic version. pub fn next(self: *Self) ?u8 { // We use `start` in order to make the very first invocation of `next()` to return // the very first character. It should be possible to avoid this variable. if (self.start) { self.start = false; } else { const newline = self.curr() == '\n'; self.offset += 1; if (newline) { self.col = 1; self.line += 1; } else { self.col += 1; } } if (self.offset >= self.content.len) { return null; } else { return self.curr(); } }   pub fn peek(self: Self) ?u8 { if (self.offset + 1 >= self.content.len) { return null; } else { return self.content[self.offset + 1]; } }   fn divOrComment(self: *Self) LexerError!?Token { var result = self.buildToken(); if (self.peek()) |peek_ch| { if (peek_ch == '*') { _ = self.next(); // peeked character while (self.next()) |ch| { if (ch == '*') { if (self.peek()) |next_ch| { if (next_ch == '/') { _ = self.next(); // peeked character return null; } } } } return LexerError.EndOfFileInComment; } } result.typ = .divide; return result; }   fn identifierOrKeyword(self: *Self) !Token { var result = self.buildToken(); const init_offset = self.offset; while (self.peek()) |ch| : (_ = self.next()) { switch (ch) { '_', 'a'...'z', 'A'...'Z', '0'...'9' => {}, else => break, } } const final_offset = self.offset + 1;   if (std.mem.eql(u8, self.content[init_offset..final_offset], "if")) { result.typ = .kw_if; } else if (std.mem.eql(u8, self.content[init_offset..final_offset], "else")) { result.typ = .kw_else; } else if (std.mem.eql(u8, self.content[init_offset..final_offset], "while")) { result.typ = .kw_while; } else if (std.mem.eql(u8, self.content[init_offset..final_offset], "print")) { result.typ = .kw_print; } else if (std.mem.eql(u8, self.content[init_offset..final_offset], "putc")) { result.typ = .kw_putc; } else { result.typ = .identifier; result.value = TokenValue{ .string = self.content[init_offset..final_offset] }; }   return result; }   fn string(self: *Self) !Token { var result = self.buildToken(); result.typ = .string; const init_offset = self.offset; while (self.next()) |ch| { switch (ch) { '"' => break, '\n' => return LexerError.EndOfLineInString, '\\' => { switch (self.peek() orelse return LexerError.EndOfFileInString) { 'n', '\\' => _ = self.next(), // peeked character else => return LexerError.UnknownEscapeSequence, } }, else => {}, } } else { return LexerError.EndOfFileInString; } const final_offset = self.offset + 1; result.value = TokenValue{ .string = self.content[init_offset..final_offset] }; return result; }   /// Choose either `ifyes` or `ifno` token type depending on whether the peeked /// character is `by`. fn followed(self: *Self, by: u8, ifyes: TokenType, ifno: TokenType) Token { var result = self.buildToken(); if (self.peek()) |ch| { if (ch == by) { _ = self.next(); // peeked character result.typ = ifyes; } else { result.typ = ifno; } } else { result.typ = ifno; } return result; }   /// Raise an error if there's no next `by` character but return token with `typ` otherwise. fn consecutive(self: *Self, by: u8, typ: TokenType) LexerError!Token { const result = self.buildTokenT(typ); if (self.peek()) |ch| { if (ch == by) { _ = self.next(); // peeked character return result; } else { return LexerError.UnrecognizedCharacter; } } else { return LexerError.UnrecognizedCharacter; } }   fn integerLiteral(self: *Self) LexerError!Token { var result = self.buildTokenT(.integer); const init_offset = self.offset; while (self.peek()) |ch| { switch (ch) { '0'...'9' => _ = self.next(), // peeked character '_', 'a'...'z', 'A'...'Z' => return LexerError.InvalidNumber, else => break, } } const final_offset = self.offset + 1; result.value = TokenValue{ .intlit = std.fmt.parseInt(i32, self.content[init_offset..final_offset], 10) catch { return LexerError.InvalidNumber; }, }; return result; }   // This is a beautiful way of how Zig allows to remove bilerplate and at the same time // to not lose any error completeness guarantees. fn nextOrEmpty(self: *Self) LexerError!u8 { return self.next() orelse LexerError.EmptyCharacterConstant; }   fn integerChar(self: *Self) LexerError!Token { var result = self.buildTokenT(.integer); switch (try self.nextOrEmpty()) { '\'', '\n' => return LexerError.EmptyCharacterConstant, '\\' => { switch (try self.nextOrEmpty()) { 'n' => result.value = TokenValue{ .intlit = '\n' }, '\\' => result.value = TokenValue{ .intlit = '\\' }, else => return LexerError.EmptyCharacterConstant, } switch (try self.nextOrEmpty()) { '\'' => {}, else => return LexerError.MulticharacterConstant, } }, else => { result.value = TokenValue{ .intlit = self.curr() }; switch (try self.nextOrEmpty()) { '\'' => {}, else => return LexerError.MulticharacterConstant, } }, } return result; } };   pub fn lex(allocator: std.mem.Allocator, content: []u8) !std.ArrayList(Token) { var tokens = std.ArrayList(Token).init(allocator); var lexer = Lexer.init(content); while (lexer.next()) |ch| { switch (ch) { ' ' => {}, '*' => try tokens.append(lexer.buildTokenT(.multiply)), '%' => try tokens.append(lexer.buildTokenT(.mod)), '+' => try tokens.append(lexer.buildTokenT(.add)), '-' => try tokens.append(lexer.buildTokenT(.subtract)), '<' => try tokens.append(lexer.followed('=', .less_equal, .less)), '>' => try tokens.append(lexer.followed('=', .greater_equal, .greater)), '=' => try tokens.append(lexer.followed('=', .equal, .assign)), '!' => try tokens.append(lexer.followed('=', .not_equal, .not)), '(' => try tokens.append(lexer.buildTokenT(.left_paren)), ')' => try tokens.append(lexer.buildTokenT(.right_paren)), '{' => try tokens.append(lexer.buildTokenT(.left_brace)), '}' => try tokens.append(lexer.buildTokenT(.right_brace)), ';' => try tokens.append(lexer.buildTokenT(.semicolon)), ',' => try tokens.append(lexer.buildTokenT(.comma)), '&' => try tokens.append(try lexer.consecutive('&', .bool_and)), '|' => try tokens.append(try lexer.consecutive('|', .bool_or)), '/' => { if (try lexer.divOrComment()) |token| try tokens.append(token); }, '_', 'a'...'z', 'A'...'Z' => try tokens.append(try lexer.identifierOrKeyword()), '"' => try tokens.append(try lexer.string()), '0'...'9' => try tokens.append(try lexer.integerLiteral()), '\'' => try tokens.append(try lexer.integerChar()), else => {}, } } try tokens.append(lexer.buildTokenT(.eof));   return tokens; }   pub fn main() !void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = arena.allocator();   var arg_it = std.process.args(); _ = try arg_it.next(allocator) orelse unreachable; // program name const file_name = arg_it.next(allocator); // We accept both files and standard input. var file_handle = blk: { if (file_name) |file_name_delimited| { const fname: []const u8 = try file_name_delimited; break :blk try std.fs.cwd().openFile(fname, .{}); } else { break :blk std.io.getStdIn(); } }; defer file_handle.close(); const input_content = try file_handle.readToEndAlloc(allocator, std.math.maxInt(usize));   const tokens = try lex(allocator, input_content); const pretty_output = try tokenListToString(allocator, tokens); _ = try std.io.getStdOut().write(pretty_output); }   fn tokenListToString(allocator: std.mem.Allocator, token_list: std.ArrayList(Token)) ![]u8 { var result = std.ArrayList(u8).init(allocator); var w = result.writer(); for (token_list.items) |token| { const common_args = .{ token.line, token.col, token.typ.toString() }; if (token.value) |value| { const init_fmt = "{d:>5}{d:>7} {s:<15}"; switch (value) { .string => |str| _ = try w.write(try std.fmt.allocPrint( allocator, init_fmt ++ "{s}\n", common_args ++ .{str}, )), .intlit => |i| _ = try w.write(try std.fmt.allocPrint( allocator, init_fmt ++ "{d}\n", common_args ++ .{i}, )), } } else { _ = try w.write(try std.fmt.allocPrint(allocator, "{d:>5}{d:>7} {s}\n", common_args)); } } return result.items; }  
http://rosettacode.org/wiki/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#Pure
Pure
  using system;   printf "There are %d command line argumants\n" argc; puts "They are " $$ map (puts) argv;  
http://rosettacode.org/wiki/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#PureBasic
PureBasic
If OpenConsole() Define n=CountProgramParameters() PrintN("Reading all parameters") While n PrintN(ProgramParameter()) n-1 Wend Print(#CRLF$+"Press Enter") Input() CloseConsole() EndIf
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#Frink
Frink
  // This is a single-line comment /* This is a comment that spans multiple lines and so on. */  
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#Futhark
Futhark
  -- Single-line comment   -- Multi-line -- comment (yes, just several single-line comments).  
http://rosettacode.org/wiki/Conway%27s_Game_of_Life
Conway's Game of Life
The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead,   in an   m-by-m   (or m×m)   square array of cells. We calculate   N   - the sum of live cells in C's   eight-location neighbourhood,   then cell   C   is alive or dead in the next generation based on the following table: C N new C 1 0,1 -> 0 # Lonely 1 4,5,6,7,8 -> 0 # Overcrowded 1 2,3 -> 1 # Lives 0 3 -> 1 # It takes three to give birth! 0 0,1,2,4,5,6,7,8 -> 0 # Barren Assume cells beyond the boundary are always dead. The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players.   One interacts with the Game of Life by creating an initial configuration and observing how it evolves. Task Although you should test your implementation on more complex examples such as the   glider   in a larger universe,   show the action of the blinker   (three adjoining cells in a row all alive),   over three generations, in a 3 by 3 grid. References   Its creator John Conway, explains   the game of life.   Video from numberphile on youtube.   John Conway   Inventing Game of Life   - Numberphile video. Related task   Langton's ant   - another well known cellular automaton.
#MiniScript
MiniScript
// Conway's Game of Life clear rows = 64; rowRange = range(0, rows-1) cols = 96; colRange = range(0, cols-1) // prepare two tile displays, in display layers 4 and 5 img = Image.create(2, 1); img.setPixel 1, 0, color.white grids = [] for dispIdx in [4,5] display(dispIdx).mode = displayMode.tile td = display(dispIdx) td.cellSize = 10 // size of cells on screen td.extent = [cols, rows] td.overlap = -1 // adds a small gap between cells td.tileSet = img; td.tileSetTileSize = 1 td.clear 0 grids.push td end for   // initialize to a random state for x in colRange for y in rowRange td.setCell x, y, rnd > 0.5 end for end for   curIdx = 5 // main loop while true yield td = grids[curIdx-4] newIdx = 4 + (curIdx == 4) newTd = grids[newIdx-4] for x in colRange for y in rowRange // get sum of neighboring states sum = 0 for i in [x-1, x, x+1] if i < 0 or i >= cols then continue for j in [y-1, y, y+1] if j < 0 or j >= rows then continue if i==x and j==y then continue sum = sum + td.cell(i,j) end for end for // Now, update the cell based on current state // and neighboring sum. if td.cell(x,y) then newTd.setCell x, y, (sum == 2 or sum == 3) else newTd.setCell x, y, sum == 3 end if end for end for display(newIdx).mode = displayMode.tile display(curIdx).mode = displayMode.off curIdx = newIdx end while
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include if-then-else and switch. Less common are arithmetic if, ternary operator and Hash-based conditionals. Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
#Factor
Factor
  t 1 2 ? ! returns 1  
http://rosettacode.org/wiki/Compare_a_list_of_strings
Compare a list of strings
Task Given a   list   of arbitrarily many strings, show how to:   test if they are all lexically equal   test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order) Each of those two tests should result in a single true or false value, which could be used as the condition of an   if   statement or similar. If the input list has less than two elements, the tests should always return true. There is no need to provide a complete program and output. Assume that the strings are already stored in an array/list/sequence/tuple variable (whatever is most idiomatic) with the name   strings,   and just show the expressions for performing those two tests on it (plus of course any includes and custom functions etc. that it needs),   with as little distractions as possible. Try to write your solution in a way that does not modify the original list,   but if it does then please add a note to make that clear to readers. If you need further guidance/clarification,   see #Perl and #Python for solutions that use implicit short-circuiting loops,   and #Raku for a solution that gets away with simply using a built-in language feature. 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
#XProfan
XProfan
Proc allsame Parameters long liste var int result = 1 var int cnt = GetCount(liste) Case cnt == 0 : Return 0 Case cnt == 1 : Return 1 WhileLoop 1, cnt-1 If GetString$(liste,&loop - 1) <> GetString$(liste,&loop) result = 0 BREAK EndIf EndWhile Return result EndProc   Proc strict_order Parameters long liste var int result = 1 var int cnt = GetCount(liste) Case cnt == 0 : Return 0 Case cnt == 1 : Return 1 WhileLoop 1, cnt-1 If GetString$(liste,&loop) <= GetString$(liste,&loop - 1) result = 0 BREAK EndIf EndWhile Return result EndProc   cls declare string s[4] s[0] = "AA,BB,CC" s[1] = "AA,AA,AA" s[2] = "AA,CC,BB" s[3] = "AA,ACB,BB,CC" s[4] = "single_element"   WhileLoop 0,4 ClearList 0 Move("StrToList",s[&loop],",") Print "list:",s[&loop] Print "...is " + if(allsame(0), "", "not ") + "lexically equal" Print "...is " + if(strict_order(0), "", "not ") + "in strict ascending order" EndWhile   ClearList 0 WaitKey end
http://rosettacode.org/wiki/Compare_a_list_of_strings
Compare a list of strings
Task Given a   list   of arbitrarily many strings, show how to:   test if they are all lexically equal   test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order) Each of those two tests should result in a single true or false value, which could be used as the condition of an   if   statement or similar. If the input list has less than two elements, the tests should always return true. There is no need to provide a complete program and output. Assume that the strings are already stored in an array/list/sequence/tuple variable (whatever is most idiomatic) with the name   strings,   and just show the expressions for performing those two tests on it (plus of course any includes and custom functions etc. that it needs),   with as little distractions as possible. Try to write your solution in a way that does not modify the original list,   but if it does then please add a note to make that clear to readers. If you need further guidance/clarification,   see #Perl and #Python for solutions that use implicit short-circuiting loops,   and #Raku for a solution that gets away with simply using a built-in language feature. 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
#zkl
zkl
fcn allEQ(strings){ (not strings.filter1('!=(strings[0]))) } fcn monoUp(strings){ strings.len()<2 or strings.reduce(fcn(a,b){ if(a>=b) return(Void.Stop,False); b }).toBool() }
http://rosettacode.org/wiki/Comma_quibbling
Comma quibbling
Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}". An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}". An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}". An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}". Test your function with the following series of inputs showing your output here on this page: [] # (No input words). ["ABC"] ["ABC", "DEF"] ["ABC", "DEF", "G", "H"] Note: Assume words are non-empty strings of uppercase characters for this task.
#Oforth
Oforth
: quibbing(l) -- string | i s | StringBuffer new "{" << l size dup 1- ->s loop: i [ l at(i) << i s < ifTrue: [ ", " << continue ] i s == ifTrue: [ " and " << ] ] "}" << dup freeze ;
http://rosettacode.org/wiki/Comma_quibbling
Comma quibbling
Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}". An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}". An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}". An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}". Test your function with the following series of inputs showing your output here on this page: [] # (No input words). ["ABC"] ["ABC", "DEF"] ["ABC", "DEF", "G", "H"] Note: Assume words are non-empty strings of uppercase characters for this task.
#Ol
Ol
  (define (quibble . args) (display "{") (let loop ((args args)) (unless (null? args) (begin (display (car args)) (cond ((= 1 (length args)) #t) ((= 2 (length args)) (display " and ")) (else (display ", "))) (loop (cdr args))))) (print "}"))   ; testing => (quibble) (quibble "ABC") (quibble "ABC" "DEF") (quibble "ABC" "DEF" "G" "H")  
http://rosettacode.org/wiki/Combinations_with_repetitions
Combinations with repetitions
The set of combinations with repetitions is computed from a set, S {\displaystyle S} (of cardinality n {\displaystyle n} ), and a size of resulting selection, k {\displaystyle k} , by reporting the sets of cardinality k {\displaystyle k} where each member of those sets is chosen from S {\displaystyle S} . In the real world, it is about choosing sets where there is a “large” supply of each type of element and where the order of choice does not matter. For example: Q: How many ways can a person choose two doughnuts from a store selling three types of doughnut: iced, jam, and plain? (i.e., S {\displaystyle S} is { i c e d , j a m , p l a i n } {\displaystyle \{\mathrm {iced} ,\mathrm {jam} ,\mathrm {plain} \}} , | S | = 3 {\displaystyle |S|=3} , and k = 2 {\displaystyle k=2} .) A: 6: {iced, iced}; {iced, jam}; {iced, plain}; {jam, jam}; {jam, plain}; {plain, plain}. Note that both the order of items within a pair, and the order of the pairs given in the answer is not significant; the pairs represent multisets. Also note that doughnut can also be spelled donut. Task Write a function/program/routine/.. to generate all the combinations with repetitions of n {\displaystyle n} types of things taken k {\displaystyle k} at a time and use it to show an answer to the doughnut example above. For extra credit, use the function to compute and show just the number of ways of choosing three doughnuts from a choice of ten types of doughnut. Do not show the individual choices for this part. References k-combination with repetitions See also The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Unimportant Order Important Without replacement ( n k ) = n C k = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} Task: Combinations Task: Permutations With replacement ( n + k − 1 k ) = n + k − 1 C k = ( n + k − 1 ) ! ( n − 1 ) ! k ! {\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}} n k {\displaystyle n^{k}} Task: Combinations with repetitions Task: Permutations with repetitions
#VBScript
VBScript
' Combinations with repetitions - iterative - VBScript Sub printc(vi,n,vs) Dim i, w For i=0 To n-1 w=w &" "& vs(vi(i)) Next 'i Wscript.Echo w End Sub   Sub combine(flavors, draws, xitem, tell) Dim n, i, j ReDim v(draws) If tell Then Wscript.Echo "list of cwr("& flavors &","& draws &") :" Do While True For i=0 To draws-1 If v(i)>flavors-1 Then v(i+1)=v(i+1)+1 For j=i To 0 Step -1 v(j)=v(i+1) Next 'j End If Next 'i If v(draws)>0 Then Exit Do n=n+1 If tell Then Call printc(v, draws, xitem) v(0)=v(0)+1 Loop Wscript.Echo "cwr("& flavors &","& draws &")="&n End Sub   items=Array( "iced", "jam", "plain" ) combine 3, 2, items, True combine 10, 3, , False combine 10, 7, , False combine 10, 9, , False
http://rosettacode.org/wiki/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#Python
Python
import sys program_name = sys.argv[0] arguments = sys.argv[1:] count = len(arguments)
http://rosettacode.org/wiki/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#R
R
R CMD BATCH --vanilla --slave '--args a=1 b=c(2,5,6)' test.r test.out
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#FutureBasic
FutureBasic
  // Single line comment ' Single line comment rem Single line comment /* Single line comment */   /* Multiline comment */  
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#FUZE_BASIC
FUZE BASIC
//Comment (No space required) # Comment (Space required) REM Comment (Space require) PRINT "This is an inline comment."//Comment (No space required) END
http://rosettacode.org/wiki/Conway%27s_Game_of_Life
Conway's Game of Life
The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead,   in an   m-by-m   (or m×m)   square array of cells. We calculate   N   - the sum of live cells in C's   eight-location neighbourhood,   then cell   C   is alive or dead in the next generation based on the following table: C N new C 1 0,1 -> 0 # Lonely 1 4,5,6,7,8 -> 0 # Overcrowded 1 2,3 -> 1 # Lives 0 3 -> 1 # It takes three to give birth! 0 0,1,2,4,5,6,7,8 -> 0 # Barren Assume cells beyond the boundary are always dead. The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players.   One interacts with the Game of Life by creating an initial configuration and observing how it evolves. Task Although you should test your implementation on more complex examples such as the   glider   in a larger universe,   show the action of the blinker   (three adjoining cells in a row all alive),   over three generations, in a 3 by 3 grid. References   Its creator John Conway, explains   the game of life.   Video from numberphile on youtube.   John Conway   Inventing Game of Life   - Numberphile video. Related task   Langton's ant   - another well known cellular automaton.
#Nim
Nim
import os, strutils, random   randomize() var w, h: int if paramCount() >= 2: w = parseInt(paramStr(1)) h = parseInt(paramStr(2)) if w <= 0: w = 30 if h <= 0: h = 30   # Initialize var univ, utmp = newSeq[seq[bool]](h) for y in 0..<h: univ[y].newSeq w utmp[y].newSeq w for x in 0 ..< w: if rand(9) < 1: univ[y][x] = true   while true: # Show stdout.write "\e[H" for y in 0..<h: for x in 0..<w: stdout.write if univ[y][x]: "\e[07m \e[m" else: " " stdout.write "\e[E" stdout.flushFile   # Evolve for y in 0..<h: for x in 0..<w: var n = 0 for y1 in y-1..y+1: for x1 in x-1..x+1: if univ[(y1+h) mod h][(x1 + w) mod w]: inc n   if univ[y][x]: dec n utmp[y][x] = n == 3 or (n == 2 and univ[y][x]) swap(univ,utmp)   sleep 200
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include if-then-else and switch. Less common are arithmetic if, ternary operator and Hash-based conditionals. Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
#FALSE
FALSE
condition[body]?
http://rosettacode.org/wiki/Compare_a_list_of_strings
Compare a list of strings
Task Given a   list   of arbitrarily many strings, show how to:   test if they are all lexically equal   test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order) Each of those two tests should result in a single true or false value, which could be used as the condition of an   if   statement or similar. If the input list has less than two elements, the tests should always return true. There is no need to provide a complete program and output. Assume that the strings are already stored in an array/list/sequence/tuple variable (whatever is most idiomatic) with the name   strings,   and just show the expressions for performing those two tests on it (plus of course any includes and custom functions etc. that it needs),   with as little distractions as possible. Try to write your solution in a way that does not modify the original list,   but if it does then please add a note to make that clear to readers. If you need further guidance/clarification,   see #Perl and #Python for solutions that use implicit short-circuiting loops,   and #Raku for a solution that gets away with simply using a built-in language feature. 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
#zonnon
zonnon
  module CompareStrings; type Vector = array * of string; var v,w: Vector; i: integer; all,ascending: boolean; begin v := new Vector(3); v[0] := "uno"; v[1] := "uno"; v[2] := "uno";   all := true; for i := 1 to len(v) - 1 do all := all & (v[i - 1] = v[i]); end;   w := new Vector(3); w[0] := "abc"; w[1] := "bcd"; w[2] := "cde"; v := w; ascending := true; for i := 1 to len(v) - 1 do ascending := ascending & (v[i - 1] <= v[i]) end;   write("all equals?: ");writeln(all); write("ascending?: ");writeln(ascending) end CompareStrings.  
http://rosettacode.org/wiki/Compare_a_list_of_strings
Compare a list of strings
Task Given a   list   of arbitrarily many strings, show how to:   test if they are all lexically equal   test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order) Each of those two tests should result in a single true or false value, which could be used as the condition of an   if   statement or similar. If the input list has less than two elements, the tests should always return true. There is no need to provide a complete program and output. Assume that the strings are already stored in an array/list/sequence/tuple variable (whatever is most idiomatic) with the name   strings,   and just show the expressions for performing those two tests on it (plus of course any includes and custom functions etc. that it needs),   with as little distractions as possible. Try to write your solution in a way that does not modify the original list,   but if it does then please add a note to make that clear to readers. If you need further guidance/clarification,   see #Perl and #Python for solutions that use implicit short-circuiting loops,   and #Raku for a solution that gets away with simply using a built-in language feature. 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
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 FOR j=160 TO 200 STEP 10 20 RESTORE j 30 READ n 40 LET test1=1: LET test2=1 50 FOR i=1 TO n 60 READ a$ 70 PRINT a$;" "; 80 IF i=1 THEN GO TO 110 90 IF p$<>a$ THEN LET test1=0 100 IF p$>=a$ THEN LET test2=0 110 LET p$=a$ 120 NEXT i 130 PRINT 'test1'test2 140 NEXT j 150 STOP 160 DATA 3,"AA","BB","CC" 170 DATA 3,"AA","AA","AA" 180 DATA 3,"AA","CC","BB" 190 DATA 4,"AA","ACB","BB","CC" 200 DATA 1,"single_element"
http://rosettacode.org/wiki/Comma_quibbling
Comma quibbling
Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}". An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}". An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}". An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}". Test your function with the following series of inputs showing your output here on this page: [] # (No input words). ["ABC"] ["ABC", "DEF"] ["ABC", "DEF", "G", "H"] Note: Assume words are non-empty strings of uppercase characters for this task.
#PARI.2FGP
PARI/GP
comma(v)={ if(#v==0, return("{}")); if(#v==1, return(Str("{"v[1]"}"))); my(s=Str("{",v[1])); for(i=2,#v-1,s=Str(s,", ",v[i])); Str(s," and ",v[#v],"}") }; comma([]) comma(["ABC"]) comma(["ABC", "DEF"]) comma(["ABC", "DEF", "G", "H"])
http://rosettacode.org/wiki/Combinations_with_repetitions
Combinations with repetitions
The set of combinations with repetitions is computed from a set, S {\displaystyle S} (of cardinality n {\displaystyle n} ), and a size of resulting selection, k {\displaystyle k} , by reporting the sets of cardinality k {\displaystyle k} where each member of those sets is chosen from S {\displaystyle S} . In the real world, it is about choosing sets where there is a “large” supply of each type of element and where the order of choice does not matter. For example: Q: How many ways can a person choose two doughnuts from a store selling three types of doughnut: iced, jam, and plain? (i.e., S {\displaystyle S} is { i c e d , j a m , p l a i n } {\displaystyle \{\mathrm {iced} ,\mathrm {jam} ,\mathrm {plain} \}} , | S | = 3 {\displaystyle |S|=3} , and k = 2 {\displaystyle k=2} .) A: 6: {iced, iced}; {iced, jam}; {iced, plain}; {jam, jam}; {jam, plain}; {plain, plain}. Note that both the order of items within a pair, and the order of the pairs given in the answer is not significant; the pairs represent multisets. Also note that doughnut can also be spelled donut. Task Write a function/program/routine/.. to generate all the combinations with repetitions of n {\displaystyle n} types of things taken k {\displaystyle k} at a time and use it to show an answer to the doughnut example above. For extra credit, use the function to compute and show just the number of ways of choosing three doughnuts from a choice of ten types of doughnut. Do not show the individual choices for this part. References k-combination with repetitions See also The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Unimportant Order Important Without replacement ( n k ) = n C k = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} Task: Combinations Task: Permutations With replacement ( n + k − 1 k ) = n + k − 1 C k = ( n + k − 1 ) ! ( n − 1 ) ! k ! {\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}} n k {\displaystyle n^{k}} Task: Combinations with repetitions Task: Permutations with repetitions
#Wren
Wren
var combrep // recursive combrep = Fn.new { |n, lst| if (n == 0 ) return [[]] if (lst.count == 0) return [] var r = combrep.call(n, lst[1..-1]) for (x in combrep.call(n-1, lst)) { var y = x.toList y.add(lst[0]) r.add(y) } return r }   System.print(combrep.call(2, ["iced", "jam", "plain"])) System.print(combrep.call(3, (1..10).toList).count)
http://rosettacode.org/wiki/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#Racket
Racket
#lang racket (current-command-line-arguments)
http://rosettacode.org/wiki/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#Raku
Raku
# with arguments supplied $ raku -e 'sub MAIN($x, $y) { say $x + $y }' 3 5 8   # missing argument: $ raku -e 'sub MAIN($x, $y) { say $x + $y }' 3 Usage: -e '...' x y
http://rosettacode.org/wiki/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#RapidQ
RapidQ
PRINT "This program is named "; Command$(0) FOR i=1 TO CommandCount PRINT "The argument "; i; " is "; Command$(i) NEXT i
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#Gambas
Gambas
  ' This whole line is a comment and is ignored by the gambas interpreter print "Hello" ' Comments after an apostrophe are ignored '' A bold-style comment ' TODO: To Do comment will appear in Task Bar ' FIXME: Fix Me comment will appear in Task Bar ' NOTE: Note commnet will appear in Task Bar  
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#GAP
GAP
# Comment (till end of line)
http://rosettacode.org/wiki/Conway%27s_Game_of_Life
Conway's Game of Life
The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead,   in an   m-by-m   (or m×m)   square array of cells. We calculate   N   - the sum of live cells in C's   eight-location neighbourhood,   then cell   C   is alive or dead in the next generation based on the following table: C N new C 1 0,1 -> 0 # Lonely 1 4,5,6,7,8 -> 0 # Overcrowded 1 2,3 -> 1 # Lives 0 3 -> 1 # It takes three to give birth! 0 0,1,2,4,5,6,7,8 -> 0 # Barren Assume cells beyond the boundary are always dead. The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players.   One interacts with the Game of Life by creating an initial configuration and observing how it evolves. Task Although you should test your implementation on more complex examples such as the   glider   in a larger universe,   show the action of the blinker   (three adjoining cells in a row all alive),   over three generations, in a 3 by 3 grid. References   Its creator John Conway, explains   the game of life.   Video from numberphile on youtube.   John Conway   Inventing Game of Life   - Numberphile video. Related task   Langton's ant   - another well known cellular automaton.
#OCaml
OCaml
let get g x y = try g.(x).(y) with _ -> 0   let neighbourhood g x y = (get g (x-1) (y-1)) + (get g (x-1) (y )) + (get g (x-1) (y+1)) + (get g (x ) (y-1)) + (get g (x ) (y+1)) + (get g (x+1) (y-1)) + (get g (x+1) (y )) + (get g (x+1) (y+1))   let next_cell g x y = let n = neighbourhood g x y in match g.(x).(y), n with | 1, 0 | 1, 1 -> 0 (* lonely *) | 1, 4 | 1, 5 | 1, 6 | 1, 7 | 1, 8 -> 0 (* overcrowded *) | 1, 2 | 1, 3 -> 1 (* lives *) | 0, 3 -> 1 (* get birth *) | _ (* 0, (0|1|2|4|5|6|7|8) *) -> 0 (* barren *)   let copy g = Array.map Array.copy g   let next g = let width = Array.length g and height = Array.length g.(0) and new_g = copy g in for x = 0 to pred width do for y = 0 to pred height do new_g.(x).(y) <- (next_cell g x y) done done; (new_g)   let print g = let width = Array.length g and height = Array.length g.(0) in for x = 0 to pred width do for y = 0 to pred height do if g.(x).(y) = 0 then print_char '.' else print_char 'o' done; print_newline() done
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include if-then-else and switch. Less common are arithmetic if, ternary operator and Hash-based conditionals. Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
#Fancy
Fancy
if: (x < y) then: { "x < y!" println # will only execute this block if x < y }  
http://rosettacode.org/wiki/Comma_quibbling
Comma quibbling
Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}". An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}". An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}". An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}". Test your function with the following series of inputs showing your output here on this page: [] # (No input words). ["ABC"] ["ABC", "DEF"] ["ABC", "DEF", "G", "H"] Note: Assume words are non-empty strings of uppercase characters for this task.
#Pascal
Pascal
  program CommaQuibbling;   uses SysUtils, Classes, StrUtils;   const OuterBracket =['[', ']'];   type   {$IFNDEF FPC} SizeInt = LongInt; {$ENDIF}       { TCommaQuibble }   TCommaQuibble = class(TStringList) private function GetCommaquibble: string; procedure SetCommaQuibble(AValue: string); public property CommaQuibble: string read GetCommaquibble write SetCommaQuibble; end;   {$IFNDEF FPC} // Delphi support   function WordPosition(const N: Integer; const S: string; const WordDelims: TSysCharSet): SizeInt; var PS, P, PE: PChar; Count: Integer; begin Result := 0; Count := 0; PS := PChar(pointer(S)); PE := PS + Length(S); P := PS; while (P < PE) and (Count <> N) do begin while (P < PE) and (P^ in WordDelims) do inc(P); if (P < PE) then inc(Count); if (Count <> N) then while (P < PE) and not (P^ in WordDelims) do inc(P) else Result := (P - PS) + 1; end; end;   function ExtractWordPos(N: Integer; const S: string; const WordDelims: TSysCharSet; out Pos: Integer): string; var i, j, l: SizeInt; begin j := 0; i := WordPosition(N, S, WordDelims); if (i > High(Integer)) then begin Result := ''; Pos := -1; Exit; end; Pos := i; if (i <> 0) then begin j := i; l := Length(S); while (j <= l) and not (S[j] in WordDelims) do inc(j); end; SetLength(Result, j - i); if ((j - i) > 0) then Result := copy(S, i, j - i); end;   function ExtractWord(N: Integer; const S: string; const WordDelims: TSysCharSet): string; inline; var i: SizeInt; begin Result := ExtractWordPos(N, S, WordDelims, i); end; {$ENDIF}   { TCommaQuibble }   procedure TCommaQuibble.SetCommaQuibble(AValue: string); begin AValue := ExtractWord(1, AValue, OuterBracket); commatext := AValue; end;   function TCommaQuibble.GetCommaquibble: string; var x: Integer; Del: string; begin result := ''; Del := ', '; for x := 0 to Count - 1 do begin result := result + Strings[x]; if x = Count - 2 then Del := ' and ' else if x = Count - 1 then Del := ''; result := result + Del; end; result := '{' + result + '}'; end;   const TestData: array[0..7] of string = ('[]', '["ABC"]', '["ABC", "DEF"]', '["ABC", "DEF", "G", "H"]', '', '"ABC"', '"ABC", "DEF"', '"ABC", "DEF", "G", "H"');   var Quibble: TCommaQuibble; TestString: string;   begin Quibble := TCommaQuibble.Create;   for TestString in TestData do begin Quibble.CommaQuibble := TestString; writeln(Quibble.CommaQuibble); end; end.
http://rosettacode.org/wiki/Combinations_with_repetitions
Combinations with repetitions
The set of combinations with repetitions is computed from a set, S {\displaystyle S} (of cardinality n {\displaystyle n} ), and a size of resulting selection, k {\displaystyle k} , by reporting the sets of cardinality k {\displaystyle k} where each member of those sets is chosen from S {\displaystyle S} . In the real world, it is about choosing sets where there is a “large” supply of each type of element and where the order of choice does not matter. For example: Q: How many ways can a person choose two doughnuts from a store selling three types of doughnut: iced, jam, and plain? (i.e., S {\displaystyle S} is { i c e d , j a m , p l a i n } {\displaystyle \{\mathrm {iced} ,\mathrm {jam} ,\mathrm {plain} \}} , | S | = 3 {\displaystyle |S|=3} , and k = 2 {\displaystyle k=2} .) A: 6: {iced, iced}; {iced, jam}; {iced, plain}; {jam, jam}; {jam, plain}; {plain, plain}. Note that both the order of items within a pair, and the order of the pairs given in the answer is not significant; the pairs represent multisets. Also note that doughnut can also be spelled donut. Task Write a function/program/routine/.. to generate all the combinations with repetitions of n {\displaystyle n} types of things taken k {\displaystyle k} at a time and use it to show an answer to the doughnut example above. For extra credit, use the function to compute and show just the number of ways of choosing three doughnuts from a choice of ten types of doughnut. Do not show the individual choices for this part. References k-combination with repetitions See also The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Unimportant Order Important Without replacement ( n k ) = n C k = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} Task: Combinations Task: Permutations With replacement ( n + k − 1 k ) = n + k − 1 C k = ( n + k − 1 ) ! ( n − 1 ) ! k ! {\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}} n k {\displaystyle n^{k}} Task: Combinations with repetitions Task: Permutations with repetitions
#XPL0
XPL0
code ChOut=8, CrLf=9, IntOut=11, Text=12; int Count, Array(10);   proc Combos(D, S, K, N, Names); \Generate all size K combinations of N objects int D, S, K, N, Names; \depth of recursion, starting value of N, etc. int I; [if D<K then \depth < size [for I:= S to N-1 do [Array(D):= I; Combos(D+1, I, K, N, Names); ]; ] else [Count:= Count+1; if Names(0) then [for I:= 0 to K-1 do [Text(0, Names(Array(I))); ChOut(0, ^ )]; CrLf(0); ]; ]; ];   [Count:= 0; Combos(0, 0, 2, 3, ["iced", "jam", "plain"]); Text(0, "Combos = "); IntOut(0, Count); CrLf(0); Count:= 0; Combos(0, 0, 3, 10, [0]); Text(0, "Combos = "); IntOut(0, Count); CrLf(0); ]
http://rosettacode.org/wiki/Combinations_with_repetitions
Combinations with repetitions
The set of combinations with repetitions is computed from a set, S {\displaystyle S} (of cardinality n {\displaystyle n} ), and a size of resulting selection, k {\displaystyle k} , by reporting the sets of cardinality k {\displaystyle k} where each member of those sets is chosen from S {\displaystyle S} . In the real world, it is about choosing sets where there is a “large” supply of each type of element and where the order of choice does not matter. For example: Q: How many ways can a person choose two doughnuts from a store selling three types of doughnut: iced, jam, and plain? (i.e., S {\displaystyle S} is { i c e d , j a m , p l a i n } {\displaystyle \{\mathrm {iced} ,\mathrm {jam} ,\mathrm {plain} \}} , | S | = 3 {\displaystyle |S|=3} , and k = 2 {\displaystyle k=2} .) A: 6: {iced, iced}; {iced, jam}; {iced, plain}; {jam, jam}; {jam, plain}; {plain, plain}. Note that both the order of items within a pair, and the order of the pairs given in the answer is not significant; the pairs represent multisets. Also note that doughnut can also be spelled donut. Task Write a function/program/routine/.. to generate all the combinations with repetitions of n {\displaystyle n} types of things taken k {\displaystyle k} at a time and use it to show an answer to the doughnut example above. For extra credit, use the function to compute and show just the number of ways of choosing three doughnuts from a choice of ten types of doughnut. Do not show the individual choices for this part. References k-combination with repetitions See also The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Unimportant Order Important Without replacement ( n k ) = n C k = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} Task: Combinations Task: Permutations With replacement ( n + k − 1 k ) = n + k − 1 C k = ( n + k − 1 ) ! ( n − 1 ) ! k ! {\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}} n k {\displaystyle n^{k}} Task: Combinations with repetitions Task: Permutations with repetitions
#zkl
zkl
fcn combosK(k,seq){ // repeats, seq is finite if (k==1) return(seq); if (not seq) return(T); self.fcn(k-1,seq).apply(T.extend.fp(seq[0])).extend(self.fcn(k,seq[1,*])); }
http://rosettacode.org/wiki/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#Raven
Raven
ARGS print   stack (6 items) 0 => "raven" 1 => "myprogram" 2 => "-c" 3 => "alpha beta" 4 => "-h" 5 => "gamma"
http://rosettacode.org/wiki/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#REALbasic
REALbasic
Function Run(args() as String) As Integer For each arg As String In args Stdout.WriteLine(arg) Next End Function
http://rosettacode.org/wiki/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#REXX
REXX
say 'command arguments:' say arg(1)
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#gecho
gecho
( this is a test comment... o.O ) 1 2 + .
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#Gema
Gema
! comment starts with "!" and continues to end of line
http://rosettacode.org/wiki/Conway%27s_Game_of_Life
Conway's Game of Life
The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead,   in an   m-by-m   (or m×m)   square array of cells. We calculate   N   - the sum of live cells in C's   eight-location neighbourhood,   then cell   C   is alive or dead in the next generation based on the following table: C N new C 1 0,1 -> 0 # Lonely 1 4,5,6,7,8 -> 0 # Overcrowded 1 2,3 -> 1 # Lives 0 3 -> 1 # It takes three to give birth! 0 0,1,2,4,5,6,7,8 -> 0 # Barren Assume cells beyond the boundary are always dead. The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players.   One interacts with the Game of Life by creating an initial configuration and observing how it evolves. Task Although you should test your implementation on more complex examples such as the   glider   in a larger universe,   show the action of the blinker   (three adjoining cells in a row all alive),   over three generations, in a 3 by 3 grid. References   Its creator John Conway, explains   the game of life.   Video from numberphile on youtube.   John Conway   Inventing Game of Life   - Numberphile video. Related task   Langton's ant   - another well known cellular automaton.
#OCTAVE
OCTAVE
  clear all x=55; % Size of the Lattice (same as LAWE)   z(1:1:x^2)=0; % Initialise the binary lattice z_prime=z; % prepare the z prime   idx=7*x+2; % Origin z(idx+4)=1; % Populate the binary lattice with the Gosper Glider z(idx+x+4)=1; z(idx+1+4)=1; z(idx+x+1+4)=1;   z(idx+14)=1; z(idx+14+x)=1; z(idx+14+x+x)=1; z(idx+15+x+x+x)=1; z(idx+15-x)=1; z(idx+16-x-x)=1; z(idx+16+x+x+x+x)=1; z(idx+17-x-x)=1; z(idx+17+x+x+x+x)=1;   z(idx+18+x)=1; z(idx+19-x)=1; z(idx+19+x+x+x)=1; z(idx+20)=1; z(idx+20+x)=1; z(idx+20+x+x)=1; z(idx+21+x)=1;   z(idx+24)=1; z(idx+25)=1; z(idx+24-x)=1; z(idx+25-x)=1; z(idx+24-x-x)=1; z(idx+25-x-x)=1; z(idx+26-x-x-x)=1; z(idx+26+x)=1; z(idx+28-x-x-x)=1; z(idx+28+x)=1; z(idx+28-x-x-x-x)=1; z(idx+28+x+x)=1;   z(idx+38)=1; z(idx+38-x)=1; z(idx+39)=1; z(idx-x+39)=1;         for k=1:1:80; % Number of frames for n=x+2:1:x^2-x-1; % one time pass   theta=0; % Sum the surrounding area (top equation) for c=n-1:1:n+1; for m=-1:1:1; theta=theta+z(m*x+c); endfor endfor   z_prime(n)= round(1/5*(z(n)*acos(sin(pi/4*(theta-z(n)-9/2))) + (1-z(n)) * acos(sin(pi/4*(theta-z(n) + 3))))); % bottom equation   endfor   figure(2) title('GOL','FontWeight','bold'); xlabel("X"); ylabel("Y"); imagesc(reshape(z,x,x)') z=z_prime; pause % each press advances the algorithm one step endfor  
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include if-then-else and switch. Less common are arithmetic if, ternary operator and Hash-based conditionals. Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
#Forth
Forth
( condition ) IF ( true statements ) THEN ( condition ) IF ( true statements ) ELSE ( false statements ) THEN
http://rosettacode.org/wiki/Comma_quibbling
Comma quibbling
Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}". An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}". An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}". An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}". Test your function with the following series of inputs showing your output here on this page: [] # (No input words). ["ABC"] ["ABC", "DEF"] ["ABC", "DEF", "G", "H"] Note: Assume words are non-empty strings of uppercase characters for this task.
#Perl
Perl
sub comma_quibbling(@) { return "{$_}" for @_ < 2 ? "@_" : join(', ', @_[0..@_-2]) . ' and ' . $_[-1]; }   print comma_quibbling(@$_), "\n" for [], [qw(ABC)], [qw(ABC DEF)], [qw(ABC DEF G H)];
http://rosettacode.org/wiki/Comma_quibbling
Comma quibbling
Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}". An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}". An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}". An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}". Test your function with the following series of inputs showing your output here on this page: [] # (No input words). ["ABC"] ["ABC", "DEF"] ["ABC", "DEF", "G", "H"] Note: Assume words are non-empty strings of uppercase characters for this task.
#Phix
Phix
function quibble(sequence words) if length(words)>=2 then words[-2..-1] = {words[-2]&" and "&words[-1]} end if return "{"&join(words,", ")&"}" end function constant tests = {{}, {"ABC"}, {"ABC","DEF"}, {"ABC","DEF","G","H"}} for i=1 to length(tests) do ?quibble(tests[i]) end for
http://rosettacode.org/wiki/Combinations_with_repetitions
Combinations with repetitions
The set of combinations with repetitions is computed from a set, S {\displaystyle S} (of cardinality n {\displaystyle n} ), and a size of resulting selection, k {\displaystyle k} , by reporting the sets of cardinality k {\displaystyle k} where each member of those sets is chosen from S {\displaystyle S} . In the real world, it is about choosing sets where there is a “large” supply of each type of element and where the order of choice does not matter. For example: Q: How many ways can a person choose two doughnuts from a store selling three types of doughnut: iced, jam, and plain? (i.e., S {\displaystyle S} is { i c e d , j a m , p l a i n } {\displaystyle \{\mathrm {iced} ,\mathrm {jam} ,\mathrm {plain} \}} , | S | = 3 {\displaystyle |S|=3} , and k = 2 {\displaystyle k=2} .) A: 6: {iced, iced}; {iced, jam}; {iced, plain}; {jam, jam}; {jam, plain}; {plain, plain}. Note that both the order of items within a pair, and the order of the pairs given in the answer is not significant; the pairs represent multisets. Also note that doughnut can also be spelled donut. Task Write a function/program/routine/.. to generate all the combinations with repetitions of n {\displaystyle n} types of things taken k {\displaystyle k} at a time and use it to show an answer to the doughnut example above. For extra credit, use the function to compute and show just the number of ways of choosing three doughnuts from a choice of ten types of doughnut. Do not show the individual choices for this part. References k-combination with repetitions See also The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Unimportant Order Important Without replacement ( n k ) = n C k = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} Task: Combinations Task: Permutations With replacement ( n + k − 1 k ) = n + k − 1 C k = ( n + k − 1 ) ! ( n − 1 ) ! k ! {\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}} n k {\displaystyle n^{k}} Task: Combinations with repetitions Task: Permutations with repetitions
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 READ n 20 DIM d$(n,5) 30 FOR i=1 TO n 40 READ d$(i) 50 NEXT i 60 DATA 3,"iced","jam","plain" 70 FOR i=1 TO n 80 FOR j=i TO n 90 PRINT d$(i);" ";d$(j) 100 NEXT j 110 NEXT i
http://rosettacode.org/wiki/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#Ring
Ring
  see copy("=",30) + nl see "Command Line Parameters" + nl see "Size : " + len(sysargv) + nl see sysargv see copy("=",30) + nl for x = 1 to len(sysargv) see x + nl next  
http://rosettacode.org/wiki/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#Ruby
Ruby
#! /usr/bin/env ruby p ARGV
http://rosettacode.org/wiki/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#Rust
Rust
use std::env;   fn main(){ let args: Vec<_> = env::args().collect(); println!("{:?}", args); }
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#Genie
Genie
// Comment continues until end of line   /* Comment lasts between delimiters */
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#GML
GML
// comment starts with "//" and continues to the end of the line
http://rosettacode.org/wiki/Conway%27s_Game_of_Life
Conway's Game of Life
The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead,   in an   m-by-m   (or m×m)   square array of cells. We calculate   N   - the sum of live cells in C's   eight-location neighbourhood,   then cell   C   is alive or dead in the next generation based on the following table: C N new C 1 0,1 -> 0 # Lonely 1 4,5,6,7,8 -> 0 # Overcrowded 1 2,3 -> 1 # Lives 0 3 -> 1 # It takes three to give birth! 0 0,1,2,4,5,6,7,8 -> 0 # Barren Assume cells beyond the boundary are always dead. The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players.   One interacts with the Game of Life by creating an initial configuration and observing how it evolves. Task Although you should test your implementation on more complex examples such as the   glider   in a larger universe,   show the action of the blinker   (three adjoining cells in a row all alive),   over three generations, in a 3 by 3 grid. References   Its creator John Conway, explains   the game of life.   Video from numberphile on youtube.   John Conway   Inventing Game of Life   - Numberphile video. Related task   Langton's ant   - another well known cellular automaton.
#Ol
Ol
  #!/usr/bin/ol (import (otus random!))   (define MAX 65536) ; should be power of two ; size of game board (should be less than MAX) (define WIDTH 170) (define HEIGHT 96)   ; helper function (define (hash x y) (let ((x (mod (+ x WIDTH) WIDTH)) (y (mod (+ y HEIGHT) HEIGHT))) (+ (* y MAX) x)))   ; helper function (define neighbors '( (-1 . -1) ( 0 . -1) ( 1 . -1) (-1 . 0) ( 1 . 0) (-1 . 1) ( 0 . 1) ( 1 . 1) ))   ; dead-or-alive cell test (define (alive gen x y) (case (fold (lambda (f xy) (+ f (get gen (hash (+ x (car xy)) (+ y (cdr xy))) 0))) 0 neighbors) (2 (get gen (hash x y) #false)) (3 #true)))   ; --------------- (import (lib gl2)) (gl:set-window-title "Convey's The game of Life")   (glShadeModel GL_SMOOTH) (glClearColor 0.11 0.11 0.11 1) (glOrtho 0 WIDTH 0 HEIGHT 0 1)   (glPointSize (/ 854 WIDTH))   ; generate random field (gl:set-userdata (list->ff (map (lambda (i) (let ((x (rand! WIDTH)) (y (rand! HEIGHT))) (cons (hash x y) 1))) (iota 2000)))) ; main game loop (gl:set-renderer (lambda (mouse) (let ((generation (gl:get-userdata))) (glClear GL_COLOR_BUFFER_BIT)   ; draw the cells (glColor3f 0.2 0.5 0.2) (glBegin GL_POINTS) (ff-fold (lambda (st key value) (glVertex2f (mod key MAX) (div key MAX)) ) #f generation) (glEnd)   (gl:set-userdata ; next cells generation (ff-fold (lambda (st key value) (let ((x (mod key MAX)) (y (div key MAX))) (fold (lambda (st key) (let ((x (+ x (car key))) (y (+ y (cdr key)))) (if (alive generation x y) (put st (hash x y) 1) st))) (if (alive generation x y) (put st (hash x y) 1) st) ; the cell neighbors))) #empty generation)))))  
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include if-then-else and switch. Less common are arithmetic if, ternary operator and Hash-based conditionals. Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
#Fortran
Fortran
if ( a .gt. 20.0 ) then q = q + a**2 else if ( a .ge. 0.0 ) then q = q + 2*a**3 else q = q - a end if
http://rosettacode.org/wiki/Comma_quibbling
Comma quibbling
Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}". An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}". An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}". An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}". Test your function with the following series of inputs showing your output here on this page: [] # (No input words). ["ABC"] ["ABC", "DEF"] ["ABC", "DEF", "G", "H"] Note: Assume words are non-empty strings of uppercase characters for this task.
#PHP
PHP
<?php   function quibble($arr){   $words = count($arr);   if($words == 0){ return '{}'; }elseif($words == 1){ return '{'.$arr[0].'}'; }elseif($words == 2){ return '{'.$arr[0].' and '.$arr[1].'}'; }else{ return '{'.implode(', ', array_splice($arr, 0, -1) ). ' and '.$arr[0].'}'; }   }     $tests = [ [], ["ABC"], ["ABC", "DEF"], ["ABC", "DEF", "G", "H"] ];   foreach ($tests as $test) { echo quibble($test) . PHP_EOL; }
http://rosettacode.org/wiki/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#S-lang
S-lang
variable a; foreach a (__argv) print(a);  
http://rosettacode.org/wiki/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#Sather
Sather
class MAIN is main(args:ARRAY{STR}) is loop #OUT + args.elt! + "\n"; end; end; end;
http://rosettacode.org/wiki/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#Scala
Scala
object CommandLineArguments extends App { println(s"Received the following arguments: + ${args.mkString("", ", ", ".")}") }
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#gnuplot
gnuplot
# this is a comment   # backslash continues \ a comment to the next \ line or lines
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#Go
Go
// this is a single line comment /* this is a multi-line block comment. /* It does not nest */
http://rosettacode.org/wiki/Conway%27s_Game_of_Life
Conway's Game of Life
The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead,   in an   m-by-m   (or m×m)   square array of cells. We calculate   N   - the sum of live cells in C's   eight-location neighbourhood,   then cell   C   is alive or dead in the next generation based on the following table: C N new C 1 0,1 -> 0 # Lonely 1 4,5,6,7,8 -> 0 # Overcrowded 1 2,3 -> 1 # Lives 0 3 -> 1 # It takes three to give birth! 0 0,1,2,4,5,6,7,8 -> 0 # Barren Assume cells beyond the boundary are always dead. The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players.   One interacts with the Game of Life by creating an initial configuration and observing how it evolves. Task Although you should test your implementation on more complex examples such as the   glider   in a larger universe,   show the action of the blinker   (three adjoining cells in a row all alive),   over three generations, in a 3 by 3 grid. References   Its creator John Conway, explains   the game of life.   Video from numberphile on youtube.   John Conway   Inventing Game of Life   - Numberphile video. Related task   Langton's ant   - another well known cellular automaton.
#ooRexx
ooRexx
/* REXX --------------------------------------------------------------- * 07.08.2014 Walter Pachl Conway's Game of life graphical * Input is a file containing the initial pattern. * The compute area is extended when needed * (i.e., when cells are born outside the current compute area) * When computing the pattern sequence is complete, the graphical * output starts and continues until Cancel is pressed. * 10.08.2014 WP fixed the output of what.txt *--------------------------------------------------------------------*/ Parse Arg what speed If what='?' Then Do Say 'Create a file containing the pattern to be processed' Say 'named somename.in (octagon.in such as this for the octagon):' Say ' ** ' Say ' * * ' Say ' * * ' Say '* *' Say '* *' Say ' * * ' Say ' * * ' Say ' ** ' Say 'Run the program by entering "rexx conlife somename [pause]"', 'on the command line.' Say '(pause is the amount of milliseconds between 2 pictures.', 'default is 1000)' Say 'A file somename.lst will be created.' Say 'Hereafter you will see the pattern''s development', 'in a new window.' Say 'Press the Cancel button to end the presentation.' Exit End Parse Version interpreter '_' level '(' If interpreter<>'REXX-ooRexx' Then Do Say interpreter level Say 'This program must be run with object Rexx.' Exit End If what='' Then what='octagon' If right(what,3)='.in' then what=left(what,length(what)-3) infile=what'.in' If lines(infile)=0 Then Do Say 'Input file' infile 'not found.' Say 'Enter conlife ? for help.' Exit End If speed='' Then speed=1000 .local~myspeed=speed   Call tl what --'type' what'.lst'   .local~title=what array=.local~myarrayData d = .drawDlg~new if d~initCode <> 0 then do say 'The Draw dialog was not created correctly. Aborting.' return d~initCode end d~execute("SHOWTOP") return 0   ::requires "ooDialog.cls"   ::class 'drawDlg' subclass UserDialog   ::attribute interrupted unguarded   ::method init expose walterFont   forward class (super) continue -- colornames: -- 1 dark red 7 light grey 13 red -- 2 dark green 8 pale green 14 light green -- 3 dark yellow 9 light blue 15 yellow -- 4 dark blue 10 white 16 blue -- 5 purple 11 grey 17 pink -- 6 blue grey 12 dark grey 18 turquoise   self~interrupted = .true   -- Create a font to write the nice big letters and digits opts = .directory~new opts~weight = 700 walterFont = self~createFontEx("Arial",14,opts) walterFont = self~createFontEx("Courier",18,opts)   if \self~createcenter(200, 235,"Walter's Clock", , ,"System",14) then self~initCode = 1   ::method defineDialog   self~createPushButton(/*IDC_PB_DRAW*/100, 0, 0,240,200,"DISABLED NOTAB") -- The drawing surface.   self~createPushButton(IDCANCEL,160,220, 35, 12,,"&Cancel")   ::method initDialog unguarded expose x y dc myPen change al. fid nn what array change = 0 x = self~factorx y = self~factory dc = self~getButtonDC(100) myPen = self~createPen(1,'solid',0) t = .TimeSpan~fromMicroSeconds(500000) -- .5 seconds msg = .Message~new(self,'life') alrm = .Alarm~new(t, msg) array=.local~myArrayData Do s=1 to array~items al.s=array[s] Parse Var al.s ' == ' al.s End nn=s-2 --say 'nn'nn Call lineout fid   ::method interrupt unguarded   self~interrupted = .true   ::method cancel unguarded -- Stop the drawing program and quit. expose x y self~hide self~interrupted = .true return self~cancel:super   ::method leaving unguarded -- Best place to clean up resources expose dc myPen walterFont   self~deleteObject(myPen) self~freeButtonDC(/*IDC_PB_DRAW*/100,dc) self~deleteFont(walterFont)   ::method life unguarded /* draw individual pixels */ expose x y dc myPen change walterFont al. nn what mx = trunc(20*x); my = trunc(20*y); size = 400   curPen = self~objectToDC(dc, myPen)   -- Select the nice big letters and digits into the device context to use to -- to write with: curFont = self~fontToDC(dc, walterFont)   -- Create a white brush and select it into the device to paint with. whiteBrush = self~createBrush(10) curBrush = self~objectToDC(dc, whiteBrush)   -- Paint the drawing area surface with the white brush self~rectangle(dc, 1, 1, 500, 600, 'FILL') self~writeDirect(dc, 10, 20,'Conway''s Game of Life') self~writeDirect(dc, 10, 40,.local~title) self~writeDirect(dc, 10,460,'Walter Pachl, 8 Aug 2014') dx=.local~dxval dy=.local~dyval do s=1 By 1 until self~interrupted self~transparentText(dc) self~interrupted = .false sm=s//nn+1 If s>1 Then Do ali=al.sb Do While ali<>'' Parse Var ali x ',' y ali zxa=(x+dx)*10 zya=(y+dy)*10 self~draw_square(dc,zxa,zya,3,10) End End self~draw_square(dc, 380, 10,100,10) self~writeDirect(dc, 340, 20,time()) self~writeDirect(dc, 340, 40,right(sm,2) 'of' right(nn,2)) ali=al.sm Do While ali<>'' Parse Var ali x ',' y ali zxa=(x+dx)*10 zya=(y+dy)*10 self~draw_square(dc,zxa,zya,3,5) End -- self~interrupted = .true sb=sm self~objectToDC(dc, curPen) self~objectToDC(dc, curBrush) call msSleep .local~myspeed --self~pause End   ::method pause j = msSleep(10)   ::method draw_square Use Arg dc, x, y, d, c Do zx=x-d to x+d Do zy=y-d to y+d self~drawPixel(dc, zx, zy, c) End End   ::method quot Parse Arg x,y If y=0 Then Return '???' Else Return x/y   ::routine tl /* REXX --------------------------------------------------------------- * 02.08.2014 Walter Pachl * Input is a file containing the initial pattern * The compute area is extended when needed * (cells are born outside the current compute area) * The program stops when the picture shown is the same as the first * or equal to the previous one *--------------------------------------------------------------------*/ Parse Arg f If f='' Then f='bipole' fid=f'.in' oid=f'.txt'; 'erase' oid oil=f'.lst'; 'erase' oil debug=0 If debug Then Do dbg=f'.xxx'; 'erase' dbg End ml=0 l.='' ol.='' Parse Value '10 10' With xb yb xc=copies(' ',xb) Do ri=yb+1 By 1 While lines(fid)>0 l.ri=xc||linein(fid) ml=max(ml,length(strip(l.ri,'T'))) End ri=ri-1 ml=ml+xb ri=ri+yb yy=ri a.=' ' b.=' ' m.='' x.='' list.='' Parse Value 1 ml 1 yy With xmi xma ymi yma Parse Value '-10 30 -10 30' With xmi xma ymi yma Parse Value '999 -999 999 -999 999 -999 999 -999', With xmin xmax ymin ymax xlo xhi ylo yhi Do y=1 To yy z=yy-y+1 l=l.z Do x=1 By 1 While l<>'' Parse Var l c +1 l If c='*' Then a.x.z='*' End End Call show Do step=1 To 60 Call store If step>1 & is_equal(step,1) Then Leave If step>1 & is_equal(step,step-1) Then Leave Call show_neighbors Do y=yma To ymi By -1 ol=format(x,3)' ' Do x=xmi To xma neighbors=neighbors(x,y) If a.x.y=' ' Then Do /* dead cell */ If neighbors=3 Then Do b.x.y='*' /* gets life */ mmo=xmi xma ymi yma xmi=min(xmi,x-1) xma=max(xma,x+1) ymi=min(ymi,y-1) yma=max(yma,y+1) mm=xmi xma ymi yma If mm<>mmo Then Call debug mmo '1->' mm End Else /* life cell */ b.x.y=' ' /* remains dead */ End Else Do /* life cell */ If neighbors=2 |, neighbors=3 Then Do b.x.y='*' /* remains life */ mmo=xmi xma ymi yma xmi=min(xmi,x-1) xma=max(xma,x+1) ymi=min(ymi,y-1) yma=max(yma,y+1) mm=xmi xma ymi yma If mm<>mmo Then Call debug mmo '2->' mm End Else b.x.y=' ' /* dies */ End End End /* b. is the new state and is now copied to a. */ Do y=yma To ymi By -1 Do x=xmi To xma a.x.y=b.x.y End End End /* Output name and all states */ Call lineout oid,' 'f st=' +' /* top and bottom border */ sb=' +' /* top and bottom border */ Do s=1 To step st=st||'-'right(s,2,'-')||copies('-',xmax-xmin-2)'+' sb=sb||copies('-',xmax-xmin+1)'+' End array=.array~new Do y=ymin To ymax Do s=1 To step Do x=xmin To xmax If substr(m.s.y,x,1)='*' Then Do xlo=min(xlo,x) xhi=max(xhi,x) ylo=min(ylo,y) yhi=max(yhi,y) End End End End Do y=ymin To ymax ol='' Do s=1 To step Do x=xmin To xmax If substr(m.s.y,x,1)='*' Then Do list.s=list.s (x-xlo+1)','||(y-ylo+1) End End array[s]=s '-' words(list.s) '==' list.s End --Call lineout oid,ol '|' .local~myArrayData=array End height=yhi-ylo+1 width=xhi-xlo+1 .local~dxval=(48-width)%2 .local~dyval=(48-height)%2 Call o st /* top border */ xl.='|' Do y=ymax To ymin By -1 Do s=1 To step xl.y=xl.y||substr(ol.s.y,xmin,xmax-xmin+1)'|' End End Do y=ymax To ymin By -1 Call o ' 'xl.y End Call o sb /* bottom border */ Call lineout oid Say 'frames are shown in' oid If debug Then Do Say 'original area' 1 ml '/' 1 yy Say 'compute area ' xmi xma '/' ymi yma Say 'used area ' xlo xhi '/' ylo yhi End Do s=1 To step call lineout oil,s '==>' words(list.s) '==' list.s End Return   o: Parse Arg lili Call lineout oid,lili Return   set: Parse Arg x,y a.x.y='*' Return   neighbors: Procedure Expose a. debug Parse Arg x,y neighbors=0 do xa=x-1 to x+1 do ya=y-1 to y+1 If xa<>x | ya<>y then If a.xa.ya='*' Then neighbors=neighbors+1 End End Return neighbors   store: /* store current state (a.) in lines m.step.* */ Do y=yma To ymi By -1 ol='' Do x=xmi To xma z=a.x.y ol=ol||z End x.step.y=ol If ol<>'' then Do ymin=min(ymin,y) ymax=max(ymax,y) p=pos('*',ol) q=length(strip(ol,'T')) If p>0 Then xmin=min(xmin,p) xmax=max(xmax,q) End m.step.y=ol ol.step.y=ol --If pos('*',ol)>0 Then Do -- Say '====>' right(step,2) right(y,3) '>'ol'<' xmin xmax -- Say ' 'copies('1234567890',3) -- End End Return   is_equal: /* test ist state a.b is equal to state a.a */ Parse Arg a,b Do y=yy To 1 By -1 If x.b.y<>x.a.y Then Return 0 End Return 1   show: Procedure Expose dbg a. yy ml debug Do y=-5 To 13 ol='>' Do x=-5 To 13 ol=ol||a.x.y End Call debug ol End Return   show_neighbors: Procedure Expose a. xmi xma ymi yma dbg debug Do y=yma To ymi By -1 ol=format(y,3)' ' Do x=xmi To xma ol=ol||neighbors(x,y) End Call debug ol End Return   debug: If debug Then Return lineout(dbg,arg(1)) Else Return  
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include if-then-else and switch. Less common are arithmetic if, ternary operator and Hash-based conditionals. Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
#FreeBASIC
FreeBASIC
Dim a As Integer = 1 If a = 1 Then sub1 ElseIf a = 2 Then sub2 Else sub3 End If
http://rosettacode.org/wiki/Comma_quibbling
Comma quibbling
Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}". An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}". An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}". An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}". Test your function with the following series of inputs showing your output here on this page: [] # (No input words). ["ABC"] ["ABC", "DEF"] ["ABC", "DEF", "G", "H"] Note: Assume words are non-empty strings of uppercase characters for this task.
#PicoLisp
PicoLisp
(for L '([] ["ABC"] ["ABC", "DEF"] ["ABC", "DEF", "G", "H"]) (let H (head -1 L) (prinl "{" (glue ", " H) (and H " and ") (last L) "}" ) ) )
http://rosettacode.org/wiki/Comma_quibbling
Comma quibbling
Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}". An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}". An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}". An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}". Test your function with the following series of inputs showing your output here on this page: [] # (No input words). ["ABC"] ["ABC", "DEF"] ["ABC", "DEF", "G", "H"] Note: Assume words are non-empty strings of uppercase characters for this task.
#PL.2FI
PL/I
*process or(!); quib: Proc Options(main); /********************************************************************* * 06.10.2013 Walter Pachl *********************************************************************/ put Edit*process or(!); quib: Proc Options(main); /********************************************************************* * 06.10.2013 Walter Pachl * 07.10.2013 -"- change "Oxford comma" to and *********************************************************************/ put Edit(quibbling(''))(Skip,a); put Edit(quibbling('ABC'))(Skip,a); put Edit(quibbling('ABC DEF'))(Skip,a); put Edit(quibbling('ABC DEF G H'))(Skip,a); return;   quibbling: proc(s) Returns(Char(100) Var); Dcl s Char(*); Dcl result Char(100) Var Init(''); Dcl word(10) Char(100) Var; Dcl (wi,p) Bin Fixed(31); If s='' Then result=''; Else Do; Do wi=1 By 1 While(s^=''); p=index(s,' '); if p=0 Then Do; word(wi)=s; s=''; End; Else Do; word(wi)=left(s,p-1); s=substr(s,p+1); End; end; wn=wi-1; result=word(1); Do i=2 To wn-1; result=result!!', '!!word(i); End; If wn>1 Then result=result!!' and '!!word(wn); End; Return('{'!!result!!'}'); End; End;
http://rosettacode.org/wiki/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#Scheme
Scheme
(define (main args) (for-each (lambda (arg) (display arg) (newline)) args))
http://rosettacode.org/wiki/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#Seed7
Seed7
$ include "seed7_05.s7i";   const proc: main is func local var integer: i is 0; begin writeln("This program is named " <& name(PROGRAM) <& "."); for i range 1 to length(argv(PROGRAM)) do writeln("The argument #" <& i <& " is " <& argv(PROGRAM)[i]); end for; end func;
http://rosettacode.org/wiki/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#Sidef
Sidef
say ARGV;
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#Golfscript
Golfscript
# end of line comment
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#Gri
Gri
# this is a comment show 123 # this too is a comment
http://rosettacode.org/wiki/Conway%27s_Game_of_Life
Conway's Game of Life
The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead,   in an   m-by-m   (or m×m)   square array of cells. We calculate   N   - the sum of live cells in C's   eight-location neighbourhood,   then cell   C   is alive or dead in the next generation based on the following table: C N new C 1 0,1 -> 0 # Lonely 1 4,5,6,7,8 -> 0 # Overcrowded 1 2,3 -> 1 # Lives 0 3 -> 1 # It takes three to give birth! 0 0,1,2,4,5,6,7,8 -> 0 # Barren Assume cells beyond the boundary are always dead. The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players.   One interacts with the Game of Life by creating an initial configuration and observing how it evolves. Task Although you should test your implementation on more complex examples such as the   glider   in a larger universe,   show the action of the blinker   (three adjoining cells in a row all alive),   over three generations, in a 3 by 3 grid. References   Its creator John Conway, explains   the game of life.   Video from numberphile on youtube.   John Conway   Inventing Game of Life   - Numberphile video. Related task   Langton's ant   - another well known cellular automaton.
#Oz
Oz
declare Rules = [rule(c:1 n:[0 1] new:0) %% Lonely rule(c:1 n:[4 5 6 7 8] new:0) %% Overcrowded rule(c:1 n:[2 3] new:1) %% Lives rule(c:0 n:[3] new:1) %% It takes three to give birth! rule(c:0 n:[0 1 2 4 5 6 7 8] new:0) %% Barren ]   Blinker = ["..." "###" "..."]   Toad = ["...." ".###" "###." "...."]   Glider = [".#.........." "..#........." "###........." "............" "............" "............" "............" "............" "............" "............" "............"]   Init = Blinker MaxGen = 2   %% G(i) -> G(i+1) fun {Evolve Gi} fun {Get X#Y} Row = {CondSelect Gi Y unit} in {CondSelect Row X 0} %% cells beyond boundaries are dead (0) end fun {GetNeighbors X Y} {Map [X-1#Y-1 X#Y-1 X+1#Y-1 X-1#Y X+1#Y X-1#Y+1 X#Y+1 X+1#Y+1] Get} end in {Record.mapInd Gi fun {$ Y Row} {Record.mapInd Row fun {$ X C} N = {Sum {GetNeighbors X Y}} in for Rule in Rules return:Return do if C == Rule.c andthen {Member N Rule.n} then {Return Rule.new} end end end} end} end   %% For example: [".#" %% "#."] -> grid(1:row(1:0 2:1) 2:row(1:1 2:0)) fun {ReadG LinesList} {List.toTuple grid {Map LinesList fun {$ Line} {List.toTuple row {Map Line fun {$ C} if C == &. then 0 elseif C == &# then 1 end end}} end}} end   %% Inverse to ReadG fun {ShowG G} {Map {Record.toList G} fun {$ Row} {Map {Record.toList Row} fun {$ C} if C == 0 then &. elseif C == 1 then &# end end} end} end   %% Helpers fun {Sum Xs} {FoldL Xs Number.'+' 0} end fun lazy {Iterate F V} V|{Iterate F {F V}} end   G0 = {ReadG Init} Gn = {Iterate Evolve G0} in for Gi in Gn I in 0..MaxGen do {System.showInfo "\nGen. "#I} {ForAll {ShowG Gi} System.showInfo} end
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include if-then-else and switch. Less common are arithmetic if, ternary operator and Hash-based conditionals. Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
#friendly_interactive_shell
friendly interactive shell
set var 'Hello World' if test $var = 'Hello World' echo 'Welcome.' else if test $var = 'Bye World' echo 'Bye.' else echo 'Huh?' end
http://rosettacode.org/wiki/Comma_quibbling
Comma quibbling
Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}". An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}". An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}". An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}". Test your function with the following series of inputs showing your output here on this page: [] # (No input words). ["ABC"] ["ABC", "DEF"] ["ABC", "DEF", "G", "H"] Note: Assume words are non-empty strings of uppercase characters for this task.
#PL.2FM
PL/M
100H:   /* COPY A STRING (MINUS TERMINATOR), RETURNS LENGTH (MINUS TERMINATOR) */ COPY$STR: PROCEDURE(SRC, DST) ADDRESS; DECLARE (SRC, DST) ADDRESS; DECLARE (SCH BASED SRC, DCH BASED DST) BYTE; DECLARE L ADDRESS; L = 0; DO WHILE SCH <> '$'; DCH = SCH; SRC = SRC + 1; DST = DST + 1; L = L + 1; END; RETURN L; END COPY$STR;   /* QUIBBLE GIVEN ARRAY OF $-TERMINATED STRINGS, STORE RESULT IN BUFR */ QUIBBLE: PROCEDURE(WORDS, BUFR) ADDRESS; DECLARE (WORDS, BUFR, ADR) ADDRESS; DECLARE (WORD BASED WORDS, WPTR) ADDRESS; DECLARE (WCHAR BASED WPTR, BCHAR BASED BUFR) BYTE;   /* BRACES AND LOWERCASE LETTERS ARE NOT WITHIN PL/M CHARSET */ DECLARE LBRACE LITERALLY '123', RBRACE LITERALLY '125'; DECLARE ANDSTR DATA (32,97,110,100,32,'$');   ADR = BUFR; BCHAR = LBRACE; BUFR = BUFR + 1; DO WHILE WORD <> 0; BUFR = BUFR + COPY$STR(WORD, BUFR); WORDS = WORDS + 2; IF WORD <> 0 THEN IF WORD(1) <> 0 THEN BUFR = BUFR + COPY$STR(.', $', BUFR); ELSE BUFR = BUFR + COPY$STR(.ANDSTR, BUFR); END; BCHAR = RBRACE; BUFR = BUFR + 1; BCHAR = '$'; RETURN ADR; END QUIBBLE;   /* --- CP/M OUTPUT AND TESTING --- */ BDOS: PROCEDURE(FUNC, ARG); /* MAKE CP/M SYSTEM CALL */ DECLARE FUNC BYTE, ARG ADDRESS; GO TO 5; END BDOS;   DECLARE BDOS$EXIT LITERALLY '0', /* EXIT TO CP/M */ BDOS$PUTS LITERALLY '9'; /* PRINT STRING */   PUTS: PROCEDURE(S); DECLARE S ADDRESS; CALL BDOS(BDOS$PUTS, S); CALL BDOS(BDOS$PUTS, .(13,10,'$')); END PUTS;   /* ARRAY WITH INITIALLY NO CONTENTS */ DECLARE ARR (5) ADDRESS INITIAL (0,0,0,0,0);   CALL PUTS(QUIBBLE(.ARR, .MEMORY)); /* NO STRINGS */ ARR(0) = .'ABC$'; CALL PUTS(QUIBBLE(.ARR, .MEMORY)); /* ABC */ ARR(1) = .'DEF$'; CALL PUTS(QUIBBLE(.ARR, .MEMORY)); /* ABC AND DEF */ ARR(2) = .'G$'; ARR(3) = .'H$'; CALL PUTS(QUIBBLE(.ARR, .MEMORY)); /* ABC, DEF, G AND H */   CALL BDOS(BDOS$EXIT, 0); EOF
http://rosettacode.org/wiki/Comma_quibbling
Comma quibbling
Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}". An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}". An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}". An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}". Test your function with the following series of inputs showing your output here on this page: [] # (No input words). ["ABC"] ["ABC", "DEF"] ["ABC", "DEF", "G", "H"] Note: Assume words are non-empty strings of uppercase characters for this task.
#Plain_English
Plain English
To quibble four words: Add "ABC" to some string things. Add "DEF" to the string things. Add "G" to the string things. Add "H" to the string things. Quibble the string things.   To quibble one word: Add "ABC" to some string things. Quibble the string things.   To quibble some string things: Quibble the string things giving a string. Destroy the string things. Write the string on the console.   To quibble some string things giving a string: Append "{" to the string. Put the string things' count into a count. If the count is 0, append "}" to the string; exit. Get a string thing from the string things. If the count is 1, append the string thing's string then "}" to the string; exit. Loop. If a counter is past the count minus 2, append the string thing's string then " and " then the string thing's next's string then "}" to the string; exit. Append the string thing's string then ", " to the string. Put the string thing's next into the string thing. Repeat.   To quibble two words: Add "ABC" to some string things. Add "DEF" to the string things. Quibble the string things.   To quibble zero words: Quibble some string things.   To run: Start up. Quibble zero words. Quibble one word. Quibble two words. Quibble four words. Wait for the escape key. Shut down.
http://rosettacode.org/wiki/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#Slate
Slate
StartupArguments do: [| :arg | inform: arg]
http://rosettacode.org/wiki/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#Smalltalk
Smalltalk
(1 to: Smalltalk getArgc) do: [ :i | (Smalltalk getArgv: i) displayNl ]
http://rosettacode.org/wiki/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#Standard_ML
Standard ML
print ("This program is named " ^ CommandLine.name () ^ ".\n"); val args = CommandLine.arguments (); Array.appi (fn (i, x) => print ("the argument #" ^ Int.toString (i+1) ^ " is " ^ x ^ "\n")) (Array.fromList args);
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#Groovy
Groovy
100 REM Standard BASIC comments begin with "REM" (remark) and extend to the end of the line 110 PRINT "this is code": REM comment after statement
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#GW-BASIC
GW-BASIC
100 REM Standard BASIC comments begin with "REM" (remark) and extend to the end of the line 110 PRINT "this is code": REM comment after statement
http://rosettacode.org/wiki/Conway%27s_Game_of_Life
Conway's Game of Life
The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead,   in an   m-by-m   (or m×m)   square array of cells. We calculate   N   - the sum of live cells in C's   eight-location neighbourhood,   then cell   C   is alive or dead in the next generation based on the following table: C N new C 1 0,1 -> 0 # Lonely 1 4,5,6,7,8 -> 0 # Overcrowded 1 2,3 -> 1 # Lives 0 3 -> 1 # It takes three to give birth! 0 0,1,2,4,5,6,7,8 -> 0 # Barren Assume cells beyond the boundary are always dead. The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players.   One interacts with the Game of Life by creating an initial configuration and observing how it evolves. Task Although you should test your implementation on more complex examples such as the   glider   in a larger universe,   show the action of the blinker   (three adjoining cells in a row all alive),   over three generations, in a 3 by 3 grid. References   Its creator John Conway, explains   the game of life.   Video from numberphile on youtube.   John Conway   Inventing Game of Life   - Numberphile video. Related task   Langton's ant   - another well known cellular automaton.
#PARI.2FGP
PARI/GP
step(M)={ my(N=M,W=matsize(M)[1],L=#M,t); for(l=1,W,for(w=1,L, t=sum(i=l-1,l+1,sum(j=w-1,w+1,if(i<1||j<1||i>W||j>L,0,M[i,j]))); N[l,w]=(t==3||(M[l,w]&&t==4)) )); N }; M=[0,1,0;0,1,0;0,1,0]; for(i=1,3,print(M);M=step(M))
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include if-then-else and switch. Less common are arithmetic if, ternary operator and Hash-based conditionals. Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
#Futhark
Futhark
  if <condition> then <truebranch> else <falsebranch>  
http://rosettacode.org/wiki/Comma_quibbling
Comma quibbling
Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}". An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}". An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}". An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}". Test your function with the following series of inputs showing your output here on this page: [] # (No input words). ["ABC"] ["ABC", "DEF"] ["ABC", "DEF", "G", "H"] Note: Assume words are non-empty strings of uppercase characters for this task.
#PowerShell
PowerShell
  function Out-Quibble { [OutputType([string])] Param ( # Zero or more strings. [Parameter(Mandatory=$false, Position=0)] [AllowEmptyString()] [string[]] $Text = "" )   # If not null or empty... if ($Text) { # Remove empty strings from the array. $text = "$Text".Split(" ", [StringSplitOptions]::RemoveEmptyEntries) } else { return "{}" }   # Build a format string. $outStr = "" for ($i = 0; $i -lt $text.Count; $i++) { $outStr += "{$i}, " } $outStr = $outStr.TrimEnd(", ")   # If more than one word, insert " and" at last comma position. if ($text.Count -gt 1) { $cIndex = $outStr.LastIndexOf(",") $outStr = $outStr.Remove($cIndex,1).Insert($cIndex," and") }   # Output the formatted string. "{" + $outStr -f $text + "}" }  
http://rosettacode.org/wiki/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#Swift
Swift
let args = Process.arguments println("This program is named \(args[0]).") println("There are \(args.count-1) arguments.") for i in 1..<args.count { println("the argument #\(i) is \(args[i])") }
http://rosettacode.org/wiki/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#Tailspin
Tailspin
  $ARGS -> !OUT::write  
http://rosettacode.org/wiki/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#Tcl
Tcl
if { $argc > 1 } { puts [lindex $argv 1] }
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#Haskell
Haskell
i code = True -- I am a comment.   {- I am also a comment. {-comments can be nested-} let u x = x x (this code not compiled) Are you? -}   -- |This is a Haddock documentation comment for the following code i code = True -- ^This is a Haddock documentation comment for the preceding code   {-| This is a Haddock documentation block comment -} i code = True
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#Haxe
Haxe
// Single line commment.   /* Multiple line comment. */
http://rosettacode.org/wiki/Conway%27s_Game_of_Life
Conway's Game of Life
The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead,   in an   m-by-m   (or m×m)   square array of cells. We calculate   N   - the sum of live cells in C's   eight-location neighbourhood,   then cell   C   is alive or dead in the next generation based on the following table: C N new C 1 0,1 -> 0 # Lonely 1 4,5,6,7,8 -> 0 # Overcrowded 1 2,3 -> 1 # Lives 0 3 -> 1 # It takes three to give birth! 0 0,1,2,4,5,6,7,8 -> 0 # Barren Assume cells beyond the boundary are always dead. The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players.   One interacts with the Game of Life by creating an initial configuration and observing how it evolves. Task Although you should test your implementation on more complex examples such as the   glider   in a larger universe,   show the action of the blinker   (three adjoining cells in a row all alive),   over three generations, in a 3 by 3 grid. References   Its creator John Conway, explains   the game of life.   Video from numberphile on youtube.   John Conway   Inventing Game of Life   - Numberphile video. Related task   Langton's ant   - another well known cellular automaton.
#Pascal
Pascal
program Gol; // Game of life {$IFDEF FPC} //save as gol.pp/gol.pas {$Mode delphi} {$ELSE} //for Delphi save as gol.dpr {$Apptype Console} {$ENDIF} uses crt;   const colMax = 76; rowMax = 22; dr = colMax+2; // element count of one row   cDelay = 20; // delay in ms   (* expand field by one row/column before and after for easier access no special treatment of torus *)   type tFldElem = byte;//0..1 tpFldElem = ^tFldElem; tRow = array[0..colMax+1] of tFldElem; tpRow = ^tRow; tBoard = array[0..rowMax+1] of tRow; tpBoard = ^tBoard; tpBoards = array[0..1] of tpBoard;   type tIntArr = array[0..2*dr+2] of tFldElem; tpIntArr = ^tIntArr;   var aBoard,bBoard : tBoard; pBoards :tpBoards; gblActBoard : byte; gblUseTorus :boolean; gblGenCnt : integer;   procedure PrintGen; const cChar: array[0..1] of char = (' ','#'); var p0 : tpIntArr; col,row: integer; s : string[colMax]; begin setlength(s,colmax); gotoxy(1,1); writeln(gblGenCnt:10); For row := 1 to rowMax do begin p0 := @pBoards[gblActBoard]^[row,0];; For col := 1 to colMax do s[col] := cChar[p0[col]]; writeln(s); end; delay(cDelay); end;   procedure Init0(useTorus:boolean); begin gblUseTorus := useTorus; gblGenCnt := 0; fillchar(aBoard,SizeOf(aBoard),#0); pBoards[0] := @aBoard; pBoards[1] := @bBoard; gblActBoard := 0;   clrscr; end;   procedure InitRandom(useTorus:boolean); var col,row : integer; begin Init0(useTorus); For row := 1 to rowMax do For col := 1 to colMax do aBoard[row,col]:= tFldElem(random>0.9); end;   procedure InitBlinker(useTorus:boolean); var col,row : integer; begin Init0(useTorus); For col := 1 to colMax do begin IF (col+2) mod 4 = 0 then begin For row := 1 to rowmax do IF row mod 4 <> 0 then aBoard[row,col]:= 1; end; end; end;   procedure Torus; var p0 : tpIntArr; row: integer; begin //copy column 1-> colMax+1 and colMax-> 0 p0 := @pBoards[gblActBoard]^[1,0]; For row := 1 to rowMax do begin p0^[0] := p0^[colMax]; p0^[colmax+1] := p0^[1]; //next row p0 := Pointer(PtrUint(p0)+SizeOf(tRow)); end; //copy row 1-> rowMax+1 move(pBoards[gblActBoard]^[1,0],pBoards[gblActBoard]^[rowMax+1,0],sizeof(trow)); //copy row rowMax-> 0 move(pBoards[gblActBoard]^[rowMax,0],pBoards[gblActBoard]^[0,0],sizeof(trow)); end;   function Survive(p: tpIntArr):tFldElem; //p points to actual_board [row-1,col-1] //calculates the sum of alive around [row,col] aka p^[dr+1] //really fast using fpc 2.6.4 no element on stack const cSurvives : array[boolean,0..8] of byte = //0,1,2,3,4,5,6,7,8 sum of alive neighbours ((0,0,0,1,0,0,0,0,0), {alive =false 1->born} (0,0,1,1,0,0,0,0,0)); {alive =true 0->die } var sum : integer; begin // row above // sum := byte(aBoard[row-1,col-1])+byte(aBoard[row-1,col])+byte(aBoard[row-1,col+1]); sum := integer(p^[ 0])+integer(p^[ 1])+integer(p^[ 2]); sum := sum+integer(p^[ dr+0]) +integer(p^[ dr+2]); sum := sum+integer(p^[2*dr+0])+integer(p^[2*dr+1])+integer(p^[2*dr+2]); survive := cSurvives[boolean(p^[dr+1]),sum]; end;   procedure NextGen; var p0,p1 : tpFldElem; row: NativeInt; col :NativeInt; begin if gblUseTorus then Torus; p1 := @pBoards[1-gblActBoard]^[1,1]; //One row above and one column before because of survive p0 := @pBoards[ gblActBoard]^[0,0]; For row := rowMax-1 downto 0 do begin For col := colMax-1 downto 0 do begin p1^ := survive(tpIntArr(p0)); inc(p0); inc(p1); end; // jump over the borders inc(p1,2); inc(p0,2); end; //aBoard := bBoard; gblActBoard :=1-gblActBoard; inc(gblGenCnt); end;   begin InitBlinker(false); repeat PrintGen; NextGen; until keypressed; PrintGen; end.  
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include if-then-else and switch. Less common are arithmetic if, ternary operator and Hash-based conditionals. Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
#GAP
GAP
if <condition> then <statements> elif <condition> then <statements> else <statements> fi;
http://rosettacode.org/wiki/Comma_quibbling
Comma quibbling
Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}". An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}". An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}". An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}". Test your function with the following series of inputs showing your output here on this page: [] # (No input words). ["ABC"] ["ABC", "DEF"] ["ABC", "DEF", "G", "H"] Note: Assume words are non-empty strings of uppercase characters for this task.
#Prolog
Prolog
words_series(Words, Bracketed) :- words_serialized(Words, Serialized), atomics_to_string(["{",Serialized,"}"], Bracketed).   words_serialized([], ""). words_serialized([Word], Word) :- !. words_serialized(Words, Serialized) :- append(Rest, [Last], Words), %% Splits the list of *Words* into the *Last* word and the *Rest* atomics_to_string(Rest, ", ", WithCommas), atomics_to_string([WithCommas, " and ", Last], Serialized).       test :- forall( member(Words, [[], ["ABC"], ["ABC", "DEF"], ["ABC", "DEF", "G", "H"]]), ( words_series(Words, Series), format('~w ~15|=> ~w~n', [Words, Series])) ).
http://rosettacode.org/wiki/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#Toka
Toka
[ arglist array.get type cr ] is show-arg [ dup . char: = emit space ] is #= 1 #args [ i #= show-arg ] countedLoop
http://rosettacode.org/wiki/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#TXR
TXR
@(next :args) @(collect) @arg @(end) @(output) My args are: {@(rep)@arg, @(last)@arg@(end)} @(end)
http://rosettacode.org/wiki/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#UNIX_Shell
UNIX Shell
WHOLELIST="$@"
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#HicEst
HicEst
! a comment starts with a "!" and ends at the end of the line
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#Hope
Hope
! All Hope comments begin with "!" and extend to the end of the line
http://rosettacode.org/wiki/Conway%27s_Game_of_Life
Conway's Game of Life
The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead,   in an   m-by-m   (or m×m)   square array of cells. We calculate   N   - the sum of live cells in C's   eight-location neighbourhood,   then cell   C   is alive or dead in the next generation based on the following table: C N new C 1 0,1 -> 0 # Lonely 1 4,5,6,7,8 -> 0 # Overcrowded 1 2,3 -> 1 # Lives 0 3 -> 1 # It takes three to give birth! 0 0,1,2,4,5,6,7,8 -> 0 # Barren Assume cells beyond the boundary are always dead. The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players.   One interacts with the Game of Life by creating an initial configuration and observing how it evolves. Task Although you should test your implementation on more complex examples such as the   glider   in a larger universe,   show the action of the blinker   (three adjoining cells in a row all alive),   over three generations, in a 3 by 3 grid. References   Its creator John Conway, explains   the game of life.   Video from numberphile on youtube.   John Conway   Inventing Game of Life   - Numberphile video. Related task   Langton's ant   - another well known cellular automaton.
#Perl
Perl
life.pl numrows numcols numiterations life.pl 5 10 15