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/Parsing/RPN_calculator_algorithm
Parsing/RPN calculator algorithm
Task Create a stack-based evaluator for an expression in   reverse Polish notation (RPN)   that also shows the changes in the stack as each individual token is processed as a table. Assume an input of a correct, space separated, string of tokens of an RPN expression Test with the RPN expression generated from the   Parsing/Shunting-yard algorithm   task:         3 4 2 * 1 5 - 2 3 ^ ^ / + Print or display the output here Notes   ^   means exponentiation in the expression above.   /   means division. See also   Parsing/Shunting-yard algorithm for a method of generating an RPN from an infix expression.   Several solutions to 24 game/Solve make use of RPN evaluators (although tracing how they work is not a part of that task).   Parsing/RPN to infix conversion.   Arithmetic evaluation.
#Icon_and_Unicon
Icon and Unicon
procedure main() EvalRPN("3 4 2 * 1 5 - 2 3 ^ ^ / +") end   link printf invocable all   procedure EvalRPN(expr) #: evaluate (and trace stack) an RPN string   stack := [] expr ? until pos(0) do { tab(many(' ')) # consume previous seperator token := tab(upto(' ')|0) # get token if token := numeric(token) then { # ... numeric push(stack,token) printf("pushed numeric  %i : %s\n",token,list2string(stack)) } else { # ... operator every b|a := pop(stack) # pop & reverse operands case token of { "+"|"-"|"*"|"^" : push(stack,token(a,b)) "/" : push(stack,token(real(a),b)) default : runerr(205,token) } printf("applied operator %s : %s\n",token,list2string(stack)) } } end   procedure list2string(L) #: format list as a string every (s := "[ ") ||:= !L || " " return s || "]" end
http://rosettacode.org/wiki/Palindrome_detection
Palindrome detection
A palindrome is a phrase which reads the same backward and forward. Task[edit] Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. For extra credit: Support Unicode characters. Write a second function (possibly as a wrapper to the first) which detects inexact palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used. Hints It might be useful for this task to know how to reverse a string. This task's entries might also form the subjects of the task Test a function. Related tasks Word plays Ordered words Palindrome detection Semordnilap Anagrams Anagrams/Deranged anagrams 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
#ARM_Assembly
ARM Assembly
@ Check whether the ASCII string in [r0] is a palindrome @ Returns with zero flag set if palindrome. palin: mov r1,r0 @ Find end of string 1: ldrb r2,[r1],#1 @ Grab character and increment pointer tst r2,r2 @ Zero yet? bne 1b @ If not try next byte sub r1,r1,#2 @ Move R1 to last actual character. 2: cmp r0,r1 @ When R0 >= R1, cmpgt r2,r2 @ make sure zero is set, bxeq lr @ and stop (the string is a palindrome). ldrb r2,[r1],#-1 @ Grab [R1] (end) and decrement. ldrb r3,[r0],#1 @ Grab [R0] (begin) and increment cmp r2,r3 @ Are they equal? bxne lr @ If not, it's not a palindrome. b 2b @ Otherwise, try next pair.   @ Try the function on a couple of strings .global _start _start: ldr r8,=words @ Word pointer 1: ldr r9,[r8],#4 @ Grab word and move pointer tst r9,r9 @ Null? moveq r7,#1 @ Then we're done; syscall 1 = exit swieq #0 mov r1,r9 @ Print the word bl print mov r0,r9 @ Test if the word is a palindrome bl palin ldreq r1,=yes @ "Yes" if it is a palindrome ldrne r1,=no @ "No" if it's not a palindrome bl print b 1b @ Next word   @ Print zero-terminated string [r1] using Linux syscall print: push {r7,lr} @ Keep R7 and link register mov r2,r1 @ Find end of string 1: ldrb r0,[r2],#1 @ Grab character and increment pointer tst r0,r0 @ Zero yet? bne 1b @ If not, keep going sub r2,r2,r1 @ Calculate length of string (bytes to write) mov r0,#1 @ Stdout = 1 mov r7,#4 @ Syscall 4 = write swi #0 @ Make the syscall pop {r7,lr} @ Restore R7 and link register bx lr   @ Strings yes: .asciz ": yes\n" @ Output yes or no no: .asciz ": no\n" w1: .asciz "rotor" @ Words to test w2: .asciz "racecar" w3: .asciz "level" w4: .asciz "redder" w5: .asciz "rosetta" words: .word w1,w2,w3,w4,w5,0
http://rosettacode.org/wiki/Palindromic_gapful_numbers
Palindromic gapful numbers
Palindromic gapful numbers You are encouraged to solve this task according to the task description, using any language you may know. Numbers   (positive integers expressed in base ten)   that are (evenly) divisible by the number formed by the first and last digit are known as   gapful numbers. Evenly divisible   means divisible with   no   remainder. All   one─   and two─digit   numbers have this property and are trivially excluded.   Only numbers   ≥ 100   will be considered for this Rosetta Code task. Example 1037   is a   gapful   number because it is evenly divisible by the number   17   which is formed by the first and last decimal digits of   1037. A palindromic number is   (for this task, a positive integer expressed in base ten),   when the number is reversed,   is the same as the original number. Task   Show   (nine sets)   the first   20   palindromic gapful numbers that   end   with:   the digit   1   the digit   2   the digit   3   the digit   4   the digit   5   the digit   6   the digit   7   the digit   8   the digit   9   Show   (nine sets, like above)   of palindromic gapful numbers:   the last   15   palindromic gapful numbers   (out of      100)   the last   10   palindromic gapful numbers   (out of   1,000)       {optional} For other ways of expressing the (above) requirements, see the   discussion   page. Note All palindromic gapful numbers are divisible by eleven. Related tasks   palindrome detection.   gapful numbers. Also see   The OEIS entry:   A108343 gapful numbers.
#Pascal
Pascal
9 : 96878077087869 9 : 9687870990787869 9 : 968787783387787869
http://rosettacode.org/wiki/Parsing/Shunting-yard_algorithm
Parsing/Shunting-yard algorithm
Task Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output as each individual token is processed. Assume an input of a correct, space separated, string of tokens representing an infix expression Generate a space separated output string representing the RPN Test with the input string: 3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3 print and display the output here. Operator precedence is given in this table: operator precedence associativity operation ^ 4 right exponentiation * 3 left multiplication / 3 left division + 2 left addition - 2 left subtraction Extra credit Add extra text explaining the actions and an optional comment for the action on receipt of each token. Note The handling of functions and arguments is not required. See also Parsing/RPN calculator algorithm for a method of calculating a final value from this output RPN expression. Parsing/RPN to infix conversion.
#PicoLisp
PicoLisp
(de operator (Op) (member Op '("\^" "*" "/" "+" "-")) )   (de leftAssoc (Op) (member Op '("*" "/" "+" "-")) )   (de precedence (Op) (case Op ("\^" 4) (("*" "/") 3) (("+" "-") 2) ) )   (de shuntingYard (Str) (make (let (Fmt (-7 -30 -4) Stack) (tab Fmt "Token" "Output" "Stack") (for Token (str Str "_") (cond ((num? Token) (link @)) ((= "(" Token) (push 'Stack Token)) ((= ")" Token) (until (= "(" (car Stack)) (unless Stack (quit "Unbalanced Stack") ) (link (pop 'Stack)) ) (pop 'Stack) ) (T (while (and (operator (car Stack)) ((if (leftAssoc (car Stack)) <= <) (precedence Token) (precedence (car Stack)) ) ) (link (pop 'Stack)) ) (push 'Stack Token) ) ) (tab Fmt Token (glue " " (made)) Stack) ) (while Stack (when (= "(" (car Stack)) (quit "Unbalanced Stack") ) (link (pop 'Stack)) (tab Fmt NIL (glue " " (made)) Stack) ) ) ) )
http://rosettacode.org/wiki/Parsing/Shunting-yard_algorithm
Parsing/Shunting-yard algorithm
Task Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output as each individual token is processed. Assume an input of a correct, space separated, string of tokens representing an infix expression Generate a space separated output string representing the RPN Test with the input string: 3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3 print and display the output here. Operator precedence is given in this table: operator precedence associativity operation ^ 4 right exponentiation * 3 left multiplication / 3 left division + 2 left addition - 2 left subtraction Extra credit Add extra text explaining the actions and an optional comment for the action on receipt of each token. Note The handling of functions and arguments is not required. See also Parsing/RPN calculator algorithm for a method of calculating a final value from this output RPN expression. Parsing/RPN to infix conversion.
#PL.2FI
PL/I
  cvt: procedure options (main); /* 15 January 2012. */ declare (in, stack, out) character (100) varying; declare (ch, chs) character (1); declare display bit (1) static initial ('0'b);   in = '3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3';   in = '(' || in || ' ) '; /* Initialize with parentheses */   put skip edit ('INPUT', 'STACK', 'OUTPUT') (a, col(37), a, col(47), a);   stack = ' '; out = ''; /* Initialize */ do while (length (in) > 0); ch = substr(in, 1, 1); select (ch); when (' ') ;   when ('+', '-', '*', '/', '^') do; /* Copy any equal or higher-priority operators from the stack */ /* to the output string */ chs = substr(stack, 1, 1); do while ((spriority(chs) >= priority(ch)) & ( chs ^= ')' ) ); if display then put skip list ('unstacking: ' || chs); out = out || ' ' || chs; stack = substr(stack, 2); chs = substr(stack, 1, 1); end; /* Now copy the input to the TOS. */ if display then put skip list ('copying ' || ch || ' to TOS'); stack = ch || stack; end; when ( '(' ) do; stack = '(' || stack; if display then put skip list ('stacking the (' ); end; when ( ')' ) do; /* copy all operators from the stack to the output, */ /* until a '(' is encountered. */ chs = substr(stack, 1, 1); do while (chs ^= '(' ); if display then put skip list ('copying stack ' || chs || ' to output'); put skip edit (stack, out) (col(37), a, col(47), a); out = out || ' ' || chs; stack = substr(stack, 2); chs = substr(stack, 1, 1); end; /* Now delete the '(' from the input and */ /* the ')' from the top of the stack. */ if display then put skip edit ('Deleting ( from TOS') (col(30), a); stack = substr(stack, 2); /* The '(' on the input is removed at the end of the loop. */ end; otherwise /* it's an operand. */ do; out = out || ' '; do while (ch ^= ' '); if display then put skip list ('copying ' || ch || ' to output'); out = out || ch; in = substr(in, 2); ch = substr(in, 1, 1); end; end; end; in = substr(in, 2); /* Remove one character from the input */ put skip edit (in, stack, out) (a, col(37), a, col(47), a); end;   priority: procedure (ch) returns (character(1)); declare ch character (1);   return ( translate(ch, '1122335', '()+-*/^' ) ); end priority;   spriority: procedure (ch) returns (character(1)); declare ch character (1);   return ( translate(ch, '1122334', '()+-*/^' ) ); end spriority;   end cvt;  
http://rosettacode.org/wiki/Paraffins
Paraffins
This organic chemistry task is essentially to implement a tree enumeration algorithm. Task Enumerate, without repetitions and in order of increasing size, all possible paraffin molecules (also known as alkanes). Paraffins are built up using only carbon atoms, which has four bonds, and hydrogen, which has one bond.   All bonds for each atom must be used, so it is easiest to think of an alkane as linked carbon atoms forming the "backbone" structure, with adding hydrogen atoms linking the remaining unused bonds. In a paraffin, one is allowed neither double bonds (two bonds between the same pair of atoms), nor cycles of linked carbons.   So all paraffins with   n   carbon atoms share the empirical formula     CnH2n+2 But for all   n ≥ 4   there are several distinct molecules ("isomers") with the same formula but different structures. The number of isomers rises rather rapidly when   n   increases. In counting isomers it should be borne in mind that the four bond positions on a given carbon atom can be freely interchanged and bonds rotated (including 3-D "out of the paper" rotations when it's being observed on a flat diagram),   so rotations or re-orientations of parts of the molecule (without breaking bonds) do not give different isomers.   So what seem at first to be different molecules may in fact turn out to be different orientations of the same molecule. Example With   n = 3   there is only one way of linking the carbons despite the different orientations the molecule can be drawn;   and with   n = 4   there are two configurations:   a   straight   chain:     (CH3)(CH2)(CH2)(CH3)   a branched chain:       (CH3)(CH(CH3))(CH3) Due to bond rotations, it doesn't matter which direction the branch points in. The phenomenon of "stereo-isomerism" (a molecule being different from its mirror image due to the actual 3-D arrangement of bonds) is ignored for the purpose of this task. The input is the number   n   of carbon atoms of a molecule (for instance 17). The output is how many different different paraffins there are with   n   carbon atoms (for instance   24,894   if   n = 17). The sequence of those results is visible in the OEIS entry:     oeis:A00602 number of n-node unrooted quartic trees; number of n-carbon alkanes C(n)H(2n+2) ignoring stereoisomers. The sequence is (the index starts from zero, and represents the number of carbon atoms): 1, 1, 1, 1, 2, 3, 5, 9, 18, 35, 75, 159, 355, 802, 1858, 4347, 10359, 24894, 60523, 148284, 366319, 910726, 2278658, 5731580, 14490245, 36797588, 93839412, 240215803, 617105614, 1590507121, 4111846763, 10660307791, 27711253769, ... Extra credit Show the paraffins in some way. A flat 1D representation, with arrays or lists is enough, for instance: *Main> all_paraffins 1 [CCP H H H H] *Main> all_paraffins 2 [BCP (C H H H) (C H H H)] *Main> all_paraffins 3 [CCP H H (C H H H) (C H H H)] *Main> all_paraffins 4 [BCP (C H H (C H H H)) (C H H (C H H H)), CCP H (C H H H) (C H H H) (C H H H)] *Main> all_paraffins 5 [CCP H H (C H H (C H H H)) (C H H (C H H H)), CCP H (C H H H) (C H H H) (C H H (C H H H)), CCP (C H H H) (C H H H) (C H H H) (C H H H)] *Main> all_paraffins 6 [BCP (C H H (C H H (C H H H))) (C H H (C H H (C H H H))), BCP (C H H (C H H (C H H H))) (C H (C H H H) (C H H H)), BCP (C H (C H H H) (C H H H)) (C H (C H H H) (C H H H)), CCP H (C H H H) (C H H (C H H H)) (C H H (C H H H)), CCP (C H H H) (C H H H) (C H H H) (C H H (C H H H))] Showing a basic 2D ASCII-art representation of the paraffins is better; for instance (molecule names aren't necessary): methane ethane propane isobutane   H H H H H H H H H │ │ │ │ │ │ │ │ │ H ─ C ─ H H ─ C ─ C ─ H H ─ C ─ C ─ C ─ H H ─ C ─ C ─ C ─ H │ │ │ │ │ │ │ │ │ H H H H H H H │ H │ H ─ C ─ H │ H Links   A paper that explains the problem and its solution in a functional language: http://www.cs.wright.edu/~tkprasad/courses/cs776/paraffins-turner.pdf   A Haskell implementation: https://github.com/ghc/nofib/blob/master/imaginary/paraffins/Main.hs   A Scheme implementation: http://www.ccs.neu.edu/home/will/Twobit/src/paraffins.scm   A Fortress implementation:         (this site has been closed) http://java.net/projects/projectfortress/sources/sources/content/ProjectFortress/demos/turnersParaffins0.fss?rev=3005
#Ruby
Ruby
MAX_N = 500 BRANCH = 4   def tree(br, n, l=n, sum=1, cnt=1) for b in br+1 .. BRANCH sum += n return if sum >= MAX_N # prevent unneeded long math return if l * 2 >= sum and b >= BRANCH if b == br + 1 c = $ra[n] * cnt else c = c * ($ra[n] + (b - br - 1)) / (b - br) end $unrooted[sum] += c if l * 2 < sum next if b >= BRANCH $ra[sum] += c (1...n).each {|m| tree(b, m, l, sum, c)} end end   def bicenter(s) return if s.odd? aux = $ra[s / 2] $unrooted[s] += aux * (aux + 1) / 2 end   $ra = [0] * MAX_N $unrooted = [0] * MAX_N   $ra[0] = $ra[1] = $unrooted[0] = $unrooted[1] = 1 for n in 1...MAX_N tree(0, n) bicenter(n) puts "%d: %d" % [n, $unrooted[n]] end
http://rosettacode.org/wiki/Pangram_checker
Pangram checker
Pangram checker You are encouraged to solve this task according to the task description, using any language you may know. A pangram is a sentence that contains all the letters of the English alphabet at least once. For example:   The quick brown fox jumps over the lazy dog. Task Write a function or method to check a sentence to see if it is a   pangram   (or not)   and show its use. Related tasks   determine if a string has all the same characters   determine if a string has all unique characters
#Component_Pascal
Component Pascal
  MODULE BbtPangramChecker; IMPORT StdLog,DevCommanders,TextMappers;   PROCEDURE Check(str: ARRAY OF CHAR): BOOLEAN; CONST letters = 26; VAR i,j: INTEGER; status: ARRAY letters OF BOOLEAN; resp : BOOLEAN; BEGIN FOR i := 0 TO LEN(status) -1 DO status[i] := FALSE END;   FOR i := 0 TO LEN(str) - 1 DO j := ORD(CAP(str[i])) - ORD('A'); IF (0 <= j) & (25 >= j) & ~status[j] THEN status[j] := TRUE END END;   resp := TRUE; FOR i := 0 TO LEN(status) - 1 DO; resp := resp & status[i] END; RETURN resp; END Check;   PROCEDURE Do*; VAR params: DevCommanders.Par; s: TextMappers.Scanner; BEGIN params := DevCommanders.par; s.ConnectTo(params.text); s.SetPos(params.beg); s.Scan; WHILE (~s.rider.eot) DO IF (s.type = TextMappers.char) & (s.char = '~') THEN RETURN ELSIF (s.type # TextMappers.string) THEN StdLog.String("Invalid parameter");StdLog.Ln ELSE StdLog.Char("'");StdLog.String(s.string + "' is pangram?:> "); StdLog.Bool(Check(s.string));StdLog.Ln END; s.Scan END END Do;   END BbtPangramChecker.  
http://rosettacode.org/wiki/Pascal_matrix_generation
Pascal matrix generation
A pascal matrix is a two-dimensional square matrix holding numbers from   Pascal's triangle,   also known as   binomial coefficients   and which can be shown as   nCr. Shown below are truncated   5-by-5   matrices   M[i, j]   for   i,j   in range   0..4. A Pascal upper-triangular matrix that is populated with   jCi: [[1, 1, 1, 1, 1], [0, 1, 2, 3, 4], [0, 0, 1, 3, 6], [0, 0, 0, 1, 4], [0, 0, 0, 0, 1]] A Pascal lower-triangular matrix that is populated with   iCj   (the transpose of the upper-triangular matrix): [[1, 0, 0, 0, 0], [1, 1, 0, 0, 0], [1, 2, 1, 0, 0], [1, 3, 3, 1, 0], [1, 4, 6, 4, 1]] A Pascal symmetric matrix that is populated with   i+jCi: [[1, 1, 1, 1, 1], [1, 2, 3, 4, 5], [1, 3, 6, 10, 15], [1, 4, 10, 20, 35], [1, 5, 15, 35, 70]] Task Write functions capable of generating each of the three forms of   n-by-n   matrices. Use those functions to display upper, lower, and symmetric Pascal   5-by-5   matrices on this page. The output should distinguish between different matrices and the rows of each matrix   (no showing a list of 25 numbers assuming the reader should split it into rows). Note The   Cholesky decomposition   of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size.
#Lua
Lua
function factorial (n) local f = 1 for i = 2, n do f = f * i end return f end   function binomial (n, k) if k > n then return 0 end return factorial(n) / (factorial(k) * factorial(n - k)) end   function pascalMatrix (form, size) local matrix = {} for row = 1, size do matrix[row] = {} for col = 1, size do if form == "upper" then matrix[row][col] = binomial(col - 1, row - 1) end if form == "lower" then matrix[row][col] = binomial(row - 1, col - 1) end if form == "symmetric" then matrix[row][col] = binomial(row + col - 2, col - 1) end end end matrix.form = form:sub(1, 1):upper() .. form:sub(2, -1) return matrix end   function show (mat) print(mat.form .. ":") for i = 1, #mat do for j = 1, #mat[i] do io.write(mat[i][j] .. "\t") end print() end print() end   for _, form in pairs({"upper", "lower", "symmetric"}) do show(pascalMatrix(form, 5)) end
http://rosettacode.org/wiki/Pascal%27s_triangle
Pascal's triangle
Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is either 1 or the sum of the two elements right above it. For example, the next row of the triangle would be:   1   (since the first element of each row doesn't have two elements above it)   4   (1 + 3)   6   (3 + 3)   4   (3 + 1)   1   (since the last element of each row doesn't have two elements above it) So the triangle now looks like this: 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 Each row   n   (starting with row   0   at the top) shows the coefficients of the binomial expansion of   (x + y)n. Task Write a function that prints out the first   n   rows of the triangle   (with   f(1)   yielding the row consisting of only the element 1). This can be done either by summing elements from the previous rows or using a binary coefficient or combination function. Behavior for   n ≤ 0   does not need to be uniform, but should be noted. See also Evaluate binomial coefficients
#E
E
def pascalsTriangle(n, out) { def row := [].diverge(int) out.print("<table style='text-align: center; border: 0; border-collapse: collapse;'>") for y in 1..n { out.print("<tr>") row.push(1) def skip := n - y if (skip > 0) { out.print(`<td colspan="$skip"></td>`) } for x => v in row { out.print(`<td>$v</td><td></td>`) } for i in (1..!y).descending() { row[i] += row[i - 1] } out.println("</tr>") } out.print("</table>") }
http://rosettacode.org/wiki/Parsing/RPN_to_infix_conversion
Parsing/RPN to infix conversion
Parsing/RPN to infix conversion You are encouraged to solve this task according to the task description, using any language you may know. Task Create a program that takes an RPN representation of an expression formatted as a space separated sequence of tokens and generates the equivalent expression in infix notation. Assume an input of a correct, space separated, string of tokens Generate a space separated output string representing the same expression in infix notation Show how the major datastructure of your algorithm changes with each new token parsed. Test with the following input RPN strings then print and display the output here. RPN input sample output 3 4 2 * 1 5 - 2 3 ^ ^ / + 3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3 1 2 + 3 4 + ^ 5 6 + ^ ( ( 1 + 2 ) ^ ( 3 + 4 ) ) ^ ( 5 + 6 ) Operator precedence and operator associativity is given in this table: operator precedence associativity operation ^ 4 right exponentiation * 3 left multiplication / 3 left division + 2 left addition - 2 left subtraction See also   Parsing/Shunting-yard algorithm   for a method of generating an RPN from an infix expression.   Parsing/RPN calculator algorithm   for a method of calculating a final value from this output RPN expression.   Postfix to infix   from the RubyQuiz site.
#Ruby
Ruby
rpn = RPNExpression.new("3 4 2 * 1 5 - 2 3 ^ ^ / +") infix = rpn.to_infix ruby = rpn.to_ruby
http://rosettacode.org/wiki/Parsing/RPN_to_infix_conversion
Parsing/RPN to infix conversion
Parsing/RPN to infix conversion You are encouraged to solve this task according to the task description, using any language you may know. Task Create a program that takes an RPN representation of an expression formatted as a space separated sequence of tokens and generates the equivalent expression in infix notation. Assume an input of a correct, space separated, string of tokens Generate a space separated output string representing the same expression in infix notation Show how the major datastructure of your algorithm changes with each new token parsed. Test with the following input RPN strings then print and display the output here. RPN input sample output 3 4 2 * 1 5 - 2 3 ^ ^ / + 3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3 1 2 + 3 4 + ^ 5 6 + ^ ( ( 1 + 2 ) ^ ( 3 + 4 ) ) ^ ( 5 + 6 ) Operator precedence and operator associativity is given in this table: operator precedence associativity operation ^ 4 right exponentiation * 3 left multiplication / 3 left division + 2 left addition - 2 left subtraction See also   Parsing/Shunting-yard algorithm   for a method of generating an RPN from an infix expression.   Parsing/RPN calculator algorithm   for a method of calculating a final value from this output RPN expression.   Postfix to infix   from the RubyQuiz site.
#Sidef
Sidef
func p(pair, prec) { pair[0] < prec ? "( #{pair[1]} )" : pair[1] }   func rpm_to_infix(string) { say "#{'='*17}\n#{string}" var stack = [] string.each_word { |w| if (w ~~ /\d/) { stack << [9, Num(w)] } else { var y = stack.pop var x = stack.pop given(w) { when ('^') { stack << [4, [p(x,5), w, p(y,4)].join(' ')] } when (<* />) { stack << [3, [p(x,3), w, p(y,3)].join(' ')] } when (<+ ->) { stack << [2, [p(x,2), w, p(y,2)].join(' ')] } } say stack } } say '-'*17 stack.map{_[1]} }   var tests = [ '3 4 2 * 1 5 - 2 3 ^ ^ / +', '1 2 + 3 4 + ^ 5 6 + ^', ]   tests.each { say rpm_to_infix(_).join(' ') }
http://rosettacode.org/wiki/Partial_function_application
Partial function application
Partial function application   is the ability to take a function of many parameters and apply arguments to some of the parameters to create a new function that needs only the application of the remaining arguments to produce the equivalent of applying all arguments to the original function. E.g: Given values v1, v2 Given f(param1, param2) Then partial(f, param1=v1) returns f'(param2) And f(param1=v1, param2=v2) == f'(param2=v2) (for any value v2) Note that in the partial application of a parameter, (in the above case param1), other parameters are not explicitly mentioned. This is a recurring feature of partial function application. Task Create a function fs( f, s ) that takes a function, f( n ), of one value and a sequence of values s. Function fs should return an ordered sequence of the result of applying function f to every value of s in turn. Create function f1 that takes a value and returns it multiplied by 2. Create function f2 that takes a value and returns it squared. Partially apply f1 to fs to form function fsf1( s ) Partially apply f2 to fs to form function fsf2( s ) Test fsf1 and fsf2 by evaluating them with s being the sequence of integers from 0 to 3 inclusive and then the sequence of even integers from 2 to 8 inclusive. Notes In partially applying the functions f1 or f2 to fs, there should be no explicit mention of any other parameters to fs, although introspection of fs within the partial applicator to find its parameters is allowed. This task is more about how results are generated rather than just getting results.
#Raku
Raku
sub fs ( Code $f, @s ) { @s.map: { .$f } }   sub f1 ( $n ) { $n * 2 } sub f2 ( $n ) { $n ** 2 }   my &fsf1 := &fs.assuming(&f1); my &fsf2 := &fs.assuming(&f2);   for [1..3], [2, 4 ... 8] X &fsf1, &fsf2 -> ($s, $f) { say $f.($s); }
http://rosettacode.org/wiki/Password_generator
Password generator
Create a password generation program which will generate passwords containing random ASCII characters from the following groups: lower-case letters: a ──► z upper-case letters: A ──► Z digits: 0 ──► 9 other printable characters:  !"#$%&'()*+,-./:;<=>?@[]^_{|}~ (the above character list excludes white-space, backslash and grave) The generated password(s) must include   at least one   (of each of the four groups): lower-case letter, upper-case letter, digit (numeral),   and one "other" character. The user must be able to specify the password length and the number of passwords to generate. The passwords should be displayed or written to a file, one per line. The randomness should be from a system source or library. The program should implement a help option or button which should describe the program and options when invoked. You may also allow the user to specify a seed value, and give the option of excluding visually similar characters. For example:           Il1     O0     5S     2Z           where the characters are:   capital eye, lowercase ell, the digit one   capital oh, the digit zero   the digit five, capital ess   the digit two, capital zee
#Ring
Ring
  # Project : Password generator   chars = list(4) strp = list(2) password = "" chars[1] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" chars[2] = "abcdefghijklmnopqrstuvwxyz" chars[3] = "0123456789" chars[4] = "!\#$%&'()*+,-./:;<=>?@[]^_{|}~"   init() plen = number(strp[1])   for n = 1 to strp[2] passwords(chars) see "password = " + password + nl next   func passwords(chars) index = 0 password = "" while index < plen index = index + 1 charsind1 = index % len(chars) + 1 charsind2 = random(len(chars[charsind1])-1) + 1 password = password + chars[charsind1][charsind2] end   func init() fp = fopen("C:\Ring\calmosoft\pwgen.ring","r") r = "" str = "" nr = 0 while isstring(r) r = fgetc(fp) if r != char(10) and not feof(fp) str = str + r nr = nr + 1 strp[nr] = str else str = "" ok end fclose(fp)  
http://rosettacode.org/wiki/Parallel_brute_force
Parallel brute force
Task Find, through brute force, the five-letter passwords corresponding with the following SHA-256 hashes: 1. 1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad 2. 3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b 3. 74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f Your program should naively iterate through all possible passwords consisting only of five lower-case ASCII English letters. It should use concurrent or parallel processing, if your language supports that feature. You may calculate SHA-256 hashes by calling a library or through a custom implementation. Print each matching password, along with its SHA-256 hash. Related task: SHA-256
#Visual_Basic_.NET
Visual Basic .NET
Imports System.Text   Module Module1   Function Matches(a As Byte(), b As Byte()) As Boolean For i = 0 To 31 If a(i) <> b(i) Then Return False End If Next Return True End Function   Function StringHashToByteArray(s As String) As Byte() Return Enumerable.Range(0, s.Length / 2).Select(Function(i) CType(Convert.ToInt16(s.Substring(i * 2, 2), 16), Byte)).ToArray End Function   Sub Main() Dim h1 = StringHashToByteArray("1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad") Dim h2 = StringHashToByteArray("3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b") Dim h3 = StringHashToByteArray("74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f")   Parallel.For(0, 26, Sub(a As Integer) Dim sha = Security.Cryptography.SHA256.Create() Dim password(4) As Byte Dim hash As Byte()   password(0) = 97 + a   password(1) = 97 While password(1) < 123 password(2) = 97 While password(2) < 123 password(3) = 97 While password(3) < 123 password(4) = 97 While password(4) < 123 hash = sha.ComputeHash(password) If Matches(h1, hash) OrElse Matches(h2, hash) OrElse Matches(h3, hash) Then Console.WriteLine(Encoding.ASCII.GetString(password) + " => " + BitConverter.ToString(hash).ToLower().Replace("-", "")) End If password(4) += 1 End While password(3) += 1 End While password(2) += 1 End While password(1) += 1 End While End Sub) End Sub   End Module
http://rosettacode.org/wiki/Parallel_calculations
Parallel calculations
Many programming languages allow you to specify computations to be run in parallel. While Concurrent computing is focused on concurrency, the purpose of this task is to distribute time-consuming calculations on as many CPUs as possible. Assume we have a collection of numbers, and want to find the one with the largest minimal prime factor (that is, the one that contains relatively large factors). To speed up the search, the factorization should be done in parallel using separate threads or processes, to take advantage of multi-core CPUs. Show how this can be formulated in your language. Parallelize the factorization of those numbers, then search the returned list of numbers and factors for the largest minimal factor, and return that number and its prime factors. For the prime number decomposition you may use the solution of the Prime decomposition task.
#Rust
Rust
  //! This solution uses [rayon](https://github.com/rayon-rs/rayon), a data-parallelism library. //! Since Rust guarantees that a program has no data races, adding parallelism to a sequential //! computation is as easy as importing the rayon traits and calling the `par_iter()` method.   extern crate rayon;   extern crate prime_decomposition;   use rayon::prelude::*;   /// Returns the largest minimal factor of the numbers in a slice pub fn largest_min_factor(numbers: &[usize]) -> usize { numbers .par_iter() .map(|n| { // `factor` returns a sorted vector, so we just take the first element. prime_decomposition::factor(*n)[0] }) .max() .unwrap() }   fn main() { let numbers = &[ 1_122_725, 1_125_827, 1_122_725, 1_152_800, 1_157_978, 1_099_726, ]; let max = largest_min_factor(numbers); println!("The largest minimal factor is {}", max); }  
http://rosettacode.org/wiki/Parallel_calculations
Parallel calculations
Many programming languages allow you to specify computations to be run in parallel. While Concurrent computing is focused on concurrency, the purpose of this task is to distribute time-consuming calculations on as many CPUs as possible. Assume we have a collection of numbers, and want to find the one with the largest minimal prime factor (that is, the one that contains relatively large factors). To speed up the search, the factorization should be done in parallel using separate threads or processes, to take advantage of multi-core CPUs. Show how this can be formulated in your language. Parallelize the factorization of those numbers, then search the returned list of numbers and factors for the largest minimal factor, and return that number and its prime factors. For the prime number decomposition you may use the solution of the Prime decomposition task.
#SequenceL
SequenceL
import <Utilities/Conversion.sl>; import <Utilities/Math.sl>; import <Utilities/Sequence.sl>;   main(args(2)) := let inputs := stringToInt(args); factored := primeFactorization(inputs); minFactors := vectorMin(factored);   indexOfMax := firstIndexOf(minFactors, vectorMax(minFactors)); in "Number " ++ intToString(inputs[indexOfMax]) ++ " has largest minimal factor:\n" ++ delimit(intToString(factored[indexOfMax]), ' ');
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm
Parsing/RPN calculator algorithm
Task Create a stack-based evaluator for an expression in   reverse Polish notation (RPN)   that also shows the changes in the stack as each individual token is processed as a table. Assume an input of a correct, space separated, string of tokens of an RPN expression Test with the RPN expression generated from the   Parsing/Shunting-yard algorithm   task:         3 4 2 * 1 5 - 2 3 ^ ^ / + Print or display the output here Notes   ^   means exponentiation in the expression above.   /   means division. See also   Parsing/Shunting-yard algorithm for a method of generating an RPN from an infix expression.   Several solutions to 24 game/Solve make use of RPN evaluators (although tracing how they work is not a part of that task).   Parsing/RPN to infix conversion.   Arithmetic evaluation.
#J
J
a: , <;._1 ' ' , '3 4 2 * 1 5 - 2 3 ^ ^ / +' ┌┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┐ ││3│4│2│*│1│5│-│2│3│^│^│/│+│ └┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┘
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm
Parsing/RPN calculator algorithm
Task Create a stack-based evaluator for an expression in   reverse Polish notation (RPN)   that also shows the changes in the stack as each individual token is processed as a table. Assume an input of a correct, space separated, string of tokens of an RPN expression Test with the RPN expression generated from the   Parsing/Shunting-yard algorithm   task:         3 4 2 * 1 5 - 2 3 ^ ^ / + Print or display the output here Notes   ^   means exponentiation in the expression above.   /   means division. See also   Parsing/Shunting-yard algorithm for a method of generating an RPN from an infix expression.   Several solutions to 24 game/Solve make use of RPN evaluators (although tracing how they work is not a part of that task).   Parsing/RPN to infix conversion.   Arithmetic evaluation.
#Java_2
Java
  import java.util.LinkedList;   public class RPN{ public static void main(String[] args) { evalRPN("3 4 2 * 1 5 - 2 3 ^ ^ / +"); }   private static void evalRPN(String expr){ LinkedList<Double> stack = new LinkedList<Double>(); System.out.println("Input\tOperation\tStack after"); for (String token : expr.split("\\s")){ System.out.print(token + "\t"); if (token.equals("*")) { System.out.print("Operate\t\t"); double secondOperand = stack.pop(); double firstOperand = stack.pop(); stack.push(firstOperand * secondOperand); } else if (token.equals("/")) { System.out.print("Operate\t\t"); double secondOperand = stack.pop(); double firstOperand = stack.pop(); stack.push(firstOperand / secondOperand); } else if (token.equals("-")) { System.out.print("Operate\t\t"); double secondOperand = stack.pop(); double firstOperand = stack.pop(); stack.push(firstOperand - secondOperand); } else if (token.equals("+")) { System.out.print("Operate\t\t"); double secondOperand = stack.pop(); double firstOperand = stack.pop(); stack.push(firstOperand + secondOperand); } else if (token.equals("^")) { System.out.print("Operate\t\t"); double secondOperand = stack.pop(); double firstOperand = stack.pop(); stack.push(Math.pow(firstOperand, secondOperand)); } else { System.out.print("Push\t\t"); try { stack.push(Double.parseDouble(token+"")); } catch (NumberFormatException e) { System.out.println("\nError: invalid token " + token); return; } } System.out.println(stack); } if (stack.size() > 1) { System.out.println("Error, too many operands: " + stack); return; } System.out.println("Final answer: " + stack.pop()); } }  
http://rosettacode.org/wiki/Palindrome_detection
Palindrome detection
A palindrome is a phrase which reads the same backward and forward. Task[edit] Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. For extra credit: Support Unicode characters. Write a second function (possibly as a wrapper to the first) which detects inexact palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used. Hints It might be useful for this task to know how to reverse a string. This task's entries might also form the subjects of the task Test a function. Related tasks Word plays Ordered words Palindrome detection Semordnilap Anagrams Anagrams/Deranged anagrams Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Arturo
Arturo
palindrome?: $[seq] -> seq = reverse seq   loop ["abba" "boom" "radar" "civic" "great"] 'wrd [ print [wrd ": palindrome?" palindrome? wrd] ]
http://rosettacode.org/wiki/Palindromic_gapful_numbers
Palindromic gapful numbers
Palindromic gapful numbers You are encouraged to solve this task according to the task description, using any language you may know. Numbers   (positive integers expressed in base ten)   that are (evenly) divisible by the number formed by the first and last digit are known as   gapful numbers. Evenly divisible   means divisible with   no   remainder. All   one─   and two─digit   numbers have this property and are trivially excluded.   Only numbers   ≥ 100   will be considered for this Rosetta Code task. Example 1037   is a   gapful   number because it is evenly divisible by the number   17   which is formed by the first and last decimal digits of   1037. A palindromic number is   (for this task, a positive integer expressed in base ten),   when the number is reversed,   is the same as the original number. Task   Show   (nine sets)   the first   20   palindromic gapful numbers that   end   with:   the digit   1   the digit   2   the digit   3   the digit   4   the digit   5   the digit   6   the digit   7   the digit   8   the digit   9   Show   (nine sets, like above)   of palindromic gapful numbers:   the last   15   palindromic gapful numbers   (out of      100)   the last   10   palindromic gapful numbers   (out of   1,000)       {optional} For other ways of expressing the (above) requirements, see the   discussion   page. Note All palindromic gapful numbers are divisible by eleven. Related tasks   palindrome detection.   gapful numbers. Also see   The OEIS entry:   A108343 gapful numbers.
#Perl
Perl
use strict; use warnings; use feature 'say';   use constant Inf => 1e10;   sub is_p_gapful { my($d,$n) = @_; return '' unless 0 == $n % 11; my @digits = split //, $n; $d eq $digits[0] and (0 == $n % ($digits[0].$digits[-1])) and $n eq join '', reverse @digits; }   for ([1, 20], [86, 15]) { my($offset, $count) = @$_; say "Palindromic gapful numbers starting at $offset:"; for my $d ('1'..'9') { my $n = 0; my $out = "$d: "; $out .= do { $n+1 < $count+$offset ? (is_p_gapful($d,$_) and ++$n and $n >= $offset and "$_ ") : last } for 100 .. Inf; say $out } say '' }
http://rosettacode.org/wiki/Parsing/Shunting-yard_algorithm
Parsing/Shunting-yard algorithm
Task Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output as each individual token is processed. Assume an input of a correct, space separated, string of tokens representing an infix expression Generate a space separated output string representing the RPN Test with the input string: 3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3 print and display the output here. Operator precedence is given in this table: operator precedence associativity operation ^ 4 right exponentiation * 3 left multiplication / 3 left division + 2 left addition - 2 left subtraction Extra credit Add extra text explaining the actions and an optional comment for the action on receipt of each token. Note The handling of functions and arguments is not required. See also Parsing/RPN calculator algorithm for a method of calculating a final value from this output RPN expression. Parsing/RPN to infix conversion.
#Python
Python
from collections import namedtuple from pprint import pprint as pp   OpInfo = namedtuple('OpInfo', 'prec assoc') L, R = 'Left Right'.split()   ops = { '^': OpInfo(prec=4, assoc=R), '*': OpInfo(prec=3, assoc=L), '/': OpInfo(prec=3, assoc=L), '+': OpInfo(prec=2, assoc=L), '-': OpInfo(prec=2, assoc=L), '(': OpInfo(prec=9, assoc=L), ')': OpInfo(prec=0, assoc=L), }   NUM, LPAREN, RPAREN = 'NUMBER ( )'.split()     def get_input(inp = None): 'Inputs an expression and returns list of (TOKENTYPE, tokenvalue)'   if inp is None: inp = input('expression: ') tokens = inp.strip().split() tokenvals = [] for token in tokens: if token in ops: tokenvals.append((token, ops[token])) #elif token in (LPAREN, RPAREN): # tokenvals.append((token, token)) else: tokenvals.append((NUM, token)) return tokenvals   def shunting(tokenvals): outq, stack = [], [] table = ['TOKEN,ACTION,RPN OUTPUT,OP STACK,NOTES'.split(',')] for token, val in tokenvals: note = action = '' if token is NUM: action = 'Add number to output' outq.append(val) table.append( (val, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) ) elif token in ops: t1, (p1, a1) = token, val v = t1 note = 'Pop ops from stack to output' while stack: t2, (p2, a2) = stack[-1] if (a1 == L and p1 <= p2) or (a1 == R and p1 < p2): if t1 != RPAREN: if t2 != LPAREN: stack.pop() action = '(Pop op)' outq.append(t2) else: break else: if t2 != LPAREN: stack.pop() action = '(Pop op)' outq.append(t2) else: stack.pop() action = '(Pop & discard "(")' table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) ) break table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) ) v = note = '' else: note = '' break note = '' note = '' if t1 != RPAREN: stack.append((token, val)) action = 'Push op token to stack' else: action = 'Discard ")"' table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) ) note = 'Drain stack to output' while stack: v = '' t2, (p2, a2) = stack[-1] action = '(Pop op)' stack.pop() outq.append(t2) table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) ) v = note = '' return table   if __name__ == '__main__': infix = '3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3' print( 'For infix expression: %r\n' % infix ) rp = shunting(get_input(infix)) maxcolwidths = [len(max(x, key=len)) for x in zip(*rp)] row = rp[0] print( ' '.join('{cell:^{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row))) for row in rp[1:]: print( ' '.join('{cell:<{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row)))   print('\n The final output RPN is: %r' % rp[-1][2])
http://rosettacode.org/wiki/Paraffins
Paraffins
This organic chemistry task is essentially to implement a tree enumeration algorithm. Task Enumerate, without repetitions and in order of increasing size, all possible paraffin molecules (also known as alkanes). Paraffins are built up using only carbon atoms, which has four bonds, and hydrogen, which has one bond.   All bonds for each atom must be used, so it is easiest to think of an alkane as linked carbon atoms forming the "backbone" structure, with adding hydrogen atoms linking the remaining unused bonds. In a paraffin, one is allowed neither double bonds (two bonds between the same pair of atoms), nor cycles of linked carbons.   So all paraffins with   n   carbon atoms share the empirical formula     CnH2n+2 But for all   n ≥ 4   there are several distinct molecules ("isomers") with the same formula but different structures. The number of isomers rises rather rapidly when   n   increases. In counting isomers it should be borne in mind that the four bond positions on a given carbon atom can be freely interchanged and bonds rotated (including 3-D "out of the paper" rotations when it's being observed on a flat diagram),   so rotations or re-orientations of parts of the molecule (without breaking bonds) do not give different isomers.   So what seem at first to be different molecules may in fact turn out to be different orientations of the same molecule. Example With   n = 3   there is only one way of linking the carbons despite the different orientations the molecule can be drawn;   and with   n = 4   there are two configurations:   a   straight   chain:     (CH3)(CH2)(CH2)(CH3)   a branched chain:       (CH3)(CH(CH3))(CH3) Due to bond rotations, it doesn't matter which direction the branch points in. The phenomenon of "stereo-isomerism" (a molecule being different from its mirror image due to the actual 3-D arrangement of bonds) is ignored for the purpose of this task. The input is the number   n   of carbon atoms of a molecule (for instance 17). The output is how many different different paraffins there are with   n   carbon atoms (for instance   24,894   if   n = 17). The sequence of those results is visible in the OEIS entry:     oeis:A00602 number of n-node unrooted quartic trees; number of n-carbon alkanes C(n)H(2n+2) ignoring stereoisomers. The sequence is (the index starts from zero, and represents the number of carbon atoms): 1, 1, 1, 1, 2, 3, 5, 9, 18, 35, 75, 159, 355, 802, 1858, 4347, 10359, 24894, 60523, 148284, 366319, 910726, 2278658, 5731580, 14490245, 36797588, 93839412, 240215803, 617105614, 1590507121, 4111846763, 10660307791, 27711253769, ... Extra credit Show the paraffins in some way. A flat 1D representation, with arrays or lists is enough, for instance: *Main> all_paraffins 1 [CCP H H H H] *Main> all_paraffins 2 [BCP (C H H H) (C H H H)] *Main> all_paraffins 3 [CCP H H (C H H H) (C H H H)] *Main> all_paraffins 4 [BCP (C H H (C H H H)) (C H H (C H H H)), CCP H (C H H H) (C H H H) (C H H H)] *Main> all_paraffins 5 [CCP H H (C H H (C H H H)) (C H H (C H H H)), CCP H (C H H H) (C H H H) (C H H (C H H H)), CCP (C H H H) (C H H H) (C H H H) (C H H H)] *Main> all_paraffins 6 [BCP (C H H (C H H (C H H H))) (C H H (C H H (C H H H))), BCP (C H H (C H H (C H H H))) (C H (C H H H) (C H H H)), BCP (C H (C H H H) (C H H H)) (C H (C H H H) (C H H H)), CCP H (C H H H) (C H H (C H H H)) (C H H (C H H H)), CCP (C H H H) (C H H H) (C H H H) (C H H (C H H H))] Showing a basic 2D ASCII-art representation of the paraffins is better; for instance (molecule names aren't necessary): methane ethane propane isobutane   H H H H H H H H H │ │ │ │ │ │ │ │ │ H ─ C ─ H H ─ C ─ C ─ H H ─ C ─ C ─ C ─ H H ─ C ─ C ─ C ─ H │ │ │ │ │ │ │ │ │ H H H H H H H │ H │ H ─ C ─ H │ H Links   A paper that explains the problem and its solution in a functional language: http://www.cs.wright.edu/~tkprasad/courses/cs776/paraffins-turner.pdf   A Haskell implementation: https://github.com/ghc/nofib/blob/master/imaginary/paraffins/Main.hs   A Scheme implementation: http://www.ccs.neu.edu/home/will/Twobit/src/paraffins.scm   A Fortress implementation:         (this site has been closed) http://java.net/projects/projectfortress/sources/sources/content/ProjectFortress/demos/turnersParaffins0.fss?rev=3005
#Scala
Scala
object Paraffins extends App { val (nMax, nBranches) = (250, 4) val rooted, unrooted = Array.tabulate(nMax + 1)(i => if (i < 2) BigInt(1) else BigInt(0)) val (unrooted, c) = (rooted.clone(), new Array[BigInt](nBranches))   for (n <- 1 to nMax) { def tree(br: Int, n: Int, l: Int, inSum: Int, cnt: BigInt): Unit = { var sum = inSum for (b <- br + 1 to nBranches) { sum += n if (sum > nMax || (l * 2 >= sum && b >= nBranches)) return   if (b == br + 1) c(br) = rooted(n) * cnt else { c(br) = c(br) * (rooted(n) + BigInt(b - br - 1)) c(br) = c(br) / BigInt(b - br) } if (l * 2 < sum) unrooted(sum) = unrooted(sum) + c(br) if (b < nBranches) rooted(sum) = rooted(sum) + c(br)   for (m <- n - 1 to 1 by -1) tree(b, m, l, sum, c(br)) } }   def bicenter(s: Int): Unit = if ((s & 1) == 0) { val halves = rooted(s / 2) unrooted(s) = unrooted(s) + ((halves + BigInt(1)) * halves >> 1) }   tree(0, n, n, 1, BigInt(1)) bicenter(n) println(f"$n%3d: ${unrooted(n)}%s") } }
http://rosettacode.org/wiki/Pangram_checker
Pangram checker
Pangram checker You are encouraged to solve this task according to the task description, using any language you may know. A pangram is a sentence that contains all the letters of the English alphabet at least once. For example:   The quick brown fox jumps over the lazy dog. Task Write a function or method to check a sentence to see if it is a   pangram   (or not)   and show its use. Related tasks   determine if a string has all the same characters   determine if a string has all unique characters
#Cowgol
Cowgol
include "cowgol.coh";   sub pangram(str: [uint8]): (r: uint8) is var letters: uint8[26]; MemZero(&letters[0], 26);   loop var chr := [str]; if chr == 0 then break; end if; str := @next str; chr := (chr | 32) - 'a'; if chr >= 26 then continue; end if; letters[chr] := letters[chr] | 1; end loop;   r := 1; chr := 0; while chr < 26 loop r := r & letters[chr]; if r == 0 then break; end if; chr := chr + 1; end loop; end sub;   var yesno: [uint8][] := {": no\n", ": yes\n"}; var test: [uint8][] := { "The quick brown fox jumps over the lazy dog.", "The five boxing wizards dump quickly." };   var i: @indexof test := 0; while i < @sizeof test loop print(test[i]); print(yesno[pangram(test[i])]); i := i + 1; end loop;
http://rosettacode.org/wiki/Pangram_checker
Pangram checker
Pangram checker You are encouraged to solve this task according to the task description, using any language you may know. A pangram is a sentence that contains all the letters of the English alphabet at least once. For example:   The quick brown fox jumps over the lazy dog. Task Write a function or method to check a sentence to see if it is a   pangram   (or not)   and show its use. Related tasks   determine if a string has all the same characters   determine if a string has all unique characters
#Crystal
Crystal
def pangram?(sentence) ('a'..'z').all? {|c| sentence.downcase.includes?(c) } end   p pangram?("not a pangram") p pangram?("The quick brown fox jumps over the lazy dog.")
http://rosettacode.org/wiki/Pascal_matrix_generation
Pascal matrix generation
A pascal matrix is a two-dimensional square matrix holding numbers from   Pascal's triangle,   also known as   binomial coefficients   and which can be shown as   nCr. Shown below are truncated   5-by-5   matrices   M[i, j]   for   i,j   in range   0..4. A Pascal upper-triangular matrix that is populated with   jCi: [[1, 1, 1, 1, 1], [0, 1, 2, 3, 4], [0, 0, 1, 3, 6], [0, 0, 0, 1, 4], [0, 0, 0, 0, 1]] A Pascal lower-triangular matrix that is populated with   iCj   (the transpose of the upper-triangular matrix): [[1, 0, 0, 0, 0], [1, 1, 0, 0, 0], [1, 2, 1, 0, 0], [1, 3, 3, 1, 0], [1, 4, 6, 4, 1]] A Pascal symmetric matrix that is populated with   i+jCi: [[1, 1, 1, 1, 1], [1, 2, 3, 4, 5], [1, 3, 6, 10, 15], [1, 4, 10, 20, 35], [1, 5, 15, 35, 70]] Task Write functions capable of generating each of the three forms of   n-by-n   matrices. Use those functions to display upper, lower, and symmetric Pascal   5-by-5   matrices on this page. The output should distinguish between different matrices and the rows of each matrix   (no showing a list of 25 numbers assuming the reader should split it into rows). Note The   Cholesky decomposition   of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size.
#Maple
Maple
  PascalUT := proc(n::integer) local M := Matrix(n,n): local i: local j: M[1,1..n] := 1: for j from 2 to n do for i from 2 to n do M[i,j] := M[i,j-1] + M[i-1,j-1]: end: end: return M: end proc:   PascalUT(5);   PascalLT := proc(n::integer) local M := Matrix(n,n): local i: local j: M[1..n,1] := 1: for i from 2 to n do for j from 2 to n do M[i,j] := M[i-1,j] + M[i-1,j-1]: end: end: return M: end proc:   PascalLT(5);   Pascal := proc(n::integer) local M := Matrix(n,n): local i: local j: M[1..n,1] := 1: M[1,2..n] := 1: for i from 2 to n do for j from 2 to n do M[i,j] := M[i,j-1] + M[i-1,j]: end: end: return M: end proc:   Pascal(5);    
http://rosettacode.org/wiki/Pascal%27s_triangle
Pascal's triangle
Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is either 1 or the sum of the two elements right above it. For example, the next row of the triangle would be:   1   (since the first element of each row doesn't have two elements above it)   4   (1 + 3)   6   (3 + 3)   4   (3 + 1)   1   (since the last element of each row doesn't have two elements above it) So the triangle now looks like this: 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 Each row   n   (starting with row   0   at the top) shows the coefficients of the binomial expansion of   (x + y)n. Task Write a function that prints out the first   n   rows of the triangle   (with   f(1)   yielding the row consisting of only the element 1). This can be done either by summing elements from the previous rows or using a binary coefficient or combination function. Behavior for   n ≤ 0   does not need to be uniform, but should be noted. See also Evaluate binomial coefficients
#Eiffel
Eiffel
  note description : "Prints pascal's triangle" output : "[ Per requirements of the RosettaCode example, execution will print the first n rows of pascal's triangle ]" date : "19 December 2013" authors : "Sandro Meier", "Roman Brunner" revision : "1.0" libraries : "Relies on HASH_TABLE from EIFFEL_BASE library" implementation : "[ Recursive implementation to calculate the n'th row. ]" warning : "[ Will not work for large n's (INTEGER_32) ]"   class APPLICATION   inherit ARGUMENTS   create make   feature {NONE} -- Initialization   make local n:INTEGER do create {HASH_TABLE[ARRAY[INTEGER],INTEGER]}pascal_lines.make (n) --create the hash_table object io.new_line n:=25 draw(n) end feature line(n:INTEGER):ARRAY[INTEGER] --Calculates the n'th line local upper_line:ARRAY[INTEGER] i:INTEGER do if n=1 then --trivial case first line create Result.make_filled (0, 1, n+2) Result.put (0, 1) Result.put (1, 2) Result.put (0, 3) elseif pascal_lines.has (n) then --checks if the result was already calculated Result := pascal_lines.at (n) else --calculates the n'th line recursively create Result.make_filled(0,1,n+2) --for caluclation purposes add a 0 at the beginning of each line Result.put (0, 1) upper_line:=line(n-1) from i:=1 until i>upper_line.count-1 loop Result.put(upper_line[i]+upper_line[i+1],i+1) i:=i+1 end Result.put (0, n+2) --for caluclation purposes add a 0 at the end of each line pascal_lines.put (Result, n) end end   draw(n:INTEGER) --draw n lines of pascal's triangle local space_string:STRING width, i:INTEGER   do space_string:=" " --question of design: add space_string at the beginning of each line width:=line(n).count space_string.multiply (width) from i:=1 until i>n loop space_string.remove_tail (1) io.put_string (space_string) across line(i) as c loop if c.item/=0 then io.put_string (c.item.out+" ") end end io.new_line i:=i+1 end end   feature --Access pascal_lines:HASH_TABLE[ARRAY[INTEGER],INTEGER] --Contains all already calculated lines end  
http://rosettacode.org/wiki/Parsing/RPN_to_infix_conversion
Parsing/RPN to infix conversion
Parsing/RPN to infix conversion You are encouraged to solve this task according to the task description, using any language you may know. Task Create a program that takes an RPN representation of an expression formatted as a space separated sequence of tokens and generates the equivalent expression in infix notation. Assume an input of a correct, space separated, string of tokens Generate a space separated output string representing the same expression in infix notation Show how the major datastructure of your algorithm changes with each new token parsed. Test with the following input RPN strings then print and display the output here. RPN input sample output 3 4 2 * 1 5 - 2 3 ^ ^ / + 3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3 1 2 + 3 4 + ^ 5 6 + ^ ( ( 1 + 2 ) ^ ( 3 + 4 ) ) ^ ( 5 + 6 ) Operator precedence and operator associativity is given in this table: operator precedence associativity operation ^ 4 right exponentiation * 3 left multiplication / 3 left division + 2 left addition - 2 left subtraction See also   Parsing/Shunting-yard algorithm   for a method of generating an RPN from an infix expression.   Parsing/RPN calculator algorithm   for a method of calculating a final value from this output RPN expression.   Postfix to infix   from the RubyQuiz site.
#Tcl
Tcl
package require Tcl 8.5   # Helpers proc precassoc op { dict get {^ {4 right} * {3 left} / {3 left} + {2 left} - {2 left}} $op } proc pop stk { upvar 1 $stk s set val [lindex $s end] set s [lreplace $s end end] return $val }   proc rpn2infix rpn { foreach token $rpn { switch $token { "^" - "/" - "*" - "+" - "-" { lassign [pop stack] bprec b lassign [pop stack] aprec a lassign [precassoc $token] p assoc if {$aprec < $p || ($aprec == $p && $assoc eq "right")} { set a "($a)" } if {$bprec < $p || ($bprec == $p && $assoc eq "left")} { set b "($b)" } lappend stack [list $p "$a $token $b"] } default { lappend stack [list 9 $token] } } puts "$token -> $stack" } return [lindex $stack end 1] }   puts [rpn2infix {3 4 2 * 1 5 - 2 3 ^ ^ / +}] puts [rpn2infix {1 2 + 3 4 + ^ 5 6 + ^}]
http://rosettacode.org/wiki/Partial_function_application
Partial function application
Partial function application   is the ability to take a function of many parameters and apply arguments to some of the parameters to create a new function that needs only the application of the remaining arguments to produce the equivalent of applying all arguments to the original function. E.g: Given values v1, v2 Given f(param1, param2) Then partial(f, param1=v1) returns f'(param2) And f(param1=v1, param2=v2) == f'(param2=v2) (for any value v2) Note that in the partial application of a parameter, (in the above case param1), other parameters are not explicitly mentioned. This is a recurring feature of partial function application. Task Create a function fs( f, s ) that takes a function, f( n ), of one value and a sequence of values s. Function fs should return an ordered sequence of the result of applying function f to every value of s in turn. Create function f1 that takes a value and returns it multiplied by 2. Create function f2 that takes a value and returns it squared. Partially apply f1 to fs to form function fsf1( s ) Partially apply f2 to fs to form function fsf2( s ) Test fsf1 and fsf2 by evaluating them with s being the sequence of integers from 0 to 3 inclusive and then the sequence of even integers from 2 to 8 inclusive. Notes In partially applying the functions f1 or f2 to fs, there should be no explicit mention of any other parameters to fs, although introspection of fs within the partial applicator to find its parameters is allowed. This task is more about how results are generated rather than just getting results.
#REXX
REXX
/*REXX program demonstrates a method of a partial function application. */ s=; do a=0 to 3 /*build 1st series of some low integers*/ s=strip(s a) /*append to the integer to the S list*/ end /*a*/   call fs 'f1',s; say 'for f1: series=' s", result=" result call fs 'f2',s; say 'for f2: series=' s", result=" result   s=; do b=2 to 8 by 2 /*build 2nd series, low even integers. */ s=strip(s b) /*append to the integer to the S list*/ end /*b*/   call fs 'f1',s; say 'for f1: series=' s", result=" result call fs 'f2',s; say 'for f2: series=' s", result=" result exit /*stick a fork in it, we're all done. */ /*────────────────────────────────────────────────────────────────────────────*/ f1: return arg(1)* 2 f2: return arg(1)**2 /*────────────────────────────────────────────────────────────────────────────*/ fs: procedure; arg f,s; $=; do j=1 for words(s); z=word(s,j) interpret '$=$' f"("z')' end /*j*/ return strip($)
http://rosettacode.org/wiki/Password_generator
Password generator
Create a password generation program which will generate passwords containing random ASCII characters from the following groups: lower-case letters: a ──► z upper-case letters: A ──► Z digits: 0 ──► 9 other printable characters:  !"#$%&'()*+,-./:;<=>?@[]^_{|}~ (the above character list excludes white-space, backslash and grave) The generated password(s) must include   at least one   (of each of the four groups): lower-case letter, upper-case letter, digit (numeral),   and one "other" character. The user must be able to specify the password length and the number of passwords to generate. The passwords should be displayed or written to a file, one per line. The randomness should be from a system source or library. The program should implement a help option or button which should describe the program and options when invoked. You may also allow the user to specify a seed value, and give the option of excluding visually similar characters. For example:           Il1     O0     5S     2Z           where the characters are:   capital eye, lowercase ell, the digit one   capital oh, the digit zero   the digit five, capital ess   the digit two, capital zee
#Ruby
Ruby
ARRS = [("a".."z").to_a, ("A".."Z").to_a, ("0".."9").to_a, %q(!"#$%&'()*+,-./:;<=>?@[]^_{|}~).chars] # " quote to reset clumsy code colorizer ALL = ARRS.flatten   def generate_pwd(size, num) raise ArgumentError, "Desired size too small" unless size >= ARRS.size num.times.map do arr = ARRS.map(&:sample) (size - ARRS.size).times{ arr << ALL.sample} arr.shuffle.join end end   puts generate_pwd(8,3)  
http://rosettacode.org/wiki/Parallel_brute_force
Parallel brute force
Task Find, through brute force, the five-letter passwords corresponding with the following SHA-256 hashes: 1. 1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad 2. 3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b 3. 74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f Your program should naively iterate through all possible passwords consisting only of five lower-case ASCII English letters. It should use concurrent or parallel processing, if your language supports that feature. You may calculate SHA-256 hashes by calling a library or through a custom implementation. Print each matching password, along with its SHA-256 hash. Related task: SHA-256
#Wren
Wren
import "/crypto" for Sha256   var hashes = [ "1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad", "3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b", "74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f" ]   var findHash = Fn.new { |i| var bytes = List.filled(5, 0) var r = 97..122 bytes[0] = i for (j in r) { bytes[1] = j for (k in r) { bytes[2] = k for (l in r) { bytes[3] = l for (m in r) { bytes[4] = m var d = Sha256.digest(bytes) for (hash in hashes) { if (hash == d) { var s = bytes.map { |b| String.fromByte(b) }.join() System.print("%(s) => %(d)") hashes.remove(hash) if (hashes.count == 0) return } } } } } } }   for (i in 0..25) { var fib = Fiber.new(findHash) fib.call(97+i) }
http://rosettacode.org/wiki/Parallel_calculations
Parallel calculations
Many programming languages allow you to specify computations to be run in parallel. While Concurrent computing is focused on concurrency, the purpose of this task is to distribute time-consuming calculations on as many CPUs as possible. Assume we have a collection of numbers, and want to find the one with the largest minimal prime factor (that is, the one that contains relatively large factors). To speed up the search, the factorization should be done in parallel using separate threads or processes, to take advantage of multi-core CPUs. Show how this can be formulated in your language. Parallelize the factorization of those numbers, then search the returned list of numbers and factors for the largest minimal factor, and return that number and its prime factors. For the prime number decomposition you may use the solution of the Prime decomposition task.
#Sidef
Sidef
var nums = [1275792312878611, 12345678915808973, 1578070919762253, 14700694496703910,];   var factors = nums.map {|n| prime_factors.ffork(n) }.map { .wait } say ((nums ~Z factors)->max_by {|m| m[1][0] })
http://rosettacode.org/wiki/Parallel_calculations
Parallel calculations
Many programming languages allow you to specify computations to be run in parallel. While Concurrent computing is focused on concurrency, the purpose of this task is to distribute time-consuming calculations on as many CPUs as possible. Assume we have a collection of numbers, and want to find the one with the largest minimal prime factor (that is, the one that contains relatively large factors). To speed up the search, the factorization should be done in parallel using separate threads or processes, to take advantage of multi-core CPUs. Show how this can be formulated in your language. Parallelize the factorization of those numbers, then search the returned list of numbers and factors for the largest minimal factor, and return that number and its prime factors. For the prime number decomposition you may use the solution of the Prime decomposition task.
#Standard_ML
Standard ML
  structure TTd = Thread.Thread ; structure TTm = Thread.Mutex  ;     val threadedBigPrime = fn input:IntInf.int list =>   let   (* --------------------- code from prime decomposition page ------------------- *) val factor = fn n :IntInf.int => let val unfactored = fn (u,_,_) => u; val factors = fn (_,f,_) => f; val try = fn (_,_,i) => i; fun getresult t = unfactored t::(factors t); fun until done change x = if done x then getresult x else until done change (change x); (* iteration *) fun lastprime t = unfactored t < (try t)*(try t) fun trymore t = if unfactored t mod (try t) = 0 then (unfactored t div (try t) , try t::(factors t) , try t) else (unfactored t, factors t , try t + 1) in until lastprime trymore (n,[],2) end; (* --------------------- end of code from prime decomposition page ------------ *)     val mx = TTm.mutex () ; val results : IntInf.int list list ref = ref [ ] ; val tasks  : IntInf.int list list ref = ref [ ] ;     val divideup = fn cores => fn inp : IntInf.int list => let val np = (List.length inp) div cores + (cores +1) div cores (* assume length > cores to reduce code *) val rec divd = fn ([], outp) => ([],outp ) | (inp,outp) => divd ( List.drop (inp,np) , (List.take (inp,np))::outp ) handle Subscript => ([],inp :: outp) in #2 ( divd (inp, [ ] )) end;     val doTask = fn () => let val mytask : IntInf.int list ref = ref []; val myres  : IntInf.int list list ref = ref []; in ( TTm.lock mx ; mytask := hd ( !tasks ) ; tasks:= tl (!tasks)  ; TTm.unlock mx ; myres  := List.map factor ( !mytask ) ; TTm.lock mx ; results :=  !myres @ ( !results )  ; TTm.unlock mx ; TTd.exit () ) end;     val cores = TTd.numProcessors (); val tmp = tasks := divideup cores input ; val processes = List.tabulate ( cores , fn i => TTd.fork (doTask , []) ) ; val maxim = ( while ( List.exists TTd.isActive processes ) do (Posix.Process.sleep (Time.fromReal 1.0 )); List.foldr IntInf.max 1 ( List.map (fn i => List.last i ) (!results) ) ) (* maximal lowest prime *)   in   List.filter (fn lst => List.last lst = maxim ) (!results)   end ;  
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm
Parsing/RPN calculator algorithm
Task Create a stack-based evaluator for an expression in   reverse Polish notation (RPN)   that also shows the changes in the stack as each individual token is processed as a table. Assume an input of a correct, space separated, string of tokens of an RPN expression Test with the RPN expression generated from the   Parsing/Shunting-yard algorithm   task:         3 4 2 * 1 5 - 2 3 ^ ^ / + Print or display the output here Notes   ^   means exponentiation in the expression above.   /   means division. See also   Parsing/Shunting-yard algorithm for a method of generating an RPN from an infix expression.   Several solutions to 24 game/Solve make use of RPN evaluators (although tracing how they work is not a part of that task).   Parsing/RPN to infix conversion.   Arithmetic evaluation.
#JavaScript
JavaScript
  const e = '3 4 2 * 1 5 - 2 3 ^ ^ / +'; const s = [], tokens = e.split(' '); for (const t of tokens) { const n = Number(t); if (!isNaN(n)) { s.push(n); } else { if (s.length < 2) { throw new Error(`${t}: ${s}: insufficient operands.`); } const o2 = s.pop(), o1 = s.pop(); switch (t) { case '+': s.push(o1 + o2); break; case '-': s.push(o1 - o2); break; case '*': s.push(o1 * o2); break; case '/': s.push(o1 / o2); break; case '^': s.push(Math.pow(o1, o2)); break; default: throw new Error(`Unrecognized operator: [${t}]`); } } console.log(`${t}: ${s}`); }   if (s.length > 1) { throw new Error(`${s}: insufficient operators.`); }  
http://rosettacode.org/wiki/Palindrome_detection
Palindrome detection
A palindrome is a phrase which reads the same backward and forward. Task[edit] Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. For extra credit: Support Unicode characters. Write a second function (possibly as a wrapper to the first) which detects inexact palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used. Hints It might be useful for this task to know how to reverse a string. This task's entries might also form the subjects of the task Test a function. Related tasks Word plays Ordered words Palindrome detection Semordnilap Anagrams Anagrams/Deranged anagrams Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#AutoHotkey
AutoHotkey
IsPalindrome(Str){ Loop, Parse, Str ReversedStr := A_LoopField . ReversedStr return, (ReversedStr == Str)?"Exact":(RegExReplace(ReversedStr,"\W")=RegExReplace(Str,"\W"))?"Inexact":"False" }
http://rosettacode.org/wiki/Palindromic_gapful_numbers
Palindromic gapful numbers
Palindromic gapful numbers You are encouraged to solve this task according to the task description, using any language you may know. Numbers   (positive integers expressed in base ten)   that are (evenly) divisible by the number formed by the first and last digit are known as   gapful numbers. Evenly divisible   means divisible with   no   remainder. All   one─   and two─digit   numbers have this property and are trivially excluded.   Only numbers   ≥ 100   will be considered for this Rosetta Code task. Example 1037   is a   gapful   number because it is evenly divisible by the number   17   which is formed by the first and last decimal digits of   1037. A palindromic number is   (for this task, a positive integer expressed in base ten),   when the number is reversed,   is the same as the original number. Task   Show   (nine sets)   the first   20   palindromic gapful numbers that   end   with:   the digit   1   the digit   2   the digit   3   the digit   4   the digit   5   the digit   6   the digit   7   the digit   8   the digit   9   Show   (nine sets, like above)   of palindromic gapful numbers:   the last   15   palindromic gapful numbers   (out of      100)   the last   10   palindromic gapful numbers   (out of   1,000)       {optional} For other ways of expressing the (above) requirements, see the   discussion   page. Note All palindromic gapful numbers are divisible by eleven. Related tasks   palindrome detection.   gapful numbers. Also see   The OEIS entry:   A108343 gapful numbers.
#Phix
Phix
with javascript_semantics function reverse_n(atom s) atom e = 0 while s>0 do e = e*10 + remainder(s,10) s = floor(s/10) end while return e end function constant mx = 1000, data = {{1, 20, "%7d "}, {86, 100, "%8d "}, {991, 1000, "%10d "}} include builtins\ordinal.e function digit(sequence results, integer d) integer count = 0, pow = 1, fl = d*11 for nd=3 to 15 do -- (number of digits, usually quits early) -- (obvs. 64-bit phix is fine with 19 digits, but 32-bit ain't) bool odd = (remainder(nd,2)==1) for s=d*pow to (d+1)*pow-1 do -- (eg 300 to 399) integer e = reverse_n(s) for m=0 to iff(odd?9:0) do -- (1 or 10 iterations) atom p = e + iff(odd ? s*pow*100+m*pow*10 : s*pow*10) if remainder(p,fl)==0 then -- gapful! count += 1 results[count][d] = p if count==mx then return results end if end if end for end for if odd then pow *= 10 end if end for if count<mx then ?9/0 end if -- oh dear... return results end function procedure main() sequence results = repeat(repeat({},9),mx) for d=1 to 9 do -- (the start/end digit) results = digit(results,d) end for for i=1 to length(data) do {integer s, integer e, string fmt} = data[i] printf(1,"%,d%s to %,d%s palindromic gapful numbers (> 100) ending with:\n", {s,ord(s),e,ord(e)}) for d=1 to 9 do printf(1,"%d: ",d) for j=s to e do printf(1,fmt,results[j][d]) end for printf(1,"\n") end for printf(1,"\n") end for end procedure main()
http://rosettacode.org/wiki/Parsing/Shunting-yard_algorithm
Parsing/Shunting-yard algorithm
Task Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output as each individual token is processed. Assume an input of a correct, space separated, string of tokens representing an infix expression Generate a space separated output string representing the RPN Test with the input string: 3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3 print and display the output here. Operator precedence is given in this table: operator precedence associativity operation ^ 4 right exponentiation * 3 left multiplication / 3 left division + 2 left addition - 2 left subtraction Extra credit Add extra text explaining the actions and an optional comment for the action on receipt of each token. Note The handling of functions and arguments is not required. See also Parsing/RPN calculator algorithm for a method of calculating a final value from this output RPN expression. Parsing/RPN to infix conversion.
#Racket
Racket
  #lang racket ;print column of width w (define (display-col w s) (let* ([n-spaces (- w (string-length s))] [spaces (make-string n-spaces #\space)]) (display (string-append s spaces)))) ;print columns given widths (idea borrowed from PicoLisp) (define (tab ws . ss) (for-each display-col ws ss) (newline))   (define input "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3")   (define (paren? s) (or (string=? s "(") (string=? s ")"))) (define-values (prec lasso? rasso? op?) (let ([table '(["^" 4 r] ["*" 3 l] ["/" 3 l] ["+" 2 l] ["-" 2 l])]) (define (asso x) (caddr (assoc x table))) (values (λ (x) (cadr (assoc x table))) (λ (x) (symbol=? (asso x) 'l)) (λ (x) (symbol=? (asso x) 'r)) (λ (x) (member x (map car table))))))   (define (shunt s) (define widths (list 8 (string-length input) (string-length input) 20)) (tab widths "TOKEN" "OUT" "STACK" "ACTION") (let shunt ([out '()] [ops '()] [in (string-split s)] [action ""]) (match in ['() (if (memf paren? ops) (error "unmatched parens") (reverse (append (reverse ops) out)))] [(cons x in) (tab widths x (string-join (reverse out) " ") (string-append* ops) action) (match x [(? string->number n) (shunt (cons n out) ops in (format "out ~a" n))] ["(" (shunt out (cons "(" ops) in "push (")] [")" (let-values ([(l r) (splitf-at ops (λ (y) (not (string=? y "("))))]) (match r ['() (error "unmatched parens")] [(cons _ r) (shunt (append (reverse l) out) r in "clear til )")]))] [else (let-values ([(l r) (splitf-at ops (λ (y) (and (op? y) ((if (lasso? x) <= <) (prec x) (prec y)))))]) (shunt (append (reverse l) out) (cons x r) in (format "out ~a, push ~a" l x)))])])))  
http://rosettacode.org/wiki/Paraffins
Paraffins
This organic chemistry task is essentially to implement a tree enumeration algorithm. Task Enumerate, without repetitions and in order of increasing size, all possible paraffin molecules (also known as alkanes). Paraffins are built up using only carbon atoms, which has four bonds, and hydrogen, which has one bond.   All bonds for each atom must be used, so it is easiest to think of an alkane as linked carbon atoms forming the "backbone" structure, with adding hydrogen atoms linking the remaining unused bonds. In a paraffin, one is allowed neither double bonds (two bonds between the same pair of atoms), nor cycles of linked carbons.   So all paraffins with   n   carbon atoms share the empirical formula     CnH2n+2 But for all   n ≥ 4   there are several distinct molecules ("isomers") with the same formula but different structures. The number of isomers rises rather rapidly when   n   increases. In counting isomers it should be borne in mind that the four bond positions on a given carbon atom can be freely interchanged and bonds rotated (including 3-D "out of the paper" rotations when it's being observed on a flat diagram),   so rotations or re-orientations of parts of the molecule (without breaking bonds) do not give different isomers.   So what seem at first to be different molecules may in fact turn out to be different orientations of the same molecule. Example With   n = 3   there is only one way of linking the carbons despite the different orientations the molecule can be drawn;   and with   n = 4   there are two configurations:   a   straight   chain:     (CH3)(CH2)(CH2)(CH3)   a branched chain:       (CH3)(CH(CH3))(CH3) Due to bond rotations, it doesn't matter which direction the branch points in. The phenomenon of "stereo-isomerism" (a molecule being different from its mirror image due to the actual 3-D arrangement of bonds) is ignored for the purpose of this task. The input is the number   n   of carbon atoms of a molecule (for instance 17). The output is how many different different paraffins there are with   n   carbon atoms (for instance   24,894   if   n = 17). The sequence of those results is visible in the OEIS entry:     oeis:A00602 number of n-node unrooted quartic trees; number of n-carbon alkanes C(n)H(2n+2) ignoring stereoisomers. The sequence is (the index starts from zero, and represents the number of carbon atoms): 1, 1, 1, 1, 2, 3, 5, 9, 18, 35, 75, 159, 355, 802, 1858, 4347, 10359, 24894, 60523, 148284, 366319, 910726, 2278658, 5731580, 14490245, 36797588, 93839412, 240215803, 617105614, 1590507121, 4111846763, 10660307791, 27711253769, ... Extra credit Show the paraffins in some way. A flat 1D representation, with arrays or lists is enough, for instance: *Main> all_paraffins 1 [CCP H H H H] *Main> all_paraffins 2 [BCP (C H H H) (C H H H)] *Main> all_paraffins 3 [CCP H H (C H H H) (C H H H)] *Main> all_paraffins 4 [BCP (C H H (C H H H)) (C H H (C H H H)), CCP H (C H H H) (C H H H) (C H H H)] *Main> all_paraffins 5 [CCP H H (C H H (C H H H)) (C H H (C H H H)), CCP H (C H H H) (C H H H) (C H H (C H H H)), CCP (C H H H) (C H H H) (C H H H) (C H H H)] *Main> all_paraffins 6 [BCP (C H H (C H H (C H H H))) (C H H (C H H (C H H H))), BCP (C H H (C H H (C H H H))) (C H (C H H H) (C H H H)), BCP (C H (C H H H) (C H H H)) (C H (C H H H) (C H H H)), CCP H (C H H H) (C H H (C H H H)) (C H H (C H H H)), CCP (C H H H) (C H H H) (C H H H) (C H H (C H H H))] Showing a basic 2D ASCII-art representation of the paraffins is better; for instance (molecule names aren't necessary): methane ethane propane isobutane   H H H H H H H H H │ │ │ │ │ │ │ │ │ H ─ C ─ H H ─ C ─ C ─ H H ─ C ─ C ─ C ─ H H ─ C ─ C ─ C ─ H │ │ │ │ │ │ │ │ │ H H H H H H H │ H │ H ─ C ─ H │ H Links   A paper that explains the problem and its solution in a functional language: http://www.cs.wright.edu/~tkprasad/courses/cs776/paraffins-turner.pdf   A Haskell implementation: https://github.com/ghc/nofib/blob/master/imaginary/paraffins/Main.hs   A Scheme implementation: http://www.ccs.neu.edu/home/will/Twobit/src/paraffins.scm   A Fortress implementation:         (this site has been closed) http://java.net/projects/projectfortress/sources/sources/content/ProjectFortress/demos/turnersParaffins0.fss?rev=3005
#Seed7
Seed7
$ include "seed7_05.s7i"; include "bigint.s7i";   const integer: max_n is 500; const integer: branch is 4;   var array bigInteger: rooted is max_n times 0_; var array bigInteger: unrooted is max_n times 0_;   const proc: tree (in integer: br, in integer: n, in integer: l, in var integer: sum, in bigInteger: cnt) is func local var integer: b is 0; var integer: m is 0; var bigInteger: c is 0_; var bigInteger: diff is 0_; begin for b range br + 1 to branch do sum +:= n; if sum > max_n or l * 2 >= sum and b >= branch then # Prevent unneeded long math. b := branch; else if b = (br + 1) then c := rooted[n] * cnt; else diff := bigInteger conv (b - br); c := c * (rooted[n] + pred(diff)) div diff; end if; if l * 2 < sum then unrooted[sum] +:= c; end if; if b < branch then rooted[sum] +:= c; for m range n-1 downto 1 do tree(b, m, l, sum, c); end for; end if; end if; end for; end func;   const proc: bicenter (in integer: s) is func begin if not odd(s) then unrooted[s] +:= (rooted[s div 2] * succ(rooted[s div 2])) >> 1; end if; end func;   const proc: main is func local var bigInteger: cnt is 1_; var integer: n is 0; var integer: sum is 1; begin rooted[1] := 1_; unrooted[1] := 1_; for n range 1 to max_n do tree(0, n, n, sum, cnt); bicenter(n); writeln(n <& ": " <& unrooted[n]); end for; end func;
http://rosettacode.org/wiki/Paraffins
Paraffins
This organic chemistry task is essentially to implement a tree enumeration algorithm. Task Enumerate, without repetitions and in order of increasing size, all possible paraffin molecules (also known as alkanes). Paraffins are built up using only carbon atoms, which has four bonds, and hydrogen, which has one bond.   All bonds for each atom must be used, so it is easiest to think of an alkane as linked carbon atoms forming the "backbone" structure, with adding hydrogen atoms linking the remaining unused bonds. In a paraffin, one is allowed neither double bonds (two bonds between the same pair of atoms), nor cycles of linked carbons.   So all paraffins with   n   carbon atoms share the empirical formula     CnH2n+2 But for all   n ≥ 4   there are several distinct molecules ("isomers") with the same formula but different structures. The number of isomers rises rather rapidly when   n   increases. In counting isomers it should be borne in mind that the four bond positions on a given carbon atom can be freely interchanged and bonds rotated (including 3-D "out of the paper" rotations when it's being observed on a flat diagram),   so rotations or re-orientations of parts of the molecule (without breaking bonds) do not give different isomers.   So what seem at first to be different molecules may in fact turn out to be different orientations of the same molecule. Example With   n = 3   there is only one way of linking the carbons despite the different orientations the molecule can be drawn;   and with   n = 4   there are two configurations:   a   straight   chain:     (CH3)(CH2)(CH2)(CH3)   a branched chain:       (CH3)(CH(CH3))(CH3) Due to bond rotations, it doesn't matter which direction the branch points in. The phenomenon of "stereo-isomerism" (a molecule being different from its mirror image due to the actual 3-D arrangement of bonds) is ignored for the purpose of this task. The input is the number   n   of carbon atoms of a molecule (for instance 17). The output is how many different different paraffins there are with   n   carbon atoms (for instance   24,894   if   n = 17). The sequence of those results is visible in the OEIS entry:     oeis:A00602 number of n-node unrooted quartic trees; number of n-carbon alkanes C(n)H(2n+2) ignoring stereoisomers. The sequence is (the index starts from zero, and represents the number of carbon atoms): 1, 1, 1, 1, 2, 3, 5, 9, 18, 35, 75, 159, 355, 802, 1858, 4347, 10359, 24894, 60523, 148284, 366319, 910726, 2278658, 5731580, 14490245, 36797588, 93839412, 240215803, 617105614, 1590507121, 4111846763, 10660307791, 27711253769, ... Extra credit Show the paraffins in some way. A flat 1D representation, with arrays or lists is enough, for instance: *Main> all_paraffins 1 [CCP H H H H] *Main> all_paraffins 2 [BCP (C H H H) (C H H H)] *Main> all_paraffins 3 [CCP H H (C H H H) (C H H H)] *Main> all_paraffins 4 [BCP (C H H (C H H H)) (C H H (C H H H)), CCP H (C H H H) (C H H H) (C H H H)] *Main> all_paraffins 5 [CCP H H (C H H (C H H H)) (C H H (C H H H)), CCP H (C H H H) (C H H H) (C H H (C H H H)), CCP (C H H H) (C H H H) (C H H H) (C H H H)] *Main> all_paraffins 6 [BCP (C H H (C H H (C H H H))) (C H H (C H H (C H H H))), BCP (C H H (C H H (C H H H))) (C H (C H H H) (C H H H)), BCP (C H (C H H H) (C H H H)) (C H (C H H H) (C H H H)), CCP H (C H H H) (C H H (C H H H)) (C H H (C H H H)), CCP (C H H H) (C H H H) (C H H H) (C H H (C H H H))] Showing a basic 2D ASCII-art representation of the paraffins is better; for instance (molecule names aren't necessary): methane ethane propane isobutane   H H H H H H H H H │ │ │ │ │ │ │ │ │ H ─ C ─ H H ─ C ─ C ─ H H ─ C ─ C ─ C ─ H H ─ C ─ C ─ C ─ H │ │ │ │ │ │ │ │ │ H H H H H H H │ H │ H ─ C ─ H │ H Links   A paper that explains the problem and its solution in a functional language: http://www.cs.wright.edu/~tkprasad/courses/cs776/paraffins-turner.pdf   A Haskell implementation: https://github.com/ghc/nofib/blob/master/imaginary/paraffins/Main.hs   A Scheme implementation: http://www.ccs.neu.edu/home/will/Twobit/src/paraffins.scm   A Fortress implementation:         (this site has been closed) http://java.net/projects/projectfortress/sources/sources/content/ProjectFortress/demos/turnersParaffins0.fss?rev=3005
#Tcl
Tcl
package require Tcl 8.5   set maxN 200 set rooted [lrepeat $maxN 0] lset rooted 0 1; lset rooted 1 1 set unrooted $rooted   proc choose {m k} { if {$k == 1} { return $m } for {set r $m; set i 1} {$i < $k} {incr i} { set r [expr {$r * ($m+$i) / ($i+1)}] } return $r }   proc tree {br n cnt sum l} { global maxN rooted unrooted for {set b [expr {$br+1}]} {$b <= 4} {incr b} { set s [expr {$sum + ($b-$br) * $n}] if {$s >= $maxN} return set c [expr {[choose [lindex $rooted $n] [expr {$b-$br}]] * $cnt}] if {$l*2 < $s} { lset unrooted $s [expr {[lindex $unrooted $s] + $c}] } if {$b == 4} return lset rooted $s [expr {[lindex $rooted $s] + $c}] for {set m $n} {[incr m -1]} {} { tree $b $m $c $s $l } } }   proc bicenter {s} { if {$s & 1} return global unrooted rooted set r [lindex $rooted [expr {$s/2}]] lset unrooted $s [expr {[lindex $unrooted $s] + $r*($r+1)/2}] }   for {set n 1} {$n < $maxN} {incr n} { tree 0 $n 1 1 $n bicenter $n puts "${n}: [lindex $unrooted $n]" }
http://rosettacode.org/wiki/Pangram_checker
Pangram checker
Pangram checker You are encouraged to solve this task according to the task description, using any language you may know. A pangram is a sentence that contains all the letters of the English alphabet at least once. For example:   The quick brown fox jumps over the lazy dog. Task Write a function or method to check a sentence to see if it is a   pangram   (or not)   and show its use. Related tasks   determine if a string has all the same characters   determine if a string has all unique characters
#D
D
bool isPangram(in string text) pure nothrow @safe @nogc { uint bitset;   foreach (immutable c; text) { if (c >= 'a' && c <= 'z') bitset |= (1u << (c - 'a')); else if (c >= 'A' && c <= 'Z') bitset |= (1u << (c - 'A')); }   return bitset == 0b11_11111111_11111111_11111111; }   void main() { assert("the quick brown fox jumps over the lazy dog".isPangram); assert(!"ABCDEFGHIJKLMNOPQSTUVWXYZ".isPangram); assert(!"ABCDEFGHIJKL.NOPQRSTUVWXYZ".isPangram); assert("ABC.D.E.FGHI*J/KL-M+NO*PQ R\nSTUVWXYZ".isPangram); }
http://rosettacode.org/wiki/Pascal_matrix_generation
Pascal matrix generation
A pascal matrix is a two-dimensional square matrix holding numbers from   Pascal's triangle,   also known as   binomial coefficients   and which can be shown as   nCr. Shown below are truncated   5-by-5   matrices   M[i, j]   for   i,j   in range   0..4. A Pascal upper-triangular matrix that is populated with   jCi: [[1, 1, 1, 1, 1], [0, 1, 2, 3, 4], [0, 0, 1, 3, 6], [0, 0, 0, 1, 4], [0, 0, 0, 0, 1]] A Pascal lower-triangular matrix that is populated with   iCj   (the transpose of the upper-triangular matrix): [[1, 0, 0, 0, 0], [1, 1, 0, 0, 0], [1, 2, 1, 0, 0], [1, 3, 3, 1, 0], [1, 4, 6, 4, 1]] A Pascal symmetric matrix that is populated with   i+jCi: [[1, 1, 1, 1, 1], [1, 2, 3, 4, 5], [1, 3, 6, 10, 15], [1, 4, 10, 20, 35], [1, 5, 15, 35, 70]] Task Write functions capable of generating each of the three forms of   n-by-n   matrices. Use those functions to display upper, lower, and symmetric Pascal   5-by-5   matrices on this page. The output should distinguish between different matrices and the rows of each matrix   (no showing a list of 25 numbers assuming the reader should split it into rows). Note The   Cholesky decomposition   of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
symPascal[size_] := NestList[Accumulate, Table[1, {k, size}], size - 1]   upperPascal[size_] := CholeskyDecomposition[symPascal@size]   lowerPascal[size_] := Transpose@CholeskyDecomposition[symPascal@size]   Column[MapThread[ Labeled[Grid[#1@5], #2, Top] &, {{upperPascal, lowerPascal, symPascal}, {"Upper", "Lower", "Symmetric"}}]]
http://rosettacode.org/wiki/Pascal_matrix_generation
Pascal matrix generation
A pascal matrix is a two-dimensional square matrix holding numbers from   Pascal's triangle,   also known as   binomial coefficients   and which can be shown as   nCr. Shown below are truncated   5-by-5   matrices   M[i, j]   for   i,j   in range   0..4. A Pascal upper-triangular matrix that is populated with   jCi: [[1, 1, 1, 1, 1], [0, 1, 2, 3, 4], [0, 0, 1, 3, 6], [0, 0, 0, 1, 4], [0, 0, 0, 0, 1]] A Pascal lower-triangular matrix that is populated with   iCj   (the transpose of the upper-triangular matrix): [[1, 0, 0, 0, 0], [1, 1, 0, 0, 0], [1, 2, 1, 0, 0], [1, 3, 3, 1, 0], [1, 4, 6, 4, 1]] A Pascal symmetric matrix that is populated with   i+jCi: [[1, 1, 1, 1, 1], [1, 2, 3, 4, 5], [1, 3, 6, 10, 15], [1, 4, 10, 20, 35], [1, 5, 15, 35, 70]] Task Write functions capable of generating each of the three forms of   n-by-n   matrices. Use those functions to display upper, lower, and symmetric Pascal   5-by-5   matrices on this page. The output should distinguish between different matrices and the rows of each matrix   (no showing a list of 25 numbers assuming the reader should split it into rows). Note The   Cholesky decomposition   of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size.
#Nim
Nim
import math, sequtils, strutils   type SquareMatrix = seq[seq[Natural]]   func newSquareMatrix(n: Positive): SquareMatrix = ## Create a square matrix. newSeqWith(n, newSeq[Natural](n))   func pascalUpperTriangular(n: Positive): SquareMatrix = ## Create an upper Pascal matrix. result = newSquareMatrix(n) for i in 0..<n: for j in i..<n: result[i][j] = binom(j, i)   func pascalLowerTriangular(n: Positive): SquareMatrix = ## Create a lower Pascal matrix. result = newSquareMatrix(n) for i in 0..<n: for j in i..<n: result[j][i] = binom(j, i)   func pascalSymmetric(n: Positive): SquareMatrix = ## Create a symmetric Pascal matrix. result = newSquareMatrix(n) for i in 0..<n: for j in 0..<n: result[i][j] = binom(i + j, i)   proc print(m: SquareMatrix) = ## Print a square matrix. let matMax = max(m.mapIt(max(it))) let length = ($matMax).len for i in 0..m.high: echo "| ", m[i].mapIt(($it).align(length)).join(" "), " |"   echo "Upper:" print pascalUpperTriangular(5) echo "\nLower:" print pascalLowerTriangular(5) echo "\nSymmetric:" print pascalSymmetric(5)
http://rosettacode.org/wiki/Pascal%27s_triangle
Pascal's triangle
Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is either 1 or the sum of the two elements right above it. For example, the next row of the triangle would be:   1   (since the first element of each row doesn't have two elements above it)   4   (1 + 3)   6   (3 + 3)   4   (3 + 1)   1   (since the last element of each row doesn't have two elements above it) So the triangle now looks like this: 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 Each row   n   (starting with row   0   at the top) shows the coefficients of the binomial expansion of   (x + y)n. Task Write a function that prints out the first   n   rows of the triangle   (with   f(1)   yielding the row consisting of only the element 1). This can be done either by summing elements from the previous rows or using a binary coefficient or combination function. Behavior for   n ≤ 0   does not need to be uniform, but should be noted. See also Evaluate binomial coefficients
#Elixir
Elixir
defmodule Pascal do def triangle(n), do: triangle(n,[1])   def triangle(0,list), do: list def triangle(n,list) do IO.inspect list new_list = Enum.zip([0]++list, list++[0]) |> Enum.map(fn {a,b} -> a+b end) triangle(n-1,new_list) end end   Pascal.triangle(8)
http://rosettacode.org/wiki/Parsing/RPN_to_infix_conversion
Parsing/RPN to infix conversion
Parsing/RPN to infix conversion You are encouraged to solve this task according to the task description, using any language you may know. Task Create a program that takes an RPN representation of an expression formatted as a space separated sequence of tokens and generates the equivalent expression in infix notation. Assume an input of a correct, space separated, string of tokens Generate a space separated output string representing the same expression in infix notation Show how the major datastructure of your algorithm changes with each new token parsed. Test with the following input RPN strings then print and display the output here. RPN input sample output 3 4 2 * 1 5 - 2 3 ^ ^ / + 3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3 1 2 + 3 4 + ^ 5 6 + ^ ( ( 1 + 2 ) ^ ( 3 + 4 ) ) ^ ( 5 + 6 ) Operator precedence and operator associativity is given in this table: operator precedence associativity operation ^ 4 right exponentiation * 3 left multiplication / 3 left division + 2 left addition - 2 left subtraction See also   Parsing/Shunting-yard algorithm   for a method of generating an RPN from an infix expression.   Parsing/RPN calculator algorithm   for a method of calculating a final value from this output RPN expression.   Postfix to infix   from the RubyQuiz site.
#TXR
TXR
;; alias for circumflex, which is reserved syntax (defvar exp (intern "^"))   (defvar *prec* ^((,exp . 4) (* . 3) (/ . 3) (+ . 2) (- . 2)))   (defvar *asso* ^((,exp . :right) (* . nil) (/ . :left) (+ . nil) (- . :left)))   (defun debug-print (label val) (format t "~a: ~a\n" label val) val)   (defun rpn-to-lisp (rpn) (let (stack) (each ((term rpn)) (if (symbolp (debug-print "rpn term" term)) (let ((right (pop stack)) (left (pop stack))) (push ^(,term ,left ,right) stack)) (push term stack)) (debug-print "stack" stack)) (if (rest stack) (return-from error "*excess stack elements*")) (debug-print "lisp" (pop stack))))   (defun prec (term) (or (cdr (assoc term *prec*)) 99))   (defun asso (term dfl) (or (cdr (assoc term *asso*)) dfl))   (defun inf-term (op term left-or-right) (if (atom term) `@term` (let ((pt (prec (car term))) (po (prec op)) (at (asso (car term) left-or-right)) (ao (asso op left-or-right))) (cond ((< pt po) `(@(lisp-to-infix term))`) ((> pt po) `@(lisp-to-infix term)`) ((and (eq at ao) (eq left-or-right ao)) `@(lisp-to-infix term)`) (t `(@(lisp-to-infix term))`)))))   (defun lisp-to-infix (lisp) (tree-case lisp ((op left right) (let ((left-inf (inf-term op left :left)) (right-inf (inf-term op right :right))) `@{left-inf} @op @{right-inf}`)) (() (return-from error "*stack underflow*")) (else `@lisp`)))   (defun string-to-rpn (str) (debug-print "rpn" (mapcar (do if (int-str @1) (int-str @1) (intern @1)) (tok-str str #/[^ \t]+/))))   (debug-print "infix" (block error (tree-case *args* ((a b . c) "*excess args*") ((a) (lisp-to-infix (rpn-to-lisp (string-to-rpn a)))) (else "*arg needed*"))))
http://rosettacode.org/wiki/Parsing/RPN_to_infix_conversion
Parsing/RPN to infix conversion
Parsing/RPN to infix conversion You are encouraged to solve this task according to the task description, using any language you may know. Task Create a program that takes an RPN representation of an expression formatted as a space separated sequence of tokens and generates the equivalent expression in infix notation. Assume an input of a correct, space separated, string of tokens Generate a space separated output string representing the same expression in infix notation Show how the major datastructure of your algorithm changes with each new token parsed. Test with the following input RPN strings then print and display the output here. RPN input sample output 3 4 2 * 1 5 - 2 3 ^ ^ / + 3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3 1 2 + 3 4 + ^ 5 6 + ^ ( ( 1 + 2 ) ^ ( 3 + 4 ) ) ^ ( 5 + 6 ) Operator precedence and operator associativity is given in this table: operator precedence associativity operation ^ 4 right exponentiation * 3 left multiplication / 3 left division + 2 left addition - 2 left subtraction See also   Parsing/Shunting-yard algorithm   for a method of generating an RPN from an infix expression.   Parsing/RPN calculator algorithm   for a method of calculating a final value from this output RPN expression.   Postfix to infix   from the RubyQuiz site.
#Visual_Basic_.NET
Visual Basic .NET
Option Strict On   Imports System.Text.RegularExpressions   Module Module1   Class Operator_ Sub New(t As Char, p As Integer, Optional i As Boolean = False) Token = t Precedence = p IsRightAssociative = i End Sub   Property Token As Char Get Return m_token End Get Private Set(value As Char) m_token = value End Set End Property   Property Precedence As Integer Get Return m_precedence End Get Private Set(value As Integer) m_precedence = value End Set End Property   Property IsRightAssociative As Boolean Get Return m_right End Get Private Set(value As Boolean) m_right = value End Set End Property   Private m_token As Char Private m_precedence As Integer Private m_right As Boolean End Class   ReadOnly operators As New Dictionary(Of Char, Operator_) From { {"+"c, New Operator_("+"c, 2)}, {"-"c, New Operator_("-"c, 2)}, {"/"c, New Operator_("/"c, 3)}, {"*"c, New Operator_("*"c, 3)}, {"^"c, New Operator_("^"c, 4, True)} }   Class Expression Public Sub New(e As String) Ex = e End Sub   Sub New(e1 As String, e2 As String, o As Operator_) Ex = String.Format("{0} {1} {2}", e1, o.Token, e2) Op = o End Sub   ReadOnly Property Ex As String ReadOnly Property Op As Operator_ End Class   Function PostfixToInfix(postfix As String) As String Dim stack As New Stack(Of Expression)   For Each token As String In Regex.Split(postfix, "\s+") Dim c = token(0) Dim op = operators.FirstOrDefault(Function(kv) kv.Key = c).Value If Not IsNothing(op) AndAlso token.Length = 1 Then Dim rhs = stack.Pop() Dim lhs = stack.Pop()   Dim opPrec = op.Precedence   Dim lhsPrec = If(IsNothing(lhs.Op), Integer.MaxValue, lhs.Op.Precedence) Dim rhsPrec = If(IsNothing(rhs.Op), Integer.MaxValue, rhs.Op.Precedence)   Dim newLhs As String If lhsPrec < opPrec OrElse (lhsPrec = opPrec AndAlso c = "^") Then 'lhs.Ex = "(" + lhs.Ex + ")" newLhs = "(" + lhs.Ex + ")" Else newLhs = lhs.Ex End If   Dim newRhs As String If rhsPrec < opPrec OrElse (rhsPrec = opPrec AndAlso c <> "^") Then 'rhs.Ex = "(" + rhs.Ex + ")" newRhs = "(" + rhs.Ex + ")" Else newRhs = rhs.Ex End If   stack.Push(New Expression(newLhs, newRhs, op)) Else stack.Push(New Expression(token)) End If   'Print intermediate result Console.WriteLine("{0} -> [{1}]", token, String.Join(", ", stack.Reverse().Select(Function(e) e.Ex))) Next   Return stack.Peek().Ex End Function   Sub Main() Dim inputs = {"3 4 2 * 1 5 - 2 3 ^ ^ / +", "1 2 + 3 4 + ^ 5 6 + ^"} For Each e In inputs Console.WriteLine("Postfix : {0}", e) Console.WriteLine("Infix : {0}", PostfixToInfix(e)) Console.WriteLine() Next Console.ReadLine() 'remove before submit End Sub   End Module
http://rosettacode.org/wiki/Partial_function_application
Partial function application
Partial function application   is the ability to take a function of many parameters and apply arguments to some of the parameters to create a new function that needs only the application of the remaining arguments to produce the equivalent of applying all arguments to the original function. E.g: Given values v1, v2 Given f(param1, param2) Then partial(f, param1=v1) returns f'(param2) And f(param1=v1, param2=v2) == f'(param2=v2) (for any value v2) Note that in the partial application of a parameter, (in the above case param1), other parameters are not explicitly mentioned. This is a recurring feature of partial function application. Task Create a function fs( f, s ) that takes a function, f( n ), of one value and a sequence of values s. Function fs should return an ordered sequence of the result of applying function f to every value of s in turn. Create function f1 that takes a value and returns it multiplied by 2. Create function f2 that takes a value and returns it squared. Partially apply f1 to fs to form function fsf1( s ) Partially apply f2 to fs to form function fsf2( s ) Test fsf1 and fsf2 by evaluating them with s being the sequence of integers from 0 to 3 inclusive and then the sequence of even integers from 2 to 8 inclusive. Notes In partially applying the functions f1 or f2 to fs, there should be no explicit mention of any other parameters to fs, although introspection of fs within the partial applicator to find its parameters is allowed. This task is more about how results are generated rather than just getting results.
#Ruby
Ruby
fs = proc { |f, s| s.map &f } f1 = proc { |n| n * 2 } f2 = proc { |n| n ** 2 } fsf1 = fs.curry[f1] fsf2 = fs.curry[f2]   [0..3, (2..8).step(2)].each do |e| p fsf1[e] p fsf2[e] end
http://rosettacode.org/wiki/Password_generator
Password generator
Create a password generation program which will generate passwords containing random ASCII characters from the following groups: lower-case letters: a ──► z upper-case letters: A ──► Z digits: 0 ──► 9 other printable characters:  !"#$%&'()*+,-./:;<=>?@[]^_{|}~ (the above character list excludes white-space, backslash and grave) The generated password(s) must include   at least one   (of each of the four groups): lower-case letter, upper-case letter, digit (numeral),   and one "other" character. The user must be able to specify the password length and the number of passwords to generate. The passwords should be displayed or written to a file, one per line. The randomness should be from a system source or library. The program should implement a help option or button which should describe the program and options when invoked. You may also allow the user to specify a seed value, and give the option of excluding visually similar characters. For example:           Il1     O0     5S     2Z           where the characters are:   capital eye, lowercase ell, the digit one   capital oh, the digit zero   the digit five, capital ess   the digit two, capital zee
#Run_BASIC
Run BASIC
a$(1) = "0123456789" a$(2) = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" a$(3) = "abcdefghijklmnopqrstuvwxyz" a$(4) = "!""#$%&'()*+,-./:;<=>?@[]^_{|}~" a$(0) = a$(1) + a$(2) + a$(3) + a$(4)   [main] print "----------- Password Generator -----------" input "Number of Characters:";howBig if howBig < 1 then goto [exit]   input "How many to generate:";howMany if howMany < 1 then goto [main]   ' ----------------------------- ' Generate Password ' ----------------------------- [gen] cls print "Generate ";howMany;" passwords with ";howBig;" characters" i = 0 while i < howMany pw$ = "" ok$ = "...." pw$ = "" for j = 1 to howBig w$ = mid$(a$(0),int(rnd(0) * len(a$(0))) + 1,1) for k = 1 to 4 if instr(a$(k),w$) then ok$ = left$(ok$,k-1) + "*" + mid$(ok$,k+1) next k pw$ = pw$ + w$ next j if ok$ = "****" then ' Do we pass with the requirements i = i + 1 print "#";i;" ";pw$ end if WEND goto [main] [exit] ' get outta here end
http://rosettacode.org/wiki/Parallel_brute_force
Parallel brute force
Task Find, through brute force, the five-letter passwords corresponding with the following SHA-256 hashes: 1. 1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad 2. 3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b 3. 74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f Your program should naively iterate through all possible passwords consisting only of five lower-case ASCII English letters. It should use concurrent or parallel processing, if your language supports that feature. You may calculate SHA-256 hashes by calling a library or through a custom implementation. Print each matching password, along with its SHA-256 hash. Related task: SHA-256
#zkl
zkl
var [const] MsgHash=Import.lib("zklMsgHash"); var [const] gotEm=Atomic.Int(); // global signal for all threads   const THREADS=9, // how we will split task, THREADS<=26 CHR_a="a".toAsc();   fcn crack(c,n,hashes){ // thread sha256:=MsgHash.SHA256; // the SHA-256 hash method, byte bucket bytes,hash := Data(),Data().howza(0); // byte buckets to reduce garbage production firstLtrs:=(c+CHR_a).walker(n); ltrs:=CHR_a.walker; // iterator starting at 97/"a" foreach a,b,c,d,e in (firstLtrs,ltrs(26),ltrs(26),ltrs(26),ltrs(26)){ if(not hashes2go) return(); // all cracked, stop, not really needed bytes.clear(a,b,c,d,e); // recycle Data, faster than creating Strings sha256(bytes,1,hash); // put hash in hash if(hashes.holds(hash)){ println(bytes.text," --> ",hash.pump(String,"%02x".fmt)); hashes2go.dec(); // I cracked one, let mom thread know } } }
http://rosettacode.org/wiki/Parallel_calculations
Parallel calculations
Many programming languages allow you to specify computations to be run in parallel. While Concurrent computing is focused on concurrency, the purpose of this task is to distribute time-consuming calculations on as many CPUs as possible. Assume we have a collection of numbers, and want to find the one with the largest minimal prime factor (that is, the one that contains relatively large factors). To speed up the search, the factorization should be done in parallel using separate threads or processes, to take advantage of multi-core CPUs. Show how this can be formulated in your language. Parallelize the factorization of those numbers, then search the returned list of numbers and factors for the largest minimal factor, and return that number and its prime factors. For the prime number decomposition you may use the solution of the Prime decomposition task.
#Swift
Swift
import BigInt import Foundation   extension BinaryInteger { @inlinable public func primeDecomposition() -> [Self] { guard self > 1 else { return [] }   func step(_ x: Self) -> Self { return 1 + (x << 2) - ((x >> 1) << 1) }   let maxQ = Self(Double(self).squareRoot()) var d: Self = 1 var q: Self = self & 1 == 0 ? 2 : 3   while q <= maxQ && self % q != 0 { q = step(d) d += 1 }   return q <= maxQ ? [q] + (self / q).primeDecomposition() : [self] } }   let numbers = [ 112272537195293, 112582718962171, 112272537095293, 115280098190773, 115797840077099, 1099726829285419, 1275792312878611, BigInt("64921987050997300559") ]   func findLargestMinFactor<T: BinaryInteger>(for nums: [T], then: @escaping ((n: T, factors: [T])) -> ()) { let waiter = DispatchSemaphore(value: 0) let lock = DispatchSemaphore(value: 1) var factors = [(n: T, factors: [T])]()   DispatchQueue.concurrentPerform(iterations: nums.count) {i in let n = nums[i]   print("Factoring \(n)")   let nFacs = n.primeDecomposition().sorted()   print("Factored \(n)")   lock.wait() factors.append((n, nFacs))   if factors.count == nums.count { waiter.signal() }   lock.signal() }   waiter.wait()   then(factors.sorted(by: { $0.factors.first! > $1.factors.first! }).first!) }   findLargestMinFactor(for: numbers) {res in let (n, factors) = res   print("Number with largest min prime factor: \(n); factors: \(factors)")   exit(0) }   dispatchMain()
http://rosettacode.org/wiki/Parallel_calculations
Parallel calculations
Many programming languages allow you to specify computations to be run in parallel. While Concurrent computing is focused on concurrency, the purpose of this task is to distribute time-consuming calculations on as many CPUs as possible. Assume we have a collection of numbers, and want to find the one with the largest minimal prime factor (that is, the one that contains relatively large factors). To speed up the search, the factorization should be done in parallel using separate threads or processes, to take advantage of multi-core CPUs. Show how this can be formulated in your language. Parallelize the factorization of those numbers, then search the returned list of numbers and factors for the largest minimal factor, and return that number and its prime factors. For the prime number decomposition you may use the solution of the Prime decomposition task.
#Tcl
Tcl
package require Tcl 8.6 package require Thread   # Pooled computation engine; runs event loop internally namespace eval pooled { variable poolSize 3; # Needs to be tuned to system size   proc computation {computationDefinition entryPoint values} { variable result variable poolSize # Add communication shim append computationDefinition [subst -nocommands { proc poolcompute {value target} { set outcome [$entryPoint \$value] set msg [list set ::pooled::result(\$value) \$outcome] thread::send -async \$target \$msg } }]   # Set up the pool set pool [tpool::create -initcmd $computationDefinition \ -maxworkers $poolSize]   # Prepare to receive results unset -nocomplain result array set result {}   # Dispatch the computations foreach value $values { tpool::post $pool [list poolcompute $value [thread::id]] }   # Wait for results while {[array size result] < [llength $values]} {vwait pooled::result}   # Dispose of the pool tpool::release $pool   # Return the results return [array get result] } }
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm
Parsing/RPN calculator algorithm
Task Create a stack-based evaluator for an expression in   reverse Polish notation (RPN)   that also shows the changes in the stack as each individual token is processed as a table. Assume an input of a correct, space separated, string of tokens of an RPN expression Test with the RPN expression generated from the   Parsing/Shunting-yard algorithm   task:         3 4 2 * 1 5 - 2 3 ^ ^ / + Print or display the output here Notes   ^   means exponentiation in the expression above.   /   means division. See also   Parsing/Shunting-yard algorithm for a method of generating an RPN from an infix expression.   Several solutions to 24 game/Solve make use of RPN evaluators (although tracing how they work is not a part of that task).   Parsing/RPN to infix conversion.   Arithmetic evaluation.
#Julia
Julia
function rpn(s) stack = Any[] for op in map(eval, map(parse, split(s))) if isa(op, Function) arg2 = pop!(stack) arg1 = pop!(stack) push!(stack, op(arg1, arg2)) else push!(stack, op) end println("$op: ", join(stack, ", ")) end length(stack) != 1 && error("invalid RPN expression $s") return stack[1] end rpn("3 4 2 * 1 5 - 2 3 ^ ^ / +")
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm
Parsing/RPN calculator algorithm
Task Create a stack-based evaluator for an expression in   reverse Polish notation (RPN)   that also shows the changes in the stack as each individual token is processed as a table. Assume an input of a correct, space separated, string of tokens of an RPN expression Test with the RPN expression generated from the   Parsing/Shunting-yard algorithm   task:         3 4 2 * 1 5 - 2 3 ^ ^ / + Print or display the output here Notes   ^   means exponentiation in the expression above.   /   means division. See also   Parsing/Shunting-yard algorithm for a method of generating an RPN from an infix expression.   Several solutions to 24 game/Solve make use of RPN evaluators (although tracing how they work is not a part of that task).   Parsing/RPN to infix conversion.   Arithmetic evaluation.
#Kotlin
Kotlin
// version 1.1.2   fun rpnCalculate(expr: String) { if (expr.isEmpty()) throw IllegalArgumentException("Expresssion cannot be empty") println("For expression = $expr\n") println("Token Action Stack") val tokens = expr.split(' ').filter { it != "" } val stack = mutableListOf<Double>() for (token in tokens) { val d = token.toDoubleOrNull() if (d != null) { stack.add(d) println(" $d Push num onto top of stack $stack") } else if ((token.length > 1) || (token !in "+-*/^")) { throw IllegalArgumentException("$token is not a valid token") } else if (stack.size < 2) { throw IllegalArgumentException("Stack contains too few operands") } else { val d1 = stack.removeAt(stack.lastIndex) val d2 = stack.removeAt(stack.lastIndex) stack.add(when (token) { "+" -> d2 + d1 "-" -> d2 - d1 "*" -> d2 * d1 "/" -> d2 / d1 else -> Math.pow(d2, d1) }) println(" $token Apply op to top of stack $stack") } } println("\nThe final value is ${stack[0]}") }   fun main(args: Array<String>) { val expr = "3 4 2 * 1 5 - 2 3 ^ ^ / +" rpnCalculate(expr) }
http://rosettacode.org/wiki/Palindrome_detection
Palindrome detection
A palindrome is a phrase which reads the same backward and forward. Task[edit] Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. For extra credit: Support Unicode characters. Write a second function (possibly as a wrapper to the first) which detects inexact palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used. Hints It might be useful for this task to know how to reverse a string. This task's entries might also form the subjects of the task Test a function. Related tasks Word plays Ordered words Palindrome detection Semordnilap Anagrams Anagrams/Deranged anagrams 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
#AutoIt
AutoIt
;== AutoIt Version: 3.3.8.1   Global $aString[7] = [ _ "In girum imus nocte, et consumimur igni", _ ; inexact palindrome "Madam, I'm Adam.", _ ; inexact palindrome "salàlas", _ ; exact palindrome "radar", _ ; exact palindrome "Lagerregal", _ ; exact palindrome "Ein Neger mit Gazelle zagt im Regen nie.", _ ; inexact palindrome "something wrong"] ; no palindrome Global $sSpace42 = " "   For $i = 0 To 6 If _IsPalindrome($aString[$i]) Then ConsoleWrite('"' & $aString[$i] & '"' & StringLeft($sSpace42, 42-StringLen($aString[$i])) & 'is an exact palindrome.' & @LF) Else If _IsPalindrome( StringRegExpReplace($aString[$i], '\W', '') ) Then ConsoleWrite('"' & $aString[$i] & '"' & StringLeft($sSpace42, 42-StringLen($aString[$i])) & 'is an inexact palindrome.' & @LF) Else ConsoleWrite('"' & $aString[$i] & '"' & StringLeft($sSpace42, 42-StringLen($aString[$i])) & 'is not a palindrome.' & @LF) EndIf EndIf Next   Func _IsPalindrome($_string) Local $iLen = StringLen($_string) For $i = 1 To Int($iLen/2) If StringMid($_string, $i, 1) <> StringMid($_string, $iLen-($i-1), 1) Then Return False Next Return True EndFunc  
http://rosettacode.org/wiki/Palindromic_gapful_numbers
Palindromic gapful numbers
Palindromic gapful numbers You are encouraged to solve this task according to the task description, using any language you may know. Numbers   (positive integers expressed in base ten)   that are (evenly) divisible by the number formed by the first and last digit are known as   gapful numbers. Evenly divisible   means divisible with   no   remainder. All   one─   and two─digit   numbers have this property and are trivially excluded.   Only numbers   ≥ 100   will be considered for this Rosetta Code task. Example 1037   is a   gapful   number because it is evenly divisible by the number   17   which is formed by the first and last decimal digits of   1037. A palindromic number is   (for this task, a positive integer expressed in base ten),   when the number is reversed,   is the same as the original number. Task   Show   (nine sets)   the first   20   palindromic gapful numbers that   end   with:   the digit   1   the digit   2   the digit   3   the digit   4   the digit   5   the digit   6   the digit   7   the digit   8   the digit   9   Show   (nine sets, like above)   of palindromic gapful numbers:   the last   15   palindromic gapful numbers   (out of      100)   the last   10   palindromic gapful numbers   (out of   1,000)       {optional} For other ways of expressing the (above) requirements, see the   discussion   page. Note All palindromic gapful numbers are divisible by eleven. Related tasks   palindrome detection.   gapful numbers. Also see   The OEIS entry:   A108343 gapful numbers.
#Prolog
Prolog
init_palindrome(Digit, p(10, Next, 0)):- Next is Digit * 10 - 1.   next_palindrome(Digit, p(Power, Next, Even), p(Power1, Next2, Even1), Palindrome):- Next1 is Next + 1, (Next1 is Power * (Digit + 1) -> (Even == 1 -> Power1 is Power * 10 ; Power1 = Power), Next2 is Digit * Power1, Even1 is 1 - Even ; Power1 = Power, Next2 = Next1, Even1 = Even ), (Even1 == 1 -> X is 10 * Power1, Y = Next2 ; X = Power1, Y is Next2 // 10 ), reverse_number(Y, Z), Palindrome is Next2 * X + Z.   reverse_number(N, R):- reverse_number(N, 0, R).   reverse_number(0, Result, Result):- !. reverse_number(N, R, Result):- R1 is R * 10 + N mod 10, N1 is N // 10, reverse_number(N1, R1, Result).   is_gapful(N):- is_gapful(N, N).   is_gapful(N, M):- M < 10, !, 0 is N mod (N mod 10 + 10 * (M mod 10)). is_gapful(N, M):- M1 is M // 10, is_gapful(N, M1).   find_palindromic_gapful_numbers(N, List):- find_palindromic_gapful_numbers(N, 1, List).   find_palindromic_gapful_numbers(_, 10, []):- !. find_palindromic_gapful_numbers(N, Digit, [Numbers|Rest]):- find_palindromic_gapful_numbers1(Digit, N, Numbers), Next_digit is Digit + 1, find_palindromic_gapful_numbers(N, Next_digit, Rest).   find_palindromic_gapful_numbers1(Digit, N, List):- init_palindrome(Digit, P), find_palindromic_gapful_numbers1(Digit, P, N, 0, List).   find_palindromic_gapful_numbers1(_, _, N, N, []):- !. find_palindromic_gapful_numbers1(Digit, P, N, Count, List):- next_palindrome(Digit, P, P_next, Palindrome), (is_gapful(Palindrome) -> Count1 is Count + 1, List = [Palindrome|Rest] ; Count1 = Count, List = Rest ), find_palindromic_gapful_numbers1(Digit, P_next, N, Count1, Rest).   print_numbers(First, Last, Numbers):- (First == 1 -> writef("First %w palindromic gapful numbers ending in:\n", [Last]) ; Count is Last - First + 1, writef("Last %w of first %w palindromic gapful numbers ending in:\n", [Count, Last]) ), print_numbers(First, Last, 1, Numbers), nl.   print_numbers(_, _, 10, _):- !. print_numbers(First, Last, Digit, [N|Numbers]):- writef("%w:", [Digit]), print_numbers1(First, Last, 1, N), Next_digit is Digit + 1, print_numbers(First, Last, Next_digit, Numbers).   print_numbers1(_, Last, I, _):- I > Last, nl, !. print_numbers1(First, Last, I, [_|Numbers]):- I < First, !, J is I + 1, print_numbers1(First, Last, J, Numbers). print_numbers1(First, Last, I, [N|Numbers]):- writef(" %w", [N]), J is I + 1, print_numbers1(First, Last, J, Numbers).   main:- find_palindromic_gapful_numbers(1000, Numbers), print_numbers(1, 20, Numbers), print_numbers(86, 100, Numbers), print_numbers(991, 1000, Numbers).
http://rosettacode.org/wiki/Parsing/Shunting-yard_algorithm
Parsing/Shunting-yard algorithm
Task Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output as each individual token is processed. Assume an input of a correct, space separated, string of tokens representing an infix expression Generate a space separated output string representing the RPN Test with the input string: 3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3 print and display the output here. Operator precedence is given in this table: operator precedence associativity operation ^ 4 right exponentiation * 3 left multiplication / 3 left division + 2 left addition - 2 left subtraction Extra credit Add extra text explaining the actions and an optional comment for the action on receipt of each token. Note The handling of functions and arguments is not required. See also Parsing/RPN calculator algorithm for a method of calculating a final value from this output RPN expression. Parsing/RPN to infix conversion.
#Raku
Raku
my %prec = '^' => 4, '*' => 3, '/' => 3, '+' => 2, '-' => 2, '(' => 1;   my %assoc = '^' => 'right', '*' => 'left', '/' => 'left', '+' => 'left', '-' => 'left';   sub shunting-yard ($prog) { my @inp = $prog.words; my @ops; my @res;   sub report($op) { printf "%25s  %-7s %10s %s\n", ~@res, ~@ops, $op, ~@inp } sub shift($t) { report( "shift $t"); @ops.push: $t } sub reduce($t) { report("reduce $t"); @res.push: $t }   while @inp { given @inp.shift { when /\d/ { reduce $_ }; when '(' { shift $_ } when ')' { while @ops and (my $x = @ops.pop and $x ne '(') { reduce $x } } default { my $newprec = %prec{$_}; while @ops { my $oldprec = %prec{@ops[*-1]}; last if $newprec > $oldprec; last if $newprec == $oldprec and %assoc{$_} eq 'right'; reduce @ops.pop; } shift $_; } } } reduce @ops.pop while @ops; @res; }   say shunting-yard '3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3';
http://rosettacode.org/wiki/Paraffins
Paraffins
This organic chemistry task is essentially to implement a tree enumeration algorithm. Task Enumerate, without repetitions and in order of increasing size, all possible paraffin molecules (also known as alkanes). Paraffins are built up using only carbon atoms, which has four bonds, and hydrogen, which has one bond.   All bonds for each atom must be used, so it is easiest to think of an alkane as linked carbon atoms forming the "backbone" structure, with adding hydrogen atoms linking the remaining unused bonds. In a paraffin, one is allowed neither double bonds (two bonds between the same pair of atoms), nor cycles of linked carbons.   So all paraffins with   n   carbon atoms share the empirical formula     CnH2n+2 But for all   n ≥ 4   there are several distinct molecules ("isomers") with the same formula but different structures. The number of isomers rises rather rapidly when   n   increases. In counting isomers it should be borne in mind that the four bond positions on a given carbon atom can be freely interchanged and bonds rotated (including 3-D "out of the paper" rotations when it's being observed on a flat diagram),   so rotations or re-orientations of parts of the molecule (without breaking bonds) do not give different isomers.   So what seem at first to be different molecules may in fact turn out to be different orientations of the same molecule. Example With   n = 3   there is only one way of linking the carbons despite the different orientations the molecule can be drawn;   and with   n = 4   there are two configurations:   a   straight   chain:     (CH3)(CH2)(CH2)(CH3)   a branched chain:       (CH3)(CH(CH3))(CH3) Due to bond rotations, it doesn't matter which direction the branch points in. The phenomenon of "stereo-isomerism" (a molecule being different from its mirror image due to the actual 3-D arrangement of bonds) is ignored for the purpose of this task. The input is the number   n   of carbon atoms of a molecule (for instance 17). The output is how many different different paraffins there are with   n   carbon atoms (for instance   24,894   if   n = 17). The sequence of those results is visible in the OEIS entry:     oeis:A00602 number of n-node unrooted quartic trees; number of n-carbon alkanes C(n)H(2n+2) ignoring stereoisomers. The sequence is (the index starts from zero, and represents the number of carbon atoms): 1, 1, 1, 1, 2, 3, 5, 9, 18, 35, 75, 159, 355, 802, 1858, 4347, 10359, 24894, 60523, 148284, 366319, 910726, 2278658, 5731580, 14490245, 36797588, 93839412, 240215803, 617105614, 1590507121, 4111846763, 10660307791, 27711253769, ... Extra credit Show the paraffins in some way. A flat 1D representation, with arrays or lists is enough, for instance: *Main> all_paraffins 1 [CCP H H H H] *Main> all_paraffins 2 [BCP (C H H H) (C H H H)] *Main> all_paraffins 3 [CCP H H (C H H H) (C H H H)] *Main> all_paraffins 4 [BCP (C H H (C H H H)) (C H H (C H H H)), CCP H (C H H H) (C H H H) (C H H H)] *Main> all_paraffins 5 [CCP H H (C H H (C H H H)) (C H H (C H H H)), CCP H (C H H H) (C H H H) (C H H (C H H H)), CCP (C H H H) (C H H H) (C H H H) (C H H H)] *Main> all_paraffins 6 [BCP (C H H (C H H (C H H H))) (C H H (C H H (C H H H))), BCP (C H H (C H H (C H H H))) (C H (C H H H) (C H H H)), BCP (C H (C H H H) (C H H H)) (C H (C H H H) (C H H H)), CCP H (C H H H) (C H H (C H H H)) (C H H (C H H H)), CCP (C H H H) (C H H H) (C H H H) (C H H (C H H H))] Showing a basic 2D ASCII-art representation of the paraffins is better; for instance (molecule names aren't necessary): methane ethane propane isobutane   H H H H H H H H H │ │ │ │ │ │ │ │ │ H ─ C ─ H H ─ C ─ C ─ H H ─ C ─ C ─ C ─ H H ─ C ─ C ─ C ─ H │ │ │ │ │ │ │ │ │ H H H H H H H │ H │ H ─ C ─ H │ H Links   A paper that explains the problem and its solution in a functional language: http://www.cs.wright.edu/~tkprasad/courses/cs776/paraffins-turner.pdf   A Haskell implementation: https://github.com/ghc/nofib/blob/master/imaginary/paraffins/Main.hs   A Scheme implementation: http://www.ccs.neu.edu/home/will/Twobit/src/paraffins.scm   A Fortress implementation:         (this site has been closed) http://java.net/projects/projectfortress/sources/sources/content/ProjectFortress/demos/turnersParaffins0.fss?rev=3005
#Wren
Wren
import "/big" for BigInt import "/fmt" for Fmt   var branches = 4 var nMax = 250 var rooted = List.filled(nMax + 1, BigInt.zero) var unrooted = List.filled(nMax + 1, BigInt.zero) var c = List.filled(branches, BigInt.zero)   var tree tree = Fn.new { |br, n, l, sum, cnt| var b = br + 1 while (b <= branches) { sum = sum + n if (sum > nMax) return if (l*2 >= sum && b >= branches) return if (b == br + 1) { c[br] = rooted[n] * cnt } else { var tmp = rooted[n] + BigInt.new(b - br - 1) c[br] = c[br] * tmp c[br] = c[br] / BigInt.new(b - br) } if (l*2 < sum) unrooted[sum] = unrooted[sum] + c[br] if (b < branches) rooted[sum] = rooted[sum] + c[br] var m = n - 1 while (m > 0) { tree.call(b, m, l, sum, c[br]) m = m - 1 } b = b + 1 } }   var bicenter = Fn.new { |s| if (s%2 == 0) { var tmp = (rooted[(s/2).floor] + BigInt.one) * rooted[(s/2).floor] tmp = tmp >> 1 unrooted[s] = unrooted[s] + tmp } }   rooted[0] = BigInt.one rooted[1] = BigInt.one unrooted[0] = BigInt.one unrooted[1] = BigInt.one for (n in 1..nMax) { tree.call(0, n, n, 1, BigInt.one) bicenter.call(n) Fmt.print("$3d: $i", n, unrooted[n]) }
http://rosettacode.org/wiki/Pangram_checker
Pangram checker
Pangram checker You are encouraged to solve this task according to the task description, using any language you may know. A pangram is a sentence that contains all the letters of the English alphabet at least once. For example:   The quick brown fox jumps over the lazy dog. Task Write a function or method to check a sentence to see if it is a   pangram   (or not)   and show its use. Related tasks   determine if a string has all the same characters   determine if a string has all unique characters
#Delphi
Delphi
program PangramChecker;   {$APPTYPE CONSOLE}   uses StrUtils;   function IsPangram(const aString: string): Boolean; var c: char; begin for c := 'a' to 'z' do if not ContainsText(aString, c) then Exit(False);   Result := True; end;   begin Writeln(IsPangram('The quick brown fox jumps over the lazy dog')); // true Writeln(IsPangram('Not a panagram')); // false end.
http://rosettacode.org/wiki/Pangram_checker
Pangram checker
Pangram checker You are encouraged to solve this task according to the task description, using any language you may know. A pangram is a sentence that contains all the letters of the English alphabet at least once. For example:   The quick brown fox jumps over the lazy dog. Task Write a function or method to check a sentence to see if it is a   pangram   (or not)   and show its use. Related tasks   determine if a string has all the same characters   determine if a string has all unique characters
#Draco
Draco
proc nonrec pangram(*char s) bool: ulong letters; char c; byte b; byte A = pretend('a', byte); byte Z = pretend('z', byte);   letters := 0L0; while c := s*; s := s + 1; c /= '\e' do b := pretend(c, byte) | 32; if b >= A and b <= Z then letters := letters | 0L1 << (b-A) fi od; letters = 0x3FFFFFF corp   proc nonrec test(*char s) void: writeln("\"", s, "\": ", if pangram(s) then "yes" else "no" fi) corp   proc nonrec main() void: test("The quick brown fox jumps over the lazy dog."); test("The five boxing wizards jump quickly."); test("Not a pangram") corp
http://rosettacode.org/wiki/Pascal_matrix_generation
Pascal matrix generation
A pascal matrix is a two-dimensional square matrix holding numbers from   Pascal's triangle,   also known as   binomial coefficients   and which can be shown as   nCr. Shown below are truncated   5-by-5   matrices   M[i, j]   for   i,j   in range   0..4. A Pascal upper-triangular matrix that is populated with   jCi: [[1, 1, 1, 1, 1], [0, 1, 2, 3, 4], [0, 0, 1, 3, 6], [0, 0, 0, 1, 4], [0, 0, 0, 0, 1]] A Pascal lower-triangular matrix that is populated with   iCj   (the transpose of the upper-triangular matrix): [[1, 0, 0, 0, 0], [1, 1, 0, 0, 0], [1, 2, 1, 0, 0], [1, 3, 3, 1, 0], [1, 4, 6, 4, 1]] A Pascal symmetric matrix that is populated with   i+jCi: [[1, 1, 1, 1, 1], [1, 2, 3, 4, 5], [1, 3, 6, 10, 15], [1, 4, 10, 20, 35], [1, 5, 15, 35, 70]] Task Write functions capable of generating each of the three forms of   n-by-n   matrices. Use those functions to display upper, lower, and symmetric Pascal   5-by-5   matrices on this page. The output should distinguish between different matrices and the rows of each matrix   (no showing a list of 25 numbers assuming the reader should split it into rows). Note The   Cholesky decomposition   of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size.
#PARI.2FGP
PARI/GP
  Pl(n)={matpascal(n-1)} printf("%d",Pl(5))  
http://rosettacode.org/wiki/Pascal%27s_triangle
Pascal's triangle
Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is either 1 or the sum of the two elements right above it. For example, the next row of the triangle would be:   1   (since the first element of each row doesn't have two elements above it)   4   (1 + 3)   6   (3 + 3)   4   (3 + 1)   1   (since the last element of each row doesn't have two elements above it) So the triangle now looks like this: 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 Each row   n   (starting with row   0   at the top) shows the coefficients of the binomial expansion of   (x + y)n. Task Write a function that prints out the first   n   rows of the triangle   (with   f(1)   yielding the row consisting of only the element 1). This can be done either by summing elements from the previous rows or using a binary coefficient or combination function. Behavior for   n ≤ 0   does not need to be uniform, but should be noted. See also Evaluate binomial coefficients
#Emacs_Lisp
Emacs Lisp
(require 'cl-lib)   (defun next-row (row) (cl-mapcar #'+ (cons 0 row) (append row '(0))))   (defun triangle (row rows) (if (= rows 0) '() (cons row (triangle (next-row row) (- rows 1)))))
http://rosettacode.org/wiki/Parsing/RPN_to_infix_conversion
Parsing/RPN to infix conversion
Parsing/RPN to infix conversion You are encouraged to solve this task according to the task description, using any language you may know. Task Create a program that takes an RPN representation of an expression formatted as a space separated sequence of tokens and generates the equivalent expression in infix notation. Assume an input of a correct, space separated, string of tokens Generate a space separated output string representing the same expression in infix notation Show how the major datastructure of your algorithm changes with each new token parsed. Test with the following input RPN strings then print and display the output here. RPN input sample output 3 4 2 * 1 5 - 2 3 ^ ^ / + 3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3 1 2 + 3 4 + ^ 5 6 + ^ ( ( 1 + 2 ) ^ ( 3 + 4 ) ) ^ ( 5 + 6 ) Operator precedence and operator associativity is given in this table: operator precedence associativity operation ^ 4 right exponentiation * 3 left multiplication / 3 left division + 2 left addition - 2 left subtraction See also   Parsing/Shunting-yard algorithm   for a method of generating an RPN from an infix expression.   Parsing/RPN calculator algorithm   for a method of calculating a final value from this output RPN expression.   Postfix to infix   from the RubyQuiz site.
#Wren
Wren
import "/seq" for Stack import "/pattern" for Pattern   class Expression { static ops { "-+/*^" }   construct new(ex, op, prec) { _ex = ex _op = op _prec = prec }   static build(e1, e2, o) { new("%(e1) %(o) %(e2)", o, (ops.indexOf(o)/2).floor) }   ex { _ex } ex=(other) { _ex = other } prec { _prec }   toString { _ex } }   var postfixToInfix = Fn.new { |postfix| var expr = Stack.new() var p = Pattern.new("+1/s") for (token in p.splitAll(postfix)) { var c = token[0] var idx = Expression.ops.indexOf(c) if (idx != -1 && token.count == 1) { var r = expr.pop() var l = expr.pop() var opPrec = (idx/2).floor if (l.prec < opPrec || (l.prec == opPrec && c == "^")) { l.ex = "(%(l.ex))" } if (r.prec < opPrec || (r.prec == opPrec && c != "^")) { r.ex = "(%(r.ex))" } expr.push(Expression.build(l.ex, r.ex, token)) } else { expr.push(Expression.new(token, "", 3)) } System.print("%(token) -> %(expr)") } return expr.peek().ex }   var es = [ "3 4 2 * 1 5 - 2 3 ^ ^ / +", "1 2 + 3 4 + ^ 5 6 + ^" ] for (e in es) { System.print("Postfix : %(e)") System.print("Infix : %(postfixToInfix.call(e))\n") }
http://rosettacode.org/wiki/Partial_function_application
Partial function application
Partial function application   is the ability to take a function of many parameters and apply arguments to some of the parameters to create a new function that needs only the application of the remaining arguments to produce the equivalent of applying all arguments to the original function. E.g: Given values v1, v2 Given f(param1, param2) Then partial(f, param1=v1) returns f'(param2) And f(param1=v1, param2=v2) == f'(param2=v2) (for any value v2) Note that in the partial application of a parameter, (in the above case param1), other parameters are not explicitly mentioned. This is a recurring feature of partial function application. Task Create a function fs( f, s ) that takes a function, f( n ), of one value and a sequence of values s. Function fs should return an ordered sequence of the result of applying function f to every value of s in turn. Create function f1 that takes a value and returns it multiplied by 2. Create function f2 that takes a value and returns it squared. Partially apply f1 to fs to form function fsf1( s ) Partially apply f2 to fs to form function fsf2( s ) Test fsf1 and fsf2 by evaluating them with s being the sequence of integers from 0 to 3 inclusive and then the sequence of even integers from 2 to 8 inclusive. Notes In partially applying the functions f1 or f2 to fs, there should be no explicit mention of any other parameters to fs, although introspection of fs within the partial applicator to find its parameters is allowed. This task is more about how results are generated rather than just getting results.
#Scala
Scala
def fs[X](f:X=>X)(s:Seq[X]) = s map f def f1(x:Int) = x * 2 def f2(x:Int) = x * x   def fsf[X](f:X=>X) = fs(f) _ val fsf1 = fsf(f1) // or without the fsf intermediary: val fsf1 = fs(f1) _ val fsf2 = fsf(f2) // or without the fsf intermediary: val fsf2 = fs(f2) _   assert(fsf1(List(0,1,2,3)) == List(0,2,4,6)) assert(fsf2(List(0,1,2,3)) == List(0,1,4,9))
http://rosettacode.org/wiki/Partial_function_application
Partial function application
Partial function application   is the ability to take a function of many parameters and apply arguments to some of the parameters to create a new function that needs only the application of the remaining arguments to produce the equivalent of applying all arguments to the original function. E.g: Given values v1, v2 Given f(param1, param2) Then partial(f, param1=v1) returns f'(param2) And f(param1=v1, param2=v2) == f'(param2=v2) (for any value v2) Note that in the partial application of a parameter, (in the above case param1), other parameters are not explicitly mentioned. This is a recurring feature of partial function application. Task Create a function fs( f, s ) that takes a function, f( n ), of one value and a sequence of values s. Function fs should return an ordered sequence of the result of applying function f to every value of s in turn. Create function f1 that takes a value and returns it multiplied by 2. Create function f2 that takes a value and returns it squared. Partially apply f1 to fs to form function fsf1( s ) Partially apply f2 to fs to form function fsf2( s ) Test fsf1 and fsf2 by evaluating them with s being the sequence of integers from 0 to 3 inclusive and then the sequence of even integers from 2 to 8 inclusive. Notes In partially applying the functions f1 or f2 to fs, there should be no explicit mention of any other parameters to fs, although introspection of fs within the partial applicator to find its parameters is allowed. This task is more about how results are generated rather than just getting results.
#Sidef
Sidef
func fs(f) { func(*args) { args.map {f(_)} } }   func double(n) { n * 2 }; func square(n) { n ** 2 };   var fs_double = fs(double); var fs_square = fs(square);   var s = (0 .. 3); say "fs_double(#{s}): #{fs_double(s...)}"; say "fs_square(#{s}): #{fs_square(s...)}";   s = [2, 4, 6, 8]; say "fs_double(#{s}): #{fs_double(s...)}"; say "fs_square(#{s}): #{fs_square(s...)}";
http://rosettacode.org/wiki/Password_generator
Password generator
Create a password generation program which will generate passwords containing random ASCII characters from the following groups: lower-case letters: a ──► z upper-case letters: A ──► Z digits: 0 ──► 9 other printable characters:  !"#$%&'()*+,-./:;<=>?@[]^_{|}~ (the above character list excludes white-space, backslash and grave) The generated password(s) must include   at least one   (of each of the four groups): lower-case letter, upper-case letter, digit (numeral),   and one "other" character. The user must be able to specify the password length and the number of passwords to generate. The passwords should be displayed or written to a file, one per line. The randomness should be from a system source or library. The program should implement a help option or button which should describe the program and options when invoked. You may also allow the user to specify a seed value, and give the option of excluding visually similar characters. For example:           Il1     O0     5S     2Z           where the characters are:   capital eye, lowercase ell, the digit one   capital oh, the digit zero   the digit five, capital ess   the digit two, capital zee
#Rust
Rust
  use rand::distributions::Alphanumeric; use rand::prelude::IteratorRandom; use rand::{thread_rng, Rng}; use std::iter; use std::process; use structopt::StructOpt; const OTHER_VALUES: &str = "!\"#$%&'()*+,-./:;<=>?@[]^_{|}~";   // the core logic that creates our password fn generate_password(length: u8) -> String { // cache thread_rng for better performance let mut rng = thread_rng(); // the Alphanumeric struct provides 3/4 // of the characters for passwords // so we can sample from it let mut base_password: Vec<char> = iter::repeat(()) .map(|()| rng.sample(Alphanumeric)) .take(length as usize) .collect(); let mut end_range = 10; // if the user supplies a password length less than 10 // we need to adjust the random sample range if length < end_range { end_range = length; } // create a random count of how many other characters to add let mut to_add = rng.gen_range(1, end_range as usize); loop { // create an iterator of required other characters let special = OTHER_VALUES.chars().choose(&mut rng).unwrap(); to_add -= 1; base_password[to_add] = special; if to_add == 0 { break; } } base_password.iter().collect() }   #[derive(StructOpt, Debug)] #[structopt(name = "password-generator", about = "A simple password generator.")] struct Opt { // make it SECURE by default // https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html /// The password length #[structopt(default_value = "160")] length: u8, /// How many passwords to generate #[structopt(default_value = "1")] count: u8, }   fn main() { // instantiate the options and use them as // arguments to our password generator let opt = Opt::from_args(); const MINIMUM_LENGTH: u8 = 30; if opt.length < MINIMUM_LENGTH { eprintln!( "Please provide a password length greater than or equal to {}", MINIMUM_LENGTH ); process::exit(1); } for index in 0..opt.count { let password = generate_password(opt.length); // do not print a newline after the last password match index + 1 == opt.count { true => print!("{}", password), _ => println!("{}", password), }; } }  
http://rosettacode.org/wiki/Parallel_calculations
Parallel calculations
Many programming languages allow you to specify computations to be run in parallel. While Concurrent computing is focused on concurrency, the purpose of this task is to distribute time-consuming calculations on as many CPUs as possible. Assume we have a collection of numbers, and want to find the one with the largest minimal prime factor (that is, the one that contains relatively large factors). To speed up the search, the factorization should be done in parallel using separate threads or processes, to take advantage of multi-core CPUs. Show how this can be formulated in your language. Parallelize the factorization of those numbers, then search the returned list of numbers and factors for the largest minimal factor, and return that number and its prime factors. For the prime number decomposition you may use the solution of the Prime decomposition task.
#Wren
Wren
/* parallel_calculations.wren */   import "./math" for Int   class C { static minPrimeFactor(n) { Int.primeFactors(n)[0] }   static allPrimeFactors(n) { Int.primeFactors(n) } }
http://rosettacode.org/wiki/Parallel_calculations
Parallel calculations
Many programming languages allow you to specify computations to be run in parallel. While Concurrent computing is focused on concurrency, the purpose of this task is to distribute time-consuming calculations on as many CPUs as possible. Assume we have a collection of numbers, and want to find the one with the largest minimal prime factor (that is, the one that contains relatively large factors). To speed up the search, the factorization should be done in parallel using separate threads or processes, to take advantage of multi-core CPUs. Show how this can be formulated in your language. Parallelize the factorization of those numbers, then search the returned list of numbers and factors for the largest minimal factor, and return that number and its prime factors. For the prime number decomposition you may use the solution of the Prime decomposition task.
#zkl
zkl
fcn factorize(x,y,z,etc){ xyzs:=vm.arglist; fs:=xyzs.apply(factors.strand) // queue up factorizing for x,y,... .apply("noop") // wait for all threads to finish factoring .apply(fcn{ (0).min(vm.arglist) }); // find minimum factor for x,y... [0..].zip(fs).filter(fcn([(n,x)],M){ x==M }.fp1((0).max(fs))) // find max of mins .apply('wrap([(n,_)]){ xyzs[n] }) // and pluck src from arglist }
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm
Parsing/RPN calculator algorithm
Task Create a stack-based evaluator for an expression in   reverse Polish notation (RPN)   that also shows the changes in the stack as each individual token is processed as a table. Assume an input of a correct, space separated, string of tokens of an RPN expression Test with the RPN expression generated from the   Parsing/Shunting-yard algorithm   task:         3 4 2 * 1 5 - 2 3 ^ ^ / + Print or display the output here Notes   ^   means exponentiation in the expression above.   /   means division. See also   Parsing/Shunting-yard algorithm for a method of generating an RPN from an infix expression.   Several solutions to 24 game/Solve make use of RPN evaluators (although tracing how they work is not a part of that task).   Parsing/RPN to infix conversion.   Arithmetic evaluation.
#Lambdatalk
Lambdatalk
  {calc 3 4 2 * 1 5 - 2 3 pow pow / +} -> 3: 4: 3 2: 4 3 *: 2 4 3 1: 8 3 5: 1 8 3 -: 5 1 8 3 2: -4 8 3 3: 2 -4 8 3 pow: 3 2 -4 8 3 pow: 8 -4 8 3 /: 65536 8 3 +: 0.0001220703125 3 -> 3.0001220703125   where   {def calc {def calc.r {lambda {:x :s} {if {empty? :x} then -> {car :s} else {car :x}: {disp :s}{br} {calc.r {cdr :x} {if {unop? {car :x}} then {cons {{car :x} {car :s}} {cdr :s}} else {if {binop? {car :x}} then {cons {{car :x} {car {cdr :s}} {car :s}} {cdr {cdr :s}}} else {cons {car :x} :s}} }}}}} {lambda {:s} {calc.r {list :s} nil}}}   using the unop? & binop? functions to test unary and binary operators   {def unop? {lambda {:op} {or {W.equal? :op sqrt} // n sqrt sqrt(n) {W.equal? :op exp} // n exp exp(n) {W.equal? :op log} // n log log(n) {W.equal? :op cos} // n cos cos(n) ... and so // ... }}}   {def binop? {lambda {:op} {or {W.equal? :op +} // m n + m+n {W.equal? :op -} // m n - m-n {W.equal? :op *} // m n * m*n {W.equal? :op /} // m n / m/n {W.equal? :op %} // m n % m%n {W.equal? :op pow} // m n pow m^n ... and so on // ... }}}   and the list, empty? and disp functions to create a list from a string, test its emptynes and display it.   {def list {lambda {:s} {if {W.empty? {S.rest :s}} then {cons {S.first :s} nil} else {cons {S.first :s} {list {S.rest :s}}}}}}   {def empty? {lambda {:x} {W.equal? :x nil}}}   {def disp {lambda {:l} {if {empty? :l} then else {car :l} {disp {cdr :l}}}}}   Note that everything is exclusively built on 5 lambdatalk primitives: - "cons, car, cdr", to create lists, - "W.equal?" which test the equality between two words, - and the "or" boolean function.  
http://rosettacode.org/wiki/Palindrome_detection
Palindrome detection
A palindrome is a phrase which reads the same backward and forward. Task[edit] Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. For extra credit: Support Unicode characters. Write a second function (possibly as a wrapper to the first) which detects inexact palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used. Hints It might be useful for this task to know how to reverse a string. This task's entries might also form the subjects of the task Test a function. Related tasks Word plays Ordered words Palindrome detection Semordnilap Anagrams Anagrams/Deranged anagrams Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#AWK
AWK
function is_palindro(s) { if ( s == reverse(s) ) return 1 return 0 }
http://rosettacode.org/wiki/Palindromic_gapful_numbers
Palindromic gapful numbers
Palindromic gapful numbers You are encouraged to solve this task according to the task description, using any language you may know. Numbers   (positive integers expressed in base ten)   that are (evenly) divisible by the number formed by the first and last digit are known as   gapful numbers. Evenly divisible   means divisible with   no   remainder. All   one─   and two─digit   numbers have this property and are trivially excluded.   Only numbers   ≥ 100   will be considered for this Rosetta Code task. Example 1037   is a   gapful   number because it is evenly divisible by the number   17   which is formed by the first and last decimal digits of   1037. A palindromic number is   (for this task, a positive integer expressed in base ten),   when the number is reversed,   is the same as the original number. Task   Show   (nine sets)   the first   20   palindromic gapful numbers that   end   with:   the digit   1   the digit   2   the digit   3   the digit   4   the digit   5   the digit   6   the digit   7   the digit   8   the digit   9   Show   (nine sets, like above)   of palindromic gapful numbers:   the last   15   palindromic gapful numbers   (out of      100)   the last   10   palindromic gapful numbers   (out of   1,000)       {optional} For other ways of expressing the (above) requirements, see the   discussion   page. Note All palindromic gapful numbers are divisible by eleven. Related tasks   palindrome detection.   gapful numbers. Also see   The OEIS entry:   A108343 gapful numbers.
#Python
Python
from itertools import count from pprint import pformat import re import heapq     def pal_part_gen(odd=True): for i in count(1): fwd = str(i) rev = fwd[::-1][1:] if odd else fwd[::-1] yield int(fwd + rev)   def pal_ordered_gen(): yield from heapq.merge(pal_part_gen(odd=True), pal_part_gen(odd=False))   def is_gapful(x): return (x % (int(str(x)[0]) * 10 + (x % 10)) == 0)   if __name__ == '__main__': start = 100 for mx, last in [(20, 20), (100, 15), (1_000, 10)]: print(f"\nLast {last} of the first {mx} binned-by-last digit " f"gapful numbers >= {start}") bin = {i: [] for i in range(1, 10)} gen = (i for i in pal_ordered_gen() if i >= start and is_gapful(i)) while any(len(val) < mx for val in bin.values()): g = next(gen) val = bin[g % 10] if len(val) < mx: val.append(g) b = {k:v[-last:] for k, v in bin.items()} txt = pformat(b, width=220) print('', re.sub(r"[{},\[\]]", '', txt))
http://rosettacode.org/wiki/Parsing/Shunting-yard_algorithm
Parsing/Shunting-yard algorithm
Task Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output as each individual token is processed. Assume an input of a correct, space separated, string of tokens representing an infix expression Generate a space separated output string representing the RPN Test with the input string: 3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3 print and display the output here. Operator precedence is given in this table: operator precedence associativity operation ^ 4 right exponentiation * 3 left multiplication / 3 left division + 2 left addition - 2 left subtraction Extra credit Add extra text explaining the actions and an optional comment for the action on receipt of each token. Note The handling of functions and arguments is not required. See also Parsing/RPN calculator algorithm for a method of calculating a final value from this output RPN expression. Parsing/RPN to infix conversion.
#REXX
REXX
/*REXX pgm converts infix arith. expressions to Reverse Polish notation (shunting─yard).*/ parse arg x /*obtain optional argument from the CL.*/ if x='' then x= '3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3' /*Not specified? Then use the default.*/ ox=x x='(' space(x) ") " /*force stacking for the expression. */ #=words(x) /*get number of tokens in expression. */ do i=1 for #; @.i=word(x, i) /*assign the input tokens to an array. */ end /*i*/ tell=1 /*set to 0 if working steps not wanted.*/ L=max( 20, length(x) ) /*use twenty for the minimum show width*/   say 'token' center("input" , L, '─') center("stack" , L%2, '─'), center("output", L, '─') center("action", L, '─') op= ")(-+/*^"; Rop=substr(op,3); p.=; n=length(op); RPN= /*some handy-dandy vars.*/ s.= do i=1 for n; _=substr(op,i,1); s._=(i+1)%2; p._=s._+(i==n); end /*i*/ $= /* [↑] assign the operator priorities.*/ do k=1 for #;  ?=@.k /*process each token from the @. list.*/ select /*@.k is: (, operator, ), operand*/ when ?=='(' then do; $="(" $; call show 'moving'  ? "──► stack"; end when isOp(?) then do;  !=word($, 1) /*get token from stack*/ do while ! \==')' & s.!>=p.? RPN=RPN ! /*add token to RPN.*/ $=subword($, 2) /*del token from stack*/ call show 'unstacking:'  !  !=word($, 1) /*get token from stack*/ end /*while*/ $=? $ /*add token to stack*/ call show 'moving'  ? "──► stack" end when ?==')' then do;  !=word($, 1) /*get token from stack*/ do while  !\=='('; RPN=RPN ! /*add token to RPN. */ $=subword($, 2) /*del token from stack*/  != word($, 1) /*get token from stack*/ call show 'moving stack' ! "──► RPN" end /*while*/ $=subword($, 2) /*del token from stack*/ call show 'deleting ( from the stack' end otherwise RPN=RPN ? /*add operand to RPN. */ call show 'moving'  ? "──► RPN" end /*select*/ end /*k*/ say RPN=space(RPN $) /*elide any superfluous blanks in RPN. */ say ' input:' ox; say " RPN──►" RPN /*display the input and the RPN. */ parse source upper . y . /*invoked via the C.L. or REXX pgm? */ if y=='COMMAND' then exit /*stick a fork in it, we're all done. */ else return RPN /*return RPN to invoker (the RESULT). */ /*──────────────────────────────────────────────────────────────────────────────────────────*/ isOp: return pos(arg(1),rOp) \== 0 /*is the first argument a "real" operator? */ show: if tell then say center(?,5) left(subword(x,k),L) left($,L%2) left(RPN,L) arg(1); return
http://rosettacode.org/wiki/Paraffins
Paraffins
This organic chemistry task is essentially to implement a tree enumeration algorithm. Task Enumerate, without repetitions and in order of increasing size, all possible paraffin molecules (also known as alkanes). Paraffins are built up using only carbon atoms, which has four bonds, and hydrogen, which has one bond.   All bonds for each atom must be used, so it is easiest to think of an alkane as linked carbon atoms forming the "backbone" structure, with adding hydrogen atoms linking the remaining unused bonds. In a paraffin, one is allowed neither double bonds (two bonds between the same pair of atoms), nor cycles of linked carbons.   So all paraffins with   n   carbon atoms share the empirical formula     CnH2n+2 But for all   n ≥ 4   there are several distinct molecules ("isomers") with the same formula but different structures. The number of isomers rises rather rapidly when   n   increases. In counting isomers it should be borne in mind that the four bond positions on a given carbon atom can be freely interchanged and bonds rotated (including 3-D "out of the paper" rotations when it's being observed on a flat diagram),   so rotations or re-orientations of parts of the molecule (without breaking bonds) do not give different isomers.   So what seem at first to be different molecules may in fact turn out to be different orientations of the same molecule. Example With   n = 3   there is only one way of linking the carbons despite the different orientations the molecule can be drawn;   and with   n = 4   there are two configurations:   a   straight   chain:     (CH3)(CH2)(CH2)(CH3)   a branched chain:       (CH3)(CH(CH3))(CH3) Due to bond rotations, it doesn't matter which direction the branch points in. The phenomenon of "stereo-isomerism" (a molecule being different from its mirror image due to the actual 3-D arrangement of bonds) is ignored for the purpose of this task. The input is the number   n   of carbon atoms of a molecule (for instance 17). The output is how many different different paraffins there are with   n   carbon atoms (for instance   24,894   if   n = 17). The sequence of those results is visible in the OEIS entry:     oeis:A00602 number of n-node unrooted quartic trees; number of n-carbon alkanes C(n)H(2n+2) ignoring stereoisomers. The sequence is (the index starts from zero, and represents the number of carbon atoms): 1, 1, 1, 1, 2, 3, 5, 9, 18, 35, 75, 159, 355, 802, 1858, 4347, 10359, 24894, 60523, 148284, 366319, 910726, 2278658, 5731580, 14490245, 36797588, 93839412, 240215803, 617105614, 1590507121, 4111846763, 10660307791, 27711253769, ... Extra credit Show the paraffins in some way. A flat 1D representation, with arrays or lists is enough, for instance: *Main> all_paraffins 1 [CCP H H H H] *Main> all_paraffins 2 [BCP (C H H H) (C H H H)] *Main> all_paraffins 3 [CCP H H (C H H H) (C H H H)] *Main> all_paraffins 4 [BCP (C H H (C H H H)) (C H H (C H H H)), CCP H (C H H H) (C H H H) (C H H H)] *Main> all_paraffins 5 [CCP H H (C H H (C H H H)) (C H H (C H H H)), CCP H (C H H H) (C H H H) (C H H (C H H H)), CCP (C H H H) (C H H H) (C H H H) (C H H H)] *Main> all_paraffins 6 [BCP (C H H (C H H (C H H H))) (C H H (C H H (C H H H))), BCP (C H H (C H H (C H H H))) (C H (C H H H) (C H H H)), BCP (C H (C H H H) (C H H H)) (C H (C H H H) (C H H H)), CCP H (C H H H) (C H H (C H H H)) (C H H (C H H H)), CCP (C H H H) (C H H H) (C H H H) (C H H (C H H H))] Showing a basic 2D ASCII-art representation of the paraffins is better; for instance (molecule names aren't necessary): methane ethane propane isobutane   H H H H H H H H H │ │ │ │ │ │ │ │ │ H ─ C ─ H H ─ C ─ C ─ H H ─ C ─ C ─ C ─ H H ─ C ─ C ─ C ─ H │ │ │ │ │ │ │ │ │ H H H H H H H │ H │ H ─ C ─ H │ H Links   A paper that explains the problem and its solution in a functional language: http://www.cs.wright.edu/~tkprasad/courses/cs776/paraffins-turner.pdf   A Haskell implementation: https://github.com/ghc/nofib/blob/master/imaginary/paraffins/Main.hs   A Scheme implementation: http://www.ccs.neu.edu/home/will/Twobit/src/paraffins.scm   A Fortress implementation:         (this site has been closed) http://java.net/projects/projectfortress/sources/sources/content/ProjectFortress/demos/turnersParaffins0.fss?rev=3005
#zkl
zkl
var BN=Import("zklBigNum");   const nMax=100, nBranches=4;   var rooted =(nMax+1).pump(List.createLong(nMax+1).write,BN.fp(0)), unrooted=(nMax+1).pump(List.createLong(nMax+1).write,BN.fp(0)); rooted[0]=BN(1); rooted[1]=BN(1); unrooted[0]=BN(1); unrooted[1]=BN(1);   fcn tree(br,n,l,inSum,cnt){ var c=(nBranches).pump(List().write,0); // happens only once   sum := inSum; foreach b in ([br + 1 .. nBranches]){ sum += n; if (sum > nMax or (l * 2 >= sum and b >= nBranches)) return(); if (b == br + 1) c[br] = rooted[n] * cnt; // -->BigInt else{ c[br].mul(rooted[n] + b - br - 1); c[br].div(b - br); } if (l * 2 < sum) unrooted[sum].add(c[br]); if (b < nBranches) rooted[sum].add(c[br]); foreach m in ([n-1 .. 1,-1]) { tree(b, m, l, sum, c[br]); } } }   fcn bicenter(s){ if (s.isEven) unrooted[s].add(rooted[s / 2] * (rooted[s / 2] + 1) / 2); }   foreach n in ([1 .. nMax]){ tree(0, n, n, 1, BN(1)); bicenter(n); println(n, ": ", unrooted[n]); }
http://rosettacode.org/wiki/Pangram_checker
Pangram checker
Pangram checker You are encouraged to solve this task according to the task description, using any language you may know. A pangram is a sentence that contains all the letters of the English alphabet at least once. For example:   The quick brown fox jumps over the lazy dog. Task Write a function or method to check a sentence to see if it is a   pangram   (or not)   and show its use. Related tasks   determine if a string has all the same characters   determine if a string has all unique characters
#E
E
def isPangram(sentence :String) { return ("abcdefghijklmnopqrstuvwxyz".asSet() &! sentence.toLowerCase().asSet()).size() == 0 }
http://rosettacode.org/wiki/Pangram_checker
Pangram checker
Pangram checker You are encouraged to solve this task according to the task description, using any language you may know. A pangram is a sentence that contains all the letters of the English alphabet at least once. For example:   The quick brown fox jumps over the lazy dog. Task Write a function or method to check a sentence to see if it is a   pangram   (or not)   and show its use. Related tasks   determine if a string has all the same characters   determine if a string has all unique characters
#EDSAC_order_code
EDSAC order code
  [Pangram checker for Rosetta Code. EDSAC program, Initial Orders 2.]   [Outline: Make a table, one entry per 5-bit character code. Initialize entry for each letter to 1. When a letter is read, convert its entry to 0.]   [Subroutine to read string from the input and store it with character codes in low 5 bits. String is terminated by blank row of tape, which is stored. Input: 0F holds address of string in address field (bits 1..11). 21 locations; workspace: 4F] T 56 K GKA3FT17@AFA18@T7@I4FA4FUFS19@G12@S20@G16@T4FA7@A2FE4@T4FEFUFP8FPD   [*************** Rosetta Code task *************** Subroutine to test whether string is a pangram. Input: 0F = address of string, characters in low 5 bits, terminated by blank row of tape. Output: 1F = (number of missing letters) - 1. 87 memory locations; workspace 4F.] T 88 K G K A 3 F [make and plant link for return] T 48 @ [Fill letter table with 1's. The code is a bit neater if we work backwards.] A 54 @ [index of last entry] [3] A 51 @ [make T order for table entry] T 6 @ [plant in code] A 53 @ [acc := 1] [6] T F [table entry := 1] A 6 @ [dec address in table] S 2 F S 51 @ [finished table?] E 3 @ [loop back if not] [Set non-letters to 0, except blank row := -1] T 4 F [clear acc] T 66 @ [figures shift] T 70 @ [letters shift] T 73 @ [carriage return] T 75 @ [space] T 79 @ [line feed] S 53 @ [acc := -1] T 71 @ [blank row of tape] [Loop to read characters from string. Terminated by blank row of tape. Assume acc = 0 here.] A F [load address of string] A 49 @ [make order to read first char] [21] T 22 @ [plant in code] [22] A F [char to acc] L D [shift to address field] A 50 @ [make A order for this char in table] U 28 @ [plant in code] A 52 @ [convert to T order] T 31 @ [plant in code] [28] A F [load table entry] G 35 @ [jump out if it's -1, i.e. blank row] T 4 F [clear acc] [31] T F [table entry := 0 to flag that letter is present] A 22 @ [inc address in input string] A 2 F G 21 @ [back to read next char] [Get total of table entries, again working backwards. The number of missing letters is (total + 1).] [35] T 4 F [clear acc] T 1 F [initialize total := 0] A 54 @ [index of last entry] [38] A 50 @ [make A order for table entry] T 41 @ [plant in code] A 1 F [load total so far] [41] A F [add table entry] T 1 F [update total] A 41 @ [load A order] S 2 F [dec address] S 50 @ [finished table?] E 38 @ [loop back if not] T 4 F [clear acc before exit] [48] E F [Constants] [49] A F [to make A order referring to input] [50] A 55 @ [to make A order referring to table] [51] T 55 @ [to make T order referring to table] [52] O F [add to A order to convert to T order] [53] P D [constant 1] [54] P 31 F [to change address by 31] [Table] [55] PFPFPFPFPFPFPFPFPFPFPF [66] PFPFPFPF [11 = figures shift] [70] PF [15 = letters shift] [71] PFPF [16 = blank row of tape] [73] PFPF [18 = carriage return] [75] PFPFPFPF [20 = space] [79] PFPFPFPFPFPFPFPF [24 = line feed]   [Main routine to demonstrate pangram-checking subroutine] T 200 K G K [Constants] [0] P 25 @ [address for input string] [1] N F [letter N] [2] Y F [letter Y] [3] K 2048 F [letter shift] [4] @ F [carriage return] [5] & F [line feed] [6] K 4096 F [null char] [Enter with acc = 0] [7] O 3 @ [set letters shift] [8] A @ [load address of input] T F [pass to input subroutine in 0F] [10] A 10 @ [call input subroutine, doesn't change 0F] G 56 F [12] A 12 @ [call pangram subroutine] G 88 F [We could print the number of missing letters, but we'll just print 'Y' or 'N'.] A 1 F [load (number missing) - 1] E 18 @ [jump if not pangram] O 2 @ [print 'Y'] G 19 @ [exit] [18] O 1 @ [print 'N'] [19] O 4 @ [print CR, LF] O 5 @ O 6 @ [print null to flush printer buffer] Z F [stop] T F [on Reset, clear acc] E 8 @ [and test another string] [25] [input string goes here] E 7 Z [define entry point] P F [acc = 0 on entry] THE!QUICK!BROWN!FOX!JUMPS!OVER!THE!LAZY!DOG.  
http://rosettacode.org/wiki/Pascal_matrix_generation
Pascal matrix generation
A pascal matrix is a two-dimensional square matrix holding numbers from   Pascal's triangle,   also known as   binomial coefficients   and which can be shown as   nCr. Shown below are truncated   5-by-5   matrices   M[i, j]   for   i,j   in range   0..4. A Pascal upper-triangular matrix that is populated with   jCi: [[1, 1, 1, 1, 1], [0, 1, 2, 3, 4], [0, 0, 1, 3, 6], [0, 0, 0, 1, 4], [0, 0, 0, 0, 1]] A Pascal lower-triangular matrix that is populated with   iCj   (the transpose of the upper-triangular matrix): [[1, 0, 0, 0, 0], [1, 1, 0, 0, 0], [1, 2, 1, 0, 0], [1, 3, 3, 1, 0], [1, 4, 6, 4, 1]] A Pascal symmetric matrix that is populated with   i+jCi: [[1, 1, 1, 1, 1], [1, 2, 3, 4, 5], [1, 3, 6, 10, 15], [1, 4, 10, 20, 35], [1, 5, 15, 35, 70]] Task Write functions capable of generating each of the three forms of   n-by-n   matrices. Use those functions to display upper, lower, and symmetric Pascal   5-by-5   matrices on this page. The output should distinguish between different matrices and the rows of each matrix   (no showing a list of 25 numbers assuming the reader should split it into rows). Note The   Cholesky decomposition   of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size.
#Pascal
Pascal
program Pascal_matrix(Output);   const N = 5;   type NxN_Matrix = array[0..N,0..N] of integer;   var PM,PX : NxN_Matrix;   function Pascal_sym(x : integer; p : NxN_Matrix) : NxN_Matrix; var I,J : integer; begin for I := 1 to x do begin for J := 1 to x do p[I,J] := p[I-1,J]+p[I,J-1] end; Pascal_sym := p; end;   function Pascal_upp(x : integer; p : NxN_Matrix) : NxN_Matrix; var I,J : integer; begin for I := 1 to x do begin for J := 1 to x do p[I,J] := p[I-1,J-1]+p[I,J-1] end; Pascal_upp := p end;   function Pascal_low(x : integer; p : NxN_Matrix) : NxN_Matrix; var p1,p2 : NxN_Matrix; I,J : integer; begin p1 := Pascal_upp(x,p); p2 := p1; for I := 1 to x do begin for J := 1 to x do p1[J,I] := p2[I,J] end; Pascal_low := p1 end;   procedure PrintMatrix(titel : ansistring; x : integer; p : NxN_Matrix); var I,J : integer; begin writeln(titel); for I := 1 to x do begin for J := 1 to x do write(p[I,J]:5); writeln(''); end; end;   begin PX[0,0] := 0; PM[0,0] := 1; PM := Pascal_upp(N, PM); PrintMatrix('Upper:', N, PM); writeln(''); PM := PX; PM[0,0] := 1; PM := Pascal_low(N, PM); PrintMatrix('Lower:', N, PM); writeln(''); PM := PX; PM[1,0] := 1; PM := Pascal_sym(N, PM); PrintMatrix('Symmetric', N, PM); writeln(''); readln; end.
http://rosettacode.org/wiki/Pascal%27s_triangle
Pascal's triangle
Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is either 1 or the sum of the two elements right above it. For example, the next row of the triangle would be:   1   (since the first element of each row doesn't have two elements above it)   4   (1 + 3)   6   (3 + 3)   4   (3 + 1)   1   (since the last element of each row doesn't have two elements above it) So the triangle now looks like this: 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 Each row   n   (starting with row   0   at the top) shows the coefficients of the binomial expansion of   (x + y)n. Task Write a function that prints out the first   n   rows of the triangle   (with   f(1)   yielding the row consisting of only the element 1). This can be done either by summing elements from the previous rows or using a binary coefficient or combination function. Behavior for   n ≤ 0   does not need to be uniform, but should be noted. See also Evaluate binomial coefficients
#Erlang
Erlang
  -import(lists). -export([pascal/1]).   pascal(1)-> [[1]]; pascal(N) -> L = pascal(N-1), [H|_] = L, [lists:zipwith(fun(X,Y)->X+Y end,[0]++H,H++[0])|L].  
http://rosettacode.org/wiki/Parsing/RPN_to_infix_conversion
Parsing/RPN to infix conversion
Parsing/RPN to infix conversion You are encouraged to solve this task according to the task description, using any language you may know. Task Create a program that takes an RPN representation of an expression formatted as a space separated sequence of tokens and generates the equivalent expression in infix notation. Assume an input of a correct, space separated, string of tokens Generate a space separated output string representing the same expression in infix notation Show how the major datastructure of your algorithm changes with each new token parsed. Test with the following input RPN strings then print and display the output here. RPN input sample output 3 4 2 * 1 5 - 2 3 ^ ^ / + 3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3 1 2 + 3 4 + ^ 5 6 + ^ ( ( 1 + 2 ) ^ ( 3 + 4 ) ) ^ ( 5 + 6 ) Operator precedence and operator associativity is given in this table: operator precedence associativity operation ^ 4 right exponentiation * 3 left multiplication / 3 left division + 2 left addition - 2 left subtraction See also   Parsing/Shunting-yard algorithm   for a method of generating an RPN from an infix expression.   Parsing/RPN calculator algorithm   for a method of calculating a final value from this output RPN expression.   Postfix to infix   from the RubyQuiz site.
#zkl
zkl
tests:=T("3 4 2 * 1 5 - 2 3 ^ ^ / +","1 2 + 3 4 + ^ 5 6 + ^");   var opa=D( "^",T(4, True), "*",T(3, False), "/",T(3, False), "+",T(2, False), "-",T(2, False) );   const nPrec = 9;   foreach t in (tests) { parseRPN(t) }   fcn parseRPN(e){ println("\npostfix:", e); stack:=L(); foreach tok in (e.split()){ println("token: ", tok); opPrec,rAssoc:=opa.find(tok,T(Void,Void)); if(opPrec){ rhsPrec,rhsExpr := stack.pop(); lhsPrec,lhsExpr := stack.pop(); if(lhsPrec < opPrec or (lhsPrec == opPrec and rAssoc)) lhsExpr = "(" + lhsExpr + ")"; lhsExpr += " " + tok + " "; if(rhsPrec < opPrec or (rhsPrec == opPrec and not rAssoc)){ lhsExpr += "(" + rhsExpr + ")" } else lhsExpr += rhsExpr; lhsPrec = opPrec; stack.append(T(lhsPrec,lhsExpr)); } else stack.append(T(nPrec, tok)); foreach f in (stack){ println(0'|  %d "%s"|.fmt(f.xplode())) } } println("infix:", stack[0][1]) }
http://rosettacode.org/wiki/Partial_function_application
Partial function application
Partial function application   is the ability to take a function of many parameters and apply arguments to some of the parameters to create a new function that needs only the application of the remaining arguments to produce the equivalent of applying all arguments to the original function. E.g: Given values v1, v2 Given f(param1, param2) Then partial(f, param1=v1) returns f'(param2) And f(param1=v1, param2=v2) == f'(param2=v2) (for any value v2) Note that in the partial application of a parameter, (in the above case param1), other parameters are not explicitly mentioned. This is a recurring feature of partial function application. Task Create a function fs( f, s ) that takes a function, f( n ), of one value and a sequence of values s. Function fs should return an ordered sequence of the result of applying function f to every value of s in turn. Create function f1 that takes a value and returns it multiplied by 2. Create function f2 that takes a value and returns it squared. Partially apply f1 to fs to form function fsf1( s ) Partially apply f2 to fs to form function fsf2( s ) Test fsf1 and fsf2 by evaluating them with s being the sequence of integers from 0 to 3 inclusive and then the sequence of even integers from 2 to 8 inclusive. Notes In partially applying the functions f1 or f2 to fs, there should be no explicit mention of any other parameters to fs, although introspection of fs within the partial applicator to find its parameters is allowed. This task is more about how results are generated rather than just getting results.
#Smalltalk
Smalltalk
  | f1 f2 fs fsf1 fsf2 partial |   partial := [ :afs :af | [ :s | afs value: af value: s ] ].   fs := [ :f :s | s collect: [ :x | f value: x ]]. f1 := [ :x | x * 2 ]. f2:= [ :x | x * x ]. fsf1 := partial value: fs value: f1. fsf2 := partial value: fs value: f2.   fsf1 value: (0 to: 3). " #(0 2 4 6)" fsf2 value: (0 to: 3). " #(0 1 4 9)"   fsf1 value: #(2 4 6 8). " #(4 8 12 16)" fsf2 value: #(2 4 6 8). " #(4 16 36 64)"  
http://rosettacode.org/wiki/Partial_function_application
Partial function application
Partial function application   is the ability to take a function of many parameters and apply arguments to some of the parameters to create a new function that needs only the application of the remaining arguments to produce the equivalent of applying all arguments to the original function. E.g: Given values v1, v2 Given f(param1, param2) Then partial(f, param1=v1) returns f'(param2) And f(param1=v1, param2=v2) == f'(param2=v2) (for any value v2) Note that in the partial application of a parameter, (in the above case param1), other parameters are not explicitly mentioned. This is a recurring feature of partial function application. Task Create a function fs( f, s ) that takes a function, f( n ), of one value and a sequence of values s. Function fs should return an ordered sequence of the result of applying function f to every value of s in turn. Create function f1 that takes a value and returns it multiplied by 2. Create function f2 that takes a value and returns it squared. Partially apply f1 to fs to form function fsf1( s ) Partially apply f2 to fs to form function fsf2( s ) Test fsf1 and fsf2 by evaluating them with s being the sequence of integers from 0 to 3 inclusive and then the sequence of even integers from 2 to 8 inclusive. Notes In partially applying the functions f1 or f2 to fs, there should be no explicit mention of any other parameters to fs, although introspection of fs within the partial applicator to find its parameters is allowed. This task is more about how results are generated rather than just getting results.
#Tcl
Tcl
package require Tcl 8.6 proc partial {f1 f2} { variable ctr coroutine __curry[incr ctr] apply {{f1 f2} { for {set x [info coroutine]} 1 {} { set x [{*}$f1 $f2 [yield $x]] } }} $f1 $f2 }
http://rosettacode.org/wiki/Password_generator
Password generator
Create a password generation program which will generate passwords containing random ASCII characters from the following groups: lower-case letters: a ──► z upper-case letters: A ──► Z digits: 0 ──► 9 other printable characters:  !"#$%&'()*+,-./:;<=>?@[]^_{|}~ (the above character list excludes white-space, backslash and grave) The generated password(s) must include   at least one   (of each of the four groups): lower-case letter, upper-case letter, digit (numeral),   and one "other" character. The user must be able to specify the password length and the number of passwords to generate. The passwords should be displayed or written to a file, one per line. The randomness should be from a system source or library. The program should implement a help option or button which should describe the program and options when invoked. You may also allow the user to specify a seed value, and give the option of excluding visually similar characters. For example:           Il1     O0     5S     2Z           where the characters are:   capital eye, lowercase ell, the digit one   capital oh, the digit zero   the digit five, capital ess   the digit two, capital zee
#Scala
Scala
object makepwd extends App {   def newPassword( salt:String = "", length:Int = 13, strong:Boolean = true ) = {   val saltHash = salt.hashCode & ~(1 << 31)   import java.util.Calendar._   val cal = java.util.Calendar.getInstance() val rand = new scala.util.Random((cal.getTimeInMillis+saltHash).toLong) val lower = ('a' to 'z').mkString val upper = ('A' to 'Z').mkString val nums = ('0' to '9').mkString val strongs = "!\"#$%&'()*+,-./:;<=>?@[]^_{|}~" val unwanted = if( strong ) "" else "0Ol"   val pool = (lower + upper + nums + (if( strong ) strongs else "")). filterNot( c => unwanted.contains(c) )   val pwdStream = Stream.continually( (for( n <- 1 to length; c = pool(rand.nextInt(pool.length) ) ) yield c).mkString )   // Drop passwords that don't have at least one of each required character pwdStream.filter( pwd => pwd.exists(_.isUpper) && pwd.exists(_.isLower) && pwd.exists(_.isDigit) && (if(strong) pwd.exists(! _.isLetterOrDigit) else true) ).head }   val pwdLength = """^(\d{1,4})$""".r val howMany = """^\-n(\d{0,3})$""".r val help = """^\-\-(help)$""".r val pwdSalt = """^\-s(.*)""".r val strongOption = """(?i)(strong)""".r     var (salt,length,strong,helpWanted,count,unknown) = ("",13,false,false,1,false)   args.foreach{ case pwdLength(l) => length = math.min(math.max(l.toInt,6),4000) case strongOption(s) => strong = true case pwdSalt(s) => salt = s case howMany(c) => count = math.min(c.toInt,100) case help(h) => helpWanted = true case _ => unknown = true }   if( count > 1 ) println   if( helpWanted || unknown ) { println( """ makepwd <length> "strong" -s<salt> -n<how-many> --help   <length> = how long should the password be "strong" = strong password, omit if special characters not wanted -s<salt> = "-s" followed by any non-blank characters (increases password randomness) -n<how-many> = "-n" followed by the number of passwords wanted --help = displays this   For example: makepwd 13 strong -n20 -sABCDEFG """.stripMargin ) } else for( i <- 1 to count ) println( newPassword( i + salt, length, strong ) )   if( count > 1 ) println }
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm
Parsing/RPN calculator algorithm
Task Create a stack-based evaluator for an expression in   reverse Polish notation (RPN)   that also shows the changes in the stack as each individual token is processed as a table. Assume an input of a correct, space separated, string of tokens of an RPN expression Test with the RPN expression generated from the   Parsing/Shunting-yard algorithm   task:         3 4 2 * 1 5 - 2 3 ^ ^ / + Print or display the output here Notes   ^   means exponentiation in the expression above.   /   means division. See also   Parsing/Shunting-yard algorithm for a method of generating an RPN from an infix expression.   Several solutions to 24 game/Solve make use of RPN evaluators (although tracing how they work is not a part of that task).   Parsing/RPN to infix conversion.   Arithmetic evaluation.
#Liberty_BASIC
Liberty BASIC
  global stack$   expr$ = "3 4 2 * 1 5 - 2 3 ^ ^ / +" print "Expression:" print expr$ print   print "Input","Operation","Stack after"   stack$="" token$ = "#" i = 1 token$ = word$(expr$, i) token2$ = " "+token$+" "   do print "Token ";i;": ";token$, select case 'operation case instr("+-*/^",token$)<>0 print "operate", op2$=pop$() op1$=pop$() if op1$="" then print "Error: stack empty for ";i;"-th token: ";token$ end end if   op1=val(op1$) op2=val(op2$)   select case token$ case "+" res = op1+op2 case "-" res = op1-op2 case "*" res = op1*op2 case "/" res = op1/op2 case "^" res = op1^op2 end select   call push str$(res) 'default:number case else print "push", call push token$ end select print "Stack: ";reverse$(stack$) i = i+1 token$ = word$(expr$, i) token2$ = " "+token$+" " loop until token$ =""   res$=pop$() print print "Result:" ;res$ extra$=pop$() if extra$<>"" then print "Error: extra things on a stack: ";extra$ end if end   '--------------------------------------- function reverse$(s$) reverse$ = "" token$="#" while token$<>"" i=i+1 token$=word$(s$,i,"|") reverse$ = token$;" ";reverse$ wend end function '--------------------------------------- sub push s$ stack$=s$+"|"+stack$ 'stack end sub   function pop$() 'it does return empty on empty stack pop$=word$(stack$,1,"|") stack$=mid$(stack$,instr(stack$,"|")+1) end function  
http://rosettacode.org/wiki/Palindrome_detection
Palindrome detection
A palindrome is a phrase which reads the same backward and forward. Task[edit] Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. For extra credit: Support Unicode characters. Write a second function (possibly as a wrapper to the first) which detects inexact palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used. Hints It might be useful for this task to know how to reverse a string. This task's entries might also form the subjects of the task Test a function. Related tasks Word plays Ordered words Palindrome detection Semordnilap Anagrams Anagrams/Deranged anagrams 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
#BaCon
BaCon
  OPTION COMPARE TRUE   INPUT "Enter your line... ", word$   IF word$ = REVERSE$(word$) THEN PRINT "This is an exact palindrome!" ELIF EXTRACT$(word$, "[[:punct:]]|[[:blank:]]", TRUE) = REVERSE$(EXTRACT$(word$, "[[:punct:]]|[[:blank:]]", TRUE)) THEN PRINT "This is an inexact palindrome!" ELSE PRINT "Not a palindrome." ENDIF  
http://rosettacode.org/wiki/Palindromic_gapful_numbers
Palindromic gapful numbers
Palindromic gapful numbers You are encouraged to solve this task according to the task description, using any language you may know. Numbers   (positive integers expressed in base ten)   that are (evenly) divisible by the number formed by the first and last digit are known as   gapful numbers. Evenly divisible   means divisible with   no   remainder. All   one─   and two─digit   numbers have this property and are trivially excluded.   Only numbers   ≥ 100   will be considered for this Rosetta Code task. Example 1037   is a   gapful   number because it is evenly divisible by the number   17   which is formed by the first and last decimal digits of   1037. A palindromic number is   (for this task, a positive integer expressed in base ten),   when the number is reversed,   is the same as the original number. Task   Show   (nine sets)   the first   20   palindromic gapful numbers that   end   with:   the digit   1   the digit   2   the digit   3   the digit   4   the digit   5   the digit   6   the digit   7   the digit   8   the digit   9   Show   (nine sets, like above)   of palindromic gapful numbers:   the last   15   palindromic gapful numbers   (out of      100)   the last   10   palindromic gapful numbers   (out of   1,000)       {optional} For other ways of expressing the (above) requirements, see the   discussion   page. Note All palindromic gapful numbers are divisible by eleven. Related tasks   palindrome detection.   gapful numbers. Also see   The OEIS entry:   A108343 gapful numbers.
#Raku
Raku
constant @digits = '0','1','2','3','4','5','6','7','8','9';   # Infinite lazy iterator to generate palindromic "gap" numbers my @npal = flat [ @digits ], [ '00','11','22','33','44','55','66','77','88','99' ], { sink @^previous, @^penultimate; [ flat @digits.map: -> \digit { @penultimate.map: digit ~ * ~ digit } ] } … *;   # Individual lazy palindromic gapful number iterators for each start/end digit my @gappal = (1..9).map: -> \digit { my \divisor = digit + 10 * digit; @npal.map: -> \this { next unless (my \test = digit ~ this ~ digit) %% divisor; test } }   # Display ( "(Required) First 20 gapful palindromes:", ^20, 7 ,"\n(Required) 86th through 100th:", 85..99, 8 ,"\n(Optional) 991st through 1,000th:", 990..999, 10 ,"\n(Extra stretchy) 9,995th through 10,000th:", 9994..9999, 12 ,"\n(Meh) 100,000th:", 99999, 14 ).hyper(:1batch).map: -> $caption, $range, $fmt { my $now = now; say $caption; put "$_: " ~ @gappal[$_-1][|$range].fmt("%{$fmt}s") for 1..9; say round( now - $now, .001 ), " seconds"; }
http://rosettacode.org/wiki/Parsing/Shunting-yard_algorithm
Parsing/Shunting-yard algorithm
Task Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output as each individual token is processed. Assume an input of a correct, space separated, string of tokens representing an infix expression Generate a space separated output string representing the RPN Test with the input string: 3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3 print and display the output here. Operator precedence is given in this table: operator precedence associativity operation ^ 4 right exponentiation * 3 left multiplication / 3 left division + 2 left addition - 2 left subtraction Extra credit Add extra text explaining the actions and an optional comment for the action on receipt of each token. Note The handling of functions and arguments is not required. See also Parsing/RPN calculator algorithm for a method of calculating a final value from this output RPN expression. Parsing/RPN to infix conversion.
#Ruby
Ruby
rpn = RPNExpression.from_infix("3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3")
http://rosettacode.org/wiki/Parsing/Shunting-yard_algorithm
Parsing/Shunting-yard algorithm
Task Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output as each individual token is processed. Assume an input of a correct, space separated, string of tokens representing an infix expression Generate a space separated output string representing the RPN Test with the input string: 3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3 print and display the output here. Operator precedence is given in this table: operator precedence associativity operation ^ 4 right exponentiation * 3 left multiplication / 3 left division + 2 left addition - 2 left subtraction Extra credit Add extra text explaining the actions and an optional comment for the action on receipt of each token. Note The handling of functions and arguments is not required. See also Parsing/RPN calculator algorithm for a method of calculating a final value from this output RPN expression. Parsing/RPN to infix conversion.
#Rust
Rust
type Number = f64;   #[derive(Debug, Copy, Clone, PartialEq)] struct Operator { token: char, operation: fn(Number, Number) -> Number, precedence: u8, is_left_associative: bool, }   #[derive(Debug, Clone, PartialEq)] enum Token { Digit(Number), Operator(Operator), LeftParen, RightParen, }   impl Operator { fn new_token( token: char, precedence: u8, is_left_associative: bool, operation: fn(Number, Number) -> Number, ) -> Token { Token::Operator(Operator { token: token, operation: operation, precedence: precedence, is_left_associative, }) }   fn apply(&self, x: Number, y: Number) -> Number { (self.operation)(x, y) } }   trait Stack<T> { fn top(&self) -> Option<T>; }   impl<T: Clone> Stack<T> for Vec<T> { fn top(&self) -> Option<T> { if self.is_empty() { return None; } self.last().cloned() } } fn lex_token(input: char) -> Result<Token, char> { let ret = match input { '0'...'9' => Token::Digit(input.to_digit(10).unwrap() as Number), '+' => Operator::new_token('+', 1, true, |x, y| x + y), '-' => Operator::new_token('-', 1, true, |x, y| x - y), '*' => Operator::new_token('*', 2, true, |x, y| x * y), '/' => Operator::new_token('/', 2, true, |x, y| x / y), '^' => Operator::new_token('^', 3, false, |x, y| x.powf(y)), '(' => Token::LeftParen, ')' => Token::RightParen, _ => return Err(input), }; Ok(ret) }   fn lex(input: String) -> Result<Vec<Token>, char> { input .chars() .filter(|c| !c.is_whitespace()) .map(lex_token) .collect() }   fn tilt_until(operators: &mut Vec<Token>, output: &mut Vec<Token>, stop: Token) -> bool { while let Some(token) = operators.pop() { if token == stop { return true; } output.push(token) } false }   fn shunting_yard(tokens: Vec<Token>) -> Result<Vec<Token>, String> { let mut output: Vec<Token> = Vec::new(); let mut operators: Vec<Token> = Vec::new();   for token in tokens { match token { Token::Digit(_) => output.push(token), Token::LeftParen => operators.push(token), Token::Operator(operator) => { while let Some(top) = operators.top() { match top { Token::LeftParen => break, Token::Operator(top_op) => { let p = top_op.precedence; let q = operator.precedence; if (p > q) || (p == q && operator.is_left_associative) { output.push(operators.pop().unwrap()); } else { break; } } _ => unreachable!("{:?} must not be on operator stack", token), } } operators.push(token); } Token::RightParen => { if !tilt_until(&mut operators, &mut output, Token::LeftParen) { return Err(String::from("Mismatched ')'")); } } } }   if tilt_until(&mut operators, &mut output, Token::LeftParen) { return Err(String::from("Mismatched '('")); }   assert!(operators.is_empty()); Ok(output) }   fn calculate(postfix_tokens: Vec<Token>) -> Result<Number, String> { let mut stack = Vec::new();   for token in postfix_tokens { match token { Token::Digit(number) => stack.push(number), Token::Operator(operator) => { if let Some(y) = stack.pop() { if let Some(x) = stack.pop() { stack.push(operator.apply(x, y)); continue; } } return Err(format!("Missing operand for operator '{}'", operator.token)); } _ => unreachable!("Unexpected token {:?} during calculation", token), } }   assert!(stack.len() == 1); Ok(stack.pop().unwrap()) }   fn run(input: String) -> Result<Number, String> { let tokens = match lex(input) { Ok(tokens) => tokens, Err(c) => return Err(format!("Invalid character: {}", c)), }; let postfix_tokens = match shunting_yard(tokens) { Ok(tokens) => tokens, Err(message) => return Err(message), };   calculate(postfix_tokens) }
http://rosettacode.org/wiki/Pangram_checker
Pangram checker
Pangram checker You are encouraged to solve this task according to the task description, using any language you may know. A pangram is a sentence that contains all the letters of the English alphabet at least once. For example:   The quick brown fox jumps over the lazy dog. Task Write a function or method to check a sentence to see if it is a   pangram   (or not)   and show its use. Related tasks   determine if a string has all the same characters   determine if a string has all unique characters
#Elixir
Elixir
defmodule Pangram do def checker(str) do unused = Enum.to_list(?a..?z) -- to_char_list(String.downcase(str)) Enum.empty?(unused) end end   text = "The quick brown fox jumps over the lazy dog." IO.puts "#{Pangram.checker(text)}\t#{text}" text = (Enum.to_list(?A..?Z) -- 'Test') |> to_string IO.puts "#{Pangram.checker(text)}\t#{text}"
http://rosettacode.org/wiki/Pangram_checker
Pangram checker
Pangram checker You are encouraged to solve this task according to the task description, using any language you may know. A pangram is a sentence that contains all the letters of the English alphabet at least once. For example:   The quick brown fox jumps over the lazy dog. Task Write a function or method to check a sentence to see if it is a   pangram   (or not)   and show its use. Related tasks   determine if a string has all the same characters   determine if a string has all unique characters
#Erlang
Erlang
-module(pangram). -export([is_pangram/1]).   is_pangram(String) -> ordsets:is_subset(lists:seq($a, $z), ordsets:from_list(string:to_lower(String))).
http://rosettacode.org/wiki/Pascal_matrix_generation
Pascal matrix generation
A pascal matrix is a two-dimensional square matrix holding numbers from   Pascal's triangle,   also known as   binomial coefficients   and which can be shown as   nCr. Shown below are truncated   5-by-5   matrices   M[i, j]   for   i,j   in range   0..4. A Pascal upper-triangular matrix that is populated with   jCi: [[1, 1, 1, 1, 1], [0, 1, 2, 3, 4], [0, 0, 1, 3, 6], [0, 0, 0, 1, 4], [0, 0, 0, 0, 1]] A Pascal lower-triangular matrix that is populated with   iCj   (the transpose of the upper-triangular matrix): [[1, 0, 0, 0, 0], [1, 1, 0, 0, 0], [1, 2, 1, 0, 0], [1, 3, 3, 1, 0], [1, 4, 6, 4, 1]] A Pascal symmetric matrix that is populated with   i+jCi: [[1, 1, 1, 1, 1], [1, 2, 3, 4, 5], [1, 3, 6, 10, 15], [1, 4, 10, 20, 35], [1, 5, 15, 35, 70]] Task Write functions capable of generating each of the three forms of   n-by-n   matrices. Use those functions to display upper, lower, and symmetric Pascal   5-by-5   matrices on this page. The output should distinguish between different matrices and the rows of each matrix   (no showing a list of 25 numbers assuming the reader should split it into rows). Note The   Cholesky decomposition   of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size.
#Perl
Perl
#!/usr/bin/perl use warnings; use strict; use feature qw{ say };     sub upper { my ($i, $j) = @_; my @m; for my $x (0 .. $i - 1) { for my $y (0 .. $j - 1) { $m[$x][$y] = $x > $y ? 0 : ! $x || $x == $y ? 1 : $m[$x-1][$y-1] + $m[$x][$y-1]; } } return \@m }     sub lower { my ($i, $j) = @_; my @m; for my $x (0 .. $i - 1) { for my $y (0 .. $j - 1) { $m[$x][$y] = $x < $y ? 0 : ! $x || $x == $y ? 1 : $m[$x-1][$y-1] + $m[$x-1][$y]; } } return \@m }     sub symmetric { my ($i, $j) = @_; my @m; for my $x (0 .. $i - 1) { for my $y (0 .. $j - 1) { $m[$x][$y] = ! $x || ! $y ? 1 : $m[$x-1][$y] + $m[$x][$y-1]; } } return \@m }     sub pretty { my $m = shift; for my $row (@$m) { say join ', ', @$row; } }     pretty(upper(5, 5)); say '-' x 14; pretty(lower(5, 5)); say '-' x 14; pretty(symmetric(5, 5));
http://rosettacode.org/wiki/Pascal%27s_triangle
Pascal's triangle
Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is either 1 or the sum of the two elements right above it. For example, the next row of the triangle would be:   1   (since the first element of each row doesn't have two elements above it)   4   (1 + 3)   6   (3 + 3)   4   (3 + 1)   1   (since the last element of each row doesn't have two elements above it) So the triangle now looks like this: 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 Each row   n   (starting with row   0   at the top) shows the coefficients of the binomial expansion of   (x + y)n. Task Write a function that prints out the first   n   rows of the triangle   (with   f(1)   yielding the row consisting of only the element 1). This can be done either by summing elements from the previous rows or using a binary coefficient or combination function. Behavior for   n ≤ 0   does not need to be uniform, but should be noted. See also Evaluate binomial coefficients
#ERRE
ERRE
  PROGRAM PASCAL_TRIANGLE   PROCEDURE PASCAL(R%) LOCAL I%,C%,K% FOR I%=0 TO R%-1 DO C%=1 FOR K%=0 TO I% DO WRITE("###";C%;) C%=(C%*(I%-K%)) DIV (K%+1) END FOR PRINT END FOR END PROCEDURE   BEGIN PASCAL(9) END PROGRAM  
http://rosettacode.org/wiki/Partial_function_application
Partial function application
Partial function application   is the ability to take a function of many parameters and apply arguments to some of the parameters to create a new function that needs only the application of the remaining arguments to produce the equivalent of applying all arguments to the original function. E.g: Given values v1, v2 Given f(param1, param2) Then partial(f, param1=v1) returns f'(param2) And f(param1=v1, param2=v2) == f'(param2=v2) (for any value v2) Note that in the partial application of a parameter, (in the above case param1), other parameters are not explicitly mentioned. This is a recurring feature of partial function application. Task Create a function fs( f, s ) that takes a function, f( n ), of one value and a sequence of values s. Function fs should return an ordered sequence of the result of applying function f to every value of s in turn. Create function f1 that takes a value and returns it multiplied by 2. Create function f2 that takes a value and returns it squared. Partially apply f1 to fs to form function fsf1( s ) Partially apply f2 to fs to form function fsf2( s ) Test fsf1 and fsf2 by evaluating them with s being the sequence of integers from 0 to 3 inclusive and then the sequence of even integers from 2 to 8 inclusive. Notes In partially applying the functions f1 or f2 to fs, there should be no explicit mention of any other parameters to fs, although introspection of fs within the partial applicator to find its parameters is allowed. This task is more about how results are generated rather than just getting results.
#TXR
TXR
$ txr -p "(mapcar (op mapcar (op * 2)) (list (range 0 3) (range 2 8 2)))" ((0 2 4 6) (4 8 12 16))   $ txr -p "(mapcar (op mapcar (op * @1 @1)) (list (range 0 3) (range 2 8 2)))" ((0 1 4 9) (4 16 36 64))
http://rosettacode.org/wiki/Partial_function_application
Partial function application
Partial function application   is the ability to take a function of many parameters and apply arguments to some of the parameters to create a new function that needs only the application of the remaining arguments to produce the equivalent of applying all arguments to the original function. E.g: Given values v1, v2 Given f(param1, param2) Then partial(f, param1=v1) returns f'(param2) And f(param1=v1, param2=v2) == f'(param2=v2) (for any value v2) Note that in the partial application of a parameter, (in the above case param1), other parameters are not explicitly mentioned. This is a recurring feature of partial function application. Task Create a function fs( f, s ) that takes a function, f( n ), of one value and a sequence of values s. Function fs should return an ordered sequence of the result of applying function f to every value of s in turn. Create function f1 that takes a value and returns it multiplied by 2. Create function f2 that takes a value and returns it squared. Partially apply f1 to fs to form function fsf1( s ) Partially apply f2 to fs to form function fsf2( s ) Test fsf1 and fsf2 by evaluating them with s being the sequence of integers from 0 to 3 inclusive and then the sequence of even integers from 2 to 8 inclusive. Notes In partially applying the functions f1 or f2 to fs, there should be no explicit mention of any other parameters to fs, although introspection of fs within the partial applicator to find its parameters is allowed. This task is more about how results are generated rather than just getting results.
#Visual_Basic_.NET
Visual Basic .NET
Module PartialApplication Function fs(Of TSource, TResult)(f As Func(Of TSource, TResult), s As IEnumerable(Of TSource)) As IEnumerable(Of TResult) ' This is exactly what Enumerable.Select does. Return s.Select(f) End Function   Function f1(x As Integer) As Integer Return x * 2 End Function   Function f2(x As Integer) As Integer Return x * x End Function   ' The overload that takes a binary function and partially applies to its first parameter. Function PartialApply(Of T1, T2, TResult)(f As Func(Of T1, T2, TResult), arg As T1) As Func(Of T2, TResult) Return Function(arg2) f(arg, arg2) End Function   Sub Main() Dim args1 As Integer() = {0, 1, 2, 3} Dim args2 As Integer() = {2, 4, 6, 8}   Dim fsf1 = PartialApply(Of Func(Of Integer, Integer), IEnumerable(Of Integer), IEnumerable(Of Integer))(AddressOf fs, AddressOf f1) Dim fsf2 = PartialApply(Of Func(Of Integer, Integer), IEnumerable(Of Integer), IEnumerable(Of Integer))(AddressOf fs, AddressOf f2)   Console.WriteLine("fsf1, 0-3: " & String.Join(", ", fsf1(args1))) Console.WriteLine("fsf1, evens: " & String.Join(", ", fsf1(args2))) Console.WriteLine("fsf2, 0-3: " & String.Join(", ", fsf2(args1))) Console.WriteLine("fsf2, evens: " & String.Join(", ", fsf2(args2))) End Sub End Module
http://rosettacode.org/wiki/Password_generator
Password generator
Create a password generation program which will generate passwords containing random ASCII characters from the following groups: lower-case letters: a ──► z upper-case letters: A ──► Z digits: 0 ──► 9 other printable characters:  !"#$%&'()*+,-./:;<=>?@[]^_{|}~ (the above character list excludes white-space, backslash and grave) The generated password(s) must include   at least one   (of each of the four groups): lower-case letter, upper-case letter, digit (numeral),   and one "other" character. The user must be able to specify the password length and the number of passwords to generate. The passwords should be displayed or written to a file, one per line. The randomness should be from a system source or library. The program should implement a help option or button which should describe the program and options when invoked. You may also allow the user to specify a seed value, and give the option of excluding visually similar characters. For example:           Il1     O0     5S     2Z           where the characters are:   capital eye, lowercase ell, the digit one   capital oh, the digit zero   the digit five, capital ess   the digit two, capital zee
#Seed7
Seed7
$ include "seed7_05.s7i";   const func string: generate (in integer: length) is func result var string: password is ""; local const set of char: allowed is {'!' .. '~'} - {'\\', '`'}; const set of char: special is allowed - {'A' .. 'Z'} | {'a' .. 'z'} | {'0' .. '9'}; var integer: index is 0; var char: ch is ' '; var boolean: ucPresent is FALSE; var boolean: lcPresent is FALSE; var boolean: digitPresent is FALSE; var boolean: specialPresent is FALSE; begin repeat password := ""; ucPresent := FALSE; lcPresent := FALSE; digitPresent := FALSE; specialPresent := FALSE; for index range 1 to length do ch := rand(allowed); ucPresent := ucPresent or ch in {'A' .. 'Z'}; lcPresent := lcPresent or ch in {'a' .. 'z'}; digitPresent := digitPresent or ch in {'0' .. '9'}; specialPresent := specialPresent or ch in special; password &:= ch; end for; until ucPresent and lcPresent and digitPresent and specialPresent; end func;   const proc: main is func local var integer: length is 0; var integer: count is 0; begin if length(argv(PROGRAM)) <> 2 or not isDigitString(argv(PROGRAM)[1]) or not isDigitString(argv(PROGRAM)[2]) then writeln("Usage: pwgen length count"); writeln(" pwgen -?"); writeln("length: The length of the password (min 4)"); writeln("count: How many passwords should be generated"); writeln("-? Write this text"); else length := integer(argv(PROGRAM)[1]); count := integer(argv(PROGRAM)[2]); if length < 4 then writeln("Passwords must be at least 4 characters long."); else for count do writeln(generate(length)); end for; end if; end if; end func;
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm
Parsing/RPN calculator algorithm
Task Create a stack-based evaluator for an expression in   reverse Polish notation (RPN)   that also shows the changes in the stack as each individual token is processed as a table. Assume an input of a correct, space separated, string of tokens of an RPN expression Test with the RPN expression generated from the   Parsing/Shunting-yard algorithm   task:         3 4 2 * 1 5 - 2 3 ^ ^ / + Print or display the output here Notes   ^   means exponentiation in the expression above.   /   means division. See also   Parsing/Shunting-yard algorithm for a method of generating an RPN from an infix expression.   Several solutions to 24 game/Solve make use of RPN evaluators (although tracing how they work is not a part of that task).   Parsing/RPN to infix conversion.   Arithmetic evaluation.
#Lua
Lua
  local stack = {} function push( a ) table.insert( stack, 1, a ) end function pop() if #stack == 0 then return nil end return table.remove( stack, 1 ) end function writeStack() for i = #stack, 1, -1 do io.write( stack[i], " " ) end print() end function operate( a ) local s if a == "+" then push( pop() + pop() ) io.write( a .. "\tadd\t" ); writeStack() elseif a == "-" then s = pop(); push( pop() - s ) io.write( a .. "\tsub\t" ); writeStack() elseif a == "*" then push( pop() * pop() ) io.write( a .. "\tmul\t" ); writeStack() elseif a == "/" then s = pop(); push( pop() / s ) io.write( a .. "\tdiv\t" ); writeStack() elseif a == "^" then s = pop(); push( pop() ^ s ) io.write( a .. "\tpow\t" ); writeStack() elseif a == "%" then s = pop(); push( pop() % s ) io.write( a .. "\tmod\t" ); writeStack() else push( tonumber( a ) ) io.write( a .. "\tpush\t" ); writeStack() end end function calc( s ) local t, a = "", "" print( "\nINPUT", "OP", "STACK" ) for i = 1, #s do a = s:sub( i, i ) if a == " " then operate( t ); t = "" else t = t .. a end end if a ~= "" then operate( a ) end print( string.format( "\nresult: %.13f", pop() ) ) end --[[ entry point ]]-- calc( "3 4 2 * 1 5 - 2 3 ^ ^ / +" ) calc( "22 11 *" )
http://rosettacode.org/wiki/Palindrome_detection
Palindrome detection
A palindrome is a phrase which reads the same backward and forward. Task[edit] Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. For extra credit: Support Unicode characters. Write a second function (possibly as a wrapper to the first) which detects inexact palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used. Hints It might be useful for this task to know how to reverse a string. This task's entries might also form the subjects of the task Test a function. Related tasks Word plays Ordered words Palindrome detection Semordnilap Anagrams Anagrams/Deranged anagrams 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
#Bash
Bash
  #! /bin/bash # very simple way to detect a palindrome in Bash # output of bash --version -> GNU bash, version 4.4.7(1)-release x86_64 ...   echo "enter a string" read input   size=${#input} count=0   while (($count < $size)) do array[$count]=${input:$count:1} (( count+=1 )) done   count=0   for ((i=0 ; i < $size; i+=1)) do if [ "${array[$i]}" == "${array[$size - $i - 1]}" ] then (( count += 1 )) fi done   if (( $count == $size )) then echo "$input is a palindrome" fi  
http://rosettacode.org/wiki/Palindromic_gapful_numbers
Palindromic gapful numbers
Palindromic gapful numbers You are encouraged to solve this task according to the task description, using any language you may know. Numbers   (positive integers expressed in base ten)   that are (evenly) divisible by the number formed by the first and last digit are known as   gapful numbers. Evenly divisible   means divisible with   no   remainder. All   one─   and two─digit   numbers have this property and are trivially excluded.   Only numbers   ≥ 100   will be considered for this Rosetta Code task. Example 1037   is a   gapful   number because it is evenly divisible by the number   17   which is formed by the first and last decimal digits of   1037. A palindromic number is   (for this task, a positive integer expressed in base ten),   when the number is reversed,   is the same as the original number. Task   Show   (nine sets)   the first   20   palindromic gapful numbers that   end   with:   the digit   1   the digit   2   the digit   3   the digit   4   the digit   5   the digit   6   the digit   7   the digit   8   the digit   9   Show   (nine sets, like above)   of palindromic gapful numbers:   the last   15   palindromic gapful numbers   (out of      100)   the last   10   palindromic gapful numbers   (out of   1,000)       {optional} For other ways of expressing the (above) requirements, see the   discussion   page. Note All palindromic gapful numbers are divisible by eleven. Related tasks   palindrome detection.   gapful numbers. Also see   The OEIS entry:   A108343 gapful numbers.
#REXX
REXX
/*REXX program computes and displays palindromic gapful numbers, it also can show those */ /*─────────────────────── palindromic gapful numbers listed by their last decimal digit.*/ numeric digits 20 /*ensure enough decimal digits gapfuls.*/ parse arg palGaps /*obtain optional arguments from the CL*/ if palGaps='' then palGaps= 20 100@@15 1000@@10 /*Not specified? Then use the defaults*/   do until palGaps=''; parse var palGaps stuff palGaps; call palGap stuff end /*until*/ exit 0 /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ palGap: procedure; parse arg n '@' sp "@" z; #= 0; if sp=='' then sp= 100 @ending= ' (ending in a specific digit) '; if z=='' then z= n @which= ' last '; if z==n then @which= " first " @palGap#Start= ' palindromic gapful numbers starting at: ' say center(@which z ' of ' n @palGap#Start sp" " @ending, 140, "═") #.= 0 /*array of result counts for each digit*/ newSP= max(110, sp%11*11) /*calculate the new starting point. */ tot= n * 9 /*total # of results that are wanted. */ $.=; sum= 0 /*blank lists; digit results (so far).*/ do j=newSP by 11 until sum==tot /*loop 'til all digit counters filled. */ if reverse(j) \==j then iterate /*Not a palindrome? Then skip it.*/ parse var j a 2 '' -1 b /*obtain the first and last dec. digit.*/ if #.b ==n then iterate /*Digit quota filled? Then skip it.*/ if j // (a||b) \==0 then iterate /*Not divisible by A||B? " " " */ sum= sum + 1; #.b= #.b + 1 /*bump the sum counter & digit counter.*/ $.b= $.b j /*append J to the correct list. */ end /*j*/ /* [↓] just show the last Z numbers.*/ do k=1 for 9; say k':' strip( subword($.k, 1 + n - z) ) end /*k*/; say return
http://rosettacode.org/wiki/Parsing/Shunting-yard_algorithm
Parsing/Shunting-yard algorithm
Task Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output as each individual token is processed. Assume an input of a correct, space separated, string of tokens representing an infix expression Generate a space separated output string representing the RPN Test with the input string: 3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3 print and display the output here. Operator precedence is given in this table: operator precedence associativity operation ^ 4 right exponentiation * 3 left multiplication / 3 left division + 2 left addition - 2 left subtraction Extra credit Add extra text explaining the actions and an optional comment for the action on receipt of each token. Note The handling of functions and arguments is not required. See also Parsing/RPN calculator algorithm for a method of calculating a final value from this output RPN expression. Parsing/RPN to infix conversion.
#Sidef
Sidef
var prec = Hash( '^' => 4, '*' => 3, '/' => 3, '+' => 2, '-' => 2, '(' => 1, )   var assoc = Hash( '^' => 'right', '*' => 'left', '/' => 'left', '+' => 'left', '-' => 'left', )   func shunting_yard(prog) { var inp = prog.words var ops = [] var res = []   func report (op) { printf("%25s  %-7s %10s %s\n", res.join(' '), ops.join(' '), op, inp.join(' ')) }   func shift (t) { report( "shift #{t}"); ops << t } func reduce (t) { report("reduce #{t}"); res << t }   while (inp) { given(var t = inp.shift) { when (/\d/) { reduce(t) } when ('(') { shift(t) } when (')') { while (ops) { (var x = ops.pop) == '(' ? break : reduce(x) } } default { var newprec = prec{t} while (ops) { var oldprec = prec{ops[-1]}   break if (newprec > oldprec) break if ((newprec == oldprec) && (assoc{t} == 'right'))   reduce(ops.pop) } shift(t) } } } while (ops) { reduce(ops.pop) } return res }   say shunting_yard('3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3').join(' ')
http://rosettacode.org/wiki/Pangram_checker
Pangram checker
Pangram checker You are encouraged to solve this task according to the task description, using any language you may know. A pangram is a sentence that contains all the letters of the English alphabet at least once. For example:   The quick brown fox jumps over the lazy dog. Task Write a function or method to check a sentence to see if it is a   pangram   (or not)   and show its use. Related tasks   determine if a string has all the same characters   determine if a string has all unique characters
#Excel
Excel
ISPANGRAM =LAMBDA(s, LET( abc, CHARS(LOWER("abcdefghijklmnopqrstuvwxyz")), AND( LAMBDA(c, ISNUMBER(SEARCH(c, s, 1)) )( abc ) ) ) )
http://rosettacode.org/wiki/Pangram_checker
Pangram checker
Pangram checker You are encouraged to solve this task according to the task description, using any language you may know. A pangram is a sentence that contains all the letters of the English alphabet at least once. For example:   The quick brown fox jumps over the lazy dog. Task Write a function or method to check a sentence to see if it is a   pangram   (or not)   and show its use. Related tasks   determine if a string has all the same characters   determine if a string has all unique characters
#F.23
F#
let isPangram (str: string) = (set['a'..'z'] - set(str.ToLower())).IsEmpty
http://rosettacode.org/wiki/Pascal_matrix_generation
Pascal matrix generation
A pascal matrix is a two-dimensional square matrix holding numbers from   Pascal's triangle,   also known as   binomial coefficients   and which can be shown as   nCr. Shown below are truncated   5-by-5   matrices   M[i, j]   for   i,j   in range   0..4. A Pascal upper-triangular matrix that is populated with   jCi: [[1, 1, 1, 1, 1], [0, 1, 2, 3, 4], [0, 0, 1, 3, 6], [0, 0, 0, 1, 4], [0, 0, 0, 0, 1]] A Pascal lower-triangular matrix that is populated with   iCj   (the transpose of the upper-triangular matrix): [[1, 0, 0, 0, 0], [1, 1, 0, 0, 0], [1, 2, 1, 0, 0], [1, 3, 3, 1, 0], [1, 4, 6, 4, 1]] A Pascal symmetric matrix that is populated with   i+jCi: [[1, 1, 1, 1, 1], [1, 2, 3, 4, 5], [1, 3, 6, 10, 15], [1, 4, 10, 20, 35], [1, 5, 15, 35, 70]] Task Write functions capable of generating each of the three forms of   n-by-n   matrices. Use those functions to display upper, lower, and symmetric Pascal   5-by-5   matrices on this page. The output should distinguish between different matrices and the rows of each matrix   (no showing a list of 25 numbers assuming the reader should split it into rows). Note The   Cholesky decomposition   of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size.
#Phix
Phix
function pascal_upper(integer n) sequence res = repeat(repeat(0,n),n) res[1] = repeat(1,n) for i=2 to n do for j=2 to i do res[j,i] = res[j,i-1]+res[j-1,i-1] end for end for return res end function function pascal_lower(integer n) sequence res = repeat(repeat(0,n),n) for i=1 to n do res[i,1] = 1 end for for i=2 to n do for j=2 to i do res[i,j] = res[i-1,j]+res[i-1,j-1] end for end for return res end function function pascal_symmetric(integer n) sequence res = repeat(repeat(0,n),n) for i=1 to n do res[i,1] = 1 res[1,i] = 1 end for for i=2 to n do for j = 2 to n do res[i,j] = res[i-1,j]+res[i,j-1] end for end for return res end function ppOpt({pp_Nest,1,pp_IntCh,false,pp_IntFmt,"%2d"}) puts(1,"=== Pascal upper matrix ===\n") pp(pascal_upper(5)) puts(1,"=== Pascal lower matrix ===\n") pp(pascal_lower(5)) puts(1,"=== Pascal symmetrical matrix ===\n") pp(pascal_symmetric(5))
http://rosettacode.org/wiki/Pascal%27s_triangle
Pascal's triangle
Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is either 1 or the sum of the two elements right above it. For example, the next row of the triangle would be:   1   (since the first element of each row doesn't have two elements above it)   4   (1 + 3)   6   (3 + 3)   4   (3 + 1)   1   (since the last element of each row doesn't have two elements above it) So the triangle now looks like this: 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 Each row   n   (starting with row   0   at the top) shows the coefficients of the binomial expansion of   (x + y)n. Task Write a function that prints out the first   n   rows of the triangle   (with   f(1)   yielding the row consisting of only the element 1). This can be done either by summing elements from the previous rows or using a binary coefficient or combination function. Behavior for   n ≤ 0   does not need to be uniform, but should be noted. See also Evaluate binomial coefficients
#Euphoria
Euphoria
sequence row row = {} for m = 1 to 10 do row = row & 1 for n = length(row)-1 to 2 by -1 do row[n] += row[n-1] end for print(1,row) puts(1,'\n') end for
http://rosettacode.org/wiki/Partial_function_application
Partial function application
Partial function application   is the ability to take a function of many parameters and apply arguments to some of the parameters to create a new function that needs only the application of the remaining arguments to produce the equivalent of applying all arguments to the original function. E.g: Given values v1, v2 Given f(param1, param2) Then partial(f, param1=v1) returns f'(param2) And f(param1=v1, param2=v2) == f'(param2=v2) (for any value v2) Note that in the partial application of a parameter, (in the above case param1), other parameters are not explicitly mentioned. This is a recurring feature of partial function application. Task Create a function fs( f, s ) that takes a function, f( n ), of one value and a sequence of values s. Function fs should return an ordered sequence of the result of applying function f to every value of s in turn. Create function f1 that takes a value and returns it multiplied by 2. Create function f2 that takes a value and returns it squared. Partially apply f1 to fs to form function fsf1( s ) Partially apply f2 to fs to form function fsf2( s ) Test fsf1 and fsf2 by evaluating them with s being the sequence of integers from 0 to 3 inclusive and then the sequence of even integers from 2 to 8 inclusive. Notes In partially applying the functions f1 or f2 to fs, there should be no explicit mention of any other parameters to fs, although introspection of fs within the partial applicator to find its parameters is allowed. This task is more about how results are generated rather than just getting results.
#Wren
Wren
var fs = Fn.new { |f, s| s.map { |e| f.call(e) }.toList } var f1 = Fn.new { |n| 2 * n } var f2 = Fn.new { |n| n * n }   var partial = Fn.new { |f, g| Fn.new { |x| f.call(g, x) } }   var ss = [[0, 1, 2, 3], [2, 4, 6, 8]] for (s in ss) { var fsf1 = partial.call(fs, f1) var fsf2 = partial.call(fs, f2) System.print(fsf1.call(s)) System.print(fsf2.call(s)) System.print() }
http://rosettacode.org/wiki/Partial_function_application
Partial function application
Partial function application   is the ability to take a function of many parameters and apply arguments to some of the parameters to create a new function that needs only the application of the remaining arguments to produce the equivalent of applying all arguments to the original function. E.g: Given values v1, v2 Given f(param1, param2) Then partial(f, param1=v1) returns f'(param2) And f(param1=v1, param2=v2) == f'(param2=v2) (for any value v2) Note that in the partial application of a parameter, (in the above case param1), other parameters are not explicitly mentioned. This is a recurring feature of partial function application. Task Create a function fs( f, s ) that takes a function, f( n ), of one value and a sequence of values s. Function fs should return an ordered sequence of the result of applying function f to every value of s in turn. Create function f1 that takes a value and returns it multiplied by 2. Create function f2 that takes a value and returns it squared. Partially apply f1 to fs to form function fsf1( s ) Partially apply f2 to fs to form function fsf2( s ) Test fsf1 and fsf2 by evaluating them with s being the sequence of integers from 0 to 3 inclusive and then the sequence of even integers from 2 to 8 inclusive. Notes In partially applying the functions f1 or f2 to fs, there should be no explicit mention of any other parameters to fs, although introspection of fs within the partial applicator to find its parameters is allowed. This task is more about how results are generated rather than just getting results.
#zkl
zkl
fcn fs(f,s){s.apply(f)} fcn f1(n){n*2} fcn f2(n){n*n} var fsf1=fs.fp(f1), fsf2=fs.fp(f2); fsf1([0..3]); //-->L(0,2,4,6) fsf2([2..8,2]); //-->L(4,16,36,64)