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/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.
#Common_Lisp
Common Lisp
(if (= val 42) "That is the answer to life, the universe and everything" "Try again") ; the else clause here is optional
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
#Phix
Phix
with javascript_semantics function allsame(sequence s) for i=2 to length(s) do if s[i]!=s[1] then return false end if end for return true end function function strict_order(sequence s) for i=2 to length(s) do if s[i]<=s[i-1] then return false end if end for return true end function procedure test(sequence s) printf(1,"%-22V allsame:%5t, strict_order:%5t\n",{s,allsame(s),strict_order(s)}) end procedure test({"AA","BB","CC"}) test({"AA","AA","AA"}) test({"AA","CC","BB"}) test({"AA","ACB","BB","CC"}) test({"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.
#Gambas
Gambas
Public Sub Main() Dim sInput As String[] = ["", "ABC", "ABC DEF", "ABC DEF G H"] Dim sTemp As String   For Each sTemp In sInput Print sTemp & " = "; sTemp = Replace(sTemp, " ", ",") If RInStr(sTemp, ",") > 0 Then sTemp = Mid(sTemp, 1, RInStr(sTemp, ",") - 1) & " and " & Mid(sTemp, RInStr(sTemp, ",") + 1) End If sTemp = "{" & sTemp & "}" Print sTemp Next   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
#Mercury
Mercury
:- module comb. :- interface. :- import_module list, int, bag.   :- pred choose(list(T)::in, int::in, bag(T)::out) is nondet. :- pred choose_all(list(T)::in, int::in, list(list(T))::out) is det. :- pred count_choices(list(T)::in, int::in, int::out) is det.   :- implementation. :- import_module solutions.   choose(L, N, R) :- choose(L, N, bag.init, R).   :- pred choose(list(T)::in, int::in, bag(T)::in, bag(T)::out) is nondet. choose(L, N, !R) :- ( N = 0 -> true  ; member(X, L), bag.insert(!.R, X, !:R), choose(L, N - 1, !R) ).   choose_all(L, N, R) :- solutions(choose(L, N), R0), list.map(bag.to_list, R0, R).   count_choices(L, N, Count) :- aggregate(choose(L, N), count, 0, Count).   :- pred count(T::in, int::in, int::out) is det. count(_, N0, N) :- N0 + 1 = N.
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
#Nim
Nim
import sugar, sequtils   proc combsReps[T](lst: seq[T], k: int): seq[seq[T]] = if k == 0: @[newSeq[T]()] elif lst.len == 0: @[] else: lst.combsReps(k - 1).map((x: seq[T]) => lst[0] & x) & lst[1 .. ^1].combsReps(k)   echo(@["iced", "jam", "plain"].combsReps(2)) echo toSeq(1..10).combsReps(3).len
http://rosettacode.org/wiki/Combinations_and_permutations
Combinations and permutations
This page uses content from Wikipedia. The original article was at Combination. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) This page uses content from Wikipedia. The original article was at Permutation. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Implement the combination   (nCk)   and permutation   (nPk)   operators in the target language: n C k = ( n k ) = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle ^{n}\operatorname {C} _{k}={\binom {n}{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)} See the Wikipedia articles for a more detailed description. To test, generate and print examples of:   A sample of permutations from 1 to 12 and Combinations from 10 to 60 using exact Integer arithmetic.   A sample of permutations from 5 to 15000 and Combinations from 100 to 1000 using approximate Floating point arithmetic. This 'floating point' code could be implemented using an approximation, e.g., by calling the Gamma function. Related task   Evaluate binomial coefficients 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
#Stata
Stata
real scalar comb1(n, k) { return(exp(lnfactorial(n)-lnfactorial(k)-lnfactorial(n-k))) }   real scalar perm(n, k) { return(exp(lnfactorial(n)-lnfactorial(n-k))) }
http://rosettacode.org/wiki/Combinations_and_permutations
Combinations and permutations
This page uses content from Wikipedia. The original article was at Combination. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) This page uses content from Wikipedia. The original article was at Permutation. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Implement the combination   (nCk)   and permutation   (nPk)   operators in the target language: n C k = ( n k ) = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle ^{n}\operatorname {C} _{k}={\binom {n}{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)} See the Wikipedia articles for a more detailed description. To test, generate and print examples of:   A sample of permutations from 1 to 12 and Combinations from 10 to 60 using exact Integer arithmetic.   A sample of permutations from 5 to 15000 and Combinations from 100 to 1000 using approximate Floating point arithmetic. This 'floating point' code could be implemented using an approximation, e.g., by calling the Gamma function. Related task   Evaluate binomial coefficients 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
#Swift
Swift
import BigInt   func permutations(n: Int, k: Int) -> BigInt { let l = n - k + 1   guard l <= n else { return 1 }   return (l...n).reduce(BigInt(1), { $0 * BigInt($1) }) }   func combinations(n: Int, k: Int) -> BigInt { let fact = {() -> BigInt in guard k > 1 else { return 1 }   return (2...k).map({ BigInt($0) }).reduce(1, *) }()   return permutations(n: n, k: k) / fact }   print("Sample of permutations from 1 to 12")   for i in 1...12 { print("\(i) P \(i / 3) = \(permutations(n: i, k: i / 3))") }   print("\nSample of combinations from 10 to 60")   for i in stride(from: 10, through: 60, by: 10) { print("\(i) C \(i / 3) = \(combinations(n: i, k: i / 3))") }   print("\nSample of permutations from 5 to 15,000")   for i in [5, 50, 500, 1000, 5000, 15000] { let k = i / 3 let res = permutations(n: i, k: k).description let extra = res.count > 40 ? "... (\(res.count - 40) more digits)" : ""   print("\(i) P \(k) = \(res.prefix(40))\(extra)") }   print("\nSample of combinations from 100 to 1000")   for i in stride(from: 100, through: 1000, by: 100) { let k = i / 3 let res = combinations(n: i, k: k).description let extra = res.count > 40 ? "... (\(res.count - 40) more digits)" : ""   print("\(i) C \(k) = \(res.prefix(40))\(extra)") }
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
#Nim
Nim
  import re, strformat, strutils   type TokenKind = enum tkUnknown = "UNKNOWN_TOKEN", tkMul = "Op_multiply", tkDiv = "Op_divide", tkMod = "Op_mod", tkAdd = "Op_add", tkSub = "Op_subtract", tkNeg = "Op_negate", tkLt = "Op_less", tkLte = "Op_lessequal", tkGt = "Op_greater", tkGte = "Op_greaterequal", tkEq = "Op_equal", tkNeq = "Op_notequal", tkNot = "Op_not", tkAsgn = "Op_assign", tkAnd = "Op_and", tkOr = "Op_or", tkLpar = "LeftParen", tkRpar = "RightParen", tkLbra = "LeftBrace", tkRbra = "RightBrace", tkSmc = "Semicolon", tkCom = "Comma", tkIf = "Keyword_if", tkElse = "Keyword_else", tkWhile = "Keyword_while", tkPrint = "Keyword_print", tkPutc = "Keyword_putc", tkId = "Identifier", tkInt = "Integer", tkChar = "Integer", tkStr = "String", tkEof = "End_of_input"   Token = object kind: TokenKind value: string   TokenAnn = object ## Annotated token with messages for compiler token: Token line, column: int   proc getSymbols(table: openArray[(char, TokenKind)]): seq[char] = result = newSeq[char]() for ch, tokenKind in items(table): result.add ch   const tkSymbols = { # single-char tokens '*': tkMul, '%': tkMod, '+': tkAdd, '-': tkSub, '(': tkLpar, ')': tkRpar, '{': tkLbra, '}': tkRbra, ';': tkSmc, ',': tkCom, '/': tkDiv, # the comment case /* ... */ is handled in `stripUnimportant` } symbols = getSymbols(tkSymbols)   proc findTokenKind(table: openArray[(char, TokenKind)]; needle: char): TokenKind = for ch, tokenKind in items(table): if ch == needle: return tokenKind tkUnknown   proc stripComment(text: var string, lineNo, colNo: var int) = var matches: array[1, string]   if match(text, re"\A(/\*[\s\S]*?\*/)", matches): text = text[matches[0].len..^1] for s in matches[0]: if s == '\n': inc lineNo colNo = 1 else: inc colNo   proc stripUnimportant(text: var string; lineNo, colNo: var int) = while true: if text.len == 0: return elif text[0] == '\n': inc lineNo colNo = 1 text = text[1..^1] elif text[0] == ' ': inc colNo text = text[1..^1] elif text.len >= 2 and text[0] == '/' and text[1] == '*': stripComment(text, lineNo, colNo) else: return   proc lookAhead(ch1, ch2: char, tk1, tk2: TokenKind): (TokenKind, int) = if ch1 == ch2: (tk1, 2) else: (tk2, 1)   proc consumeToken(text: var string; tkl: var int): Token = ## Return token removing it from the `text` and write its length to ## `tkl`. If the token can not be defined, return `tkUnknown` as a ## token, shrink text by 1 and write 1 to its length.   var matches: array[1, string] tKind: TokenKind val: string   if text.len == 0: (tKind, tkl) = (tkEof, 0)   # Simple characters elif text[0] in symbols: (tKind, tkl) = (tkSymbols.findTokenKind(text[0]), 1) elif text[0] == '<': (tKind, tkl) = lookAhead(text[1], '=', tkLte, tkLt) elif text[0] == '>': (tKind, tkl) = lookAhead(text[1], '=', tkGte, tkGt) elif text[0] == '=': (tKind, tkl) = lookAhead(text[1], '=', tkEq, tkAsgn) elif text[0] == '!': (tKind, tkl) = lookAhead(text[1], '=', tkNeq, tkNot) elif text[0] == '&': (tKind, tkl) = lookAhead(text[1], '&', tkAnd, tkUnknown) elif text[0] == '|': (tKind, tkl) = lookAhead(text[1], '|', tkOr, tkUnknown)   # Keywords elif match(text, re"\Aif\b"): (tKind, tkl) = (tkIf, 2) elif match(text, re"\Aelse\b"): (tKind, tkl) = (tkElse, 4) elif match(text, re"\Awhile\b"): (tKind, tkl) = (tkWhile, 5) elif match(text, re"\Aprint\b"): (tKind, tkl) = (tkPrint, 5) elif match(text, re"\Aputc\b"): (tKind, tkl) = (tkPutc, 4)   # Literals and identifiers elif match(text, re"\A([0-9]+)", matches): (tKind, tkl) = (tkInt, matches[0].len) val = matches[0] elif match(text, re"\A([_a-zA-Z][_a-zA-Z0-9]*)", matches): (tKind, tkl) = (tkId, matches[0].len) val = matches[0] elif match(text, re"\A('(?:[^'\n]|\\\\|\\n)')", matches): (tKind, tkl) = (tkChar, matches[0].len) val = case matches[0] of r"' '": $ord(' ') of r"'\n'": $ord('\n') of r"'\\'": $ord('\\') else: $ord(matches[0][1]) # "'a'"[1] == 'a' elif match(text, re"\A(""[^""\n]*"")", matches): (tKind, tkl) = (tkStr, matches[0].len) val = matches[0] else: (tKind, tkl) = (tkUnknown, 1)   text = text[tkl..^1] Token(kind: tKind, value: val)   proc tokenize*(text: string): seq[TokenAnn] = result = newSeq[TokenAnn]() var lineNo, colNo: int = 1 text = text token: Token tokenLength: int   while text.len > 0: stripUnimportant(text, lineNo, colNo) token = consumeToken(text, tokenLength) result.add TokenAnn(token: token, line: lineNo, column: colNo) inc colNo, tokenLength   proc output*(s: seq[TokenAnn]): string = var tokenKind: TokenKind value: string line, column: int   for tokenAnn in items(s): line = tokenAnn.line column = tokenAnn.column tokenKind = tokenAnn.token.kind value = tokenAnn.token.value result.add( fmt"{line:>5}{column:>7} {tokenKind:<15}{value}" .strip(leading = false) & "\n")   when isMainModule: import os   let input = if paramCount() > 0: readFile paramStr(1) else: readAll stdin   echo input.tokenize.output  
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"
#jq
jq
$ARGS.positional contains an array of the positional arguments as JSON strings
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"
#Jsish
Jsish
#!/usr/local/bin/jsish puts(Info.argv0()); puts(console.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"
#Julia
Julia
using Printf   prog = Base.basename(Base.source_path())   println(prog, "'s command-line arguments are:") for s in ARGS println(" ", s) end  
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.)
#Deluge
Deluge
// single 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.)
#Dragon
Dragon
// This 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.
#INTERCAL
INTERCAL
pad=: 0,0,~0,.0,.~] life=: (3 3 (+/ e. 3+0,4&{)@,;._3 ])@pad NB. the above could also be a one-line solution: life=: (3 3 (+/ e. 3+0,4&{)@,;._3 ])@(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.
#Computer.2Fzero_Assembly
Computer/zero Assembly
if (condition) { // Some Task }   if (condition) { // Some Task } else if (condition2) { // Some Task } else { // Some Task }
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
#Phixmonti
Phixmonti
include ..\Utilitys.pmt   ( "alpha" "beta" "gamma" "delta" "epsilon" "zeta" "eta" "theta" "iota" "kappa" "lambda" "mu" )   dup dup sort == /# put 0 (false) in the pile, indicating that they are not in ascending order #/   drop /# discard the result #/   dup len swap 1 get rot repeat == /# put 0 (false) in the pile, indicating that they are not repeated strings #/  
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
#Picat
Picat
main => Lists = [["AA","BB","CC"], ["AA","AA","AA"], ["AA","CC","BB"], ["AA","ACB","BB","CC"], ["single_element"], []], foreach(L in Lists) Same = all_same(L).cond(true,false), Sorted = sorted(L).cond(true,false), printf("%-18w all_same:%-5w sorted:%-5w\n",L,Same,Sorted) end.   all_same([]). all_same([_]). all_same([A,B|Rest]) :- A == B, all_same([B|Rest]).
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.
#Go
Go
package main   import ( "fmt" "strings" )   func q(s []string) string { switch len(s) { case 0: return "{}" case 1: return "{" + s[0] + "}" case 2: return "{" + s[0] + " and " + s[1] + "}" default: return "{" + strings.Join(s[:len(s)-1], ", ") + " and " + s[len(s)-1] + "}" } }   func main() { fmt.Println(q([]string{})) fmt.Println(q([]string{"ABC"})) fmt.Println(q([]string{"ABC", "DEF"})) fmt.Println(q([]string{"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
#OCaml
OCaml
let rec combs_with_rep k xxs = match k, xxs with | 0, _ -> [[]] | _, [] -> [] | k, x::xs -> List.map (fun ys -> x::ys) (combs_with_rep (k-1) xxs) @ combs_with_rep k xs
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
#PARI.2FGP
PARI/GP
ways(k,v,s=[])={ if(k==0,return([])); if(k==1,return(vector(#v,i,concat(s,[v[i]])))); if(#v==1,return(ways(k-1,v,concat(s,v)))); my(u=vecextract(v,2^#v-2)); concat(ways(k-1,v,concat(s,[v[1]])),ways(k,u,s)) }; xc(k,v)=binomial(#v+k-1,k); ways(2, ["iced","jam","plain"])
http://rosettacode.org/wiki/Combinations_and_permutations
Combinations and permutations
This page uses content from Wikipedia. The original article was at Combination. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) This page uses content from Wikipedia. The original article was at Permutation. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Implement the combination   (nCk)   and permutation   (nPk)   operators in the target language: n C k = ( n k ) = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle ^{n}\operatorname {C} _{k}={\binom {n}{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)} See the Wikipedia articles for a more detailed description. To test, generate and print examples of:   A sample of permutations from 1 to 12 and Combinations from 10 to 60 using exact Integer arithmetic.   A sample of permutations from 5 to 15000 and Combinations from 100 to 1000 using approximate Floating point arithmetic. This 'floating point' code could be implemented using an approximation, e.g., by calling the Gamma function. Related task   Evaluate binomial coefficients 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
#Tcl
Tcl
# Exact integer versions proc tcl::mathfunc::P {n k} { set t 1 for {set i $n} {$i > $n-$k} {incr i -1} { set t [expr {$t * $i}] } return $t } proc tcl::mathfunc::C {n k} { set t [P $n $k] for {set i $k} {$i > 1} {incr i -1} { set t [expr {$t / $i}] } return $t }   # Floating point versions using the Gamma function package require math proc tcl::mathfunc::lnGamma n {math::ln_Gamma $n} proc tcl::mathfunc::fP {n k} { expr {exp(lnGamma($n+1) - lnGamma($n-$k+1))} } proc tcl::mathfunc::fC {n k} { expr {exp(lnGamma($n+1) - lnGamma($n-$k+1) - lnGamma($k+1))} }
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
#ObjectIcon
ObjectIcon
# -*- ObjectIcon -*- # # The Rosetta Code lexical analyzer in Object Icon. Based upon the ATS # implementation. # # Usage: lex [INPUTFILE [OUTPUTFILE]] # If INPUTFILE or OUTPUTFILE is "-" or missing, then standard input # or standard output is used, respectively. *) #   import io   $define EOF -1   $define TOKEN_ELSE 0 $define TOKEN_IF 1 $define TOKEN_PRINT 2 $define TOKEN_PUTC 3 $define TOKEN_WHILE 4 $define TOKEN_MULTIPLY 5 $define TOKEN_DIVIDE 6 $define TOKEN_MOD 7 $define TOKEN_ADD 8 $define TOKEN_SUBTRACT 9 $define TOKEN_NEGATE 10 $define TOKEN_LESS 11 $define TOKEN_LESSEQUAL 12 $define TOKEN_GREATER 13 $define TOKEN_GREATEREQUAL 14 $define TOKEN_EQUAL 15 $define TOKEN_NOTEQUAL 16 $define TOKEN_NOT 17 $define TOKEN_ASSIGN 18 $define TOKEN_AND 19 $define TOKEN_OR 20 $define TOKEN_LEFTPAREN 21 $define TOKEN_RIGHTPAREN 22 $define TOKEN_LEFTBRACE 23 $define TOKEN_RIGHTBRACE 24 $define TOKEN_SEMICOLON 25 $define TOKEN_COMMA 26 $define TOKEN_IDENTIFIER 27 $define TOKEN_INTEGER 28 $define TOKEN_STRING 29 $define TOKEN_END_OF_INPUT 30   global whitespace global ident_start global ident_continuation   procedure main(args) local inpf, outf local pushback_buffer, inp, pushback   initial { whitespace := ' \t\v\f\r\n' ident_start := '_' ++ &letters ident_continuation := ident_start ++ &digits }   inpf := FileStream.stdin outf := FileStream.stdout if 1 <= *args & args[1] ~== "-" then { inpf := FileStream(args[1], FileOpt.RDONLY) | stop(&why) } if 2 <= *args & args[2] ~== "-" then { outf := FileStream(args[2], ior(FileOpt.WRONLY, FileOpt.TRUNC, FileOpt.CREAT)) | stop(&why) }   pushback_buffer := [] inp := create inputter(inpf, pushback_buffer) pushback := create repeat push(pushback_buffer, \@&source) @pushback # The first invocation does nothing.   scan_text(outf, inp, pushback) end   procedure scan_text(outf, inp, pushback) local ch   while /ch | ch[1] ~=== EOF do { skip_spaces_and_comments(inp, pushback) ch := @inp if ch[1] === EOF then { print_token(outf, [TOKEN_END_OF_INPUT, "", ch[2], ch[3]]) } else { ch @pushback print_token(outf, get_next_token(inp, pushback)) } } end   procedure get_next_token(inp, pushback) local ch, ch1 local ln, cn   skip_spaces_and_comments(inp, pushback) ch := @inp ln := ch[2] # line number cn := ch[3] # column number case ch[1] of { "," : return [TOKEN_COMMA, ",", ln, cn] ";" : return [TOKEN_SEMICOLON, ";", ln, cn] "(" : return [TOKEN_LEFTPAREN, "(", ln, cn] ")" : return [TOKEN_RIGHTPAREN, ")", ln, cn] "{" : return [TOKEN_LEFTBRACE, "{", ln, cn] "}" : return [TOKEN_RIGHTBRACE, "}", ln, cn] "*" : return [TOKEN_MULTIPLY, "*", ln, cn] "/" : return [TOKEN_DIVIDE, "/", ln, cn] "%" : return [TOKEN_MOD, "%", ln, cn] "+" : return [TOKEN_ADD, "+", ln, cn] "-" : return [TOKEN_SUBTRACT, "-", ln, cn] "<" : { ch1 := @inp if ch1[1] === "=" then { return [TOKEN_LESSEQUAL, "<=", ln, cn] } else { ch1 @pushback return [TOKEN_LESS, "<", ln, cn] } } ">" : { ch1 := @inp if ch1[1] === "=" then { return [TOKEN_GREATEREQUAL, ">=", ln, cn] } else { ch1 @pushback return [TOKEN_GREATER, ">", ln, cn] } } "=" : { ch1 := @inp if ch1[1] === "=" then { return [TOKEN_EQUAL, "==", ln, cn] } else { ch1 @pushback return [TOKEN_ASSIGN, "=", ln, cn] } } "!" : { ch1 := @inp if ch1[1] === "=" then { return [TOKEN_NOTEQUAL, "!=", ln, cn] } else { ch1 @pushback return [TOKEN_NOT, "!", ln, cn] } } "&" : { ch1 := @inp if ch1[1] === "&" then { return [TOKEN_AND, "&&", ln, cn] } else { unexpected_character(ln, cn, ch) } } "|" : { ch1 := @inp if ch1[1] === "|" then { return [TOKEN_OR, "||", ln, cn] } else { unexpected_character(ln, cn, ch) } } "\"" : { ch @pushback return scan_string_literal(inp) } "'" : { ch @pushback return scan_character_literal(inp, pushback) } default : { if any(&digits, ch[1]) then { ch @pushback return scan_integer_literal(inp, pushback) } else if any(ident_start, ch[1]) then { ch @pushback return scan_identifier_or_reserved_word (inp, pushback) } else { unexpected_character(ln, cn, ch) } } } end   procedure scan_identifier_or_reserved_word(inp, pushback) local ch local s local line_no, column_no   s := "" ch := @inp line_no := ch[2] column_no := ch[3] while EOF ~=== ch[1] & any(ident_continuation, ch[1]) do { s ||:= ch[1] ch := @inp } ch @pushback return reserved_word_lookup (s, line_no, column_no) end   procedure scan_integer_literal(inp, pushback) local ch local s local line_no, column_no   s := "" ch := @inp line_no := ch[2] column_no := ch[3] while EOF ~=== ch[1] & any(ident_continuation, ch[1]) do { s ||:= ch[1] ch := @inp } ch @pushback not upto(~&digits, s) | invalid_integer_literal(line_no, column_no, s) return [TOKEN_INTEGER, s, line_no, column_no] end   procedure scan_character_literal(inp, pushback) local ch, ch1 local close_quote local toktup local line_no, column_no   ch := @inp # The opening quote. close_quote := ch[1] # Same as the opening quote. ch @pushback   line_no := ch[2] column_no := ch[3]   toktup := scan_character_literal_without_checking_end(inp) ch1 := @inp if ch1[1] ~=== close_quote then { repeat { case ch1[1] of { EOF : unterminated_character_literal(line_no, column_no) close_quote : multicharacter_literal(line_no, column_no) default : ch1 := @inp } } } return toktup end   procedure scan_character_literal_without_checking_end(inp) local ch, ch1, ch2   ch := @inp # The opening quote. ch1 := @inp EOF ~=== ch1[1] | unterminated_character_literal(ch[2], ch[3]) if ch1[1] == "\\" then { ch2 := @inp EOF ~=== ch2[1] | unterminated_character_literal(ch[2], ch[3]) case ch2[1] of { "n" : return [TOKEN_INTEGER, string(ord("\n")), ch[2], ch[3]] "\\" : return [TOKEN_INTEGER, string(ord("\\")), ch[2], ch[3]] default : unsupported_escape(ch1[2], ch1[3], ch2) } } else { return [TOKEN_INTEGER, string(ord(ch1[1])), ch[2], ch[3]] } end   procedure scan_string_literal(inp) local ch, ch1, ch2 local line_no, column_no local close_quote local s local retval   ch := @inp # The opening quote close_quote := ch[1] # Same as the opening quote. line_no := ch[2] column_no := ch[3]   s := ch[1] until \retval do { ch1 := @inp ch1[1] ~=== EOF | unterminated_string_literal (line_no, column_no, "end of input") ch1[1] ~== "\n" | unterminated_string_literal (line_no, column_no, "end of line") if ch1[1] == close_quote then { retval := [TOKEN_STRING, s || close_quote, line_no, column_no] } else if ch1[1] ~== "\\" then { s ||:= ch1[1] } else { ch2 := @inp EOF ~=== ch2[1] | unsupported_escape(line_no, column_no, ch2) case ch2[1] of { "n" : s ||:= "\\n" "\\" : s ||:= "\\\\" default : unsupported_escape(line_no, column_no, ch2) } } } return retval end   procedure skip_spaces_and_comments(inp, pushback) local ch, ch1   repeat { ch := @inp (EOF === ch[1]) & { ch @pushback; return } if not any(whitespace, ch[1]) then { (ch[1] == "/") | { ch @pushback; return } (ch1 := @inp) | { ch @pushback; return } (ch1[1] == "*") | { ch1 @pushback; ch @pushback; return } scan_comment(inp, ch[2], ch[3]) } } end   procedure scan_comment(inp, line_no, column_no) local ch, ch1   until (\ch)[1] == "*" & (\ch1)[1] == "/" do { ch := @inp (EOF === ch[1]) & unterminated_comment(line_no, column_no) if ch[1] == "*" then { ch1 := @inp (EOF === ch[1]) & unterminated_comment(line_no, column_no) } } return end   procedure reserved_word_lookup(s, line_no, column_no)   # Lookup is by an extremely simple perfect hash.   static reserved_words static reserved_word_tokens local hashval, token, toktup   initial { reserved_words := ["if", "print", "else", "", "putc", "", "", "while", ""] reserved_word_tokens := [TOKEN_IF, TOKEN_PRINT, TOKEN_ELSE, TOKEN_IDENTIFIER, TOKEN_PUTC, TOKEN_IDENTIFIER, TOKEN_IDENTIFIER, TOKEN_WHILE, TOKEN_IDENTIFIER] }   if *s < 2 then { toktup := [TOKEN_IDENTIFIER, s, line_no, column_no] } else { hashval := ((ord(s[1]) + ord(s[2])) % (*reserved_words)) + 1 token := reserved_word_tokens[hashval] if token = TOKEN_IDENTIFIER | s ~== reserved_words[hashval] then { toktup := [TOKEN_IDENTIFIER, s, line_no, column_no] } else { toktup := [token, s, line_no, column_no] } } return toktup end   procedure print_token(outf, toktup) static token_names local s_line, s_column   initial { token_names := ["Keyword_else", "Keyword_if", "Keyword_print", "Keyword_putc", "Keyword_while", "Op_multiply", "Op_divide", "Op_mod", "Op_add", "Op_subtract", "Op_negate", "Op_less", "Op_lessequal", "Op_greater", "Op_greaterequal", "Op_equal", "Op_notequal", "Op_not", "Op_assign", "Op_and", "Op_or", "LeftParen", "RightParen", "LeftBrace", "RightBrace", "Semicolon", "Comma", "Identifier", "Integer", "String", "End_of_input"] }   /outf := FileStream.stdout s_line := string(toktup[3]) s_column := string(toktup[4]) writes(outf, right (s_line, max(5, *s_line))) writes(outf, " ") writes(outf, right (s_column, max(5, *s_column))) writes(outf, " ") writes(outf, token_names[toktup[1] + 1]) case toktup[1] of { TOKEN_IDENTIFIER : writes(outf, " ", toktup[2]) TOKEN_INTEGER : writes(outf, " ", toktup[2]) TOKEN_STRING : writes(outf, " ", toktup[2]) } write(outf) return end   procedure inputter(inpf, pushback_buffer) local buffer local line_no, column_no local c   buffer := "" line_no := 1 column_no := 1   repeat { buffer? { until *pushback_buffer = 0 & pos(0) do { if *pushback_buffer ~= 0 then { suspend pop(pushback_buffer) } else { c := move(1) suspend [c, line_no, column_no] if c == "\n" then { line_no +:= 1 column_no := 1 } else { column_no +:= 1 } } } } (buffer := reads(inpf, 2048)) | suspend [EOF, line_no, column_no] } end   procedure unterminated_comment(line_no, column_no) error("unterminated comment starting at ", line_no, ":", column_no) end   procedure unexpected_character(line_no, column_no, ch) error("unexpected character '", ch[1], "' starting at ", line_no, ":", column_no) end   procedure unterminated_string_literal (line_no, column_no, cause) error("unterminated string literal (", cause, ") starting at ", line_no, ":", column_no) end   procedure unsupported_escape (line_no, column_no, ch) if ch[1] === EOF then { error("unexpected \\ at end of input", " starting at ", line_no, ":", column_no) } else { error("unsupported escape \\", ch[1], " starting at ", line_no, ":", column_no) } end   procedure invalid_integer_literal(line_no, column_no, s) error("invalid integer literal ", s, " starting at ", line_no, ":", column_no) end   procedure unterminated_character_literal(line_no, column_no) error("unterminated character literal starting at ", line_no, ":", column_no) end   procedure multicharacter_literal(line_no, column_no) error("unsupported multicharacter literal starting at ", line_no, ":", column_no) end   procedure error(args[]) write!([FileStream.stderr] ||| args) exit(1) 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"
#Klong
Klong
  .p'.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"
#Kotlin
Kotlin
fun main(args: Array<String>) { println("There are " + args.size + " arguments given.") args.forEachIndexed { i, a -> println("The argument #${i+1} is $a and is at index $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"
#Lasso
Lasso
#!/usr/bin/lasso9   iterate($argv) => { stdoutnl("Argument " + loop_count + ": " + loop_value) }
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.)
#DWScript
DWScript
(* This is a comment. It may extend across multiple lines. *)   { Alternatively curly braces can be used. }   /* C-style multi-line comments are supported */   // and single-line C++ style comments too
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.)
#Dyalect
Dyalect
/* This is a multi-line comment */   //This is a single-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.
#J
J
pad=: 0,0,~0,.0,.~] life=: (3 3 (+/ e. 3+0,4&{)@,;._3 ])@pad NB. the above could also be a one-line solution: life=: (3 3 (+/ e. 3+0,4&{)@,;._3 ])@(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.
#Crack
Crack
if (condition) { // Some Task }   if (condition) { // Some Task } else if (condition2) { // Some Task } else { // Some Task }
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
#PicoLisp
PicoLisp
(= "AA" "AA" "AA") -> T (= "AA" "AA" "Aa") -> NIL (< "AA" "AA") -> NIL (< "AA" "Aa") -> T (< "1" "A" "B" "Z" "c" ) -> T (> "A" "B" "Z" "C") -> NIL
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
#PL.2FI
PL/I
*process source xref attributes or(!); /*-------------------------------------------------------------------- * 01.07.2014 Walter Pachl *-------------------------------------------------------------------*/ clist: Proc Options(main); Dcl (hbound) Builtin; Dcl sysprint Print; Dcl abc(3) Char(2) Init('AA','BB','CC'); Dcl aaa(3) Char(2) Init('AA','AA','AA'); Dcl acb(3) Char(2) Init('AA','CC','BB'); Call test('ABC',ABC); Call test('AAA',AAA); Call test('ACB',ACB);   test: Procedure(name,x); Dcl name Char(*); Dcl x(*) Char(*); Dcl (all_equal,increasing) Bit(1) Init('1'b); Dcl (i,i1) Bin Fixed(31); Dcl txt Char(50) Var; Do i=1 To hbound(x)-1 While(all_equal ! increasing); i1=i+1; Select; When(x(i1)=x(i)) increasing='0'b; When(x(i1)<x(i)) Do; increasing='0'b; all_equal='0'b; End; Otherwise /* x(i1)>x(i) */ all_equal='0'b; End; End; Select; When(all_equal) txt='all elements are equal'; When(increasing) txt='elements are in increasing order'; Otherwise txt='neither equal nor in increasing order'; End; Put Skip List(name!!': '!!txt); End; 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.
#Groovy
Groovy
def commaQuibbling = { it.size() < 2 ? "{${it.join(', ')}}" : "{${it[0..-2].join(', ')} and ${it[-1]}}" }
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.
#Haskell
Haskell
quibble ws = "{" ++ quibbles ws ++ "}" where quibbles [] = "" quibbles [a] = a quibbles [a,b] = a ++ " and " ++ b quibbles (a:bs) = a ++ ", " ++ quibbles bs   main = mapM_ (putStrLn . quibble) $ [[], ["ABC"], ["ABC", "DEF"], ["ABC", "DEF", "G", "H"]] ++ (map words ["One two three four", "Me myself I", "Jack Jill", "Loner" ])  
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
#Pascal
Pascal
program CombWithRep; //combinations with repetitions //Limit = count of elements //Maxval = value of top , lowest is always 0 //so 0..Maxvalue => maxValue+1 elements {$IFDEF FPC} // {$R+,O+} {$MODE DELPHI}{$OPTIMIZATION ON,ALL}{$COPERATORS ON} {$ELSE}{$APPTYPE CONSOLE}{$ENDIF} uses SysUtils;//GetTickCount64   var CombIdx: array of byte;   function InitCombIdx(ElemCount: Int32): pbyte; begin setlength(CombIdx, ElemCount + 1); Fillchar(CombIdx[0], sizeOf(CombIdx[0]) * (ElemCount + 1), #0); Result := @CombIdx[0]; end;   function NextCombWithRep(pComb: pByte; MaxVal, ElemCount: UInt32): boolean; var i, dgt: NativeInt; begin i := -1; repeat i += 1; dgt := pComb[i]; if dgt < MaxVal then break; until i > ElemCount; Result := i >= ElemCount; dgt +=1; repeat pComb[i] := dgt; i -= 1; until i < 0; end;   procedure GetDoughnuts(ElemCount: NativeInt); const doughnuts: array[0..2] of string = ('iced', 'jam', 'plain'); var pComb: pByte; MaxVal, i: Uint32; begin if ElemCount < 1 then EXIT; MaxVal := High(doughnuts); writeln('Getting ', ElemCount, ' elements of ', MaxVal + 1, ' different'); pComb := InitCombIdx(ElemCount); repeat Write('['); for i := 0 to ElemCount - 2 do Write(pComb[i], ','); Write(pComb[ElemCount - 1], ']'); Write('{'); for i := 0 to ElemCount - 2 do Write(doughnuts[pComb[i]], ','); Write(doughnuts[pComb[ElemCount - 1]], '}'); until NextCombWithRep(pComb, MaxVal, ElemCount); writeln(#10); end;   procedure Check(ElemCount: Int32; ElemRange: Uint32); var pComb: pByte; T0: int64; rec_cnt: NativeInt; begin T0 := GetTickCount64; rec_cnt := 0; ElemRange -= 1; pComb := InitCombIdx(ElemCount); repeat Inc(rec_cnt); until NextCombWithRep(pComb, ElemRange, ElemCount); T0 := GetTickCount64 - T0; writeln('Getting ', ElemCount, ' elements of ', ElemRange + 1, ' different'); writeln(rec_cnt: 10, t0: 10,' ms'); end;   begin GetDoughnuts(2); GetDoughnuts(3); Check(3, 10); Check(9, 10); Check(15, 16); {$IFDEF WINDOWS} readln; {$ENDIF} end.
http://rosettacode.org/wiki/Combinations_and_permutations
Combinations and permutations
This page uses content from Wikipedia. The original article was at Combination. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) This page uses content from Wikipedia. The original article was at Permutation. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Implement the combination   (nCk)   and permutation   (nPk)   operators in the target language: n C k = ( n k ) = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle ^{n}\operatorname {C} _{k}={\binom {n}{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)} See the Wikipedia articles for a more detailed description. To test, generate and print examples of:   A sample of permutations from 1 to 12 and Combinations from 10 to 60 using exact Integer arithmetic.   A sample of permutations from 5 to 15000 and Combinations from 100 to 1000 using approximate Floating point arithmetic. This 'floating point' code could be implemented using an approximation, e.g., by calling the Gamma function. Related task   Evaluate binomial coefficients 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 and permutations - vbs - 10/04/2017 dim i,j Wscript.StdOut.WriteLine "-- Long Integer - Permutations - from 1 to 12" for i=1 to 12 for j=1 to i Wscript.StdOut.Write "P(" & i & "," & j & ")=" & perm(i,j) & " " next 'j Wscript.StdOut.WriteLine "" next 'i Wscript.StdOut.WriteLine "-- Float integer - Combinations from 10 to 60" for i=10 to 60 step 10 for j=1 to i step i\5 Wscript.StdOut.Write "C(" & i & "," & j & ")=" & comb(i,j) & " " next 'j Wscript.StdOut.WriteLine "" next 'i Wscript.StdOut.WriteLine "-- Float integer - Permutations from 5000 to 15000" for i=5000 to 15000 step 5000 for j=10 to 70 step 20 Wscript.StdOut.Write "C(" & i & "," & j & ")=" & perm(i,j) & " " next 'j Wscript.StdOut.WriteLine "" next 'i Wscript.StdOut.WriteLine "-- Float integer - Combinations from 200 to 1000" for i=200 to 1000 step 200 for j=20 to 100 step 20 Wscript.StdOut.Write "P(" & i & "," & j & ")=" & comb(i,j) & " " next 'j Wscript.StdOut.WriteLine "" next 'i function perm(x,y) dim i,z z=1 for i=x-y+1 to x z=z*i next 'i perm=z end function 'perm function fact(x) dim i,z z=1 for i=2 to x z=z*i next 'i fact=z end function 'fact function comb(byval x,byval y) if y>x then comb=0 elseif x=y then comb=1 else if x-y<y then y=x-y comb=perm(x,y)/fact(y) end if end function 'comb
http://rosettacode.org/wiki/Combinations_and_permutations
Combinations and permutations
This page uses content from Wikipedia. The original article was at Combination. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) This page uses content from Wikipedia. The original article was at Permutation. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Implement the combination   (nCk)   and permutation   (nPk)   operators in the target language: n C k = ( n k ) = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle ^{n}\operatorname {C} _{k}={\binom {n}{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)} See the Wikipedia articles for a more detailed description. To test, generate and print examples of:   A sample of permutations from 1 to 12 and Combinations from 10 to 60 using exact Integer arithmetic.   A sample of permutations from 5 to 15000 and Combinations from 100 to 1000 using approximate Floating point arithmetic. This 'floating point' code could be implemented using an approximation, e.g., by calling the Gamma function. Related task   Evaluate binomial coefficients 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
#Visual_Basic_.NET
Visual Basic .NET
' Combinations and permutations - 10/04/2017 Imports System.Numerics 'BigInteger Module CombPermRc   Sub Main() Dim i, j As Long For i = 1 To 12 For j = 1 To i Console.Write("P(" & i & "," & j & ")=" & PermBig(i, j).ToString & " ") Next j Console.WriteLine("") Next i Console.WriteLine("--") For i = 10 To 60 Step 10 For j = 1 To i Step i \ 5 Console.Write("C(" & i & "," & j & ")=" & CombBig(i, j).ToString & " ") Next j Console.WriteLine("") Next i Console.WriteLine("--") For i = 5000 To 15000 Step 5000 For j = 4000 To 5000 Step 1000 Console.Write("P(" & i & "," & j & ")=" & PermBig(i, j).ToString("E") & " ") Next j Console.WriteLine("") Next i Console.WriteLine("--") For i = 5000 To 15000 Step 5000 For j = 4000 To 5000 Step 1000 Console.Write("C(" & i & "," & j & ")=" & CombBig(i, j).ToString("E") & " ")   Next j Console.WriteLine("") Next i Console.WriteLine("--") i = 5000 : j = 4000 Console.WriteLine("C(" & i & "," & j & ")=" & CombBig(i, j).ToString) End Sub 'Main   Function PermBig(x As Long, y As Long) As BigInteger Dim i As Long, z As BigInteger z = 1 For i = x - y + 1 To x z = z * i Next i Return (z) End Function 'PermBig   Function FactBig(x As Long) As BigInteger Dim i As Long, z As BigInteger z = 1 For i = 2 To x z = z * i Next i Return (z) End Function 'FactBig   Function CombBig(ByVal x As Long, ByVal y As Long) As BigInteger If y > x Then Return (0) ElseIf x = y Then Return (1) Else If x - y < y Then y = x - y Return (PermBig(x, y) / FactBig(y)) End If End Function 'CombBig   End Module
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
#OCaml
OCaml
(*------------------------------------------------------------------*) (* The Rosetta Code lexical analyzer, in OCaml. Based on the ATS. *)   (* When you compare this code to the ATS code, please keep in mind that, although ATS has an ML-like syntax:   * The type system is not the same at all.   * Most ATS functions are not closures. Those that are will have special notations such as "<cloref1>" associated with them. *)   (*------------------------------------------------------------------*) (* The following functions are compatible with ASCII. *)   let is_digit ichar = 48 <= ichar && ichar <= 57   let is_lower ichar = 97 <= ichar && ichar <= 122   let is_upper ichar = 65 <= ichar && ichar <= 90   let is_alpha ichar = is_lower ichar || is_upper ichar   let is_alnum ichar = is_digit ichar || is_alpha ichar   let is_ident_start ichar = is_alpha ichar || ichar = 95   let is_ident_continuation ichar = is_alnum ichar || ichar = 95   let is_space ichar = ichar = 32 || (9 <= ichar && ichar <= 13)   (*------------------------------------------------------------------*)   let reverse_list_to_string lst = List.rev lst |> List.to_seq |> String.of_seq   (*------------------------------------------------------------------*) (* Character input more like that of C. There are various advantages and disadvantages to this method, but key points in its favor are: (a) it is how character input is done in the original ATS code, (b) Unicode code points are 21-bit positive integers. *)   let eof = (-1)   let input_ichar channel = try int_of_char (input_char channel) with | End_of_file -> eof   (*------------------------------------------------------------------*)   (* The type of an input character. *)   module Ch = struct type t = { ichar : int; line_no : int; column_no : int } end   (*------------------------------------------------------------------*) (* Inputting with unlimited pushback, and with counting of lines and columns. *)   module Inp = struct type t = { inpf : in_channel; pushback : Ch.t list; line_no : int; column_no : int }   let of_in_channel inpf = { inpf = inpf; pushback = []; line_no = 1; column_no = 1 }   let get_ch inp = match inp.pushback with | ch :: tail -> (ch, {inp with pushback = tail}) | [] -> let ichar = input_ichar inp.inpf in if ichar = int_of_char '\n' then ({ ichar = ichar; line_no = inp.line_no; column_no = inp.column_no }, { inp with line_no = inp.line_no + 1; column_no = 1 }) else ({ ichar = ichar; line_no = inp.line_no; column_no = inp.column_no }, { inp with column_no = inp.column_no + 1 })   let push_back_ch ch inp = {inp with pushback = ch :: inp.pushback} end   (*------------------------------------------------------------------*) (* Tokens, appearing in tuples with arguments, and with line and column numbers. The tokens are integers, so they can be used as array indices. *)   (* (token, argument, line_no, column_no) *) type toktup_t = int * string * int * int   let token_ELSE = 0 let token_IF = 1 let token_PRINT = 2 let token_PUTC = 3 let token_WHILE = 4 let token_MULTIPLY = 5 let token_DIVIDE = 6 let token_MOD = 7 let token_ADD = 8 let token_SUBTRACT = 9 let token_NEGATE = 10 let token_LESS = 11 let token_LESSEQUAL = 12 let token_GREATER = 13 let token_GREATEREQUAL = 14 let token_EQUAL = 15 let token_NOTEQUAL = 16 let token_NOT = 17 let token_ASSIGN = 18 let token_AND = 19 let token_OR = 20 let token_LEFTPAREN = 21 let token_RIGHTPAREN = 22 let token_LEFTBRACE = 23 let token_RIGHTBRACE = 24 let token_SEMICOLON = 25 let token_COMMA = 26 let token_IDENTIFIER = 27 let token_INTEGER = 28 let token_STRING = 29 let token_END_OF_INPUT = 30 ;;   (* A *very* simple perfect hash for the reserved words. (Yes, this is overkill, except for demonstration of the principle.) *)   let reserved_words = [| "if"; "print"; "else"; ""; "putc"; ""; ""; "while"; "" |] let reserved_word_tokens = [| token_IF; token_PRINT; token_ELSE; token_IDENTIFIER; token_PUTC; token_IDENTIFIER; token_IDENTIFIER; token_WHILE; token_IDENTIFIER |]   let reserved_word_lookup s line_no column_no = if String.length s < 2 then (token_IDENTIFIER, s, line_no, column_no) else let hashval = (int_of_char s.[0] + int_of_char s.[1]) mod 9 in let token = reserved_word_tokens.(hashval) in if token = token_IDENTIFIER || s <> reserved_words.(hashval) then (token_IDENTIFIER, s, line_no, column_no) else (token, s, line_no, column_no)   (* Token to string lookup. *)   let token_names = [| "Keyword_else"; "Keyword_if"; "Keyword_print"; "Keyword_putc"; "Keyword_while"; "Op_multiply"; "Op_divide"; "Op_mod"; "Op_add"; "Op_subtract"; "Op_negate"; "Op_less"; "Op_lessequal"; "Op_greater"; "Op_greaterequal"; "Op_equal"; "Op_notequal"; "Op_not"; "Op_assign"; "Op_and"; "Op_or"; "LeftParen"; "RightParen"; "LeftBrace"; "RightBrace"; "Semicolon"; "Comma"; "Identifier"; "Integer"; "String"; "End_of_input" |]   let token_name token = token_names.(token)   (*------------------------------------------------------------------*)   exception Unterminated_comment of int * int exception Unterminated_character_literal of int * int exception Multicharacter_literal of int * int exception End_of_input_in_string_literal of int * int exception End_of_line_in_string_literal of int * int exception Unsupported_escape of int * int * int exception Invalid_integer_literal of int * int * string exception Unexpected_character of int * int * char   (*------------------------------------------------------------------*) (* Skipping past spaces and comments. (A comment in the target language is, if you think about it, a kind of space.) *)   let scan_comment inp line_no column_no = let rec loop inp = let (ch, inp) = Inp.get_ch inp in if ch.ichar = eof then raise (Unterminated_comment (line_no, column_no)) else if ch.ichar = int_of_char '*' then let (ch1, inp) = Inp.get_ch inp in if ch1.ichar = eof then raise (Unterminated_comment (line_no, column_no)) else if ch1.ichar = int_of_char '/' then inp else loop inp else loop inp in loop inp   let skip_spaces_and_comments inp = let rec loop inp = let (ch, inp) = Inp.get_ch inp in if is_space ch.ichar then loop inp else if ch.ichar = int_of_char '/' then let (ch1, inp) = Inp.get_ch inp in if ch1.ichar = int_of_char '*' then scan_comment inp ch.line_no ch.column_no |> loop else let inp = Inp.push_back_ch ch1 inp in let inp = Inp.push_back_ch ch inp in inp else Inp.push_back_ch ch inp in loop inp   (*------------------------------------------------------------------*) (* Integer literals, identifiers, and reserved words. *)   (* In ATS the predicate for simple scan was supplied by template expansion, which (typically) produces faster code than passing a function or closure (although passing either of those could have been done). Here I pass the predicate as a function/closure. It is worth contrasting the methods. *) let rec simple_scan pred lst inp = let (ch, inp) = Inp.get_ch inp in if pred ch.ichar then simple_scan pred (char_of_int ch.ichar :: lst) inp else (lst, Inp.push_back_ch ch inp)   (* Demonstration of one way to make a new closure in OCaml. (In ATS, one might see things that look similar but are actually template operations.) *) let simple_scan_iic = simple_scan is_ident_continuation   let scan_integer_literal inp = let (ch, inp) = Inp.get_ch inp in let _ = assert (is_digit ch.ichar) in let (lst, inp) = simple_scan_iic [char_of_int ch.ichar] inp in let s = reverse_list_to_string lst in if List.for_all (fun c -> is_digit (int_of_char c)) lst then ((token_INTEGER, s, ch.line_no, ch.column_no), inp) else raise (Invalid_integer_literal (ch.line_no, ch.column_no, s))   let scan_identifier_or_reserved_word inp = let (ch, inp) = Inp.get_ch inp in let _ = assert (is_ident_start ch.ichar) in let (lst, inp) = simple_scan_iic [char_of_int ch.ichar] inp in let s = reverse_list_to_string lst in let toktup = reserved_word_lookup s ch.line_no ch.column_no in (toktup, inp)   (*------------------------------------------------------------------*) (* String literals. *)   let scan_string_literal inp = let (ch, inp) = Inp.get_ch inp in let _ = assert (ch.ichar = int_of_char '"') in   let rec scan lst inp = let (ch1, inp) = Inp.get_ch inp in if ch1.ichar = eof then raise (End_of_input_in_string_literal (ch.line_no, ch.column_no)) else if ch1.ichar = int_of_char '\n' then raise (End_of_line_in_string_literal (ch.line_no, ch.column_no)) else if ch1.ichar = int_of_char '"' then (lst, inp) else if ch1.ichar <> int_of_char '\\' then scan (char_of_int ch1.ichar :: lst) inp else let (ch2, inp) = Inp.get_ch inp in if ch2.ichar = int_of_char 'n' then scan ('n' :: '\\' :: lst) inp else if ch2.ichar = int_of_char '\\' then scan ('\\' :: '\\' :: lst) inp else raise (Unsupported_escape (ch1.line_no, ch1.column_no, ch2.ichar)) in let lst = '"' :: [] in let (lst, inp) = scan lst inp in let lst = '"' :: lst in let s = reverse_list_to_string lst in ((token_STRING, s, ch.line_no, ch.column_no), inp)   (*------------------------------------------------------------------*) (* Character literals. *)   let scan_character_literal_without_checking_end inp = let (ch, inp) = Inp.get_ch inp in let _ = assert (ch.ichar = int_of_char '\'') in let (ch1, inp) = Inp.get_ch inp in if ch1.ichar = eof then raise (Unterminated_character_literal (ch.line_no, ch.column_no)) else if ch1.ichar = int_of_char '\\' then let (ch2, inp) = Inp.get_ch inp in if ch2.ichar = eof then raise (Unterminated_character_literal (ch.line_no, ch.column_no)) else if ch2.ichar = int_of_char 'n' then let s = (int_of_char '\n' |> string_of_int) in ((token_INTEGER, s, ch.line_no, ch.column_no), inp) else if ch2.ichar = int_of_char '\\' then let s = (int_of_char '\\' |> string_of_int) in ((token_INTEGER, s, ch.line_no, ch.column_no), inp) else raise (Unsupported_escape (ch1.line_no, ch1.column_no, ch2.ichar)) else let s = string_of_int ch1.ichar in ((token_INTEGER, s, ch.line_no, ch.column_no), inp)   let scan_character_literal inp = let (toktup, inp) = scan_character_literal_without_checking_end inp in let (_, _, line_no, column_no) = toktup in   let check_end inp = let (ch, inp) = Inp.get_ch inp in if ch.ichar = int_of_char '\'' then inp else let rec loop_to_end (ch1 : Ch.t) inp = if ch1.ichar = eof then raise (Unterminated_character_literal (line_no, column_no)) else if ch1.ichar = int_of_char '\'' then raise (Multicharacter_literal (line_no, column_no)) else let (ch1, inp) = Inp.get_ch inp in loop_to_end ch1 inp in loop_to_end ch inp in let inp = check_end inp in (toktup, inp)   (*------------------------------------------------------------------*)   let get_next_token inp = let inp = skip_spaces_and_comments inp in let (ch, inp) = Inp.get_ch inp in let ln = ch.line_no in let cn = ch.column_no in if ch.ichar = eof then ((token_END_OF_INPUT, "", ln, cn), inp) else match char_of_int ch.ichar with | ',' -> ((token_COMMA, ",", ln, cn), inp) | ';' -> ((token_SEMICOLON, ";", ln, cn), inp) | '(' -> ((token_LEFTPAREN, "(", ln, cn), inp) | ')' -> ((token_RIGHTPAREN, ")", ln, cn), inp) | '{' -> ((token_LEFTBRACE, "{", ln, cn), inp) | '}' -> ((token_RIGHTBRACE, "}", ln, cn), inp) | '*' -> ((token_MULTIPLY, "*", ln, cn), inp) | '/' -> ((token_DIVIDE, "/", ln, cn), inp) | '%' -> ((token_MOD, "%", ln, cn), inp) | '+' -> ((token_ADD, "+", ln, cn), inp) | '-' -> ((token_SUBTRACT, "-", ln, cn), inp) | '<' -> let (ch1, inp) = Inp.get_ch inp in if ch1.ichar = int_of_char '=' then ((token_LESSEQUAL, "<=", ln, cn), inp) else let inp = Inp.push_back_ch ch1 inp in ((token_LESS, "<", ln, cn), inp) | '>' -> let (ch1, inp) = Inp.get_ch inp in if ch1.ichar = int_of_char '=' then ((token_GREATEREQUAL, ">=", ln, cn), inp) else let inp = Inp.push_back_ch ch1 inp in ((token_GREATER, ">", ln, cn), inp) | '=' -> let (ch1, inp) = Inp.get_ch inp in if ch1.ichar = int_of_char '=' then ((token_EQUAL, "==", ln, cn), inp) else let inp = Inp.push_back_ch ch1 inp in ((token_ASSIGN, "=", ln, cn), inp) | '!' -> let (ch1, inp) = Inp.get_ch inp in if ch1.ichar = int_of_char '=' then ((token_NOTEQUAL, "!=", ln, cn), inp) else let inp = Inp.push_back_ch ch1 inp in ((token_NOT, "!", ln, cn), inp) | '&' -> let (ch1, inp) = Inp.get_ch inp in if ch1.ichar = int_of_char '&' then ((token_AND, "&&", ln, cn), inp) else raise (Unexpected_character (ch.line_no, ch.column_no, char_of_int ch.ichar)) | '|' -> let (ch1, inp) = Inp.get_ch inp in if ch1.ichar = int_of_char '|' then ((token_OR, "||", ln, cn), inp) else raise (Unexpected_character (ch.line_no, ch.column_no, char_of_int ch.ichar)) | '"' -> let inp = Inp.push_back_ch ch inp in scan_string_literal inp | '\'' -> let inp = Inp.push_back_ch ch inp in scan_character_literal inp | _ when is_digit ch.ichar -> let inp = Inp.push_back_ch ch inp in scan_integer_literal inp | _ when is_ident_start ch.ichar -> let inp = Inp.push_back_ch ch inp in scan_identifier_or_reserved_word inp | _ -> raise (Unexpected_character (ch.line_no, ch.column_no, char_of_int ch.ichar))   let print_token outf toktup = let (token, arg, line_no, column_no) = toktup in let name = token_name token in let (padding, str) = match 0 with | _ when token = token_IDENTIFIER -> (" ", arg) | _ when token = token_INTEGER -> (" ", arg) | _ when token = token_STRING -> (" ", arg) | _ -> ("", "") in Printf.fprintf outf "%5d %5d %s%s%s\n" line_no column_no name padding str   let scan_text outf inp = let rec loop inp = let (toktup, inp) = get_next_token inp in begin print_token outf toktup; let (token, _, _, _) = toktup in if token <> token_END_OF_INPUT then loop inp end in loop inp   (*------------------------------------------------------------------*)   let main () = let inpf_filename = if 2 <= Array.length Sys.argv then Sys.argv.(1) else "-" in let outf_filename = if 3 <= Array.length Sys.argv then Sys.argv.(2) else "-" in let inpf = if inpf_filename = "-" then stdin else open_in inpf_filename in let outf = if outf_filename = "-" then stdout else open_out outf_filename in let inp = Inp.of_in_channel inpf in scan_text outf inp ;;   main ()   (*------------------------------------------------------------------*)
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"
#LFE
LFE
  $ ./bin/lfe -pa ebin/ -c "alpha beta" -h "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"
#Liberty_BASIC
Liberty BASIC
print CommandLine$
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"
#Lingo
Lingo
put the commandline -- "-c alpha beta -h gamma"
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.)
#Dylan
Dylan
// This is a comment   /* This is a comment that spans multiple 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.)
#D.C3.A9j.C3.A0_Vu
Déjà Vu
#this is a comment !print "this is not a comment, obviously" #this is a comment as well
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.
#JAMES_II.2FRule-based_Cellular_Automata
JAMES II/Rule-based Cellular Automata
@caversion 1;   dimensions 2;   //using Moore neighborhood neighborhood moore;   //available states state DEAD, ALIVE;   /* if current state is ALIVE and the neighborhood does not contain 2 or 3 ALIVE states the cell changes to DEAD */ rule{ALIVE}:!ALIVE{2,3}->DEAD;   /* if current state is DEAD and there are exactly 3 ALIVE cells in the neighborhood the cell changes to ALIVE */ rule{DEAD}:ALIVE{3}->ALIVE;
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.
#D
D
void main() { enum int i = 5;   // "static if" for various static checks: static if (i == 7) { // ... } else { //... }   // is(T == U) checks if type T is U. static if (is(typeof(i) == int)) { // ... } else { // ... }   // D switch is improved over C switch: switch (i) { case 0: break; // Silent fallthrough is forbidden. case 1: goto case; // Explicit fallthrough. case 2: // Empty cases don't require an explicit fallthrough. case 3: return; case 4, 5, 7: // Multiple cases. break; case 8: .. case 15: // Inclusive interval. goto case 3; default: // Default case is required. break; }   enum Colors { yellow, blue, brown, green } immutable c = Colors.blue;   // "final switch" is safer, for enums (and in future other values, // like Algebraic), because all cases must be present. // with() is handy to avoid repeating "Colors." for each case. final switch (c) with (Colors) { case yellow: break; case blue: break; case brown, green: break; // case yellow: .. case brown: // Forbidden in final switches. // default: // Forbidden in final switches. } }
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
#Plain_English
Plain English
To decide if some string things are lexically equal: If the string things are empty, say yes. Get a string thing from the string things. Put the string thing's string into a canonical string. Loop. If the string thing is nil, say yes. If the string thing's string is not the canonical string, say no. Put the string thing's next into the string thing. Repeat.   To decide if some string things are in ascending order: If the string things' count is less than 2, say yes. Get a string thing from the string things. Put the string thing's next into the string thing. Loop. If the string thing is nil, say yes. If the string thing's string is less than the string thing's previous' string, say no. Put the string thing's next into the string thing. Repeat.
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
#PowerShell
PowerShell
  function IsAscending ( [string[]]$Array ) { ( 0..( $Array.Count - 2 ) ).Where{ $Array[$_] -le $Array[$_+1] }.Count -eq $Array.Count - 1 } function IsEqual ( [string[]]$Array ) { ( 0..( $Array.Count - 2 ) ).Where{ $Array[$_] -eq $Array[$_+1] }.Count -eq $Array.Count - 1 }   IsAscending 'A', 'B', 'B', 'C' IsAscending 'A', 'C', 'B', 'C' IsAscending 'A', 'A', 'A', 'A'   IsEqual 'A', 'B', 'B', 'C' IsEqual 'A', 'C', 'B', 'C' IsEqual 'A', 'A', 'A', 'A'  
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.
#Icon_and_Unicon
Icon and Unicon
procedure main() every write(quibble([] | ["ABC"] | ["ABC","DEF"] | ["ABC","DEF","G","H"])) end   procedure quibble(A) join := s := "" while s := pull(A)||join||s do join := if *join = 0 then " and " else ", " return "{"||s||"}" 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.
#J
J
quibLast2=: ' and ' joinstring (2 -@<. #) {. ] withoutLast2=: ([: # _2&}.) {. ] quibble=: '{', '}' ,~ ', ' joinstring withoutLast2 , <@quibLast2
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
#Perl
Perl
sub p { $_[0] ? map p($_[0] - 1, [@{$_[1]}, $_[$_]], @_[$_ .. $#_]), 2 .. $#_ : $_[1] } sub f { $_[0] ? $_[0] * f($_[0] - 1) : 1 } sub pn{ f($_[0] + $_[1] - 1) / f($_[0]) / f($_[1] - 1) }   for (p(2, [], qw(iced jam plain))) { print "@$_\n"; }   printf "\nThere are %d ways to pick 7 out of 10\n", pn(7,10);  
http://rosettacode.org/wiki/Combinations_and_permutations
Combinations and permutations
This page uses content from Wikipedia. The original article was at Combination. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) This page uses content from Wikipedia. The original article was at Permutation. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Implement the combination   (nCk)   and permutation   (nPk)   operators in the target language: n C k = ( n k ) = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle ^{n}\operatorname {C} _{k}={\binom {n}{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)} See the Wikipedia articles for a more detailed description. To test, generate and print examples of:   A sample of permutations from 1 to 12 and Combinations from 10 to 60 using exact Integer arithmetic.   A sample of permutations from 5 to 15000 and Combinations from 100 to 1000 using approximate Floating point arithmetic. This 'floating point' code could be implemented using an approximation, e.g., by calling the Gamma function. Related task   Evaluate binomial coefficients 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
import "/big" for BigInt import "/fmt" for Fmt import "/trait" for Stepped   var perm = Fn.new { |n, k| if (n <= 0 || k < 0) Fiber.abort("Invalid argument(s).") if (k == 0) return BigInt.one return (n-k+1..n).reduce(BigInt.one) { |acc, i| acc * BigInt.new(i) } }   var comb = Fn.new { |n, k| if (n <= 0 || k < 0) Fiber.abort("Invalid argument(s).") var fact = BigInt.one if (k > 1) fact = (2..k).reduce(BigInt.one) { |acc, i| acc * BigInt.new(i) } return perm.call(n, k) / fact }   System.print("A sample of permutations from 1 to 12:") for (n in 1..12) Fmt.print("$2d P $-2d = $i", n, (n/3).floor, perm.call(n, (n/3).floor))   System.print("\nA sample of combinations from 10 to 60:") for (n in Stepped.new(10..60, 10)) { Fmt.print("$2d C $-2d = $i", n, (n/3).floor, comb.call(n, (n/3).floor)) }   System.print("\nA sample of permutations from 5 to 15000:") var na = [5, 50, 500, 1000, 5000, 15000] for (n in na) { var k = (n/3).floor var s = perm.call(n, k).toString var l = s.count var e = (l <= 40) ? "" : "... (%(l - 40) more digits)" Fmt.print("$5d P $-4d = $s$s", n, k, s.take(40).join(), e) }   System.print("\nA sample of combinations from 100 to 1000:") for (n in Stepped.new(100..1000, 100)) { var k = (n/3).floor var s = comb.call(n, k).toString var l = s.count var e = (l <= 40) ? "" : "... (%(l - 40) more digits)" Fmt.print("$4d C $-3d = $s$s", n, k, s.take(40).join(), e) }
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
#Ol
Ol
  (import (owl parse))   (define (get-comment) (get-either (let-parses ( (_ (get-imm #\*)) (_ (get-imm #\/))) #true) (let-parses ( (_ get-byte) (_ (get-comment))) #true)))   (define get-whitespace (get-any-of (get-byte-if (lambda (x) (has? '(#\tab #\newline #\space #\return) x))) ; whitespace (let-parses ( ; comment (_ (get-imm #\/)) (_ (get-imm #\*)) (_ (get-comment))) #true)))   (define get-operator (let-parses ( (operator (get-any-of (get-word "||" 'Op_or) (get-word "&&" 'Op_and) (get-word "!=" 'Op_notequal) (get-word "==" 'Op_equal) (get-word ">=" 'Op_greaterequal) (get-word "<=" 'Op_lessequal)   (get-word "=" 'Op_assign) (get-word "!" 'Op_nop) (get-word ">" 'Op_greater) (get-word "<" 'Op_less) (get-word "-" 'Op_subtract) (get-word "+" 'Op_add) (get-word "%" 'Op_mod) (get-word "/" 'Op_divide) (get-word "*" 'Op_multiply)))) (cons 'operator operator)))   (define get-symbol (let-parses ( (symbol (get-any-of (get-word "(" 'LeftParen) (get-word ")" 'RightParen) (get-word "{" 'LeftBrace) (get-word "}" 'RightBrace) (get-word ";" 'Semicolon) (get-word "," 'Comma)))) (cons 'symbol symbol)))   (define get-keyword (let-parses ( (keyword (get-any-of (get-word "if" 'Keyword_if) (get-word "else" 'Keyword_else) (get-word "while" 'Keyword_while) (get-word "print" 'Keyword_print) (get-word "putc" 'Keyword_putc)))) (cons 'keyword keyword)))       (define get-identifier (let-parses ( (lead (get-byte-if (lambda (x) (or (<= #\a x #\z) (<= #\A x #\Z) (= x #\_))))) (tail (get-greedy* (get-byte-if (lambda (x) (or (<= #\a x #\z) (<= #\A x #\Z) (= x #\_) (<= #\0 x #\9))))))) (cons 'identifier (bytes->string (cons lead tail)))))   (define get-integer (let-parses ( (main (get-greedy+ (get-byte-if (lambda (x) (<= #\0 x #\9))))) ) (cons 'integer (string->integer (bytes->string main)))))   (define get-character (let-parses ( (_ (get-imm #\')) (char (get-any-of (get-word "\\n" #\newline) (get-word "\\\\" #\\) (get-byte-if (lambda (x) (not (or (eq? x #\') (eq? x #\newline))))))) (_ (get-imm #\')) ) (cons 'character char)))   (define get-string (let-parses ( (_ (get-imm #\")) ;" (data (get-greedy* (get-any-of (get-word "\\n" #\newline) (get-word "\\\\" #\\) ;\" (get-byte-if (lambda (x) (not (or (eq? x #\") (eq? x #\newline)))))))) ;", newline (_ (get-imm #\")) ) ;" (cons 'string (bytes->string data))))   (define get-token (let-parses ( (_ (get-greedy* get-whitespace)) (token (get-any-of get-symbol get-keyword get-identifier get-operator get-integer get-character get-string )) ) token))   (define token-parser (let-parses ( (tokens (get-greedy+ get-token)) (_ (get-greedy* get-whitespace))) tokens))     (define (translate source) (let ((stream (try-parse token-parser (str-iter source) #t))) (for-each print (car stream)) (if (null? (cdr stream)) (print 'End_of_input))))  
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"
#Logo
Logo
logo file.logo - arg1 arg2 arg3
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.)
#E
E
# This is a regular comment.   ? "This is an Updoc comment, which > is an executable example or test case.".split(" ") # value: ["This", "is", "an", "Updoc", "comment,", "which # is", "an", "executable", "example", "or", "test", "case."]
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.)
#EasyLang
EasyLang
# This 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.
#Java
Java
public class GameOfLife{ public static void main(String[] args){ String[] dish= { "_#_", "_#_", "_#_",}; int gens= 3; for(int i= 0;i < gens;i++){ System.out.println("Generation " + i + ":"); print(dish); dish= life(dish); } }   public static String[] life(String[] dish){ String[] newGen= new String[dish.length]; for(int row= 0;row < dish.length;row++){//each row newGen[row]= ""; for(int i= 0;i < dish[row].length();i++){//each char in the row String above= "";//neighbors above String same= "";//neighbors in the same row String below= "";//neighbors below if(i == 0){//all the way on the left //no one above if on the top row //otherwise grab the neighbors from above above= (row == 0) ? null : dish[row - 1].substring(i, i + 2); same= dish[row].substring(i + 1, i + 2); //no one below if on the bottom row //otherwise grab the neighbors from below below= (row == dish.length - 1) ? null : dish[row + 1] .substring(i, i + 2); }else if(i == dish[row].length() - 1){//right //no one above if on the top row //otherwise grab the neighbors from above above= (row == 0) ? null : dish[row - 1].substring(i - 1, i + 1); same= dish[row].substring(i - 1, i); //no one below if on the bottom row //otherwise grab the neighbors from below below= (row == dish.length - 1) ? null : dish[row + 1] .substring(i - 1, i + 1); }else{//anywhere else //no one above if on the top row //otherwise grab the neighbors from above above= (row == 0) ? null : dish[row - 1].substring(i - 1, i + 2); same= dish[row].substring(i - 1, i) + dish[row].substring(i + 1, i + 2); //no one below if on the bottom row //otherwise grab the neighbors from below below= (row == dish.length - 1) ? null : dish[row + 1] .substring(i - 1, i + 2); } int neighbors= getNeighbors(above, same, below); if(neighbors < 2 || neighbors > 3){ newGen[row]+= "_";//<2 or >3 neighbors -> die }else if(neighbors == 3){ newGen[row]+= "#";//3 neighbors -> spawn/live }else{ newGen[row]+= dish[row].charAt(i);//2 neighbors -> stay } } } return newGen; }   public static int getNeighbors(String above, String same, String below){ int ans= 0; if(above != null){//no one above for(char x: above.toCharArray()){//each neighbor from above if(x == '#') ans++;//count it if someone is here } } for(char x: same.toCharArray()){//two on either side if(x == '#') ans++;//count it if someone is here } if(below != null){//no one below for(char x: below.toCharArray()){//each neighbor below if(x == '#') ans++;//count it if someone is here } } return ans; }   public static void print(String[] dish){ for(String s: dish){ System.out.println(s); } } }
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.
#Dao
Dao
a = 3 if( a == 1 ){ io.writeln( 'a == 1' ) }else if( a== 3 ){ io.writeln( 'a == 3' ) }else{ io.writeln( 'a is neither 1 nor 3' ) }
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
#Prolog
Prolog
los(["AA","BB","CC"]). los(["AA","AA","AA"]). los(["AA","CC","BB"]). los(["AA","ACB","BB","CC"]). los(["single_element"]).   lexically_equal(S,S,S). in_order(G,L,G) :- compare(<,L,G).   test_list(List) :- List = [L|T], write('for list '), write(List), nl, (foldl(lexically_equal, T, L, _) -> writeln('The items in the list ARE lexically equal') ; writeln('The items in the list are NOT lexically equal')), (foldl(in_order, T, L, _) -> writeln('The items in the list ARE in ascending order') ; writeln('The items in the list are NOT in ascending order')), nl.   test :- forall(los(List), test_list(List)).
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.
#Java
Java
public class Quibbler {   public static String quibble(String[] words) { String qText = "{"; for(int wIndex = 0; wIndex < words.length; wIndex++) { qText += words[wIndex] + (wIndex == words.length-1 ? "" : wIndex == words.length-2 ? " and " : ", "; } qText += "}"; return qText; }   public static void main(String[] args) { System.out.println(quibble(new String[]{})); System.out.println(quibble(new String[]{"ABC"})); System.out.println(quibble(new String[]{"ABC", "DEF"})); System.out.println(quibble(new String[]{"ABC", "DEF", "G"})); System.out.println(quibble(new String[]{"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
#Phix
Phix
with javascript_semantics procedure show_choices(sequence set, integer n, at=1, sequence res={}) if length(res)=n then ?res else for i=at to length(set) do show_choices(set,n,i,append(deep_copy(res),set[i])) end for end if end procedure show_choices({"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
#PHP
PHP
<?php function combos($arr, $k) { if ($k == 0) { return array(array()); }   if (count($arr) == 0) { return array(); }   $head = $arr[0];   $combos = array(); $subcombos = combos($arr, $k-1); foreach ($subcombos as $subcombo) { array_unshift($subcombo, $head); $combos[] = $subcombo; } array_shift($arr); $combos = array_merge($combos, combos($arr, $k)); return $combos; }   $arr = array("iced", "jam", "plain"); $result = combos($arr, 2); foreach($result as $combo) { echo implode(' ', $combo), "<br>"; } $donuts = range(1, 10); $num_donut_combos = count(combos($donuts, 3)); echo "$num_donut_combos ways to order 3 donuts given 10 types"; ?>
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
#Perl
Perl
#!/usr/bin/env perl   use strict; use warnings; no warnings 'once';     #----- Definition of the language to be lexed -----#   my @tokens = ( # Name | Format | Value # # -------------- |----------------------|-------------# ['Op_multiply' , '*' , ], ['Op_divide' , '/' , ], ['Op_mod' , '%' , ], ['Op_add' , '+' , ], ['Op_subtract' , '-' , ], ['Op_lessequal' , '<=' , ], ['Op_less' , '<' , ], ['Op_greaterequal', '>=' , ], ['Op_greater' , '>' , ], ['Op_equal' , '==' , ], ['Op_assign' , '=' , ], ['Op_not' , '!' , ], ['Op_notequal' , '!=' , ], ['Op_and' , '&&' , ], ['Op_or' , '||' , ], ['Keyword_else' , qr/else\b/ , ], ['Keyword_if' , qr/if\b/ , ], ['Keyword_while' , qr/while\b/ , ], ['Keyword_print' , qr/print\b/ , ], ['Keyword_putc' , qr/putc\b/ , ],   ['LeftParen' , '(' , ], ['RightParen' , ')' , ], ['LeftBrace' , '{' , ], ['RightBrace' , '}' , ], ['Semicolon' , ';' , ], ['Comma' , ',' , ],   ['Identifier' , qr/[_a-z][_a-z0-9]*/i, \&raw ], ['Integer' , qr/[0-9]+\b/ , \&raw ], ['Integer' , qr/'([^']*)(')?/ , \&char_val ], ['String' , qr/"([^"]*)(")?/ , \&string_raw],   ['End_of_input' , qr/$/ , ], );   my $comment = qr/\/\* .+? (?: \*\/ | $ (?{die "End-of-file in comment\n"}) )/xs; my $whitespace = qr/(?: \s | $comment)*/x; my $unrecognized = qr/\w+ | ./x;   #| Returns the value of a matched char literal, or dies if it is invalid sub char_val { my $str = string_val(); die "Multiple characters\n" if length $str > 1; die "No character\n" if length $str == 0; ord $str; }   #| Returns the value of a matched string literal, or dies if it is invalid sub string_val { my ($str, $end) = ($1, $2); die "End-of-file\n" if not defined $end; die "End-of-line\n" if $str =~ /\n/; $str =~ s/\\(.)/ $1 eq 'n' ? "\n" : $1 eq '\\' ? $1 : $1 eq $end ? $1 : die "Unknown escape sequence \\$1\n" /rge; }   #| Returns the source string of a matched literal sub raw { $& }   #| Returns the source string of a matched string literal, or dies if invalid sub string_raw { string_val(); # Just for the error handling side-effects $&; }     #----- Lexer "engine" -----#   # Construct the scanner regex:   my $tokens = join "|", map { my $format = $tokens[$_][1]; "\n".(ref $format ? $format : quotemeta $format)." (*MARK:$_) "; } 0..$#tokens;   my $regex = qr/ \G (?| $whitespace \K (?| $tokens ) | $whitespace? \K ($unrecognized) (*MARK:!) ) /x;     # Run the lexer:   my $input = do { local $/ = undef; <STDIN> }; my $pos = 0; my $linecol = linecol_accumulator();   while ($input =~ /$regex/g) { # Get the line and column number my ($line, $col) = $linecol->(substr $input, $pos, $-[0] - $pos); $pos = $-[0];   # Get the token type that was identified by the scanner regex my $type = $main::REGMARK; die "Unrecognized token $1 at line $line, col $col\n" if $type eq '!'; my ($name, $evaluator) = @{$tokens[$type]}[0, 2];   # Get the token value my $value; if ($evaluator) { eval { $value = $evaluator->() }; if ($@) { chomp $@; die "$@ in $name at line $line, col $col\n" } }   # Print the output line print "$line\t$col\t$name".($value ? "\t$value" : '')."\n"; }   #| Returns a closure, which can be fed a string one piece at a time and gives #| back the cumulative line and column number each time sub linecol_accumulator { my ($line, $col) = (1, 1); sub { my $str = shift; my @lines = split "\n", $str, -1; my ($l, $c) = @lines ? (@lines - 1, length $lines[-1]) : (0, 0); if ($l) { $line += $l; $col = 1 + $c } else { $col += $c } ($line, $col) } }
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"
#LSE64
LSE64
argc , nl # number of arguments (including command itself) 0 # argument dup arg dup 0 = || ,t 1 + repeat drop
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"
#Lua
Lua
print( "Program name:", arg[0] )   print "Arguments:" for i = 1, #arg do print( i," ", arg[i] ) 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"
#M2000_Interpreter
M2000 Interpreter
  Module Checkit { Document a$ = { Module Global A { Show Read a$="nothing", x=0 Print a$, x A$=Key$ } A: End } Dir temporary$ Save.doc a$, "program.gsb" \\ open if gsb extension is register to m2000.exe Win quote$(dir$+"program.gsb") \\ +txt is a switch for interpreter to use string comparison as text (not binary) \\ so we can send switches and commands before the program loading Win appdir$+"m2000.exe", quote$(dir$+"program.gsb +txt : Data {Hello}, 100") \\ no coma after name (we can use "program.gsb" for names with spaces) Use program.gsb "From Use statement", 200 \\ delete file Wait 5000 Dos "del "+quote$(dir$+"program.gsb"); \\ open directory Rem : Win temporary$ } Checkit  
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.)
#EchoLisp
EchoLisp
  666 ; this is an end-of-line comment   #| This is a multi-line comment Nesting is not allowed |#   ;; The (info <name> [<string>)] function associates a symbol and a comment ;; These info strings are saved in permanent memory (local storage) ;; Unicode characters may be used, as everywhere in the language   (define mynumber 666) → mynumber (info 'mynumber "👀 Symbols may be commented with an information string 👺") (info 'mynumber) → displays the above inside the 'info' field.  
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.)
#ECL
ECL
// this is a one-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.
#JavaScript
JavaScript
function GameOfLife () {   this.init = function (turns,width,height) { this.board = new Array(height); for (var x = 0; x < height; x++) { this.board[x] = new Array(width); for (var y = 0; y < width; y++) { this.board[x][y] = Math.round(Math.random()); } } this.turns = turns; }   this.nextGen = function() { this.boardNext = new Array(this.board.length); for (var i = 0; i < this.board.length; i++) { this.boardNext[i] = new Array(this.board[i].length); } for (var x = 0; x < this.board.length; x++) { for (var y = 0; y < this.board[x].length; y++) { var n = 0; for (var dx = -1; dx <= 1; dx++) { for (var dy = -1; dy <= 1; dy++) { if ( dx == 0 && dy == 0){} else if (typeof this.board[x+dx] !== 'undefined' && typeof this.board[x+dx][y+dy] !== 'undefined' && this.board[x+dx][y+dy]) { n++; } } } var c = this.board[x][y]; switch (n) { case 0: case 1: c = 0; break; case 2: break; case 3: c = 1; break; default: c = 0; } this.boardNext[x][y] = c; } } this.board = this.boardNext.slice(); }   this.print = function() { for (var x = 0; x < this.board.length; x++) { var l = ""; for (var y = 0; y < this.board[x].length; y++) { if (this.board[x][y]) l += "X"; else l += " "; } print(l); } }   this.start = function() { for (var t = 0; t < this.turns; t++) { print("---\nTurn "+(t+1)); this.print(); this.nextGen() } }   }     var game = new GameOfLife();   print("---\n3x3 Blinker over three turns."); game.init(3); game.board = [ [0,0,0], [1,1,1], [0,0,0]]; game.start();   print("---\n10x6 Glider over five turns."); game.init(5); game.board = [ [0,0,0,0,0,0,0,0,0,0], [0,0,1,0,0,0,0,0,0,0], [0,0,0,1,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]]; game.start();   print("---\nRandom 5x10"); game.init(5,5,10); game.start();
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.
#Delphi
Delphi
if (input.Field == "Hello World") { sVar = "good"; } else if (input.Field == "Bye World") { sVar = "bad"; } else { sVar = "neutral"; }
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
#PureBasic
PureBasic
EnableExplicit DataSection Data.s ~"AA\tAA\tAA\nAA\tBB\tCC\nAA\tCC\tBB\nAA\tACB\tBB\tCC\nsingel_element" EndDataSection   Macro PassFail(PF) If PF : PrintN("Pass") : Else : PrintN("Fail") : EndIf EndMacro   Macro ProcRec(Proc) Define tf1$,tf2$ : Static chk.b : chk=#True tf1$=StringField(s$,c,tz$) : tf2$=StringField(s$,c+1,tz$) If Len(tf2$) : Proc(s$,tz$,c+1) : EndIf EndMacro   Procedure.b IsStringsEqual(s$,tz$=~"\t",c.i=1) ProcRec(IsStringsEqual) chk & Bool(tf1$=tf2$ Or tf2$="") ProcedureReturn chk EndProcedure   Procedure.b IsStringsAscending(s$,tz$=~"\t",c.i=1) ProcRec(IsStringsAscending) chk & Bool(tf1$<tf2$ Or tf2$="") ProcedureReturn chk EndProcedure   Define t$,sf$,c.i,i.i,PF.b Read.s t$ : c=CountString(t$,~"\n") OpenConsole("Compare a list of Strings") For i=1 To c+1 sf$=StringField(t$,i,~"\n") PrintN("List : "+sf$) Print("Lexical test  : ") : PassFail(IsStringsEqual(sf$)) Print("Ascending test : ") : PassFail(IsStringsAscending(sf$)) PrintN("") Next Input()
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.
#JavaScript
JavaScript
function quibble(words) { return "{" + words.slice(0, words.length-1).join(",") + (words.length > 1 ? " and " : "") + (words[words.length-1] || '') + "}"; }   [[], ["ABC"], ["ABC", "DEF"], ["ABC", "DEF", "G", "H"]].forEach( function(s) { console.log(quibble(s)); } );
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
#PicoLisp
PicoLisp
(de combrep (N Lst) (cond ((=0 N) '(NIL)) ((not Lst)) (T (conc (mapcar '((X) (cons (car Lst) X)) (combrep (dec N) Lst) ) (combrep N (cdr Lst)) ) ) ) )
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
#Prolog
Prolog
  combinations_of_length(_,[]). combinations_of_length([X|T],[X|Combinations]):- combinations_of_length([X|T],Combinations). combinations_of_length([_|T],[X|Combinations]):- combinations_of_length(T,[X|Combinations]).  
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
#Phix
Phix
-- -- demo\rosetta\Compiler\core.e -- ============================ -- -- Standard declarations and routines used by lex.exw, parse.exw, cgen.exw, and interp.exw -- (included in distribution as above, which contains some additional sanity checks) -- with javascript_semantics global constant EOF = -1, STDIN = 0, STDOUT = 1 global enum NONE=0, UNARY=1, BINARY=2 global type nary(integer n) return n=NONE or n=UNARY or n=BINARY end type global sequence tkNames = {} -- eg/ie {"Op_multiply","Op_divide",..} global sequence precedences = {} global sequence narys = {} -- NONE/UNARY/BINARY global sequence operators = {} -- eg/ie {"*","/","+","-","<","<=",..} global sequence opcodes = {} -- idx to tkNames, matching operators global constant KEYWORDS = new_dict() -- eg/ie {"if"=>idx to tkNames} global enum OPERATOR=1, DIGIT, LETTER -- character classes global sequence charmap = repeat(0,255) charmap['0'..'9'] = DIGIT charmap['A'..'Z'] = LETTER charmap['a'..'z'] = LETTER charmap['_'] = LETTER function tkName(string s, nary n = NONE, integer precedence = -1) tkNames = append(tkNames,s) narys = append(narys,n) precedences = append(precedences,precedence) return length(tkNames) end function function tkOp(string s, string op, nary n, integer precedence) integer res = tkName(s, n, precedence) operators = append(operators,op) opcodes = append(opcodes,res) for i=1 to length(op) do charmap[op[i]] = OPERATOR end for return res end function function tkKw(string s, string keyword) integer res = tkName(s) putd(keyword, res, KEYWORDS) return res end function global constant tk_EOI = tkName("End_of_input"), --1 tk_mul = tkOp("Op_multiply", "*", BINARY,13), --2 tk_div = tkOp("Op_divide", "/", BINARY,13), --3 tk_mod = tkOp("Op_mod", "%", BINARY,13), --4 tk_add = tkOp("Op_add", "+", BINARY,12), --5 tk_sub = tkOp("Op_subtract", "-", BINARY,12), --6 tk_neg = tkName("Op_negate", UNARY, 14), --7 tk_not = tkOp("Op_not", "!", UNARY, 14), --8 tk_lt = tkOp("Op_less", "<", BINARY,10), --9 tk_le = tkOp("Op_lessequal", "<=",BINARY,10), --10 tk_gt = tkOp("Op_greater", ">", BINARY,10), --11 tk_ge = tkOp("Op_greaterequal", ">=",BINARY,10), --12 tk_eq = tkOp("Op_equal", "==",BINARY, 9), --13 tk_ne = tkOp("Op_notequal", "!=",BINARY, 9), --14 tk_assign = tkOp("Op_assign", "=", NONE, -1), --15 tk_and = tkOp("Op_and", "&&",BINARY, 5), --16 tk_or = tkOp("Op_or", "||",BINARY, 4), --17 tk_if = tkKw("Keyword_if", "if"), --18 tk_else = tkKw("Keyword_else", "else"), --19 tk_while = tkKw("Keyword_while","while"), --20 tk_print = tkKw("Keyword_print","print"), --21 tk_putc = tkKw("Keyword_putc", "putc"), --22 tk_LeftParen = tkOp("LeftParen", "(", NONE, -1), --23 tk_RightParen = tkOp("RightParen", ")", NONE, -1), --24 tk_LeftBrace = tkOp("LeftBrace", "{", NONE, -1), --25 tk_RightBrace = tkOp("RightBrace", "}", NONE, -1), --26 tk_Semicolon = tkOp("Semicolon", ";", NONE, -1), --27 tk_Comma = tkOp("Comma", ",", NONE, -1), --28 tk_Identifier = tkName("Identifier"), --29 tk_Integer = tkName("Integer"), --30 tk_String = tkName("String"), --31 tk_Sequence = tkName("Sequence"), --32 tk_Prints = tkName("tk_Prints"), --33 tk_Printi = tkName("tk_Printi") --34 global integer input_file = STDIN, output_file = STDOUT type strint(object o) return string(o) or integer(o) end type global strint tok_line, -- save of line/col at the start of tok_col -- token/comment, for result/errors global object oneline = "" constant errfmt = "Line %s column %s:\n%s%s" function errline() oneline = substitute(trim(oneline,"\r\n"),'\t',' ') string padding = repeat(' ',tok_col) return sprintf("%s\n%s^ ",{oneline,padding}) end function global procedure error(sequence msg, sequence args={}) if length(args) then msg = sprintf(msg,args) end if string el = iff(atom(oneline)?"":errline()) if integer(tok_line) then tok_line = sprintf("%d",tok_line) end if if integer(tok_col) then tok_col = sprintf("%d",tok_col) end if printf(STDOUT,errfmt,{tok_line,tok_col,el,msg}) {} = wait_key() abort(1) end procedure include js_io.e -- fake file i/o for running under pwa/p2js function open_file(string file_name, string mode) integer fn = iff(platform()=JS?js_open(file_name) :open(file_name, mode)) if fn<=0 then printf(STDOUT, "Could not open %s", {file_name}) {} = wait_key() abort(1) end if return fn end function global procedure open_files(sequence cl) if length(cl)>2 then input_file = open_file(cl[3],"r") if length(cl)>3 then output_file = open_file(cl[4],"w") end if end if end procedure global procedure close_files() if platform()!=JS then if input_file!=STDIN then close(input_file) end if if output_file!=STDOUT then close(output_file) end if end if end procedure global function enquote(string s) return sprintf(`"%s"`,substitute(s,"\n","\\n")) end function global function unquote(string s) if s[1]!='\"' then ?9/0 end if if s[$]!='\"' then ?9/0 end if s = substitute(s[2..-2],"\\n","\n") return s 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"
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
#!/usr/local/bin/MathematicaScript -script $CommandLine
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"
#Mercury
Mercury
  :- module cmd_line_args. :- interface.   :- import_module io. :- pred main(io::di, io::uo) is det.   :- implementation. :- import_module int, list, string.   main(!IO) :- io.progname("", ProgName, !IO), io.format("This program is named %s.\n", [s(ProgName)], !IO), io.command_line_arguments(Args, !IO), list.foldl2(print_arg, Args, 1, _, !IO).   :- pred print_arg(string::in, int::in, int::out, io::di, io::uo) is det.   print_arg(Arg, ArgNum, ArgNum + 1, !IO) :- io.format("the argument #%d is %s\n", [i(ArgNum), s(Arg)], !IO).  
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"
#min
min
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.)
#EDSAC_order_code
EDSAC order code
[This is a comment] [ And so is this ] [But in 1949 they wouldn't have been]
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.)
#EGL
EGL
-- inline comment, continues until new 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.
#jq
jq
# Notes on the implementation:   # 1. For efficiency, the implementation requires that the world # has boundaries, as illustrated in the examples. # 2. For speed, the simulation uses the exploded string. # 3. The ASCII values of the "alive" and "empty" symbols are # hardcoded: "." => 46; " " => 32 # 4. To adjust the refresh rate, adjust the input to "spin".   def lines: split("\n")|length;   def cols: split("\n")[0]|length + 1; # allow for the newline   # Is there a "." (46) at [x,y] relative to position i, # assuming the width is w? # Input is an array; result is 0 or 1 so we can easily count the total. def isAlive(x; y; i; w): if .[i+ w*y + x] == 46 then 1 else 0 end;   def neighborhood(i;w): isAlive(-1; -1; i; w) + isAlive(0; -1; i; w) + isAlive(1; -1; i; w) + isAlive(-1; 0; i; w) + isAlive(1; 0; i; w) + isAlive(-1; 1; i; w) + isAlive(0; 1; i; w) + isAlive(1; 1; i; w) ;   # The basic rules: def evolve(cell; sum) : if cell == 46 then if sum == 2 or sum == 3 then 46 else 32 end elif cell == 32 then if sum == 3 then 46 else 32 end else cell end ;   # [world, lines, cols] | next(w) => [world, lines, cols] def next: .[0] as $world | .[1] as $lines | .[2] as $w | reduce range(0; $world|length) as $i ($world; .[$i] as $c | if $c == 32 or $c == 46 then # updates are "simultaneous" i.e. relative to $world, not "." ($world | neighborhood($i; $w)) as $sum | evolve($c; $sum) as $next | if $c == $next then . else .[$i] = $next end else . end ) | [., $lines, $w] ;  
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.
#Deluge
Deluge
if (input.Field == "Hello World") { sVar = "good"; } else if (input.Field == "Bye World") { sVar = "bad"; } else { sVar = "neutral"; }
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
#Python
Python
all(a == nexta for a, nexta in zip(strings, strings[1:])) # All equal all(a < nexta for a, nexta in zip(strings, strings[1:])) # Strictly ascending   len(set(strings)) == 1 # Concise all equal sorted(strings, reverse=True) == strings # Concise (but not particularly efficient) ascending  
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
#Quackery
Quackery
[ [ true swap dup size 1 > while behead swap witheach [ over != if [ dip not conclude ] ] ] drop ] is allthesame ( [ --> b )   [ [ true swap dup size 1 > while behead swap witheach [ tuck $> if [ dip not conclude ] ] ] drop ] is allinorder ( [ --> b )
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.
#jq
jq
def quibble: if length == 0 then "" elif length == 1 then .[0] else (.[0:length-1] | join(", ")) + " and " + .[length-1] 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.
#Julia
Julia
function quibble(arr::Array) if isempty(arr) rst = "" else rst = "$(arr[end])" end if length(arr) > 1 rst = join(arr[1:end-1], ", ") * " and " * rst end return "{" * rst * "}" end   @show quibble([]) @show quibble(["ABC"]) @show quibble(["ABC", "DEF"]) @show 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
#PureBasic
PureBasic
Procedure nextCombination(Array combIndex(1), elementCount) ;combIndex() must be dimensioned to 'k' - 1, elementCount equals 'n' - 1 ;combination produced includes repetition of elements and is represented by the array combIndex() Protected i, indexValue, combSize = ArraySize(combIndex()), curIndex   ;update indexes curIndex = combSize Repeat combIndex(curIndex) + 1 If combIndex(curIndex) > elementCount   curIndex - 1 If curIndex < 0 For i = 0 To combSize combIndex(i) = 0 Next ProcedureReturn #False ;array reset to first combination EndIf   ElseIf curIndex < combSize   indexValue = combIndex(curIndex) Repeat curIndex + 1 combIndex(curIndex) = indexValue Until curIndex = combSize   EndIf Until curIndex = combSize   ProcedureReturn #True ;array contains next combination EndProcedure   Procedure.s display(Array combIndex(1), Array dougnut.s(1)) Protected i, elementCount = ArraySize(combIndex()), output.s = " " For i = 0 To elementCount output + dougnut(combIndex(i)) + " + " Next ProcedureReturn Left(output, Len(output) - 3) EndProcedure   DataSection Data.s "iced", "jam", "plain" EndDataSection   If OpenConsole() Define n = 3, k = 2, i, combinationCount Dim combIndex(k - 1) Dim dougnut.s(n - 1) For i = 0 To n - 1: Read.s dougnut(i): Next   PrintN("Combinations of " + Str(n) + " dougnut types taken " + Str(k) + " at a time with repetitions.") combinationCount = 0 Repeat PrintN(display(combIndex(), dougnut())) combinationCount + 1 Until Not nextCombination(combIndex(), n - 1) PrintN("Total combination count: " + Str(combinationCount))   ;extra credit n = 10: k = 3 Dim combIndex(k - 1) combinationCount = 0 Repeat: combinationCount + 1: Until Not nextCombination(combIndex(), n - 1) PrintN(#CRLF$ + "Ways to select " + Str(k) + " items from " + Str(n) + " types: " + Str(combinationCount))   Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input() CloseConsole() EndIf
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
#Prolog
Prolog
/* Test harness for the analyzer, not needed if we are actually using the output. */ load_file(File, Input) :- read_file_to_codes(File, Codes, []), maplist(char_code, Chars, Codes), atom_chars(Input,Chars).   test_file(File) :- load_file(File, Input), tester(Input).   tester(S) :- atom_chars(S,Chars), tokenize(Chars,L), maplist(print_tok, L), !.   print_tok(L) :- L =.. [Op,Line,Pos], format('~d\t~d\t~p~n', [Line,Pos,Op]). print_tok(string(Value,Line,Pos)) :- format('~d\t~d\tstring\t\t"~w"~n', [Line,Pos,Value]). print_tok(identifier(Value,Line,Pos)) :- format('~d\t~d\tidentifier\t~p~n', [Line,Pos,Value]). print_tok(integer(Value,Line,Pos)) :- format('~d\t~d\tinteger\t\t~p~n', [Line,Pos,Value]).     /* Tokenize   run the input over a DCG to get out the tokens.   In - a list of chars to tokenize Tokens = a list of tokens (excluding spaces). */ tokenize(In,RelTokens) :- newline_positions(In,1,NewLines), tokenize(In,[0|NewLines],1,1,Tokens), check_for_exceptions(Tokens), exclude(token_name(space),Tokens,RelTokens).   tokenize([],NewLines,Pos,LineNo,[end_of_input(LineNo,Offset)]) :- position_offset(NewLines,Pos,Offset). tokenize(In,NewLines,Pos,LineNo,Out) :- position_offset(NewLines,Pos,Offset), phrase(tok(Tok,TokLen,LineNo,Offset),In,T), ( Tok = [] -> Out = Toks ; Out = [Tok|Toks] ), Pos1 is Pos + TokLen, update_line_no(LineNo,NewLines,Pos1,NewLineNo,NewNewLines), tokenize(T,NewNewLines,Pos1,NewLineNo,Toks).   update_line_no(LNo,[L],_,LNo,[L]). update_line_no(LNo,[L,Nl|T],Pos,LNo,[L,Nl|T]) :- Pos =< Nl. update_line_no(LNo,[_,Nl|T],Pos,LNo2,Nlines) :- Pos > Nl, succ(LNo,LNo1), update_line_no(LNo1,[Nl|T],Pos,LNo2,Nlines).   position_offset([Line|_],Pos,Offset) :- Offset is Pos - Line.   token_name(Name,Tok) :- functor(Tok,Name,_).   % Get a list of all the newlines and their position in the data % This is used to create accurate row/column numbers. newline_positions([],N,[N]). newline_positions(['\n'|T],N,[N|Nt]) :- succ(N,N1), newline_positions(T,N1,Nt). newline_positions([C|T],N,Nt) :- dif(C,'\n'), succ(N,N1), newline_positions(T,N1,Nt).   % The tokenizer can tokenize some things that it shouldn't, deal with them here. check_for_exceptions([]). % all ok check_for_exceptions([op_divide(L,P),op_multiply(_,_)|_]) :- format(atom(Error), 'Unclosed comment at line ~d,~d', [L,P]), throw(Error). check_for_exceptions([integer(_,L,P),identifier(_,_,_)|_]) :- format(atom(Error), 'Invalid identifier at line ~d,~d', [L,P]), throw(Error). check_for_exceptions([_|T]) :- check_for_exceptions(T).     /* A set of helper DCGs for the more complicated token types */ :- set_prolog_flag(double_quotes, chars).   identifier(I) --> c_types(I,csym). identifier(['_']) --> ['_']. identifier([]) --> [].   integer_(I,L) --> c_types(N,digit), { number_codes(I,N), length(N,L) }.   % get a sequence of characters of the same type (https://www.swi-prolog.org/pldoc/doc_for?object=char_type/2) c_types([C|T],Type) --> c_type(C,Type), c_types(T,Type). c_types([C],Type) --> c_type(C,Type). c_type(C,Type) --> [C],{ char_type(C,Type) }.   anything([]) --> []. anything([A|T]) --> [A], anything(T).   string_([]) --> []. string_([A|T]) --> [A], { dif(A,'\n') }, string_(T).     /* The token types are all handled by the tok DCG, order of predicates is important here. */ % comment tok([],CLen,_,_) --> "/*", anything(A), "*/", { length(A,Len), CLen is Len + 4 }.   % toks tok(op_and(L,P),2,L,P) --> "&&". tok(op_or(L,P),2,L,P) --> "||". tok(op_lessequal(L,P),2,L,P) --> "<=". tok(op_greaterequal(L,P),2,L,P) --> ">=". tok(op_greaterequal(L,P),2,L,P) --> ">=". tok(op_equal(L,P),2,L,P) --> "==". tok(op_notequal(L,P),2,L,P) --> "!=". tok(op_assign(L,P),1,L,P) --> "=". tok(op_multiply(L,P),1,L,P) --> "*". tok(op_divide(L,P),1,L,P) --> "/". tok(op_mod(L,P),1,L,P) --> "%". tok(op_add(L,P),1,L,P) --> "+". tok(op_subtract(L,P),1,L,P) --> "-". tok(op_negate(L,P),1,L,P) --> "-". tok(op_less(L,P),1,L,P) --> "<". tok(op_greater(L,P),1,L,P) --> ">". tok(op_not(L,P),1,L,P) --> "!".   % symbols tok(left_paren(L,P),1,L,P) --> "(". tok(right_paren(L,P),1,L,P) --> ")". tok(left_brace(L,P),1,L,P) --> "{". tok(right_brace(L,P),1,L,P) --> "}". tok(semicolon(L,P),1,L,P) --> ";". tok(comma(L,P),1,L,P) --> ",".   % keywords tok(keyword_if(L,P),2,L,P) --> "if". tok(keyword_else(L,P),4,L,P) --> "else". tok(keyword_while(L,P),5,L,P) --> "while". tok(keyword_print(L,P),5,L,P) --> "print". tok(keyword_putc(L,P),4,L,P) --> "putc".   % identifier and literals tok(identifier(I,L,P),Len,L,P) --> c_type(S,csymf), identifier(T), { atom_chars(I,[S|T]), length([S|T],Len) }. tok(integer(V,L,P),Len,L,P) --> integer_(V,Len). tok(integer(I,L,P),4,L,P) --> "'\\\\'", { char_code('\\', I) }. tok(integer(I,L,P),4,L,P) --> "'\\n'", { char_code('\n', I) }. tok(integer(I,L,P),3,L,P) --> ['\''], [C], ['\''], { dif(C,'\n'), dif(C,'\''), char_code(C,I) }. tok(string(S,L,P),SLen,L,P) --> ['"'], string_(A),['"'], { atom_chars(S,A), length(A,Len), SLen is Len + 2 }.   % spaces tok(space(L,P),Len,L,P) --> c_types(S,space), { length(S,Len) }.   % anything else is an error tok(_,_,L,P) --> { format(atom(Error), 'Invalid token at line ~d,~d', [L,P]), throw(Error) }.
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"
#MMIX
MMIX
argv IS $1 argc IS $0 i IS $2   LOC #100 Main LOC @ SETL i,1 % i = 1 Loop CMP $3,argc,2 % argc < 2 ? BN $3,1F % then jump to end XOR $255,$255,$255 % clear $255 8ADDU $255,i,argv % i*8 + argv LDOU $255,$255,0 % argv[i] TRAP 0,Fputs,StdOut % write the argument GETA $255,NewLine % add a newline TRAP 0,Fputs,StdOut INCL i,1 % increment index SUB argc,argc,1 % argc-- BP argc,Loop % argc > 0? then Loop 1H LOC @ XOR $255,$255,$255 % exit(0) TRAP 0,Halt,0   NewLine BYTE #a,0
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"
#Modula-2
Modula-2
MODULE try;   FROM Arguments IMPORT GetArgs, ArgTable, GetEnv; FROM InOut IMPORT WriteCard, WriteLn, WriteString;   VAR count, item : SHORTCARD; storage : ArgTable;   BEGIN GetArgs (count, storage); WriteString ('Count ='); WriteCard (count, 4); WriteLn; item := 0; REPEAT WriteCard (item, 4); WriteString (' : '); WriteString (storage^ [item]^); WriteLn; INC (item) UNTIL item = count END try.
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.)
#Eiffel
Eiffel
-- inline comment, continues until new 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.)
#Ela
Ela
//single line comment   /*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.
#Jsish
Jsish
/* Conway's game of life, in Jsish */ function GameOfLife () { this.title = "Conway's Game of Life"; this.cls = "\u001B[H\u001B[2J";   this.init = function (turns, width, height) { this.board = new Array(height); for (var x = 0; x < height; x++) { this.board[x] = new Array(width); for (var y = 0; y < width; y++) { this.board[x][y] = Math.round(Math.random()); } } this.turns = turns; };   this.nextGen = function() { this.boardNext = new Array(this.board.length); for (var i = 0; i < this.board.length; i++) { this.boardNext[i] = new Array(this.board[i].length); } for (var x = 0; x < this.board.length; x++) { for (var y = 0; y < this.board[x].length; y++) { var n = 0; for (var dx = -1; dx <= 1; dx++) { for (var dy = -1; dy <= 1; dy++) { if ( dx == 0 && dy == 0){} else if (typeof this.board[x+dx] !== 'undefined' && typeof this.board[x+dx][y+dy] !== 'undefined' && this.board[x+dx][y+dy]) { n++; } } } var c = this.board[x][y]; switch (n) { case 0: case 1: c = 0; break; case 2: break; case 3: c = 1; break; default: c = 0; } this.boardNext[x][y] = c; } } this.board = this.boardNext.slice(0); };   this.print = function() { for (var x = 0; x < this.board.length; x++) { var l = ""; for (var y = 0; y < this.board[x].length; y++) { if (this.board[x][y]) l += "X"; else l += " "; } puts(l); } };   this.start = function() { for (var t = 0; t < this.turns; t++) { sleep(500); printf(this.cls); puts(this.title + "\n---\nTurn "+(t+1)); this.print(); this.nextGen(); } };   }   var game = new GameOfLife(); if (Interp.conf('unitTest')) { game.init(3,3,3); game.title="---\n3x3 Blinker over three turns."; game.board = [ [0,0,0], [1,1,1], [0,0,0]]; game.cls=""; game.start(); } else { game.init(3,3,3); game.title="---\n3x3 Blinker over three turns."; game.board = [ [0,0,0], [1,1,1], [0,0,0]]; game.start();   game.init(5,10,6); game.title="---\n10x6 Glider over five turns."; game.board = [ [0,0,0,0,0,0,0,0,0,0], [0,0,1,0,0,0,0,0,0,0], [0,0,0,1,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]]; game.start();   var steps = (console.args[0]) ? parseInt(console.args[0]) || 1 : 50; game.init(steps, 32,16); game.title="---\nRandom 32x16, " + steps + " step" + ((steps === 1) ? "" : "s"); game.start(); }   /* =!EXPECTSTART!= --- 3x3 Blinker over three turns. --- Turn 1   XXX   --- 3x3 Blinker over three turns. --- Turn 2 X X X --- 3x3 Blinker over three turns. --- Turn 3   XXX   =!EXPECTEND!= */
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.
#DM
DM
if (condition) // Do thing, DM uses indentation for control flow.   if (condition) // Do thing   else if (condition) // Do thing   else // Do thing  
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
#R
R
  chunks <- function (compare, xs) { starts = which(c(T, !compare(head(xs, -1), xs[-1]), T)) lapply(seq(1,length(starts)-1), function(i) xs[starts[i]:(starts[i+1]-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
#Racket
Racket
#lang racket/base (define ((list-stringX? stringX?) strs) (or (null? strs) (null? (cdr strs)) (apply stringX? strs))) (define list-string=? (list-stringX? string=?)) (define list-string<? (list-stringX? string<?))   (module+ test (require tests/eli-tester) (test (list-string=? '()) => #t (list-string=? '("a")) => #t (list-string=? '("a" "a")) => #t (list-string=? '("a" "a" "a")) => #t (list-string=? '("b" "b" "a")) => #f)   (test (list-string<? '()) => #t (list-string<? '("a")) => #t (list-string<? '("a" "b")) => #t (list-string<? '("a" "a")) => #f (list-string<? '("a" "b" "a")) => #f (list-string<? '("a" "b" "c")) => #t))
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.
#Kotlin
Kotlin
// version 1.0.6   fun commaQuibble(s: String): String { val t = s.trim('[', ']').replace(" ", "").replace("\"", "") val words = t.split(',') val sb = StringBuilder("{") for (i in 0 until words.size) { sb.append(when (i) { 0 -> "" words.lastIndex -> " and " else -> ", " }) sb.append(words[i]) } return sb.append("}").toString() }   fun main(args: Array<String>) { val inputs = arrayOf( """[]""", """["ABC"]""", """["ABC", "DEF"]""", """["ABC", "DEF", "G", "H"]""" ) for (input in inputs) println("${input.padEnd(24)} -> ${commaQuibble(input)}") }
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
#Python
Python
>>> from itertools import combinations_with_replacement >>> n, k = 'iced jam plain'.split(), 2 >>> list(combinations_with_replacement(n,k)) [('iced', 'iced'), ('iced', 'jam'), ('iced', 'plain'), ('jam', 'jam'), ('jam', 'plain'), ('plain', 'plain')] >>> # Extra credit >>> len(list(combinations_with_replacement(range(10), 3))) 220 >>>
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
#Quackery
Quackery
( nextplain generates the next plaindrome in the current base by adding one to a given plaindrome, then replacing each trailing zero with the least significant non-zero digit of the number   See: https://oeis.org/search?q=plaindromes   4 base put -1 10 times [ nextplain dup echo sp ] drop base release   prints "0 1 2 3 11 12 13 22 23 33" i.e. decimal "0 1 2 3 5 6 7 10 11 15"   Right padding the base 4 representations with zeros gives all the combinations with repetitions for selecting two doughnuts in a store selling four types of doughnut, numbered 0, 1, 2, and 3.   00 01 02 03 11 12 13 22 23 33 )   [ 1+ dup 0 = if done 0 swap [ base share /mod dup 0 = while drop dip 1+ again ] swap rot 1+ times [ base share * over + ] nip ] is nextplain ( n --> n )   [ dup base put swap ** 1 - [] swap -1 [ 2dup > while nextplain rot over join unrot again ] base release 2drop ] is kcombnums ( n n --> [ )   [ [] unrot times [ base share /mod rot join swap ] drop ] is ndigits ( n n --> [ )   [ [] unrot witheach [ dip dup peek nested rot swap join swap ] drop ] is [peek] ( [ [ --> [ )   [ dup temp put size dup base put dip dup kcombnums [] unrot witheach [ over ndigits temp share swap [peek] nested rot swap join swap ] temp release base release drop ] is kcombs ( n [ --> [ )   2 $ "jam iced plain" nest$ kcombs witheach [ witheach [ echo$ sp ] cr ] cr 3 10 kcombnums size echo
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
#Python
Python
from __future__ import print_function import sys   # following two must remain in the same order   tk_EOI, tk_Mul, tk_Div, tk_Mod, tk_Add, tk_Sub, tk_Negate, tk_Not, tk_Lss, tk_Leq, tk_Gtr, \ tk_Geq, tk_Eq, tk_Neq, tk_Assign, tk_And, tk_Or, tk_If, tk_Else, tk_While, tk_Print, \ tk_Putc, tk_Lparen, tk_Rparen, tk_Lbrace, tk_Rbrace, tk_Semi, tk_Comma, tk_Ident, \ tk_Integer, tk_String = range(31)   all_syms = ["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"]   # single character only symbols symbols = { '{': tk_Lbrace, '}': tk_Rbrace, '(': tk_Lparen, ')': tk_Rparen, '+': tk_Add, '-': tk_Sub, '*': tk_Mul, '%': tk_Mod, ';': tk_Semi, ',': tk_Comma }   key_words = {'if': tk_If, 'else': tk_Else, 'print': tk_Print, 'putc': tk_Putc, 'while': tk_While}   the_ch = " " # dummy first char - but it must be a space the_col = 0 the_line = 1 input_file = None   #*** show error and exit def error(line, col, msg): print(line, col, msg) exit(1)   #*** get the next character from the input def next_ch(): global the_ch, the_col, the_line   the_ch = input_file.read(1) the_col += 1 if the_ch == '\n': the_line += 1 the_col = 0 return the_ch   #*** 'x' - character constants def char_lit(err_line, err_col): n = ord(next_ch()) # skip opening quote if the_ch == '\'': error(err_line, err_col, "empty character constant") elif the_ch == '\\': next_ch() if the_ch == 'n': n = 10 elif the_ch == '\\': n = ord('\\') else: error(err_line, err_col, "unknown escape sequence \\%c" % (the_ch)) if next_ch() != '\'': error(err_line, err_col, "multi-character constant") next_ch() return tk_Integer, err_line, err_col, n   #*** process divide or comments def div_or_cmt(err_line, err_col): if next_ch() != '*': return tk_Div, err_line, err_col   # comment found next_ch() while True: if the_ch == '*': if next_ch() == '/': next_ch() return gettok() elif len(the_ch) == 0: error(err_line, err_col, "EOF in comment") else: next_ch()   #*** "string" def string_lit(start, err_line, err_col): global the_ch text = ""   while next_ch() != start: if len(the_ch) == 0: error(err_line, err_col, "EOF while scanning string literal") if the_ch == '\n': error(err_line, err_col, "EOL while scanning string literal") if the_ch == '\\': next_ch() if the_ch != 'n': error(err_line, err_col, "escape sequence unknown \\%c" % the_ch) the_ch = '\n' text += the_ch   next_ch() return tk_String, err_line, err_col, text   #*** handle identifiers and integers def ident_or_int(err_line, err_col): is_number = True text = ""   while the_ch.isalnum() or the_ch == '_': text += the_ch if not the_ch.isdigit(): is_number = False next_ch()   if len(text) == 0: error(err_line, err_col, "ident_or_int: unrecognized character: (%d) '%c'" % (ord(the_ch), the_ch))   if text[0].isdigit(): if not is_number: error(err_line, err_col, "invalid number: %s" % (text)) n = int(text) return tk_Integer, err_line, err_col, n   if text in key_words: return key_words[text], err_line, err_col   return tk_Ident, err_line, err_col, text   #*** look ahead for '>=', etc. def follow(expect, ifyes, ifno, err_line, err_col): if next_ch() == expect: next_ch() return ifyes, err_line, err_col   if ifno == tk_EOI: error(err_line, err_col, "follow: unrecognized character: (%d) '%c'" % (ord(the_ch), the_ch))   return ifno, err_line, err_col   #*** return the next token type def gettok(): while the_ch.isspace(): next_ch()   err_line = the_line err_col = the_col   if len(the_ch) == 0: return tk_EOI, err_line, err_col elif the_ch == '/': return div_or_cmt(err_line, err_col) elif the_ch == '\'': return char_lit(err_line, err_col) elif the_ch == '<': return follow('=', tk_Leq, tk_Lss, err_line, err_col) elif the_ch == '>': return follow('=', tk_Geq, tk_Gtr, err_line, err_col) elif the_ch == '=': return follow('=', tk_Eq, tk_Assign, err_line, err_col) elif the_ch == '!': return follow('=', tk_Neq, tk_Not, err_line, err_col) elif the_ch == '&': return follow('&', tk_And, tk_EOI, err_line, err_col) elif the_ch == '|': return follow('|', tk_Or, tk_EOI, err_line, err_col) elif the_ch == '"': return string_lit(the_ch, err_line, err_col) elif the_ch in symbols: sym = symbols[the_ch] next_ch() return sym, err_line, err_col else: return ident_or_int(err_line, err_col)   #*** main driver input_file = sys.stdin if len(sys.argv) > 1: try: input_file = open(sys.argv[1], "r", 4096) except IOError as e: error(0, 0, "Can't open %s" % sys.argv[1])   while True: t = gettok() tok = t[0] line = t[1] col = t[2]   print("%5d  %5d  %-14s" % (line, col, all_syms[tok]), end='')   if tok == tk_Integer: print("  %5d" % (t[3])) elif tok == tk_Ident: print("  %s" % (t[3])) elif tok == tk_String: print(' "%s"' % (t[3])) else: print("")   if tok == tk_EOI: break
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"
#Modula-3
Modula-3
MODULE Args EXPORTS Main;   IMPORT IO, Params;   BEGIN IO.Put(Params.Get(0) & "\n"); IF Params.Count > 1 THEN FOR i := 1 TO Params.Count - 1 DO IO.Put(Params.Get(i) & "\n"); END; END; END 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"
#Nanoquery
Nanoquery
// // command-line arguments //   // output all arguments for i in range(0, len(args) - 1) println args[i] end