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/Parametric_polymorphism
Parametric polymorphism
Parametric Polymorphism type variables Task Write a small example for a type declaration that is parametric over another type, together with a short bit of code (and its type signature) that uses it. A good example is a container type, let's say a binary tree, together with some function that traverses the tree, say, a map-function that operates on every element of the tree. This language feature only applies to statically-typed languages.
#Julia
Julia
module BinaryTrees   mutable struct BinaryTree{V} v::V l::Union{BinaryTree{V}, Nothing} r::Union{BinaryTree{V}, Nothing} end   BinaryTree(v) = BinaryTree(v, nothing, nothing)   map(f, bt::BinaryTree) = BinaryTree(f(bt.v), map(f, bt.l), map(f, bt.r)) map(f, bt::Nothing) = nothing   let inttree = BinaryTree( 0, BinaryTree( 1, BinaryTree(3), BinaryTree(5), ), BinaryTree( 2, BinaryTree(4), nothing, ), ) map(x -> 2x^2, inttree) end   let strtree = BinaryTree( "hello", BinaryTree( "world!", BinaryTree("Julia"), nothing, ), BinaryTree( "foo", BinaryTree("bar"), BinaryTree("baz"), ), ) map(uppercase, strtree) end   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.
#EchoLisp
EchoLisp
  (require 'hash) (string-delimiter "")   (define (^ a b ) (expt a b)) ;; add this not-native function (define-syntax-rule (r-assoc? op) (= op "^")) (define-syntax-rule (l-assoc? op) (not ( = op "^" ))) (define PRECEDENCES (list->hash '(("+" . 2) ("-" . 2) ("*" . 3) ("/" . 3) ("//" . 3) ("^" . 4)) (make-hash)))   ;; RPN vector or list -> infix tree -> (a op (b op c) d) .. (define (rpn->infix rpn) (define S (stack 'S)) (for ((token rpn)) (if (procedure? token) (let [(op2 (pop S)) (op1 (pop S))] (unless (and op1 op2) (error "cannot translate expression" rpn)) (push S (list op1 token op2)) ) (push S token )) (writeln 'token (string token) 'stack (stack->list S))) (begin0 (pop S) ;; return (top S) (unless (stack-empty? S) (error "ill-formed rpn" rpn))) )   ;; a node tree is (left op right) or a number (define-syntax-id _.left (first _)) ; mynode.left expands to (first mynode) (define-syntax-id _.right (third _)) (define-syntax-id _.op (string (second _ ))) (define-syntax-rule (precedence node) (hash-ref PRECEDENCES (string (second node))))   (define (left-par? node) ; does lhs needs ( lhs ) ? (cond [(number? node.left) #f] [(< (precedence node.left) (precedence node)) #t] [(and (r-assoc? node.op) (= (precedence node.left) (precedence node))) #t] [else #f]))   (define (right-par? node) (cond [(number? node.right) #f] [(< (precedence node.right) (precedence node)) #t] [(and (l-assoc? node.op) (= (precedence node.right) (precedence node))) #t] [else #f]))   ;; infix tree -> char string (define (infix->string node) (cond [(number? node) (string node)] [else (let [(lhs (infix->string node.left)) (rhs (infix->string node.right))] (when (left-par? node) (set! lhs (string-append "(" lhs ")"))) (when (right-par? node) (set! rhs (string-append "(" rhs ")"))) (string-append lhs " " node.op " " rhs))]))  
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.
#Groovy
Groovy
def fs = { fn, values -> values.collect { fn(it) } } def f1 = { v -> v * 2 } def f2 = { v -> v ** 2 } def fsf1 = fs.curry(f1) def fsf2 = fs.curry(f2)
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.
#Haskell
Haskell
fs = map f1 = (* 2) f2 = (^ 2)   fsf1 = fs f1 fsf2 = fs f2   main :: IO () main = do print $ fsf1 [0, 1, 2, 3] -- prints [0, 2, 4, 6] print $ fsf2 [0, 1, 2, 3] -- prints [0, 1, 4, 9] print $ fsf1 [2, 4, 6, 8] -- prints [4, 8, 12, 16] print $ fsf2 [2, 4, 6, 8] -- prints [4, 16, 36, 64]
http://rosettacode.org/wiki/Partition_an_integer_x_into_n_primes
Partition an integer x into n primes
Task Partition a positive integer   X   into   N   distinct primes. Or, to put it in another way: Find   N   unique primes such that they add up to   X. Show in the output section the sum   X   and the   N   primes in ascending order separated by plus (+) signs: •   partition 99809 with 1 prime. •   partition 18 with 2 primes. •   partition 19 with 3 primes. •   partition 20 with 4 primes. •   partition 2017 with 24 primes. •   partition 22699 with 1, 2, 3, and 4 primes. •   partition 40355 with 3 primes. The output could/should be shown in a format such as: Partitioned 19 with 3 primes: 3+5+11   Use any spacing that may be appropriate for the display.   You need not validate the input(s).   Use the lowest primes possible;   use  18 = 5+13,   not   18 = 7+11.   You only need to show one solution. This task is similar to factoring an integer. Related tasks   Count in factors   Prime decomposition   Factors of an integer   Sieve of Eratosthenes   Primality by trial division   Factors of a Mersenne number   Factors of a Mersenne number   Sequence of primes by trial division
#Prolog
Prolog
prime_partition(N, 1, [N], Min):- is_prime(N), N > Min, !. prime_partition(N, K, [P|Rest], Min):- K > 1, is_prime(P), P > Min, P < N, K1 is K - 1, N1 is N - P, prime_partition(N1, K1, Rest, P), !.   prime_partition(N, K, Primes):- prime_partition(N, K, Primes, 1).   print_primes([Prime]):- !, writef('%w\n', [Prime]). print_primes([Prime|Primes]):- writef('%w + ', [Prime]), print_primes(Primes).   print_prime_partition(N, K):- prime_partition(N, K, Primes), !, writef('%w = ', [N]), print_primes(Primes). print_prime_partition(N, K):- writef('%w cannot be partitioned into %w primes.\n', [N, K]).   main:- find_prime_numbers(100000), print_prime_partition(99809, 1), print_prime_partition(18, 2), print_prime_partition(19, 3), print_prime_partition(20, 4), print_prime_partition(2017, 24), print_prime_partition(22699, 1), print_prime_partition(22699, 2), print_prime_partition(22699, 3), print_prime_partition(22699, 4), print_prime_partition(40355, 3).
http://rosettacode.org/wiki/Partition_function_P
Partition function P
The Partition Function P, often notated P(n) is the number of solutions where n∈ℤ can be expressed as the sum of a set of positive integers. Example P(4) = 5 because 4 = Σ(4) = Σ(3,1) = Σ(2,2) = Σ(2,1,1) = Σ(1,1,1,1) P(n) can be expressed as the recurrence relation: P(n) = P(n-1) +P(n-2) -P(n-5) -P(n-7) +P(n-12) +P(n-15) -P(n-22) -P(n-26) +P(n-35) +P(n-40) ... The successive numbers in the above equation have the differences:   1, 3, 2, 5, 3, 7, 4, 9, 5, 11, 6, 13, 7, 15, 8 ... This task may be of popular interest because Mathologer made the video, The hardest "What comes next?" (Euler's pentagonal formula), where he asks the programmers among his viewers to calculate P(666). The video has been viewed more than 100,000 times in the first couple of weeks since its release. In Wolfram Language, this function has been implemented as PartitionsP. Task Write a function which returns the value of PartitionsP(n). Solutions can be iterative or recursive. Bonus task: show how long it takes to compute PartitionsP(6666). References The hardest "What comes next?" (Euler's pentagonal formula) The explanatory video by Mathologer that makes this task a popular interest. Partition Function P Mathworld entry for the Partition function. Partition function (number theory) Wikipedia entry for the Partition function. Related tasks 9 billion names of God the integer
#Wren
Wren
import "/big" for BigInt   var p = [] var pd = []   var partDiffDiff = Fn.new { |n| (n&1 == 1) ? (n + 1)/2 : n + 1 }   var partDiff = Fn.new { |n| if (n < 2) return 1 pd[n] = pd[n-1] + partDiffDiff.call(n-1) return pd[n] }   var partitionsP = Fn.new { |n| if (n < 2) return var psum = BigInt.zero for (i in 1..n) { var pdi = partDiff.call(i) if (pdi > n) break var sign = (i-1)%4 < 2 ? 1 : -1 psum = psum + p[n-pdi] * sign } p[n] = psum }   var start = System.clock var N = 6666 p = List.filled(N+1, null) pd = List.filled(N+1, 0) p[0] = BigInt.one p[1] = BigInt.one pd[0] = 1 pd[1] = 1 for (n in 2..N) partitionsP.call(n) System.print("p[%(N)] = %(p[N])") System.print("Took %(System.clock - start) seconds")
http://rosettacode.org/wiki/Pascal%27s_triangle/Puzzle
Pascal's triangle/Puzzle
This puzzle involves a Pascals Triangle, also known as a Pyramid of Numbers. [ 151] [ ][ ] [40][ ][ ] [ ][ ][ ][ ] [ X][11][ Y][ 4][ Z] Each brick of the pyramid is the sum of the two bricks situated below it. Of the three missing numbers at the base of the pyramid, the middle one is the sum of the other two (that is, Y = X + Z). Task Write a program to find a solution to this puzzle.
#Picat
Picat
import cp.   go => puzzle(T, X, Y,Z), foreach(TT in T) println(TT) end, println([x=X,y=Y,z=Z]), nl, fail, % are there any more solutions? nl.   % Port of the Prolog solution puzzle(Ts, X, Y, Z) :- Ts = [ [151], [_, _], [40, _, _], [_, _, _, _], [X, 11, Y, 4, Z]], Y #= X + Z, triangle(Ts), Vs = vars(Ts), Vs :: 0..10000, solve(Vs).   triangle([T|Ts]) :- ( Ts = [N|_] -> triangle_(T, N), triangle(Ts) ; true ).   triangle_([], _). triangle_([T|Ts],[A,B|Rest]) :- T #= A + B, triangle_(Ts, [B|Rest]).
http://rosettacode.org/wiki/Pascal%27s_triangle/Puzzle
Pascal's triangle/Puzzle
This puzzle involves a Pascals Triangle, also known as a Pyramid of Numbers. [ 151] [ ][ ] [40][ ][ ] [ ][ ][ ][ ] [ X][11][ Y][ 4][ Z] Each brick of the pyramid is the sum of the two bricks situated below it. Of the three missing numbers at the base of the pyramid, the middle one is the sum of the other two (that is, Y = X + Z). Task Write a program to find a solution to this puzzle.
#PicoLisp
PicoLisp
(be number (@N @Max) (^ @C (box 0)) (repeat) (or ((^ @ (>= (val (-> @C)) (-> @Max))) T (fail)) ((^ @N (inc (-> @C)))) ) )   (be + (@A @B @Sum) (^ @ (-> @A)) (^ @ (-> @B)) (^ @Sum (+ (-> @A) (-> @B))) )   (be + (@A @B @Sum) (^ @ (-> @A)) (^ @ (-> @Sum)) (^ @B (- (-> @Sum) (-> @A))) T (^ @ (ge0 (-> @B))) )   (be + (@A @B @Sum) (number @A @Sum) (^ @B (- (-> @Sum) (-> @A))) )   #{ 151 A B 40 C D E F G H X 11 Y 4 Z }#   (be puzzle (@X @Y @Z) (+ @A @B 151) (+ 40 @C @A) (+ @C @D @B) (+ @E @F 40) (+ @F @G @C) (+ @G @H @D) (+ @X 11 @E) (+ 11 @Y @F) (+ @Y 4 @G) (+ 4 @Z @H) (+ @X @Z @Y) T )
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
#Lua
Lua
function randPW (length) local index, pw, rnd = 0, "" local chars = { "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz", "0123456789", "!\"#$%&'()*+,-./:;<=>?@[]^_{|}~" } repeat index = index + 1 rnd = math.random(chars[index]:len()) if math.random(2) == 1 then pw = pw .. chars[index]:sub(rnd, rnd) else pw = chars[index]:sub(rnd, rnd) .. pw end index = index % #chars until pw:len() >= length return pw end   math.randomseed(os.time()) if #arg ~= 2 then print("\npwgen.lua") print("=========\n") print("A Lua script to generate random passwords.\n") print("Usage: lua pwgen.lua [password length] [number of passwords to generate]\n") os.exit() end for i = 1, arg[2] do print(randPW(tonumber(arg[1]))) end
http://rosettacode.org/wiki/Permutations
Permutations
Task Write a program that generates all   permutations   of   n   different objects.   (Practically numerals!) Related tasks   Find the missing permutation   Permutations/Derangements The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Unimportant Order Important Without replacement ( n k ) = n C k = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} Task: Combinations Task: Permutations With replacement ( n + k − 1 k ) = n + k − 1 C k = ( n + k − 1 ) ! ( n − 1 ) ! k ! {\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}} n k {\displaystyle n^{k}} Task: Combinations with repetitions Task: Permutations with repetitions
#True_BASIC
True BASIC
SUB SWAP(vb1, vb2) LET temp = vb1 LET vb1 = vb2 LET vb2 = temp END SUB   LET n = 4 DIM a(4) DIM c(4)   FOR i = 1 TO n LET a(i) = i NEXT i PRINT   DO FOR i = 1 TO n PRINT a(i); NEXT i PRINT LET i = n DO LET i = i - 1 LOOP UNTIL (i = 0) OR (a(i) < a(i + 1)) LET j = i + 1 LET k = n DO WHILE j < k CALL SWAP (a(j), a(k)) LET j = j + 1 LET k = k - 1 LOOP IF i > 0 THEN LET j = i + 1 DO WHILE a(j) < a(i) LET j = j + 1 LOOP CALL SWAP (a(i), a(j)) END IF LOOP UNTIL i = 0 END
http://rosettacode.org/wiki/Penney%27s_game
Penney's game
Penney's game is a game where two players bet on being the first to see a particular sequence of heads or tails in consecutive tosses of a fair coin. It is common to agree on a sequence length of three then one player will openly choose a sequence, for example: Heads, Tails, Heads, or HTH for short. The other player on seeing the first players choice will choose his sequence. The coin is tossed and the first player to see his sequence in the sequence of coin tosses wins. Example One player might choose the sequence HHT and the other THT. Successive coin tosses of HTTHT gives the win to the second player as the last three coin tosses are his sequence. Task Create a program that tosses the coin, keeps score and plays Penney's game against a human opponent. Who chooses and shows their sequence of three should be chosen randomly. If going first, the computer should randomly choose its sequence of three. If going second, the computer should automatically play the optimum sequence. Successive coin tosses should be shown. Show output of a game where the computer chooses first and a game where the user goes first here on this page. See also The Penney Ante Part 1 (Video). The Penney Ante Part 2 (Video).
#zkl
zkl
fcn coinToss{ (0).random(2) and "H" or "T" } // (0).random(2) --> 0<=r<2 reg myBet, yourBet; if(coinToss()=="H"){ // The toss says I go first myBet=(3).pump(String,coinToss); println("I bet ",myBet); yourBet=ask("Your bet of three (H/T): ")[0,3].toUpper(); }else{ yourBet=ask("Your bet of three (H/T): ")[0,3].toUpper(); myBet=((yourBet[1]=="H") and "T" or "H") + yourBet[0,2]; println("I bet ",myBet); } print("Flipping: "); coins:=""; while(1){ print(toss:=coinToss()); coins=coins + toss; if(Void!=coins.find(yourBet)){ println(" You win!"); break; } if(Void!=coins.find(myBet)) { println(" I win!"); break; } // ignore we both won }
http://rosettacode.org/wiki/Pathological_floating_point_problems
Pathological floating point problems
Most programmers are familiar with the inexactness of floating point calculations in a binary processor. The classic example being: 0.1 + 0.2 = 0.30000000000000004 In many situations the amount of error in such calculations is very small and can be overlooked or eliminated with rounding. There are pathological problems however, where seemingly simple, straight-forward calculations are extremely sensitive to even tiny amounts of imprecision. This task's purpose is to show how your language deals with such classes of problems. A sequence that seems to converge to a wrong limit. Consider the sequence: v1 = 2 v2 = -4 vn = 111   -   1130   /   vn-1   +   3000  /   (vn-1 * vn-2) As   n   grows larger, the series should converge to   6   but small amounts of error will cause it to approach   100. Task 1 Display the values of the sequence where   n =   3, 4, 5, 6, 7, 8, 20, 30, 50 & 100   to at least 16 decimal places. n = 3 18.5 n = 4 9.378378 n = 5 7.801153 n = 6 7.154414 n = 7 6.806785 n = 8 6.5926328 n = 20 6.0435521101892689 n = 30 6.006786093031205758530554 n = 50 6.0001758466271871889456140207471954695237 n = 100 6.000000019319477929104086803403585715024350675436952458072592750856521767230266 Task 2 The Chaotic Bank Society   is offering a new investment account to their customers. You first deposit   $e - 1   where   e   is   2.7182818...   the base of natural logarithms. After each year, your account balance will be multiplied by the number of years that have passed, and $1 in service charges will be removed. So ... after 1 year, your balance will be multiplied by 1 and $1 will be removed for service charges. after 2 years your balance will be doubled and $1 removed. after 3 years your balance will be tripled and $1 removed. ... after 10 years, multiplied by 10 and $1 removed, and so on. What will your balance be after   25   years? Starting balance: $e-1 Balance = (Balance * year) - 1 for 25 years Balance after 25 years: $0.0399387296732302 Task 3, extra credit Siegfried Rump's example.   Consider the following function, designed by Siegfried Rump in 1988. f(a,b) = 333.75b6 + a2( 11a2b2 - b6 - 121b4 - 2 ) + 5.5b8 + a/(2b) compute   f(a,b)   where   a=77617.0   and   b=33096.0 f(77617.0, 33096.0)   =   -0.827396059946821 Demonstrate how to solve at least one of the first two problems, or both, and the third if you're feeling particularly jaunty. See also;   Floating-Point Arithmetic   Section 1.3.2 Difficult problems.
#Sidef
Sidef
func series (n) { var (u, v) = (2, -4) (n-2).times { (u, v) = (v, 111 - 1130/v + 3000/(v * u)) } return v }   [(3..8)..., 20, 30, 50, 100].each {|n| printf("n = %3d -> %s\n", n, series(n)) }
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
#Common_Lisp
Common Lisp
(defpackage #:parallel-brute-force (:use #:cl #:lparallel))   (in-package #:parallel-brute-force)   (defparameter *alphabet* "abcdefghijklmnopqrstuvwxyz") (defparameter *hash0* "1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad") (defparameter *hash1* "3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b") (defparameter *hash2* "74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f") (defparameter *kernel-size* 7)   (defun sha-256 (input) (ironclad:byte-array-to-hex-string (ironclad:digest-sequence :sha256 (ironclad:ascii-string-to-byte-array input))))   (defun call-with-5-char-string (fun first-char) (loop with str = (make-array 5 :element-type 'character :initial-element first-char) for c1 across *alphabet* do (setf (char str 1) c1) (loop for c2 across *alphabet* do (setf (char str 2) c2) (loop for c3 across *alphabet* do (setf (char str 3) c3) (loop for c4 across *alphabet* do (setf (char str 4) c4) (funcall fun (copy-seq str)))))))   (defmacro with-5-char-string ((str first-char) &body body) `(call-with-5-char-string (lambda (,str) ,@body) ,first-char))   (defun find-passwords-with (first-char) (let (results) (with-5-char-string (str first-char) (let ((hash (sha-256 str))) (when (or (string= hash *hash0*) (string= hash *hash1*) (string= hash *hash2*)) (push (list str hash) results)))) (nreverse results)))   (defun find-passwords () (setf *kernel* (make-kernel *kernel-size*)) (let ((results (unwind-protect (pmapcan #'find-passwords-with *alphabet*) (end-kernel)))) (dolist (r results) (format t "~A: ~A~%" (first r) (second r)))))
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.
#Delphi
Delphi
  program Parallel_calculations;   {$APPTYPE CONSOLE}   uses System.SysUtils, System.Threading, Velthuis.BigIntegers;   function IsPrime(n: BigInteger): Boolean; var i: BigInteger; begin if n <= 1 then exit(False);   i := 2; while i < BigInteger.Sqrt(n) do begin if n mod i = 0 then exit(False); inc(i); end;   Result := True; end;   function GetPrimes(n: BigInteger): TArray<BigInteger>; var divisor, next, rest: BigInteger; begin divisor := 2; next := 3; rest := n; while (rest <> 1) do begin while (rest mod divisor = 0) do begin SetLength(Result, Length(Result) + 1); Result[High(Result)] := divisor; rest := rest div divisor; end; divisor := next; next := next + 2; end; end;   function Min(l: TArray<BigInteger>): BigInteger; begin if Length(l) = 0 then exit(0);   Result := l[0]; for var v in l do if v < result then Result := v; end;   const n: array of Uint64 = [12757923, 12878611, 12757923, 15808973, 15780709, 197622519];   var m: BigInteger; len, j, i: Uint64; l: TArray<TArray<BigInteger>>;   begin j := 0; m := 0; len := length(n); SetLength(l, len);   TParallel.for (0, len - 1, procedure(i: Integer) begin l[i] := getPrimes(n[i]); end);   for i := 0 to len - 1 do begin var _min := Min(l[i]); if _min > m then begin m := _min; j := i; end; end;   writeln('Number ', n[j].ToString, ' has largest minimal factor:'); for var v in l[j] do write(' ', v.ToString);   readln; 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.
#C
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h>   void die(const char *msg) { fprintf(stderr, "%s", msg); abort(); }   #define MAX_D 256 double stack[MAX_D]; int depth;   void push(double v) { if (depth >= MAX_D) die("stack overflow\n"); stack[depth++] = v; }   double pop() { if (!depth) die("stack underflow\n"); return stack[--depth]; }   double rpn(char *s) { double a, b; int i; char *e, *w = " \t\n\r\f";   for (s = strtok(s, w); s; s = strtok(0, w)) { a = strtod(s, &e); if (e > s) printf(" :"), push(a); #define binop(x) printf("%c:", *s), b = pop(), a = pop(), push(x) else if (*s == '+') binop(a + b); else if (*s == '-') binop(a - b); else if (*s == '*') binop(a * b); else if (*s == '/') binop(a / b); else if (*s == '^') binop(pow(a, b)); #undef binop else { fprintf(stderr, "'%c': ", *s); die("unknown oeprator\n"); } for (i = depth; i-- || 0 * putchar('\n'); ) printf(" %g", stack[i]); }   if (depth != 1) die("stack leftover\n");   return pop(); }   int main(void) { char s[] = " 3 4 2 * 1 5 - 2 3 ^ ^ / + "; printf("%g\n", rpn(s)); return 0; }
http://rosettacode.org/wiki/Pancake_numbers
Pancake numbers
Adrian Monk has problems and an assistant, Sharona Fleming. Sharona can deal with most of Adrian's problems except his lack of punctuality paying her remuneration. 2 pay checks down and she prepares him pancakes for breakfast. Knowing that he will be unable to eat them unless they are stacked in ascending order of size she leaves him only a skillet which he can insert at any point in the pile and flip all the above pancakes, repeating until the pile is sorted. Sharona has left the pile of n pancakes such that the maximum number of flips is required. Adrian is determined to do this in as few flips as possible. This sequence n->p(n) is known as the Pancake numbers. The task is to determine p(n) for n = 1 to 9, and for each show an example requiring p(n) flips. Sorting_algorithms/Pancake_sort actually performs the sort some giving the number of flips used. How do these compare with p(n)? Few people know p(20), generously I shall award an extra credit for anyone doing more than p(16). References Bill Gates and the pancake problem A058986
#F.23
F#
  // Pancake numbers. Nigel Galloway: October 28th., 2020 let pKake z=let n=[for n in 1..z-1->Array.ofList([n.. -1..0]@[n+1..z-1])] let e=let rec fG n g=match g with 0->n |_->fG (n*g) (g-1) in fG 1 z let rec fN i g l=match (Set.count g)-e with 0->(i,List.last l) |_->let l=l|>List.collect(fun g->[for n in n->List.permute(fun g->n.[g]) g])|>Set.ofList fN (i+1) (Set.union g l) (Set.difference l g|>Set.toList) fN 0 (set[[1..z]]) [[1..z]]   [1..9]|>List.iter(fun n->let i,g=pKake n in printfn "Maximum number of flips to sort %d elements is %d. e.g %A->%A" n i g [1..n])  
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.
#EchoLisp
EchoLisp
  (require 'hash) (require 'tree)   (define OPS (make-hash)) (hash-set OPS "^" '( 4 #f)) ;; right assoc (hash-set OPS "*" '( 3 #t)) ;; left assoc (hash-set OPS "/" '( 3 #t)) (hash-set OPS "+" '( 2 #t)) (hash-set OPS "-" '( 2 #t))   ;; helpers (define (is-right-par? token) (string=? token ")")) (define (is-left-par? token) (string=? token "(")) (define (is-num? op) (not (hash-ref OPS op))) ;; crude (define (is-op? op) (hash-ref OPS op)) (define (is-left? op) (second (hash-ref OPS op))) (define (is-right? op) (not (is-left? op))) (define (op-prec op) (first (hash-ref OPS op)))   ;; Wikipedia algorithm, translated as it is   (define (shunt tokens S Q) (for ((token tokens)) (writeln "S: " (stack->list S) "Q: " (queue->list Q) "token: "token) (cond [(is-left-par? token) (push S token) ] [(is-right-par? token) (while (and (stack-top S) (not (is-left-par? (stack-top S)))) (q-push Q ( pop S))) (when (stack-empty? S) (error 'misplaced-parenthesis "()" )) (pop S)] ; // left par   [(is-op? token) (while (and (is-op? (stack-top S)) (or (and (is-left? token) (<= (op-prec token) (op-prec (stack-top S)))) (and (is-right? token) (< (op-prec token) (op-prec (stack-top S)))))) (q-push Q (pop S))) (push S token)]   [(is-num? token) (q-push Q token)] [else (error 'bad-token token)])) ; for (while (stack-top S) (q-push Q (pop S))))   (string-delimiter "") (define (task infix) (define S (stack 'S)) (define Q (queue 'Q)) (shunt (text-parse infix) S Q) (writeln 'infix infix) (writeln 'RPN (queue->list Q)))  
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
#D
D
import std.stdio, std.bigint;   enum uint nMax = 250; enum uint nBranches = 4;   __gshared BigInt[nMax + 1] rooted = [1.BigInt, 1.BigInt /*...*/], unrooted = [1.BigInt, 1.BigInt /*...*/];   void tree(in uint br, in uint n, in uint l, in uint inSum, in BigInt cnt) nothrow { __gshared static BigInt[nBranches] c;   uint sum = inSum; foreach (immutable b; br + 1 .. nBranches + 1) { sum += n; if (sum > nMax || (l * 2 >= sum && b >= nBranches)) return; if (b == br + 1) { c[br] = rooted[n] * cnt; } else { c[br] *= rooted[n] + b - br - 1; c[br] /= b - br; } if (l * 2 < sum) unrooted[sum] += c[br]; if (b < nBranches) rooted[sum] += c[br]; foreach_reverse (immutable m; 1 .. n) tree(b, m, l, sum, c[br]); } }   void bicenter(in uint s) nothrow { if ((s & 1) == 0) unrooted[s] += rooted[s / 2] * (rooted[s / 2] + 1) / 2; }   void main() { foreach (immutable n; 1 .. nMax + 1) { tree(0, n, n, 1, 1.BigInt); n.bicenter; writeln(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
#Action.21
Action!
INCLUDE "D2:CHARTEST.ACT" ;from the Action! Tool Kit   DEFINE CHAR_COUNT="26"   BYTE FUNC IsPangram(CHAR ARRAY t) BYTE ARRAY tab(CHAR_COUNT) BYTE i,c   FOR i=0 TO CHAR_COUNT-1 DO tab(i)=0 OD   FOR i=1 TO t(0) DO c=ToLower(t(i)) IF c>='a AND c<='z THEN tab(c-'a)=1 FI OD   FOR i=0 TO CHAR_COUNT-1 DO IF tab(i)=0 THEN RETURN (0) FI OD RETURN (1)   PROC Test(CHAR ARRAY t) BYTE res   res=IsPangram(t) PrintF("""%S"" is ",t) IF res=0 THEN Print("not ") FI PrintE("a pangram.") PutE() RETURN   PROC Main() Put(125) PutE() ;clear screen Test("The quick brown fox jumps over the lazy dog.") Test("QwErTyUiOpAsDfGhJkLzXcVbNm") Test("Not a pangram") Test("") RETURN
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
#ActionScript
ActionScript
function pangram(k:string):Boolean { var lowerK:String = k.toLowerCase(); var has:Object = {}   for (var i:Number=0; i<=k.length-1; i++) { has[lowerK.charAt(i)] = true; }   var result:Boolean = true;   for (var ch:String='a'; ch <= 'z'; ch=String.fromCharCode(ch.charCodeAt(0)+1)) { result = result && has[ch] }   return result || false; }
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.
#Common_Lisp
Common Lisp
(defun pascal-lower (n &aux (a (make-array (list n n) :initial-element 0))) (dotimes (i n) (setf (aref a i 0) 1)) (dotimes (i (1- n) a) (dotimes (j (1- n)) (setf (aref a (1+ i) (1+ j)) (+ (aref a i j) (aref a i (1+ j)))))))   (defun pascal-upper (n &aux (a (make-array (list n n) :initial-element 0))) (dotimes (i n) (setf (aref a 0 i) 1)) (dotimes (i (1- n) a) (dotimes (j (1- n)) (setf (aref a (1+ j) (1+ i)) (+ (aref a j i) (aref a (1+ j) i))))))   (defun pascal-symmetric (n &aux (a (make-array (list n n) :initial-element 0))) (dotimes (i n) (setf (aref a i 0) 1 (aref a 0 i) 1)) (dotimes (i (1- n) a) (dotimes (j (1- n)) (setf (aref a (1+ i) (1+ j)) (+ (aref a (1+ i) j) (aref a i (1+ j)))))))   ? (pascal-lower 4) #2A((1 0 0 0) (1 1 0 0) (1 2 1 0) (1 3 3 1)) ? (pascal-upper 4) #2A((1 1 1 1) (0 1 2 3) (0 0 1 3) (0 0 0 1)) ? (pascal-symmetric 4) #2A((1 1 1 1) (1 2 3 4) (1 3 6 10) (1 4 10 20))   ;In case one really insists in printing the array row by row:   (defun print-matrix (a) (let ((p (array-dimension a 0)) (q (array-dimension a 1))) (dotimes (i p) (dotimes (j q) (princ (aref a i j)) (princ #\Space)) (terpri))))   ? (print-matrix (pascal-lower 5)) 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   ? (print-matrix (pascal-upper 5)) 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   ? (print-matrix (pascal-symmetric 5)) 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
http://rosettacode.org/wiki/Parameterized_SQL_statement
Parameterized SQL statement
SQL injection Using a SQL update statement like this one (spacing is optional): UPDATE players SET name = 'Smith, Steve', score = 42, active = TRUE WHERE jerseyNum = 99 Non-parameterized SQL is the GoTo statement of database programming. Don't do it, and make sure your coworkers don't either.
#Huginn
Huginn
import Database as db; import Algorithms as algo; import FileSystem as fs;   main() { dbPath = "/tmp/parametrized-sql.sqlite"; fs.remove( dbPath ); fs.open( dbPath, fs.OPEN_MODE.WRITE ); conn = db.connect( "sqlite3:///" + dbPath );   // Setup... conn.query( "CREATE TABLE Players (\n" "\tname VARCHAR(64),\n" "\tscore FLOAT,\n" "\tactive INTEGER,\n" "\tno VARCHAR(8)\n" ");" ).execute(); conn.query( "INSERT INTO Players VALUES ( 'name', 0, 'false', 99 );" ).execute(); conn.query( "INSERT INTO Players VALUES ( 'name', 0, 'false', 100 );" ).execute();   // Demonstrate parameterized SQL... parametrizedQuery = conn.query( "UPDATE Players SET name=?, score=?, active=? WHERE no=?" ); for ( i, v : algo.enumerate( ( "Smith, Steve", 42, true, 99 ) ) ) { parametrizedQuery.bind( i + 1, string( v ) ); } parametrizedQuery.execute();   // and show the results... for ( record : conn.query( "SELECT * FROM Players;" ).execute() ) { print( "{}\n".format( record ) ); } return ( 0 ); }
http://rosettacode.org/wiki/Parameterized_SQL_statement
Parameterized SQL statement
SQL injection Using a SQL update statement like this one (spacing is optional): UPDATE players SET name = 'Smith, Steve', score = 42, active = TRUE WHERE jerseyNum = 99 Non-parameterized SQL is the GoTo statement of database programming. Don't do it, and make sure your coworkers don't either.
#Java
Java
  import java.sql.DriverManager; import java.sql.Connection; import java.sql.PreparedStatement;   public class DBDemo{ private String protocol; //set this to some connection protocol like "jdbc:sqlserver://" private String dbName; //set this to the name of your database private String username; private String password;   PreparedStatement query;   public int setUpAndExecPS(){ try { Connection conn = DriverManager.getConnection(protocol + dbName, username, password);   query = conn.prepareStatement( "UPDATE players SET name = ?, score = ?, active = ? WHERE jerseyNum = ?");   query.setString(1, "Smith, Steve");//automatically sanitizes and adds quotes query.setInt(2, 42); query.setBoolean(3, true); query.setInt(4, 99); //there are similar methods for other SQL types in PerparedStatement return query.executeUpdate();//returns the number of rows changed //PreparedStatement.executeQuery() will return a java.sql.ResultSet, //execute() will simply return a boolean saying whether it succeeded or not   } catch (Exception e) { e.printStackTrace(); }   return 0; } }  
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
#BCPL
BCPL
get "libhdr"   let pascal(n) be for i=0 to n-1 $( let c = 1 for j=1 to 2*(n-1-i) do wrch(' ') for k=0 to i $( writef("%I3 ",c) c := c*(i-k)/(k+1) $) wrch('*N') $)   let start() be pascal(8)
http://rosettacode.org/wiki/Parse_an_IP_Address
Parse an IP Address
The purpose of this task is to demonstrate parsing of text-format IP addresses, using IPv4 and IPv6. Taking the following as inputs: 127.0.0.1 The "localhost" IPv4 address 127.0.0.1:80 The "localhost" IPv4 address, with a specified port (80) ::1 The "localhost" IPv6 address [::1]:80 The "localhost" IPv6 address, with a specified port (80) 2605:2700:0:3::4713:93e3 Rosetta Code's primary server's public IPv6 address [2605:2700:0:3::4713:93e3]:80 Rosetta Code's primary server's public IPv6 address, with a specified port (80) Task Emit each described IP address as a hexadecimal integer representing the address, the address space, and the port number specified, if any. In languages where variant result types are clumsy, the result should be ipv4 or ipv6 address number, something which says which address space was represented, port number and something that says if the port was specified. Example 127.0.0.1   has the address number   7F000001   (2130706433 decimal) in the ipv4 address space. ::ffff:127.0.0.1   represents the same address in the ipv6 address space where it has the address number   FFFF7F000001   (281472812449793 decimal). ::1   has address number   1   and serves the same purpose in the ipv6 address space that   127.0.0.1   serves in the ipv4 address space.
#Julia
Julia
  const testdata = ["127.0.0.1", "127.0.0.1:80", "::1", "[::1]:80", "2605:2700:0:3::4713:93e3", "[2605:2700:0:3::4713:93e3]:80", "::ffff:192.168.173.22", "[::ffff:192.168.173.22]:80", "1::", "[1::]:80", "::", "[::]:80"]   maybev4(ip) = search(ip, '.') > 0 && length(matchall(r":", ip)) < 2 maybev6(ip) = length(matchall(r":", ip)) > 1   function parseip(ip) if (mat = match(r"^\[([:.\da-fA-F]+)\]:(\d+)$", ip))!= nothing || (mat = match(r"^([\d.]+)[:/](\d+)$", ip)) != nothing port = mat.captures[2] ip = mat.captures[1] else port = "none" end if maybev4(ip) println("Processing ip v4 $ip") iphex = hex(Int(Base.IPv4(ip))) addresspace = "IPv4" elseif maybev6(ip) println("Processing ip v6 $ip") iphex = hex(UInt128(Base.IPv6(ip))) addresspace = "IPv6" else throw("Bad IP address argument $ip") end iphex, addresspace, port end   for ip in testdata hx, add, por = parseip(ip) println("For input $ip, IP in hex is $hx, address space $add, port $por.") end  
http://rosettacode.org/wiki/Parse_an_IP_Address
Parse an IP Address
The purpose of this task is to demonstrate parsing of text-format IP addresses, using IPv4 and IPv6. Taking the following as inputs: 127.0.0.1 The "localhost" IPv4 address 127.0.0.1:80 The "localhost" IPv4 address, with a specified port (80) ::1 The "localhost" IPv6 address [::1]:80 The "localhost" IPv6 address, with a specified port (80) 2605:2700:0:3::4713:93e3 Rosetta Code's primary server's public IPv6 address [2605:2700:0:3::4713:93e3]:80 Rosetta Code's primary server's public IPv6 address, with a specified port (80) Task Emit each described IP address as a hexadecimal integer representing the address, the address space, and the port number specified, if any. In languages where variant result types are clumsy, the result should be ipv4 or ipv6 address number, something which says which address space was represented, port number and something that says if the port was specified. Example 127.0.0.1   has the address number   7F000001   (2130706433 decimal) in the ipv4 address space. ::ffff:127.0.0.1   represents the same address in the ipv6 address space where it has the address number   FFFF7F000001   (281472812449793 decimal). ::1   has address number   1   and serves the same purpose in the ipv6 address space that   127.0.0.1   serves in the ipv4 address space.
#Kotlin
Kotlin
// version 1.1.3   import java.math.BigInteger   enum class AddressSpace { IPv4, IPv6, Invalid }   data class IPAddressComponents( val address: BigInteger, val addressSpace: AddressSpace, val port: Int // -1 denotes 'not specified' )   val INVALID = IPAddressComponents(BigInteger.ZERO, AddressSpace.Invalid, 0)   fun ipAddressParse(ipAddress: String): IPAddressComponents { var addressSpace = AddressSpace.IPv4 var ipa = ipAddress.toLowerCase() var port = -1 var trans = false   if (ipa.startsWith("::ffff:") && '.' in ipa) { addressSpace = AddressSpace.IPv6 trans = true ipa = ipa.drop(7) } else if (ipa.startsWith("[::ffff:") && '.' in ipa) { addressSpace = AddressSpace.IPv6 trans = true ipa = ipa.drop(8).replace("]", "") } val octets = ipa.split('.').reversed().toTypedArray() var address = BigInteger.ZERO if (octets.size == 4) { val split = octets[0].split(':') if (split.size == 2) { val temp = split[1].toIntOrNull() if (temp == null || temp !in 0..65535) return INVALID port = temp octets[0] = split[0] }   for (i in 0..3) { val num = octets[i].toLongOrNull() if (num == null || num !in 0..255) return INVALID val bigNum = BigInteger.valueOf(num) address = address.or(bigNum.shiftLeft(i * 8)) }   if (trans) address += BigInteger("ffff00000000", 16) } else if (octets.size == 1) { addressSpace = AddressSpace.IPv6 if (ipa[0] == '[') { ipa = ipa.drop(1) val split = ipa.split("]:") if (split.size != 2) return INVALID val temp = split[1].toIntOrNull() if (temp == null || temp !in 0..65535) return INVALID port = temp ipa = ipa.dropLast(2 + split[1].length) } val hextets = ipa.split(':').reversed().toMutableList() val len = hextets.size   if (ipa.startsWith("::")) hextets[len - 1] = "0" else if (ipa.endsWith("::")) hextets[0] = "0"   if (ipa == "::") hextets[1] = "0" if (len > 8 || (len == 8 && hextets.any { it == "" }) || hextets.count { it == "" } > 1) return INVALID if (len < 8) { var insertions = 8 - len for (i in 0..7) { if (hextets[i] == "") { hextets[i] = "0" while (insertions-- > 0) hextets.add(i, "0") break } } } for (j in 0..7) { val num = hextets[j].toLongOrNull(16) if (num == null || num !in 0x0..0xFFFF) return INVALID val bigNum = BigInteger.valueOf(num) address = address.or(bigNum.shiftLeft(j * 16)) } } else return INVALID   return IPAddressComponents(address, addressSpace, port) }   fun main(args: Array<String>) { val ipas = listOf( "127.0.0.1", "127.0.0.1:80", "::1", "[::1]:80", "2605:2700:0:3::4713:93e3", "[2605:2700:0:3::4713:93e3]:80", "::ffff:192.168.173.22", "[::ffff:192.168.173.22]:80", "1::", "::", "256.0.0.0", "::ffff:127.0.0.0.1" ) for (ipa in ipas) { val (address, addressSpace, port) = ipAddressParse(ipa) println("IP address  : $ipa") println("Address  : ${"%X".format(address)}") println("Address Space : $addressSpace") println("Port  : ${if (port == -1) "not specified" else port.toString()}") println() } }
http://rosettacode.org/wiki/Parametric_polymorphism
Parametric polymorphism
Parametric Polymorphism type variables Task Write a small example for a type declaration that is parametric over another type, together with a short bit of code (and its type signature) that uses it. A good example is a container type, let's say a binary tree, together with some function that traverses the tree, say, a map-function that operates on every element of the tree. This language feature only applies to statically-typed languages.
#Kotlin
Kotlin
// version 1.0.6   class BinaryTree<T>(var value: T) { var left : BinaryTree<T>? = null var right: BinaryTree<T>? = null   fun <U> map(f: (T) -> U): BinaryTree<U> { val tree = BinaryTree<U>(f(value)) if (left != null) tree.left = left?.map(f) if (right != null) tree.right = right?.map(f) return tree }   fun showTopThree() = "(${left?.value}, $value, ${right?.value})" }   fun main(args: Array<String>) { val b = BinaryTree(6) b.left = BinaryTree(5) b.right = BinaryTree(7) println(b.showTopThree()) val b2 = b.map { it * 10.0 } println(b2.showTopThree()) }
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.
#F.23
F#
type ast = | Num of int | Add of ast * ast | Sub of ast * ast | Mul of ast * ast | Div of ast * ast | Exp of ast * ast   let (|Int|_|) = System.Int32.TryParse >> function | (true, v) -> Some(v) | (false, _) -> None   let rec parse = function | [] -> failwith "Not enough tokens" | (Int head)::tail -> (Num(head), tail) | op::tail -> let (left, rest1) = parse tail let (right, rest2) = parse rest1 match op with | "+" -> (Add (right, left)), rest2 | "-" -> (Sub (right, left)), rest2 | "*" -> (Mul (right, left)), rest2 | "/" -> (Div (right, left)), rest2 | "^" -> (Exp (right, left)), rest2 | _ -> failwith ("unknown op: " + op)   let rec infix p x = let brackets (x : ast) = seq { yield "("; yield! infix 0 x; yield ")" } let left op context l r = seq { yield! infix context l; yield op; yield! infix context r } let right op context l r = seq { yield! brackets l; yield op; yield! infix context r } seq { match x with | Num (n) -> yield n.ToString() | Add (l, r) when p <= 2 -> yield! left "+" 2 l r | Sub (l, r) when p <= 2 -> yield! left "-" 2 l r | Mul (l, r) when p <= 3 -> yield! left "*" 3 l r | Div (l, r) when p <= 3 -> yield! left "/" 3 l r | Exp (Exp(ll, lr), r) -> yield! right "^" 4 (Exp(ll,lr)) r | Exp (l, r) -> yield! left "^" 4 l r | _ -> yield! brackets x }   [<EntryPoint>] let main argv = let (tree, rest) = argv |> Array.rev |> Seq.toList |> parse match rest with | [] -> printfn "%A" tree | _ -> failwith ("not a valid RPN expression (excess tokens): " + System.String.Join(" ", argv)) Seq.iter (printf " %s") (infix 0 tree); printfn "" 0  
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.
#Icon_and_Unicon
Icon and Unicon
link printf   procedure main() fsf1 := partial(fs,f1) fsf2 := partial(fs,f2) every s := [ 0, 1, 2, 3 ] | [ 2, 4, 6, 8 ] do { printf("\ns  := %s\n",list2string(s)) printf("fsf1(s) := %s\n",list2string(fsf1(s))) printf("fsf2(s) := %s\n",list2string(fsf2(s))) } end   procedure partial(f,g) #: partial application of f & g @( p := create repeat { s := (r@&source)[1] # return r / get argument s r := f(g,s) # apply f(g,...) } ) # create and activate procedure p return p end   procedure fs(f,s) #: return list where f is applied to each element of s every put(r := [], f(!s)) return r end   procedure f1(n) # double return n * 2 end   procedure f2(n) #: square return n ^ 2 end   procedure list2string(L) #: format list as a string every (s := "[ ") ||:= !L || " " return s || "]" end
http://rosettacode.org/wiki/Partition_an_integer_x_into_n_primes
Partition an integer x into n primes
Task Partition a positive integer   X   into   N   distinct primes. Or, to put it in another way: Find   N   unique primes such that they add up to   X. Show in the output section the sum   X   and the   N   primes in ascending order separated by plus (+) signs: •   partition 99809 with 1 prime. •   partition 18 with 2 primes. •   partition 19 with 3 primes. •   partition 20 with 4 primes. •   partition 2017 with 24 primes. •   partition 22699 with 1, 2, 3, and 4 primes. •   partition 40355 with 3 primes. The output could/should be shown in a format such as: Partitioned 19 with 3 primes: 3+5+11   Use any spacing that may be appropriate for the display.   You need not validate the input(s).   Use the lowest primes possible;   use  18 = 5+13,   not   18 = 7+11.   You only need to show one solution. This task is similar to factoring an integer. Related tasks   Count in factors   Prime decomposition   Factors of an integer   Sieve of Eratosthenes   Primality by trial division   Factors of a Mersenne number   Factors of a Mersenne number   Sequence of primes by trial division
#Python
Python
from itertools import combinations as cmb     def isP(n): if n == 2: return True if n % 2 == 0: return False return all(n % x > 0 for x in range(3, int(n ** 0.5) + 1, 2))     def genP(n): p = [2] p.extend([x for x in range(3, n + 1, 2) if isP(x)]) return p     data = [ (99809, 1), (18, 2), (19, 3), (20, 4), (2017, 24), (22699, 1), (22699, 2), (22699, 3), (22699, 4), (40355, 3)]     for n, cnt in data: ci = iter(cmb(genP(n), cnt)) while True: try: c = next(ci) if sum(c) == n: print(' '.join( [repr((n, cnt)), "->", '+'.join(str(s) for s in c)] )) break except StopIteration: print(repr((n, cnt)) + " -> Not possible") break
http://rosettacode.org/wiki/Pascal%27s_triangle/Puzzle
Pascal's triangle/Puzzle
This puzzle involves a Pascals Triangle, also known as a Pyramid of Numbers. [ 151] [ ][ ] [40][ ][ ] [ ][ ][ ][ ] [ X][11][ Y][ 4][ Z] Each brick of the pyramid is the sum of the two bricks situated below it. Of the three missing numbers at the base of the pyramid, the middle one is the sum of the other two (that is, Y = X + Z). Task Write a program to find a solution to this puzzle.
#Prolog
Prolog
:- use_module(library(clpfd)).   puzzle(Ts, X, Y, Z) :- Ts = [ [151], [_, _], [40, _, _], [_, _, _, _], [X, 11, Y, 4, Z]], Y #= X + Z, triangle(Ts), append(Ts, Vs), Vs ins 0..sup, label(Vs).   triangle([T|Ts]) :- ( Ts = [N|_] -> triangle_(T, N), triangle(Ts) ; true ).   triangle_([], _). triangle_([T|Ts], [A,B|Rest]) :- T #= A + B, triangle_(Ts, [B|Rest]).   % ?- puzzle(_,X,Y,Z). % X = 5, % Y = 13, % Z = 8 ;
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
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
(* Length is the Length of the password, num is the number you want, \ and similar=1 if you want similar characters, 0 if not. True and \ False, should work in place of 1/0 *) pwgen[length_Integer: 5, num_Integer: 1, similars_Boolean: 1] := pwgenerator[length, num, similars] = Module[{list, valid, validchars, similar, k, j, password, pwlist, lcase, ucase, digits, spec, s}, lcase = Alphabet[]; ucase = Capitalize[lcase]; digits = Range[0, 9]; spec = StringPartition["!:#$%\'()*+,-./:;>=<?@{}[]^_|~", 1]; validchars = Flatten[Union[lcase, ucase, digits, spec]]; similar = StringPartition["Il10O5S2Z", 1]; list = {};   Table[valid = 0; While[valid == 0, For[j = 0; k = {};, j < length, j++, AppendTo[k, RandomInteger[{1, Length[validchars]}]]]; k = Flatten[k]; password = validchars[[k]]; Which[(Intersection[password, similar] >= 1 && similars == 0 ), valid = 0;, (Intersection[password, similar] == 0 && similars == 1), valid = 0;, (Intersection[password, similar] == 0 && similars == 0 ), valid = 1; Return[password], (Intersection[password, similar] >= 1 && similars == 1), valid = 1; Return[password]]; ], {num}];     ]
http://rosettacode.org/wiki/Permutations
Permutations
Task Write a program that generates all   permutations   of   n   different objects.   (Practically numerals!) Related tasks   Find the missing permutation   Permutations/Derangements The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Unimportant Order Important Without replacement ( n k ) = n C k = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} Task: Combinations Task: Permutations With replacement ( n + k − 1 k ) = n + k − 1 C k = ( n + k − 1 ) ! ( n − 1 ) ! k ! {\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}} n k {\displaystyle n^{k}} Task: Combinations with repetitions Task: Permutations with repetitions
#Ursala
Ursala
#import std   permutations =   ~&itB^?a( # are both the input argument list and its tail non-empty? @ahPfatPRD *= refer ^C( # yes, recursively generate all permutations of the tail, and for each one ~&a, # insert the head at the first position ~&ar&& ~&arh2falrtPXPRD), # if the rest is non-empty, recursively insert at all subsequent positions ~&aNC) # no, return the singleton list of the argument
http://rosettacode.org/wiki/Pathological_floating_point_problems
Pathological floating point problems
Most programmers are familiar with the inexactness of floating point calculations in a binary processor. The classic example being: 0.1 + 0.2 = 0.30000000000000004 In many situations the amount of error in such calculations is very small and can be overlooked or eliminated with rounding. There are pathological problems however, where seemingly simple, straight-forward calculations are extremely sensitive to even tiny amounts of imprecision. This task's purpose is to show how your language deals with such classes of problems. A sequence that seems to converge to a wrong limit. Consider the sequence: v1 = 2 v2 = -4 vn = 111   -   1130   /   vn-1   +   3000  /   (vn-1 * vn-2) As   n   grows larger, the series should converge to   6   but small amounts of error will cause it to approach   100. Task 1 Display the values of the sequence where   n =   3, 4, 5, 6, 7, 8, 20, 30, 50 & 100   to at least 16 decimal places. n = 3 18.5 n = 4 9.378378 n = 5 7.801153 n = 6 7.154414 n = 7 6.806785 n = 8 6.5926328 n = 20 6.0435521101892689 n = 30 6.006786093031205758530554 n = 50 6.0001758466271871889456140207471954695237 n = 100 6.000000019319477929104086803403585715024350675436952458072592750856521767230266 Task 2 The Chaotic Bank Society   is offering a new investment account to their customers. You first deposit   $e - 1   where   e   is   2.7182818...   the base of natural logarithms. After each year, your account balance will be multiplied by the number of years that have passed, and $1 in service charges will be removed. So ... after 1 year, your balance will be multiplied by 1 and $1 will be removed for service charges. after 2 years your balance will be doubled and $1 removed. after 3 years your balance will be tripled and $1 removed. ... after 10 years, multiplied by 10 and $1 removed, and so on. What will your balance be after   25   years? Starting balance: $e-1 Balance = (Balance * year) - 1 for 25 years Balance after 25 years: $0.0399387296732302 Task 3, extra credit Siegfried Rump's example.   Consider the following function, designed by Siegfried Rump in 1988. f(a,b) = 333.75b6 + a2( 11a2b2 - b6 - 121b4 - 2 ) + 5.5b8 + a/(2b) compute   f(a,b)   where   a=77617.0   and   b=33096.0 f(77617.0, 33096.0)   =   -0.827396059946821 Demonstrate how to solve at least one of the first two problems, or both, and the third if you're feeling particularly jaunty. See also;   Floating-Point Arithmetic   Section 1.3.2 Difficult problems.
#Stata
Stata
clear set obs 100 gen n=_n gen v=. replace v=2 in 1 replace v=-4 in 2 replace v=111-1130/v[_n-1]+3000/(v[_n-1]*v[_n-2]) in 3/l format %20.16f v list if inlist(n,3,4,5,6,7,8,20,30,50,100), noobs
http://rosettacode.org/wiki/Pathological_floating_point_problems
Pathological floating point problems
Most programmers are familiar with the inexactness of floating point calculations in a binary processor. The classic example being: 0.1 + 0.2 = 0.30000000000000004 In many situations the amount of error in such calculations is very small and can be overlooked or eliminated with rounding. There are pathological problems however, where seemingly simple, straight-forward calculations are extremely sensitive to even tiny amounts of imprecision. This task's purpose is to show how your language deals with such classes of problems. A sequence that seems to converge to a wrong limit. Consider the sequence: v1 = 2 v2 = -4 vn = 111   -   1130   /   vn-1   +   3000  /   (vn-1 * vn-2) As   n   grows larger, the series should converge to   6   but small amounts of error will cause it to approach   100. Task 1 Display the values of the sequence where   n =   3, 4, 5, 6, 7, 8, 20, 30, 50 & 100   to at least 16 decimal places. n = 3 18.5 n = 4 9.378378 n = 5 7.801153 n = 6 7.154414 n = 7 6.806785 n = 8 6.5926328 n = 20 6.0435521101892689 n = 30 6.006786093031205758530554 n = 50 6.0001758466271871889456140207471954695237 n = 100 6.000000019319477929104086803403585715024350675436952458072592750856521767230266 Task 2 The Chaotic Bank Society   is offering a new investment account to their customers. You first deposit   $e - 1   where   e   is   2.7182818...   the base of natural logarithms. After each year, your account balance will be multiplied by the number of years that have passed, and $1 in service charges will be removed. So ... after 1 year, your balance will be multiplied by 1 and $1 will be removed for service charges. after 2 years your balance will be doubled and $1 removed. after 3 years your balance will be tripled and $1 removed. ... after 10 years, multiplied by 10 and $1 removed, and so on. What will your balance be after   25   years? Starting balance: $e-1 Balance = (Balance * year) - 1 for 25 years Balance after 25 years: $0.0399387296732302 Task 3, extra credit Siegfried Rump's example.   Consider the following function, designed by Siegfried Rump in 1988. f(a,b) = 333.75b6 + a2( 11a2b2 - b6 - 121b4 - 2 ) + 5.5b8 + a/(2b) compute   f(a,b)   where   a=77617.0   and   b=33096.0 f(77617.0, 33096.0)   =   -0.827396059946821 Demonstrate how to solve at least one of the first two problems, or both, and the third if you're feeling particularly jaunty. See also;   Floating-Point Arithmetic   Section 1.3.2 Difficult problems.
#Swift
Swift
extension Numeric where Self: Strideable { @inlinable public func power(_ n: Self) -> Self { return stride(from: 0, to: n, by: 1).lazy.map({_ in self }).reduce(1, *) } }   protocol PathologicalFloat: SignedNumeric, Strideable, ExpressibleByFloatLiteral { static var e: Self { get }   static func /(_ lhs: Self, _ rhs: Self) -> Self }   extension Double: PathologicalFloat { static var e: Double { Double("2.71828182845904523536028747135266249")! } }   extension Float: PathologicalFloat { static var e: Float { Float("2.7182818284590")! } }   extension Decimal: PathologicalFloat { static var e: Decimal { Decimal(string: "2.71828182845904523536028747135266249")! } }   extension BDouble: PathologicalFloat { static var e: BDouble { BDouble("2.71828182845904523536028747135266249")! }   public func advanced(by n: BDouble) -> BDouble { self + n } public func distance(to other: BDouble) -> BDouble { abs(self - other) } }   func badSequence<T: PathologicalFloat>(n: Int) -> T { guard n != 1 else { return 2 } guard n != 2 else { return -4 }   var a: T = 2, b: T = -4   for _ in stride(from: 2, to: n, by: 1) { (a, b) = (b, 111 - 1130 / b + 3000 / (a * b)) }   return b }   func chaoticBank<T: PathologicalFloat>(years: T) -> T { var balance = T.e - 1   for year: T in stride(from: 1, through: 25, by: 1) { balance = (balance * year) - 1 }   return balance }   func rumpFunction<T: PathologicalFloat>(_ a: T, _ b: T) -> T { let aSquared = a.power(2) let bSix = b.power(6)   let f1 = 333.75 * bSix let f2 = aSquared * (11 * aSquared * b.power(2) - bSix - 121 * b.power(4) - 2) let f3 = 5.5 * b.power(8) + a / (2 * b)   return f1 + f2 + f3 }   func fmt<T: CVarArg>(_ n: T) -> String { String(format: "%16.16f", n) }   print("Bad sequence") for i in [3, 4, 5, 6, 7, 8, 20, 30, 50, 100] { let vFloat: Float = badSequence(n: i) let vDouble: Double = badSequence(n: i) let vDecimal: Decimal = badSequence(n: i) let vBigDouble: BDouble = badSequence(n: i)   print("v(\(i)) as Float \(fmt(vFloat)); as Double = \(fmt(vDouble)); as Decimal = \(vDecimal); as BDouble = \(vBigDouble.decimalExpansion(precisionAfterDecimalPoint: 16, rounded: false))") }     let bankFloat: Float = chaoticBank(years: 25) let bankDouble: Double = chaoticBank(years: 25) let bankDecimal: Decimal = chaoticBank(years: 25) let bankBigDouble: BDouble = chaoticBank(years: 25)   print("\nChaotic bank") print("After 25 years your bank will be \(bankFloat) if stored as a Float") print("After 25 years your bank will be \(bankDouble) if stored as a Double") print("After 25 years your bank will be \(bankDecimal) if stored as a Decimal") print("After 25 years your bank will be \(bankBigDouble.decimalExpansion(precisionAfterDecimalPoint: 16, rounded: false)) if stored as a BigDouble")   let rumpFloat: Float = rumpFunction(77617.0, 33096.0) let rumpDouble: Double = rumpFunction(77617.0, 33096.0) let rumpDecimal: Decimal = rumpFunction(77617.0, 33096.0) let rumpBigDouble: BDouble = rumpFunction(77617.0, 33096.0)   print("\nRump's function") print("rump(77617.0, 33096.0) as Float \(rumpFloat); as Double = \(rumpDouble); as Decimal = \(rumpDecimal); as BDouble = \(rumpBigDouble.decimalExpansion(precisionAfterDecimalPoint: 16, rounded: false))")
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
#D
D
import std.digest.sha; import std.parallelism; import std.range; import std.stdio;   // Find the five lower-case letter strings representing the following sha256 hashes immutable p1 = cast(ubyte[32]) x"1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad"; immutable p2 = cast(ubyte[32]) x"3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b"; immutable p3 = cast(ubyte[32]) x"74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f";   void main() { import std.datetime.stopwatch;   auto sw = StopWatch(AutoStart.yes); // Switch these top loops to toggle between non-parallel and parrallel solutions. // foreach(char a; 'a'..'z'+1) { foreach(i, a; taskPool.parallel(iota('a', 'z'+1))) { char[5] psw; psw[0] = cast(char) a; foreach(char b; 'a'..'z'+1) { psw[1] = b; foreach(char c; 'a'..'z'+1) { psw[2] = c; foreach(char d; 'a'..'z'+1) { psw[3] = d; foreach(char e; 'a'..'z'+1) { psw[4] = e; auto hash = psw.sha256Of; if (equal(hash, p1) || equal(hash, p2) || equal(hash, p3)) { writefln("%s <=> %(%x%)", psw, hash); } } } } } } sw.stop; writeln(sw.peek); }   //Specialization that supports static arrays too bool equal(T)(const T[] p, const T[] q) { if (p.length != q.length) { return false; }   for(int i=0; i<p.length; i++) { if (p[i] != q[i]) { return false; } }   return true; }
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.
#Erlang
Erlang
  -module( parallel_calculations ).   -export( [fun_results/2, task/0] ).   fun_results( Fun, Datas ) -> My_pid = erlang:self(), Pids = [fun_spawn( Fun, X, My_pid ) || X <- Datas], [fun_receive(X) || X <- Pids].   task() -> Numbers = [12757923, 12878611, 12757923, 15808973, 15780709, 197622519], Results = fun_results( fun factors/1, Numbers ), Min_results = [lists:min(X) || X <- Results], {_Max_min_factor, Number} = lists:max( lists:zip(Min_results, Numbers) ), {Number, Factors} = lists:keyfind( Number, 1, lists:zip(Numbers, Results) ), io:fwrite( "~p has largest minimal factor among its prime factors ~p~n", [Number, Factors] ).       factors(N) -> factors(N,2,[]).   factors(1,_,Acc) -> Acc; factors(N,K,Acc) when N rem K == 0 -> factors(N div K,K, [K|Acc]); factors(N,K,Acc) -> factors(N,K+1,Acc).   fun_receive( Pid ) -> receive {ok, Result, Pid} -> Result; {Type, Error, Pid} -> erlang:Type( Error ) end.   fun_spawn( Fun, Data, My_pid ) -> erlang:spawn( fun() -> Result = try {ok, Fun(Data), erlang:self()}   catch Type:Error -> {Type, Error, erlang:self()}   end, My_pid ! Result 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.
#C.23
C#
using System; using System.Collections.Generic; using System.Linq; using System.Globalization; using System.Threading;   namespace RPNEvaluator { class RPNEvaluator { static void Main(string[] args) { Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;   string rpn = "3 4 2 * 1 5 - 2 3 ^ ^ / +"; Console.WriteLine("{0}\n", rpn);   decimal result = CalculateRPN(rpn); Console.WriteLine("\nResult is {0}", result); }   static decimal CalculateRPN(string rpn) { string[] rpnTokens = rpn.Split(' '); Stack<decimal> stack = new Stack<decimal>(); decimal number = decimal.Zero;   foreach (string token in rpnTokens) { if (decimal.TryParse(token, out number)) { stack.Push(number); } else { switch (token) { case "^": case "pow": { number = stack.Pop(); stack.Push((decimal)Math.Pow((double)stack.Pop(), (double)number)); break; } case "ln": { stack.Push((decimal)Math.Log((double)stack.Pop(), Math.E)); break; } case "sqrt": { stack.Push((decimal)Math.Sqrt((double)stack.Pop())); break; } case "*": { stack.Push(stack.Pop() * stack.Pop()); break; } case "/": { number = stack.Pop(); stack.Push(stack.Pop() / number); break; } case "+": { stack.Push(stack.Pop() + stack.Pop()); break; } case "-": { number = stack.Pop(); stack.Push(stack.Pop() - number); break; } default: Console.WriteLine("Error in CalculateRPN(string) Method!"); break; } } PrintState(stack); }   return stack.Pop(); }   static void PrintState(Stack<decimal> stack) { decimal[] arr = stack.ToArray();   for (int i = arr.Length - 1; i >= 0; i--) { Console.Write("{0,-8:F3}", arr[i]); }   Console.WriteLine(); } } }
http://rosettacode.org/wiki/Pancake_numbers
Pancake numbers
Adrian Monk has problems and an assistant, Sharona Fleming. Sharona can deal with most of Adrian's problems except his lack of punctuality paying her remuneration. 2 pay checks down and she prepares him pancakes for breakfast. Knowing that he will be unable to eat them unless they are stacked in ascending order of size she leaves him only a skillet which he can insert at any point in the pile and flip all the above pancakes, repeating until the pile is sorted. Sharona has left the pile of n pancakes such that the maximum number of flips is required. Adrian is determined to do this in as few flips as possible. This sequence n->p(n) is known as the Pancake numbers. The task is to determine p(n) for n = 1 to 9, and for each show an example requiring p(n) flips. Sorting_algorithms/Pancake_sort actually performs the sort some giving the number of flips used. How do these compare with p(n)? Few people know p(20), generously I shall award an extra credit for anyone doing more than p(16). References Bill Gates and the pancake problem A058986
#FreeBASIC
FreeBASIC
  Function pancake(n As Integer) As Integer Dim As Integer gap = 2, sum = 2, adj = -1 While (sum < n) adj += 1 gap = gap * 2 - 1 sum += gap Wend Return n + adj End Function   For n As Integer = 1 To 20 Print Using "p(##) = ## "; n; pancake(n); If n Mod 5 = 0 Then ? Next n Sleep  
http://rosettacode.org/wiki/Pancake_numbers
Pancake numbers
Adrian Monk has problems and an assistant, Sharona Fleming. Sharona can deal with most of Adrian's problems except his lack of punctuality paying her remuneration. 2 pay checks down and she prepares him pancakes for breakfast. Knowing that he will be unable to eat them unless they are stacked in ascending order of size she leaves him only a skillet which he can insert at any point in the pile and flip all the above pancakes, repeating until the pile is sorted. Sharona has left the pile of n pancakes such that the maximum number of flips is required. Adrian is determined to do this in as few flips as possible. This sequence n->p(n) is known as the Pancake numbers. The task is to determine p(n) for n = 1 to 9, and for each show an example requiring p(n) flips. Sorting_algorithms/Pancake_sort actually performs the sort some giving the number of flips used. How do these compare with p(n)? Few people know p(20), generously I shall award an extra credit for anyone doing more than p(16). References Bill Gates and the pancake problem A058986
#Go
Go
package main   import "fmt"   func pancake(n int) int { gap, sum, adj := 2, 2, -1 for sum < n { adj++ gap = gap*2 - 1 sum += gap } return n + adj }   func main() { for i := 0; i < 4; i++ { for j := 1; j < 6; j++ { n := i*5 + j fmt.Printf("p(%2d) = %2d ", n, pancake(n)) } fmt.Println() } }
http://rosettacode.org/wiki/Pancake_numbers
Pancake numbers
Adrian Monk has problems and an assistant, Sharona Fleming. Sharona can deal with most of Adrian's problems except his lack of punctuality paying her remuneration. 2 pay checks down and she prepares him pancakes for breakfast. Knowing that he will be unable to eat them unless they are stacked in ascending order of size she leaves him only a skillet which he can insert at any point in the pile and flip all the above pancakes, repeating until the pile is sorted. Sharona has left the pile of n pancakes such that the maximum number of flips is required. Adrian is determined to do this in as few flips as possible. This sequence n->p(n) is known as the Pancake numbers. The task is to determine p(n) for n = 1 to 9, and for each show an example requiring p(n) flips. Sorting_algorithms/Pancake_sort actually performs the sort some giving the number of flips used. How do these compare with p(n)? Few people know p(20), generously I shall award an extra credit for anyone doing more than p(16). References Bill Gates and the pancake problem A058986
#Java
Java
public class Pancake { private static int pancake(int n) { int gap = 2; int sum = 2; int adj = -1; while (sum < n) { adj++; gap = 2 * gap - 1; sum += gap; } return n + adj; }   public static void main(String[] args) { for (int i = 0; i < 4; i++) { for (int j = 1; j < 6; j++) { int n = 5 * i + j; System.out.printf("p(%2d) = %2d ", n, pancake(n)); } System.out.println(); } } }
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.
#F.23
F#
open System   type action = Shift | ReduceStack | ReduceInput   type State (input : string list, stack : string list, output : string list) = member x.Input with get() = input member x.Stack with get() = stack member x.Output with get() = output   member x.report act = let markTop = function | [] -> [] | x::xs -> ("["+x+"]")::xs let (s, text) = if x.Stack = [] && x.Input = [] then x, "" else match act with | Shift -> State((markTop x.Input), x.Stack, x.Output), "shift" | ReduceStack -> State(x.Input, (markTop x.Stack), x.Output), "reduce" | ReduceInput -> State((markTop x.Input), x.Stack, x.Output), "reduce"   let lstr (x :string list) = String.Join(" ", (List.toArray x)) printfn "%25s  %-9s %6s %s" (lstr (List.rev s.Output)) (lstr (List.rev s.Stack)) text (lstr s.Input)   member x.shift = x.report Shift State(x.Input.Tail, (x.Input.Head)::x.Stack, x.Output)   member x.reduce = x.report ReduceStack State (x.Input, (x.Stack.Tail), (x.Stack.Head)::x.Output)   member x.reduceNumber = x.report ReduceInput State(x.Input.Tail, x.Stack, (x.Input.Head)::x.Output)   let prec = function | "^" -> 4 | "*" | "/" -> 3 | "+" | "-" -> 2 | "(" -> 1 | x -> failwith ("No precedence! Not an operator: " + x)   type assocKind = | Left | Right let assoc = function | "^" -> Right | _ -> Left   let (|Number|Open|Close|Operator|) x = if (Double.TryParse >> fst) x then Number elif x = "(" then Open elif x = ")" then Close else Operator   let rec shunting_yard (s : State) =   let rec reduce_to_Open (s : State) = match s.Stack with | [] -> failwith "mismatched parentheses!" | "("::xs -> State(s.Input.Tail, xs, s.Output) | _ -> reduce_to_Open s.reduce   let reduce_by_prec_and_shift x s = let (xPrec, xAssoc) = (prec x, assoc x) let rec loop (s : State) = match s.Stack with | [] -> s | x::xs -> let topPrec = prec x if xAssoc = Left && xPrec <= topPrec || xAssoc = Right && xPrec < topPrec then loop s.reduce else s (loop s).shift   let rec reduce_rest (s : State) = match s.Stack with | [] -> s | "("::_ -> failwith "mismatched parentheses!" | x::_ -> reduce_rest s.reduce   match s.Input with | x::inputRest -> match x with | Number -> shunting_yard s.reduceNumber | Open -> shunting_yard s.shift | Close -> shunting_yard (reduce_to_Open s) | Operator -> shunting_yard (reduce_by_prec_and_shift x s) | [] -> reduce_rest s   [<EntryPoint>] let main argv = let input = if argv.Length = 0 then "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3".Split() else argv shunting_yard (State((Array.toList input), [], [])) |> (fun s -> s.report ReduceStack) 0
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
#FreeBASIC
FreeBASIC
' version 31-12-2016 ' compile with: fbc -s console ' uses gmp, translation from pascal   #Include Once "gmp.bi"   Const As Integer max_n = 500, branch = 4   Dim Shared As mpz_ptr rooted(), unrooted(), c() Dim Shared As mpz_ptr cnt, tmp   Sub tree(br As UInteger, n As UInteger, l As UInteger, sum As UInteger, cnt As mpz_ptr)   Dim As UInteger b, m   For b = br +1 To branch sum = sum + n If sum > max_n Then Return   ' prevent unneeded long math If (l * 2 >= sum) And (b >= branch) Then Return   If b = (br +1) Then mpz_mul(c(br), rooted(n), cnt) Else mpz_add_ui(tmp, rooted(n), b - br -1) mpz_mul(c(br), c(br), tmp) mpz_divexact_ui(c(br), c(br), b - br) End If   If l * 2 < sum Then mpz_add(unrooted(sum), unrooted(sum), c(br)) End If If b < branch Then mpz_add(rooted(sum), rooted(sum), c(br)) For m = n -1 To 1 Step -1 tree(b, m, l, sum, c(br)) Next End If Next   End Sub   Sub bicenter(s As UInteger) If (s And 1) = 1 Then Return mpz_add_ui(tmp, rooted(s \ 2), 1) mpz_mul(tmp, rooted(s \ 2), tmp) mpz_tdiv_q_2exp(tmp, tmp, 1) mpz_add(unrooted(s), unrooted(s), tmp) End Sub   ' ------=< MAIN >=------   Dim As UInteger n, sum Dim As ZString Ptr ans   ReDim rooted(max_n), unrooted(max_n) For n = 0 To max_n rooted(n) = Allocate(Len(__mpz_struct)) : Mpz_init( rooted(n)) unrooted(n) = Allocate(Len(__mpz_struct)) : Mpz_init(unrooted(n)) Next For n = 0 To 1 mpz_set_ui( rooted(n), 1) mpz_set_ui(unrooted(n), 1) Next   ReDim c(branch -1) For n = 0 To branch -1 c(n) = Allocate(Len(__mpz_struct)) : Mpz_init(c(n)) Next   cnt = Allocate(Len(__mpz_struct)) : Mpz_init_set_ui(cnt, 1) tmp = Allocate(Len(__mpz_struct)) : Mpz_init(tmp)   sum = 1 For n = 1 To max_n tree(0, n, n, sum, cnt) bicenter(n) 'gmp_printf("%d: %Zd"+Chr(13)+Chr(10), n, unrooted(n)) ans = Mpz_get_str (0, 10, unrooted(n)) Print Using "###: "; n; : Print *ans Next   For n = 0 To max_n mpz_Clear( rooted(n)) mpz_Clear(unrooted(n)) Next   For n = 0 To branch -1 mpz_clear(c(n)) Next   mpz_clear(cnt) mpz_clear(tmp)   ' empty keyboard buffer While Inkey <> "" : Wend Print : Print "hit any key to end program" Sleep 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
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO; with Ada.Strings.Maps; use Ada.Strings.Maps; with Ada.Characters.Handling; use Ada.Characters.Handling; procedure pangram is   function ispangram(txt: String) return Boolean is (Is_Subset(To_Set(Span => ('a','z')), To_Set(To_Lower(txt))));   begin put_line(Boolean'Image(ispangram("This is a test"))); put_line(Boolean'Image(ispangram("The quick brown fox jumps over the lazy dog"))); put_line(Boolean'Image(ispangram("NOPQRSTUVWXYZ abcdefghijklm"))); put_line(Boolean'Image(ispangram("abcdefghijklopqrstuvwxyz"))); --Missing m, n end pangram;  
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.
#D
D
import std.stdio, std.bigint, std.range, std.algorithm;   auto binomialCoeff(in uint n, in uint k) pure nothrow { BigInt result = 1; foreach (immutable i; 1 .. k + 1) result = result * (n - i + 1) / i; return result; }   auto pascalUpp(in uint n) pure nothrow { return n.iota.map!(i => n.iota.map!(j => binomialCoeff(j, i))); }   auto pascalLow(in uint n) pure nothrow { return n.iota.map!(i => n.iota.map!(j => binomialCoeff(i, j))); }   auto pascalSym(in uint n) pure nothrow { return n.iota.map!(i => n.iota.map!(j => binomialCoeff(i + j, i))); }   void main() { enum n = 5; writefln("Upper:\n%(%(%2d %)\n%)", pascalUpp(n)); writefln("\nLower:\n%(%(%2d %)\n%)", pascalLow(n)); writefln("\nSymmetric:\n%(%(%2d %)\n%)", pascalSym(n)); }
http://rosettacode.org/wiki/Parameterized_SQL_statement
Parameterized SQL statement
SQL injection Using a SQL update statement like this one (spacing is optional): UPDATE players SET name = 'Smith, Steve', score = 42, active = TRUE WHERE jerseyNum = 99 Non-parameterized SQL is the GoTo statement of database programming. Don't do it, and make sure your coworkers don't either.
#Julia
Julia
using SQLite   name = "Smith, Steve" jerseys = Dict("Smith, Steve" => 99) sqlbool(tf::Bool) = if(tf) "TRUE" else "FALSE" end   db = SQLite.DB() # no filename given, so create an in-memory temporary SQLite.execute!(db, "create table players (id integer primary key, name text, score number, active bool, jerseynum integer)")   SQLite.query(db, "INSERT INTO players (name, score, active, jerseynum) values ('Jones, James', 9, 'FALSE', 99)") SQLite.query(db, "UPDATE players SET name = ?, score = ?, active = ? WHERE jerseynum = ?"; values = ["Smith, Steve", 42, sqlbool(true), jerseys[name]])   tbl = SQLite.query(db, "SELECT * from players") println(tbl)
http://rosettacode.org/wiki/Parameterized_SQL_statement
Parameterized SQL statement
SQL injection Using a SQL update statement like this one (spacing is optional): UPDATE players SET name = 'Smith, Steve', score = 42, active = TRUE WHERE jerseyNum = 99 Non-parameterized SQL is the GoTo statement of database programming. Don't do it, and make sure your coworkers don't either.
#Kotlin
Kotlin
// Version 1.2.41   import java.sql.DriverManager import java.sql.Connection   fun main(args: Array<String>) { val url = "jdbc:mysql://localhost:3306/test" val username = "example" val password = "password123" val conn = DriverManager.getConnection(url, username, password) val query = conn.prepareStatement( "UPDATE players SET name = ?, score = ?, active = ? WHERE jerseyNum = ?" ) with (query) { setString(1, "Smith, Steve") setInt(2, 42) setBoolean(3, true) setInt(4, 99) val rowCount = executeUpdate() if (rowCount == 0) println("Update failed") close() } conn.close() }
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
#Befunge
Befunge
0" :swor fo rebmuN">:#,_&> 55+, v v01*p00-1:g00.:<1p011p00:\-1_v#:< >g:1+10p/48*,:#^_$ 55+,1+\: ^>$$@
http://rosettacode.org/wiki/Parse_an_IP_Address
Parse an IP Address
The purpose of this task is to demonstrate parsing of text-format IP addresses, using IPv4 and IPv6. Taking the following as inputs: 127.0.0.1 The "localhost" IPv4 address 127.0.0.1:80 The "localhost" IPv4 address, with a specified port (80) ::1 The "localhost" IPv6 address [::1]:80 The "localhost" IPv6 address, with a specified port (80) 2605:2700:0:3::4713:93e3 Rosetta Code's primary server's public IPv6 address [2605:2700:0:3::4713:93e3]:80 Rosetta Code's primary server's public IPv6 address, with a specified port (80) Task Emit each described IP address as a hexadecimal integer representing the address, the address space, and the port number specified, if any. In languages where variant result types are clumsy, the result should be ipv4 or ipv6 address number, something which says which address space was represented, port number and something that says if the port was specified. Example 127.0.0.1   has the address number   7F000001   (2130706433 decimal) in the ipv4 address space. ::ffff:127.0.0.1   represents the same address in the ipv6 address space where it has the address number   FFFF7F000001   (281472812449793 decimal). ::1   has address number   1   and serves the same purpose in the ipv6 address space that   127.0.0.1   serves in the ipv4 address space.
#Nim
Nim
import net, sequtils, strscans, strutils   const NoPort = -1   func parseIpAddressAndPort(str: string): tuple[ipAddr: IpAddress; port: int] = var ipString: string var port: int if str.scanf("[$+]:$i", ipString, port): # IP v6 address with port. return (ipString.parseIpAddress(), port) if '.' in str and str.scanf("$+:$i", ipString, port): # IP v4 address with port. return (ipString.parseIpAddress(), port) # IP address without port. result = (str.parseIpAddress(), NoPort)     const Inputs = ["127.0.0.1", "127.0.0.1:80", "::1", "[::1]:80", "2605:2700:0:3::4713:93e3", "[2605:2700:0:3::4713:93e3]:80"]   # Room to reserve to display the input. const InputSize = Inputs.mapIt(it.len).foldl(max(a, b)) + 2   echo "Input".alignLeft(InputSize), "Address".align(32), " Space", " Port"   for input in Inputs: try: let (ipAddress, port) = input.parseIpAddressAndPort() let portStr = if port == NoPort: "" else: $port case ipAddress.family of IPv6: echo input.alignLeft(InputSize), ipAddress.address_v6.map(toHex).join().align(32), "IP v6".align(7), portStr.align(6) of IPv4: echo input.alignLeft(InputSize), ipAddress.address_v4.map(toHex).join().align(32), "IP v4".align(7), portStr.align(6)   except ValueError: echo "Invalid IP address: ", input
http://rosettacode.org/wiki/Parse_an_IP_Address
Parse an IP Address
The purpose of this task is to demonstrate parsing of text-format IP addresses, using IPv4 and IPv6. Taking the following as inputs: 127.0.0.1 The "localhost" IPv4 address 127.0.0.1:80 The "localhost" IPv4 address, with a specified port (80) ::1 The "localhost" IPv6 address [::1]:80 The "localhost" IPv6 address, with a specified port (80) 2605:2700:0:3::4713:93e3 Rosetta Code's primary server's public IPv6 address [2605:2700:0:3::4713:93e3]:80 Rosetta Code's primary server's public IPv6 address, with a specified port (80) Task Emit each described IP address as a hexadecimal integer representing the address, the address space, and the port number specified, if any. In languages where variant result types are clumsy, the result should be ipv4 or ipv6 address number, something which says which address space was represented, port number and something that says if the port was specified. Example 127.0.0.1   has the address number   7F000001   (2130706433 decimal) in the ipv4 address space. ::ffff:127.0.0.1   represents the same address in the ipv6 address space where it has the address number   FFFF7F000001   (281472812449793 decimal). ::1   has address number   1   and serves the same purpose in the ipv6 address space that   127.0.0.1   serves in the ipv4 address space.
#Perl
Perl
sub parse_v4 { my ($ip, $port) = @_; my @quad = split(/\./, $ip);   return unless @quad == 4; for (@quad) { return if ($_ > 255) }   if (!length $port) { $port = -1 } elsif ($port =~ /^(\d+)$/) { $port = $1 } else { return }   my $h = join '' => map(sprintf("%02x", $_), @quad); return $h, $port }   sub parse_v6 { my $ip = shift; my $omits;   return unless $ip =~ /^[\da-f:.]+$/i; # invalid char   $ip =~ s/^:/0:/; $omits = 1 if $ip =~ s/::/:z:/g; return if $ip =~ /z.*z/; # multiple omits illegal   my $v4 = ''; my $len = 8;   if ($ip =~ s/:((?:\d+\.){3}\d+)$//) { # hybrid 4/6 ip ($v4) = parse_v4($1) or return; $len -= 2;   } # what's left should be v6 only return unless $ip =~ /^[:a-fz\d]+$/i;   my @h = split(/:/, $ip); return if @h + $omits > $len; # too many segments   @h = map( $_ eq 'z' ? (0) x ($len - @h + 1) : ($_), @h); return join('' => map(sprintf("%04x", hex($_)), @h)).$v4; }   sub parse_ip { my $str = shift; $str =~ s/^\s*//; $str =~ s/\s*$//;   if ($str =~ s/^((?:\d+\.)+\d+)(?::(\d+))?$//) { return 'v4', parse_v4($1, $2); }   my ($ip, $port); if ($str =~ /^\[(.*?)\]:(\d+)$/) { $port = $2; $ip = parse_v6($1); } else { $port = -1; $ip = parse_v6($str); }   return unless $ip; return 'v6', $ip, $port; }   for (qw/127.0.0.1 127.0.0.1:80 ::1 [::1]:80 2605:2700:0:3::4713:93e3 [2605:2700:0:3::4713:93e3]:80 ::ffff:192.168.0.1 [::ffff:192.168.0.1]:22 ::ffff:127.0.0.0.1 a::b::1/) { print "$_\n\t"; my ($ver, $ip, $port) = parse_ip($_) or print "parse error\n" and next;   print "$ver $ip\tport $port\n\n"; }
http://rosettacode.org/wiki/Parametric_polymorphism
Parametric polymorphism
Parametric Polymorphism type variables Task Write a small example for a type declaration that is parametric over another type, together with a short bit of code (and its type signature) that uses it. A good example is a container type, let's say a binary tree, together with some function that traverses the tree, say, a map-function that operates on every element of the tree. This language feature only applies to statically-typed languages.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
f[a_] := Join[a, a] f[{1, 2, 3}] f[{"1", "2", "3"}] f[{1.1, 2.1, 3.1}] f[G[1, "a", Pi]] g[x_] := x^2 g[2] g[3.5] g[Pi] g["a"]
http://rosettacode.org/wiki/Parametric_polymorphism
Parametric polymorphism
Parametric Polymorphism type variables Task Write a small example for a type declaration that is parametric over another type, together with a short bit of code (and its type signature) that uses it. A good example is a container type, let's say a binary tree, together with some function that traverses the tree, say, a map-function that operates on every element of the tree. This language feature only applies to statically-typed languages.
#Mercury
Mercury
:- type tree(A) ---> empty ; node(A, tree(A), tree(A)).   :- func map(func(A) = B, tree(A)) = tree(B).   map(_, empty) = empty. map(F, node(A, Left, Right)) = node(F(A), map(F, Left), map(F, Right)).
http://rosettacode.org/wiki/Parametric_polymorphism
Parametric polymorphism
Parametric Polymorphism type variables Task Write a small example for a type declaration that is parametric over another type, together with a short bit of code (and its type signature) that uses it. A good example is a container type, let's say a binary tree, together with some function that traverses the tree, say, a map-function that operates on every element of the tree. This language feature only applies to statically-typed languages.
#Nim
Nim
import strutils, sugar   type Tree[T] = ref object value: T left, right: Tree[T]     proc newTree[T](value = default(T)): Tree[T] = ## Create a tree with a single node with the given value. Tree[T](value: value)     proc map[T, U](tree: Tree[T]; f: (T) -> U): Tree[U] = ## Apply function "f" to each element of a tree, building ## another tree. result = newTree[U](f(tree.value)) if not tree.left.isNil: result.left = tree.left.map(f) if not tree.right.isNil: result.right = tree.right.map(f)     proc print(tree: Tree; indent = 0) = ## Print a tree. let start = repeat(' ', indent) echo start, "value: ", tree.value if tree.left.isNil: echo start, " nil" else: print(tree.left, indent + 2) if tree.right.isNil: echo start, " nil" else: print(tree.right, indent + 2)     when isMainModule:   echo "Initial tree:" var tree = newTree[int](5) tree.left = newTree[int](2) tree.right = newTree[int](7) print(tree)   echo "" echo "Tree created by applying a function to each node:" let tree1 = tree.map((x) => 1 / x) print(tree1)
http://rosettacode.org/wiki/Parametric_polymorphism
Parametric polymorphism
Parametric Polymorphism type variables Task Write a small example for a type declaration that is parametric over another type, together with a short bit of code (and its type signature) that uses it. A good example is a container type, let's say a binary tree, together with some function that traverses the tree, say, a map-function that operates on every element of the tree. This language feature only applies to statically-typed languages.
#Objective-C
Objective-C
@interface Tree<T> : NSObject { T value; Tree<T> *left; Tree<T> *right; }   - (void)replaceAll:(T)v; @end   @implementation Tree - (void)replaceAll:(id)v { value = v; [left replaceAll:v]; [right replaceAll:v]; } @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.
#Go
Go
package main   import ( "fmt" "strings" )   var tests = []string{ "3 4 2 * 1 5 - 2 3 ^ ^ / +", "1 2 + 3 4 + ^ 5 6 + ^", }   var opa = map[string]struct { prec int rAssoc bool }{ "^": {4, true}, "*": {3, false}, "/": {3, false}, "+": {2, false}, "-": {2, false}, }   const nPrec = 9   func main() { for _, t := range tests { parseRPN(t) } }   func parseRPN(e string) { fmt.Println("\npostfix:", e) type sf struct { prec int expr string } var stack []sf for _, tok := range strings.Fields(e) { fmt.Println("token:", tok) if op, isOp := opa[tok]; isOp { rhs := &stack[len(stack)-1] stack = stack[:len(stack)-1] lhs := &stack[len(stack)-1] if lhs.prec < op.prec || (lhs.prec == op.prec && op.rAssoc) { lhs.expr = "(" + lhs.expr + ")" } lhs.expr += " " + tok + " " if rhs.prec < op.prec || (rhs.prec == op.prec && !op.rAssoc) { lhs.expr += "(" + rhs.expr + ")" } else { lhs.expr += rhs.expr } lhs.prec = op.prec } else { stack = append(stack, sf{nPrec, tok}) } for _, f := range stack { fmt.Printf("  %d %q\n", f.prec, f.expr) } } fmt.Println("infix:", stack[0].expr) }
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.
#J
J
fs=:1 :'u"0 y' f1=:*&2 f2=:^&2 fsf1=:f1 fs fsf2=:f2 fs
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.
#Java
Java
import java.util.Arrays;   public class PartialApplication { interface IntegerFunction { int call(int arg); }   // Original method fs(f, s). static int[] fs(IntegerFunction f, int[] s) { int[] r = new int[s.length]; for (int i = 0; i < s.length; i++) r[i] = f.call(s[i]); return r; }   interface SequenceFunction { int[] call(int[] arg); }   // Curried method fs(f).call(s), // necessary for partial application. static SequenceFunction fs(final IntegerFunction f) { return new SequenceFunction() { public int[] call(int[] s) { // Call original method. return fs(f, s); } }; }   static IntegerFunction f1 = new IntegerFunction() { public int call(int i) { return i * 2; } };   static IntegerFunction f2 = new IntegerFunction() { public int call(int i) { return i * i; } };   static SequenceFunction fsf1 = fs(f1); // Partial application.   static SequenceFunction fsf2 = fs(f2);   public static void main(String[] args) { int[][] sequences = { { 0, 1, 2, 3 }, { 2, 4, 6, 8 }, };   for (int[] array : sequences) { System.out.printf( "array: %s\n" + " fsf1(array): %s\n" + " fsf2(array): %s\n", Arrays.toString(array), Arrays.toString(fsf1.call(array)), Arrays.toString(fsf2.call(array))); } } }
http://rosettacode.org/wiki/Partition_an_integer_x_into_n_primes
Partition an integer x into n primes
Task Partition a positive integer   X   into   N   distinct primes. Or, to put it in another way: Find   N   unique primes such that they add up to   X. Show in the output section the sum   X   and the   N   primes in ascending order separated by plus (+) signs: •   partition 99809 with 1 prime. •   partition 18 with 2 primes. •   partition 19 with 3 primes. •   partition 20 with 4 primes. •   partition 2017 with 24 primes. •   partition 22699 with 1, 2, 3, and 4 primes. •   partition 40355 with 3 primes. The output could/should be shown in a format such as: Partitioned 19 with 3 primes: 3+5+11   Use any spacing that may be appropriate for the display.   You need not validate the input(s).   Use the lowest primes possible;   use  18 = 5+13,   not   18 = 7+11.   You only need to show one solution. This task is similar to factoring an integer. Related tasks   Count in factors   Prime decomposition   Factors of an integer   Sieve of Eratosthenes   Primality by trial division   Factors of a Mersenne number   Factors of a Mersenne number   Sequence of primes by trial division
#Racket
Racket
#lang racket (require math/number-theory)   (define memoised-next-prime (let ((m# (make-hash))) (λ (P) (hash-ref! m# P (λ () (next-prime P))))))   (define (partition-X-into-N-primes X N) (define (partition-x-into-n-primes-starting-at-P x n P result) (cond ((= n x 0) result) ((or (= n 0) (= x 0) (> P x)) #f) (else (let ((P′ (memoised-next-prime P))) (or (partition-x-into-n-primes-starting-at-P (- x P) (- n 1) P′ (cons P result)) (partition-x-into-n-primes-starting-at-P x n P′ result))))))   (reverse (or (partition-x-into-n-primes-starting-at-P X N 2 null) (list 'no-solution))))   (define (report-partition X N) (let ((result (partition-X-into-N-primes X N))) (printf "partition ~a\twith ~a\tprimes: ~a~%" X N (string-join (map ~a result) " + "))))   (module+ test (report-partition 99809 1) (report-partition 18 2) (report-partition 19 3) (report-partition 20 4) (report-partition 2017 24) (report-partition 22699 1) (report-partition 22699 2) (report-partition 22699 3) (report-partition 22699 4) (report-partition 40355 3))
http://rosettacode.org/wiki/Partition_an_integer_x_into_n_primes
Partition an integer x into n primes
Task Partition a positive integer   X   into   N   distinct primes. Or, to put it in another way: Find   N   unique primes such that they add up to   X. Show in the output section the sum   X   and the   N   primes in ascending order separated by plus (+) signs: •   partition 99809 with 1 prime. •   partition 18 with 2 primes. •   partition 19 with 3 primes. •   partition 20 with 4 primes. •   partition 2017 with 24 primes. •   partition 22699 with 1, 2, 3, and 4 primes. •   partition 40355 with 3 primes. The output could/should be shown in a format such as: Partitioned 19 with 3 primes: 3+5+11   Use any spacing that may be appropriate for the display.   You need not validate the input(s).   Use the lowest primes possible;   use  18 = 5+13,   not   18 = 7+11.   You only need to show one solution. This task is similar to factoring an integer. Related tasks   Count in factors   Prime decomposition   Factors of an integer   Sieve of Eratosthenes   Primality by trial division   Factors of a Mersenne number   Factors of a Mersenne number   Sequence of primes by trial division
#Raku
Raku
use Math::Primesieve; my $sieve = Math::Primesieve.new;   # short circuit for '1' partition multi partition ( Int $number, 1 ) { $number.is-prime ?? $number !! () }   multi partition ( Int $number, Int $parts where * > 0 = 2 ) { my @these = $sieve.primes($number); for @these.combinations($parts) { .return if .sum == $number }; () }   # TESTING (18,2, 19,3, 20,4, 99807,1, 99809,1, 2017,24, 22699,1, 22699,2, 22699,3, 22699,4, 40355,3)\ .race(:1batch).map: -> $number, $parts { say (sprintf "Partition %5d into %2d prime piece", $number, $parts), $parts == 1 ?? ': ' !! 's: ', join '+', partition($number, $parts) || 'not possible' }
http://rosettacode.org/wiki/Pascal%27s_triangle/Puzzle
Pascal's triangle/Puzzle
This puzzle involves a Pascals Triangle, also known as a Pyramid of Numbers. [ 151] [ ][ ] [40][ ][ ] [ ][ ][ ][ ] [ X][11][ Y][ 4][ Z] Each brick of the pyramid is the sum of the two bricks situated below it. Of the three missing numbers at the base of the pyramid, the middle one is the sum of the other two (that is, Y = X + Z). Task Write a program to find a solution to this puzzle.
#PureBasic
PureBasic
; Known; ; A. ; [ 151] ; [a ][b ] ; [40][c ][d ] ; [e ][f ][g ][h ] ; [ X][11][ Y][ 4][ Z] ; ; B. ; Y = X + Z   Procedure.i SolveForZ(x) Protected a,b,c,d,e,f,g,h,z For z=0 To 20 e=x+11: f=11+(x+z): g=(x+z)+4: h=4+z If e+f=40 c=f+g : d=g+h: a=40+c: b=c+d If a+b=151 ProcedureReturn z EndIf EndIf Next z ProcedureReturn -1 EndProcedure   Define x=-1, z=0, title$="Pascal's triangle/Puzzle in PureBasic" Repeat x+1 z=SolveForZ(x) Until z>=0 MessageRequester(title$,"X="+Str(x)+#CRLF$+"Y="+Str(x+z)+#CRLF$+"Z="+Str(z))
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
#Nim
Nim
import os, parseopt, random, sequtils, strformat, strutils   const Symbols = toSeq("!\"#$%&'()*+,-./:;<=>?@[]^_{|}~")     proc passGen(passLength = 10, count = 1, seed = 0, excludeSimilars = false): seq[string] = ## Generate a sequence of passwords.   # Initialize the random number generator. if seed == 0: randomize() else: randomize(seed)   # Prepare list of chars per category. var lowerLetters = toSeq('a'..'z') upperLetters = toSeq('A'..'Z') digits = toSeq('0'..'9')   if excludeSimilars: lowerLetters.delete(lowerLetters.find('l')) for c in "IOSZ": upperLetters.delete(upperLetters.find(c)) for c in "012": digits.delete(digits.find(c))   let all = lowerLetters & upperLetters & digits & Symbols   # Generate the passwords. for _ in 1..count: var password = newString(passLength) password[0] = lowerLetters.sample password[1] = upperLetters.sample password[2] = digits.sample password[3] = Symbols.sample for i in 4..<passLength: password[i] = all.sample password.shuffle() result.add password     proc printHelp() = ## Print the help message. echo &"Usage: {getAppFileName().lastPathPart} " & "[-h] [-l:length] [-c:count] [-s:seed] [-x:(true|false)]" echo " -h: display this help" echo " -l: length of generated passwords" echo " -c: number of passwords to generate" echo " -s: seed for the random number generator" echo " -x: exclude similar characters"     proc getIntValue(key, val: string): int = ## Get a positive integer value from a string. try: result = val.parseInt() if result <= 0: raise newException(ValueError, "") except ValueError: quit &"Wrong value for option -{key}: {val}", QuitFailure     var passLength = 10 count = 1 seed = 0 excludeSimilars = false   # Process options. var parser = initOptParser()   for kind, key, val in parser.getopt(): if kind != cmdShortOption: printHelp() quit(QuitFailure)   case key of "h": printHelp() quit(QuitSuccess) of "l": passLength = getIntValue(key, val) of "c": count = getIntValue(key, val) of "s": seed = getIntValue(key, val) of "x": if val.toLowerAscii == "true": excludeSimilars = true elif val.toLowerAscii == "false": excludeSimilars = false else: quit &"Wrong value for option -x: {val}", QuitFailure else: quit &"Wrong option: -{key}"   # Display the passwords. for pw in passGen(passLength, count, seed, excludeSimilars): echo pw
http://rosettacode.org/wiki/Permutations
Permutations
Task Write a program that generates all   permutations   of   n   different objects.   (Practically numerals!) Related tasks   Find the missing permutation   Permutations/Derangements The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Unimportant Order Important Without replacement ( n k ) = n C k = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} Task: Combinations Task: Permutations With replacement ( n + k − 1 k ) = n + k − 1 C k = ( n + k − 1 ) ! ( n − 1 ) ! k ! {\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}} n k {\displaystyle n^{k}} Task: Combinations with repetitions Task: Permutations with repetitions
#VBA
VBA
Public Sub Permute(n As Integer, Optional printem As Boolean = True) 'Generate, count and print (if printem is not false) all permutations of first n integers Dim P() As Integer Dim t As Integer, i As Integer, j As Integer, k As Integer Dim count As Long Dim Last As Boolean   If n <= 1 Then   Debug.Print "Please give a number greater than 1" Exit Sub   End If   'Initialize ReDim P(n)   For i = 1 To n P(i) = i Next   count = 0 Last = False   Do While Not Last 'print? If printem Then   For t = 1 To n Debug.Print P(t); Next   Debug.Print   End If   count = count + 1   Last = True i = n - 1   Do While i > 0   If P(i) < P(i + 1) Then   Last = False Exit Do   End If   i = i - 1 Loop   j = i + 1 k = n   While j < k ' Swap p(j) and p(k) t = P(j) P(j) = P(k) P(k) = t j = j + 1 k = k - 1 Wend   j = n   While P(j) > P(i) j = j - 1 Wend   j = j + 1 'Swap p(i) and p(j) t = P(i) P(i) = P(j) P(j) = t Loop 'While not last Debug.Print "Number of permutations: "; count   End Sub
http://rosettacode.org/wiki/Pathological_floating_point_problems
Pathological floating point problems
Most programmers are familiar with the inexactness of floating point calculations in a binary processor. The classic example being: 0.1 + 0.2 = 0.30000000000000004 In many situations the amount of error in such calculations is very small and can be overlooked or eliminated with rounding. There are pathological problems however, where seemingly simple, straight-forward calculations are extremely sensitive to even tiny amounts of imprecision. This task's purpose is to show how your language deals with such classes of problems. A sequence that seems to converge to a wrong limit. Consider the sequence: v1 = 2 v2 = -4 vn = 111   -   1130   /   vn-1   +   3000  /   (vn-1 * vn-2) As   n   grows larger, the series should converge to   6   but small amounts of error will cause it to approach   100. Task 1 Display the values of the sequence where   n =   3, 4, 5, 6, 7, 8, 20, 30, 50 & 100   to at least 16 decimal places. n = 3 18.5 n = 4 9.378378 n = 5 7.801153 n = 6 7.154414 n = 7 6.806785 n = 8 6.5926328 n = 20 6.0435521101892689 n = 30 6.006786093031205758530554 n = 50 6.0001758466271871889456140207471954695237 n = 100 6.000000019319477929104086803403585715024350675436952458072592750856521767230266 Task 2 The Chaotic Bank Society   is offering a new investment account to their customers. You first deposit   $e - 1   where   e   is   2.7182818...   the base of natural logarithms. After each year, your account balance will be multiplied by the number of years that have passed, and $1 in service charges will be removed. So ... after 1 year, your balance will be multiplied by 1 and $1 will be removed for service charges. after 2 years your balance will be doubled and $1 removed. after 3 years your balance will be tripled and $1 removed. ... after 10 years, multiplied by 10 and $1 removed, and so on. What will your balance be after   25   years? Starting balance: $e-1 Balance = (Balance * year) - 1 for 25 years Balance after 25 years: $0.0399387296732302 Task 3, extra credit Siegfried Rump's example.   Consider the following function, designed by Siegfried Rump in 1988. f(a,b) = 333.75b6 + a2( 11a2b2 - b6 - 121b4 - 2 ) + 5.5b8 + a/(2b) compute   f(a,b)   where   a=77617.0   and   b=33096.0 f(77617.0, 33096.0)   =   -0.827396059946821 Demonstrate how to solve at least one of the first two problems, or both, and the third if you're feeling particularly jaunty. See also;   Floating-Point Arithmetic   Section 1.3.2 Difficult problems.
#TI-83_BASIC
TI-83 BASIC
u(1)=2 u(2)=-4
http://rosettacode.org/wiki/Pathological_floating_point_problems
Pathological floating point problems
Most programmers are familiar with the inexactness of floating point calculations in a binary processor. The classic example being: 0.1 + 0.2 = 0.30000000000000004 In many situations the amount of error in such calculations is very small and can be overlooked or eliminated with rounding. There are pathological problems however, where seemingly simple, straight-forward calculations are extremely sensitive to even tiny amounts of imprecision. This task's purpose is to show how your language deals with such classes of problems. A sequence that seems to converge to a wrong limit. Consider the sequence: v1 = 2 v2 = -4 vn = 111   -   1130   /   vn-1   +   3000  /   (vn-1 * vn-2) As   n   grows larger, the series should converge to   6   but small amounts of error will cause it to approach   100. Task 1 Display the values of the sequence where   n =   3, 4, 5, 6, 7, 8, 20, 30, 50 & 100   to at least 16 decimal places. n = 3 18.5 n = 4 9.378378 n = 5 7.801153 n = 6 7.154414 n = 7 6.806785 n = 8 6.5926328 n = 20 6.0435521101892689 n = 30 6.006786093031205758530554 n = 50 6.0001758466271871889456140207471954695237 n = 100 6.000000019319477929104086803403585715024350675436952458072592750856521767230266 Task 2 The Chaotic Bank Society   is offering a new investment account to their customers. You first deposit   $e - 1   where   e   is   2.7182818...   the base of natural logarithms. After each year, your account balance will be multiplied by the number of years that have passed, and $1 in service charges will be removed. So ... after 1 year, your balance will be multiplied by 1 and $1 will be removed for service charges. after 2 years your balance will be doubled and $1 removed. after 3 years your balance will be tripled and $1 removed. ... after 10 years, multiplied by 10 and $1 removed, and so on. What will your balance be after   25   years? Starting balance: $e-1 Balance = (Balance * year) - 1 for 25 years Balance after 25 years: $0.0399387296732302 Task 3, extra credit Siegfried Rump's example.   Consider the following function, designed by Siegfried Rump in 1988. f(a,b) = 333.75b6 + a2( 11a2b2 - b6 - 121b4 - 2 ) + 5.5b8 + a/(2b) compute   f(a,b)   where   a=77617.0   and   b=33096.0 f(77617.0, 33096.0)   =   -0.827396059946821 Demonstrate how to solve at least one of the first two problems, or both, and the third if you're feeling particularly jaunty. See also;   Floating-Point Arithmetic   Section 1.3.2 Difficult problems.
#Visual_Basic_.NET
Visual Basic .NET
Imports System.Globalization Imports System.Numerics Imports Numerics   #Const USE_BIGRATIONAL = True #Const BANDED_ROWS = True #Const INCREASED_LIMITS = True   #If Not USE_BIGRATIONAL Then ' Mock structure to make test code work. Structure BigRational Overrides Function ToString() As String Return "NOT USING BIGRATIONAL" End Function Shared Narrowing Operator CType(value As BigRational) As Decimal Return -1 End Operator End Structure #End If   Module Common Public Const FMT_STR = "{0,4} {1,-15:G9} {2,-24:G17} {3,-32} {4,-32}" Public ReadOnly Property Headings As String = String.Format(CultureInfo.InvariantCulture, FMT_STR, {"N", "Single", "Double", "Decimal", "BigRational (rounded as decimal)"})   <Conditional("BANDED_ROWS")> Sub SetConsoleFormat(n As Integer) If n Mod 2 = 0 Then Console.BackgroundColor = ConsoleColor.Black Console.ForegroundColor = ConsoleColor.White Else Console.BackgroundColor = ConsoleColor.White Console.ForegroundColor = ConsoleColor.Black End If End Sub   Function FormatOutput(n As Integer, x As (sn As Single, db As Double, dm As Decimal, br As BigRational)) As String SetConsoleFormat(n) Return String.Format(CultureInfo.CurrentCulture, FMT_STR, n, x.sn, x.db, x.dm, CDec(x.br)) End Function   Sub Main() WrongConvergence() Console.WriteLine() ChaoticBankSociety()   Console.WriteLine() SiegfriedRump()   SetConsoleFormat(0) End Sub End Module
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
#Delphi
Delphi
  program Parallel_Brute_Force;   {$APPTYPE CONSOLE}   uses System.SysUtils, System.Threading, DCPsha256;   function Sha256(W: string): string; var HashDigest: array[0..31] of byte; d, i: Byte; begin Result := ''; with TDCP_sha256.Create(nil) do begin Init; UpdateStr(W); final(HashDigest[0]); for i := 0 to High(HashDigest) do Result := Result + lowercase(HashDigest[i].ToHexString(2)); end; end;   procedure Force(a: int64); var password: string; hash: string; i, j, k, l: integer; w: string; const Words: TArray<string> = ['1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad', '3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b', '74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f']; begin password := ' '; password[1] := chr(97 + a);   for i := 97 to 122 do begin password[2] := chr(i); for j := 97 to 122 do begin password[3] := chr(j); for k := 97 to 122 do begin password[4] := chr(k); for l := 97 to 122 do begin password[5] := chr(l); hash := Sha256(password);   for w in Words do begin if SameText(hash, w) then begin Writeln('>>', password, ' => ', hash); end; end; end; end; end; end; end;   var s: string; begin   TParallel.&For(0, 25, Force);   Writeln('Enter to exit'); readln; end.
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.
#F.23
F#
open System open PrimeDecomp // Has the decompose function from the Prime decomposition task   let data = [112272537195293L; 112582718962171L; 112272537095293L; 115280098190773L; 115797840077099L; 1099726829285419L] let decomp num = decompose num 2L   let largestMinPrimeFactor (numbers: int64 list) = let decompDetails = Async.Parallel [ for n in numbers -> async { return n, decomp n } ] // Compute the number and its prime decomposition list |> Async.RunSynchronously // Start and wait for all parallel computations to complete. |> Array.sortBy (snd >> List.min >> (~-)) // Sort in descending order, based on the min prime decomp number.   decompDetails.[0]   let showLargestMinPrimeFactor numbers = let number, primeList = largestMinPrimeFactor numbers printf "Number %d has largest minimal factor:\n " number List.iter (printf "%d ") primeList   showLargestMinPrimeFactor data
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.
#Factor
Factor
  USING: io kernel fry locals sequences arrays math.primes.factors math.parser channels threads prettyprint ; IN: <filename>   :: map-parallel ( seq quot -- newseq ) <channel> :> ch seq [ '[ _ quot call ch to ] "factors" spawn ] { } map-as dup length [ ch from ] replicate nip ;   { 576460752303423487 576460752303423487 576460752303423487 112272537195293 115284584522153 115280098190773 115797840077099 112582718962171 112272537095293 1099726829285419 } dup [ factors ] map-parallel dup [ infimum ] map dup supremum swap index swap dupd nth -rot swap nth "Number with largest min. factor is " swap number>string append ", with factors: " append write .  
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.
#C.2B.2B
C++
#include <vector> #include <string> #include <sstream> #include <iostream> #include <cmath> #include <algorithm> #include <iterator> #include <cstdlib>   double rpn(const std::string &expr){ std::istringstream iss(expr); std::vector<double> stack; std::cout << "Input\tOperation\tStack after" << std::endl; std::string token; while (iss >> token) { std::cout << token << "\t"; double tokenNum; if (std::istringstream(token) >> tokenNum) { std::cout << "Push\t\t"; stack.push_back(tokenNum); } else { std::cout << "Operate\t\t"; double secondOperand = stack.back(); stack.pop_back(); double firstOperand = stack.back(); stack.pop_back(); if (token == "*") stack.push_back(firstOperand * secondOperand); else if (token == "/") stack.push_back(firstOperand / secondOperand); else if (token == "-") stack.push_back(firstOperand - secondOperand); else if (token == "+") stack.push_back(firstOperand + secondOperand); else if (token == "^") stack.push_back(std::pow(firstOperand, secondOperand)); else { //just in case std::cerr << "Error" << std::endl; std::exit(1); } } std::copy(stack.begin(), stack.end(), std::ostream_iterator<double>(std::cout, " ")); std::cout << std::endl; } return stack.back(); }   int main() { std::string s = " 3 4 2 * 1 5 - 2 3 ^ ^ / + "; std::cout << "Final answer: " << rpn(s) << std::endl;   return 0; }
http://rosettacode.org/wiki/Pancake_numbers
Pancake numbers
Adrian Monk has problems and an assistant, Sharona Fleming. Sharona can deal with most of Adrian's problems except his lack of punctuality paying her remuneration. 2 pay checks down and she prepares him pancakes for breakfast. Knowing that he will be unable to eat them unless they are stacked in ascending order of size she leaves him only a skillet which he can insert at any point in the pile and flip all the above pancakes, repeating until the pile is sorted. Sharona has left the pile of n pancakes such that the maximum number of flips is required. Adrian is determined to do this in as few flips as possible. This sequence n->p(n) is known as the Pancake numbers. The task is to determine p(n) for n = 1 to 9, and for each show an example requiring p(n) flips. Sorting_algorithms/Pancake_sort actually performs the sort some giving the number of flips used. How do these compare with p(n)? Few people know p(20), generously I shall award an extra credit for anyone doing more than p(16). References Bill Gates and the pancake problem A058986
#Julia
Julia
function pancake(len) gap, gapsum, adj = 2, 2, -1 while gapsum < len adj += 1 gap = gap * 2 - 1 gapsum += gap end return len + adj end   for i in 1:25 print("pancake(", lpad(i, 2), ") = ", rpad(pancake(i), 5)) i % 5 == 0 && println() end  
http://rosettacode.org/wiki/Pancake_numbers
Pancake numbers
Adrian Monk has problems and an assistant, Sharona Fleming. Sharona can deal with most of Adrian's problems except his lack of punctuality paying her remuneration. 2 pay checks down and she prepares him pancakes for breakfast. Knowing that he will be unable to eat them unless they are stacked in ascending order of size she leaves him only a skillet which he can insert at any point in the pile and flip all the above pancakes, repeating until the pile is sorted. Sharona has left the pile of n pancakes such that the maximum number of flips is required. Adrian is determined to do this in as few flips as possible. This sequence n->p(n) is known as the Pancake numbers. The task is to determine p(n) for n = 1 to 9, and for each show an example requiring p(n) flips. Sorting_algorithms/Pancake_sort actually performs the sort some giving the number of flips used. How do these compare with p(n)? Few people know p(20), generously I shall award an extra credit for anyone doing more than p(16). References Bill Gates and the pancake problem A058986
#Kotlin
Kotlin
fun pancake(n: Int): Int { var gap = 2 var sum = 2 var adj = -1 while (sum < n) { adj++ gap = gap * 2 - 1 sum += gap } return n + adj }   fun main() { (1 .. 20).map {"p(%2d) = %2d".format(it, pancake(it))} val lines = results.chunked(5).map { it.joinToString(" ") } lines.forEach { println(it) } }
http://rosettacode.org/wiki/Pancake_numbers
Pancake numbers
Adrian Monk has problems and an assistant, Sharona Fleming. Sharona can deal with most of Adrian's problems except his lack of punctuality paying her remuneration. 2 pay checks down and she prepares him pancakes for breakfast. Knowing that he will be unable to eat them unless they are stacked in ascending order of size she leaves him only a skillet which he can insert at any point in the pile and flip all the above pancakes, repeating until the pile is sorted. Sharona has left the pile of n pancakes such that the maximum number of flips is required. Adrian is determined to do this in as few flips as possible. This sequence n->p(n) is known as the Pancake numbers. The task is to determine p(n) for n = 1 to 9, and for each show an example requiring p(n) flips. Sorting_algorithms/Pancake_sort actually performs the sort some giving the number of flips used. How do these compare with p(n)? Few people know p(20), generously I shall award an extra credit for anyone doing more than p(16). References Bill Gates and the pancake problem A058986
#MAD
MAD
NORMAL MODE IS INTEGER VECTOR VALUES ROW = $5(2HP[,I2,4H] = ,I2,S2)*$   INTERNAL FUNCTION(N) ENTRY TO P. GAP = 2 ADJ = -1 THROUGH LOOP, FOR SUM=2, GAP, SUM.GE.N ADJ = ADJ + 1 LOOP GAP = GAP * 2 - 1 FUNCTION RETURN N + ADJ END OF FUNCTION   THROUGH OUTP, FOR R=1, 5, R.G.20 OUTP PRINT FORMAT ROW, R,P.(R), R+1,P.(R+1), R+2,P.(R+2), 0 R+3,P.(R+3), R+4,P.(R+4), R+5,P.(R+5)   END OF PROGRAM
http://rosettacode.org/wiki/Pancake_numbers
Pancake numbers
Adrian Monk has problems and an assistant, Sharona Fleming. Sharona can deal with most of Adrian's problems except his lack of punctuality paying her remuneration. 2 pay checks down and she prepares him pancakes for breakfast. Knowing that he will be unable to eat them unless they are stacked in ascending order of size she leaves him only a skillet which he can insert at any point in the pile and flip all the above pancakes, repeating until the pile is sorted. Sharona has left the pile of n pancakes such that the maximum number of flips is required. Adrian is determined to do this in as few flips as possible. This sequence n->p(n) is known as the Pancake numbers. The task is to determine p(n) for n = 1 to 9, and for each show an example requiring p(n) flips. Sorting_algorithms/Pancake_sort actually performs the sort some giving the number of flips used. How do these compare with p(n)? Few people know p(20), generously I shall award an extra credit for anyone doing more than p(16). References Bill Gates and the pancake problem A058986
#Nim
Nim
import strformat, strutils   func pancake(n: int): int = var gap, sumGaps = 2 pg = 1 adj = -1 while sumGaps < n: inc adj inc pg, gap swap pg, gap inc sumGaps, gap result = n + adj   var line = "" for n in 1..20: line.addSep(" ") line.add &"p({n:>2}) = {pancake(n):>2}" if n mod 5 == 0: (echo line; line.setLen(0))
http://rosettacode.org/wiki/Pancake_numbers
Pancake numbers
Adrian Monk has problems and an assistant, Sharona Fleming. Sharona can deal with most of Adrian's problems except his lack of punctuality paying her remuneration. 2 pay checks down and she prepares him pancakes for breakfast. Knowing that he will be unable to eat them unless they are stacked in ascending order of size she leaves him only a skillet which he can insert at any point in the pile and flip all the above pancakes, repeating until the pile is sorted. Sharona has left the pile of n pancakes such that the maximum number of flips is required. Adrian is determined to do this in as few flips as possible. This sequence n->p(n) is known as the Pancake numbers. The task is to determine p(n) for n = 1 to 9, and for each show an example requiring p(n) flips. Sorting_algorithms/Pancake_sort actually performs the sort some giving the number of flips used. How do these compare with p(n)? Few people know p(20), generously I shall award an extra credit for anyone doing more than p(16). References Bill Gates and the pancake problem A058986
#Perl
Perl
use strict; use warnings; use feature 'say';   sub pancake { my($n) = @_; my ($gap, $sum, $adj) = (2, 2, -1); while ($sum < $n) { $sum += $gap = $gap * 2 - 1 and $adj++ } $n + $adj; }   my $out; $out .= sprintf "p(%2d) = %2d ", $_, pancake $_ for 1..20; say $out =~ s/.{1,55}\K /\n/gr;   # Maximum number of flips plus examples using exhaustive search sub pancake2 { my ($n) = @_; my $numStacks = 1; my @goalStack = 1 .. $n; my %newStacks = my %stacks = (join(' ',@goalStack), 0); for my $k (1..1000) { my %nextStacks; for my $pos (2..$n) { for my $key (keys %newStacks) { my @arr = split ' ', $key; my $cakes = join ' ', (reverse @arr[0..$pos-1]), @arr[$pos..$#arr]; $nextStacks{$cakes} = $k unless $stacks{$cakes}; } } %stacks = (%stacks, (%newStacks = %nextStacks)); my $perms = scalar %stacks; my %inverted = reverse %stacks; return $k-1, $inverted{(sort keys %inverted)[-1]} if $perms == $numStacks; $numStacks = $perms; } }   say "\nThe maximum number of flips to sort a given number of elements is:"; for my $n (1..9) { my ($a,$b) = pancake2($n); say "pancake($n) = $a example: $b"; }
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.
#AppleScript
AppleScript
on doTask() set part1 to {"First 20 palindromic gapful numbers > 100 ending with each digit from 1 to 9:"} set part2 to {"86th to 100th such:"} set part3 to {"991st to 1000th:"} set astid to AppleScript's text item delimiters set AppleScript's text item delimiters to " " repeat with endDigit from 1 to 9 set {collector1, collector2, collector3} to {{}, {}, {}} set outerNumber to endDigit * 11 -- Number formed from the palindromes' first and last digits. set oddDigitCount to true -- Starting with palindromes in the hundreds. set baseHi to endDigit * 10 -- Number formed from just the "high end" digits, initially endDigit and a middle 0. set hi to baseHi set carryCheck to hi + 10 -- Number reached when incrementing the "high end" number changes its first digit. set inc to 10 -- Incrementor for the middle digit(s) of the palindromes themselves. set counter to 0 set maxNeeded to 1000 set done to false repeat until (done) -- Work out every 10th palindrome (middle digit = 0) from the current "high end" number. set pal to hi if (oddDigitCount) then set temp to hi div 10 else set temp to hi end if repeat until (temp is 0) set pal to pal * 10 + temp mod 10 set temp to temp div 10 end repeat -- Check the result and the following 9 palindromes (derived by incrementing the middle digit(s)) -- and store as text any which are both gapful and the ones required. repeat 10 times if (pal mod outerNumber is 0) then set counter to counter + 1 if (counter ≤ 20) then set end of collector1 to intText(pal) else if (counter < 86) then else if (counter ≤ 100) then set end of collector2 to intText(pal) else if (counter < 991) then else --if (counter ≤ 1000) then set end of collector3 to intText(pal) set done to (counter = maxNeeded) if (done) then exit repeat end if end if set pal to pal + inc end repeat -- Increment the high end number's penultimate digit after every 10th palindrome. -- If a carry changes its first digit, reset for longer palindromes. set hi to hi + 10 if (hi = carryCheck) then set oddDigitCount to (not oddDigitCount) if (oddDigitCount) then set baseHi to baseHi * 10 set carryCheck to carryCheck * 10 set inc to inc div 11 * 10 else set inc to inc * 11 end if set hi to baseHi end if end repeat set {end of part1, end of part2, end of part3} to {collector1 as text, collector2 as text, collector3 as text} end repeat set AppleScript's text item delimiters to linefeed set output to {part1, "", part2, "", part3} as text set AppleScript's text item delimiters to astid   return output end doTask   on intText(n) if (n < 100000000) then return n as text set txt to text 2 thru end of ((100000000 + (n mod 100000000 as integer)) as text) set n to n div 100000000 repeat set lo to n mod 100000000 as integer set n to n div 100000000 if (n is 0) then return (lo as text) & txt set txt to (text 2 thru end of ((100000000 + lo) as text)) & txt end repeat end intText   return doTask()
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.
#Fortran
Fortran
MODULE COMPILER !At least of arithmetic expressions. INTEGER KBD,MSG !I/O units.   INTEGER ENUFF !How long s a piece of string? PARAMETER (ENUFF = 66) !This long. CHARACTER*(ENUFF) RP !Holds the Reverse Polish Notation. INTEGER LR !And this is its length.   INTEGER OPSYMBOLS !Recognised operator symbols. PARAMETER (OPSYMBOLS = 11) !There are also some associates. TYPE SYMB !To recognise symbols and carry associated information. CHARACTER*1 IS !Its text. Careful with the trailing space and comparisons. INTEGER*1 PRECEDENCE !Controls the order of evaluation. CHARACTER*48 USAGE !Description. END TYPE SYMB !The cross-linkage of precedences is tricky. TYPE(SYMB) SYMBOL(0:OPSYMBOLS) !Righto, I'll have some. PARAMETER (SYMBOL =(/ !Note that "*" is not to be seen as a match to "**". o SYMB(" ", 0,"Not recognised as an operator's symbol."), 1 SYMB(" ", 1,"separates symbols and aids legibility."), 2 SYMB(")", 4,"opened with ( to bracket a sub-expression."), 3 SYMB("]", 4,"opened with [ to bracket a sub-expression."), 4 SYMB("}", 4,"opened with { to bracket a sub-expression."), 5 SYMB("+",11,"addition, and unary + to no effect."), 6 SYMB("-",11,"subtraction, and unary - for neg. numbers."), 7 SYMB("*",12,"multiplication."), 8 SYMB("×",12,"multiplication, if you can find this."), 9 SYMB("/",12,"division."), o SYMB("÷",12,"division for those with a fancy keyboard."), C 13 is used so that stacked ^ will have lower priority than incoming ^, thus delivering right-to-left evaluation. 1 SYMB("^",14,"raise to power. Not recognised is **.")/)) CHARACTER*3 BRAOPEN,BRACLOSE !Three types are allowed. PARAMETER (BRAOPEN = "([{", BRACLOSE = ")]}") !These. INTEGER BRALEVEL !In and out, in and out. That's the game. INTEGER PRBRA,PRPOW !Special double values. PARAMETER (PRBRA = SYMBOL( 3).PRECEDENCE) !Bracketing PARAMETER (PRPOW = SYMBOL(11).PRECEDENCE) !And powers refer leftwards.   CHARACTER*10 DIGIT !Numberish is a bit more complex. PARAMETER (DIGIT = "0123456789") !But this will do for integers.   INTEGER STACKLIMIT !How high is a stack? PARAMETER (STACKLIMIT = 66) !This should suffice. TYPE DEFERRED !I need a siding for lower-precedence operations. CHARACTER*1 OPC !The operation code. INTEGER*1 PRECEDENCE !Its precedence in the siding may differ. END TYPE DEFERRED !Anyway, that's enough. TYPE(DEFERRED) OPSTACK(0:STACKLIMIT) !One siding, please. INTEGER OSP !The operation stack pointer.   INTEGER INCOMING,TOKENTYPE,NOTHING,ANUMBER,OPENBRA,HUH !Some mnemonics. PARAMETER (NOTHING = 0, ANUMBER = -1, OPENBRA = -2, HUH = -3) !The ordering is not arbitrary. CONTAINS !Now to mess about. SUBROUTINE EMIT(STUFF) !The objective is to produce some RPN text. CHARACTER*(*) STUFF !The term of the moment. INTEGER L !A length. WRITE (MSG,1) STUFF !Announce. 1 FORMAT ("Emit ",A) !Whatever it is. IF (STUFF.EQ."") RETURN !Ha ha. L = LEN(STUFF) !So, how much is there to append? IF (LR + L.GE.ENUFF) STOP "Too much RPN for RP!" !Perhaps too much. IF (LR.GT.0) THEN !Is there existing stuff? LR = LR + 1 !Yes. Advance one, RP(LR:LR) = " " !And place a space. END IF !So much for separators. RP(LR + 1:LR + L) = STUFF !Place the stuff. LR = LR + L !Count it in. END SUBROUTINE EMIT !Simple enough, if a bit finicky.   SUBROUTINE STACKOP(C,P) !Push an item into the siding. CHARACTER*1 C !The operation code. INTEGER P !Its precedence. OSP = OSP + 1 !Stacking up... IF (OSP.GT.STACKLIMIT) STOP "OSP overtopped!" !Perhaps not. OPSTACK(OSP).OPC = C !Righto, OPSTACK(OSP).PRECEDENCE = P !The deed is simple. WRITE (MSG,1) C,OPSTACK(1:OSP) !Announce. 1 FORMAT ("Stack ",A1,9X,",OpStk=",33(A1,I2:",")) END SUBROUTINE STACKOP !So this is more for mnemonic ease.   LOGICAL FUNCTION COMPILE(TEXT) !A compiler confronts a compiler! CHARACTER*(*) TEXT !To be inspected. INTEGER L1,L2 !Fingers for the scan. CHARACTER*1 C !Character of the moment. INTEGER HAPPY !Ah, shades of mood. LR = 0 !No output yet. OSP = 0 !Nothing stacked. OPSTACK(0).OPC = "" !Prepare a bouncer. OPSTACK(0).PRECEDENCE = 0 !So that loops won't go past. BRALEVEL = 0 !None seen. HAPPY = +1 !Nor any problems. L2 = 1 !Syncopation: one past the end of the previous token. Chew into an operand, possibly obstructed by an open bracket. 100 CALL FORASIGN !Find something to inspect. IF (TOKENTYPE.EQ.NOTHING) THEN !Run off the end? IF (OSP.GT.0) CALL GRUMP("Another operand or one of " !E.g. "1 +". 1 //BRAOPEN//" is expected.") !Give a hint, because stacked stuff awaits. ELSE IF (TOKENTYPE.EQ.ANUMBER) THEN !If a number, CALL EMIT(TEXT(L1:L2 - 1)) !Roll all its digits. ELSE IF (TOKENTYPE.EQ.OPENBRA) THEN !Starting a sub-expression? CALL STACKOP(C,PRBRA - 1) !Thus ( has less precedence than ). GO TO 100 !And I still want an operand. C ELSE IF (TOKENTYPE.EQ.ANAME) THEN !Name of something? C CALL EMIT(TEXT(L1:L2 - 1)) !Roll it. ELSE !No further options. CALL GRUMP("Huh? Unexpected "//C) !Probably something like "1 + +" END IF !Righto, finished with operands. Chase after an operator, possibly interrupted by a close bracket,. 200 CALL FORASIGN !Find something to inspect. IF (TOKENTYPE.LT.0) THEN !But, have I an operand-like token instead? CALL GRUMP("Operator expected, not "//C) !It seems so. ELSE !Normally, an operator is to hand. Possibly a NOTHING, though. WRITE (MSG,201) C,INCOMING,OPSTACK(1:OSP) !Document it. 201 FORMAT ("Oprn=>",A1,"< Prec=",I2, !Try to align with other output. 1 ",OpStk=",33(A1,I2:",")) !So as not to clutter the display. DO WHILE(OPSTACK(OSP).PRECEDENCE .GE. INCOMING) !Shunt higher-precedence stuff out. IF (OPSTACK(OSP).PRECEDENCE .EQ. PRBRA - 1) !Only opening brackets have this precedence. 1 CALL GRUMP("Unbalanced "//OPSTACK(OSP).OPC) !And they vanish only when meeting their closing bracket. CALL EMIT(OPSTACK(OSP).OPC) !Otherwise we have an operator. OSP = OSP - 1 !It has gone forth. END DO !On to the next. IF (TOKENTYPE.GT.NOTHING) THEN !Now, only lower-precedence items are still in the stack. IF (INCOMING.EQ.PRBRA) THEN !And this is a special arrival. CALL BALANCEBRA(C) !It should match an earlier entry. BRALEVEL = BRALEVEL - 1 !Count it out. GO TO 200 !And I still haven't got an operator. ELSE !All others are normal operators. IF (C.EQ."^") INCOMING = PRPOW - 1 !Special trick to cause leftwards association of x^2^3. CALL STACKOP(C,INCOMING) !Shunt aside, to await the next arrival. END IF !So much for that operator. END IF !Providing it was not just an end-of-input flusher. END IF !And not a misplaced operand. Carry on? IF (HAPPY .GT. 0) GO TO 100 !No problems, and not a nothing from the end of the text. Completed. COMPILE = HAPPY.GE.0 !One hopes so. CONTAINS !Now for some assistants. SUBROUTINE GRUMP(GROWL) !There might be a problem. CHARACTER*(*) GROWL !The fault. WRITE (MSG,1) GROWL !Say it. IF (L1.GT. 1) WRITE (MSG,1) "Tasty:",TEXT( 1:L1 - 1) !Now explain the context. IF (L2.GT.L1) WRITE (MSG,1) "Nasty:",TEXT(L1:L2 - 1) !This is the token when trouble was found. IF (L2.LE.LEN(TEXT)) WRITE (MSG,1) "Misty:",TEXT(L2:) !And this remains to be seen. 1 FORMAT (4X,A,1X,A) !A simple layout works nicely for reasonable-length texts. HAPPY = -1 . !Just so. END SUBROUTINE GRUMP !Enuogh said.   SUBROUTINE BALANCEBRA(B) !Perhaps a happy meeting. CHARACTER*1 B !The closer. CHARACTER*1 O !The putative opener. INTEGER IT,L !Fingers. CHARACTER*88 GROWL !A scratchpad. O = OPSTACK(OSP).OPC !This should match B. WRITE (MSG,1) O,B !Perhaps. 1 FORMAT ("Match ",2A) !Show what I've got, anyway. IT = INDEX(BRAOPEN,O) !So, what sort did I save? IF (IT .EQ. INDEX(BRACLOSE,B)) THEN !A friend? OSP = OSP - 1 !Yes. They vanish together. ELSE !Otherwise, something is out of place. GROWL = "Unbalanced {[(...)]} bracketing! The closing " !Alas. 1 //B//" is unmatched." !So, a mess. IF (IT.GT.0) GROWL(62:) = "A "//BRACLOSE(IT:IT) !Perhaps there had been no opening bracket. 1 //" would be better." !But if there had, this would be its friend. CALL GRUMP(GROWL) !Take that! END IF !So much for discrepancies. END SUBROUTINE BALANCEBRA !But, hopefully, amity prevails.   SUBROUTINE FORASIGN !See what comes next. INTEGER I !A stepper. L1 = L2 !Pick up where the previous scan left off. 10 IF (L1.GT.LEN(TEXT)) THEN !Are we off the end yet? C = "" !Yes. Scrub the marker. L2 = L1 !TEXT(L1:L2 - 1) will be null. TOKENTYPE = NOTHING !But this is to be checked first. INCOMING = SYMBOL(1).PRECEDENCE !For flushing sidetracked operators. HAPPY = 0 !Fading away. ELSE !Otherwise, there is grist. Check for spaces and move past them. C = TEXT(L1:L1) !Grab the first character of the prospective token. IF (C.LE." ") THEN !Boring? L1 = L1 + 1 !Yes. Step past it. GO TO 10 !And look afresh. END IF !Otherwise, L1 now fingers the start. Caught something to inspect. L2 = L1 + 1 !This is one beyond. Just for digit strings. IF (INDEX(DIGIT,C).GT.0) THEN !So, has one started? TOKENTYPE = ANUMBER !Yep. 20 IF (L2.LE.LEN(TEXT)) THEN !Probe ahead. IF (INDEX(DIGIT,TEXT(L2:L2)).GT.0) THEN !Another digit? L2 = L2 + 1 !Yes. Leaving L1 fingering its start, GO TO 20 !Chase its end. END IF !So much for another digit. END IF !And checking against the end. C ELSE IF (INDEX(LETTERS,C).GT.0) THEN !Some sort of name? C advance L2 while in NAMEISH. ELSE IF (INDEX(BRAOPEN,C).GT.0) THEN !An open bracket? TOKENTYPE = OPENBRA !Yep. ELSE !Otherwise, anything else. DO I = OPSYMBOLS,1,-1 !Scan backwards, to find ** before *, if present. IF (SYMBOL(I).IS .EQ. C) EXIT !Found? END DO !On to the next. A linear search will do. IF (I.LE.0) THEN !Is it identified? TOKENTYPE = HUH !No. INCOMING = SYMBOL(0).PRECEDENCE !And this might provoke a flush. ELSE !If it is identified, TOKENTYPE = I !Then this is a positive number. INCOMING = SYMBOL(I).PRECEDENCE !And this is of interest. END IF !Righto, anything has been identified, possibly as HUH. END IF !So much for classification. END IF !If there is something to see. WRITE (MSG,30) C,INCOMING,TOKENTYPE !Announce. 30 FORMAT ("Next=>",A1,"< Prec=",I2,",Ttype=",I2) !C might be blank. END SUBROUTINE FORASIGN !I call for a sign, and I see what? END FUNCTION COMPILE !That's the main activity. END MODULE COMPILER !So, enough of this.   PROGRAM POKE USE COMPILER CHARACTER*66 TEXT LOGICAL HIC MSG = 6 KBD = 5 WRITE (MSG,1) 1 FORMAT ("Produce RPN from infix...",/)   10 WRITE (MSG,11) 11 FORMAT("Infix: ",$) READ(KBD,12) TEXT 12 FORMAT (A) IF (TEXT.EQ."") STOP "Enough." HIC = COMPILE(TEXT) WRITE (MSG,13) HIC,RP(1:LR) 13 FORMAT (L6," RPN: >",A,"<") GO TO 10 END
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
#Go
Go
package main   import ( "fmt" "math/big" )   const branches = 4 const nMax = 500   var rooted, unrooted [nMax + 1]big.Int var c [branches]big.Int var tmp = new(big.Int) var one = big.NewInt(1)   func tree(br, n, l, sum int, cnt *big.Int) { for b := br + 1; b <= branches; b++ { sum += n if sum > nMax { return } if l*2 >= sum && b >= branches { return } if b == br+1 { c[br].Mul(&rooted[n], cnt) } else { tmp.Add(&rooted[n], tmp.SetInt64(int64(b-br-1))) c[br].Mul(&c[br], tmp) c[br].Div(&c[br], tmp.SetInt64(int64(b-br))) } if l*2 < sum { unrooted[sum].Add(&unrooted[sum], &c[br]) } if b < branches { rooted[sum].Add(&rooted[sum], &c[br]) } for m := n - 1; m > 0; m-- { tree(b, m, l, sum, &c[br]) } } }   func bicenter(s int) { if s&1 == 0 { tmp.Rsh(tmp.Mul(&rooted[s/2], tmp.Add(&rooted[s/2], one)), 1) unrooted[s].Add(&unrooted[s], tmp) } }   func main() { rooted[0].SetInt64(1) rooted[1].SetInt64(1) unrooted[0].SetInt64(1) unrooted[1].SetInt64(1) for n := 1; n <= nMax; n++ { tree(0, n, n, 1, big.NewInt(1)) bicenter(n) fmt.Printf("%d: %d\n", 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
#ALGOL_68
ALGOL 68
# init pangram: # INT la = ABS "a", lz = ABS "z"; INT ua = ABS "A", uz = ABS "Z"; IF lz-la+1 > bits width THEN put(stand error, "Exception: insufficient bits in word for task"); stop FI;   PROC is a pangram = (STRING test)BOOL: ( BITS a2z := BIN(ABS(2r1 SHL (lz-la))-1); # assume: ASCII & Binary # FOR i TO UPB test WHILE INT c = ABS test[i]; IF la <= c AND c <= lz THEN a2z := a2z AND NOT(2r1 SHL (c-la)) ELIF ua <= c AND c <= uz THEN a2z := a2z AND NOT(2r1 SHL (c-ua)) FI; # WHILE # a2z /= 2r0 DO SKIP OD; a2z = 2r0 );   main:( []STRING test list = ( "Big fjiords vex quick waltz nymph", "The quick brown fox jumps over a lazy dog", "A quick brown fox jumps over a lazy dog" ); FOR key TO UPB test list DO STRING test = test list[key]; IF is a pangram(test) THEN print(("""",test,""" is a pangram!", new line)) FI OD )
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.
#Delphi
Delphi
defmodule Pascal do defp ij(n), do: for i <- 1..n, j <- 1..n, do: {i,j}   def upper_triangle(n) do Enum.reduce(ij(n), Map.new, fn {i,j},acc -> val = cond do i==1 -> 1 j<i -> 0 true -> Map.get(acc, {i-1, j-1}) + Map.get(acc, {i, j-1}) end Map.put(acc, {i,j}, val) end) |> print(1..n) end   def lower_triangle(n) do Enum.reduce(ij(n), Map.new, fn {i,j},acc -> val = cond do j==1 -> 1 i<j -> 0 true -> Map.get(acc, {i-1, j-1}) + Map.get(acc, {i-1, j}) end Map.put(acc, {i,j}, val) end) |> print(1..n) end   def symmetic_triangle(n) do Enum.reduce(ij(n), Map.new, fn {i,j},acc -> val = if i==1 or j==1, do: 1, else: Map.get(acc, {i-1, j}) + Map.get(acc, {i, j-1}) Map.put(acc, {i,j}, val) end) |> print(1..n) end   def print(matrix, range) do Enum.each(range, fn i -> Enum.map(range, fn j -> Map.get(matrix, {i,j}) end) |> IO.inspect end) end end   IO.puts "Pascal upper-triangular matrix:" Pascal.upper_triangle(5) IO.puts "Pascal lower-triangular matrix:" Pascal.lower_triangle(5) IO.puts "Pascal symmetric matrix:" Pascal.symmetic_triangle(5)
http://rosettacode.org/wiki/Parameterized_SQL_statement
Parameterized SQL statement
SQL injection Using a SQL update statement like this one (spacing is optional): UPDATE players SET name = 'Smith, Steve', score = 42, active = TRUE WHERE jerseyNum = 99 Non-parameterized SQL is the GoTo statement of database programming. Don't do it, and make sure your coworkers don't either.
#M2000_Interpreter
M2000 Interpreter
  Module Parametrized_Sql { Base "rosetta" ' warning erase database if found it in current directory Execute "rosetta", {create table players (name VarChar(64), score Float, active Integer, jerseyNum Integer);} Append "rosetta", "players","name",0,FALSE,99 sql$={ UPDATE players SET name = '{0}', score = {1}, active = {2} WHERE jerseyNum = {3} } Execute "rosetta", format$(sql$,"Smith, Steve", 42,TRUE, 99) Retrieve "rosetta","players",1,"jerseyNum",99 Read how_many Read Name$,score, active,jerseynum Print Name$="Smith, Steve", score=42, active=True, jerseynum=99 ' true true true true } Parametrized_Sql  
http://rosettacode.org/wiki/Parameterized_SQL_statement
Parameterized SQL statement
SQL injection Using a SQL update statement like this one (spacing is optional): UPDATE players SET name = 'Smith, Steve', score = 42, active = TRUE WHERE jerseyNum = 99 Non-parameterized SQL is the GoTo statement of database programming. Don't do it, and make sure your coworkers don't either.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Needs["DatabaseLink`"]; conn=OpenSQLConnection[JDBC["ODBC(DSN)","testdb"],"Username"->"John","Password"->"JohnsPassword"]; SQLExecute[conn,"UPDATE players SET name = `1`, score = `2`, active = `3` WHERE jerseyNum = `4`", {SQLArgument["Smith, Steve",42,True,99]}] CloseSQLConnection[conn];
http://rosettacode.org/wiki/Parameterized_SQL_statement
Parameterized SQL statement
SQL injection Using a SQL update statement like this one (spacing is optional): UPDATE players SET name = 'Smith, Steve', score = 42, active = TRUE WHERE jerseyNum = 99 Non-parameterized SQL is the GoTo statement of database programming. Don't do it, and make sure your coworkers don't either.
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols nobinary   import java.sql.   -- ============================================================================= class RParameterizedSQLSimple public   properties indirect connexion = Connection   properties inheritable constant DRIVER = "org.apache.derby.jdbc.EmbeddedDriver" DBURL = "jdbc:derby:" DBNAME = "/workspace/DB.DerbySamples/DB/TEAMS01" DBMODE_CREATE = ";create=true" DBMODE_NOCREATE = ";create=false" DBMODE_SHUTDOWN = ";shutdown=true"   -- ============================================================================= method RParameterizedSQLSimple() setConnexion(null) return   -- ============================================================================= method createConnexion() inheritable returns Connection signals ClassNotFoundException, InstantiationException, IllegalAccessException if getConnexion() = null then do props = Properties() props.put("user", "user1") props.put("password", "user1")   xURL = String DBURL || DBNAME || DBMODE_CREATE loadDriver(DRIVER) setConnexion(DriverManager.getConnection(xURL, props)) end   return getConnexion()   -- ============================================================================= method shutdownConnexion() inheritable returns boolean signals SQLException   dbState = boolean xURL = String DBURL || DBNAME || DBMODE_SHUTDOWN   do DriverManager.getConnection(xURL) dbState = isTrue   catch se = SQLException if (se.getErrorCode() = 50000) & ("XJ015".equals(se.getSQLState())) then do say "Derby shut down normally" dbState = isTrue end else if (se.getErrorCode() = 45000) & ("08006".equals(se.getSQLState())) then do say "Derby database shut down normally" dbState = isTrue end else do say "Derby did not shut down normally" dbState = isFalse signal se end end   return dbState   -- ============================================================================= method loadDriver(xdriver = String) inheritable static signals ClassNotFoundException, InstantiationException, IllegalAccessException   do Class.forName(xdriver).newInstance() say "Loaded the appropriate driver"   catch cnfe = ClassNotFoundException say "Unable to load the JDBC driver" xdriver say "Please check your CLASSPATH." signal cnfe   catch ie = InstantiationException say "Unable to instantiate the JDBC driver" xdriver signal ie   catch iae = IllegalAccessException say "Not allowed to access the JDBC driver" xdriver signal iae   end   return   -- ============================================================================= method updatePlayer(jerseyNum = int, name = String, score = int, active = boolean) binary inheritable returns int signals SQLException   updateSQL = "" - || "UPDATE TEAM.PLAYERS" - || " SET NAME = ?, SCORE = ?, ACTIVE = ?" - || " WHERE JERSEYNUM = ?"   rowCt = int ix = int 0   ps = getConnexion().prepareStatement(updateSQL) ix = ix + 1; ps.setString(ix, name) ix = ix + 1; ps.setInt(ix, score) ix = ix + 1; ps.setBoolean(ix, active) ix = ix + 1; ps.setInt(ix, jerseyNum) rowCt = ps.executeUpdate()   return rowCt   -- ============================================================================= method main(args = String[]) public static   do tda = RParameterizedSQLSimple() tda.createConnexion()   if tda.getConnexion() \= null then do updated = tda.updatePlayer(99, "Smith, Steve", 42, isTrue) if updated > 0 then say "Update successful" else say "Update failed"   finally tda.shutdownConnexion() end   catch ex = Exception ex.printStackTrace end   return   -- ============================================================================= method isTrue() public static returns boolean return 1 == 1   -- ============================================================================= method isFalse() public static returns boolean return \isTrue  
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
#BQN
BQN
Pascal ← {(0⊸∾+∾⟜0)⍟(↕𝕩)⋈1}   •Show¨Pascal 6
http://rosettacode.org/wiki/Parse_an_IP_Address
Parse an IP Address
The purpose of this task is to demonstrate parsing of text-format IP addresses, using IPv4 and IPv6. Taking the following as inputs: 127.0.0.1 The "localhost" IPv4 address 127.0.0.1:80 The "localhost" IPv4 address, with a specified port (80) ::1 The "localhost" IPv6 address [::1]:80 The "localhost" IPv6 address, with a specified port (80) 2605:2700:0:3::4713:93e3 Rosetta Code's primary server's public IPv6 address [2605:2700:0:3::4713:93e3]:80 Rosetta Code's primary server's public IPv6 address, with a specified port (80) Task Emit each described IP address as a hexadecimal integer representing the address, the address space, and the port number specified, if any. In languages where variant result types are clumsy, the result should be ipv4 or ipv6 address number, something which says which address space was represented, port number and something that says if the port was specified. Example 127.0.0.1   has the address number   7F000001   (2130706433 decimal) in the ipv4 address space. ::ffff:127.0.0.1   represents the same address in the ipv6 address space where it has the address number   FFFF7F000001   (281472812449793 decimal). ::1   has address number   1   and serves the same purpose in the ipv6 address space that   127.0.0.1   serves in the ipv4 address space.
#Phix
Phix
with javascript_semantics function parse_ip(string txt) sequence r integer dot = find('.',txt), colon = find(':',txt), openbr = find('[',txt), closebr = find(']',txt) if (colon=5 and txt[1..4] = "http") or (colon=6 and txt[1..5] = "https") then txt = trim(txt[colon+1..$],"/") return parse_ip(txt) end if bool ipv6 = openbr or dot=0 or (colon and colon<dot) if ipv6 then sequence res = repeat(0,8) if openbr then if openbr!=1 or closebr<openbr then return 0 end if r = scanf(txt[closebr+1..$],":%d") if length(r)!=1 then return 0 end if atom port = r[1][1] if port<0 or port>65535 then return 0 end if res &= port txt = txt[2..closebr-1] end if if dot then colon = rfind(':',txt) if colon>dot then return 0 end if object r4 = parse_ip(txt[colon+1..$]) if not sequence(r4) or length(r4)!=4 then return 0 end if res[7] = r4[1]*#100+r4[2] res[8] = r4[3]*#100+r4[4] txt = txt[1..colon-1+(txt[colon-1]=':')] dot = 2 end if sequence r8 = {} integer ip = 0 while length(txt) do colon = find(':',txt) if colon=1 then if ip then return 0 end if ip = length(r8)+1 txt = txt[2+(length(r8)=0)..$] else r = scanf(txt[1..colon-1],"%x") if length(r)!=1 then return 0 end if atom r11 = r[1][1] if r11<0 or r11>#FFFF then return 0 end if r8 &= r11 if colon=0 then exit end if txt = txt[colon+1..$] end if end while if ip then if length(r8)>=(8-dot) then return 0 end if r8[ip..ip-1] = repeat(0,(8-dot)-length(r8)) else if length(r8)!=8-dot then return 0 end if end if res[1..8-dot] = r8 return res end if -- ipv4: if dot=0 or (colon and colon<dot) then return 0 end if string d4 = substitute(txt[1..colon-1],'.',' ') r = scanf(d4,"%d %d %d %d") if length(r)!=1 then return 0 end if r = r[1] for i=1 to length(r) do if r[i]<0 or r[i]>255 then return 0 end if end for if colon then sequence r2 = scanf(txt[colon+1..$],"%d") if length(r2)!=1 then return 0 end if atom port = r2[1][1] if port<0 or port>65535 then return 0 end if r &= port end if return r end function constant tests = {{"127.0.0.1",{127,0,0,1}}, {"127.0.0.1:80",{127,0,0,1,80}}, {"::1",{0,0,0,0,0,0,0,1}}, {"[::1]:80",{0,0,0,0,0,0,0,1,80}}, {"2605:2700:0:3::4713:93e3",{#2605,#2700,0,3,0,0,#4713,#93e3}}, {"[2605:2700:0:3::4713:93e3]:80",{#2605,#2700,0,3,0,0,#4713,#93e3,80}}, {"::ffff:192.168.173.22",{0,0,0,0,0,#ffff,#c0a8,#ad16}}, {"[::ffff:192.168.173.22]:80",{0,0,0,0,0,#ffff,#c0a8,#ad16,80}}, {"1::",{1,0,0,0,0,0,0,0}}, {"[1::]:80",{1,0,0,0,0,0,0,0,80}}, {"::",{0,0,0,0,0,0,0,0}}, {"[::]:80",{0,0,0,0,0,0,0,0,80}}, {"192.168.0.1",{192,168,0,1}}, {"2001:db8:85a3:0:0:8a2e:370:7334",{#2001,#db8,#85a3,0,0,#8a2e,#370,#7334}}, {"2001:db8:85a3::8a2e:370:7334",{#2001,#db8,#85a3,0,0,#8a2e,#370,#7334}}, {"[2001:db8:85a3:8d3:1319:8a2e:370:7334]:443",{#2001,#db8,#85a3,#8d3,#1319,#8a2e,#370,#7334,443}}, {"256.0.0.0",0}, {"g::1",0}, {"::ffff:127.0.0.0.1",0}, {"a::b::1",0}, {"0000",0}, {"0000:0000",0}, {"0000:0000:0000:0000:0000:0000:0000:0000",{0,0,0,0,0,0,0,0}}, {"0000:0000:0000::0000:0000",{0,0,0,0,0,0,0,0}}, {"0000::0000::0000:0000",0}, {"ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff",{#ffff,#ffff,#ffff,#ffff,#ffff,#ffff,#ffff,#ffff}}, {"ffff:ffff:ffff:fffg:ffff:ffff:ffff:ffff",0}, {"fff:ffff:ffff:ffff:ffff:ffff:ffff:ffff",{#fff,#ffff,#ffff,#ffff,#ffff,#ffff,#ffff,#ffff}}, {"fff:ffff:0:ffff:ffff:ffff:ffff:ffff",{#fff,#ffff,0,#ffff,#ffff,#ffff,#ffff,#ffff}}, {"2001:0db8:0:0:0:0:1428:57ab",{#2001,#0db8,0,0,0,0,#1428,#57ab}}, {"2001:0db8::1428:57ab",{#2001,#0db8,0,0,0,0,#1428,#57ab}}, {"2001:0db8:0:0:8d3:0:0:0",{#2001,#0db8,0,0,#8d3,0,0,0}}, {"2001:0db8:0:0:8d3::",{#2001,#0db8,0,0,#8d3,0,0,0}}, {"2001:0db8::8d3:0:0:0",{#2001,#0db8,0,0,#8d3,0,0,0}}, {"http://127.0.0.1/",{127,0,0,1}}, {"https://127.0.0.1/",{127,0,0,1}}, {"http:",0}, {"http:/2001:db8:3:4::127.0.2.0",{#2001,#db8,3,4,0,0,#7F00,#200}}, {"::192.168.0.1",{0,0,0,0,0,0,#C0A8,1}}, {"::ffff:0:255.255.255.255",{0,0,0,0,#ffff,0,#ffff,#ffff}}, {"",0}, {"ffffffffffffffffffffffffffffffff::",0}, {"[1::]:9999999999999999999999999999",0}, {"I think that's enough tests for now",0}} for i=1 to length(tests) do {string ip, object expected} = tests[i] object actual = parse_ip(ip) if actual!=expected then ?{ip,actual,expected} ?9/0 end if string addr if actual=0 then addr = "**not a valid ip address**" else if remainder(length(actual),2) then actual[$] = sprintf(", port %d",actual[$]) else actual = append(actual,"") end if if length(actual)=5 then addr = sprintf("ivp4 address: %02x%02x%02x%02x%s",actual) elsif length(actual)=9 then addr = sprintf("ivp6 address: %04x%04x%04x%04x%04x%04x%04x%04x%s",actual) else ?9/0 end if end if printf(1,"%45s %s\n",{ip,addr}) end for
http://rosettacode.org/wiki/Parametric_polymorphism
Parametric polymorphism
Parametric Polymorphism type variables Task Write a small example for a type declaration that is parametric over another type, together with a short bit of code (and its type signature) that uses it. A good example is a container type, let's say a binary tree, together with some function that traverses the tree, say, a map-function that operates on every element of the tree. This language feature only applies to statically-typed languages.
#OCaml
OCaml
type 'a tree = Empty | Node of 'a * 'a tree * 'a tree   (** val map_tree : ('a -> 'b) -> 'a tree -> 'b tree *) let rec map_tree f = function | Empty -> Empty | Node (x,l,r) -> Node (f x, map_tree f l, map_tree f r)
http://rosettacode.org/wiki/Parametric_polymorphism
Parametric polymorphism
Parametric Polymorphism type variables Task Write a small example for a type declaration that is parametric over another type, together with a short bit of code (and its type signature) that uses it. A good example is a container type, let's say a binary tree, together with some function that traverses the tree, say, a map-function that operates on every element of the tree. This language feature only applies to statically-typed languages.
#Phix
Phix
<-------- object ---------> | | +-atom +-sequence | | +-integer +-string
http://rosettacode.org/wiki/Parametric_polymorphism
Parametric polymorphism
Parametric Polymorphism type variables Task Write a small example for a type declaration that is parametric over another type, together with a short bit of code (and its type signature) that uses it. A good example is a container type, let's say a binary tree, together with some function that traverses the tree, say, a map-function that operates on every element of the tree. This language feature only applies to statically-typed languages.
#PicoLisp
PicoLisp
(de mapTree (Tree Fun) (set Tree (Fun (car Tree))) (and (cadr Tree) (mapTree @ Fun)) (and (cddr Tree) (mapTree @ Fun)) )
http://rosettacode.org/wiki/Parametric_polymorphism
Parametric polymorphism
Parametric Polymorphism type variables Task Write a small example for a type declaration that is parametric over another type, together with a short bit of code (and its type signature) that uses it. A good example is a container type, let's say a binary tree, together with some function that traverses the tree, say, a map-function that operates on every element of the tree. This language feature only applies to statically-typed languages.
#Racket
Racket
  #lang typed/racket   (define-type (Tree A) (U False (Node A)))   (struct: (A) Node ([val : A] [left : (Tree A)] [right : (Tree A)]) #:transparent)   (: tree-map (All (A B) (A -> B) (Tree A) -> (Tree B))) (define (tree-map f tree) (match tree [#f #f] [(Node val left right) (Node (f val) (tree-map f left) (tree-map f right))]))   ;; unit tests (require typed/rackunit) (check-equal? (tree-map add1 (Node 5 (Node 3 #f #f) #f)) (Node 6 (Node 4 #f #f) #f))  
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.
#Groovy
Groovy
class PostfixToInfix { static class Expression { final static String ops = "-+/*^"   String op, ex int precedence = 3   Expression(String e) { ex = e }   Expression(String e1, String e2, String o) { ex = String.format "%s %s %s", e1, o, e2 op = o precedence = (ops.indexOf(o) / 2) as int }   @Override String toString() { return ex } }   static String postfixToInfix(final String postfix) { Stack<Expression> expr = new Stack<>()   for (String token in postfix.split("\\s+")) { char c = token.charAt(0) int idx = Expression.ops.indexOf(c as int) if (idx != -1 && token.length() == 1) {   Expression r = expr.pop() Expression l = expr.pop()   int opPrecedence = (idx / 2) as int   if (l.precedence < opPrecedence || (l.precedence == opPrecedence && c == '^' as char)) l.ex = '(' + l.ex + ')'   if (r.precedence < opPrecedence || (r.precedence == opPrecedence && c != '^' as char)) r.ex = '(' + r.ex + ')'   expr << new Expression(l.ex, r.ex, token) } else { expr << new Expression(token) } printf "%s -> %s%n", token, expr } expr.peek().ex }   static void main(String[] args) { (["3 4 2 * 1 5 - 2 3 ^ ^ / +", "1 2 + 3 4 + ^ 5 6 + ^"]).each { String e -> printf "Postfix : %s%n", e printf "Infix : %s%n", postfixToInfix(e) println() } } }
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.
#JavaScript
JavaScript
var f1 = function (x) { return x * 2; }, f2 = function (x) { return x * x; },   fs = function (f, s) { return function (s) { return s.map(f); } },   fsf1 = fs(f1), fsf2 = fs(f2);   // Test [ fsf1([0, 1, 2, 3]), fsf2([0, 1, 2, 3]),   fsf1([2, 4, 6, 8]), fsf2([2, 4, 6, 8]) ]
http://rosettacode.org/wiki/Partition_an_integer_x_into_n_primes
Partition an integer x into n primes
Task Partition a positive integer   X   into   N   distinct primes. Or, to put it in another way: Find   N   unique primes such that they add up to   X. Show in the output section the sum   X   and the   N   primes in ascending order separated by plus (+) signs: •   partition 99809 with 1 prime. •   partition 18 with 2 primes. •   partition 19 with 3 primes. •   partition 20 with 4 primes. •   partition 2017 with 24 primes. •   partition 22699 with 1, 2, 3, and 4 primes. •   partition 40355 with 3 primes. The output could/should be shown in a format such as: Partitioned 19 with 3 primes: 3+5+11   Use any spacing that may be appropriate for the display.   You need not validate the input(s).   Use the lowest primes possible;   use  18 = 5+13,   not   18 = 7+11.   You only need to show one solution. This task is similar to factoring an integer. Related tasks   Count in factors   Prime decomposition   Factors of an integer   Sieve of Eratosthenes   Primality by trial division   Factors of a Mersenne number   Factors of a Mersenne number   Sequence of primes by trial division
#REXX
REXX
/*REXX program partitions integer(s) (greater than unity) into N primes. */ parse arg what /*obtain an optional list from the C.L.*/   do until what=='' /*possibly process a series of integers*/ parse var what x n what; parse var x x '-' y /*get possible range and # partitions.*/ parse var n n '-' m /* " " " " " " */ if x=='' | x=="," then x= 19 /*Not specified? Then use the default.*/ if y=='' | y=="," then y= x /* " " " " " " */ if n=='' | n=="," then n= 3 /* " " " " " " */ if m=='' | m=="," then m= n /* " " " " " " */ call genP y /*generate Y number of primes. */ do g=x to y /*partition X ───► Y into partitions.*/ do q=n to m; call part /* " G into Q primes. */ end /*q*/ end /*g*/ end /*until*/   exit 0 /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ genP: arg high; @.1= 2; @.2= 3; #= 2 /*get highest prime, assign some vars. */ do j=@.#+2 by 2 until @.#>high /*only find odd primes from here on. */ do k=2 while k*k<=j /*divide by some known low odd primes. */ if j // @.k==0 then iterate j /*Is J divisible by P? Then ¬ prime.*/ end /*k*/ /* [↓] a prime (J) has been found. */ #= # + 1; @.#= j /*bump prime count; assign prime to @.*/ end /*j*/; return /*──────────────────────────────────────────────────────────────────────────────────────*/ getP: procedure expose i. p. @.; parse arg z /*bump the prime in the partition list.*/ if i.z==0 then do; _= z - 1; i.z= i._; end i.z= i.z + 1; _= i.z; p.z= @._; return 0 /*──────────────────────────────────────────────────────────────────────────────────────*/ list: _= p.1; if $==g then do j=2 to q; _= _ p.j end /*j*/ else _= '__(not_possible)' return 'prime' || word("s", 1 + (q==1)) translate(_, '+ ', " _") /*plural? */ /*──────────────────────────────────────────────────────────────────────────────────────*/ part: i.= 0; do j=1 for q; call getP j end /*j*/   do !=0 by 0; $= 0 /*!: a DO variable for LEAVE & ITERATE*/ do s=1 for q; $= $ + p.s /* [↓] is sum of the primes too large?*/ if $>g then do; if s==1 then leave ! /*perform a quick exit?*/ do k=s to q; i.k= 0; end /*k*/ do r=s-1 to q; call getP r; end /*r*/ iterate ! end end /*s*/ if $==g then leave /*is sum of the primes exactly right ? */ if $ <g then do; call getP q; iterate; end end /*!*/ /* [↑] Is sum too low? Bump a prime.*/ say 'partitioned' center(g,9) "into" center(q, 5) list() return
http://rosettacode.org/wiki/Pascal%27s_triangle/Puzzle
Pascal's triangle/Puzzle
This puzzle involves a Pascals Triangle, also known as a Pyramid of Numbers. [ 151] [ ][ ] [40][ ][ ] [ ][ ][ ][ ] [ X][11][ Y][ 4][ Z] Each brick of the pyramid is the sum of the two bricks situated below it. Of the three missing numbers at the base of the pyramid, the middle one is the sum of the other two (that is, Y = X + Z). Task Write a program to find a solution to this puzzle.
#Python
Python
# Pyramid solver # [151] # [ ] [ ] # [ 40] [ ] [ ] # [ ] [ ] [ ] [ ] #[ X ] [ 11] [ Y ] [ 4 ] [ Z ] # X -Y + Z = 0   def combine( snl, snr ):   cl = {} if isinstance(snl, int): cl['1'] = snl elif isinstance(snl, string): cl[snl] = 1 else: cl.update( snl)   if isinstance(snr, int): n = cl.get('1', 0) cl['1'] = n + snr elif isinstance(snr, string): n = cl.get(snr, 0) cl[snr] = n + 1 else: for k,v in snr.items(): n = cl.get(k, 0) cl[k] = n+v return cl     def constrain(nsum, vn ): nn = {} nn.update(vn) n = nn.get('1', 0) nn['1'] = n - nsum return nn   def makeMatrix( constraints ): vmap = set() for c in constraints: vmap.update( c.keys()) vmap.remove('1') nvars = len(vmap) vmap = sorted(vmap) # sort here so output is in sorted order mtx = [] for c in constraints: row = [] for vv in vmap: row.append(float(c.get(vv, 0))) row.append(-float(c.get('1',0))) mtx.append(row)   if len(constraints) == nvars: print 'System appears solvable' elif len(constraints) < nvars: print 'System is not solvable - needs more constraints.' return mtx, vmap     def SolvePyramid( vl, cnstr ):   vl.reverse() constraints = [cnstr] lvls = len(vl) for lvln in range(1,lvls): lvd = vl[lvln] for k in range(lvls - lvln): sn = lvd[k] ll = vl[lvln-1] vn = combine(ll[k], ll[k+1]) if sn is None: lvd[k] = vn else: constraints.append(constrain( sn, vn ))   print 'Constraint Equations:' for cstr in constraints: fset = ('%d*%s'%(v,k) for k,v in cstr.items() ) print ' + '.join(fset), ' = 0'   mtx,vmap = makeMatrix(constraints)   MtxSolve(mtx)   d = len(vmap) for j in range(d): print vmap[j],'=', mtx[j][d]     def MtxSolve(mtx): # Simple Matrix solver...   mDim = len(mtx) # dimension--- for j in range(mDim): rw0= mtx[j] f = 1.0/rw0[j] for k in range(j, mDim+1): rw0[k] *= f   for l in range(1+j,mDim): rwl = mtx[l] f = -rwl[j] for k in range(j, mDim+1): rwl[k] += f * rw0[k]   # backsolve part --- for j1 in range(1,mDim): j = mDim - j1 rw0= mtx[j] for l in range(0, j): rwl = mtx[l] f = -rwl[j] rwl[j] += f * rw0[j] rwl[mDim] += f * rw0[mDim]   return mtx     p = [ [151], [None,None], [40,None,None], [None,None,None,None], ['X', 11, 'Y', 4, 'Z'] ] addlConstraint = { 'X':1, 'Y':-1, 'Z':1, '1':0 } SolvePyramid( p, addlConstraint)
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
#OCaml
OCaml
let lower = "abcdefghijklmnopqrstuvwxyz" let upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" let digit = "0123456789" let other = "!\034#$%&'()*+,-./:;<=>?@[]^_{|}~"   let visually_similar = "Il1O05S2Z"     let mk_pwd len readable = let get_char i = match i mod 4 with | 0 -> lower.[Random.int (String.length lower)] | 1 -> upper.[Random.int (String.length upper)] | 2 -> digit.[Random.int (String.length digit)] | 3 -> other.[Random.int (String.length other)] | _ -> raise Exit in let f = if readable then (fun i -> let rec aux () = let c = get_char i in if String.contains visually_similar c then aux () else (String.make 1 c) in aux () ) else (fun i -> let c = get_char i in (String.make 1 c) ) in let r = Array.init len f in Array.sort (fun _ _ -> (Random.int 3) - 1) r; (String.concat "" (Array.to_list r))     let () = Random.self_init (); let num = ref 1 in let len = ref 8 in let readable = ref false in let speclist = [ "-n", Arg.Set_int num, "number of passwords"; "-c", Arg.Set_int len, "number of characters"; "--readable", Arg.Set readable, "readable"; "--rand-init", Arg.String (fun s -> Random.full_init (Array.map int_of_char (Array.of_seq (String.to_seq s))) ), "initialise the random generator with a string"; ] in Arg.parse speclist (fun s -> invalid_arg s) "Password generator"; for i = 1 to !num do print_endline (mk_pwd !len !readable) done
http://rosettacode.org/wiki/Permutations
Permutations
Task Write a program that generates all   permutations   of   n   different objects.   (Practically numerals!) Related tasks   Find the missing permutation   Permutations/Derangements The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Unimportant Order Important Without replacement ( n k ) = n C k = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} Task: Combinations Task: Permutations With replacement ( n + k − 1 k ) = n + k − 1 C k = ( n + k − 1 ) ! ( n − 1 ) ! k ! {\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}} n k {\displaystyle n^{k}} Task: Combinations with repetitions Task: Permutations with repetitions
#VBScript
VBScript
  'permutation ,recursive a=array("Hello",1,True,3.141592) cnt=0 perm a,0 wscript.echo vbcrlf &"Count " & cnt   sub print(a) s="" for i=0 to ubound(a): s=s &" " & a(i): next: wscript.echo s : cnt=cnt+1 : end sub sub swap(a,b) t=a: a=b :b=t: end sub   sub perm(byval a,i) if i=ubound(a) then print a: exit sub for j= i to ubound(a) swap a(i),a(j) perm a,i+1 swap a(i),a(j) next end sub  
http://rosettacode.org/wiki/Pathological_floating_point_problems
Pathological floating point problems
Most programmers are familiar with the inexactness of floating point calculations in a binary processor. The classic example being: 0.1 + 0.2 = 0.30000000000000004 In many situations the amount of error in such calculations is very small and can be overlooked or eliminated with rounding. There are pathological problems however, where seemingly simple, straight-forward calculations are extremely sensitive to even tiny amounts of imprecision. This task's purpose is to show how your language deals with such classes of problems. A sequence that seems to converge to a wrong limit. Consider the sequence: v1 = 2 v2 = -4 vn = 111   -   1130   /   vn-1   +   3000  /   (vn-1 * vn-2) As   n   grows larger, the series should converge to   6   but small amounts of error will cause it to approach   100. Task 1 Display the values of the sequence where   n =   3, 4, 5, 6, 7, 8, 20, 30, 50 & 100   to at least 16 decimal places. n = 3 18.5 n = 4 9.378378 n = 5 7.801153 n = 6 7.154414 n = 7 6.806785 n = 8 6.5926328 n = 20 6.0435521101892689 n = 30 6.006786093031205758530554 n = 50 6.0001758466271871889456140207471954695237 n = 100 6.000000019319477929104086803403585715024350675436952458072592750856521767230266 Task 2 The Chaotic Bank Society   is offering a new investment account to their customers. You first deposit   $e - 1   where   e   is   2.7182818...   the base of natural logarithms. After each year, your account balance will be multiplied by the number of years that have passed, and $1 in service charges will be removed. So ... after 1 year, your balance will be multiplied by 1 and $1 will be removed for service charges. after 2 years your balance will be doubled and $1 removed. after 3 years your balance will be tripled and $1 removed. ... after 10 years, multiplied by 10 and $1 removed, and so on. What will your balance be after   25   years? Starting balance: $e-1 Balance = (Balance * year) - 1 for 25 years Balance after 25 years: $0.0399387296732302 Task 3, extra credit Siegfried Rump's example.   Consider the following function, designed by Siegfried Rump in 1988. f(a,b) = 333.75b6 + a2( 11a2b2 - b6 - 121b4 - 2 ) + 5.5b8 + a/(2b) compute   f(a,b)   where   a=77617.0   and   b=33096.0 f(77617.0, 33096.0)   =   -0.827396059946821 Demonstrate how to solve at least one of the first two problems, or both, and the third if you're feeling particularly jaunty. See also;   Floating-Point Arithmetic   Section 1.3.2 Difficult problems.
#Wren
Wren
import "/big" for BigRat import "/fmt" for Fmt   var LIMIT = 100 var bigE = BigRat.fromDecimal("2.71828182845904523536028747135266249775724709369995")   // v(n) sequence task var c1 = BigRat.new(111) var c2 = BigRat.new(1130) var c3 = BigRat.new(3000) var v1 = BigRat.two var v2 = BigRat.new(-4) for (i in 3..LIMIT) { var v3 = c1 - c2/v2 + c3/(v2*v1) Fmt.print("$3d : $19s", i, v3.toDecimal(16, true, true)) v1 = v2 v2 = v3 }   // Chaotic Building Society task var balance = bigE - 1 for (year in 1..25) balance = balance * year - 1 System.print("\nBalance after 25 years is %(balance.toDecimal(16))")   // Siegfried Rump task var a = BigRat.new(77617) var b = BigRat.new(33096) var c4 = BigRat.new(33375, 100) var c5 = BigRat.new(11) var c6 = BigRat.new(121) var c7 = BigRat.new(11, 2) var f = c4 * b.pow(6) + c7 * b.pow(8) + a/(b*2) var c8 = c5 * a.pow(2) * b.pow(2) - b.pow(6) - c6 * b.pow(4) - 2 f = f + c8 * a.pow(2) System.print("\nf(77617.0, 33096.0) is %(f.toDecimal(16))")
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
#Erlang
Erlang
  #! /usr/bin/escript -mode(compile). -export([cracker/4, supervisor/3]).   hexdigit(N) when (N >= 0) and (N =< 9) -> N + $0; hexdigit(N) when (N >= 10) and (N < 16) -> N - 10 + $a.   hexbyte(N) -> [hexdigit(N bsr 4), hexdigit(N band 15)].   match(Key, Hash) -> B = crypto:hash(sha256, Key), Hash == lists:append([hexbyte(X) || <<X:8/integer>> <= B]).   cracker(Prefixes, Rest, Hashes, Boss) -> Results = [[[P|Q], Hash] || P <- Prefixes, Q <- Rest, Hash <- Hashes, match([P|Q], Hash)], Boss ! {done, Results}.   supervisor(0, Results, Caller) -> Caller ! {done, Results}; supervisor(Tasks, Results, Caller) -> receive {done, Cracked} -> supervisor(Tasks - 1, Cracked ++ Results, Caller) end.   main(_) -> Tasks = ["abc", "def", "ghi", "jkl", "mno", "pqr", "stuv", "wxyz"], Letter = lists:seq($a, $z), Rest = [[B, C, D, E] || B <- Letter, C <- Letter, D <- Letter, E <- Letter], Hashes = [ "1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad", "3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b", "74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f" ], Boss = spawn(?MODULE, supervisor, [length(Tasks), [], self()]), [spawn(?MODULE, cracker, [Prefixes, Rest, Hashes, Boss]) || Prefixes <- Tasks],   receive {done, Results} -> Results end,   [io:format("~s: ~s~n", Result) || Result <- Results].  
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.
#Fortran
Fortran
  program Primes   use ISO_FORTRAN_ENV   implicit none   integer(int64), dimension(7) :: data = (/2099726827, 15780709, 1122725370, 15808973, 576460741, 12878611, 12757923/) integer(int64), dimension(100) :: outprimes integer(int64) :: largest_factor = 0, largest = 0, minim = 0, val = 0 integer(int16) :: count = 0, OMP_GET_THREAD_NUM   call omp_set_num_threads(4); !$omp parallel do private(val,outprimes,count) shared(data,largest_factor,largest) do val = 1, 7 outprimes = 0 call find_factors(data(val), outprimes, count) minim = minval(outprimes(1:count)) if (minim > largest_factor) then largest_factor = minim largest = data(val) end if write(*, fmt = '(A7,i0,A2,i12,100i12)') 'Thread ', OMP_GET_THREAD_NUM(), ': ', data(val), outprimes(1:count) end do !$omp end parallel do   write(*, fmt = '(i0,A26,i0)') largest, ' have the Largest factor: ', largest_factor   return   contains   subroutine find_factors(n, d, count) integer(int64), intent(in) :: n integer(int64), dimension(:), intent(out) :: d integer(int16), intent(out) :: count integer(int16) :: i integer(int64) :: div, next, rest   i = 1 div = 2; next = 3; rest = n   do while (rest /= 1) do while (mod(rest, div) == 0) d(i) = div i = i + 1 rest = rest / div end do div = next next = next + 2 end do count = i - 1 end subroutine find_factors   end program Primes  
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.
#Ceylon
Ceylon
import ceylon.collection {   ArrayList }   shared void run() {   value ops = map { "+" -> plus<Float>, "*" -> times<Float>, "-" -> ((Float a, Float b) => a - b), "/" -> ((Float a, Float b) => a / b), "^" -> ((Float a, Float b) => a ^ b) };   void printTableRow(String|Float token, String description, {Float*} stack) { print("``token.string.padTrailing(8)````description.padTrailing(30)````stack``"); }   function calculate(String input) {   value stack = ArrayList<Float>(); value tokens = input.split().map((String element) => if(ops.keys.contains(element)) then element else parseFloat(element));   print("Token Operation Stack");   for(token in tokens.coalesced) { if(is Float token) { stack.push(token); printTableRow(token, "push", stack); } else if(exists op = ops[token], exists first = stack.pop(), exists second = stack.pop()) { value result = op(second, first); stack.push(result); printTableRow(token, "perform ``token`` on ``formatFloat(second, 1, 1)`` and ``formatFloat(first, 1, 1)``", stack); } else { throw Exception("bad syntax"); } } return stack.pop(); }   print(calculate("3 4 2 * 1 5 - 2 3 ^ ^ / +")); }
http://rosettacode.org/wiki/Pancake_numbers
Pancake numbers
Adrian Monk has problems and an assistant, Sharona Fleming. Sharona can deal with most of Adrian's problems except his lack of punctuality paying her remuneration. 2 pay checks down and she prepares him pancakes for breakfast. Knowing that he will be unable to eat them unless they are stacked in ascending order of size she leaves him only a skillet which he can insert at any point in the pile and flip all the above pancakes, repeating until the pile is sorted. Sharona has left the pile of n pancakes such that the maximum number of flips is required. Adrian is determined to do this in as few flips as possible. This sequence n->p(n) is known as the Pancake numbers. The task is to determine p(n) for n = 1 to 9, and for each show an example requiring p(n) flips. Sorting_algorithms/Pancake_sort actually performs the sort some giving the number of flips used. How do these compare with p(n)? Few people know p(20), generously I shall award an extra credit for anyone doing more than p(16). References Bill Gates and the pancake problem A058986
#Phix
Phix
with javascript_semantics function pancake(integer n) integer gap = 2, sum_gaps = gap, adj = -1 while sum_gaps<n do adj += 1 gap = gap*2-1 sum_gaps += gap end while n += adj return n end function sequence t = tagset(20), r = columnize({t,apply(t,pancake)}), p = apply(true,sprintf,{{"p(%2d) = %2d"},r}) printf(1,"%s\n",join_by(p,1,5))
http://rosettacode.org/wiki/Pancake_numbers
Pancake numbers
Adrian Monk has problems and an assistant, Sharona Fleming. Sharona can deal with most of Adrian's problems except his lack of punctuality paying her remuneration. 2 pay checks down and she prepares him pancakes for breakfast. Knowing that he will be unable to eat them unless they are stacked in ascending order of size she leaves him only a skillet which he can insert at any point in the pile and flip all the above pancakes, repeating until the pile is sorted. Sharona has left the pile of n pancakes such that the maximum number of flips is required. Adrian is determined to do this in as few flips as possible. This sequence n->p(n) is known as the Pancake numbers. The task is to determine p(n) for n = 1 to 9, and for each show an example requiring p(n) flips. Sorting_algorithms/Pancake_sort actually performs the sort some giving the number of flips used. How do these compare with p(n)? Few people know p(20), generously I shall award an extra credit for anyone doing more than p(16). References Bill Gates and the pancake problem A058986
#Python
Python
"""Pancake numbers. Requires Python>=3.7.""" import time   from collections import deque from operator import itemgetter from typing import Tuple   Pancakes = Tuple[int, ...]     def flip(pancakes: Pancakes, position: int) -> Pancakes: """Flip the stack of pancakes at the given position.""" return tuple([*reversed(pancakes[:position]), *pancakes[position:]])     def pancake(n: int) -> Tuple[Pancakes, int]: """Return the nth pancake number.""" init_stack = tuple(range(1, n + 1)) stack_flips = {init_stack: 0} queue = deque([init_stack])   while queue: stack = queue.popleft() flips = stack_flips[stack] + 1   for i in range(2, n + 1): flipped = flip(stack, i) if flipped not in stack_flips: stack_flips[flipped] = flips queue.append(flipped)   return max(stack_flips.items(), key=itemgetter(1))     if __name__ == "__main__": start = time.time()   for n in range(1, 10): pancakes, p = pancake(n) print(f"pancake({n}) = {p:>2}. Example: {list(pancakes)}")   print(f"\nTook {time.time() - start:.3} seconds.")  
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.
#C
C
#include <stdbool.h> #include <stdio.h> #include <stdint.h>   typedef uint64_t integer;   integer reverse(integer n) { integer rev = 0; while (n > 0) { rev = rev * 10 + (n % 10); n /= 10; } return rev; }   typedef struct palgen_tag { integer power; integer next; int digit; bool even; } palgen_t;   void init_palgen(palgen_t* palgen, int digit) { palgen->power = 10; palgen->next = digit * palgen->power - 1; palgen->digit = digit; palgen->even = false; }   integer next_palindrome(palgen_t* p) { ++p->next; if (p->next == p->power * (p->digit + 1)) { if (p->even) p->power *= 10; p->next = p->digit * p->power; p->even = !p->even; } return p->next * (p->even ? 10 * p->power : p->power) + reverse(p->even ? p->next : p->next/10); }   bool gapful(integer n) { integer m = n; while (m >= 10) m /= 10; return n % (n % 10 + 10 * m) == 0; }   void print(int len, integer array[][len]) { for (int digit = 1; digit < 10; ++digit) { printf("%d: ", digit); for (int i = 0; i < len; ++i) printf(" %llu", array[digit - 1][i]); printf("\n"); } }   int main() { const int n1 = 20, n2 = 15, n3 = 10; const int m1 = 100, m2 = 1000;   integer pg1[9][n1]; integer pg2[9][n2]; integer pg3[9][n3];   for (int digit = 1; digit < 10; ++digit) { palgen_t pgen; init_palgen(&pgen, digit); for (int i = 0; i < m2; ) { integer n = next_palindrome(&pgen); if (!gapful(n)) continue; if (i < n1) pg1[digit - 1][i] = n; else if (i < m1 && i >= m1 - n2) pg2[digit - 1][i - (m1 - n2)] = n; else if (i >= m2 - n3) pg3[digit - 1][i - (m2 - n3)] = n; ++i; } }   printf("First %d palindromic gapful numbers ending in:\n", n1); print(n1, pg1);   printf("\nLast %d of first %d palindromic gapful numbers ending in:\n", n2, m1); print(n2, pg2);   printf("\nLast %d of first %d palindromic gapful numbers ending in:\n", n3, m2); print(n3, pg3);   return 0; }