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/Pell%27s_equation
Pell's equation
Pell's equation   (also called the Pell–Fermat equation)   is a   Diophantine equation   of the form: x2   -   ny2   =   1 with integer solutions for   x   and   y,   where   n   is a given non-square positive integer. Task requirements   find the smallest solution in positive integers to Pell's equation for   n = {61, 109, 181, 277}. See also   Wikipedia entry: Pell's equation.
#Sidef
Sidef
func solve_pell(n) {   var x = n.isqrt var y = x var z = 1 var r = 2*x   var (e1, e2) = (1, 0) var (f1, f2) = (0, 1)   loop {   y = (r*z - y) z = floor((n - y*y) / z) r = floor((x + y) / z)   (e1, e2) = (e2, r*e2 + e1) (f1, f2) = (f2, r*f2 + f1)   var A = (e2 + x*f2) var B = f2   if (A**2 - n*B**2 == 1) { return (A, B) } } }   for n in [61, 109, 181, 277] { var (x, y) = solve_pell(n) printf("x^2 - %3d*y^2 = 1 for x = %-21s and y = %s\n", n, x, y) }
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.
#11l
11l
F pascal_upp(n) V s = [[0] * n] * n s[0] = [1] * n L(i) 1 .< n L(j) i .< n s[i][j] = s[i - 1][j - 1] + s[i][j - 1] R s   F pascal_low(n) V upp = pascal_upp(n) V s = [[0] * n] * n L(x) 0 .< n L(y) 0 .< n s[y][x] = upp[x][y] R s   F pascal_sym(n) V s = [[1] * n] * n L(i) 1 .< n L(j) 1 .< n s[i][j] = s[i - 1][j] + s[i][j - 1] R s   F pp(mat) print(‘[’mat.map(String).join(",\n ")‘]’)   -V n = 5 print(‘Upper:’) pp(pascal_upp(n)) print("\nLower:") pp(pascal_low(n)) print("\nSymmetric:") pp(pascal_sym(n))
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
#11l
11l
F pascal(n) V row = [1] V k = [0] L 0 .< max(n, 0) print(row.join(‘ ’).center(16)) row = zip(row [+] k, k [+] row).map((l, r) -> l + r)   pascal(7)
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.
#11l
11l
F partial(f, g) F fg(x) R @f(@g, x) R fg   F main() F ffs(f, x) R x.map(a -> @f(a)) F f1(a) {R a * 2} F f2(a) {R a * a}   V fsf1 = partial(ffs, f1) V fsf2 = partial(ffs, f2)   print(fsf1([1, 2, 3, 4])) print(fsf2([1, 2, 3, 4]))   main()
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
#C.2B.2B
C++
#include <algorithm> #include <functional> #include <iostream> #include <vector>   std::vector<int> primes;   struct Seq { public: bool empty() { return p < 0; }   int front() { return p; }   void popFront() { if (p == 2) { p++; } else { p += 2; while (!empty() && !isPrime(p)) { p += 2; } } }   private: int p = 2;   bool isPrime(int n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3;   int d = 5; while (d * d <= n) { if (n % d == 0) return false; d += 2; if (n % d == 0) return false; d += 4; } return true; } };   // generate the first 50,000 primes and call it good void init() { Seq seq;   while (!seq.empty() && primes.size() < 50000) { primes.push_back(seq.front()); seq.popFront(); } }   bool findCombo(int k, int x, int m, int n, std::vector<int>& combo) { if (k >= m) { int sum = 0; for (int idx : combo) { sum += primes[idx]; }   if (sum == x) { auto word = (m > 1) ? "primes" : "prime"; printf("Partitioned %5d with %2d %s ", x, m, word); for (int idx = 0; idx < m; ++idx) { std::cout << primes[combo[idx]]; if (idx < m - 1) { std::cout << '+'; } else { std::cout << '\n'; } } return true; } } else { for (int j = 0; j < n; j++) { if (k == 0 || j > combo[k - 1]) { combo[k] = j; bool foundCombo = findCombo(k + 1, x, m, n, combo); if (foundCombo) { return true; } } } }   return false; }   void partition(int x, int m) { if (x < 2 || m < 1 || m >= x) { throw std::runtime_error("Invalid parameters"); }   std::vector<int> filteredPrimes; std::copy_if( primes.cbegin(), primes.cend(), std::back_inserter(filteredPrimes), [x](int a) { return a <= x; } );   int n = filteredPrimes.size(); if (n < m) { throw std::runtime_error("Not enough primes"); }   std::vector<int> combo; combo.resize(m); if (!findCombo(0, x, m, n, combo)) { auto word = (m > 1) ? "primes" : "prime"; printf("Partitioned %5d with %2d %s: (not possible)\n", x, m, word); } }   int main() { init();   std::vector<std::pair<int, int>> a{ {99809, 1}, { 18, 2}, { 19, 3}, { 20, 4}, { 2017, 24}, {22699, 1}, {22699, 2}, {22699, 3}, {22699, 4}, {40355, 3} };   for (auto& p : a) { partition(p.first, p.second); }   return 0; }
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
#F.23
F#
  // PartionP: Nigel Galloway. April 12th., 2021 let pP g=let rec fN i g e l=seq{yield(l,e+i);yield(-l,e+i+g);yield! fN(i+1)(g+2)(e+i+g)(-l)} let N,G=Array.create(g+1) 1I,seq{yield (1I,1);yield! fN 1 3 1 1I}|>Seq.takeWhile(fun(_,n)->n<=g)|>List.ofSeq seq{2..g}|>Seq.iter(fun p->N.[p]<-G|>List.takeWhile(fun(_,n)->n<=p)|>Seq.fold(fun Σ (n,g)->Σ+n*N.[p-g]) 0I); N.[g] printfn "666->%A\n\n6666->%A\n\n123456->%A" (pP 666) pP(6666) (pP 123456)  
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
#Factor
Factor
USING: kernel lists lists.lazy math sequences sequences.extras ;   ! Compute the nth pentagonal number. : penta ( n -- m ) [ sq 3 * ] [ - 2/ ] bi ;   ! An infinite lazy list of indices to add and subtract in the ! sequence of partitions to find the next P. : seq ( -- list ) 1 lfrom [ penta 1 - ] <lazy-map> 1 lfrom [ neg penta 1 - ] <lazy-map> lmerge ;   ! Reduce a sequence by adding two, subtracting two, adding two, ! etc... : ++-- ( seq -- n ) 0 [ 2/ odd? [ - ] [ + ] if ] reduce-index ;   ! Find the next member of the partitions sequence. : step ( seq pseq -- seq 'pseq ) dup length [ < ] curry pick swap take-while over <reversed> nths ++-- suffix! ;   : partitions ( m -- n ) [ seq swap [ <= ] curry lwhile list>array ] [ V{ 1 } clone swap [ step ] times last nip ] bi ;
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.
#Clojure
Clojure
(def bottom [ [0 1 0], [11 0 0], [0 1 1], [4 0 0], [0 0 1] ])   (defn plus [v1 v2] (vec (map + v1 v2))) (defn minus [v1 v2] (vec (map - v1 v2))) (defn scale [n v] (vec (map #(* n %) v )))   (defn above [row] (map #(apply plus %) (partition 2 1 row)))   (def rows (reverse (take 5 (iterate above bottom))))
http://rosettacode.org/wiki/Peaceful_chess_queen_armies
Peaceful chess queen armies
In chess, a queen attacks positions from where it is, in straight lines up-down and left-right as well as on both its diagonals. It attacks only pieces not of its own colour. ⇖ ⇑ ⇗ ⇐ ⇐ ♛ ⇒ ⇒ ⇙ ⇓ ⇘ ⇙ ⇓ ⇘ ⇓ The goal of Peaceful chess queen armies is to arrange m black queens and m white queens on an n-by-n square grid, (the board), so that no queen attacks another of a different colour. Task Create a routine to represent two-colour queens on a 2-D board. (Alternating black/white background colours, Unicode chess pieces and other embellishments are not necessary, but may be used at your discretion). Create a routine to generate at least one solution to placing m equal numbers of black and white queens on an n square board. Display here results for the m=4, n=5 case. References Peaceably Coexisting Armies of Queens (Pdf) by Robert A. Bosch. Optima, the Mathematical Programming Socity newsletter, issue 62. A250000 OEIS
#Julia
Julia
using Gtk   struct Position row::Int col::Int end   function place!(numeach, bsize, bqueens, wqueens) isattack(q, pos) = (q.row == pos.row || q.col == pos.col || abs(q.row - pos.row) == abs(q.col - pos.col)) noattack(qs, pos) = !any(x -> isattack(x, pos), qs) positionopen(bqs, wqs, p) = !any(x -> x == p, bqs) && !any(x -> x == p, wqs)   placingbqueens = true if numeach < 1 return true end for i in 1:bsize, j in 1:bsize bpos = Position(i, j) if positionopen(bqueens, wqueens, bpos) if placingbqueens && noattack(wqueens, bpos) push!(bqueens, bpos) placingbqueens = false elseif !placingbqueens && noattack(bqueens, bpos) push!(wqueens, bpos) if place!(numeach - 1, bsize, bqueens, wqueens) return true end pop!(bqueens) pop!(wqueens) placingbqueens = true end end end if !placingbqueens pop!(bqueens) end false end   function peacefulqueenapp() win = GtkWindow("Peaceful Chess Queen Armies", 800, 800) |> (GtkFrame() |> (box = GtkBox(:v))) boardsize = 5 numqueenseach = 4 hbox = GtkBox(:h) boardscale = GtkScale(false, 2:16) set_gtk_property!(boardscale, :hexpand, true) blabel = GtkLabel("Choose Board Size") nqueenscale = GtkScale(false, 1:24) set_gtk_property!(nqueenscale, :hexpand, true) qlabel = GtkLabel("Choose Number of Queens Per Side") solveit = GtkButton("Solve") set_gtk_property!(solveit, :label, " Solve ") solvequeens(wid) = (boardsize = Int(GAccessor.value(boardscale)); numqueenseach = Int(GAccessor.value(nqueenscale)); update!()) signal_connect(solvequeens, solveit, :clicked) map(w->push!(hbox, w),[blabel, boardscale, qlabel, nqueenscale, solveit]) scrwin = GtkScrolledWindow() grid = GtkGrid() push!(scrwin, grid) map(w -> push!(box, w),[hbox, scrwin]) piece = (white = "\u2655", black = "\u265B", blank = " ") stylist = GtkStyleProvider(Gtk.CssProviderLeaf(data=""" label {background-image: image(cornsilk); font-size: 48px;} button {background-image: image(tan); font-size: 48px;}"""))   function update!() bqueens, wqueens = Vector{Position}(), Vector{Position}() place!(numqueenseach, boardsize, bqueens, wqueens) if length(bqueens) == 0 warn_dialog("No solution for board size $boardsize and $numqueenseach queens each.", win) return end empty!(grid) labels = Array{Gtk.GtkLabelLeaf, 2}(undef, (boardsize, boardsize)) buttons = Array{GtkButtonLeaf, 2}(undef, (boardsize, boardsize)) for i in 1:boardsize, j in 1:boardsize if isodd(i + j) grid[i, j] = buttons[i, j] = GtkButton(piece.blank) set_gtk_property!(buttons[i, j], :expand, true) push!(Gtk.GAccessor.style_context(buttons[i, j]), stylist, 600) else grid[i, j] = labels[i, j] = GtkLabel(piece.blank) set_gtk_property!(labels[i, j], :expand, true) push!(Gtk.GAccessor.style_context(labels[i, j]), stylist, 600) end pos = Position(i, j) if pos in bqueens set_gtk_property!(grid[i, j], :label, piece.black) elseif pos in wqueens set_gtk_property!(grid[i, j], :label, piece.white) end end showall(win) end   update!() cond = Condition() endit(w) = notify(cond) signal_connect(endit, win, :destroy) showall(win) wait(cond) end   peacefulqueenapp()  
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
#Common_Lisp
Common Lisp
  (defvar *lowercase* '(#\a #\b #\c #\d #\e #\f #\g #\h #\i #\j #\k #\l #\m #\n #\o #\p #\q #\r #\s #\t #\u #\v #\w #\x #\y #\z))   (defvar *uppercase* '(#\A #\B #\C #\D #\E #\F #\G #\H #\I #\J #\K #\L #\M #\N #\O #\P #\Q #\R #\S #\T #\U #\V #\W #\X #\Y #\Z))   (defvar *numbers* '(#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9))   (defvar *special-characters* '(#\! #\\ #\# #\$ #\% #\& #\' #\( #\) #\* #\+ #\, #\- #\. #\/ #\: #\; #\< #\= #\> #\? #\@ #\[ #\] #\^ #\_ #\{ #\| #\} #\~))   (defvar *similar-characters* '(#\I #\l #\1 #\| #\O #\0 #\5 #\S #\2 #\Z))   (defun make-readable (s) (remove-if (lambda (x) (member x *similar-characters*)) s))   (defun shuffle-list (input-list) (loop with l = (length input-list) for i below l do (rotatef (nth i input-list) (nth (random l) input-list))) input-list)   (defun generate-password (len human-readable) (let* ((upper (if human-readable (make-readable *uppercase*) *uppercase*)) (lower (if human-readable (make-readable *lowercase*) *lowercase*)) (number (if human-readable (make-readable *numbers*) *numbers*)) (special (if human-readable (make-readable *special-characters*) *special-characters*)) (character-groups (list upper lower number special)) (initial-password (reduce (lambda (acc x) (cons (nth (random (length x)) x) acc)) character-groups :initial-value NIL)))   (coerce (shuffle-list (reduce (lambda (acc x) (declare (ignore x)) (let ((group (nth (random (length character-groups)) character-groups))) (cons (nth (random (length group)) group) acc))) (make-list (- len 4)) :initial-value initial-password)) 'string)))   (defun main (len count &optional human-readable) (if (< len 4) (print "Length must be at least 4~%") (loop for x from 1 to count do (print (generate-password len human-readable)))))  
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
#Ruby
Ruby
p [1,2,3].permutation.to_a
http://rosettacode.org/wiki/Peano_curve
Peano curve
Task Produce a graphical or ASCII-art representation of a Peano curve of at least order 3.
#Quackery
Quackery
[ $ "turtleduck.qky" loadfile ] now!   [ stack ] is switch.arg ( --> [ )   [ switch.arg put ] is switch ( x --> )   [ switch.arg release ] is otherwise ( --> )   [ switch.arg share  != iff ]else[ done otherwise ]'[ do ]done[ ] is case ( x --> )   [ $ "" swap witheach [ nested quackery join ] ] is expand ( $ --> $ )   [ $ "F" ] is F ( $ --> $ )   [ $ "L" ] is L ( $ --> $ )   [ $ "R" ] is R ( $ --> $ )   [ $ "AFBFARFRBFAFBLFLAFBFA" ] is A ( $ --> $ )   [ $ "BFAFBLFLAFBFARFRBFAFB" ] is B ( $ --> $ )   $ "A"   4 times expand   turtle witheach [ switch [ char F case [ 4 1 walk ] char L case [ -1 4 turn ] char R case [ 1 4 turn ] otherwise ( ignore ) ] ]
http://rosettacode.org/wiki/Peano_curve
Peano curve
Task Produce a graphical or ASCII-art representation of a Peano curve of at least order 3.
#R
R
  #to install hilbercurve library, biocmanager needs to be installed first install.packages("BiocManager") BiocManager::install("HilbertCurve") #loading library and setting seed for random numbers library(HilbertCurve) library(circlize) set.seed(123)   #4th order peano curve is generated for(i in 1:512) { peano = HilbertCurve(1, 512, level = 4, reference = TRUE, arrow = FALSE) hc_points(peano, x1 = i, np = NULL, pch = 16, size = unit(3, "mm")) }
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).
#Lua
Lua
  function penny_game() local player, computer = "", "" function player_choose() io.write( "Enter your sequence of three H and/or T: " ) local t = io.read():upper() if #t > 3 then t = t:sub( 1, 3 ) elseif #t < 3 then return "" end   for i = 1, 3 do c = t:sub( i, i ) if c ~= "T" and c ~= "H" then print( "Just H's and T's!" ) return "" end end return t end function computer_choose() local t = "" if #player > 0 then if player:sub( 2, 2 ) == "T" then t = "H" else t = "T"; end t = t .. player:sub( 1, 2 ) else for i = 1, 3 do if math.random( 2 ) == 1 then t = t .. "H" else t = t .. "T" end end end return t end if math.random( 2 ) == 1 then computer = computer_choose() io.write( "My sequence is: " .. computer .. "\n" ) while( true ) do player = player_choose() if player:len() == 3 then break end end else while( true ) do player = player_choose() if player:len() == 3 then break end end computer = computer_choose() io.write( "My sequence is: " .. computer .. "\n" ) end local coin, i = "", 1 while( true ) do if math.random( 2 ) == 1 then coin = coin .. "T" io.write( "T" ) else coin = coin .. "H" io.write( "H" ) end if #coin > 2 then local seq = coin:sub( i, i + 2 ) i = i + 1 if seq == player then print( "\nPlayer WINS!!!" ) return 1 elseif seq == computer then print( "\nComputer WINS!!!" ) return -1 end end end end math.randomseed( os.time() ) local cpu, user = 0, 0 repeat r = penny_game() if r > 0 then user = user + 1 else cpu = cpu + 1 end print( "Player: " .. user .. " CPU: " .. cpu ) io.write( "Play again (Y/N)? " ) r = io.read() until( r == "N" or r == "n" )  
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.
#jq
jq
# Input: the value at which to compute v def v: # Input: cache # Output: updated cache def v_(n): (n|tostring) as $s | . as $cache | if ($cache | has($s)) then . else if n == 1 then $cache["1"] = 2 elif n == 2 then $cache["2"] = -4 else ($cache | v_(n-1) | v_(n - 2)) as $new | $new[(n-1)|tostring] as $x | $new[(n-2)|tostring] as $y | $new + {($s): ((111 - (1130 / $x) + (3000 / ($x * $y)))) } end end; . as $m | {} | v_($m) | .[($m|tostring)] ;
http://rosettacode.org/wiki/Pell%27s_equation
Pell's equation
Pell's equation   (also called the Pell–Fermat equation)   is a   Diophantine equation   of the form: x2   -   ny2   =   1 with integer solutions for   x   and   y,   where   n   is a given non-square positive integer. Task requirements   find the smallest solution in positive integers to Pell's equation for   n = {61, 109, 181, 277}. See also   Wikipedia entry: Pell's equation.
#Swift
Swift
func solvePell<T: BinaryInteger>(n: T, _ a: inout T, _ b: inout T) { func swap(_ a: inout T, _ b: inout T, mul by: T) { (a, b) = (b, b * by + a) }   let x = T(Double(n).squareRoot()) var y = x var z = T(1) var r = x << 1 var e1 = T(1) var e2 = T(0) var f1 = T(0) var f2 = T(1)   while true { y = r * z - y z = (n - y * y) / z r = (x + y) / z   swap(&e1, &e2, mul: r) swap(&f1, &f2, mul: r)   (a, b) = (f2, e2)   swap(&b, &a, mul: x)   if a * a - n * b * b == 1 { return } } }   var x = BigInt(0) var y = BigInt(0)   for n in [61, 109, 181, 277] { solvePell(n: BigInt(n), &x, &y)   print("x\u{00b2} - \(n)y\u{00b2} = 1 for x = \(x) and y = \(y)") }
http://rosettacode.org/wiki/Pell%27s_equation
Pell's equation
Pell's equation   (also called the Pell–Fermat equation)   is a   Diophantine equation   of the form: x2   -   ny2   =   1 with integer solutions for   x   and   y,   where   n   is a given non-square positive integer. Task requirements   find the smallest solution in positive integers to Pell's equation for   n = {61, 109, 181, 277}. See also   Wikipedia entry: Pell's equation.
#Visual_Basic_.NET
Visual Basic .NET
Imports System.Numerics   Module Module1 Sub Fun(ByRef a As BigInteger, ByRef b As BigInteger, c As Integer) Dim t As BigInteger = a : a = b : b = b * c + t End Sub   Sub SolvePell(n As Integer, ByRef a As BigInteger, ByRef b As BigInteger) Dim x As Integer = Math.Sqrt(n), y As Integer = x, z As Integer = 1, r As Integer = x << 1, e1 As BigInteger = 1, e2 As BigInteger = 0, f1 As BigInteger = 0, f2 As BigInteger = 1 While True y = r * z - y : z = (n - y * y) / z : r = (x + y) / z Fun(e1, e2, r) : Fun(f1, f2, r) : a = f2 : b = e2 : Fun(b, a, x) If a * a - n * b * b = 1 Then Exit Sub End While End Sub   Sub Main() Dim x As BigInteger, y As BigInteger For Each n As Integer In {61, 109, 181, 277} SolvePell(n, x, y) Console.WriteLine("x^2 - {0,3} * y^2 = 1 for x = {1,27:n0} and y = {2,25:n0}", n, x, y) Next End Sub End Module
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.
#360_Assembly
360 Assembly
* Pascal matrix generation - 10/06/2018 PASCMATR CSECT USING PASCMATR,R13 base register B 72(R15) skip savearea DC 17F'0' savearea SAVE (14,12) save previous context ST R13,4(R15) link backward ST R15,8(R13) link forward LR R13,R15 set addressability MVC MAT,=F'1' mat(1,1)=1 LA R6,1 i=1 DO WHILE=(C,R6,LE,N) do i=1 to n; LA R7,1 j=1 DO WHILE=(C,R7,LE,N) do j=1 to n; LR R2,R6 i LA R3,1(R7) r3=j+1 LR R1,R6 i BCTR R1,0 -1 MH R1,NN *nn AR R1,R7 ~(i,j) SLA R1,2 *4 L R4,MAT-4(R1) r4=mat(i,j) LR R5,R6 i MH R5,NN *nn AR R5,R7 ~(i+1,j) SLA R5,2 *4 L R5,MAT-4(R5) r5=mat(i+1,j) AR R4,R5 r4=mat(i,j)+mat(i+1,j) MH R2,NN *nn AR R2,R3 ~(i+1,j+1) SLA R2,2 *4 ST R4,MAT-4(R2) mat(i+1,j+1)=mat(i,j)+mat(i+1,j) LA R7,1(R7) j++ ENDDO , enddo j LA R6,1(R6) i++ ENDDO , enddo i MVC TITLE,=CL20'Upper:' BAL R14,PRINTMAT call printmat MVC MAT,=F'1' mat(1,1)=1 LA R6,1 i=1 DO WHILE=(C,R6,LE,N) do i=1 to n; LA R7,1 j=1 DO WHILE=(C,R7,LE,N) do j=1 to n; LR R2,R6 i LA R3,1(R7) r3=j+1 LR R1,R6 i BCTR R1,0 -1 MH R1,NN *nn LR R0,R7 j AR R1,R0 ~(i,j) SLA R1,2 *4 L R4,MAT-4(R1) r4=mat(i,j) LA R5,1(R7) j+1 LR R1,R6 i BCTR R1,0 -1 MH R1,NN *nn AR R1,R5 ~(i,j+1) SLA R1,2 *4 L R5,MAT-4(R1) r5=mat(i,j+1) AR R4,R5 mat(i,j)+mat(i,j+1) MH R2,NN *nn AR R2,R3 ~(i+1,j+1) SLA R2,2 *4 ST R4,MAT-4(R2) mat(i+1,j+1)=mat(i,j)+mat(i,j+1) LA R7,1(R7) j++ ENDDO , enddo j LA R6,1(R6) i++ ENDDO , enddo i MVC TITLE,=CL20'Lower:' BAL R14,PRINTMAT call printmat MVC MAT+24,=F'1' mat(2,1)=1 LA R6,1 i=1 DO WHILE=(C,R6,LE,N) do i=1 to n; LA R7,1 j=1 DO WHILE=(C,R7,LE,N) do j=1 to n; LR R2,R6 i LA R3,1(R7) r3=j+1 j LR R1,R6 i BCTR R1,0 -1 MH R1,NN *nn AR R1,R3 ~(i,j+1) SLA R1,2 *4 L R4,MAT-4(R1) r4=mat(i,j+1) LR R5,R6 i MH R5,NN *nn AR R5,R7 j SLA R5,2 *4 L R5,MAT-4(R5) r5=mat(i+1,j) AR R4,R5 mat(i,j+1)+mat(i+1,j) MH R2,NN *nn AR R2,R3 ~(i+1,j+1) SLA R2,2 *4 ST R4,MAT-4(R2) mat(i+1,j+1)=mat(i,j+1)+mat(i+1,j) LA R7,1(R7) j++ ENDDO , enddo j LA R6,1(R6) i++ ENDDO , enddo i MVC TITLE,=CL20'Symmetric:' BAL R14,PRINTMAT call printmat L R13,4(0,R13) restore previous savearea pointer RETURN (14,12),RC=0 restore registers from calling sav PRINTMAT XPRNT TITLE,L'TITLE print title ----------------------- LA R10,PG pgi=0 LA R6,1 i=1 DO WHILE=(C,R6,LE,N) do i=1 to n; LA R7,1 j=1 DO WHILE=(C,R7,LE,N) do j=1 to n; LR R2,R6 i LR R3,R7 j LA R3,1(R3) j+1 MH R2,NN *nn AR R2,R3 ~(i+1,j+1) SLA R2,2 *4 L R2,MAT-4(R2) mat(i+1,j+1) XDECO R2,XDEC edit mat(i+1,j+1) MVC 0(5,R10),XDEC+7 output mat(i+1,j+1) LA R10,5(R10) pgi+=5 LA R7,1(R7) j++ ENDDO , enddo j XPRNT PG,L'PG print LA R10,PG pgi=0 LA R6,1(R6) i++ ENDDO , enddo i BR R14 return to caller ------------------- X EQU 5 matrix size N DC A(X) n=x NN DC AL2(X+1) nn=x+1 MAT DC ((X+1)*(X+1))F'0' mat(x+1,x+1) TITLE DC CL20' ' title PG DC CL80' ' buffer PGI DC H'0' buffer index XDEC DS CL12 temp YREGS END PASCMATR
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
#360_Assembly
360 Assembly
* Pascal's triangle 25/10/2015 PASCAL CSECT USING PASCAL,R15 set base register LA R7,1 n=1 LOOPN C R7,=A(M) do n=1 to m BH ELOOPN if n>m then goto MVC U,=F'1' u(1)=1 LA R8,PG pgi=@pg LA R6,1 i=1 LOOPI CR R6,R7 do i=1 to n BH ELOOPI if i>n then goto LR R1,R6 i SLA R1,2 i*4 L R3,T-4(R1) t(i) L R4,T(R1) t(i+1) AR R3,R4 t(i)+t(i+1) ST R3,U(R1) u(i+1)=t(i)+t(i+1) LR R1,R6 i SLA R1,2 i*4 L R2,U-4(R1) u(i) XDECO R2,XD edit u(i) MVC 0(4,R8),XD+8 output u(i):4 LA R8,4(R8) pgi=pgi+4 LA R6,1(R6) i=i+1 B LOOPI end i ELOOPI MVC T((M+1)*(L'T)),U t=u XPRNT PG,80 print LA R7,1(R7) n=n+1 B LOOPN end n ELOOPN XR R15,R15 set return code BR R14 return to caller M EQU 11 <== input T DC (M+1)F'0' t(m+1) init 0 U DC (M+1)F'0' u(m+1) init 0 PG DC CL80' ' pg init ' ' XD DS CL12 temp YREGS END PASCAL
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.
#Ada
Ada
with Ada.Text_IO;   procedure Partial_Function_Application is   type Sequence is array(Positive range <>) of Integer;   -- declare a function FS with a generic parameter F and a normal parameter S generic with function F(I: Integer) return Integer; -- generic parameter function FS (S: Sequence) return Sequence;   -- define FS function FS (S: Sequence) return Sequence is Result: Sequence(S'First .. S'Last); begin for Idx in S'Range loop Result(Idx) := F(S(Idx)); end loop; return Result; end FS;   -- define functions F1 and F2 function F1(I: Integer) return Integer is begin return 2*I; end F1;   function F2(I: Integer) return Integer is begin return I**2; end F2;   -- instantiate the function FS by F1 and F2 (partially apply F1 and F2 to FS) function FSF1 is new FS(F1); function FSF2 is new FS(F2);   procedure Print(S: Sequence) is begin for Idx in S'Range loop Ada.Text_IO.Put(Integer'Image(S(Idx))); end loop; Ada.Text_IO.New_Line; end Print;   begin Print(FSF1((0,1,2,3))); Print(FSF2((0,1,2,3))); Print(FSF1((2,4,6,8))); Print(FSF2((2,4,6,8))); end Partial_Function_Application;
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
#D
D
import std.array : array; import std.range : take; import std.stdio;   bool isPrime(int n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3;   int d = 5; while (d*d <= n) { if (n % d == 0) return false; d += 2; if (n % d == 0) return false; d += 4; } return true; }   auto generatePrimes() { struct Seq { int p = 2;   bool empty() { return p < 0; }   int front() { return p; }   void popFront() { if (p==2) { p++; } else { p += 2; while (!empty && !p.isPrime) { p += 2; } } } }   return Seq(); }   bool findCombo(int k, int x, int m, int n, int[] combo) { import std.algorithm : map, sum; auto getPrime = function int(int idx) => primes[idx];   if (k >= m) { if (combo.map!getPrime.sum == x) { auto word = (m > 1) ? "primes" : "prime"; writef("Partitioned %5d with %2d %s ", x, m, word); foreach (i; 0..m) { write(primes[combo[i]]); if (i < m-1) { write('+'); } else { writeln(); } } return true; } } else { foreach (j; 0..n) { if (k==0 || j>combo[k-1]) { combo[k] = j; bool foundCombo = findCombo(k+1, x, m, n, combo); if (foundCombo) { return true; } } } } return false; }   void partition(int x, int m) { import std.exception : enforce; import std.algorithm : filter; enforce(x>=2 && m>=1 && m<x);   auto lessThan = delegate int(int a) => a<=x; auto filteredPrimes = primes.filter!lessThan.array; auto n = filteredPrimes.length; enforce(n>=m, "Not enough primes");   int[] combo = new int[m]; if (!findCombo(0, x, m, n, combo)) { auto word = (m > 1) ? "primes" : "prime"; writefln("Partitioned %5d with %2d %s: (not possible)", x, m, word); } }   int[] primes; void main() { // generate first 50,000 and call it good primes = generatePrimes().take(50_000).array;   auto a = [ [99809, 1], [ 18, 2], [ 19, 3], [ 20, 4], [ 2017, 24], [22699, 1], [22699, 2], [22699, 3], [22699, 4], [40355, 3] ];   foreach(p; a) { partition(p[0], p[1]); } }
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
#FreeBASIC
FreeBASIC
Function PartitionsP(n As UInteger) As ULongInt ' if n > 416, the result becomes to large for a unsigned 64bit integer Dim As ULongInt p(n) Dim As UInteger k, j   p(0) = 1 For i As UInteger = 1 To n k = 0 While TRUE k += 1 j = (k * (3*k - 1)) \ 2 If (j > i) Then Exit While If (k And 1) Then p(i) += p(i - j) Else p(i) -= p(i - j) End If 'j = (k * (3*k + 1)) \ 2 j += k If (j > i) Then Exit While If (k And 1) Then p(i) += p(i - j) Else p(i) -= p(i - j) End If Wend Next i Return p(n) End Function   Print !"\nPartitionsP: "; For x As UInteger = 0 To 12 Print PartitionsP(x);" "; Next x   Print !"\n\ndone" Sleep
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.
#Curry
Curry
import CLPFD import Constraint (allC, andC) import Findall (findall) import List (init, last)     solve :: [[Int]] -> Success solve body@([n]:rest) = domain (concat body) 1 n & andC (zipWith atop body rest) & labeling [] (concat body) where xs `atop` ys = andC $ zipWith3 tri xs (init ys) (tail ys)   tri :: Int -> Int -> Int -> Success tri x y z = x =# y +# z   test (x,y,z) | tri y x z = [ [151] , [ _, _] , [40, _, _] , [ _, _, _, _] , [ x, 11, y, 4, z] ] main = findall $ solve . test
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.
#D
D
import std.stdio, std.algorithm;   void iterate(bool doPrint=true)(double[] v, double[] diff) @safe { static ref T E(T)(T[] x, in size_t row, in size_t col) pure nothrow @safe @nogc { return x[row * (row + 1) / 2 + col]; }   double tot = 0.0; do { // Enforce boundary conditions. E(v, 0, 0) = 151; E(v, 2, 0) = 40; E(v, 4, 1) = 11; E(v, 4, 3) = 4;   // Calculate difference from equilibrium. foreach (immutable i; 1 .. 5) { foreach (immutable j; 0 .. i + 1) { E(diff, i, j) = 0; if (j < i) E(diff, i, j) += E(v, i - 1, j) - E(v, i, j + 1) - E(v, i, j); if (j) E(diff, i, j) += E(v, i - 1, j - 1) - E(v, i, j - 1) - E(v, i, j); } }   foreach (immutable i; 1 .. 4) foreach (immutable j; 0 .. i) E(diff, i, j) += E(v, i + 1, j) + E(v, i + 1, j + 1) - E(v, i, j);   E(diff, 4, 2) += E(v, 4, 0) + E(v, 4, 4) - E(v, 4, 2);   // Do feedback, check if we are close enough. // 4: scale down the feedback to avoid oscillations. v[] += diff[] / 4; tot = diff.map!q{ a ^^ 2 }.sum;   static if (doPrint) writeln("dev: ", tot);   // tot(dx^2) < 0.1 means each cell is no more than 0.5 away // from equilibrium. It takes about 50 iterations. After // 700 iterations tot is < 1e-25, but that's overkill. } while (tot >= 0.1); }   void main() { static void show(in double[] x) nothrow @nogc { int idx; foreach (immutable i; 0 .. 5) foreach (immutable j; 0 .. i+1) { printf("%4d%c", cast(int)(0.5 + x[idx]), j < i ? ' ' : '\n'); idx++; } }   double[15] v = 0.0, diff = 0.0; iterate(v, diff); show(v); }
http://rosettacode.org/wiki/Peaceful_chess_queen_armies
Peaceful chess queen armies
In chess, a queen attacks positions from where it is, in straight lines up-down and left-right as well as on both its diagonals. It attacks only pieces not of its own colour. ⇖ ⇑ ⇗ ⇐ ⇐ ♛ ⇒ ⇒ ⇙ ⇓ ⇘ ⇙ ⇓ ⇘ ⇓ The goal of Peaceful chess queen armies is to arrange m black queens and m white queens on an n-by-n square grid, (the board), so that no queen attacks another of a different colour. Task Create a routine to represent two-colour queens on a 2-D board. (Alternating black/white background colours, Unicode chess pieces and other embellishments are not necessary, but may be used at your discretion). Create a routine to generate at least one solution to placing m equal numbers of black and white queens on an n square board. Display here results for the m=4, n=5 case. References Peaceably Coexisting Armies of Queens (Pdf) by Robert A. Bosch. Optima, the Mathematical Programming Socity newsletter, issue 62. A250000 OEIS
#Kotlin
Kotlin
import kotlin.math.abs   enum class Piece { Empty, Black, White, }   typealias Position = Pair<Int, Int>   fun place(m: Int, n: Int, pBlackQueens: MutableList<Position>, pWhiteQueens: MutableList<Position>): Boolean { if (m == 0) { return true } var placingBlack = true for (i in 0 until n) { inner@ for (j in 0 until n) { val pos = Position(i, j) for (queen in pBlackQueens) { if (queen == pos || !placingBlack && isAttacking(queen, pos)) { continue@inner } } for (queen in pWhiteQueens) { if (queen == pos || placingBlack && isAttacking(queen, pos)) { continue@inner } } placingBlack = if (placingBlack) { pBlackQueens.add(pos) false } else { pWhiteQueens.add(pos) if (place(m - 1, n, pBlackQueens, pWhiteQueens)) { return true } pBlackQueens.removeAt(pBlackQueens.lastIndex) pWhiteQueens.removeAt(pWhiteQueens.lastIndex) true } } } if (!placingBlack) { pBlackQueens.removeAt(pBlackQueens.lastIndex) } return false }   fun isAttacking(queen: Position, pos: Position): Boolean { return queen.first == pos.first || queen.second == pos.second || abs(queen.first - pos.first) == abs(queen.second - pos.second) }   fun printBoard(n: Int, blackQueens: List<Position>, whiteQueens: List<Position>) { val board = MutableList(n * n) { Piece.Empty }   for (queen in blackQueens) { board[queen.first * n + queen.second] = Piece.Black } for (queen in whiteQueens) { board[queen.first * n + queen.second] = Piece.White } for ((i, b) in board.withIndex()) { if (i != 0 && i % n == 0) { println() } if (b == Piece.Black) { print("B ") } else if (b == Piece.White) { print("W ") } else { val j = i / n val k = i - j * n if (j % 2 == k % 2) { print("• ") } else { print("◦ ") } } } println('\n') }   fun main() { val nms = listOf( Pair(2, 1), Pair(3, 1), Pair(3, 2), Pair(4, 1), Pair(4, 2), Pair(4, 3), Pair(5, 1), Pair(5, 2), Pair(5, 3), Pair(5, 4), Pair(5, 5), Pair(6, 1), Pair(6, 2), Pair(6, 3), Pair(6, 4), Pair(6, 5), Pair(6, 6), Pair(7, 1), Pair(7, 2), Pair(7, 3), Pair(7, 4), Pair(7, 5), Pair(7, 6), Pair(7, 7) ) for ((n, m) in nms) { println("$m black and $m white queens on a $n x $n board:") val blackQueens = mutableListOf<Position>() val whiteQueens = mutableListOf<Position>() if (place(m, n, blackQueens, whiteQueens)) { printBoard(n, blackQueens, whiteQueens) } else { println("No solution exists.\n") } } }
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
#Crystal
Crystal
require "random/secure"   special_chars = true similar = 0 require_groups = true length = 20 count = 1   def show_usage puts <<-USAGE   Passwords generator Usage: pass2 [count] [-l<length>] [-s{0|1|2}] [-ng] [-ns]   count: number of passwords to be generated (default: 1) -l<length>: length of passwords (default: 20) -s{0|1|2}: exclude visually similar characters. 0 - don't exclude (default) 1 - exclude 0, O, 1, I, l, | 2 - also exclude 2, Z, 5, S -ng: don''t require password to include character from every group -ns: don''t include special chars in password   Default value of switches is choosen to match the task in page header, but I suggest to use the "-s1 -ng -ns". USAGE end   count_set = false begin ARGV.each do |arg| case arg when /-l(\d+)/ length = $1.to_i raise "Error: minimal length is 4" if length < 4 when /-s(\d)/ similar = $1.to_i raise "Error: minimal length is 4" unless {0, 1, 2}.includes? similar when /-ng/ require_groups = false when /-ns/ special_chars = false when /(\d+)/ raise "incorrect arguments" if count_set count_set = true count = $1.to_i else raise "incorrect argument" end end rescue ex puts ex.message show_usage exit end   # actual program GROUPS = [('a'..'z').to_a, ('A'..'Z').to_a, ('0'..'9').to_a] GROUPS << "!\"#$%&'()*+,-./:;<=>?@[]^_{|}~".chars if special_chars   letters = GROUPS.flatten letters -= "1l|I0O".chars if similar > 0 letters -= "5S2Z".chars if similar > 1   loop do s = Array(Char).new(length) { letters.sample(Random::Secure) } # it's better to just discard in order to don't lose enthropy next if require_groups && GROUPS.any? { |x| (s & x).size == 0 } puts s.join count -= 1 break if count <= 0 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
#Run_BASIC
Run BASIC
list$ = "h,e,l,l,o" ' supply list seperated with comma's   while word$(list$,d+1,",") <> "" 'Count how many in the list d = d + 1 wend   dim theList$(d) ' place list in array for i = 1 to d theList$(i) = word$(list$,i,",") next i   for i = 1 to d ' print the Permutations for j = 2 to d perm$ = "" for k = 1 to d perm$ = perm$ + theList$(k) next k if instr(perm2$,perm$+",") = 0 then print perm$ ' only list 1 time perm2$ = perm2$ + perm$ + "," h$ = theList$(j) theList$(j) = theList$(j - 1) theList$(j - 1) = h$ next j next i end
http://rosettacode.org/wiki/Peano_curve
Peano curve
Task Produce a graphical or ASCII-art representation of a Peano curve of at least order 3.
#Racket
Racket
  /* Jens Axel Søgaard, 27th December 2018*/ #lang racket (require metapict metapict/mat)   ;;; Turtle State (define p (pt 0 0))  ; current position (define d (vec 0 1)) ; current direction (define c '())  ; line segments drawn so far   ;;; Turtle Operations (define (jump q) (set! p q)) (define (move q) (set! c (cons (curve p -- q) c)) (set! p q)) (define (forward x) (move (pt+ p (vec* x d)))) (define (left a) (set! d (rot a d))) (define (right a) (left (- a)))   ;;; Peano (define (peano n a h) (unless (= n 0) (right a) (peano (- n 1) (- a) h) (forward h) (peano (- n 1) a h) (forward h) (peano (- n 1) (- a) h) (left a)))   ;;; Produce image (set-curve-pict-size 400 400) (with-window (window -1 81 -1 82) (peano 6 90 3) (draw* c))  
http://rosettacode.org/wiki/Peano_curve
Peano curve
Task Produce a graphical or ASCII-art representation of a Peano curve of at least order 3.
#Raku
Raku
use SVG;   role Lindenmayer { has %.rules; method succ { self.comb.map( { %!rules{$^c} // $c } ).join but Lindenmayer(%!rules) } }   my $peano = 'L' but Lindenmayer( { 'L' => 'LFRFL-F-RFLFR+F+LFRFL', 'R' => 'RFLFR+F+LFRFL-F-RFLFR' } );   $peano++ xx 4; my @points = (10, 10);   for $peano.comb { state ($x, $y) = @points[0,1]; state $d = 0 + 8i; when 'F' { @points.append: ($x += $d.re).round(1), ($y += $d.im).round(1) } when /< + - >/ { $d *= "{$_}1i" } default { } }   say SVG.serialize( svg => [ :660width, :660height, :style<stroke:lime>, :rect[:width<100%>, :height<100%>, :fill<black>], :polyline[ :points(@points.join: ','), :fill<black> ], ], );
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).
#MiniScript
MiniScript
randomTorH = function() if rnd < 0.5 then return "T" else return "H" end function   if rnd < 0.5 then playerSeq = input("Input your sequence (e.g. HTH): ").upper if playerSeq[1] == "T" then compSeq = "H" else compSeq = "T" compSeq = compSeq + playerSeq[:2] print "I choose: " + compSeq else compSeq = randomTorH + randomTorH + randomTorH print "I choose: " + compSeq playerSeq = input("Input your sequence (e.g. HTH): ").upper end if   print "Here we go..." seq = "" while true flip = randomTorH print flip seq = seq + flip if seq[-3:] == playerSeq then print "You win!" break else if seq[-3:] == compSeq then print "I win!" break end if wait end while
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.
#Julia
Julia
using Printf # arbitrary precision setprecision(2000)   # Task 1 function seq(n) len = maximum(n) r = Vector{BigFloat}(len) r[1] = 2 if len > 1 r[2] = -4 end   for i in 3:len r[i] = 111 - 1130 / r[i-1] + 3000 / (r[i-1] * r[i-2]) end   return r[n] end   n = [1, 2, 3, 5, 10, 100] v = seq(n) println("Task 1 - Sequence convergence:\n", join((@sprintf("v%-3i = %23.20f", i, s) for (i, s) in zip(n, v)), '\n'))   # Task 2: solution with big float (precision can be set with setprecision function) function chaoticbankfund(years::Integer) balance = big(e) - 1 for y in 1:years balance = (balance * y) - 1 end   return balance end   println("\nTask 2 - Chaotic Bank fund after 25 years:\n", @sprintf "%.20f" chaoticbankfund(25))   # Task 3: solution with big float f(a::Union{BigInt,BigFloat}, b::Union{BigInt,BigFloat}) = 333.75b ^ 6 + a ^ 2 * ( 11a ^ 2 * b ^ 2 - b ^ 6 - 121b ^ 4 - 2 ) + 5.5b ^ 8 + a / 2b   println("\nTask 3 - Siegfried Rump's example:\nf(77617.0, 33096.0) = ", @sprintf "%.20f" f(big(77617.0), big(33096.0)))
http://rosettacode.org/wiki/Pell%27s_equation
Pell's equation
Pell's equation   (also called the Pell–Fermat equation)   is a   Diophantine equation   of the form: x2   -   ny2   =   1 with integer solutions for   x   and   y,   where   n   is a given non-square positive integer. Task requirements   find the smallest solution in positive integers to Pell's equation for   n = {61, 109, 181, 277}. See also   Wikipedia entry: Pell's equation.
#Wren
Wren
import "/big" for BigInt import "/fmt" for Fmt   var solvePell = Fn.new { |n| n = BigInt.new(n) var x = n.isqrt var y = x.copy() var z = BigInt.one var r = x * 2 var e1 = BigInt.one var e2 = BigInt.zero var f1 = BigInt.zero var f2 = BigInt.one while (true) { y = r*z - y z = (n - y*y) / z r = (x + y) / z var t = e1.copy() e1 = e2.copy() e2 = r*e2 + t t = f1.copy() f1 = f2.copy() f2 = r*f2 + t var a = e2 + x*f2 var b = f2.copy() if (a*a - n*b*b == BigInt.one) return [a, b] } }   for (n in [61, 109, 181, 277]) { var res = solvePell.call(n) Fmt.print("x² - $3dy² = 1 for x = $-21i and y = $i", n, res[0], res[1]) }
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.
#Action.21
Action!
BYTE FUNC Index(BYTE i,j,dim) RETURN (i*dim+j)   PROC PascalUpper(BYTE ARRAY mat BYTE dim) BYTE i,j   FOR i=0 TO dim-1 DO FOR j=0 TO dim-1 DO IF i>j THEN mat(Index(i,j,dim))=0 ELSEIF i=j OR i=0 THEN mat(Index(i,j,dim))=1 ELSE mat(Index(i,j,dim))=mat(Index(i-1,j-1,dim))+mat(Index(i,j-1,dim)) FI OD OD RETURN   PROC PascalLower(BYTE ARRAY mat BYTE dim) BYTE i,j   FOR i=0 TO dim-1 DO FOR j=0 TO dim-1 DO IF i<j THEN mat(Index(i,j,dim))=0 ELSEIF i=j OR j=0 THEN mat(Index(i,j,dim))=1 ELSE mat(Index(i,j,dim))=mat(Index(i-1,j-1,dim))+mat(Index(i-1,j,dim)) FI OD OD RETURN   PROC PascalSymmetric(BYTE ARRAY mat BYTE dim) BYTE i,j   FOR i=0 TO dim-1 DO FOR j=0 TO dim-1 DO IF i=0 OR j=0 THEN mat(Index(i,j,dim))=1 ELSE mat(Index(i,j,dim))=mat(Index(i-1,j,dim))+mat(Index(i,j-1,dim)) FI OD OD RETURN   PROC PrintMatrix(BYTE ARRAY mat BYTE dim) BYTE i,j,v   FOR i=0 TO dim-1 DO FOR j=0 TO dim-1 DO v=mat(Index(i,j,dim)) IF v<10 THEN Print(" ") ELSEIF v<100 THEN Print(" ") FI PrintB(v) OD PutE() OD RETURN   PROC Main() BYTE ARRAY mat(25) BYTE dim=[5]   PrintE("Pascal upper matrix:") PascalUpper(mat,dim) PrintMatrix(mat,dim) PutE()   PrintE("Pascal lower matrix:") PascalLower(mat,dim) PrintMatrix(mat,dim) PutE()   PrintE("Pascal symmetric matrix:") PascalSymmetric(mat,dim) PrintMatrix(mat,dim) RETURN
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
#8th
8th
  \ print the array : .arr \ a -- a ( . space ) a:each ;   : pasc \ a -- \ print the row .arr cr dup \ create two rows from the first, one with a leading the other with a trailing 0 [0] 0 a:insert swap 0 a:push \ add the arrays together to make the new one ' n:+ a:op ;   \ print the first 16 rows: [1] ' pasc 16 times  
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.
#ALGOL_68
ALGOL 68
MODE SET = FLEX[0]INT;   MODE F = PROC(INT)INT, FS = PROC(SET)SET;   PROC fs = (F f, SET set)SET: ( [LWB set:UPB set]INT out; FOR i FROM LWB set TO UPB set DO out[i]:=f(set[i]) OD; out );   PROC f1 = (INT value)INT: value * 2, f2 = (INT value)INT: value ** 2;   FS fsf1 = fs(f1,), fsf2 = fs(f2,);   [4]INT set; FORMAT set fmt = $"("n(UPB set-LWB set)(g(0)", ")g(0)")"l$;   set := (0, 1, 2, 3); printf((set fmt, fsf1((0, 1, 2, 3)))); # prints (0, 2, 4, 6) # printf((set fmt, fsf2((0, 1, 2, 3)))); # prints (0, 1, 4, 9) #   set := (2, 4, 6, 8); printf((set fmt, fsf1((2, 4, 6, 8)))); # prints (4, 8, 12, 16) # printf((set fmt, 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
#F.23
F#
  // Partition an integer as the sum of n primes. Nigel Galloway: November 27th., 2017 let rcTask n ng = let rec fN i g e l = seq{ match i with |1 -> if isPrime g then yield Some (g::e) else yield None |_ -> yield! Seq.mapi (fun n a->fN (i-1) (g-a) (a::e) (Seq.skip (n+1) l)) (l|>Seq.takeWhile(fun n->(g-n)>n))|>Seq.concat} match fN n ng [] primes |> Seq.tryPick id with |Some n->printfn "%d is the sum of %A" ng n |_ ->printfn "No Solution"  
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
#Go
Go
package main   import ( "fmt" "math/big" "time" )   var p []*big.Int var pd []int   func partDiffDiff(n int) int { if n&1 == 1 { return (n + 1) / 2 } return n + 1 }   func partDiff(n int) int { if n < 2 { return 1 } pd[n] = pd[n-1] + partDiffDiff(n-1) return pd[n] }   func partitionsP(n int) { if n < 2 { return } psum := new(big.Int) for i := 1; i <= n; i++ { pdi := partDiff(i) if pdi > n { break } sign := int64(-1) if (i-1)%4 < 2 { sign = 1 } t := new(big.Int).Mul(p[n-pdi], big.NewInt(sign)) psum.Add(psum, t) } p[n] = psum }   func main() { start := time.Now() const N = 6666 p = make([]*big.Int, N+1) pd = make([]int, N+1) p[0], pd[0] = big.NewInt(1), 1 p[1], pd[1] = big.NewInt(1), 1 for n := 2; n <= N; n++ { partitionsP(n) } fmt.Printf("p[%d)] = %d\n", N, p[N]) fmt.Printf("Took %s\n", time.Since(start)) }
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.
#F.23
F#
  #load"Packages\MathNet.Numerics.FSharp\MathNet.Numerics.fsx"   open MathNet.Numerics.LinearAlgebra   let A = matrix [ [ 1.; 1.; 0.; 0.; 0.; 0.; 0.; 0.; 0.; 0.; 0. ] [ -1.; 0.; 1.; 0.; 0.; 0.; 0.; 0.; 0.; 0.; 0. ] [ 0.; -1.; 1.; 1.; 0.; 0.; 0.; 0.; 0.; 0.; 0. ] [ 0.; 0.; 0.; 0.; 1.; 1.; 0.; 0.; 0.; 0.; 0. ] [ 0.; 0.; -1.; 0.; 0.; 1.; 1.; 0.; 0.; 0.; 0. ] [ 0.; 0.; 0.; -1.; 0.; 0.; 1.; 1.; 0.; 0.; 0. ] [ 0.; 0.; 0.; 0.; -1.; 0.; 0.; 0.; 1.; 0.; 0. ] [ 0.; 0.; 0.; 0.; 0.; -1.; 0.; 0.; 0.; 1.; 0. ] [ 0.; 0.; 0.; 0.; 0.; 0.; -1.; 0.; 0.; 1.; 0. ] [ 0.; 0.; 0.; 0.; 0.; 0.; 0.; -1.; 0.; 0.; 1. ] [ 0.; 0.; 0.; 0.; 0.; 0.; 0.; 0.; 1.; -1.; 1. ] ]   let b = vector [151.; -40.; 0.; 40.; 0.; 0.; -11.; -11.; -4.; -4.; 0.]   let x = A.Solve(b)   printfn "x = %f, Y = %f, Z = %f" x.[8] x.[9] x.[10]
http://rosettacode.org/wiki/Peaceful_chess_queen_armies
Peaceful chess queen armies
In chess, a queen attacks positions from where it is, in straight lines up-down and left-right as well as on both its diagonals. It attacks only pieces not of its own colour. ⇖ ⇑ ⇗ ⇐ ⇐ ♛ ⇒ ⇒ ⇙ ⇓ ⇘ ⇙ ⇓ ⇘ ⇓ The goal of Peaceful chess queen armies is to arrange m black queens and m white queens on an n-by-n square grid, (the board), so that no queen attacks another of a different colour. Task Create a routine to represent two-colour queens on a 2-D board. (Alternating black/white background colours, Unicode chess pieces and other embellishments are not necessary, but may be used at your discretion). Create a routine to generate at least one solution to placing m equal numbers of black and white queens on an n square board. Display here results for the m=4, n=5 case. References Peaceably Coexisting Armies of Queens (Pdf) by Robert A. Bosch. Optima, the Mathematical Programming Socity newsletter, issue 62. A250000 OEIS
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
ClearAll[ValidSpots, VisibleByQueen, SolveQueen, GetSolution] VisualizeState[state_] := Module[{q, cells}, q = MapIndexed[If[#["q"] == -1, {}, Text[Style[#["q"], 24], #2]] &, state, {2}]; cells = MapIndexed[{If[OddQ[Total[#2]], FaceForm[], FaceForm[GrayLevel[0.8]]], EdgeForm[Black], Rectangle[#2 - 0.5, #2 + 0.5]} &, state, {2}]; Graphics[{cells, q}] ] ValidSpots[state_, tp_Integer] := Module[{vals}, vals = Catenate@MapIndexed[If[#1["q"] == -1 \[And] DeleteCases[#1["v"], tp] == {}, #2, Missing[]] &, state, {2}]; DeleteMissing[vals] ] VisibleByQueen[{i_, j_}, {a_, b_}] := i == a \[Or] j == b \[Or] i + j == a + b \[Or] i - j == a - b PlaceQueen[state_, pos : {i_Integer, j_Integer}, tp_Integer] := Module[{vals, out}, out = state; out[[i, j]] = Association[out[[i, j]], "q" -> tp]; out = MapIndexed[If[VisibleByQueen[{i, j}, #2], <|#1, "v" -> Append[#1["v"], tp]|>, #1] &, out, {2}]; out ] SolveQueen[state_, toplace_List] := Module[{len = Length[toplace], next, valid, newstate}, If[len == 0, Print[VisualizeState@state]; Print[StringRiffle[StringJoin /@ Map[ToString, state[[All, All, "q"]] /. -1 -> ".", {2}], "\n"]]; Abort[]; , next = First[toplace]; valid = ValidSpots[state, next]; Do[ newstate = PlaceQueen[state, v, next]; SolveQueen[newstate, Rest[toplace]] , {v, valid} ] ] ] GetSolution[n_Integer?Positive, m_Integer?Positive, numcol_ : 2] := Module[{state, tp}, state = ConstantArray[<|"q" -> -1, "v" -> {}|>, {n, n}]; tp = Flatten[Transpose[ConstantArray[#, m] & /@ Range[numcol]]]; SolveQueen[state, tp] ] GetSolution[8, 4, 3](* Solves placing 3 armies of each 4 queens on an 8*8 board*) GetSolution[5, 4, 2](* Solves placing 2 armies of each 4 queens on an 5*5 board*)
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
#Elixir
Elixir
defmodule Password do @lower Enum.map(?a..?z, &to_string([&1])) @upper Enum.map(?A..?Z, &to_string([&1])) @digit Enum.map(?0..?9, &to_string([&1])) @other ~S""" !"#$%&'()*+,-./:;<=>?@[]^_{|}~ """ |> String.codepoints |> List.delete_at(-1) @all @lower ++ @upper ++ @digit ++ @other   def generator do {len, num} = get_argv Enum.each(1..num, fn _ -> pswd = [Enum.random(@lower), Enum.random(@upper), Enum.random(@digit), Enum.random(@other)] IO.puts generator(len-4, pswd) end) end   def generator(0, pswd), do: Enum.shuffle(pswd) |> Enum.join def generator(len, pswd), do: generator(len-1, [Enum.random(@all) | pswd])   def get_argv do {len,num} = case System.argv do ["?"] -> usage [] -> {8,1} [len] -> {String.to_integer(len), 1} [len,num] -> {String.to_integer(len), String.to_integer(num)} _ -> usage end if len<4 or num<1, do: usage, else: {len,num} end   defp usage do IO.puts ["Password generator\n", "Usage: [password length(=8)] [number of passwords to generate(=1)]"] exit(:normal) end end   Password.generator
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
#Rust
Rust
pub fn permutations(size: usize) -> Permutations { Permutations { idxs: (0..size).collect(), swaps: vec![0; size], i: 0 } }   pub struct Permutations { idxs: Vec<usize>, swaps: Vec<usize>, i: usize, }   impl Iterator for Permutations { type Item = Vec<usize>;   fn next(&mut self) -> Option<Self::Item> { if self.i > 0 { loop { if self.i >= self.swaps.len() { return None; } if self.swaps[self.i] < self.i { break; } self.swaps[self.i] = 0; self.i += 1; } self.idxs.swap(self.i, (self.i & 1) * self.swaps[self.i]); self.swaps[self.i] += 1; } self.i = 1; Some(self.idxs.clone()) } }   fn main() { let perms = permutations(3).collect::<Vec<_>>(); assert_eq!(perms, vec![ vec![0, 1, 2], vec![1, 0, 2], vec![2, 0, 1], vec![0, 2, 1], vec![1, 2, 0], vec![2, 1, 0], ]); }
http://rosettacode.org/wiki/Peano_curve
Peano curve
Task Produce a graphical or ASCII-art representation of a Peano curve of at least order 3.
#Ruby
Ruby
  load_library :grammar   # Peano class class Peano include Processing::Proxy attr_reader :draw_length, :vec, :theta, :axiom, :grammar DELTA = 60 # degrees def initialize(vec) @axiom = 'XF' # Axiom rules = { 'X' => 'X+YF++YF-FX--FXFX-YF+', # LSystem Rules 'Y' => '-FX+YFYF++YF+FX--FX-Y' } @grammar = Grammar.new(axiom, rules) @theta = 0 @draw_length = 100 @vec = vec end   def generate(gen) @draw_length = draw_length * 0.6**gen grammar.generate gen end   def translate_rules(prod) coss = ->(orig, alpha, len) { orig + len * DegLut.cos(alpha) } sinn = ->(orig, alpha, len) { orig - len * DegLut.sin(alpha) } [].tap do |pts| # An array to store line vertices as Vec2D prod.scan(/./) do |ch| case ch when 'F' pts << vec.copy @vec = Vec2D.new( coss.call(vec.x, theta, draw_length), sinn.call(vec.y, theta, draw_length) ) pts << vec when '+' @theta += DELTA when '-' @theta -= DELTA when 'X', 'Y' else puts("character #{ch} not in grammar") end end end end end   attr_reader :points   def setup sketch_title 'Peano' peano = Peano.new(Vec2D.new(width * 0.65, height * 0.9)) production = peano.generate 4 # 4 generations looks OK @points = peano.translate_rules(production) no_loop end   def draw background(0) render points end   def render(points) no_fill stroke 200.0 stroke_weight 3 begin_shape points.each_slice(2) do |v0, v1| v0.to_vertex(renderer) v1.to_vertex(renderer) end end_shape end   def renderer @renderer ||= GfxRender.new(g) end   def settings size(800, 800) 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).
#Nim
Nim
import os, random, sequtils, strutils   randomize()   let first = sample([false, true])   var you, me = "" if first: me = newSeqWith(3, sample("HT")).join() echo "I choose first and will win on first seeing $# in the list of tosses." % me while you.len != 3 or not allCharsInSet(you, {'H', 'T'}) or you == me: stdout.write "What sequence of three Heads/Tails will you win with? " you = stdin.readLine() else: while you.len != 3 or not allCharsInSet(you, {'H', 'T'}): echo "After you: what sequence of three Heads/Tails will you win with? " you = stdin.readLine() me = (if you[1] == 'T': 'H' else: 'T') & you[0..1] echo "I win on first seeing $# in the list of tosses" % me   var rolled = "" stdout.write "Rolling:\n " while true: rolled.add sample("HT") stdout.write rolled[^1] stdout.flushFile() if rolled.endsWith(you): echo "\n You win!" break elif rolled.endsWith(me): echo "\n I win!" break sleep(1000)
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).
#Pascal
Pascal
PROGRAM Penney;   TYPE CoinToss = (heads, tails); Sequence = array [1..3] of CoinToss; Player = record bet: Sequence; score: integer; end;   VAR Human, Computer: Player; Rounds, Count: integer;   Function TossCoin: CoinToss; { Returns heads or tails at random } Begin if random(2) = 1 then TossCoin := Heads else TossCoin := tails End;   Procedure PutToss(toss: CoinToss); { Outputs heads or tails as a letter } Begin if toss = heads then write('H') else write('T') End;   Function GetToss: CoinToss; { Reads H or T from the keyboard in either lettercase } var c: char; Begin { Keep reading characters until we get an appropriate letter } repeat read(c) until c in ['H', 'h', 'T', 't']; { Interpret the letter } if c in ['H', 'h'] then GetToss := heads else GetToss := tails End;   Procedure ShowSequence(tosses: Sequence); { Outputs three coin tosses at once } Var i: integer; Begin for i := 1 to 3 do PutToss(tosses[i]) End;   Procedure ReadSequence(var tosses: Sequence); { Accepts three coin tosses from the keyboard } Var i: integer; Begin { Get the 3 letters } for i := 1 to 3 do tosses[i] := GetToss; { Ignore the rest of the line } readln End;   Function Optimum(opponent: Sequence): Sequence; { Generates the optimum sequence against an opponent } Begin case opponent[2] of heads: Optimum[1] := tails; tails: Optimum[1] := heads end; Optimum[2] := opponent[1]; Optimum[3] := opponent[2] End;   Function RandomSequence: Sequence; { Generates three random coin tosses } Var i: integer; Begin for i := 1 to 3 do RandomSequence[i] := TossCoin End;   Function Match(first, second: Sequence): Boolean; { Detects whether a sequence of tosses matches another } Var different: boolean; i: integer; Begin different := false; i := 1; while (i <= 3) and not different do begin if not (first[i] = second[i]) then different := true; i := i + 1 end; Match := not different End;   Procedure PlayRound(var human, computer: Player); { Shows coin tosses and announces the winner } Var { We only ever need to store the 3 most recent tosses in memory. } tosses: Sequence; Begin { Start with the first three tosses } write('Tossing the coin: '); tosses := RandomSequence; ShowSequence(tosses); { Keep tossing the coin until there is a winner. } while not (Match(human.bet, tosses) or Match(computer.bet, tosses)) do begin tosses[1] := tosses[2]; tosses[2] := tosses[3]; tosses[3] := TossCoin; PutToss(tosses[3]) end; { Update the winner's score and announce the winner } writeln; writeln; if Match(human.bet, tosses) then begin writeln('Congratulations! You won this round.'); human.score := human.score + 1; writeln('Your new score is ', human.score, '.') end else begin writeln('Yay, I won this round!'); computer.score := computer.score + 1; writeln('My new score is ', computer.score, '.') end End;   { Main Algorithm }   BEGIN   { Welcome the player } writeln('Welcome to Penney''s game!'); writeln; write('How many rounds would you like to play? '); readln(Rounds); writeln; writeln('Ok, let''s play ', Rounds, ' rounds.');   { Start the game } randomize; Human.score := 0; Computer.score := 0;   for Count := 1 to Rounds do begin   writeln; writeln('*** Round #', Count, ' ***'); writeln;   { Choose someone randomly to pick the first sequence } if TossCoin = heads then begin write('I''ll pick first this time.'); Computer.bet := RandomSequence; write(' My sequence is '); ShowSequence(Computer.bet); writeln('.'); repeat write('What sequence do you want? '); ReadSequence(Human.bet); if Match(Human.bet, Computer.bet) then writeln('Hey, that''s my sequence! Think for yourself!') until not Match(Human.bet, Computer.bet); ShowSequence(Human.bet); writeln(', huh? Sounds ok to me.') end else begin write('You pick first this time. Enter 3 letters H or T: '); ReadSequence(Human.bet); Computer.bet := Optimum(Human.bet); write('Ok, so you picked '); ShowSequence(Human.bet); writeln; write('My sequence will be '); ShowSequence(Computer.bet); writeln end;   { Then we can actually play the round } writeln('Let''s go!'); writeln; PlayRound(Human, Computer); writeln; writeln('Press ENTER to go on...'); readln   end;   { All the rounds are finished; time to decide who won } writeln; writeln('*** End Result ***'); writeln; if Human.score > Computer.score then writeln('Congratulations! You won!') else if Computer.score > Human.score then writeln('Hooray! I won') else writeln('Cool, we tied.'); writeln; writeln('Press ENTER to finish.'); readln   END.
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.
#Kotlin
Kotlin
// version 1.0.6   import java.math.*   const val LIMIT = 100   val con480 = MathContext(480) val bigTwo = BigDecimal(2) val bigE = BigDecimal("2.71828182845904523536028747135266249775724709369995") // precise enough!   fun main(args: Array<String>) { // v(n) sequence task val c1 = BigDecimal(111) val c2 = BigDecimal(1130) val c3 = BigDecimal(3000) var v1 = bigTwo var v2 = BigDecimal(-4) var v3: BigDecimal for (i in 3 .. LIMIT) { v3 = c1 - c2.divide(v2, con480) + c3.divide(v2 * v1, con480) println("${"%3d".format(i)} : ${"%19.16f".format(v3)}") v1 = v2 v2 = v3 }   // Chaotic Building Society task var balance = bigE - BigDecimal.ONE for (year in 1..25) balance = balance.multiply(BigDecimal(year), con480) - BigDecimal.ONE println("\nBalance after 25 years is ${"%18.16f".format(balance)}")   // Siegfried Rump task val a = BigDecimal(77617) val b = BigDecimal(33096) val c4 = BigDecimal("333.75") val c5 = BigDecimal(11) val c6 = BigDecimal(121) val c7 = BigDecimal("5.5") var f = c4 * b.pow(6, con480) + c7 * b.pow(8, con480) + a.divide(bigTwo * b, con480) val c8 = c5 * a.pow(2, con480) * b.pow(2, con480) - b.pow(6, con480) - c6 * b.pow(4, con480) - bigTwo f += c8 * a.pow(2, con480) println("\nf(77617.0, 33096.0) is ${"%18.16f".format(f)}") }
http://rosettacode.org/wiki/Pell%27s_equation
Pell's equation
Pell's equation   (also called the Pell–Fermat equation)   is a   Diophantine equation   of the form: x2   -   ny2   =   1 with integer solutions for   x   and   y,   where   n   is a given non-square positive integer. Task requirements   find the smallest solution in positive integers to Pell's equation for   n = {61, 109, 181, 277}. See also   Wikipedia entry: Pell's equation.
#zkl
zkl
var [const] BI=Import("zklBigNum"); // libGMP   fcn solve_pell(n){ x,y,z,r := BI(n).root(2), x.copy(), BI(1), x*2; e1,e2, f1,f2 := BI(1), BI(0), BI(0), BI(1); reg t; // a,b = c,d is a=c; b=d do(30_000){ // throttle this in case of screw up y,z,r = (r*z - y), (n - y*y)/z, (x + y)/z;   t,e2,e1 = e2, r*e2 + e1, t; t,f2,f1 = f2, r*f2 + f1, t;   A,B := e2 + x*f2, f2;   if (A*A - B*B*n == 1) return(A,B); } }
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.
#Ada
Ada
-- for I/O with Ada.Text_IO; use Ada.Text_IO; with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; with Ada.Float_Text_IO; use Ada.Float_Text_IO;   -- for estimating the maximum width of a column with Ada.Numerics.Generic_Elementary_Functions;   procedure PascalMatrix is   type Matrix is array (Positive range <>, Positive range <>) of Natural;   -- instantiate Generic_Elementary_Functions for Float type package Math is new Ada.Numerics.Generic_Elementary_Functions(Float_Type => Float); use Math;   procedure Print(m: in Matrix) is -- determine the maximum width of a column w: Float := Log(Float(m'Length(1)**(m'Length(1)/2)), 10.0); width: Positive := Natural(Float'Ceiling(w)) + 1; begin for i in m'First(1)..m'Last(1) loop Put("( "); for j in m'First(2)..m'Last(2) loop Put(m(i,j), width); end loop; Put(" )"); New_Line(1); end loop; end Print;   function Upper_Triangular(n: in Positive) return Matrix is result: Matrix(1..n, 1..n) := ( 1 => ( others => 1 ), others => ( others => 0 ) ); begin for i in 2..n loop result(i,i) := 1; for j in i+1..n loop result(i,j) := result(i,j-1) + result(i-1,j-1); end loop; end loop; return result; end Upper_Triangular;   function Lower_Triangular(n: in Positive) return Matrix is result: Matrix(1..n, 1..n) := ( others => ( 1 => 1, others => 0 ) ); begin for i in 2..n loop result(i,i) := 1; for j in i+1..n loop result(j,i) := result(j-1,i) + result(j-1,i-1); end loop; end loop; return result; end Lower_Triangular;   function Symmetric(n: in Positive) return Matrix is result: Matrix(1..n, 1..n) := ( 1 => ( others => 1 ), others => ( 1 => 1, others => 0 ) ); begin for i in 2..n loop for j in 2..n loop result(i,j) := result(i,j-1) + result(i-1,j); end loop; end loop; return result; end Symmetric;   n: Positive;   begin Put("What dimension Pascal matrix would you like? "); Get(n); Put("Upper triangular:"); New_Line(1); Print(Upper_Triangular(n)); Put("Lower triangular:"); New_Line(1); Print(Lower_Triangular(n)); Put("Symmetric:"); New_Line(1); Print(Symmetric(n)); end PascalMatrix;
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
#Action.21
Action!
PROC Main() BYTE count=[10],row,item CHAR ARRAY s(5) INT v   FOR row=0 TO count-1 DO v=1 FOR item=0 TO row DO StrI(v,s) Position(2*(count-row)+4*item-s(0),row+1) Print(s) v=v*(row-item)/(item+1) OD PutE() OD RETURN
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.
#AppleScript
AppleScript
-- PARTIAL APPLICATION --------------------------------------------   on f1(x) x * 2 end f1   on f2(x) x * x end f2   on run   tell curry(map) set fsf1 to |λ|(f1) set fsf2 to |λ|(f2) end tell   {fsf1's |λ|({0, 1, 2, 3}), ¬ fsf2's |λ|({0, 1, 2, 3}), ¬ fsf1's |λ|({2, 4, 6, 8}), ¬ fsf2's |λ|({2, 4, 6, 8})} end run     -- GENERIC FUNCTIONS --------------------------------------------   -- curry :: (Script|Handler) -> Script on curry(f) script on |λ|(a) script on |λ|(b) |λ|(a, b) of mReturn(f) end |λ| end script end |λ| end script end curry   -- map :: (a -> b) -> [a] -> [b] on map(f, xs) tell mReturn(f) set lng to length of xs set lst to {} repeat with i from 1 to lng set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell end map   -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: Handler -> Script on mReturn(f) if class of f is script then f else script property |λ| : f end script end if end mReturn
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
#Factor
Factor
USING: formatting fry grouping kernel math.combinatorics math.parser math.primes sequences ;   : partition ( x n -- str ) over [ primes-upto ] 2dip '[ sum _ = ] find-combination [ number>string ] map "+" join ;   : print-partition ( x n seq -- ) [ "no solution" ] when-empty "Partitioned %5d with %2d primes: %s\n" printf ;   { 99809 1 18 2 19 3 20 4 2017 24 22699 1 22699 2 22699 3 22699 4 40355 3 } 2 group [ first2 2dup partition print-partition ] each
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
#Java
Java
import java.math.BigInteger;   public class PartitionFunction { public static void main(String[] args) { long start = System.currentTimeMillis(); BigInteger result = partitions(6666); long end = System.currentTimeMillis(); System.out.println("P(6666) = " + result); System.out.printf("elapsed time: %d milliseconds\n", end - start); }   private static BigInteger partitions(int n) { BigInteger[] p = new BigInteger[n + 1]; p[0] = BigInteger.ONE; for (int i = 1; i <= n; ++i) { p[i] = BigInteger.ZERO; for (int k = 1; ; ++k) { int j = (k * (3 * k - 1))/2; if (j > i) break; if ((k & 1) != 0) p[i] = p[i].add(p[i - j]); else p[i] = p[i].subtract(p[i - j]); j += k; if (j > i) break; if ((k & 1) != 0) p[i] = p[i].add(p[i - j]); else p[i] = p[i].subtract(p[i - j]); } } return p[n]; } }
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.
#Factor
Factor
USING: arrays backtrack combinators.extras fry grouping.extras interpolate io kernel math math.ranges sequences ;   : base ( ?x ?z -- seq ) 2dup + swap '[ _ 11 _ 4 _ ] >array ;   : up ( seq -- seq' ) [ [ + ] 2clump-map ] twice ;   : find-solution ( -- x z ) 10 [1,b] dup [ amb-lazy ] bi@ 2dup base up dup first 40 = must-be-true up first 151 = must-be-true ;   find-solution [I X = ${1}, Z = ${}I] nl
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.
#FreeBASIC
FreeBASIC
Function SolveForZ(x As Integer) As Integer Dim As Integer 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 Then c = f + g d = g + h a = 40 + c b = c + d If a + b = 151 Then Return z End If Next z Return -1 End Function   Dim As Integer x = -1, z = 0 Do x = x + 1 z = SolveForZ(x) Loop Until z >= 0   Print "X ="; x Print "Y ="; x + z Print "Z ="; z Sleep  
http://rosettacode.org/wiki/Peaceful_chess_queen_armies
Peaceful chess queen armies
In chess, a queen attacks positions from where it is, in straight lines up-down and left-right as well as on both its diagonals. It attacks only pieces not of its own colour. ⇖ ⇑ ⇗ ⇐ ⇐ ♛ ⇒ ⇒ ⇙ ⇓ ⇘ ⇙ ⇓ ⇘ ⇓ The goal of Peaceful chess queen armies is to arrange m black queens and m white queens on an n-by-n square grid, (the board), so that no queen attacks another of a different colour. Task Create a routine to represent two-colour queens on a 2-D board. (Alternating black/white background colours, Unicode chess pieces and other embellishments are not necessary, but may be used at your discretion). Create a routine to generate at least one solution to placing m equal numbers of black and white queens on an n square board. Display here results for the m=4, n=5 case. References Peaceably Coexisting Armies of Queens (Pdf) by Robert A. Bosch. Optima, the Mathematical Programming Socity newsletter, issue 62. A250000 OEIS
#Nim
Nim
import sequtils, strformat   type   Piece {.pure.} = enum Empty, Black, White Position = tuple[x, y: int]     func isAttacking(queen, pos: Position): bool = queen.x == pos.x or queen.y == pos.y or abs(queen.x - pos.x) == abs(queen.y - pos.y)     func place(m, n: int; blackQueens, whiteQueens: var seq[Position]): bool =   if m == 0: return true   var placingBlack = true for i in 0..<n: for j in 0..<n:   block inner: let pos: Position = (i, j) for queen in blackQueens: if queen == pos or not placingBlack and queen.isAttacking(pos): break inner for queen in whiteQueens: if queen == pos or placingBlack and queen.isAttacking(pos): break inner   if placingBlack: blackQueens.add pos else: whiteQueens.add pos if place(m - 1, n, blackQueens, whiteQueens): return true discard blackQueens.pop() discard whiteQueens.pop() placingBlack = not placingBlack   if not placingBlack: discard blackQueens.pop()     proc printBoard(n: int; blackQueens, whiteQueens: seq[Position]) =   var board = newSeqWith(n, newSeq[Piece](n)) # Initialized to Empty.   for queen in blackQueens: board[queen.x][queen.y] = Black for queen in whiteQueens: board[queen.x][queen.y] = White   for i in 0..<n: for j in 0..<n: stdout.write case board[i][j] of Black: "B " of White: "W " of Empty: (if (i and 1) == (j and 1): "• " else: "◦ ") stdout.write '\n'   echo ""     const Nms = [(2, 1), (3, 1), (3, 2), (4, 1), (4, 2), (4, 3), (5, 1), (5, 2), (5, 3), (5, 4), (5, 5), (6, 1), (6, 2), (6, 3), (6, 4), (6, 5), (6, 6), (7, 1), (7, 2), (7, 3), (7, 4), (7, 5), (7, 6), (7, 7)]   for (n, m) in Nms: echo &"{m} black and {m} white queens on a {n} x {n} board:" var blackQueens, whiteQueens: seq[Position] if place(m, n, blackQueens, whiteQueens): printBoard(n, blackQueens, whiteQueens) else: echo "No solution exists.\n"
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
#F.23
F#
  // A function to generate passwords of a given length. Nigel Galloway: May 2nd., 2018 let N = (set)"qwertyuiopasdfghjklzxcvbnm" let I = (set)"QWERTYUIOPASDFGHJKLZXCVBNM" let G = (set)"7894561230" let E = (set)"""!"#$%&'()*+,-./:;<=>?@[]^_{|}~[||]""" let L = Array.ofSeq (Set.unionMany [N;I;G;E]) let y = System.Random 23 let pWords n= let fN n = not (Set.isEmpty (Set.intersect N n )||Set.isEmpty (Set.intersect I n )||Set.isEmpty (Set.intersect G n )||Set.isEmpty (Set.intersect E n )) Seq.initInfinite(fun _->(set)(List.init n (fun _->L.[y.Next()%(Array.length L)])))|>Seq.filter fN|>Seq.map(Set.toArray >> System.String)  
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
#SAS
SAS
/* Store permutations in a SAS dataset. Translation of Fortran 77 */ data perm; n=6; array a{6} p1-p6; do i=1 to n; a(i)=i; end; L1: output; link L2; if next then goto L1; stop; L2: next=0; i=n-1; L10: if a(i)<a(i+1) then goto L20; i=i-1; if i=0 then goto L20; goto L10; L20: j=i+1; k=n; L30: t=a(j); a(j)=a(k); a(k)=t; j=j+1; k=k-1; if j<k then goto L30; j=i; if j=0 then return; L40: j=j+1; if a(j)<a(i) then goto L40; t=a(i); a(i)=a(j); a(j)=t; next=1; return; keep p1-p6; run;
http://rosettacode.org/wiki/Peano_curve
Peano curve
Task Produce a graphical or ASCII-art representation of a Peano curve of at least order 3.
#Rust
Rust
// [dependencies] // svg = "0.8.0"   use svg::node::element::path::Data; use svg::node::element::Path;   struct PeanoCurve { current_x: f64, current_y: f64, current_angle: i32, line_length: f64, }   impl PeanoCurve { fn new(x: f64, y: f64, length: f64, angle: i32) -> PeanoCurve { PeanoCurve { current_x: x, current_y: y, current_angle: angle, line_length: length, } } fn rewrite(order: usize) -> String { let mut str = String::from("L"); for _ in 0..order { let mut tmp = String::new(); for ch in str.chars() { match ch { 'L' => tmp.push_str("LFRFL-F-RFLFR+F+LFRFL"), 'R' => tmp.push_str("RFLFR+F+LFRFL-F-RFLFR"), _ => tmp.push(ch), } } str = tmp; } str } fn execute(&mut self, order: usize) -> Path { let mut data = Data::new().move_to((self.current_x, self.current_y)); for ch in PeanoCurve::rewrite(order).chars() { match ch { 'F' => data = self.draw_line(data), '+' => self.turn(90), '-' => self.turn(-90), _ => {} } } Path::new() .set("fill", "none") .set("stroke", "black") .set("stroke-width", "1") .set("d", data) } fn draw_line(&mut self, data: Data) -> Data { let theta = (self.current_angle as f64).to_radians(); self.current_x += self.line_length * theta.cos(); self.current_y += self.line_length * theta.sin(); data.line_to((self.current_x, self.current_y)) } fn turn(&mut self, angle: i32) { self.current_angle = (self.current_angle + angle) % 360; } fn save(file: &str, size: usize, order: usize) -> std::io::Result<()> { use svg::node::element::Rectangle; let rect = Rectangle::new() .set("width", "100%") .set("height", "100%") .set("fill", "white"); let mut p = PeanoCurve::new(8.0, 8.0, 8.0, 90); let document = svg::Document::new() .set("width", size) .set("height", size) .add(rect) .add(p.execute(order)); svg::save(file, &document) } }   fn main() { PeanoCurve::save("peano_curve.svg", 656, 4).unwrap(); }
http://rosettacode.org/wiki/Peano_curve
Peano curve
Task Produce a graphical or ASCII-art representation of a Peano curve of at least order 3.
#Sidef
Sidef
var rules = Hash( l => 'lFrFl-F-rFlFr+F+lFrFl', r => 'rFlFr+F+lFrFl-F-rFlFr', )   var lsys = LSystem( width: 500, height: 500,   xoff: -50, yoff: -50,   len: 5, angle: 90, color: 'dark green', )   lsys.execute('l', 4, "peano_curve.png", rules)
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).
#Perl
Perl
  #!usr/bin/perl use 5.020; use strict; use warnings;   #Choose who goes first binaryRand() == 0 ? flipCoin(userFirst()) : flipCoin(compFirst());   #Return a randomly generated 1 or 0 sub binaryRand { return int(rand(2)); } #Converts 1's and 0's to H's and T's, respectively. sub convert { my $randNum = binaryRand(); if($randNum == 0) { return "T" } else { return "H"; } }   #Prompts for and returns a user's sequence of 3 sub uSeq { print("Please enter a sequence of 3 of \"H\" and \"T\". EG: HHT\n>"); my $uString = <STDIN>;   while(1) { #Make it uppercase and validate input chomp($uString); $uString = uc $uString; #Check length and content (H's and T's only!) if(length $uString == 3 && (substr($uString, 0, 1) =~ /[HT]/ && substr($uString, 1, 1) =~ /[HT]/ && substr($uString, 2, 1) =~ /[HT]/)) { last; } else { print("Error, try again. \n"); print("Please enter a sequence of 3 of \"H\" and \"T\". EG: HHT\n"); $uString = <STDIN>; } } return $uString; }   #Returns an array with two elements: [0] user's seq, [1] random computer seq. sub compFirst { my $cSeq; #Randomly draw a sequence of 3 for(my $i = 0; $i < 3; $i++) { $cSeq = $cSeq . convert(); }   print("The computer guesses first:\ncomp- $cSeq\n"); my $uSeq = uSeq(); print("user- $uSeq\n"); my @seqArr = ($uSeq, $cSeq); return @seqArr; }   #Returns an array with two elements: [0] user's seq, [1] optimal computer seq. sub userFirst { print("The user quesses first:\n"); my $uSeq = uSeq(); my $cSeq; #Generate the optimal sequence based on $uSeq my $middle = substr($uSeq, 1, 1); $middle eq "H" ? $cSeq = "T" : $cSeq = "H"; $cSeq = $cSeq . substr($uSeq, 0, 2);   print("user- $uSeq\ncomp- $cSeq\n"); my @seqArr = ($uSeq, $cSeq); return @seqArr; }   #Flips a coin, checking both sequences against the contents of the given array sub flipCoin { my ($uSeq, $cSeq) = @_; my $coin; while(1) { $coin = $coin . convert(); if($coin =~ m/$uSeq/) { print("The sequence of tosses was: $coin\n"); say("The player wins! "); last; } elsif($coin =~ m/$cSeq/) { print("The sequence of tosses was: $coin\n"); say("The computer wins! "); last; } } }  
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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
v[1] = 2; v[2] = -4; v[n_] := Once[111 - 1130/v[n - 1] + 3000/(v[n - 1]*v[n - 2])] N[Map[v, {3, 4, 5, 6, 7, 8, 20, 30, 50, 100}], 80]
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.
#ALGOL_68
ALGOL 68
BEGIN # returns an upper Pascal matrix of size n # PROC upper pascal matrix = ( INT n )[,]INT: BEGIN [ 1 : n, 1 : n ]INT result; FOR j TO n DO result[ 1, j ] := 1 OD; FOR i FROM 2 TO n DO result[ i, 1 ] := 0; FOR j FROM 2 TO n DO result[ i, j ] := result[ i - 1, j - 1 ] + result[ i, j - 1 ] OD OD; result END # upper pascal matrix # ;   # returns a lower Pascal matrix of size n # PROC lower pascal matrix = ( INT n )[,]INT: BEGIN [ 1 : n, 1 : n ]INT result; FOR i TO n DO result[ i, 1 ] := 1 OD; FOR j FROM 2 TO n DO result[ 1, j ] := 0; FOR i FROM 2 TO n DO result[ i, j ] := result[ i - 1, j - 1 ] + result[ i - 1, j ] OD OD; result END # lower pascal matrix # ;   # returns a symmetric Pascal matrix of size n # PROC symmetric pascal matrix = ( INT n )[,]INT: BEGIN [ 1 : n, 1 : n ]INT result; FOR i TO n DO result[ i, 1 ] := 1; result[ 1, i ] := 1 OD; FOR j FROM 2 TO n DO FOR i FROM 2 TO n DO result[ i, j ] := result[ i, j - 1 ] + result[ i - 1, j ] OD OD; result END # symmetric pascal matrix # ;   # print the matrix m with the specified field width # PROC print matrix = ( [,]INT m, INT field width )VOID: BEGIN FOR i FROM 1 LWB m TO 1 UPB m DO FOR j FROM 2 LWB m TO 2 UPB m DO print( ( " ", whole( m[ i, j ], - field width ) ) ) OD; print( ( newline ) ) OD END # print matrix # ;   print( ( "upper:", newline ) ); print matrix( upper pascal matrix( 5 ), 2 ); print( ( "lower:", newline ) ); print matrix( lower pascal matrix( 5 ), 2 ); print( ( "symmetric:", newline ) ); print matrix( symmetric pascal matrix( 5 ), 2 )   END
http://rosettacode.org/wiki/Pascal%27s_triangle
Pascal's triangle
Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is either 1 or the sum of the two elements right above it. For example, the next row of the triangle would be:   1   (since the first element of each row doesn't have two elements above it)   4   (1 + 3)   6   (3 + 3)   4   (3 + 1)   1   (since the last element of each row doesn't have two elements above it) So the triangle now looks like this: 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 Each row   n   (starting with row   0   at the top) shows the coefficients of the binomial expansion of   (x + y)n. Task Write a function that prints out the first   n   rows of the triangle   (with   f(1)   yielding the row consisting of only the element 1). This can be done either by summing elements from the previous rows or using a binary coefficient or combination function. Behavior for   n ≤ 0   does not need to be uniform, but should be noted. See also Evaluate binomial coefficients
#Ada
Ada
package Pascal is   type Row is array (Natural range <>) of Natural;   function Length(R: Row) return Positive;   function First_Row(Max_Length: Positive) return Row;   function Next_Row(R: Row) return Row;   end Pascal;
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.
#11l
11l
-V ops = ‘-+/*^’   F postfix_to_infix(postfix) T Expression String op, ex prec = 3   F (String e1, e2 = ‘’, o = ‘’) I o == ‘’ .ex = e1 E .ex = e1‘ ’o‘ ’e2 .op = o .prec = :ops.index(o) I/ 2   F String() R .ex   [Expression] expr   L(token) postfix.split(re:‘\s+’) V c = token[0] V? idx = :ops.find(c) I idx != N V r = expr.pop() V l = expr.pop() V opPrec = idx I/ 2   I l.prec < opPrec | (l.prec == opPrec & c == ‘^’) l.ex = ‘(’l.ex‘)’   I r.prec < opPrec | (r.prec == opPrec & c != ‘^’) r.ex = ‘(’r.ex‘)’ expr.append(Expression(l.ex, r.ex, token)) E expr.append(Expression(token))   print(token‘ -> ’expr)   assert(expr.len == 1) R expr[0].ex   L(e) [‘3 4 2 * 1 5 - 2 3 ^ ^ / +’, ‘1 2 + 3 4 + ^ 5 6 + ^’] print(‘Postfix : ’e) print(‘Infix : ’postfix_to_infix(e)) print()
http://rosettacode.org/wiki/Partial_function_application
Partial function application
Partial function application   is the ability to take a function of many parameters and apply arguments to some of the parameters to create a new function that needs only the application of the remaining arguments to produce the equivalent of applying all arguments to the original function. E.g: Given values v1, v2 Given f(param1, param2) Then partial(f, param1=v1) returns f'(param2) And f(param1=v1, param2=v2) == f'(param2=v2) (for any value v2) Note that in the partial application of a parameter, (in the above case param1), other parameters are not explicitly mentioned. This is a recurring feature of partial function application. Task Create a function fs( f, s ) that takes a function, f( n ), of one value and a sequence of values s. Function fs should return an ordered sequence of the result of applying function f to every value of s in turn. Create function f1 that takes a value and returns it multiplied by 2. Create function f2 that takes a value and returns it squared. Partially apply f1 to fs to form function fsf1( s ) Partially apply f2 to fs to form function fsf2( s ) Test fsf1 and fsf2 by evaluating them with s being the sequence of integers from 0 to 3 inclusive and then the sequence of even integers from 2 to 8 inclusive. Notes In partially applying the functions f1 or f2 to fs, there should be no explicit mention of any other parameters to fs, although introspection of fs within the partial applicator to find its parameters is allowed. This task is more about how results are generated rather than just getting results.
#BBC_BASIC
BBC BASIC
fsf1 = FNpartial(PROCfs(), FNf1()) fsf2 = FNpartial(PROCfs(), FNf2())   DIM seq(3) PRINT "Calling function fsf1 with sequence 1:" seq() = 0, 1, 2, 3 : PROC(fsf1)(seq()) FOR i% = 0 TO 3 : PRINT seq(i%); : NEXT : PRINT PRINT "Calling function fsf1 with sequence 2:" seq() = 2, 4, 6, 8 : PROC(fsf1)(seq()) FOR i% = 0 TO 3 : PRINT seq(i%); : NEXT : PRINT PRINT "Calling function fsf2 with sequence 1:" seq() = 0, 1, 2, 3 : PROC(fsf2)(seq()) FOR i% = 0 TO 3 : PRINT seq(i%); : NEXT : PRINT PRINT "Calling function fsf2 with sequence 2:" seq() = 2, 4, 6, 8 : PROC(fsf2)(seq()) FOR i% = 0 TO 3 : PRINT seq(i%); : NEXT : PRINT END   REM Create a partial function: DEF FNpartial(RETURN f1%, RETURN f2%) LOCAL f$, p% DIM p% 7 : p%!0 = f1% : p%!4 = f2% f$ = "(s())" + CHR$&F2 + "(&" + STR$~p% + ")(" + \ \ CHR$&A4 + "(&" + STR$~(p%+4) + ")(),s()):" + CHR$&E1 DIM p% LEN(f$) + 4 $(p%+4) = f$ : !p% = p%+4 = p%   REM Replaces the input sequence with the output sequence: DEF PROCfs(RETURN f%, seq()) LOCAL i% FOR i% = 0 TO DIM(seq(),1) seq(i%) = FN(^f%)(seq(i%)) NEXT ENDPROC   DEF FNf1(n) = n * 2   DEF FNf2(n) = n ^ 2
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.
#Bracmat
Bracmat
( (fs=/('(x./('(y.map'($x.$y)))))) & (f1=/('(x.$x*2))) & (f2=/('(x.$x^2))) & (partial=/('(x./('(y.($x)$($y)))))) & (!partial$!fs)$!f1:?fsf1 & (!partial$!fs)$!f2:?fsf2 & out$(!fsf1$(0 1 2 3)) & out$(!fsf2$(0 1 2 3)) & out$(!fsf1$(2 4 6 8)) & out$(!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
#Go
Go
package main   import ( "fmt" "log" )   var ( primes = sieve(100000) foundCombo = false )   func sieve(limit uint) []uint { primes := []uint{2} c := make([]bool, limit+1) // composite = true // no need to process even numbers > 2 p := uint(3) for { p2 := p * p if p2 > limit { break } for i := p2; i <= limit; i += 2 * p { c[i] = true } for { p += 2 if !c[p] { break } } } for i := uint(3); i <= limit; i += 2 { if !c[i] { primes = append(primes, i) } } return primes }   func findCombo(k, x, m, n uint, combo []uint) { if k >= m { sum := uint(0) for _, c := range combo { sum += primes[c] } if sum == x { s := "s" if m == 1 { s = " " } fmt.Printf("Partitioned %5d with %2d prime%s: ", x, m, s) for i := uint(0); i < m; i++ { fmt.Print(primes[combo[i]]) if i < m-1 { fmt.Print("+") } else { fmt.Println() } } foundCombo = true } } else { for j := uint(0); j < n; j++ { if k == 0 || j > combo[k-1] { combo[k] = j if !foundCombo { findCombo(k+1, x, m, n, combo) } } } } }   func partition(x, m uint) error { if !(x >= 2 && m >= 1 && m < x) { return fmt.Errorf("x must be at least 2 and m in [1, x)") } n := uint(0) for _, prime := range primes { if prime <= x { n++ } } if n < m { return fmt.Errorf("not enough primes") } combo := make([]uint, m) foundCombo = false findCombo(0, x, m, n, combo) if !foundCombo { s := "s" if m == 1 { s = " " } fmt.Printf("Partitioned %5d with %2d prime%s: (impossible)\n", x, m, s) } return nil }   func main() { a := [...][2]uint{ {99809, 1}, {18, 2}, {19, 3}, {20, 4}, {2017, 24}, {22699, 1}, {22699, 2}, {22699, 3}, {22699, 4}, {40355, 3}, } for _, p := range a { err := partition(p[0], p[1]) if err != nil { log.Println(err) } } }
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
#JavaScript
JavaScript
  function p(n){ var a = new Array(n+1) a[0] = 1n   for (let i = 1; i <= n; i++){ a[i] = 0n for (let k = 1, s = 1; s <= i;){ a[i] += (k & 1 ? a[i-s]:-a[i-s]) k > 0 ? (s += k, k = -k):(k = -k+1, s = k*(3*k-1)/2) } }   return a[n] }   var t = Date.now() console.log("p(6666) = " + p(6666)) console.log("Computation time in ms: ", Date.now() - t)  
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.
#Go
Go
package main   import "fmt"   // representation of an expression in x, y, and z type expr struct { x, y, z float64 // coefficients c float64 // constant term }   // add two expressions func addExpr(a, b expr) expr { return expr{a.x + b.x, a.y + b.y, a.z + b.z, a.c + b.c} }   // subtract two expressions func subExpr(a, b expr) expr { return expr{a.x - b.x, a.y - b.y, a.z - b.z, a.c - b.c} }   // multiply expression by a constant func mulExpr(a expr, c float64) expr { return expr{a.x * c, a.y * c, a.z * c, a.c * c} }   // given a row of expressions, produce the next row up, by the given // sum relation between blocks func addRow(l []expr) []expr { if len(l) == 0 { panic("wrong") } r := make([]expr, len(l)-1) for i := range r { r[i] = addExpr(l[i], l[i+1]) } return r }   // given expression b in a variable, and expression a, // take b == 0 and substitute to remove that variable from a. func substX(a, b expr) expr { if b.x == 0 { panic("wrong") } return subExpr(a, mulExpr(b, a.x/b.x)) }   func substY(a, b expr) expr { if b.y == 0 { panic("wrong") } return subExpr(a, mulExpr(b, a.y/b.y)) }   func substZ(a, b expr) expr { if b.z == 0 { panic("wrong") } return subExpr(a, mulExpr(b, a.z/b.z)) }   // given an expression in a single variable, return value of that variable func solveX(a expr) float64 { if a.x == 0 || a.y != 0 || a.z != 0 { panic("wrong") } return -a.c / a.x }   func solveY(a expr) float64 { if a.x != 0 || a.y == 0 || a.z != 0 { panic("wrong") } return -a.c / a.y }   func solveZ(a expr) float64 { if a.x != 0 || a.y != 0 || a.z == 0 { panic("wrong") } return -a.c / a.z }   func main() { // representation of given information for bottom row r5 := []expr{{x: 1}, {c: 11}, {y: 1}, {c: 4}, {z: 1}} fmt.Println("bottom row:", r5)   // given definition of brick sum relation r4 := addRow(r5) fmt.Println("next row up:", r4) r3 := addRow(r4) fmt.Println("middle row:", r3)   // given relation y = x + z xyz := subExpr(expr{y: 1}, expr{x: 1, z: 1}) fmt.Println("xyz relation:", xyz) // remove z from third cell using xyz relation r3[2] = substZ(r3[2], xyz) fmt.Println("middle row after substituting for z:", r3)   // given cell = 40, b := expr{c: 40} // this gives an xy relation xy := subExpr(r3[0], b) fmt.Println("xy relation:", xy) // substitute 40 for cell r3[0] = b   // remove x from third cell using xy relation r3[2] = substX(r3[2], xy) fmt.Println("middle row after substituting for x:", r3)   // continue applying brick sum relation to get top cell r2 := addRow(r3) fmt.Println("next row up:", r2) r1 := addRow(r2) fmt.Println("top row:", r1)   // given top cell = 151, we have an equation in y y := subExpr(r1[0], expr{c: 151}) fmt.Println("y relation:", y) // using xy relation, we get an equation in x x := substY(xy, y) fmt.Println("x relation:", x) // using xyz relation, we get an equation in z z := substX(substY(xyz, y), x) fmt.Println("z relation:", z)   // show final answers fmt.Println("x =", solveX(x)) fmt.Println("y =", solveY(y)) fmt.Println("z =", solveZ(z)) }
http://rosettacode.org/wiki/Peaceful_chess_queen_armies
Peaceful chess queen armies
In chess, a queen attacks positions from where it is, in straight lines up-down and left-right as well as on both its diagonals. It attacks only pieces not of its own colour. ⇖ ⇑ ⇗ ⇐ ⇐ ♛ ⇒ ⇒ ⇙ ⇓ ⇘ ⇙ ⇓ ⇘ ⇓ The goal of Peaceful chess queen armies is to arrange m black queens and m white queens on an n-by-n square grid, (the board), so that no queen attacks another of a different colour. Task Create a routine to represent two-colour queens on a 2-D board. (Alternating black/white background colours, Unicode chess pieces and other embellishments are not necessary, but may be used at your discretion). Create a routine to generate at least one solution to placing m equal numbers of black and white queens on an n square board. Display here results for the m=4, n=5 case. References Peaceably Coexisting Armies of Queens (Pdf) by Robert A. Bosch. Optima, the Mathematical Programming Socity newsletter, issue 62. A250000 OEIS
#Perl
Perl
use strict; use warnings;   my $m = shift // 4; my $n = shift // 5; my %seen; my $gaps = join '|', qr/-*/, map qr/.{$_}(?:-.{$_})*/s, $n-1, $n, $n+1; my $attack = qr/(\w)(?:$gaps)(?!\1)\w/;   place( scalar ('-' x $n . "\n") x $n ); print "No solution to $m $n\n";   sub place { local $_ = shift; $seen{$_}++ || /$attack/ and return; # previously or attack (my $have = tr/WB//) < $m * 2 or exit !print "Solution to $m $n\n\n$_"; place( s/-\G/ qw(W B)[$have % 2] /er ) while /-/g; # place next queen }
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
#Factor
Factor
USING: arrays assocs combinators command-line continuations io kernel math math.parser multiline namespaces peg.ebnf prettyprint random sequences ; FROM: sets => without ; IN: rosetta-code.password-generator   STRING: usage password-generator generates random passwords.   Commands: -l [int>=4] Set password length (required) -c [int>0] Set password count (required) -s [int] Set seed for random number generator -x Exclude similar characters [empty] Show this help ;   ! Parse command line arguments into assoc EBNF: parse-args [=[ int = "-"? [0-9]+ => [[ concat sift string>number ]] l = "-l" " "~ int ?[ 4 >= ]? c = "-c" " "~ int ?[ 0 > ]? s = "-s" " "~ int x = "-x" => [[ 0 2array ]] arg = l | c | s | x args = arg ((" "~ arg)+)? => [[ first2 [ 1array ] dip append ]] ]=]   CONSTANT: similar { "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "0123456789" "!\"#$%&'()*+,-./:;<=>?@[]^_{|}~" }   : dissimilar ( -- seq ) similar [ "Il1O05S2Z" without ] map ;   ! Set seed if seed provided; otherwise use system rng. : choose-rng ( args-assoc -- ) "-s" of [ [ random-generator get ] dip seed-random drop ] [ system-random-generator get random-generator set ] if* ;   : choose-character-set ( args-assoc -- seq ) "-x" of dissimilar similar ? ;   ! Create a "base" for a password; one character from each ! category. : <base> ( seq -- str ) [ random ] "" map-as ;   : password ( seq length -- str ) 4 - over concat [ random ] curry "" replicate-as [ <base> ] dip append randomize ;   : .passwords ( count seq length -- ) [ password print ] 2curry times ;   : gen-pwds ( args-assoc -- ) { [ choose-rng ] [ "-c" of ] [ choose-character-set ] [ "-l" of ] } cleave .passwords ;   : main ( -- ) command-line get " " join [ parse-args gen-pwds ] [ 2drop usage print ] recover ;   MAIN: main
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
#Scala
Scala
List(1, 2, 3).permutations.foreach(println)
http://rosettacode.org/wiki/Peano_curve
Peano curve
Task Produce a graphical or ASCII-art representation of a Peano curve of at least order 3.
#VBA
VBA
Const WIDTH = 243 'a power of 3 for a evenly spaced curve Dim n As Long Dim points() As Single Dim flag As Boolean 'Store the coordinate pairs (x, y) generated by Peano into 'a SafeArrayOfPoints with lineto. The number of points 'generated depend on WIDTH. Peano is called twice. Once 'to count the number of points, and twice to generate 'the points after the dynamic array has been 'redimensionalised. 'VBA doesn't have a lineto method. Instead of AddLine, which 'requires four parameters, including the begin pair of 'coordinates, the method AddPolyline is used, which is 'called from main after all the points are generated. 'This creates a single object, whereas AddLine would 'create thousands of small unconnected line objects. Private Sub lineto(x As Integer, y As Integer) If flag Then points(n, 1) = x points(n, 2) = y End If n = n + 1 End Sub Private Sub Peano(ByVal x As Integer, ByVal y As Integer, ByVal lg As Integer, _ ByVal i1 As Integer, ByVal i2 As Integer) If (lg = 1) Then Call lineto(x * 3, y * 3) Exit Sub End If lg = lg / 3 Call Peano(x + (2 * i1 * lg), y + (2 * i1 * lg), lg, i1, i2) Call Peano(x + ((i1 - i2 + 1) * lg), y + ((i1 + i2) * lg), lg, i1, 1 - i2) Call Peano(x + lg, y + lg, lg, i1, 1 - i2) Call Peano(x + ((i1 + i2) * lg), y + ((i1 - i2 + 1) * lg), lg, 1 - i1, 1 - i2) Call Peano(x + (2 * i2 * lg), y + (2 * (1 - i2) * lg), lg, i1, i2) Call Peano(x + ((1 + i2 - i1) * lg), y + ((2 - i1 - i2) * lg), lg, i1, i2) Call Peano(x + (2 * (1 - i1) * lg), y + (2 * (1 - i1) * lg), lg, i1, i2) Call Peano(x + ((2 - i1 - i2) * lg), y + ((1 + i2 - i1) * lg), lg, 1 - i1, i2) Call Peano(x + (2 * (1 - i2) * lg), y + (2 * i2 * lg), lg, 1 - i1, i2) End Sub Sub main() n = 1: flag = False Call Peano(0, 0, WIDTH, 0, 0) 'Start Peano recursion to count number of points ReDim points(1 To n - 1, 1 To 2) n = 1: flag = True Call Peano(0, 0, WIDTH, 0, 0) 'Start Peano recursion to generate and store points ActiveSheet.Shapes.AddPolyline points 'Excel assumed End Sub
http://rosettacode.org/wiki/Peano_curve
Peano curve
Task Produce a graphical or ASCII-art representation of a Peano curve of at least order 3.
#Wren
Wren
import "graphics" for Canvas, Color, Point import "dome" for Window   class Game { static init() { Window.title = "Peano curve" Canvas.resize(820, 820) Window.resize(820, 820) Canvas.cls(Color.white) // white background __points = [] __width = 81 peano(0, 0, __width, 0, 0) var col = Color.rgb(255, 0, 255) // magenta var prev = __points[0] for (p in __points.skip(1)) { var curr = p Canvas.line(prev.x, prev.y, curr.x, curr.y, col) prev = curr } }   static peano(x, y, lg, i1, i2) { if (lg == 1) { var px = (__width - x) * 10 var py = (__width - y) * 10 __points.add(Point.new(px, py)) return } lg = (lg/3).floor peano(x+2*i1*lg, y+2*i1*lg, lg, i1, i2) peano(x+(i1-i2+1)*lg, y+(i1+i2)*lg, lg, i1, 1-i2) peano(x+lg, y+lg, lg, i1, 1-i2) peano(x+(i1+i2)*lg, y+(i1-i2+1)*lg, lg, 1-i1, 1-i2) peano(x+2*i2*lg, y+2*(1-i2)*lg, lg, i1, i2) peano(x+(1+i2-i1)*lg, y+(2-i1-i2)*lg, lg, i1, i2) peano(x+2*(1-i1)*lg, y+2*(1-i1)*lg, lg, i1, i2) peano(x+(2-i1-i2)*lg, y+(1+i2-i1)*lg, lg, 1-i1, i2) peano(x+2*(1-i2)*lg, y+2*i2*lg, lg, 1-i1, i2) }   static update() {}   static draw(dt) {} }
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).
#Phix
Phix
function trio(integer pick) return substitute_all(sprintf("%03b",pick),"10","HT") end function   function getuser(integer bot) integer user while 1 do user = 8 -- (a bit that clears after 3 shifts) printf(1,"Enter your sequence of 3 (H/T):"); while user>7 do integer c = upper(wait_key()) if c=#1B then abort(0) end if -- (Escape) if find(c,"HT") then puts(1,c) user = and_bits(user*2+(c='H'),0b111111) end if end while if user!=bot then exit end if printf(1,"\nYou may not pick the same as Robort!\n") end while printf(1,"\n") return user end function   function getbot(int user) int bot = iff(user=-1?rand(8)-1  :4-and_bits(user,2)*2+floor(user/2)) printf(1,"Robort picks %s\n", {trio(bot)}) return bot end function   function rungame(integer user, bot) /* We only need to store the last 3 tosses, as 0..7 */ int last3 = rand(8)-1   printf(1,"Rolling: %s",{trio(last3)}) while 1 do if user=last3 then printf(1,"\nUser wins!\n") return 1 elsif bot=last3 then printf(1,"\nRobort wins!\n") return 0 end if last3 = and_bits(last3,3)*2+(rand(2)=1) printf(1,"%c", iff(and_bits(last3,1) ? 'H' : 'T')) sleep(0.5) end while end function   procedure main() integer playerwins = 0, totalgames = 0, robortwins = 0   /* Just use ctrl-c or Escape to exit */ while 1 do integer user = -1, bot = -1   printf(1,"\n") if rand(2)=1 then bot = getbot(-1) user = getuser(bot) else user = getuser(-1) bot = getbot(user) end if   playerwins += rungame(user, bot) totalgames += 1 robortwins = totalgames-playerwins   printf(1,"Robort:%d You:%d out of %d games\n", {robortwins, playerwins, totalgames}) printf(1,"==================================\n") end while   end procedure main()
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).
#PicoLisp
PicoLisp
(seed (in "/dev/urandom" (rd 8)))   (setq *S (list 0 0))   (de toss (N) (make (do N (link (if (rand T) "T" "H")) ) ) )   (de comp (A Lst) (or (for ((I . L) Lst (cddr L) (cdr L)) (T (fully = A L) I) ) T ) )   (de score NIL (prinl) (prinl "Total score:") (prinl "^Iuser: " (car *S)) (prinl "^Icomp: " (cadr *S)) )   (de play NIL (let (C (toss 3) Lst (toss (rand 5 12)) U) (prinl) (prin "Select toss: ") (setq U (in NIL (skip) (line))) (prinl "Comp toss: " C) (prinl "Toss: " Lst) (setq @ (comp U Lst) @@ (comp C Lst) ) (cond ((< @ @@) (prinl "User win.") (inc *S)) ((> @ @@) (prinl "Comp win.") (inc (cdr *S))) (T (prinl "Draw, lets play again.")) ) (score) ) )   (de go NIL (loop (play) (T (prog (prinl) (prin "Want play again? Y/N: ") (= "N" (uppc (in NIL (char)))) ) ) ) )   (go)
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.
#Nim
Nim
import math, strutils, strformat import decimal import bignum   #################################################################################################### # Utilities.   proc format[T: DecimalType|Rat](val: T; intLen, fractLen: Positive): string = ## Format a decimal or a rational with "intLen" integer digits and "fractLen" ## fractional digits. let s = when T is DecimalType: ($val).split('.') else: ($val.toFloat).split('.')   result = s[0].align(intLen) & '.' if s[1].len < fractLen: result.add s[1].alignLeft(fractLen, '0') else: result.add s[1][0..<fractLen]     proc `^`(a: Rat; b: Natural): Rat = ## Missing exponentiation operator for rationals. ## Adaptation of operator for floats. case b of 0: result = newRat(1) of 1: result = a of 2: result = a * a of 3: result = a * a * a else: var (a, b) = (a.clone, b) result = newRat(1) while true: if (b and 1) != 0: result *= a b = b shr 1 if b == 0: break a *= a     #################################################################################################### # Task 1.   proc v[T: float|DecimalType|Rat](n: Positive): seq[T] = ## Return the "n" first values for sequence "Vn". var (v1, v2) = when T is float: (2.0, -4.0) elif T is Rat: (newRat(2), newRat(-4)) else: (newDecimal(2), newDecimal(-4))   result.add default(T) # Dummy value to start at index one. result.add v1 result.add v2 for _ in 3..n: # Need to change evaluation order to avoid a bug with rationals. result.add 3000 / (result[^1] * result[^2]) - 1130 / result[^1] + 111     setPrec(130) # Default precision is not sufficient.   let vfloat = v[float](100) let vdecimal = v[DecimalType](100) let vrational = v[Rat](100)   echo "Task 1" echo " n v(n) float v(n) decimal v(n) rational" for n in [3, 4, 5, 6, 7, 8, 20, 30, 50, 100]: echo &"{n:>3} {vfloat[n]:>20.16f} {vdecimal[n].format(3, 16)} {vrational[n].format(3, 16)}"     #################################################################################################### # Task 2.   proc balance[T: float|DecimalType|Rat](): T = ## Return the balance after 25 years. result = when T is float: E - 1 elif T is DecimalType: exp(newDecimal(1)) - 1 else: newInt("17182818284590452353602874713526624977572470") / newInt("10000000000000000000000000000000000000000000")   var n = when T is float: 1.0 else: 1 while n <= 25: result = result * n - 1 n += 1   echo "\nTask 2." echo "Balance after 25 years (float): ", (&"{balance[float]():.16f}")[0..17] echo "Balance after 25 years (decimal): ", balance[DecimalType]().format(1, 16) echo "Balance after 25 years: (rational): ", balance[Rat]().format(1, 16)     #################################################################################################### # Task 3.   const A = 77617 B = 33096   proc rump[T: float|DecimalType|Rat](a, b: T): T = ## Return the value of the Rump's function. let C1 = when T is float: 333.75 elif T is Rat: newRat(333.75) else: newDecimal("333.75") let C2 = when T is float: 5.5 elif T is Rat: newRat(5.5) else: newDecimal("5.5") result = C1 * b^6 + a^2 * (11 * a^2 * b^2 - b^6 - 121 * b^4 - 2) + C2 * b^8 + a / (2 * b)   echo "\nTask 3"   let rumpFloat = rump(A.toFloat, B.toFloat) let rumpDecimal = rump(newDecimal(A), newDecimal(B)) let rumpRational = rump(newRat(A), newRat(B))   echo &"f({A}, {B}) float = ", rumpFloat echo &"f({A}, {B}) decimal = ", rumpDecimal.format(1, 16) echo &"f({A}, {B}) rational = ", rumpRational.format(1, 16)
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.
#11l
11l
F infix_to_postfix(infix) -V ops = ‘-+/*^’ V sb = ‘’ [Int] s   L(token) infix.split(re:‘\s’) I token.empty L.continue   V c = token[0] V? idx = ops.find(c) I idx != N I s.empty s.append(idx) E L !s.empty V prec2 = s.last I/ 2 V prec1 = idx I/ 2 I prec2 > prec1 | (prec2 == prec1 & c != ‘^’) sb ‘’= ops[s.pop()]‘ ’ E L.break s.append(idx)   E I c == ‘(’ s.append(-2)   E I c == ‘)’ L s.last != -2 sb ‘’= ops[s.pop()]‘ ’ s.pop()   E sb ‘’= token‘ ’   L !s.empty sb ‘’= ops[s.pop()]‘ ’   R sb   V infix = ‘3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3’ print(‘infix: ’infix) print(‘postfix: ’infix_to_postfix(infix))
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.
#ALGOL_W
ALGOL W
begin  % initialises m to an upper Pascal matrix of size n %  % the bounds of m must be at least 1 :: n, 1 :: n  % procedure upperPascalMatrix ( integer array m( *, * )  ; integer value n ) ; begin for j := 1 until n do m( 1, j ) := 1; for i := 2 until n do begin m( i, 1 ) := 0; for j := 2 until n do m( i, j ) := m( i - 1, j - 1 ) + m( i, j - 1 ) end for_i end upperPascalMatrix ;    % initialises m to a lower Pascal matrix of size n  %  % the bounds of m must be at least 1 :: n, 1 :: n  % procedure lowerPascalMatrix ( integer array m( *, * )  ; integer value n ) ; begin for i := 1 until n do m( i, 1 ) := 1; for j := 2 until n do begin m( 1, j ) := 0; for i := 2 until n do m( i, j ) := m( i - 1, j - 1 ) + m( i - 1, j ) end for_j end lowerPascalMatrix ;    % initialises m to a symmetric Pascal matrix of size n %  % the bounds of m must be at least 1 :: n, 1 :: n  % procedure symmetricPascalMatrix ( integer array m( *, * )  ; integer value n ) ; begin for i := 1 until n do begin m( i, 1 ) := 1; m( 1, i ) := 1 end for_i; for j := 2 until n do for i := 2 until n do m( i, j ) := m( i, j - 1 ) + m( i - 1, j ) end symmetricPascalMatrix ;   begin % test the pascal matrix procedures %    % print the matrix m with the specified field width %  % the bounds of m must be at least 1 :: n, 1 :: n  % procedure printMatrix ( integer array m( *, * )  ; integer value n  ; integer value fieldWidth ) ; begin for i := 1 until n do begin write( i_w := fieldWidth, s_w := 0, " ", m( i, 1 ) ); for j := 2 until n do writeon( i_w := fieldWidth, s_w := 0, " ", m( i, j ) ) end for_i end printMatrix ;   integer array m( 1 :: 10, 1 :: 10 ); integer n, w;   n := 5; w := 2; upperPascalMatrix( m, n ); write( "upper:" ); printMatrix( m, n, w ); lowerPascalMatrix( m, n ); write( "lower:" ); printMatrix( m, n, w ); symmetricPascalMatrix( m, n ); write( "symmetric:" ); printMatrix( m, n, w )   end   end.
http://rosettacode.org/wiki/Pascal%27s_triangle
Pascal's triangle
Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is either 1 or the sum of the two elements right above it. For example, the next row of the triangle would be:   1   (since the first element of each row doesn't have two elements above it)   4   (1 + 3)   6   (3 + 3)   4   (3 + 1)   1   (since the last element of each row doesn't have two elements above it) So the triangle now looks like this: 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 Each row   n   (starting with row   0   at the top) shows the coefficients of the binomial expansion of   (x + y)n. Task Write a function that prints out the first   n   rows of the triangle   (with   f(1)   yielding the row consisting of only the element 1). This can be done either by summing elements from the previous rows or using a binary coefficient or combination function. Behavior for   n ≤ 0   does not need to be uniform, but should be noted. See also Evaluate binomial coefficients
#ALGOL_68
ALGOL 68
PRIO MINLWB = 8, MAXUPB = 8; OP MINLWB = ([]INT a,b)INT: (LWB a<LWB b|LWB a|LWB b), MAXUPB = ([]INT a,b)INT: (UPB a>UPB b|UPB a|UPB b);   OP + = ([]INT a,b)[]INT:( [a MINLWB b:a MAXUPB b]INT out; FOR i FROM LWB out TO UPB out DO out[i]:= 0 OD; out[LWB a:UPB a] := a; FOR i FROM LWB b TO UPB b DO out[i]+:= b[i] OD; out );   INT width = 4, stop = 9; FORMAT centre = $n((stop-UPB row+1)*width OVER 2)(q)$;   FLEX[1]INT row := 1; # example of rowing # FOR i WHILE printf((centre, $g(-width)$, row, $l$)); # WHILE # i < stop DO row := row[AT 1] + row[AT 2] OD
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.
#Ada
Ada
  type Priority is range 1..4; type Infix is record Precedence : Priority; Expression : Unbounded_String; end record; package Expression_Stack is new Generic_Stack (Infix); use Expression_Stack;   function Convert (RPN : String) return String is Arguments : Stack; procedure Pop ( Operation  : Character; Precedence  : Priority; Association : Priority ) is Right, Left : Infix; Result  : Infix; begin Pop (Right, Arguments); Pop (Left, Arguments); Result.Precedence := Association; if Left.Precedence < Precedence then Append (Result.Expression, '('); Append (Result.Expression, Left.Expression); Append (Result.Expression, ')'); else Append (Result.Expression, Left.Expression); end if; Append (Result.Expression, ' '); Append (Result.Expression, Operation); Append (Result.Expression, ' '); if Right.Precedence < Precedence then Append (Result.Expression, '('); Append (Result.Expression, Right.Expression); Append (Result.Expression, ')'); else Append (Result.Expression, Right.Expression); end if; Push (Result, Arguments); end Pop; Pointer : Integer := RPN'First; begin while Pointer <= RPN'Last loop case RPN (Pointer) is when ' ' => Pointer := Pointer + 1; when '0'..'9' => declare Start : constant Integer := Pointer; begin loop Pointer := Pointer + 1; exit when Pointer > RPN'Last or else RPN (Pointer) not in '0'..'9'; end loop; Push ( ( 4, To_Unbounded_String (RPN (Start..Pointer - 1)) ), Arguments ); end; when '+' | '-' => Pop (RPN (Pointer), 1, 1); Pointer := Pointer + 1; when '*' | '/' => Pop (RPN (Pointer), 2, 2); Pointer := Pointer + 1; when '^' => Pop (RPN (Pointer), 4, 3); Pointer := Pointer + 1; when others => raise Constraint_Error with "Syntax"; end case; end loop; declare Result : Infix; begin Pop (Result, Arguments); return To_String (Result.Expression); end; end Convert;  
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.
#C
C
#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <dlfcn.h> #include <sys/wait.h> #include <err.h>   typedef int (*intfunc)(int); typedef void (*pfunc)(int*, int);   pfunc partial(intfunc fin) { pfunc f; static int idx = 0; char cc[256], lib[256]; FILE *fp; sprintf(lib, "/tmp/stuff%d.so", ++idx); sprintf(cc, "cc -pipe -x c -shared -o %s -", lib);   fp = popen(cc, "w"); fprintf(fp, "#define t typedef\xat int _i,*i;t _i(*__)(_i);__ p =(__)%p;" "void _(i _1, _i l){while(--l>-1)l[_1]=p(l[_1]);}", fin); fclose(fp);   *(void **)(&f) = dlsym(dlopen(lib, RTLD_LAZY), "_"); unlink(lib); return f; }   int square(int a) { return a * a; }   int dbl(int a) { return a + a; }   int main() { int x[] = { 1, 2, 3, 4 }; int y[] = { 1, 2, 3, 4 }; int i;   pfunc f = partial(square); pfunc g = partial(dbl);   printf("partial square:\n"); f(x, 4); for (i = 0; i < 4; i++) printf("%d\n", x[i]);   printf("partial double:\n"); g(y, 4); for (i = 0; i < 4; i++) printf("%d\n", y[i]);   return 0; }
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
#Haskell
Haskell
import Data.List (delete, intercalate) import Data.Numbers.Primes (primes) import Data.Bool (bool)   -------------------- PRIME PARTITIONS --------------------- partitions :: Int -> Int -> [Int] partitions x n | n <= 1 = [ x | x == last ps ] | otherwise = go ps x n where ps = takeWhile (<= x) primes go ps_ x 1 = [ x | x `elem` ps_ ] go ps_ x n = ((flip bool [] . head) <*> null) (ps_ >>= found) where found p = ((flip bool [] . return . (p :)) <*> null) ((go =<< delete p . flip takeWhile ps_ . (>=)) (x - p) (pred n))   -------------------------- TEST --------------------------- main :: IO () main = mapM_ putStrLn $ (\(x, n) -> intercalate " -> " [ justifyLeft 9 ' ' (show (x, n)) , let xs = partitions x n in bool (tail $ concatMap (('+' :) . show) xs) "(no solution)" (null xs) ]) <$> concat [ [(99809, 1), (18, 2), (19, 3), (20, 4), (2017, 24)] , (,) 22699 <$> [1 .. 4] , [(40355, 3)] ]   ------------------------- GENERIC ------------------------- justifyLeft :: Int -> Char -> String -> String justifyLeft n c s = take n (s ++ replicate n c)
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
#Haskell
Haskell
{-# language DeriveFunctor #-}   ------------------------------------------------------------ -- memoization utilities   data Memo a = Node a (Memo a) (Memo a) deriving Functor   memo :: Integral a => Memo p -> a -> p memo (Node a l r) n | n == 0 = a | odd n = memo l (n `div` 2) | otherwise = memo r (n `div` 2 - 1)   nats :: Memo Int nats = Node 0 ((+1).(*2) <$> nats) ((*2).(+1) <$> nats)   ------------------------------------------------------------ -- calculating partitions   partitions :: Memo Integer partitions = partitionP <$> nats   partitionP :: Int -> Integer partitionP n | n < 2 = 1 | otherwise = sum $ zipWith (*) signs terms where terms = [ memo partitions (n - i) | i <- takeWhile (<= n) ofsets ] signs = cycle [1,1,-1,-1]   ofsets = scanl1 (+) $ mix [1,3..] [1,2..] where mix a b = concat $ zipWith (\x y -> [x,y]) a b   main = print $ partitionP 6666
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.
#Haskell
Haskell
puzzle = [["151"],["",""],["40","",""],["","","",""],["X","11","Y","4","Z"]]
http://rosettacode.org/wiki/Peaceful_chess_queen_armies
Peaceful chess queen armies
In chess, a queen attacks positions from where it is, in straight lines up-down and left-right as well as on both its diagonals. It attacks only pieces not of its own colour. ⇖ ⇑ ⇗ ⇐ ⇐ ♛ ⇒ ⇒ ⇙ ⇓ ⇘ ⇙ ⇓ ⇘ ⇓ The goal of Peaceful chess queen armies is to arrange m black queens and m white queens on an n-by-n square grid, (the board), so that no queen attacks another of a different colour. Task Create a routine to represent two-colour queens on a 2-D board. (Alternating black/white background colours, Unicode chess pieces and other embellishments are not necessary, but may be used at your discretion). Create a routine to generate at least one solution to placing m equal numbers of black and white queens on an n square board. Display here results for the m=4, n=5 case. References Peaceably Coexisting Armies of Queens (Pdf) by Robert A. Bosch. Optima, the Mathematical Programming Socity newsletter, issue 62. A250000 OEIS
#Phix
Phix
-- -- demo\rosetta\Queen_Armies.exw -- ============================= -- with javascript_semantics requires("1.0.2") -- (puts(fn,x,false) for p2js.js) string html = "" constant as_html = true constant queens = {``, `♛`, `<font color="green">♕</font>`, `<span style="color:red">?</span>`} procedure showboard(integer n, sequence blackqueens, whitequeens) sequence board = repeat(repeat('-',n),n) for i=1 to length(blackqueens) do integer {qi,qj} = blackqueens[i] board[qi,qj] = 'B' {qi,qj} = whitequeens[i] board[qi,qj] = 'W' end for if as_html then string out = sprintf("<br><b>## %d black and %d white queens on a %d-by-%d board</b><br>\n", {length(blackqueens),length(whitequeens),n,n}), tbl = "" out &= "<table style=\"font-weight:bold\">\n " for x=1 to n do for y=1 to n do if y=1 then tbl &= " </tr>\n <tr valign=\"middle\" align=\"center\">\n" end if integer xw = find({x,y},blackqueens)!=0, xb = find({x,y},whitequeens)!=0, dx = xw+xb*2+1 string ch = queens[dx], bg = iff(mod(x+y,2)?"":` bgcolor="silver"`) tbl &= sprintf(" <td style=\"width:14pt; height:14pt;\"%s>%s</td>\n",{bg,ch}) end for end for out &= tbl[11..$] out &= " </tr>\n</table>\n<br>\n" html &= out else integer b = length(blackqueens), w = length(whitequeens) printf(1,"%d black and %d white queens on a %d x %d board:\n", {b, w, n, n}) puts(1,join(board,"\n")&"\n") --  ?{n,blackqueens, whitequeens} end if end procedure function isAttacking(sequence queen, pos) integer {qi,qj} = queen, {pi,pj} = pos return qi=pi or qj=pj or abs(qi-pi)=abs(qj-pj) end function function place(integer m, n, sequence blackqueens = {}, whitequeens = {}) if m == 0 then showboard(n,blackqueens,whitequeens) return true end if bool placingBlack := true for i=1 to n do for j=1 to n do sequence pos := {i, j} for q=1 to length(blackqueens) do sequence queen := blackqueens[q] if queen == pos or ((not placingBlack) and isAttacking(queen, pos)) then pos = {} exit end if end for if pos!={} then for q=1 to length(whitequeens) do sequence queen := whitequeens[q] if queen == pos or (placingBlack and isAttacking(queen, pos)) then pos = {} exit end if end for if pos!={} then if placingBlack then blackqueens = append(deep_copy(blackqueens), pos) placingBlack = false else whitequeens = append(deep_copy(whitequeens), pos) if place(m-1, n, blackqueens, whitequeens) then return true end if blackqueens = blackqueens[1..$-1] whitequeens = whitequeens[1..$-1] placingBlack = true end if end if end if end for end for return false end function for n=2 to 7 do for m=1 to n-(n<5) do if not place(m,n) then string no = sprintf("Cannot place %d+ queen armies on a %d-by-%d board",{m,n,n}) if as_html then html &= sprintf("<b># %s</b><br><br>\n\n",{no}) else printf(1,"%s.\n", {no}) end if end if end for end for constant html_header = """ <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Queen Armies</title> </head> <body> <h2>queen armies</h2> """, -- or <div style="overflow:scroll; height:250px;"> html_footer = """ </body> </html> """ -- or </div> if as_html then if platform()=JS then puts(1,html,false) else integer fn = open("queen_armies.html","w") puts(fn,html_header) puts(fn,html) puts(fn,html_footer) close(fn) printf(1,"See queen_armies.html\n") end if end if ?"done" {} = wait_key()
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
#FreeBASIC
FreeBASIC
Dim As String charS(4) charS(1) = "0123456789" charS(2) = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" charS(3) = "abcdefghijklmnopqrstuvwxyz" charS(4) = "!""#$%&'()*+,-./:;<=>?@[]^_{|}~" charS(0) = charS(1) + charS(2) + charS(3) + charS(4)     Dim As Integer howBig, howMany Do Print !"------ Password Generator ------\n" Input "Longitud de la contrase¤a (n>=4): ", howBig If howBig < 1 Then Sleep: End   Input "Cantidad de contrase¤as (n>=1): ", howMany Loop While howMany < 1   Print !"\nGeneradas"; howMany; " contrase¤as de"; howBig; " caracteres"   Dim As Integer i = 0 Dim As String password, Ok, w While i < howMany password = "" Ok = "...." For j As Integer = 1 To howBig w = Mid(charS(0), Int(Rnd * Len(charS(0))) + 1, 1) For k As Byte = 1 To 4 If Instr(charS(k), w) Then Ok = Left(Ok, k-1) + "*" + Mid(Ok, k+1) Next k password += w Next j If Ok = "****" Then i += 1 Print Using "##. &"; i; password End If Wend Sleep  
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
#Scheme
Scheme
(define (insert l n e) (if (= 0 n) (cons e l) (cons (car l) (insert (cdr l) (- n 1) e))))   (define (seq start end) (if (= start end) (list end) (cons start (seq (+ start 1) end))))   (define (permute l) (if (null? l) '(()) (apply append (map (lambda (p) (map (lambda (n) (insert p n (car l))) (seq 0 (length p)))) (permute (cdr l))))))
http://rosettacode.org/wiki/Peano_curve
Peano curve
Task Produce a graphical or ASCII-art representation of a Peano curve of at least order 3.
#Yabasic
Yabasic
WIDTH = 243 //a power of 3 for a evenly spaced curve   open window 700, 700   Peano(0, 0, WIDTH, 0, 0)   Sub Peano(x, y, lg, i1, i2) If (lg = 1) Then line x * 3, y * 3 return End If lg = lg / 3 Peano(x + (2 * i1 * lg), y + (2 * i1 * lg), lg, i1, i2) Peano(x + ((i1 - i2 + 1) * lg), y + ((i1 + i2) * lg), lg, i1, 1 - i2) Peano(x + lg, y + lg, lg, i1, 1 - i2) Peano(x + ((i1 + i2) * lg), y + ((i1 - i2 + 1) * lg), lg, 1 - i1, 1 - i2) Peano(x + (2 * i2 * lg), y + (2 * (1 - i2) * lg), lg, i1, i2) Peano(x + ((1 + i2 - i1) * lg), y + ((2 - i1 - i2) * lg), lg, i1, i2) Peano(x + (2 * (1 - i1) * lg), y + (2 * (1 - i1) * lg), lg, i1, i2) Peano(x + ((2 - i1 - i2) * lg), y + ((1 + i2 - i1) * lg), lg, 1 - i1, i2) Peano(x + (2 * (1 - i2) * lg), y + (2 * i2 * lg), lg, 1 - i1, i2) End Sub
http://rosettacode.org/wiki/Peano_curve
Peano curve
Task Produce a graphical or ASCII-art representation of a Peano curve of at least order 3.
#zkl
zkl
lsystem("L", // axiom Dictionary("L","LFRFL-F-RFLFR+F+LFRFL", "R","RFLFR+F+LFRFL-F-RFLFR"), # rules "+-F", 4) // constants, order : turtle(_);   fcn lsystem(axiom,rules,consts,n){ // Lindenmayer system --> string foreach k in (consts){ rules.add(k,k) } buf1,buf2 := Data(Void,axiom).howza(3), Data().howza(3); // characters do(n){ buf1.pump(buf2.clear(), rules.get); t:=buf1; buf1=buf2; buf2=t; // swap buffers } buf1.text // n=4 --> 16,401 characters }
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).
#Prolog
Prolog
play :- rand1(R), game(R).   game(h) :- format('Your turn first!~n'), player_move(P), response(P,C), format('I am choosing '), maplist(writec, C), nl, rand3(R), maplist(writec,R), roll(P, C, R).   game(t) :- rand3(C), format('I am choosing '), maplist(writec, C), nl, player_move(P), rand3(R), maplist(writec, R), roll(P, C, R).   player_move([P1,P2,P3]) :- read_line_to_codes(user_input,Codes), maplist(char_code,[P1,P2,P3],Codes).   roll(P, _, P) :- format('~nYou Win!~n'), !. roll(_, C, C) :- format('~nI Win!~n'), !.   roll(P, C, [_,A,B]) :- rand1(R), coin_s(R,S), write(S), roll(P,C,[A,B,R]).   response([A,B,_], [C,A,B]) :- opp(A,C).   writec(A) :- coin_s(A,A1), write(A1). rand1(R) :- random(V), round(V,I), coin(I,R). rand3([R1,R2,R3]) :- rand1(R1), rand1(R2), rand1(R3).   coin(0,h). coin(1,t). coin_s(h, 'H'). coin_s(t, 'T'). opp(h, t). opp(t, h).
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.
#PARI.2FGP
PARI/GP
V(n,a=2,v=-4.)=if(n < 3,return(v));V(n--,v,111-1130/v+3000/(v*a))
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.
#8th
8th
\ Convert infix expression to postfix, using 'shunting-yard' algorithm \ https://en.wikipedia.org/wiki/Shunting-yard_algorithm     \ precedence of infix tokens. negative means 'right-associative', otherwise left: with: n { "+" : 2, "-" : 2, "/" : 3, "*" : 3, "^" : -4, "(" : 1, ")" : -1 } var, tokens   : precedence \ s -- s n tokens @ over m:@ nip null? if drop 0 then ;   var ops var out   : >out \ x -- out @ swap a:push drop ;   : >ops \ op prec -- 2 a:close ops @ swap a:push drop ;   : a:peek -1 a:@ ;   \ Check the array for items with greater or equal precedence, \ and move them to the out queue: : pop-ops \ op prec ops -- op prec ops \ empty array, do nothing: a:len not if ;; then   \ Look at top of ops stack: a:peek a:open \ op p ops[] op2 p2   \ if the 'p2' is not less p (meaning item on top of stack is greater or equal \ in precedence), then pop the item from the ops stack and push onto the out: 3 pick \ p2 p < not if \ op p ops[] op2 >out a:pop drop recurse ;; then drop ;     : right-paren "RIGHTPAREN" . cr 2drop \ move non-left-paren from ops and move to out: ops @ repeat a:len not if break else a:pop a:open 1 = if 2drop ;; else >out then then again drop ;   : .state \ n -- drop \ "Token: %s\n" s:strfmt . "Out: " . out @ ( . space drop ) a:each drop cr "ops: " . ops @ ( 0 a:@ . space 2drop ) a:each drop cr cr ;   : handle-number \ s n -- "NUMBER " . over . cr drop >out ;   : left-paren \ s n -- "LEFTPAREN" . cr >ops ;   : handle-op \ s n -- "OPERATOR " . over . cr \ op precedence \ Is the current op left-associative? dup sgn 1 = if \ it is, so check the ops array for items with greater or equal precedence, \ and move them to the out queue: ops @ pop-ops drop then \ push the operator >ops ;   : handle-token \ s -- precedence dup not if \ it's a number: handle-number else dup 1 = if left-paren else dup -1 = if right-paren else handle-op then then then ;   : infix>postfix \ s -- s /\s+/ s:/ \ split to indiviual whitespace-delimited tokens   \ Initialize our data structures a:new ops ! a:new out !   ( nip dup >r handle-token r> .state ) a:each drop \ remove all remaining ops and put on output: out @ ops @ a:rev ( nip a:open drop a:push ) a:each drop \ final string: " " a:join ;   "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3" infix>postfix . cr   "Expected: \n" . "3 4 2 * 1 5 - 2 3 ^ ^ / +" . cr bye  
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.
#APL
APL
upper ← ∘.!⍨¯1+⍳ lower ← ⍉(∘.!⍨¯1+⍳) symmetric ← (⊢![1]∘.+⍨)¯1+⍳
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.
#AppleScript
AppleScript
-- PASCAL MATRIX -------------------------------------------------------------   -- pascalMatrix :: ((Int, Int) -> (Int, Int)) -> Int -> [[Int]] on pascalMatrix(f, n) chunksOf(n, map(compose(my bc, f), range({{0, 0}, {n - 1, n - 1}}))) end pascalMatrix   -- Binomial coefficient -- bc :: (Int, Int) -> Int on bc(nk) set {n, k} to nk script bc_ on |λ|(a, x) floor((a * (n - x + 1)) / x) end |λ| end script foldl(bc_, 1, enumFromTo(1, k)) end bc     -- TEST ---------------------------------------------------------------------- on run set matrixSize to 5   script symm on |λ|(ab) set {a, b} to ab {a + b, a} end |λ| end script   script format on |λ|(s, xs) unlines(concat({{s}, map(my show, xs), {""}})) end |λ| end script   unlines(zipWith(format, ¬ {"Lower", "Upper", "Symmetric"}, ¬ |<*>|(map(curry(pascalMatrix), [|id|, swap, symm]), {matrixSize}))) end run     -- GENERIC FUNCTIONS ---------------------------------------------------------   -- A list of functions applied to a list of arguments -- (<*> | ap) :: [(a -> b)] -> [a] -> [b] on |<*>|(fs, xs) set {nf, nx} to {length of fs, length of xs} set acc to {} repeat with i from 1 to nf tell mReturn(item i of fs) repeat with j from 1 to nx set end of acc to |λ|(contents of (item j of xs)) end repeat end tell end repeat return acc end |<*>|   -- chunksOf :: Int -> [a] -> [[a]] on chunksOf(k, xs) script on go(ys) set {a, b} to splitAt(k, ys) if isNull(a) then {} else {a} & go(b) end if end go end script result's go(xs) end chunksOf   -- compose :: (b -> c) -> (a -> b) -> (a -> c) on compose(f, g) script on |λ|(x) mReturn(f)'s |λ|(mReturn(g)'s |λ|(x)) end |λ| end script end compose   -- concat :: [[a]] -> [a] | [String] -> String on concat(xs) if length of xs > 0 and class of (item 1 of xs) is string then set acc to "" else set acc to {} end if repeat with i from 1 to length of xs set acc to acc & item i of xs end repeat acc end concat   -- cons :: a -> [a] -> [a] on cons(x, xs) {x} & xs end cons   -- curry :: (Script|Handler) -> Script on curry(f) script on |λ|(a) script on |λ|(b) |λ|(a, b) of mReturn(f) end |λ| end script end |λ| end script end curry   -- enumFromTo :: Int -> Int -> [Int] on enumFromTo(m, n) set lst to {} repeat with i from m to n set end of lst to i end repeat return lst end enumFromTo   -- floor :: Num -> Int on floor(x) if x < 0 and x mod 1 is not 0 then (x div 1) - 1 else (x div 1) end if end floor   -- foldl :: (a -> b -> a) -> a -> [b] -> a on foldl(f, startValue, xs) tell mReturn(f) set v to startValue set lng to length of xs repeat with i from 1 to lng set v to |λ|(v, item i of xs, i, xs) end repeat return v end tell end foldl   -- foldr :: (b -> a -> a) -> a -> [b] -> a on foldr(f, startValue, xs) tell mReturn(f) set v to startValue set lng to length of xs repeat with i from lng to 1 by -1 set v to |λ|(item i of xs, v, i, xs) end repeat return v end tell end foldr   -- id :: a -> a on |id|(x) x end |id|   -- intercalate :: Text -> [Text] -> Text on intercalate(strText, lstText) set {dlm, my text item delimiters} to {my text item delimiters, strText} set strJoined to lstText as text set my text item delimiters to dlm return strJoined end intercalate   -- isNull :: [a] -> Bool on isNull(xs) if class of xs is string then xs = "" else xs = {} end if end isNull   -- map :: (a -> b) -> [a] -> [b] on map(f, xs) tell mReturn(f) set lng to length of xs set lst to {} repeat with i from 1 to lng set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell end map   -- min :: Ord a => a -> a -> a on min(x, y) if y < x then y else x end if end min   -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: Handler -> Script on mReturn(f) if class of f is script then f else script property |λ| : f end script end if end mReturn   -- quot :: Int -> Int -> Int on quot(m, n) m div n end quot   -- range :: Ix a => (a, a) -> [a] on range({a, b}) if class of a is list then set {xs, ys} to {a, b} else set {xs, ys} to {{a}, {b}} end if set lng to length of xs   if lng = length of ys then if lng > 1 then script on |λ|(_, i) enumFromTo(item i of xs, item i of ys) end |λ| end script sequence(map(result, xs)) else enumFromTo(a, b) end if else {} end if end range   -- sequence :: Monad m => [m a] -> m [a] -- sequence :: [a] -> [[a]] on sequence(xs) traverse(|id|, xs) end sequence   -- show :: a -> String on show(e) set c to class of e if c = list then script serialized on |λ|(v) show(v) end |λ| end script   "[" & intercalate(", ", map(serialized, e)) & "]" else if c = record then script showField on |λ|(kv) set {k, ev} to kv "\"" & k & "\":" & show(ev) end |λ| end script   "{" & intercalate(", ", ¬ map(showField, zip(allKeys(e), allValues(e)))) & "}" else if c = date then "\"" & iso8601Z(e) & "\"" else if c = text then "\"" & e & "\"" else if (c = integer or c = real) then e as text else if c = class then "null" else try e as text on error ("«" & c as text) & "»" end try end if end show   -- splitAt :: Int -> [a] -> ([a],[a]) on splitAt(n, xs) if n > 0 and n < length of xs then if class of xs is text then {items 1 thru n of xs as text, items (n + 1) thru -1 of xs as text} else {items 1 thru n of xs, items (n + 1) thru -1 of xs} end if else if n < 1 then {{}, xs} else {xs, {}} end if end if end splitAt   -- swap :: (a, b) -> (b, a) on swap(ab) set {a, b} to ab {b, a} end swap   -- traverse :: (a -> [b]) -> [a] -> [[b]] on traverse(f, xs) script property mf : mReturn(f) on |λ|(x, a) |<*>|(map(curry(cons), mf's |λ|(x)), a) end |λ| end script foldr(result, {{}}, xs) end traverse   -- unlines :: [String] -> String on unlines(xs) intercalate(linefeed, xs) end unlines   -- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] on zipWith(f, xs, ys) set lng to min(length of xs, length of ys) set lst to {} tell mReturn(f) repeat with i from 1 to lng set end of lst to |λ|(item i of xs, item i of ys) end repeat return lst end tell end zipWith
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
#ALGOL_W
ALGOL W
begin  % prints the first n lines of Pascal's triangle lines %  % if n is <= 0, no output is produced  % procedure printPascalTriangle( integer value n ) ; if n > 0 then begin integer array pascalLine ( 1 :: n ); pascalLine( 1 ) := 1; for line := 1 until n do begin for i := line - 1 step - 1 until 2 do pascalLine( i ) := pascalLine( i - 1 ) + pascalLine( i ); pascalLine( line ) := 1; write( s_w := 0, " " ); for i := line until n do writeon( s_w := 0, " " ); for i := 1 until line do writeon( i_w := 6, s_w := 0, pascalLine( i ) ) end for_line ; end printPascalTriangle ;   printPascalTriangle( 8 )   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.
#AutoHotkey
AutoHotkey
ParseIP(Address){ return InStr(A_LoopField, ".") ? IPv4(Address) : IPv6(Address) }   IPv4(Address){ for i, v in StrSplit(Address, "."){ x := StrSplit(v, ":") num .= SubStr("00" . Format("{:X}", x.1), -1) port := x.2 ? x.2 : "" } return [num, port] }   IPv6(Address){ for i, v in StrSplit(Address, "]") if i = 1 for j, x in StrSplit(LTrim(v, "[:"), ":") num .= x = "" ? "00000000" : SubStr("0000" x, -3) else port := LTrim(v, ":") return [SubStr("00000000000000000000000000000000" num, -31), port] }
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.
#Ada
Ada
generic type Element_Type is private; package Container is type Tree is tagged private; procedure Replace_All(The_Tree : in out Tree; New_Value : Element_Type); private type Node; type Node_Access is access Node; type Tree tagged record Value : Element_type; Left  : Node_Access := null; Right : Node_Access := null; end record; end Container;
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.
#ALGOL_68
ALGOL 68
  # rpn to infix - parses an RPN expression and generates the equivalent # # infix expression # PROC rpn to infix = ( STRING rpn )STRING: BEGIN   # we parse the string backwards using recursive descent # INT rpn pos := UPB rpn; BOOL had error := FALSE;   # mode to hold nodes of the parse tree # MODE NODE = STRUCT( INT op , UNION( REF NODE, STRING ) left , REF NODE right );   REF NODE nil node = NIL;     # op codes # INT error = 1; INT factor = 2; INT add = 3; INT sub = 4; INT mul = 5; INT div = 6; INT pwr = 7;   []STRING op name = ( "error", "factor", "+", "-", "*", "/", "^" ); []BOOL right associative = ( FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE ); []INT priority = ( 1, 1, 2, 2, 3, 3, 4 );       # returns TRUE if we have reached the end of the rpn string, # # FALSE otherwise # PROC at end = BOOL: rpn pos < LWB rpn;   # positions to the previous character, if there is one # PROC next = VOID: rpn pos -:= 1;   # skip spaces in the rpn string # PROC skip spaces = VOID: WHILE have( " " ) DO next OD # skip spaces # ;   # returns TRUE if the rpn character at rpn pos is c, # # FALSE if the character is not c or there is no character # # at rpn pos # PROC have = ( CHAR c )BOOL: IF at end THEN # no character at rpn pos # FALSE ELSE # have a character - check it is the required one # rpn[ rpn pos ] = c FI # have # ;   # gets an operand from the rpn string # # an operand is either a number or a sub-expression # PROC get operand = ( STRING rpn, STRING operand name )REF NODE: BEGIN   # handle the operator or operand, if there is one #   skip spaces;   print( ( ( "parsing " + operand name + " from: " + IF at end THEN "" ELSE rpn[ LWB rpn : rpn pos ] FI ) , newline ) );   REF NODE result := IF at end THEN # no operand # had error := TRUE; HEAP NODE := ( error, "!! Missing operand !!", NIL ) ELIF have( "+" ) THEN # addition # next; HEAP NODE right := get operand( rpn, "+ right operand" ); HEAP NODE left := get operand( rpn, "+ left operand" ); HEAP NODE := ( add, left, right ) ELIF have( "-" ) THEN # subtraction # next; HEAP NODE right := get operand( rpn, "- right operand" ); HEAP NODE left := get operand( rpn, "- left operand" ); HEAP NODE := ( sub, left, right ) ELIF have( "*" ) THEN # multiplication # next; HEAP NODE right := get operand( rpn, "* right operand" ); HEAP NODE left := get operand( rpn, "* left operand" ); HEAP NODE := ( mul, left, right ) ELIF have( "/" ) THEN # division # next; HEAP NODE right := get operand( rpn, "/ right operand" ); HEAP NODE left := get operand( rpn, "/ left operand" ); HEAP NODE := ( div, left, right ) ELIF have( "^" ) THEN # exponentiation # next; HEAP NODE right := get operand( rpn, "^ right operand" ); HEAP NODE left := get operand( rpn, "^ left operand" ); HEAP NODE := ( pwr, left, right ) ELSE # must be an operand # STRING value := "";   WHILE NOT at end AND NOT have( " " ) DO rpn[ rpn pos ] +=: value; next OD;   HEAP NODE := ( factor, value, NIL ) FI;   print( ( operand name + ": " + TOSTRING result, newline ) );   result END # get operand # ;     # converts the parse tree to a string with apppropriate parenthesis # OP TOSTRING = ( REF NODE operand )STRING: BEGIN   # converts a node of the parse tree to a string, inserting # # parenthesis if necessary # PROC possible parenthesis = ( INT op, REF NODE expr )STRING: IF op OF expr = error OR op OF expr = factor THEN # operand is an error/factor - parenthisis not needed # TOSTRING expr ELIF priority( op OF expr ) < priority( op ) THEN # the expression is a higher precedence operator than the # # one we are building the expression for - need parenthesis # ( "( " + TOSTRING expr + " )" ) ELIF right associative[ op OF operand ] AND op OF left( operand ) = op OF operand THEN # right associative operator # ( "( " + TOSTRING expr + " )" ) ELSE # lower precedence expression - parenthesis not needed # TOSTRING expr FI # possible parenthesis # ;   # gets the left branch of a node, which must be a node # PROC left = ( REF NODE operand )REF NODE: CASE left OF operand IN ( REF NODE o ): o , ( STRING s ): HEAP NODE := ( error, s, NIL ) ESAC # left # ;   IF had error THEN # an error occured parsing the expression # "Invalid expression" ELIF operand IS nil node THEN # no operand? # "<empty>" ELIF op OF operand = error OR op OF operand = factor THEN # error parsing the expression # # or a factor # CASE left OF operand IN ( REF NODE o ): "Error: String expected: (" + TOSTRING o + ")" , ( STRING s ): s ESAC ELSE # general operand # ( possible parenthesis( op OF operand, left( operand ) ) + " " + op name[ op OF operand ] + " " + possible parenthesis( op OF operand, right OF operand ) ) FI END # TOSTRING # ;   STRING result = TOSTRING get operand( rpn, "expression" );   # ensure there are no more tokens in the string # skip spaces; IF at end THEN # OK - there was only one expression # result ELSE # extraneous tokens # ( "Error - unexpected text before expression: (" + rpn[ LWB rpn : rpn pos ] + ")" ) FI END # rpn to infix # ;       main: (   # test the RPN to Infix comnverter # STRING rpn;   rpn := "3 4 2 * 1 5 - 2 3 ^ ^ / +"; print( ( rpn, ": ", rpn to infix( rpn ), newline, newline ) );   rpn := "1 2 + 3 4 + ^ 5 6 + ^"; print( ( rpn, ": ", rpn to infix( rpn ), newline ) )   )  
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.
#C.23
C#
using System; using System.Collections.Generic; using System.Linq;   class PartialFunctionApplication { static Func<T1, TResult> PartiallyApply<T1, T2, TResult>(Func<T1, T2, TResult> function, T2 argument2) { return argument1 => function(argument1, argument2); }   static void Main() { var fs = (Func<IEnumerable<int>, Func<int, int>, IEnumerable<int>>)Enumerable.Select; var f1 = (Func<int, int>)(n => n * 2); var f2 = (Func<int, int>)(n => n * n); var fsf1 = PartiallyApply(fs, f1); var fsf2 = PartiallyApply(fs, f2);   var s = new[] { 0, 1, 2, 3 }; Console.WriteLine(string.Join(", ", fsf1(s))); Console.WriteLine(string.Join(", ", fsf2(s)));   s = new[] { 2, 4, 6, 8 }; Console.WriteLine(string.Join(", ", fsf1(s))); Console.WriteLine(string.Join(", ", fsf2(s))); } }
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
#J
J
  load 'format/printf'   NB. I don't know of any way to easily make an idiomatic lazy exploration, NB. except falling back on explicit imperative control strutures. NB. However this is clearly not where J shines neither with speed nor elegance.   primes_up_to =: monad def 'p: i. _1 p: 1 + y' terms_as_text =: monad def '; }: , (": each y),.<'' + '''   search_next_terms =: dyad define acc=. x NB. -> an accumulator that contains given beginning of the partition. p=. >0{y NB. -> number of elements wanted in the partition ns=. >1{y NB. -> candidate values to be included in the partition sum=. >2{y NB. -> the integer to partition   if. p=0 do. if. sum=+/acc do. acc return. end. else. for_m. i. (#ns)-(p-1) do. r =. (acc,m{ns) search_next_terms (p-1);((m+1)}.ns);sum if. #r do. r return. end. end. end.   0$0 NB. Empty result if nothing found at the end of this path. )     NB. Prints a partition of y primes whose sum equals x. partitioned_in =: dyad define terms =. (0$0) search_next_terms y;(primes_up_to x);x if. #terms do. 'As the sum of %d primes, %d = %s' printf y;x; terms_as_text terms else. 'Didn''t find a way to express %d as a sum of %d different primes.' printf x;y end. )     tests=: (99809 1) ; (18 2) ; (19 3) ; (20 4) ; (2017 24) ; (22699 1) ; (22699 2) ; (22699 3) ; (22699 4) (0&{ partitioned_in 1&{) each tests