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.
#Nim
Nim
import math, strformat import bignum   func solvePell(n: int): (Int, Int) = let x = newInt(sqrt(n.toFloat).int) var (y, z, r) = (x, newInt(1), x shl 1) var (e1, e2) = (newInt(1), newInt(0)) var (f1, f2) = (newInt(0), newInt(1))   while true: y = r * z - y z = (n - y * y) div z r = (x + y) div z   (e1, e2) = (e2, e1 + e2 * r) (f1, f2) = (f2, f1 + f2 * r)   let (a, b) = (f2 * x + e2, f2) if a * a - n * b * b == 1: return (a, b)   for n in [61, 109, 181, 277]: let (x, y) = solvePell(n) echo &"x² - {n:3} * y² = 1 for (x, y) = ({x:>21}, {y:>19})"
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.
#Pascal
Pascal
  program Pell_console; uses SysUtils, uIntX; // uIntX is a unit in the library IntXLib4Pascal. // uIntX.TIntX is an arbitrarily large integer.   // For the given n: if there are non-trivial solutions of x^2 - n*y^2 = 1 // in non-negative integers (x,y), return the smallest. // Else return the trivial solution (x,y) = (1,0). procedure SolvePell( n : integer; out x, y : uIntX.TIntX); var m, a, c, d : integer; p, q, p_next, q_next, p_prev, q_prev : uIntX.TIntX; evenNrSteps : boolean; begin if (n >= 0) then m := Trunc( Sqrt( 1.0*n + 0.5)) // or use Rosetta Code Isqrt else m := 0; if n <= m*m then begin // if n is not a positive non-square x := 1; y := 0; exit; // return a trivial solution end; c := m; d := 1; p := 1; q := 0; p_prev := 0; q_prev := 1; a := m; evenNrSteps := true; repeat // Get the next convergent p/q in the continued fraction for sqrt(n) p_next := a*p + p_prev; q_next := a*q + q_prev; p_prev := p; p := p_next; q_prev := q; q := q_next; // Get the next term a in the continued fraction for sqrt(n) Assert((n - c*c) mod d = 0); // optional sanity check d := (n - c*c) div d; a := (m + c) div d; c := a*d - c; evenNrSteps := not evenNrSteps; until (c = m) and (d = 1); { If the first return to (c,d) = (m,1) occurs after an even number of steps, then p^2 - n*q^2 = 1, and there is no solution to x^2 - n*y^2 = -1. Else p^2 - n*q^2 = -1, and to get a solution to x^2 - n*y^2 = 1 we can either continue until we return to (c,d) = (m,1) for the second time, or use the short cut below. } if evenNrSteps then begin x := p; y := q; end else begin x := 2*p*p + 1; y := 2*p*q end; end;   // For the given n: show the Pell solution on the console. procedure ShowPellSolution( n : integer); var x, y : uIntX.TIntX; lineOut : string; begin SolvePell( n, x, y); lineOut := SysUtils.Format( 'n = %d --> (', [n]); lineOut := lineOut + x.ToString + ', ' + y.ToString + ')'; WriteLn( lineOut); end;   // Main routine begin ShowPellSolution( 61); ShowPellSolution( 109); ShowPellSolution( 181); ShowPellSolution( 277); end.  
http://rosettacode.org/wiki/Pentagram
Pentagram
A pentagram is a star polygon, consisting of a central pentagon of which each side forms the base of an isosceles triangle. The vertex of each triangle, a point of the star, is 36 degrees. Task Draw (or print) a regular pentagram, in any orientation. Use a different color (or token) for stroke and fill, and background. For the fill it should be assumed that all points inside the triangles and the pentagon are inside the pentagram. See also Angle sum of a pentagram
#SPL
SPL
mx,my = #.scrsize() xc = mx/2 yc = my/2 mr = #.min(mx,my)/3 #.angle(#.degrees) #.drawcolor(1,0,0) #.drawsize(10) > r, mr..0,-1 #.drawline(xc,yc-r,xc,yc-r) > a, 54..630,144 #.drawline(r*#.cos(a)+xc,r*#.sin(a)+yc) < #.drawcolor(1,1,0) #.drawsize(1) <
http://rosettacode.org/wiki/Pentagram
Pentagram
A pentagram is a star polygon, consisting of a central pentagon of which each side forms the base of an isosceles triangle. The vertex of each triangle, a point of the star, is 36 degrees. Task Draw (or print) a regular pentagram, in any orientation. Use a different color (or token) for stroke and fill, and background. For the fill it should be assumed that all points inside the triangles and the pentagon are inside the pentagram. See also Angle sum of a pentagram
#Tcl
Tcl
  package require Tk 8.6 ;# lmap is new in Tcl/Tk 8.6   set pi [expr 4*atan(1)]   pack [canvas .c] -expand yes -fill both ;# create the canvas   update ;# draw everything so the dimensions are accurate   set w [winfo width .c] ;# calculate appropriate dimensions set h [winfo height .c] set r [expr {min($w,$h) * 0.45}]   set points [lmap n {0 1 2 3 4 5} { set n [expr {$n * 2}] set y [expr {sin($pi * 2 * $n / 5) * $r + $h / 2}] set x [expr {cos($pi * 2 * $n / 5) * $r + $w / 2}] list $x $y }] set points [concat {*}$points] ;# flatten the list   puts [.c create line $points]   ;# a fun reader exercise is to make the shape respond to mouse events, ;# or animate it!  
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
#11l
11l
T.enum Piece EMPTY BLACK WHITE   F isAttacking(queen, pos) R queen.x == pos.x | queen.y == pos.y | abs(queen.x - pos.x) == abs(queen.y - pos.y)   F place(m, n, &pBlackQueens, &pWhiteQueens) I m == 0 R 1B   V placingBlack = 1B L(i) 0 .< n L(j) 0 .< n V pos = (i, j) L(queen) pBlackQueens I queen == pos | (!placingBlack & isAttacking(queen, pos)) L.break L.was_no_break L(queen) pWhiteQueens I queen == pos | (placingBlack & isAttacking(queen, pos)) L.break L.was_no_break I placingBlack pBlackQueens [+]= pos placingBlack = 0B E pWhiteQueens [+]= pos I place(m - 1, n, &pBlackQueens, &pWhiteQueens) R 1B pBlackQueens.pop() pWhiteQueens.pop() placingBlack = 1B   I !placingBlack pBlackQueens.pop() R 0B   F printBoard(n, blackQueens, whiteQueens) V board = [Piece.EMPTY] * (n * n)   L(queen) blackQueens board[queen.x * n + queen.y] = Piece.BLACK   L(queen) whiteQueens board[queen.x * n + queen.y] = Piece.WHITE   L(b) board V i = L.index I i != 0 & i % n == 0 print() I b == BLACK print(‘B ’, end' ‘’) E I b == WHITE print(‘W ’, end' ‘’) E V j = i I/ n V k = i - j * n I j % 2 == k % 2 print(‘x ’, end' ‘’) E print(‘o ’, end' ‘’) print("\n")   V 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) ]   L(nm) nms print(‘#. black and #. white queens on a #. x #. board:’.format(nm[1], nm[1], nm[0], nm[0])) [(Int, Int)] blackQueens, whiteQueens I place(nm[1], nm[0], &blackQueens, &whiteQueens) printBoard(nm[0], blackQueens, whiteQueens) E print("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
#Applesoft_BASIC
Applesoft BASIC
1 N=1 2 L=8 3 M$=CHR$(13) 4 D$=CHR$(4) 5 S$(0)="S" 6 F$="A FILE" 7 C$(1)=" (CURRENT OPTION)" 8 DEF FN R(T)=ASC(MID$(G$(T),INT(RND(1)*LEN(G$(T))+1),1)) 9 GOSUB 750 10 FOR Q = 0 TO 1 STEP 0 20 GOSUB 50CHOOSE 30 NEXT Q 40 END   REM *** CHOOSE *** 50 PRINT M$M$"1 GEN 2 DISP 3 FILE 4 LEN 5 NUM 6 SEED" 60 PRINT "7 CHR 8 HELP 9 QUIT "CHR$(10)"CHOOSE AN OPTION: "; 70 GET K$ 75 IF K$ > CHR$(95) THEN K$ = CHR$(ASC(K$) - 32) 80 PRINT K$ 85 ON VAL(K$) GOTO 100,200,300,400,500,600,700,800,900 90 GOTO 210OPTIONS   REM *** GENERATE *** 100 PRINT M$ 105 IF L > 32 THEN PRINT "UM... OK, THIS MIGHT TAKE A BIT."M$ 110 GOSUB 340OPEN 115 FOR P=1 TO N 120 P$="" 125 FOR I=1 TO L 135 P$=P$+CHR$(FNR(I*(I<5))) 140 NEXT I REM SHUFFLE FIRST 4 150 FOR I = 1 TO 4 151 C$=MID$(P$,I,1) 152 J=INT(RND(1)*L)+1 153 H$=MID$(P$,J,1) 154 P$=MID$(P$,1,J-1)+C$+MID$(P$,J+1,L) 155 P$=MID$(P$,1,I-1)+H$+MID$(P$,I+1,L) 156 NEXT I 180 PRINT P$ 185 NEXT P 190 GOTO 380CLOSE   REM *** DISPLAY *** 200 C = 0 REM *** OPTIONS *** 210 HOME 215 PRINT "PASSWORD GENERATOR"M$M$ 220 PRINT "1. GENERATE "N" PASSWORD"S$(N=1)M$ 225 PRINT "2. DISPLAYED"C$(C=0)M$" OR" 230 PRINT "3. WRITTEN TO "F$C$(C=1)M$ 235 PRINT "4. SPECIFY THE PASSWORD LENGTH = "L;M$ 240 PRINT "5. SPECIFY THE NUMBER OF PASSWORDS TO"M$TAB(31)"GENERATE" 245 PRINT "6. SPECIFY A SEED VALUE"M$ 250 PRINT "7. EXCLUDE VISUALLY SIMILAR CHARACTERS"M$ 255 PRINT "8. HELP AND OPTIONS" 260 RETURN   REM *** WRITE TO A FILE *** 300 C = 1 310 GOTO 210OPTIONS REM *** OPEN A FILE *** 340 IF NOT C THEN RETURN 345 PRINT D$"OPEN "F$" 350 PRINT D$"CLOSE"F$ 355 PRINT D$"DELETE "F$ 360 PRINT D$"OPEN "F$ 365 PRINT D$"WRITE "F$ 370 RETURN REM *** CLOSE A FILE *** 380 IF NOT C THEN RETURN 385 PRINT D$"CLOSE"F$ 390 RETURN   REM *** SET PASSWORD LENGTH *** 400 PRINT M$ 410 FOR I = 0 TO 1 STEP 0 420 INPUT "ENTER A NUMBER FROM 4 TO 255 TO SPECIFY THE PASSWORD LENGTH = ";L 430 IF L >= 4 AND L < 256 THEN RETURN 440 PRINT "?OUT OF RANGE" 450 NEXT I   REM *** SET NUMBER OF PASSWORDS TO GENERATE *** 500 PRINT M$ 510 FOR I = 0 TO 1 STEP 0 520 INPUT "ENTER A NUMBER FROM 1 AND UP TO SPECIFY THE NUMBER OF PASSWORDS TO GENERATE: ";N 530 IF N >= 1 THEN RETURN 540 PRINT "?OUT OF RANGE." 550 NEXT I   REM *** SET A SEED VALUE *** 600 PRINT M$ 610 INPUT "ENTER A SEED VALUE: ";S% 620 PRINT RND(S%) 630 RETURN   REM *** EXCLUDE *** 700 PRINT M$ 705 INPUT "ENTER CHARACTERS TO EXCLUDE:";E$ REM *** GROUPS *** REM ALWAYS EXCLUDE BACKSLASH AND BACKTICK (GRAVE) 710 E$=CHR$(92)+CHR$(96)+E$ 711 FOR G = 1 TO 4 712 G$(G) = "" 713 NEXT G 720 FOR G = 1 TO 2 721 FOR K = ASC("A") + (G - 1) * 32 TO ASC("Z") + (G - 1) * 32 722 GOSUB 770ADD 723 NEXT K, G 730 FOR K = 33 TO 64 731 G = 3 + (K < ASC(STR$(0)) OR K > ASC(STR$(9))) 732 GOSUB 770ADD 733 NEXT K 734 FOR K = 91 TO 96 735 GOSUB 770ADD 736 NEXT K 737 FOR K = 123 TO 126 738 GOSUB 770ADD 739 NEXT K 740 G$(0) = "" 741 FOR G = 1 TO 4 742 IF LEN(G$(G)) THEN G$(0) = G$(0) + G$(G) : NEXT G : GOTO 800HELP 743 ?"THERE MUST BE AT LEAST ONE CHARUNRACTER IN EACH GROUP" 744 GOTO 705 REM *** DEFAULT (QUICK) *** 750 G$(1)="ABCDEFGHIJKLMNOPQRSTUVWXYZ" 751 FOR I=97TO122:G$(2)=G$(2)+CHR$(I):NEXT 753 G$(3)="0123456789" 754 G$(4)="!"+CHR$(34)+"#$%&'()*+,-./:;<=>?@"+CHR$(91)+"]^"+CHR$(95) 755 FOR I=123TO126:G$(4)=G$(4)+CHR$(I):NEXTI 756 G$(0)=G$(0)+G$(1)+G$(2)+G$(3) 757 GOTO 210OPTIONS REM *** ADD TO GROUP 770 C$ = CHR$(K) 775 FOR E = 1 TO LEN(E$) 780 IF C$ <> MID$(E$,E,1) THEN NEXT E : G$(G)=G$(G)+C$ : ?C$; 790 RETURN   REM *** HELP *** 800 HOME 805 PRINT "GENERATE PASSWORDS CONTAINING RANDOM" 810 PRINT "ASCII CHARACTERS FROM THESE GROUPS:"M$ 815 PRINT " LOWERCASE UPPERCASE DIGIT OTHER"M$ 820 PRINT " "LEFT$(G$(2),9)TAB(13)LEFT$(G$(1),9)TAB(23)LEFT$(G$(3),5)TAB(29)LEFT$(G$(4),11) 825 PRINT " "MID$(G$(2),10,9)TAB(13)MID$(G$(1),10,9)TAB(23)MID$(G$(3),6,5)TAB(29)MID$(G$(4),12,11) 826 PRINT " "MID$(G$(2),19,9)TAB(13)MID$(G$(1),19,9)TAB(29)MID$(G$(4),23,15)M$ 840 PRINT "YOU MAY CHOOSE THE PASSWORD LENGTH, AND" 845 PRINT "HOW MANY PASSWORDS TO GENERATE. IT IS" 850 PRINT "ENSURED THAT THERE IS AT LEAST ONE" 855 PRINT "CHARACTER FROM EACH OF THE GROUPS IN" 860 PRINT "EACH PASSWORD. THERE IS AN OPTION TO" 865 PRINT "EXCLUDE VISUALLY SIMILAR CHARACTERS." 870 RETURN   REM *** QUIT *** 900 Q = 1 910 VTAB 23 920 RETURN
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
#Qi
Qi
  (define insert L 0 E -> [E|L] [L|Ls] N E -> [L|(insert Ls (- N 1) E)])   (define seq Start Start -> [Start] Start End -> [Start|(seq (+ Start 1) End)])   (define append-lists [] -> [] [A|B] -> (append A (append-lists B)))   (define permutate [] -> [[]] [H|T] -> (append-lists (map (/. P (map (/. N (insert P N H)) (seq 0 (length P)))) (permute T))))
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.
#IS-BASIC
IS-BASIC
100 PROGRAM "PeanoC.bas" 110 OPTION ANGLE DEGREES 120 SET VIDEO MODE 5:SET VIDEO COLOR 0:SET VIDEO X 40:SET VIDEO Y 27 130 OPEN #101:"video:" 140 DISPLAY #101:AT 1 FROM 1 TO 27 150 PLOT 280,240,ANGLE 90; 160 CALL PEANO(28,90,6) 170 DEF PEANO(D,A,LEV) 180 IF LEV=0 THEN EXIT DEF 190 PLOT RIGHT A; 200 CALL PEANO(D,-A,LEV-1) 210 PLOT FORWARD D; 220 CALL PEANO(D,A,LEV-1) 230 PLOT FORWARD D; 240 CALL PEANO(D,-A,LEV-1) 250 PLOT LEFT A; 260 END DEF
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.
#J
J
load'viewmat' hp=: 3 : '(|.,]) 1 (0 _2 _2 ,&.> _2 _1 0 + #y) } (,.|:) y' HP=: 3 3 $ 0 0 0 0 1 WR=: 16777215 16711680 viewrgb WR {~ hp ^:7 HP
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.
#Java
Java
import java.io.*;   public class PeanoCurve { public static void main(final String[] args) { try (Writer writer = new BufferedWriter(new FileWriter("peano_curve.svg"))) { PeanoCurve s = new PeanoCurve(writer); final int length = 8; s.currentAngle = 90; s.currentX = length; s.currentY = length; s.lineLength = length; s.begin(656); s.execute(rewrite(4)); s.end(); } catch (final Exception ex) { ex.printStackTrace(); } }   private PeanoCurve(final Writer writer) { this.writer = writer; }   private void begin(final int size) throws IOException { write("<svg xmlns='http://www.w3.org/2000/svg' width='%d' height='%d'>\n", size, size); write("<rect width='100%%' height='100%%' fill='white'/>\n"); write("<path stroke-width='1' stroke='black' fill='none' d='"); }   private void end() throws IOException { write("'/>\n</svg>\n"); }   private void execute(final String s) throws IOException { write("M%g,%g\n", currentX, currentY); for (int i = 0, n = s.length(); i < n; ++i) { switch (s.charAt(i)) { case 'F': line(lineLength); break; case '+': turn(ANGLE); break; case '-': turn(-ANGLE); break; } } }   private void line(final double length) throws IOException { final double theta = (Math.PI * currentAngle) / 180.0; currentX += length * Math.cos(theta); currentY += length * Math.sin(theta); write("L%g,%g\n", currentX, currentY); }   private void turn(final int angle) { currentAngle = (currentAngle + angle) % 360; }   private void write(final String format, final Object... args) throws IOException { writer.write(String.format(format, args)); }   private static String rewrite(final int order) { String s = "L"; for (int i = 0; i < order; ++i) { final StringBuilder sb = new StringBuilder(); for (int j = 0, n = s.length(); j < n; ++j) { final char ch = s.charAt(j); if (ch == 'L') sb.append("LFRFL-F-RFLFR+F+LFRFL"); else if (ch == 'R') sb.append("RFLFR+F+LFRFL-F-RFLFR"); else sb.append(ch); } s = sb.toString(); } return s; }   private final Writer writer; private double lineLength; private double currentX; private double currentY; private int currentAngle; private static final int ANGLE = 90; }
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).
#D
D
void main() { import std.stdio, std.random, std.algorithm, std.string, std.conv, std.range, core.thread;   immutable first = uniform(0, 2) == 0;   string you, me; if (first) { me = 3.iota.map!(_ => "HT"[uniform(0, $)]).text; writefln("I choose first and will win on first seeing %s in the list of tosses", me); while (you.length != 3 || you.any!(c => !c.among('H', 'T')) || you == me) { "What sequence of three Heads/Tails will you win with: ".write; you = readln.strip; } } else { while (you.length != 3 || you.any!(c => !c.among('H', 'T'))) { "After you: What sequence of three Heads/Tails will you win with: ".write; you = readln.strip; } me = (you[1] == 'T' ? 'H' : 'T') ~ you[0 .. 2]; writefln("I win on first seeing %s in the list of tosses", me); }   "Rolling:\n ".write; string rolled; while (true) { rolled ~= "HT"[uniform(0, $)]; rolled.back.write; if (rolled.endsWith(you)) return "\n You win!".writeln; if (rolled.endsWith(me)) return "\n I win!".writeln; Thread.sleep(1.seconds); } }
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.
#Excel
Excel
A1: 2 A2: -4 A3: =111-1130/A2+3000/(A2*A1) A4: =111-1130/A3+3000/(A3*A2) ...
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.
#Perl
Perl
sub solve_pell { my ($n) = @_;   use bigint try => 'GMP';   my $x = int(sqrt($n)); my $y = $x; my $z = 1; my $r = 2 * $x;   my ($e1, $e2) = (1, 0); my ($f1, $f2) = (0, 1);   for (; ;) {   $y = $r * $z - $y; $z = int(($n - $y * $y) / $z); $r = int(($x + $y) / $z);   ($e1, $e2) = ($e2, $r * $e2 + $e1); ($f1, $f2) = ($f2, $r * $f2 + $f1);   my $A = $e2 + $x * $f2; my $B = $f2;   if ($A**2 - $n * $B**2 == 1) { return ($A, $B); } } }   foreach my $n (61, 109, 181, 277) { my ($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/Pentagram
Pentagram
A pentagram is a star polygon, consisting of a central pentagon of which each side forms the base of an isosceles triangle. The vertex of each triangle, a point of the star, is 36 degrees. Task Draw (or print) a regular pentagram, in any orientation. Use a different color (or token) for stroke and fill, and background. For the fill it should be assumed that all points inside the triangles and the pentagon are inside the pentagram. See also Angle sum of a pentagram
#VBA
VBA
Sub pentagram() With ActiveSheet.Shapes.AddShape(msoShape5pointStar, 10, 10, 400, 400) .Fill.ForeColor.RGB = RGB(255, 0, 0) .Line.Weight = 3 .Line.ForeColor.RGB = RGB(0, 0, 255) End With End Sub
http://rosettacode.org/wiki/Pentagram
Pentagram
A pentagram is a star polygon, consisting of a central pentagon of which each side forms the base of an isosceles triangle. The vertex of each triangle, a point of the star, is 36 degrees. Task Draw (or print) a regular pentagram, in any orientation. Use a different color (or token) for stroke and fill, and background. For the fill it should be assumed that all points inside the triangles and the pentagon are inside the pentagram. See also Angle sum of a pentagram
#Wren
Wren
import "graphics" for Canvas, Color, Point import "dome" for Window   class Game { static init() { Window.title = "Pentagram" var width = 640 var height = 640 Window.resize(width, height) Canvas.resize(width, height) Canvas.cls(Color.white) var col = Color.hex("#6495ed") // cornflower blue for (i in 1..240) pentagram(320, 320, i, col) for (i in 241..250) pentagram(320, 320, i, Color.black) }   static update() {}   static draw(alpha) {}   static pentagram(x, y, r, col) { var points = List.filled(5, null) for (i in 0..4) { var angle = 2*Num.pi*i/5 - Num.pi/2 points[i] = Point.new(x + r*angle.cos, y + r*angle.sin) } var prev = points[0] for (i in 1..5) { var index = (i * 2) % 5 var curr = points[index] Canvas.line(prev.x, prev.y, curr.x, curr.y, col) prev = curr } } }
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
#ATS
ATS
(********************************************************************)   #define ATS_DYNLOADFLAG 0   #include "share/atspre_define.hats" #include "share/atspre_staload.hats"   staload UN = "prelude/SATS/unsafe.sats"   #define NIL list_vt_nil () #define :: list_vt_cons   #ifndef NDEBUG #then (* Safety is relatively unimportant in this program. Therefore I have made it so you can put ‘-DATS NDEBUG=1’ on your patscc command line, to skip some assertloc tests. *) #define NDEBUG 0 #endif   (********************************************************************)   #define EMPTY 0 #define BLACK 1 #define WHITE ~1   stadef is_color (c : int) : bool = (~1 <= c && c <= 1) stadef reverse_color (c : int) : int = ~c   typedef color_t (tk : tkind, c : int) = [is_color c] g1int (tk, c) typedef color_t (tk : tkind) = [c : int | is_color c] g1int (tk, c)   fn {tk : tkind} reverse_color {c : int | is_color c} (c : g1int (tk, c)) :<> [c_rev : int | is_color c_rev; c_rev == reverse_color c] g1int (tk, c_rev) = (* This template is a fancy way to say ‘minus’. *) ~c   (********************************************************************)   (* Matrix indices will run from 0..n-1 rather than 1..n. *)   #define SIDE_MAX 16 (* The maximum side size. For efficiency, please make it a power of two. *) #define BOARD_SIZE 256 (* The storage size for a board. *)   prval _ = prop_verify {SIDE_MAX * SIDE_MAX == BOARD_SIZE} ()   fn {tk : tkind} row_index {k : int | 0 <= k; k < BOARD_SIZE} (k : g1int (tk, k)) :<> [i : int | 0 <= i; i < SIDE_MAX] g1int (tk, i) = (* Let the C compiler convert this to bitmasking. *) g1int_nmod (k, g1i2i SIDE_MAX)   fn {tk : tkind} column_index {k : int | 0 <= k; k < BOARD_SIZE} (k : g1int (tk, k)) :<> [i : int | 0 <= i; i < SIDE_MAX] g1int (tk, i) = (* Let the C compiler convert this to a shift. *) k / g1i2i SIDE_MAX   fn {tk : tkind} storage_index {i, j : int | 0 <= i; i < SIDE_MAX; 0 <= j; j < SIDE_MAX} (i : g1int (tk, i), j : g1int (tk, j)) :<> [k : int | 0 <= k; k < BOARD_SIZE] g1int (tk, k) = (* Let the C compiler convert this to a shift and add. *) i + (j * g1i2i SIDE_MAX)   (********************************************************************)   extern fn {tk_index : tkind} test_equiv$reindex_i {i, j : int | 0 <= i; 0 <= j} {n : int | 0 <= n; n <= SIDE_MAX; i < n; j < n} (i : g1int (tk_index, i), j : g1int (tk_index, j), n : g1int (tk_index, n)) :<> [i1 : int | 0 <= i1; i1 < SIDE_MAX] g1int (tk_index, i1)   extern fn {tk_index : tkind} test_equiv$reindex_j {i, j : int | 0 <= i; 0 <= j} {n : int | 0 <= n; n <= SIDE_MAX; i < n; j < n} (i : g1int (tk_index, i), j : g1int (tk_index, j), n : g1int (tk_index, n)) :<> [j1 : int | 0 <= j1; j1 < SIDE_MAX] g1int (tk_index, j1)   extern fn {tk_color : tkind} test_equiv$recolor {c : int | is_color c} (c : g1int (tk_color, c)) :<> [c1 : int | is_color c1] g1int (tk_color, c1)   fn {tk_index, tk_color : tkind} test_equiv {n : int | 0 <= n; n <= SIDE_MAX} (a : &(@[color_t tk_color][BOARD_SIZE]), b : &(@[color_t tk_color][BOARD_SIZE]), n : g1int (tk_index, n)) : bool = let macdef reindex_i = test_equiv$reindex_i<tk_index> macdef reindex_j = test_equiv$reindex_j<tk_index> macdef recolor = test_equiv$recolor<tk_color>   fun loopj {j : int | ~1 <= j; j < n} .<j + 1>. (a : &(@[color_t tk_color][BOARD_SIZE]), b : &(@[color_t tk_color][BOARD_SIZE]), n : g1int (tk_index, n), j : g1int (tk_index, j)) : bool = if j < g1i2i 0 then true else let fun loopi {i : int | ~1 <= i; i < n} .<i + 1>. (a : &(@[color_t tk_color][BOARD_SIZE]), b : &(@[color_t tk_color][BOARD_SIZE]), n : g1int (tk_index, n), j : g1int (tk_index, j), i : g1int (tk_index, i)) : bool = if i < g1i2i 0 then true else let val ka = storage_index<tk_index> (i, j) val color_a = a[ka]   val i1 = test_equiv$reindex_i<tk_index> (i, j, n) val j1 = test_equiv$reindex_j<tk_index> (i, j, n) val kb = storage_index<tk_index> (i1, j1) val color_b = recolor b[kb] in if color_a = color_b then loopi (a, b, n, j, pred i) else false end in if loopi (a, b, n, j, g1i2i (pred n)) then loopj (a, b, n, pred j) else false end in loopj (a, b, n, g1i2i (pred n)) end   fn {tk_index, tk_color : tkind} test_equiv_rotate0 {n : int | 0 <= n; n <= SIDE_MAX} (a : &(@[color_t tk_color][BOARD_SIZE]), b : &(@[color_t tk_color][BOARD_SIZE]), n : g1int (tk_index, n)) : bool = let (* No rotations or reflections. *) implement test_equiv$reindex_i<tk_index> (i, j, n) = i implement test_equiv$reindex_j<tk_index> (i, j, n) = j in test_equiv<tk_index, tk_color> (a, b, n) end   fn {tk_index, tk_color : tkind} test_equiv_rotate90 {n : int | 0 <= n; n <= SIDE_MAX} (a : &(@[color_t tk_color][BOARD_SIZE]), b : &(@[color_t tk_color][BOARD_SIZE]), n : g1int (tk_index, n)) : bool = let (* Matrix rotation counterclockwise by 90 degrees. *) implement test_equiv$reindex_i<tk_index> {i, j} {n} (i, j, n) = pred n - j implement test_equiv$reindex_j<tk_index> (i, j, n) = i in test_equiv<tk_index, tk_color> (a, b, n) end   fn {tk_index, tk_color : tkind} test_equiv_rotate180 {n : int | 0 <= n; n <= SIDE_MAX} (a : &(@[color_t tk_color][BOARD_SIZE]), b : &(@[color_t tk_color][BOARD_SIZE]), n : g1int (tk_index, n)) : bool = let (* Matrix rotation by 180 degrees. *) implement test_equiv$reindex_i<tk_index> {i, j} {n} (i, j, n) = pred n - i implement test_equiv$reindex_j<tk_index> {i, j} {n} (i, j, n) = pred n - j in test_equiv<tk_index, tk_color> (a, b, n) end   fn {tk_index, tk_color : tkind} test_equiv_rotate270 {n : int | 0 <= n; n <= SIDE_MAX} (a : &(@[color_t tk_color][BOARD_SIZE]), b : &(@[color_t tk_color][BOARD_SIZE]), n : g1int (tk_index, n)) : bool = let (* Matrix rotation counterclockwise by 270 degrees. *) implement test_equiv$reindex_i<tk_index> (i, j, n) = j implement test_equiv$reindex_j<tk_index> {i, j} {n} (i, j, n) = pred n - i in test_equiv<tk_index, tk_color> (a, b, n) end   fn {tk_index, tk_color : tkind} test_equiv_reflecti {n : int | 0 <= n; n <= SIDE_MAX} (a : &(@[color_t tk_color][BOARD_SIZE]), b : &(@[color_t tk_color][BOARD_SIZE]), n : g1int (tk_index, n)) : bool = let (* Reverse the order of the rows. *) implement test_equiv$reindex_i<tk_index> {i, j} {n} (i, j, n) = pred n - i implement test_equiv$reindex_j<tk_index> (i, j, n) = j in test_equiv<tk_index, tk_color> (a, b, n) end   fn {tk_index, tk_color : tkind} test_equiv_reflectj {n : int | 0 <= n; n <= SIDE_MAX} (a : &(@[color_t tk_color][BOARD_SIZE]), b : &(@[color_t tk_color][BOARD_SIZE]), n : g1int (tk_index, n)) : bool = let (* Reverse the order of the columns. *) implement test_equiv$reindex_i<tk_index> (i, j, n) = i implement test_equiv$reindex_j<tk_index> {i, j} {n} (i, j, n) = pred n - j in test_equiv<tk_index, tk_color> (a, b, n) end   fn {tk_index, tk_color : tkind} test_equiv_reflect_diag_down {n : int | 0 <= n; n <= SIDE_MAX} (a : &(@[color_t tk_color][BOARD_SIZE]), b : &(@[color_t tk_color][BOARD_SIZE]), n : g1int (tk_index, n)) : bool = let (* Transpose the matrix around its main diagonal. *) implement test_equiv$reindex_i<tk_index> (i, j, n) = j implement test_equiv$reindex_j<tk_index> (i, j, n) = i in test_equiv<tk_index, tk_color> (a, b, n) end   fn {tk_index, tk_color : tkind} test_equiv_reflect_diag_up {n : int | 0 <= n; n <= SIDE_MAX} (a : &(@[color_t tk_color][BOARD_SIZE]), b : &(@[color_t tk_color][BOARD_SIZE]), n : g1int (tk_index, n)) : bool = let (* Transpose the matrix around its main skew diagonal. *) implement test_equiv$reindex_i<tk_index> {i, j} {n} (i, j, n) = pred n - j implement test_equiv$reindex_j<tk_index> {i, j} {n} (i, j, n) = pred n - i in test_equiv<tk_index, tk_color> (a, b, n) end   fn {tk_index, tk_color : tkind} board_equiv {n : int | 0 <= n; n <= SIDE_MAX} (a : &(@[color_t tk_color][BOARD_SIZE]), b : &(@[color_t tk_color][BOARD_SIZE]), n : g1int (tk_index, n), rotation_equiv_classes : bool) : bool = let (* Leave the colors unchanged. *) implement test_equiv$recolor<tk_color> (c) = c   (* Test without rotations or reflections. *) val equiv = test_equiv_rotate0<tk_index, tk_color> (a, b, n) in if ~rotation_equiv_classes then equiv else let (* Leave the colors unchanged. *) implement test_equiv$recolor<tk_color> (c) = c   val equiv = (equiv || test_equiv_rotate90<tk_index, tk_color> (a, b, n) || test_equiv_rotate180<tk_index, tk_color> (a, b, n) || test_equiv_rotate270<tk_index, tk_color> (a, b, n) || test_equiv_reflecti<tk_index, tk_color> (a, b, n) || test_equiv_reflectj<tk_index, tk_color> (a, b, n) || test_equiv_reflect_diag_down<tk_index, tk_color> (a, b, n) || test_equiv_reflect_diag_up<tk_index, tk_color> (a, b, n))   (* Reverse the colors of b in each test. *) implement test_equiv$recolor<tk_color> (c) = reverse_color c   val equiv = (equiv || test_equiv_rotate0<tk_index, tk_color> (a, b, n) || test_equiv_rotate90<tk_index, tk_color> (a, b, n) || test_equiv_rotate180<tk_index, tk_color> (a, b, n) || test_equiv_rotate270<tk_index, tk_color> (a, b, n) || test_equiv_reflecti<tk_index, tk_color> (a, b, n) || test_equiv_reflectj<tk_index, tk_color> (a, b, n) || test_equiv_reflect_diag_down<tk_index, tk_color> (a, b, n) || test_equiv_reflect_diag_up<tk_index, tk_color> (a, b, n)) in equiv end end   (********************************************************************)   fn {tk_index : tkind} fprint_rule {n : int | 0 <= n; n <= SIDE_MAX} (f : FILEref, n : g1int (tk_index, n)) : void = let fun loop {j : int | 0 <= j; j <= n} .<n - j>. (j : g1int (tk_index, j)) : void = if j <> n then begin fileref_puts (f, "----+"); loop (succ j) end in fileref_puts (f, "+"); loop (g1i2i 0) end   fn {tk_index, tk_color : tkind} fprint_board {n : int | 0 <= n; n <= SIDE_MAX} (f : FILEref, a : &(@[color_t tk_color][BOARD_SIZE]), n : g1int (tk_index, n)) : void = if n <> 0 then let fun loopi {i : int | ~1 <= i; i < n} .<i + 1>. (f : FILEref, a : &(@[color_t tk_color][BOARD_SIZE]), n : g1int (tk_index, n), i : g1int (tk_index, i)) : void = if i <> ~1 then let fun loopj {j : int | 0 <= j; j <= n} .<n - j>. (f : FILEref, a : &(@[color_t tk_color][BOARD_SIZE]), n : g1int (tk_index, n), i : g1int (tk_index, i), j : g1int (tk_index, j)) : void = if j <> n then let val k = storage_index<tk_index> (i, j) val color = a[k] val representation = if color = g1i2i BLACK then "| B " else if color = g1i2i WHITE then "| W " else "| " in fileref_puts (f, representation); loopj (f, a, n, i, succ j) end in fileref_puts (f, "\n"); loopj (f, a, n, i, g1i2i 0); fileref_puts (f, "|\n"); fprint_rule (f, n); loopi (f, a, n, pred i) end in fprint_rule (f, n); loopi (f, a, n, pred n) end   (********************************************************************)   (* M2_MAX equals the maximum number of queens of either color. Thus it is the maximum of 2*m, where m is the number of queens in an army. *) #define M2_MAX BOARD_SIZE   (* The even-index queens are BLACK, the odd-index queens are WHITE. *)   vtypedef board_record_vt (tk_color : tkind, p  : addr) = @{ pf = @[color_t tk_color][BOARD_SIZE] @ p, pfgc = mfree_gc_v p | p = ptr p } vtypedef board_record_vt (tk_color : tkind) = [p : addr | null < p] board_record_vt (tk_color, p)   vtypedef board_record_list_vt (tk_color : tkind, n : int) = list_vt (board_record_vt tk_color, n) vtypedef board_record_list_vt (tk_color : tkind) = [n : int] board_record_list_vt (tk_color, n)   fn board_record_vt_free {tk_color : tkind} {p  : addr} (record  : board_record_vt (tk_color, p)) : void = let val @{ pf = pf, pfgc = pfgc | p = p } = record in array_ptr_free (pf, pfgc | p) end   overload free with board_record_vt_free   fn board_record_list_vt_free {tk_color : tkind} {n  : int} (lst  : board_record_list_vt (tk_color, n)) : void = let fun loop {n  : int | 0 <= n} .<n>. (lst : board_record_list_vt (tk_color, n)) : void = case+ lst of | ~ NIL => () | ~ head :: tail => begin free head; loop tail end   prval _ = lemma_list_vt_param lst in loop lst end   fn {tk_index, tk_color : tkind} any_board_equiv {n  : int | 0 <= n; n <= SIDE_MAX} (board : &(@[color_t tk_color][BOARD_SIZE]), lst  : !board_record_list_vt tk_color, n  : g1int (tk_index, n), rotation_equiv_classes : bool) : bool = let macdef board_equiv = board_equiv<tk_index, tk_color>   fun loop {k : int | 0 <= k} .<k>. (board : &(@[color_t tk_color][BOARD_SIZE]), lst  : !board_record_list_vt (tk_color, k), n  : g1int (tk_index, n)) : bool = case+ lst of | NIL => false | head :: tail => if board_equiv (!(head.p), board, n, rotation_equiv_classes) then true else loop (board, tail, n)   prval _ = lemma_list_vt_param lst in loop (board, lst, n) end   fn {tk_index, tk_color : tkind} queens_to_board {count  : int | 0 <= count; count <= M2_MAX} (queens : &(@[g1int tk_index][M2_MAX]), count  : int count) : [p : addr | null < p] board_record_vt (tk_color, p) = let typedef color_t = color_t tk_color   fun loop {k : int | ~1 <= k; k < count} .<k + 1>. (queens : &(@[g1int tk_index][M2_MAX]), board  : &(@[color_t tk_color][BOARD_SIZE]), k  : int k) : void = if 0 <= k then let val [coords : int] coords = queens[k] #if NDEBUG <> 0 #then prval _ = $UN.prop_assert {0 <= coords} () prval _ = $UN.prop_assert {coords < BOARD_SIZE} () #else val _ = assertloc (g1i2i 0 <= coords) val _ = assertloc (coords < g1i2i BOARD_SIZE) #endif in if g1int_nmod (k, 2) = 0 then board[coords] := g1i2i BLACK else board[coords] := g1i2i WHITE; loop (queens, board, pred k) end   val @(pf, pfgc | p) = array_ptr_alloc<color_t> (i2sz BOARD_SIZE) val _ = array_initize_elt<color_t> (!p, i2sz BOARD_SIZE, g1i2i EMPTY) val _ = loop (queens, !p, pred count) in @{ pf = pf, pfgc = pfgc | p = p } end   fn {tk : tkind} queen_would_fit_in {count  : int | 0 <= count; count <= M2_MAX} {i, j  : int | 0 <= i; i < SIDE_MAX; 0 <= j; j < SIDE_MAX} (queens : &(@[g1int tk][M2_MAX]), count  : int count, i  : g1int (tk, i), j  : g1int (tk, j)) : bool = (* Would a new queen at (i,j) be feasible? *) if count = 0 then true else let fun loop {k : int | ~1 <= k; k < count} (queens : &(@[g1int tk][M2_MAX]), k  : int k) : bool = if k < 0 then true else let val [coords : int] coords = queens[k] #if NDEBUG <> 0 #then prval _ = $UN.prop_assert {0 <= coords} () prval _ = $UN.prop_assert {coords < BOARD_SIZE} () #else val _ = assertloc (g1i2i 0 <= coords) val _ = assertloc (coords < g1i2i BOARD_SIZE) #endif   val i1 = row_index<tk> coords val j1 = column_index<tk> coords in if g1int_nmod (k, 2) = g1int_nmod (count, 2) then (* The two queens are of the same color. They may not share the same square. *) begin if i <> i1 || j <> j1 then loop (queens, pred k) else false end else (* The two queens are of different colors. They may not share the same square nor attack each other. *) begin if (i <> i1 && j <> j1 && i + j <> i1 + j1 && i - j <> i1 - j1) then loop (queens, pred k) else false end end in loop (queens, pred count) end   fn {tk : tkind} latest_queen_fits_in {count  : int | 1 <= count; count <= M2_MAX} (queens : &(@[g1int tk][M2_MAX]), count  : int count) : bool = let val [coords : int] coords = queens[pred count] #if NDEBUG <> 0 #then prval _ = $UN.prop_assert {0 <= coords} () prval _ = $UN.prop_assert {coords < BOARD_SIZE} () #else val _ = assertloc (g1i2i 0 <= coords) val _ = assertloc (coords < g1i2i BOARD_SIZE) #endif   val i = row_index<tk> coords val j = column_index<tk> coords in queen_would_fit_in<tk> (queens, pred count, i, j) end   fn {tk_index, tk_color : tkind} find_solutions {m : int | 0 <= m; 2 * m <= M2_MAX} {n : int | 0 <= n; n <= SIDE_MAX} {max_solutions : int | 0 <= max_solutions} (f : FILEref, m : int m, n : g1int (tk_index, n), rotation_equiv_classes : bool, max_solutions : int max_solutions) : [num_solutions : int | 0 <= num_solutions; num_solutions <= max_solutions] @(int num_solutions, board_record_list_vt (tk_color, num_solutions)) = (* This template function both prints the solutions and returns them as a linked list. *) if m = 0 then @(0, NIL) else if max_solutions = 0 then @(0, NIL) else let macdef latest_queen_fits_in = latest_queen_fits_in<tk_index> macdef queens_to_board = queens_to_board<tk_index, tk_color> macdef fprint_board = fprint_board<tk_index, tk_color> macdef any_board_equiv = any_board_equiv<tk_index, tk_color> macdef row_index = row_index<tk_index> macdef column_index = column_index<tk_index> macdef storage_index = storage_index<tk_index>   fnx loop {num_solutions : int | 0 <= num_solutions; num_solutions <= max_solutions} {num_queens  : int | 0 <= num_queens; num_queens <= 2 * m} (solutions  : board_record_list_vt (tk_color, num_solutions), num_solutions : int num_solutions, queens  : &(@[g1int tk_index][M2_MAX]), num_queens  : int num_queens) : [num_solutions1 : int | 0 <= num_solutions1; num_solutions1 <= max_solutions] @(int num_solutions1, board_record_list_vt (tk_color, num_solutions1)) = if num_queens = 0 then @(num_solutions, solutions) else if num_solutions = max_solutions then @(num_solutions, solutions) else if latest_queen_fits_in (queens, num_queens) then begin if num_queens = 2 * m then let val board = queens_to_board (queens, num_queens) val equiv_solution = any_board_equiv (!(board.p), solutions, n, rotation_equiv_classes) in if ~equiv_solution then begin fprintln! (f, "Solution ", succ num_solutions); fprint_board (f, !(board.p), n); fileref_puts (f, "\n\n"); move_a_queen (board :: solutions, succ num_solutions, queens, num_queens) end else begin free board; move_a_queen (solutions, num_solutions, queens, num_queens) end end else add_another_queen (solutions, num_solutions, queens, num_queens) end else move_a_queen (solutions, num_solutions, queens, num_queens) and add_another_queen {num_solutions : int | 0 <= num_solutions; num_solutions <= max_solutions} {num_queens : int | 0 <= num_queens; num_queens + 1 <= 2 * m} (solutions : board_record_list_vt (tk_color, num_solutions), num_solutions : int num_solutions, queens  : &(@[g1int tk_index][M2_MAX]), num_queens : int num_queens) : [num_solutions1 : int | 0 <= num_solutions1; num_solutions1 <= max_solutions] @(int num_solutions1, board_record_list_vt (tk_color, num_solutions1)) = let val coords = storage_index (g1i2i 0, g1i2i 0) in queens[num_queens] := coords; loop (solutions, num_solutions, queens, succ num_queens) end and move_a_queen {num_solutions : int | 0 <= num_solutions; num_solutions <= max_solutions} {num_queens : int | 0 <= num_queens; num_queens <= 2 * m} (solutions : board_record_list_vt (tk_color, num_solutions), num_solutions : int num_solutions, queens : &(@[g1int tk_index][M2_MAX]), num_queens : int num_queens) : [num_solutions1 : int | 0 <= num_solutions1; num_solutions1 <= max_solutions] @(int num_solutions1, board_record_list_vt (tk_color, num_solutions1)) = if num_queens = 0 then loop (solutions, num_solutions, queens, num_queens) else let val [coords : int] coords = queens[pred num_queens] #if NDEBUG <> 0 #then prval _ = $UN.prop_assert {0 <= coords} () prval _ = $UN.prop_assert {coords < BOARD_SIZE} () #else val _ = assertloc (g1i2i 0 <= coords) val _ = assertloc (coords < g1i2i BOARD_SIZE) #endif   val [i : int] i = row_index coords val [j : int] j = column_index coords   prval _ = prop_verify {0 <= i} () prval _ = prop_verify {i < SIDE_MAX} ()   prval _ = prop_verify {0 <= j} () prval _ = prop_verify {j < SIDE_MAX} ()   #if NDEBUG <> 0 #then prval _ = $UN.prop_assert {i < n} () prval _ = $UN.prop_assert {j < n} () #else val _ = $effmask_exn assertloc (i < n) val _ = $effmask_exn assertloc (j < n) #endif in if j = pred n then begin if i = pred n then (* Backtrack. *) move_a_queen (solutions, num_solutions, queens, pred num_queens) else let val coords = storage_index (succ i, j) in queens[pred num_queens] := coords; loop (solutions, num_solutions, queens, num_queens) end end else let #if NDEBUG <> 0 #then prval _ = $UN.prop_assert {j < n - 1} () #else val _ = $effmask_exn assertloc (j < pred n) #endif in if i = pred n then let val coords = storage_index (g1i2i 0, succ j) in queens[pred num_queens] := coords; loop (solutions, num_solutions, queens, num_queens) end else let val coords = storage_index (succ i, j) in queens[pred num_queens] := coords; loop (solutions, num_solutions, queens, num_queens) end end end   var queens = @[g1int tk_index][M2_MAX] (g1i2i 0) in queens[0] := storage_index (g1i2i 0, g1i2i 0); loop (NIL, 0, queens, 1) end   (********************************************************************)   %{^ #include <stdlib.h> #include <limits.h> %}   implement main0 (argc, argv) = let stadef tk_index = int_kind stadef tk_color = int_kind   macdef usage_error (status) = begin println! ("Usage: ", argv[0], " M N IGNORE_EQUIVALENTS [MAX_SOLUTIONS]"); exit (,(status)) end   val max_max_solutions = $extval ([i : int | 0 <= i] int i, "INT_MAX") in if 4 <= argc then let val m = $extfcall (int, "atoi", argv[1]) val m = g1ofg0 m val _ = if m < 0 then usage_error (2) val _ = assertloc (0 <= m) val _ = if M2_MAX < 2 * m then begin println! (argv[0], ": M cannot be larger than ", M2_MAX / 2); usage_error (2) end val _ = assertloc (2 * m <= M2_MAX)   val n = $extfcall (int, "atoi", argv[2]) val n = g1ofg0 n val _ = if n < 0 then usage_error (2) val _ = assertloc (0 <= n) val _ = if SIDE_MAX < n then begin println! (argv[0], ": N cannot be larger than ", SIDE_MAX); usage_error (2) end val _ = assertloc (n <= SIDE_MAX)   val ignore_equivalents = if argv[3] = "T" || argv[3] = "t" || argv[3] = "1" then true else if argv[3] = "F" || argv[3] = "f" || argv[3] = "0" then false else begin println! (argv[0], ": select T=t=1 or F=f=0 ", "for IGNORE_EQUIVALENTS"); usage_error (2); false end in if argc = 5 then let val max_solutions = $extfcall (int, "atoi", argv[4]) val max_solutions = g1ofg0 max_solutions val max_solutions = max (0, max_solutions)   val @(num_solutions, solutions) = find_solutions<tk_index, tk_color> (stdout_ref, m, n, ignore_equivalents, max_solutions) in board_record_list_vt_free solutions end else let val @(num_solutions, solutions) = find_solutions<tk_index, tk_color> (stdout_ref, m, n, ignore_equivalents, max_max_solutions) in board_record_list_vt_free solutions end end else usage_error (1) end   (********************************************************************)
http://rosettacode.org/wiki/Password_generator
Password generator
Create a password generation program which will generate passwords containing random ASCII characters from the following groups: lower-case letters: a ──► z upper-case letters: A ──► Z digits: 0 ──► 9 other printable characters:  !"#$%&'()*+,-./:;<=>?@[]^_{|}~ (the above character list excludes white-space, backslash and grave) The generated password(s) must include   at least one   (of each of the four groups): lower-case letter, upper-case letter, digit (numeral),   and one "other" character. The user must be able to specify the password length and the number of passwords to generate. The passwords should be displayed or written to a file, one per line. The randomness should be from a system source or library. The program should implement a help option or button which should describe the program and options when invoked. You may also allow the user to specify a seed value, and give the option of excluding visually similar characters. For example:           Il1     O0     5S     2Z           where the characters are:   capital eye, lowercase ell, the digit one   capital oh, the digit zero   the digit five, capital ess   the digit two, capital zee
#Arturo
Arturo
lowercase: `a`..`z` uppercase: `A`..`Z` digits: `0`..`9` other: map split "!\"#$%&'()*+,-./:;<=>?@[]^_{|}~" => [to :char]   any: lowercase ++ uppercase ++ digits ++ other   generate: function [length][ if length < 4 [ print (color #red "ERROR: ") ++ "password length too short" exit ]   chars: new @[sample lowercase sample uppercase sample digits sample other] while [length > size chars][ 'chars ++ sample any ]   join shuffle chars ]   if 0 = size arg [ print { --------------------------------- Arturo password generator (c) 2021 drkameleon --------------------------------- usage: passgen.art <length> } exit ]   loop 1..10 'x [ print generate to :integer first arg ]
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
#Quackery
Quackery
[ stack ] is perms.min ( --> [ )   [ stack ] is perms.max ( --> [ )   forward is (perms)   [ over size perms.min share > if [ over temp take swap nested join temp put ] over size perms.max share < if [ dup size times [ 2dup i^ pluck rot swap nested join swap (perms) ] ] 2drop ] resolves (perms) ( [ [ --> )   [ perms.max put 1 - perms.min put [] temp put [] swap (perms) temp take perms.min release perms.max release ] is perms ( [ a b --> [ )   [ dup size dup perms ] is permutations ( [ --> [ )   ' [ 1 2 3 ] permutations echo cr $ "quack" permutations 60 wrap$ $ "quack" 3 4 perms 46 wrap$
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.
#jq
jq
  # => = 0 degrees # ^ = 90 degrees # <= = 180 degrees # v = 270 degrees   # $start : [$x, $y] def turtle($start): $start | if type == "array" then "M \($start|join(","))" else "M 0,0" end | {svg: ., up:true, angle:0};   def turtleUp: .up=true; def turtleDown: .up=false;   def turtleRotate($angle): .angle = (360 + (.angle + $angle)) % 360;   def turtleForward($d): if .up then if .angle== 0 then .svg += " m \($d),0" elif .angle== 90 then .svg += " m 0,-\($d)" elif .angle==180 then .svg += " m -\($d),0" elif .angle==270 then .svg += " m 0,\($d)" else "unsupported angle \(.angle)" | error end else if .angle== 0 then .svg += " h \($d)" elif .angle== 90 then .svg += " v -\($d)" elif .angle==180 then .svg += " h -\($d)" elif .angle==270 then .svg += " v \($d)" else "unsupported angle \(.angle)" | error end end;   def svg($size): "<svg viewBox=\"0 0 \($size) \($size)\" xmlns=\"http://www.w3.org/2000/svg\">", ., "</svg>";   def path($fill; $stroke; $width): "<path fill=\"\($fill)\" stroke=\"\($stroke)\" stroke-width=\"\($width)\" d=\"\(.svg)\" />";   def draw: path("none"; "red"; "0.1") | svg(100) ;
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.
#Julia
Julia
using Gtk, Graphics, Colors   function peano(ctx, x, y, lg, i1, i2) if lg < 3 line_to(ctx, x - 250, y - 250) stroke(ctx) move_to(ctx, x - 250 , y - 250) else lg = div(lg, 3) peano(ctx, x + (2 * i1 * lg), y + (2 * i1 * lg), lg, i1, i2) peano(ctx, x + ((i1 - i2 + 1) * lg), y + ((i1 + i2) * lg), lg, i1, 1 - i2) peano(ctx, x + lg, y + lg, lg, i1, 1 - i2) peano(ctx, x + ((i1 + i2) * lg), y + ((i1 - i2 + 1) * lg), lg, 1 - i1, 1 - i2) peano(ctx, x + (2 * i2 * lg), y + ( 2 * (1-i2) * lg), lg, i1, i2) peano(ctx, x + ((1 + i2 - i1) * lg), y + ((2 - i1 - i2) * lg), lg, i1, i2) peano(ctx, x + (2 * (1 - i1) * lg), y + (2 * (1 - i1) * lg), lg, i1, i2) peano(ctx, x + ((2 - i1 - i2) * lg), y + ((1 + i2 - i1) * lg), lg, 1 - i1, i2) peano(ctx, x + (2 * (1 - i2) * lg), y + (2 * i2 * lg), lg, 1 - i1, i2) end end   const can = @GtkCanvas() const win = GtkWindow(can, "Peano Curve", 500, 500)   @guarded draw(can) do widget ctx = getgc(can) h = height(can) w = width(can) set_source(ctx, colorant"blue") set_line_width(ctx, 1) peano(ctx, w/2, h/2, 500, 0, 0) end   show(can) const cond = Condition() endit(w) = notify(cond) signal_connect(endit, win, :destroy) wait(cond)  
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).
#Elixir
Elixir
defmodule Penney do @toss [:Heads, :Tails]   def game(score \\ {0,0}) def game({iwin, ywin}=score) do IO.puts "Penney game score I : #{iwin}, You : #{ywin}" [i, you] = @toss coin = Enum.random(@toss) IO.puts "#{i} I start, #{you} you start ..... #{coin}" {myC, yC} = setup(coin) seq = for _ <- 1..3, do: Enum.random(@toss) IO.write Enum.join(seq, " ") {winner, score} = loop(seq, myC, yC, score) IO.puts "\n #{winner} win!\n" game(score) end   defp setup(:Heads) do myC = Enum.shuffle(@toss) ++ [Enum.random(@toss)] joined = Enum.join(myC, " ") IO.puts "I chose  : #{joined}" {myC, yourChoice} end defp setup(:Tails) do yC = yourChoice myC = (@toss -- [Enum.at(yC,1)]) ++ Enum.take(yC,2) joined = Enum.join(myC, " ") IO.puts "I chose  : #{joined}" {myC, yC} end   defp yourChoice do IO.write "Enter your choice (H/T) " choice = read([]) IO.puts "You chose: #{Enum.join(choice, " ")}" choice end   defp read([_,_,_]=choice), do: choice defp read(choice) do case IO.getn("") |> String.upcase do "H" -> read(choice ++ [:Heads]) "T" -> read(choice ++ [:Tails]) _ -> read(choice) end end   defp loop(myC, myC, _, {iwin, ywin}), do: {"I", {iwin+1, ywin}} defp loop(yC, _, yC, {iwin, ywin}), do: {"You", {iwin, ywin+1}} defp loop(seq, myC, yC, score) do append = Enum.random(@toss) IO.write " #{append}" loop(tl(seq)++[append], myC, yC, score) end end   Penney.game
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.
#Factor
Factor
USING: formatting fry io kernel locals math math.functions math.ranges sequences ; IN: rosetta-code.pathological   : next2 ( x y -- y z ) swap dupd dupd '[ 111 1130 _ / - 3000 _ _ * / + ] call ;   : pathological-sequence ( -- seq ) 2 -4 100 [ next2 dup ] replicate 2nip { 0 2 -4 } prepend ;   : show-sequence ( -- ) { 3 4 5 6 7 8 20 30 50 100 } dup pathological-sequence nths [ "n = %-3d %21.16f\n" printf ] 2each ;   CONSTANT: e 106246577894593683/39085931702241241 : balance ( n -- x ) [1,b] e 1 - [ * 1 - ] reduce ;   :: f ( a b -- x ) 333+3/4 b 6 ^ * 11 a sq b sq * * b 6 ^ - b 4 ^ 121 * - 2 - a sq * b 8 ^ 5+1/2 * a 2 b * / + + + ;   : pathological-demo ( -- ) "Task 1 - Sequence convergence:" print show-sequence nl   "Task 2 - Chaotic Bank fund after 25 years:" print 25 balance "%.16f\n" printf nl   "Task 3 - Siegfried Rump's example:" print 77617 33096 f "77617 33096 f = %.16f\n" printf ;   MAIN: pathological-demo
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.
#Phix
Phix
with javascript_semantics include mpfr.e procedure fun(mpz a,b,t, integer c) -- {a,b} = {b,c*b+a} (and t gets trashed) mpz_set(t,a) mpz_set(a,b) mpz_mul_si(b,b,c) mpz_add(b,b,t) end procedure function SolvePell(integer n) integer x = floor(sqrt(n)), y = x, z = 1, r = x*2 mpz e1 = mpz_init(1), e2 = mpz_init(), f1 = mpz_init(), f2 = mpz_init(1), t = mpz_init(0), u = mpz_init(), a = mpz_init(1), b = mpz_init(0) if x*x!=n then while mpz_cmp_si(t,1)!=0 do y = r*z - y z = floor((n-y*y)/z) r = floor((x+y)/z) fun(e1,e2,t,r) -- {e1,e2} = {e2,r*e2+e1} fun(f1,f2,t,r) -- {f1,f2} = {f2,r*r2+f1} mpz_set(a,f2) mpz_set(b,e2) fun(b,a,t,x) -- {b,a} = {f2,x*f2+e2} mpz_mul(t,a,a) mpz_mul_si(u,b,n) mpz_mul(u,u,b) mpz_sub(t,t,u) -- t = a^2-n*b^2 end while end if return {a, b} end function function split_into_chunks(string x, integer one, rest) sequence res = {x[1..one]} x = x[one+1..$] integer l = length(x) while l do integer k = min(l,rest) res = append(res,x[1..k]) x = x[k+1..$] l -= k end while return join(res,"\n"&repeat(' ',29))&"\n"&repeat(' ',17) end function sequence ns = {4, 61, 109, 181, 277, 8941} for i=1 to length(ns) do integer n = ns[i] mpz {x, y} = SolvePell(n) string xs = mpz_get_str(x,comma_fill:=true), ys = mpz_get_str(y,comma_fill:=true) if length(xs)>97 then xs = split_into_chunks(xs,98,96) ys = split_into_chunks(ys,99,96) end if printf(1,"x^2 - %3d*y^2 = 1 for x = %27s and y = %25s\n", {n, xs, ys}) end for
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.
#11l
11l
F e(&x, row, col) -> & R x[row * (row + 1) I/ 2 + col]   F iterate(&v, &diff, do_print = 1B) V tot = 0.0 L e(&v, 0, 0) = 151 e(&v, 2, 0) = 40 e(&v, 4, 1) = 11 e(&v, 4, 3) = 4   L(i) 1..4 L(j) 0..i e(&diff, i, j) = 0 I j < i e(&diff, i, j) += e(&v, i - 1, j) - e(&v, i, j + 1) - e(&v, i, j) I j != 0 e(&diff, i, j) += e(&v, i - 1, j - 1) - e(&v, i, j - 1) - e(&v, i, j)   L(i) 1..3 L(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)   L(i) 0 .< v.len v[i] += diff[i] / 4   tot = sum(diff.map(a -> a * a)) I do_print print(‘dev: ’tot) I tot < 0.1 L.break   V v = [0.0] * 15 V diff = [0.0] * 15 iterate(&v, &diff)   V idx = 0 L(i) 5 L(j) 0..i print(‘#4’.format(Int(0.5 + v[idx])), end' I j < i {‘ ’} E "\n") idx++
http://rosettacode.org/wiki/Pentagram
Pentagram
A pentagram is a star polygon, consisting of a central pentagon of which each side forms the base of an isosceles triangle. The vertex of each triangle, a point of the star, is 36 degrees. Task Draw (or print) a regular pentagram, in any orientation. Use a different color (or token) for stroke and fill, and background. For the fill it should be assumed that all points inside the triangles and the pentagon are inside the pentagram. See also Angle sum of a pentagram
#XPL0
XPL0
proc FillArea(X, Y, C0, C); \Replace area colored C0 with color C int X, Y, \starting coordinate for flood fill algorithm C0, C; \initial color, and color to replace it with def S=8000; \size of queue (must be an even number) int Q(S), \queue (FIFO) F, E; \fill and empty indexes   proc EnQ(X, Y); \Enqueue coordinate int X, Y; [Q(F):= X; F:= F+1; Q(F):= Y; F:= F+1; if F >= S then F:= 0; ]; \EnQ   proc DeQ; \Dequeue coordinate [X:= Q(E); E:= E+1; Y:= Q(E); E:= E+1; if E >= S then E:= 0; ]; \DeQ   [if C0 = C then return; F:= 0; E:= 0; EnQ(X, Y); while E # F do [DeQ; if ReadPix(X, Y) = C0 then [Point(X, Y, C); EnQ(X+1, Y); \enqueue adjacent pixels EnQ(X-1, Y); EnQ(X, Y+1); EnQ(X, Y-1); ]; ]; ]; \FillArea   def Size = 200.; def Pi = 3.141592654; def Deg144 = 4.*Pi/5.; int X, Y, N; [SetVid($12); \set 640x480x4 VGA graphics for Y:= 0 to 480-1 do \fill screen [Move(0, Y); Line(640-1, Y, $F\white\)]; for N:= 0 to 5 do \draw pentagram [X:= fix(Size*Sin(float(N)*Deg144)); Y:= fix(Size*Cos(float(N)*Deg144)); if N = 0 then Move(X+320, 240-Y) else Line(X+320, 240-Y, 4\red\); ]; FillArea(0, 0, $F, 1); \replace white (F) with blue (1) ]
http://rosettacode.org/wiki/Pentagram
Pentagram
A pentagram is a star polygon, consisting of a central pentagon of which each side forms the base of an isosceles triangle. The vertex of each triangle, a point of the star, is 36 degrees. Task Draw (or print) a regular pentagram, in any orientation. Use a different color (or token) for stroke and fill, and background. For the fill it should be assumed that all points inside the triangles and the pentagon are inside the pentagram. See also Angle sum of a pentagram
#zkl
zkl
const DIM=200, SIDES=5, A=360/SIDES, R=DIM.toFloat(); vs:=[0.0..360-A,A].apply("toRad"); // angles of vertices #<<< 0'|<?xml version="1.0" standalone="no" ?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" "http://www.w3.org/TR/2001/PR-SVG-20010719/DTD/svg10.dtd"> <svg height="%d" width="%d" style="" xmlns="http://www.w3.org/2000/svg"> <rect height="100%" width="100%" style="fill:bisque;" />| #<<< .fmt(DIM*2, DIM*2).println();   var vertices=vs.pump(List,fcn(a){ R.toRectangular(a) }); //( (x,y), (x,y)... SIDES.pump(String,pline).println(); // the line pairs that draw the pentagram   fcn pline(n){ a:=(n + 2)%SIDES; // (n,a) are the endpoints of the right leg pts:=String("\"", ("% 0.3f,% 0.3f "*2), "\" "); // two points vs:='wrap(){ T(n,a).pump(List,vertices.get).flatten() }; //(x,y, x,y) String( (0'|<polyline points=| + pts).fmt(vs().xplode()), 0'|style="fill:seashell; stroke:blue; stroke-width:3;" |, 0'|transform="translate(%d,%d) rotate(-18)"|.fmt(DIM,DIM), " />\n" ); } println("</svg>");
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
#C
C
#include <math.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h>   enum Piece { Empty, Black, White, };   typedef struct Position_t { int x, y; } Position;   ///////////////////////////////////////////////   struct Node_t { Position pos; struct Node_t *next; };   void releaseNode(struct Node_t *head) { if (head == NULL) return;   releaseNode(head->next); head->next = NULL;   free(head); }   typedef struct List_t { struct Node_t *head; struct Node_t *tail; size_t length; } List;   List makeList() { return (List) { NULL, NULL, 0 }; }   void releaseList(List *lst) { if (lst == NULL) return;   releaseNode(lst->head); lst->head = NULL; lst->tail = NULL; }   void addNode(List *lst, Position pos) { struct Node_t *newNode;   if (lst == NULL) { exit(EXIT_FAILURE); }   newNode = malloc(sizeof(struct Node_t)); if (newNode == NULL) { exit(EXIT_FAILURE); }   newNode->next = NULL; newNode->pos = pos;   if (lst->head == NULL) { lst->head = lst->tail = newNode; } else { lst->tail->next = newNode; lst->tail = newNode; }   lst->length++; }   void removeAt(List *lst, size_t pos) { if (lst == NULL) return;   if (pos == 0) { struct Node_t *temp = lst->head;   if (lst->tail == lst->head) { lst->tail = NULL; }   lst->head = lst->head->next; temp->next = NULL;   free(temp); lst->length--; } else { struct Node_t *temp = lst->head; struct Node_t *rem; size_t i = pos;   while (i-- > 1) { temp = temp->next; }   rem = temp->next; if (rem == lst->tail) { lst->tail = temp; }   temp->next = rem->next;   rem->next = NULL; free(rem);   lst->length--; } }   ///////////////////////////////////////////////   bool isAttacking(Position queen, Position pos) { return queen.x == pos.x || queen.y == pos.y || abs(queen.x - pos.x) == abs(queen.y - pos.y); }   bool place(int m, int n, List *pBlackQueens, List *pWhiteQueens) { struct Node_t *queenNode; bool placingBlack = true; int i, j;   if (pBlackQueens == NULL || pWhiteQueens == NULL) { exit(EXIT_FAILURE); }   if (m == 0) return true; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { Position pos = { i, j };   queenNode = pBlackQueens->head; while (queenNode != NULL) { if ((queenNode->pos.x == pos.x && queenNode->pos.y == pos.y) || !placingBlack && isAttacking(queenNode->pos, pos)) { goto inner; } queenNode = queenNode->next; }   queenNode = pWhiteQueens->head; while (queenNode != NULL) { if ((queenNode->pos.x == pos.x && queenNode->pos.y == pos.y) || placingBlack && isAttacking(queenNode->pos, pos)) { goto inner; } queenNode = queenNode->next; }   if (placingBlack) { addNode(pBlackQueens, pos); placingBlack = false; } else { addNode(pWhiteQueens, pos); if (place(m - 1, n, pBlackQueens, pWhiteQueens)) { return true; } removeAt(pBlackQueens, pBlackQueens->length - 1); removeAt(pWhiteQueens, pWhiteQueens->length - 1); placingBlack = true; }   inner: {} } } if (!placingBlack) { removeAt(pBlackQueens, pBlackQueens->length - 1); } return false; }   void printBoard(int n, List *pBlackQueens, List *pWhiteQueens) { size_t length = n * n; struct Node_t *queenNode; char *board; size_t i, j, k;   if (pBlackQueens == NULL || pWhiteQueens == NULL) { exit(EXIT_FAILURE); }   board = calloc(length, sizeof(char)); if (board == NULL) { exit(EXIT_FAILURE); }   queenNode = pBlackQueens->head; while (queenNode != NULL) { board[queenNode->pos.x * n + queenNode->pos.y] = Black; queenNode = queenNode->next; }   queenNode = pWhiteQueens->head; while (queenNode != NULL) { board[queenNode->pos.x * n + queenNode->pos.y] = White; queenNode = queenNode->next; }   for (i = 0; i < length; i++) { if (i != 0 && i % n == 0) { printf("\n"); } switch (board[i]) { case Black: printf("B "); break; case White: printf("W "); break; default: j = i / n; k = i - j * n; if (j % 2 == k % 2) { printf(" "); } else { printf("# "); } break; } }   printf("\n\n"); }   void test(int n, int q) { List blackQueens = makeList(); List whiteQueens = makeList();   printf("%d black and %d white queens on a %d x %d board:\n", q, q, n, n); if (place(q, n, &blackQueens, &whiteQueens)) { printBoard(n, &blackQueens, &whiteQueens); } else { printf("No solution exists.\n\n"); }   releaseList(&blackQueens); releaseList(&whiteQueens); }   int main() { test(2, 1);   test(3, 1); test(3, 2);   test(4, 1); test(4, 2); test(4, 3);   test(5, 1); test(5, 2); test(5, 3); test(5, 4); test(5, 5);   test(6, 1); test(6, 2); test(6, 3); test(6, 4); test(6, 5); test(6, 6);   test(7, 1); test(7, 2); test(7, 3); test(7, 4); test(7, 5); test(7, 6); test(7, 7);   return EXIT_SUCCESS; }
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
#AWK
AWK
  # syntax: GAWK -f PASSWORD_GENERATOR.AWK [-v mask=x] [-v xt=x] # # examples: # REM 4 character passwords using Rosetta Code default of: lower, upper, number, other # GAWK -f PASSWORD_GENERATOR.AWK # # REM 8 character passwords; Rosetta Code default plus another four # GAWK -f PASSWORD_GENERATOR.AWK -v mask=LUNPEEEE # # REM 8 character passwords ignoring Rosetta Code requirement # GAWK -f PASSWORD_GENERATOR.AWK -v mask=EEEEEEEE # # REM help # GAWK -f PASSWORD_GENERATOR.AWK ? # # sorting: # PROCINFO["sorted_in"] is used by GAWK # SORTTYPE is used by Thompson Automation's TAWK # BEGIN { PROCINFO["sorted_in"] = "@ind_str_asc" ; SORTTYPE = 1 srand() # setup strings of valid characters used by mask arr["L"] = "abcdefghijklmnopqrstuvwxyz" # Lower case arr["U"] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" # Upper case arr["N"] = "0123456789" # Numbers arr["P"] = "!\"#$%&'()*+,-./:;<=>?@[]^_{|}~" # Punctuation: I.E. other arr["A"] = arr["L"] arr["U"] # Alphabetic: lower and upper case arr["E"] = arr["L"] arr["U"] arr["N"] arr["P"] # Everything: lower, upper, number, punctuation arr["B"] = " " # Blank: a space # validate array index and length of assignment for (i in arr) { if (length(i) != 1) { error(sprintf("arr[%s], index is invalid",i)) } if (length(arr[i]) == 0) { error(sprintf("arr[%s], is null",i)) } mask_valids = sprintf("%s%s",mask_valids,i) } # validate command line variables if (mask == "") { mask = "LUNP" # satisfy Rosetta Code task requirement } if (xt == "") { xt = 10 # default iterations } if (xt !~ /^[0-9]+$/) { error("xt is not 0-9") } # validate each character in mask for (i=1; i<=length(mask); i++) { c = substr(mask,i,1) if (!(c in arr)) { error(sprintf("mask position %d is %s, invalid",i,c)) } } # help if (ARGV[1] == "?") { syntax() exit(0) } if (ARGC-1 != 0) { error("no files allowed on command line") } # make passwords if (errors == 0) { for (i=1; i<=xt; i++) { make_password() } } exit(errors+0) } function error(message) { printf("error: %s\n",message) errors++ } function make_password( c,i,indx,password,valids) { for (i=1; i<=length(mask); i++) { # for each character in mask c = substr(mask,i,1) # extract 1 character from mask valids = arr[c] # valid characters for this position in mask indx = int(rand() * length(valids)) + 1 c = substr(valids,indx,1) # extract 1 character from list of valids password = password c # build password } printf("%s\n",password) } function syntax( cmd,i) { cmd = "GAWK -f PASSWORD_GENERATOR.AWK" printf("syntax: %s [-v mask=x] [-v xt=x]\n\n",cmd) printf(" mask 1..n bytes determines password format and length; consists of %s\n",mask_valids) for (i in arr) { printf("%9s - %s\n",i,(arr[i] == " ") ? "<space>" : arr[i]) } printf(" xt number of passwords to generate\n\n") printf("example: %s -v mask=%s -v xt=%s\n",cmd,mask,xt) }  
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
#R
R
next.perm <- function(a) { n <- length(a) i <- n while (i > 1 && a[i - 1] >= a[i]) i <- i - 1 if (i == 1) { NULL } else { j <- i k <- n while (j < k) { s <- a[j] a[j] <- a[k] a[k] <- s j <- j + 1 k <- k - 1 } s <- a[i - 1] j <- i while (a[j] <= s) j <- j + 1 a[i - 1] <- a[j] a[j] <- s a } }   perm <- function(n) { e <- NULL a <- 1:n repeat { e <- cbind(e, a) a <- next.perm(a) if (is.null(a)) break } unname(e) }
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.
#Lua
Lua
local PeanoLSystem = { axiom = "L", rules = { L = "LFRFL-F-RFLFR+F+LFRFL", R = "RFLFR+F+LFRFL-F-RFLFR" }, eval = function(self, n) local source, result = self.axiom for i = 1, n do result = "" for j = 1, #source do local ch = source:sub(j,j) result = result .. (self.rules[ch] and self.rules[ch] or ch) end source = result end return result end }   function Bitmap:drawPath(path, x, y, dx, dy) self:set(x, y, "@") for i = 1, #path do local ch = path:sub(i,i) if (ch == "F") then local reps = dx==0 and 1 or 3 -- aspect correction for r = 1, reps do x, y = x+dx, y+dy self:set(x, y, dx==0 and "|" or "-") end x, y = x+dx, y+dy self:set(x, y, "+") elseif (ch =="-") then dx, dy = dy, -dx elseif (ch == "+") then dx, dy = -dy, dx end end self:set(x, y, "X") end   function Bitmap:render() for y = 1, self.height do print(table.concat(self.pixels[y])) end end   bitmap = Bitmap(53*2,53) bitmap:clear(" ") bitmap:drawPath(PeanoLSystem:eval(3), 0, 0, 0, 1) bitmap:render()
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).
#Factor
Factor
USING: arrays ascii io kernel math prettyprint random sequences strings ; IN: rosetta-code.penneys-game   ! Generate a random boolean. : t|f ( -- t/f ) 1 random-bits 0 = ;   ! Checks whether the sequence chosen by the human is valid. : valid-input? ( seq -- ? ) [ [ CHAR: H = ] [ CHAR: T = ] bi or ] filter length 3 = ;   ! Prompt the human player for a sequence. : input-seq ( -- seq ) "Please input a 3-long sequence of H or T (heads or tails)." print "Example: HTH" print "> " write readln >upper >array ;   ! Get the human player's input sequence with error checking. : get-input ( -- seq ) t [ drop input-seq dup valid-input? not ] loop ;   ! Add a random coin flip to a vector. : flip-coin ( vector -- vector' ) t|f CHAR: H CHAR: T ? over push ;   ! Generate a random 3-long sequence of coin flips. : rand-seq ( -- seq ) V{ } clone 3 [ flip-coin ] times ;   ! Generate the optimal sequence response to a given sequence. : optimal ( seq1 -- seq2 ) [ second dup CHAR: H = [ CHAR: T ] [ CHAR: H ] if ] [ first ] [ second ] tri 3array nip dup "The computer chose " write >string write "." print ;   ! Choose a random sequence for the computer and report what ! was chosen. : computer-first ( -- seq ) "The computer picks a sequence first and chooses " write rand-seq dup >string write "." print >array ;   ! The human is prompted to choose any sequence with no ! restrictions. : human-first ( -- seq ) "You get to go first." print get-input ;   ! Forbid the player from choosing the same sequence as the ! computer. : human-second ( cseq -- cseq hseq ) get-input [ 2dup = not ] [ drop "You may not choose the same sequence as the computer." print get-input ] until ;   ! Display a message introducing the game. : welcome ( -- ) "Welcome to Penney's Game. The computer or the player" print "will be randomly selected to choose a sequence of" print "three coin tosses. The sequence will be shown to the" print "opponent, and then he will choose a sequence." print nl "Then, a coin will be flipped until the sequence" print "matches the last three coin flips, and a winner" print "announced." print nl ;   ! Check for human victory. : human-won? ( cseq hseq coin-flips -- ? ) 3 tail* >array = nip ;   ! Check for computer victory. : computer-won? ( cseq hseq coin-flips -- ? ) 3 tail* >array pick = 2nip ;   ! Flip a coin until a victory is detected. Then, inform the ! player who won. : flip-coins ( cseq hseq -- ) "Flipping coins..." print rand-seq [ 3dup [ human-won? ] [ computer-won? ] 3bi or ] [ flip-coin ] until dup >string print human-won? [ "You won!" print ] [ "The computer won." print ] if ;   ! Randomly choose a player to choose their sequence first. ! Then play a full round of Penney's Game. : start-game ( -- ) welcome t|f [ human-first dup optimal swap ] [ computer-first human-second ] if flip-coins ;   start-game
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.
#Fortran
Fortran
SUBROUTINE MULLER REAL*4 VN,VNL1,VNL2 !The exact precision and dynamic range REAL*8 WN,WNL1,WNL2 !Depends on the format's precise usage of bits. INTEGER I !A stepper. WRITE (6,1) !A heading. 1 FORMAT ("Muller's sequence should converge to six...",/ 1 " N Single Double") VNL1 = 2; VN = -4 !Initialise for N = 2. WNL1 = 2; WN = -4 !No fractional parts yet. DO I = 3,36 !No point going any further. VNL2 = VNL1; VNL1 = VN !Shuffle the values along one place. WNL2 = WNL1; WNL1 = WN !Ready for the next term's calculation. VN = 111 - 1130/VNL1 + 3000/(VNL1*VNL2) !Calculate the next term. WN = 111 - 1130/WNL1 + 3000/(WNL1*WNL2) !In double precision. WRITE (6,2) I,VN,WN !Show both. 2 FORMAT (I3,F12.7,F21.16) !With too many fractional digits. END DO !On to the next term. END SUBROUTINE MULLER !That was easy. Too bad the results are wrong.   SUBROUTINE CBS !The Chaotic Bank Society. INTEGER YEAR !A stepper. REAL*4 V !The balance. REAL*8 W !In double precision as well. V = 1; W = 1 !Initial values, without dozy 1D0 stuff. V = EXP(V) - 1 !Actual initial value desired is e - 1.., W = EXP(W) - 1 !This relies on double-precision W selecting DEXP. WRITE (6,1) !Here we go. 1 FORMAT (///"The Chaotic Bank Society in action..."/"Year") WRITE (6,2) 0,V,W !Show the initial deposit. 2 FORMAT (I3,F16.7,F28.16) DO YEAR = 1,25 !Step through some years. V = V*YEAR - 1 !The specified procedure. W = W*YEAR - 1 !The compiler handles type conversions. WRITE (6,2) YEAR,V,W !The current balance. END DO !On to the following year. END SUBROUTINE CBS !Madness!   REAL*4 FUNCTION SR4(A,B) !Siegfried Rump's example function of 1988. REAL*4 A,B SR4 = 333.75*B**6 1 + A**2*(11*A**2*B**2 - B**6 - 121*B**4 - 2) 2 + 5.5*B**8 + A/(2*B) END FUNCTION SR4 REAL*8 FUNCTION SR8(A,B) !Siegfried Rump's example function. REAL*8 A,B SR8 = 333.75*B**6 !.75 is exactly represented in binary. 1 + A**2*(11*A**2*B**2 - B**6 - 121*B**4 - 2) 2 + 5.5*B**8 + A/(2*B)!.5 is exactly represented in binary. END FUNCTION SR8   PROGRAM POKE REAL*4 V !Some example variables. REAL*8 W !Whose type goes to the inquiry function. WRITE (6,1) RADIX(V),DIGITS(V),"single",DIGITS(W),"double" 1 FORMAT ("Floating-point arithmetic is conducted in base ",I0,/ 1 2(I3," digits for ",A," precision",/)) WRITE (6,*) "Single precision limit",HUGE(V) WRITE (6,*) "Double precision limit",HUGE(W) WRITE (6,*)   CALL MULLER   CALL CBS   WRITE (6,10) 10 FORMAT (///"Evaluation of Siegfried Rump's function of 1988", 1 " where F(77617,33096) = -0.827396059946821") WRITE (6,*) "Single precision:",SR4(77617.0,33096.0) WRITE (6,*) "Double precision:",SR8(77617.0D0,33096.0D0) !Must match the types. END
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.
#Prolog
Prolog
  % Find the square root as a continued fraction   cf_sqrt(N, Sz, [A0, Frac]) :- A0 is floor(sqrt(N)), (A0*A0 =:= N -> Sz = 0, Frac = [] ; cf_sqrt(N, A0, A0, 0, 1, 0, [], Sz, Frac)).   cf_sqrt(N, A, A0, M0, D0, Sz0, L, Sz, R) :- M1 is D0*A0 - M0, D1 is (N - M1*M1) div D0, A1 is (A + M1) div D1, (A1 =:= 2*A -> succ(Sz0, Sz), revtl([A1|L], R, R) ; succ(Sz0, Sz1), cf_sqrt(N, A, A1, M1, D1, Sz1, [A1|L], Sz, R)).   revtl([], Z, Z). revtl([A|As], Bs, Z) :- revtl(As, [A|Bs], Z).     % evaluate an infinite continued fraction as a lazy list of convergents. % convergents([A0, As], Lz) :- lazy_list(next_convergent, eval_state(1, 0, A0, 1, As), Lz).   next_convergent(eval_state(P0, Q0, P1, Q1, [Term|Ts]), eval_state(P1, Q1, P2, Q2, Ts), R) :- P2 is Term*P1 + P0, Q2 is Term*Q1 + Q0, R is P1 rdiv Q1.     % solve Pell's equation % pell(N, X, Y) :- cf_sqrt(N, _, D), convergents(D, Rs), once((member(R, Rs), ratio(R, P, Q), P*P - N*Q*Q =:= 1)), pell_seq(N, P, Q, X, Y).   ratio(N, N, 1) :- integer(N). ratio(P rdiv Q, P, Q).   pell_seq(_, X, Y, X, Y). pell_seq(N, X0, Y0, X2, Y2) :- pell_seq(N, X0, Y0, X1, Y1), X2 is X0*X1 + N*Y0*Y1, Y2 is X0*Y1 + Y0*X1.  
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.
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO;   procedure Pyramid_of_Numbers is   B_X, B_Y, B_Z : Integer := 0; -- Unknown variables   type Block_Value is record Known  : Integer := 0; X, Y, Z : Integer := 0; end record; X : constant Block_Value := (0, 1, 0, 0); Y : constant Block_Value := (0, 0, 1, 0); Z : constant Block_Value := (0, 0, 0, 1); procedure Add (L : in out Block_Value; R : Block_Value) is begin -- Symbolically adds one block to another L.Known := L.Known + R.Known; L.X := L.X + R.X - R.Z; -- Z is excluded as n(Y - X - Z) = 0 L.Y := L.Y + R.Y + R.Z; end Add; procedure Add (L : in out Block_Value; R : Integer) is begin -- Symbolically adds a value to the block L.Known := L.Known + R; end Add;   function Image (N : Block_Value) return String is begin -- The block value, when X,Y,Z are known return Integer'Image (N.Known + N.X * B_X + N.Y * B_Y + N.Z * B_Z); end Image;   procedure Solve_2x2 (A11, A12, B1, A21, A22, B2 : Integer) is begin -- Don't care about things, supposing an integer solution exists if A22 = 0 then B_X := B2 / A21; B_Y := (B1 - A11*B_X) / A12; else B_X := (B1*A22 - B2*A12) / (A11*A22 - A21*A12); B_Y := (B1 - A11*B_X) / A12; end if; B_Z := B_Y - B_X; end Solve_2x2;   B : array (1..5, 1..5) of Block_Value; -- The lower triangle contains blocks   begin -- The bottom blocks Add (B(5,1),X); Add (B(5,2),11); Add (B(5,3),Y); Add (B(5,4),4); Add (B(5,5),Z);   -- Upward run for Row in reverse 1..4 loop for Column in 1..Row loop Add (B (Row, Column), B (Row + 1, Column)); Add (B (Row, Column), B (Row + 1, Column + 1)); end loop; end loop;   -- Now have known blocks 40=(3,1), 151=(1,1) and Y=X+Z to determine X,Y,Z Solve_2x2 ( B(1,1).X, B(1,1).Y, 151 - B(1,1).Known, B(3,1).X, B(3,1).Y, 40 - B(3,1).Known );   -- Print the results for Row in 1..5 loop New_Line; for Column in 1..Row loop Put (Image (B(Row,Column))); end loop; end loop; end Pyramid_of_Numbers;
http://rosettacode.org/wiki/Particle_fountain
Particle fountain
Implement a particle fountain. Emulate a fountain of water droplets in a gravitational field being sprayed up and then falling back down. The particle fountain should be generally ordered but individually chaotic; the particles should be going mostly in the same direction, but should have slightly different vectors. Your fountain should have at least several hundred particles in motion at any one time, and ideally several thousand. It is optional to have the individual particle interact with each other. If at all possible, link to a short video clip of your fountain in action. Off-site link to a demo video
#C.2B.2B
C++
#include <SDL2/SDL.h>   #include <algorithm> #include <chrono> #include <cmath> #include <iostream> #include <memory> #include <random> #include <tuple> #include <vector>   auto now() { using namespace std::chrono; auto time = system_clock::now(); return duration_cast<milliseconds>(time.time_since_epoch()).count(); }   auto hsv_to_rgb(int h, double s, double v) { double hp = h / 60.0; double c = s * v; double x = c * (1 - std::abs(std::fmod(hp, 2) - 1)); double m = v - c; double r = 0, g = 0, b = 0; if (hp <= 1) { r = c; g = x; } else if (hp <= 2) { r = x; g = c; } else if (hp <= 3) { g = c; b = x; } else if (hp <= 4) { g = x; b = c; } else if (hp <= 5) { r = x; b = c; } else { r = c; b = x; } r += m; g += m; b += m; return std::make_tuple(Uint8(r * 255), Uint8(g * 255), Uint8(b * 255)); }   class ParticleFountain { public: ParticleFountain(int particles, int width, int height); void run();   private: struct WindowDeleter { void operator()(SDL_Window* window) const { SDL_DestroyWindow(window); } }; struct RendererDeleter { void operator()(SDL_Renderer* renderer) const { SDL_DestroyRenderer(renderer); } }; struct PointInfo { double x = 0; double y = 0; double vx = 0; double vy = 0; double lifetime = 0; };   void update(double df); bool handle_event(); void render(); double rand() { return dist_(rng_); } double reciprocate() const { return reciprocate_ ? range_ * std::sin(now() / 1000.0) : 0.0; }   std::unique_ptr<SDL_Window, WindowDeleter> window_; std::unique_ptr<SDL_Renderer, RendererDeleter> renderer_; int width_; int height_; std::vector<PointInfo> point_info_; std::vector<SDL_Point> points_; int num_points_ = 0; double saturation_ = 0.4; double spread_ = 1.5; double range_ = 1.5; bool reciprocate_ = false; std::mt19937 rng_; std::uniform_real_distribution<> dist_; };   ParticleFountain::ParticleFountain(int n, int width, int height) : width_(width), height_(height), point_info_(n), points_(n, {0, 0}), rng_(std::random_device{}()), dist_(0.0, 1.0) { window_.reset(SDL_CreateWindow( "C++ Particle System!", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, SDL_WINDOW_RESIZABLE)); if (window_ == nullptr) throw std::runtime_error(SDL_GetError());   renderer_.reset( SDL_CreateRenderer(window_.get(), -1, SDL_RENDERER_ACCELERATED)); if (renderer_ == nullptr) throw std::runtime_error(SDL_GetError()); }   void ParticleFountain::run() { for (double df = 0.0001;;) { auto start = now(); if (!handle_event()) break; update(df); render(); df = (now() - start) / 1000.0; } }   void ParticleFountain::update(double df) { int pointidx = 0; for (PointInfo& point : point_info_) { bool willdraw = false; if (point.lifetime <= 0.0) { if (rand() < df) { point.lifetime = 2.5; point.x = width_ / 20.0; point.y = height_ / 10.0; point.vx = (spread_ * rand() - spread_ / 2 + reciprocate()) * 10.0; point.vy = (rand() - 2.9) * height_ / 20.5; willdraw = true; } } else { if (point.y > height_ / 10.0 && point.vy > 0) point.vy *= -0.3; point.vy += (height_ / 10.0) * df; point.x += point.vx * df; point.y += point.vy * df; point.lifetime -= df; willdraw = true; } if (willdraw) { points_[pointidx].x = std::floor(point.x * 10.0); points_[pointidx].y = std::floor(point.y * 10.0); ++pointidx; } } num_points_ = pointidx; }   bool ParticleFountain::handle_event() { bool result = true; SDL_Event event; while (result && SDL_PollEvent(&event)) { switch (event.type) { case SDL_QUIT: result = false; break; case SDL_WINDOWEVENT: if (event.window.event == SDL_WINDOWEVENT_RESIZED) { width_ = event.window.data1; height_ = event.window.data2; } break; case SDL_KEYDOWN: switch (event.key.keysym.scancode) { case SDL_SCANCODE_UP: saturation_ = std::min(saturation_ + 0.1, 1.0); break; case SDL_SCANCODE_DOWN: saturation_ = std::max(saturation_ - 0.1, 0.0); break; case SDL_SCANCODE_PAGEUP: spread_ = std::min(spread_ + 0.1, 5.0); break; case SDL_SCANCODE_PAGEDOWN: spread_ = std::max(spread_ - 0.1, 0.2); break; case SDL_SCANCODE_RIGHT: range_ = std::min(range_ + 0.1, 2.0); break; case SDL_SCANCODE_LEFT: range_ = std::max(range_ - 0.1, 0.1); break; case SDL_SCANCODE_SPACE: reciprocate_ = !reciprocate_; break; case SDL_SCANCODE_Q: result = false; break; default: break; } break; } } return result; }   void ParticleFountain::render() { SDL_Renderer* renderer = renderer_.get(); SDL_SetRenderDrawColor(renderer, 0x0, 0x0, 0x0, 0xff); SDL_RenderClear(renderer); auto [red, green, blue] = hsv_to_rgb((now() % 5) * 72, saturation_, 1); SDL_SetRenderDrawColor(renderer, red, green, blue, 0x7f); SDL_RenderDrawPoints(renderer, points_.data(), num_points_); SDL_RenderPresent(renderer); }   int main() { std::cout << "Use UP and DOWN arrow keys to modify the saturation of the " "particle colors.\n" "Use PAGE UP and PAGE DOWN keys to modify the \"spread\" of " "the particles.\n" "Toggle reciprocation off / on with the SPACE bar.\n" "Use LEFT and RIGHT arrow keys to modify angle range for " "reciprocation.\n" "Press the \"q\" key to quit.\n";   if (SDL_Init(SDL_INIT_VIDEO) != 0) { std::cerr << "ERROR: " << SDL_GetError() << '\n'; return EXIT_FAILURE; }   try { ParticleFountain pf(3000, 800, 800); pf.run(); } catch (const std::exception& ex) { std::cerr << "ERROR: " << ex.what() << '\n'; SDL_Quit(); return EXIT_FAILURE; }   SDL_Quit(); return EXIT_SUCCESS; }
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
#C.23
C#
using System; using System.Collections.Generic;   namespace PeacefulChessQueenArmies { using Position = Tuple<int, int>;   enum Piece { Empty, Black, White }   class Program { static bool IsAttacking(Position queen, Position pos) { return queen.Item1 == pos.Item1 || queen.Item2 == pos.Item2 || Math.Abs(queen.Item1 - pos.Item1) == Math.Abs(queen.Item2 - pos.Item2); }   static bool Place(int m, int n, List<Position> pBlackQueens, List<Position> pWhiteQueens) { if (m == 0) { return true; } bool placingBlack = true; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { var pos = new Position(i, j); foreach (var queen in pBlackQueens) { if (queen.Equals(pos) || !placingBlack && IsAttacking(queen, pos)) { goto inner; } } foreach (var queen in pWhiteQueens) { if (queen.Equals(pos) || placingBlack && IsAttacking(queen, pos)) { goto inner; } } if (placingBlack) { pBlackQueens.Add(pos); placingBlack = false; } else { pWhiteQueens.Add(pos); if (Place(m - 1, n, pBlackQueens, pWhiteQueens)) { return true; } pBlackQueens.RemoveAt(pBlackQueens.Count - 1); pWhiteQueens.RemoveAt(pWhiteQueens.Count - 1); placingBlack = true; } inner: { } } } if (!placingBlack) { pBlackQueens.RemoveAt(pBlackQueens.Count - 1); } return false; }   static void PrintBoard(int n, List<Position> blackQueens, List<Position> whiteQueens) { var board = new Piece[n * n];   foreach (var queen in blackQueens) { board[queen.Item1 * n + queen.Item2] = Piece.Black; } foreach (var queen in whiteQueens) { board[queen.Item1 * n + queen.Item2] = Piece.White; }   for (int i = 0; i < board.Length; i++) { if (i != 0 && i % n == 0) { Console.WriteLine(); } switch (board[i]) { case Piece.Black: Console.Write("B "); break; case Piece.White: Console.Write("W "); break; case Piece.Empty: int j = i / n; int k = i - j * n; if (j % 2 == k % 2) { Console.Write(" "); } else { Console.Write("# "); } break; } }   Console.WriteLine("\n"); }   static void Main() { var nms = new int[,] { {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 (int i = 0; i < nms.GetLength(0); i++) { Console.WriteLine("{0} black and {0} white queens on a {1} x {1} board:", nms[i, 1], nms[i, 0]); List<Position> blackQueens = new List<Position>(); List<Position> whiteQueens = new List<Position>(); if (Place(nms[i, 1], nms[i, 0], blackQueens, whiteQueens)) { PrintBoard(nms[i, 0], blackQueens, whiteQueens); } else { Console.WriteLine("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
#C
C
  #include <stdio.h> #include <stdlib.h> #include <time.h>   #define DEFAULT_LENGTH 4 #define DEFAULT_COUNT 1   char* symbols[] = {"ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz", "0123456789", "!\"#$%&'()*+,-./:;<=>?@[]^_{|}~"}; int length = DEFAULT_LENGTH; int count = DEFAULT_COUNT; unsigned seed; char exSymbols = 0;   void GetPassword () { //create an array of values that determine the number of characters from each category int lengths[4] = {1, 1, 1, 1}; int count = 4; while (count < length) { lengths[rand()%4]++; count++; }   //loop through the array of lengths and set the characters in password char password[length + 1]; for (int i = 0; i < length; ) { //pick which string to read from int str = rand()%4; if (!lengths[str])continue; //if the number of characters for that string have been reached, continue to the next interation   char c; switch (str) { case 2: c = symbols[str][rand()%10]; while (exSymbols && (c == 'I' || c == 'l' || c == '1' || c == 'O' || c == '0' || c == '5' || c == 'S' || c == '2' || c == 'Z')) c = symbols[str][rand()%10]; password[i] = c; break;   case 3: c = symbols[str][rand()%30]; while (exSymbols && (c == 'I' || c == 'l' || c == '1' || c == 'O' || c == '0' || c == '5' || c == 'S' || c == '2' || c == 'Z')) c = symbols[str][rand()%30]; password[i] = c; break;   default: c = symbols[str][rand()%26]; while (exSymbols && (c == 'I' || c == 'l' || c == '1' || c == 'O' || c == '0' || c == '5' || c == 'S' || c == '2' || c == 'Z')) c = symbols[str][rand()%26]; password[i] = c; break; }   i++; lengths[str]--; }   password [length] = '\0'; printf ("%s\n", password); }   int main (int argc, char* argv[]) { seed = (unsigned)time(NULL);   //handle user input from the command line for (int i = 1; i < argc; i++) { switch (argv[i][1]) { case 'l': if (sscanf (argv[i+1], "%d", &length) != 1) { puts ("Unrecognized input. Syntax: -l [integer]"); return -1; }   if (length < 4) { puts ("Password length must be at least 4 characters."); return -1; } i++; break;   case 'c': if (sscanf (argv[i+1], "%d", &count) != 1) { puts ("Unrecognized input. Syntax: -c [integer]"); return -1; }   if (count <= 0) { puts ("Count must be at least 1."); return -1; } i++; break;   case 's': if (sscanf (argv[i+1], "%d", &seed) != 1) { puts ("Unrecognized input. Syntax: -s [integer]"); return -1; } i++; break;   case 'e': exSymbols = 1; break;   default: help: printf ("Help:\nThis program generates a random password.\n" "Commands:" "Set password length: -l [integer]\n" "Set password count: -c [integer]\n" "Set seed: -s [integer]\n" "Exclude similiar characters: -e\n" "Display help: -h"); return 0; break; } }   srand (seed);   for (int i = 0; i < count; i++) GetPassword();   return 0; }  
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
#Racket
Racket
  #lang racket   ;; using a builtin (permutations '(A B C)) ;; -> '((A B C) (B A C) (A C B) (C A B) (B C A) (C B A))   ;; a random simple version (which is actually pretty good for a simple version) (define (perms l) (let loop ([l l] [tail '()]) (if (null? l) (list tail) (append-map (λ(x) (loop (remq x l) (cons x tail))) l)))) (perms '(A B C)) ;; -> '((C B A) (B C A) (C A B) (A C B) (B A C) (A B C))   ;; permutations in lexicographic order (define (lperms s) (cond [(empty? s) '()] [(empty? (cdr s)) (list s)] [else (let splice ([l '()][m (car s)][r (cdr s)]) (append (map (lambda (x) (cons m x)) (lperms (append l r))) (if (empty? r) '() (splice (append l (list m)) (car r) (cdr r)))))])) (display (lperms '(A B C))) ;; -> ((A B C) (A C B) (B A C) (B C A) (C A B) (C B A))   ;; permutations in lexicographical order using generators (require racket/generator) (define (splice s) (generator () (let outer-loop ([l '()][m (car s)][r (cdr s)]) (let ([permuter (lperm (append l r))]) (let inner-loop ([p (permuter)]) (when (not (void? p)) (let ([q (cons m p)]) (yield q) (inner-loop (permuter)))))) (if (not (empty? r)) (outer-loop (append l (list m)) (car r) (cdr r)) (void))))) (define (lperm s) (generator () (cond [(empty? s) (yield '())] [(empty? (cdr s)) (yield s)] [else (let ([splicer (splice s)]) (let loop ([q (splicer)]) (when (not (void? q)) (begin (yield q) (loop (splicer))))))]) (void))) (let ([permuter (lperm '(A B C))]) (let next-perm ([p (permuter)]) (when (not (void? p)) (begin (display p) (next-perm (permuter)))))) ;; -> (A B C)(A C B)(B A C)(B C A)(C A B)(C B 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.
#M2000_Interpreter
M2000 Interpreter
  Module Peano_curve { Cls 1, 0 Const Center=2 Report Center, "Peano curve" let factor=.9, k=3, wi=k^4 let wi2=min.data(scale.x*factor, scale.y*factor), n=wi2/wi let (dx, dy)=((scale.x-wi2)/2, (scale.y-wi2)/2) dx+=k*1.2*twipsX dy+=k*1.2*twipsY move dx, dy pen 11 { Peano(0,0,wi,0, 0) }   sub Peano(x, y, lg, i1, i2) if lg ==1 then draw to x*n+dx , y*n+dy return end if lg/=k 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 } Peano_curve  
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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Graphics[PeanoCurve[4]]
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).
#FreeBASIC
FreeBASIC
  Sub Jugador_elige(secuencia As String) Dim As String eleccion Dim As Byte valido, i Do valido = True Print !"\nIngresa una secuencia de 3 opciones, cada una de ellas H o T:"; Input " > ", secuencia If Len(secuencia) <> 3 Then valido = False If valido Then For i = 1 To 3 eleccion = Mid(Ucase(secuencia), i, 1) If eleccion <> "H" And eleccion <> "T" Then valido = False Next End If Loop Until valido End Sub   Function Aleatorio() As String Dim As Byte eleccion, i Dim As String tirada tirada = "" For i = 1 To 3 eleccion = Rnd And 1 If eleccion Then tirada += "H" Else tirada += "T" Next Return tirada End Function   Function Optima(secuencia As String) As String If Mid(secuencia, 2, 1) = "H" Then Optima = "T" + Left(secuencia, 2) Else Optima = "H" + Left(secuencia, 2) End If End Function   Randomize Timer Dim As String jugador, computador, otro Dim Shared As String secuencia Dim As Boolean ganador, valido Do Cls Color 11 Print "*** Penney's Game ***" & Chr(10) Color 7 Print "Cara eliges primero, cruz yo elijo primero." Print "Y es... "; Sleep 300 Dim As Double ht: ht = Rnd(0 - Timer) And 1 If ht Then Print "­cara!" Jugador_elige(jugador) computador = Optima(jugador) Print !"\nYo elijo "; computador; !".\n" Else Print "­cruz!" computador = Aleatorio Print !"\nYo elijo "; computador; !".\n" Jugador_elige(jugador) End If Print "Comenzando el juego ..." secuencia = "" ganador = False Do Sleep 200 Dim As Integer lanzar = Rnd And 1 If lanzar Then secuencia += "H" Print "H "; Else Print "T "; secuencia += "T" End If   If Right(secuencia, 3) = computador Then Print !"\n­Gan‚!\n" ganador = True Else If Right(secuencia, 3) = jugador Then Print !"\n­Felicidades! Ganaste.\n" ganador = True End If End If Loop Until ganador Do valido = False Input "¨Otra ronda? (S/N) ", otro If Instr("SYN", Ucase(otro)) Then valido = True Loop Until valido Loop Until Ucase(otro) = "N" Print !"\n­Gracias por jugar!" Sleep 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.
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   ' As FB's native types have only 64 bit precision at most we need to use the ' C library, GMP v6.1.0, for arbitrary precision arithmetic   #Include Once "gmp.bi" mpf_set_default_prec(640) '' 640 bit precision, enough for this exercise   Function v(n As UInteger, prev As __mpf_struct, prev2 As __mpf_struct) As __mpf_struct Dim As __mpf_struct a, b, c mpf_init(@a) : mpf_init(@b) : mpf_init(@c) If n = 0 Then mpf_set_ui(@a, 0UL) If n = 1 Then mpf_set_ui(@a, 2UL) If n = 2 Then mpf_set_si(@a, -4L) If n < 3 Then Return a mpf_ui_div(@a, 1130UL, @prev) mpf_mul(@b, @prev, @prev2) mpf_ui_div(@c, 3000UL, @b) mpf_ui_sub(@b, 111UL, @a) mpf_add(@a, @b, @c) mpf_clear(@b) mpf_clear(@c) Return a End Function   Function f(a As Double, b As Double) As __mpf_Struct Dim As __mpf_struct temp1, temp2, temp3, temp4, temp5, temp6, temp7, temp8 mpf_init(@temp1) : mpf_init(@temp2) : mpf_init(@temp3) : mpf_init(@temp4) mpf_init(@temp5) : mpf_init(@temp6) : mpf_init(@temp7) : mpf_init(@temp8) mpf_set_d(@temp1, a) '' a mpf_set_d(@temp2, b) '' b mpf_set_d(@temp3, 333.75) '' 333.75 mpf_pow_ui(@temp4, @temp2, 6UL) '' b ^ 6 mpf_mul(@temp3, @temp3, @temp4) '' 333.75 * b^6 mpf_pow_ui(@temp5, @temp1, 2UL) '' a^2 mpf_pow_ui(@temp6, @temp2, 2UL) '' b^2 mpf_mul_ui(@temp7, @temp5, 11UL) '' 11 * a^2 mpf_mul(@temp7, @temp7, @temp6) '' 11 * a^2 * b^2 mpf_sub(@temp7, @temp7, @temp4) '' 11 * a^2 * b^2 - b^6 mpf_pow_ui(@temp4, @temp2, 4UL) '' b^4 mpf_mul_ui(@temp4, @temp4, 121UL) '' 121 * b^4 mpf_sub(@temp7, @temp7, @temp4) '' 11 * a^2 * b^2 - b^6 - 121 * b^4 mpf_sub_ui(@temp7, @temp7, 2UL) '' 11 * a^2 * b^2 - b^6 - 121 * b^4 - 2 mpf_mul(@temp7, @temp7, @temp5) '' (11 * a^2 * b^2 - b^6 - 121 * b^4 - 2) * a^2 mpf_add(@temp3, @temp3, @temp7) '' 333.75 * b^6 + (11 * a^2 * b^2 - b^6 - 121 * b^4 - 2) * a^2 mpf_set_d(@temp4, 5.5) '' 5.5 mpf_pow_ui(@temp5, @temp2, 8UL) '' b^8 mpf_mul(@temp4, @temp4, @temp5) '' 5.5 * b^8 mpf_add(@temp3, @temp3, @temp4) '' 333.75 * b^6 + (11 * a^2 * b^2 - b^6 - 121 * b^4 - 2) * a^2 + 5.5 * b^8 mpf_mul_ui(@temp4, @temp2, 2UL) '' 2 * b mpf_div(@temp5, @temp1, @temp4) '' a / (2 * b) mpf_add(@temp3, @temp3, @temp5) '' 333.75 * b^6 + (11 * a^2 * b^2 - b^6 - 121 * b^4 - 2) * a^2 + 5.5 * b^8 + a / (2 * b) mpf_clear(@temp1) : mpf_clear(@temp2) : mpf_clear(@temp4) : mpf_clear(@temp5) mpf_clear(@temp6) : mpf_clear(@temp7) : mpf_clear(@temp8) Return temp3 End Function   Dim As Zstring * 60 z Dim As __mpf_struct result, prev, prev2 ' We cache the two previous results to avoid recursive calls to v For i As Integer = 1 To 100 result = v(i, prev, prev2) If (i >= 3 AndAlso i <= 8) OrElse i = 20 OrElse i = 30 OrElse i = 50 OrElse i = 100 Then gmp_sprintf(@z,"%53.50Ff",@result) '' express result to 50 decimal places Print "n ="; i , z End If prev2 = prev prev = result Next   mpf_clear(@prev) : mpf_clear(@prev2) '' note : prev = result   Dim As __mpf_struct e, balance, ii, temp mpf_init(@e) : mpf_init(@balance) : mpf_init(@ii) : mpf_init(@temp) mpf_set_str(@e, "2.71828182845904523536028747135266249775724709369995", 10) '' e to 50 decimal places mpf_sub_ui(@balance, @e, 1UL)   For i As ULong = 1 To 25 mpf_set_ui(@ii, i) mpf_mul(@temp, @balance, @ii) mpf_sub_ui(@balance, @temp, 1UL) Next   Print Print "Chaotic B/S balance after 25 years : "; gmp_sprintf(@z,"%.16Ff",@balance) '' express balance to 16 decimal places Print z mpf_clear(@e) : mpf_clear(@balance) : mpf_clear(@ii) : mpf_clear(@temp)   Print Dim rump As __mpf_struct rump = f(77617.0, 33096.0) gmp_sprintf(@z,"%.16Ff", @rump) '' express rump to 16 decimal places Print "f(77617.0, 33096.0) = "; z   Print Print "Press any key to quit" Sleep
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.
#Python
Python
import math   def solvePell(n): x = int(math.sqrt(n)) y, z, r = x, 1, x << 1 e1, e2 = 1, 0 f1, f2 = 0, 1 while True: y = r * z - y z = (n - y * y) // z r = (x + y) // z   e1, e2 = e2, e1 + e2 * r f1, f2 = f2, f1 + f2 * r   a, b = f2 * x + e2, f2 if a * a - n * b * b == 1: return a, b   for n in [61, 109, 181, 277]: x, y = solvePell(n) print("x^2 - %3d * y^2 = 1 for x = %27d and y = %25d" % (n, x, y))
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
#11l
11l
F partitions(n) V p = [BigInt(1)] [+] [BigInt(0)] * n L(i) 1 .. n V k = 0 L k++ V j = (k * (3 * k - 1)) I/ 2 I j > i L.break I k [&] 1 p[i] += p[i - j] E p[i] -= p[i - j] j = (k * (3 * k + 1)) I/ 2 I j > i L.break I k [&] 1 p[i] += p[i - j] E p[i] -= p[i - j] R p[n]   print(‘Partitions: ’(0.<15).map(x -> partitions(x)))   V start = time:perf_counter() print(partitions(6666)) print(time:perf_counter() - 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.
#ALGOL_68
ALGOL 68
MODE FIELD = REAL, VEC = [0]REAL, MAT = [0,0]REAL; MODE BRICK = UNION(INT, CHAR);   FLEX[][]BRICK puzzle = ( ( 151), ( " ", " "), ( 40, " ", " "), ( " ", " ", " ", " "), ( "x", 11, "y", 4, "z") );   PROC mat col = (INT row, col)INT: row*(row-1)OVER 2 + col; INT col x = mat col(5,1), col y = mat col(5,3), col z = mat col(5,5);   OP INIT = (REF VEC vec)VOID: FOR elem FROM LWB vec TO UPB vec DO vec[elem]:=0 OD; OP INIT = (REF MAT mat)VOID: FOR row FROM LWB mat TO UPB mat DO INIT mat[row,] OD;   OP / = (MAT a, MAT b)MAT:( # matrix division # [LWB b:UPB b]INT p ; INT sign; [,]FIELD lu = lu decomp(b, p, sign); [LWB a:UPB a, 1 LWB a:2 UPB a]FIELD out; FOR col FROM 2 LWB a TO 2 UPB a DO out[,col] := lu solve(b, lu, p, a[,col]) OD; out );   OP / = (VEC a, MAT b)VEC: ( # vector division # [LWB a:UPB a,1]FIELD transpose a; transpose a[,1]:=a; (transpose a/b)[,LWB a] );   INT upb mat = mat col(UPB puzzle, UPB puzzle); [upb mat, upb mat] REAL mat; INIT mat; [upb mat] REAL vec; INIT vec;   INT mat row := LWB mat; INT known row := UPB mat - UPB puzzle + 1;   # build the simultaneous equation to solve # FOR row FROM LWB puzzle TO UPB puzzle DO FOR col FROM LWB puzzle[row] TO UPB puzzle[row] DO IF row < UPB puzzle THEN mat[mat row, mat col(row, col)] := 1; mat[mat row, mat col(row+1, col)] := -1; mat[mat row, mat col(row+1, col+1)] := -1; mat row +:= 1 FI; CASE puzzle[row][col] IN (INT value):( mat[known row, mat col(row, col)] := 1; vec[known row] := value; known row +:= 1 ), (CHAR variable):SKIP ESAC OD OD;   # finally add x - y + z = 0 # mat[known row, col x] := 1; mat[known row, col y] := -1; mat[known row, col z] := 1;   FORMAT real repr = $g(-5,2)$;   CO # print details of the simultaneous equation being solved # FORMAT vec repr = $"("n(2 UPB mat-1)(f(real repr)", ")f(real repr)")"$, mat repr = $"("n(1 UPB mat-1)(f(vec repr)", "lx)f(vec repr)")"$;   printf(($"Vec: "l$,vec repr, vec, $l$)); printf(($"Mat: "l$,mat repr, mat, $l$)); END CO   # finally actually solve the equation # VEC solution vec = vec/mat;   # and wrap up by printing the solution # FLEX[UPB puzzle]FLEX[0]REAL solution; FOR row FROM LWB puzzle TO UPB puzzle DO solution[row] := LOC[row]REAL; FOR col FROM LWB puzzle[row] TO UPB puzzle[row] DO solution[row][col] := solution vec[mat col(row, col)] OD; printf(($n(UPB puzzle-row)(4x)$, $x"("f(real repr)")"$, solution[row], $l$)) OD;   FOR var FROM 1 BY 2 TO 5 DO printf(($5x$,$g$,puzzle[UPB puzzle][var],"=", real repr, solution[UPB puzzle][var])) OD
http://rosettacode.org/wiki/Particle_fountain
Particle fountain
Implement a particle fountain. Emulate a fountain of water droplets in a gravitational field being sprayed up and then falling back down. The particle fountain should be generally ordered but individually chaotic; the particles should be going mostly in the same direction, but should have slightly different vectors. Your fountain should have at least several hundred particles in motion at any one time, and ideally several thousand. It is optional to have the individual particle interact with each other. If at all possible, link to a short video clip of your fountain in action. Off-site link to a demo video
#Julia
Julia
using Dates, Colors, SimpleDirectMediaLayer.LibSDL2   mutable struct ParticleFountain particlenum::Int positions::Vector{Float64} velocities::Vector{Float64} lifetimes::Vector{Float64} points::Vector{SDL_Point} numpoints::Int saturation::Float64 spread::Float64 range::Float64 reciprocate::Bool ParticleFountain(N) = new(N, zeros(2N), zeros(2N), zeros(N), fill(SDL_Point(0, 0), N), 0, 0.4, 1.5, 1.5, false) end   function update(pf, w, h, df) xidx, yidx, pointidx = 1, 2, 0 recip() = pf.reciprocate ? pf.range * sin(Dates.value(now()) / 1000) : 0.0 for idx in 1:pf.particlenum willdraw = false if pf.lifetimes[idx] <= 0.0 if rand() < df pf.lifetimes[idx] = 2.5; # time to live pf.positions[xidx] = (w / 20) # starting position x pf.positions[yidx] = (h / 10) # and y pf.velocities[xidx] = 10 * (pf.spread * rand() - pf.spread / 2 + recip()) # starting velocity x pf.velocities[yidx] = (rand() - 2.9) * h / 20.5; # and y (randomized slightly so points reach different heights) willdraw = true end else if pf.positions[yidx] > h / 10 && pf.velocities[yidx] > 0 pf.velocities[yidx] *= -0.3 # "bounce" end pf.velocities[yidx] += df * h / 10 # adjust velocity pf.positions[xidx] += pf.velocities[xidx] * df # adjust position x pf.positions[yidx] += pf.velocities[yidx] * df # and y pf.lifetimes[idx] -= df willdraw = true end   if willdraw # gather all of the points that are going to be rendered pointidx += 1 pf.points[pointidx] = SDL_Point(Cint(floor(pf.positions[xidx] * 10)), Cint(floor(pf.positions[yidx] * 10))) end xidx += 2 yidx = xidx + 1 pf.numpoints = pointidx end return pf end   function fountain(particlenum = 3000, w = 800, h = 800) SDL_Init(SDL_INIT_VIDEO) window = SDL_CreateWindow("Julia Particle System!", SDL_WINDOWPOS_CENTERED_MASK, SDL_WINDOWPOS_CENTERED_MASK, w, h, SDL_WINDOW_RESIZABLE) renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED) SDL_ClearError() df = 0.0001 pf = ParticleFountain(3000) overallstart, close, frames = now(), false, 0 while !close dfstart = now() event_ref = Ref{SDL_Event}() while Bool(SDL_PollEvent(event_ref)) event_type = event_ref[].type evt = event_ref[] if event_type == SDL_QUIT close = true break end if event_type == SDL_WINDOWEVENT if evt.window.event == 5 w = evt.window.data1 h = evt.window.data2 end end if event_type == SDL_KEYDOWN comm = evt.key.keysym.scancode if comm == SDL_SCANCODE_UP saturation = min(pf.saturation + 0.1, 1.0) elseif comm == SDL_SCANCODE_DOWN saturation = max(pf.saturation - 0.1, 0.0) elseif comm == SDL_SCANCODE_PAGEUP spread = min(pf.spread + 1, 50.0) elseif comm == SDL_SCANCODE_PAGEDOWN spread = max(pf.spread - 0.1, 0.2) elseif comm == SDL_SCANCODE_LEFT range = min(pf.range + 0.1, 12.0) elseif comm == SDL_SCANCODE_RIGHT range = max(pf.range - 0.1, 0.1) elseif comm == SDL_SCANCODE_SPACE pf.reciprocate = !pf.reciprocate elseif comm == SDL_SCANCODE_Q close = true break end end end pf = update(pf, w, h, df) SDL_SetRenderDrawColor(renderer, 0x0, 0x0, 0x0, 0xff) SDL_RenderClear(renderer) rgb = parse(UInt32, hex(HSL((Dates.value(now()) % 5) * 72, pf.saturation, 0.5)), base=16) red, green, blue = rgb & 0xff, (rgb >> 8) & 0xff, (rgb >>16) & 0xff SDL_SetRenderDrawColor(renderer, red, green, blue, 0x7f) SDL_RenderDrawPoints(renderer, pf.points, pf.numpoints) SDL_RenderPresent(renderer) frames += 1 df = Float64(Dates.value(now()) - Dates.value(dfstart)) / 1000 elapsed = Float64(Dates.value(now()) - Dates.value(overallstart)) / 1000 elapsed > 0.5 && print("\r", ' '^20, "\rFPS: ", round(frames / elapsed, digits=1)) end SDL_Quit() end   println(""" Use UP and DOWN arrow keys to modify the saturation of the particle colors. Use PAGE UP and PAGE DOWN keys to modify the "spread" of the particles. Toggle reciprocation off / on with the SPACE bar. Use LEFT and RIGHT arrow keys to modify angle range for reciprocation. Press the "q" key to quit. """)   fountain()  
http://rosettacode.org/wiki/Particle_fountain
Particle fountain
Implement a particle fountain. Emulate a fountain of water droplets in a gravitational field being sprayed up and then falling back down. The particle fountain should be generally ordered but individually chaotic; the particles should be going mostly in the same direction, but should have slightly different vectors. Your fountain should have at least several hundred particles in motion at any one time, and ideally several thousand. It is optional to have the individual particle interact with each other. If at all possible, link to a short video clip of your fountain in action. Off-site link to a demo video
#Perl
Perl
#!/usr/bin/perl   use strict; # https://rosettacode.org/wiki/Particle_fountain use warnings; use Tk;   my $size = 900; my @particles; my $maxparticles = 500; my @colors = qw( red green blue yellow cyan magenta orange white );   my $mw = MainWindow->new; my $c = $mw->Canvas( -width => $size, -height => $size, -bg => 'black', )->pack; $mw->Button(-text => 'Exit', -command => sub {$mw->destroy}, )->pack(-fill => 'x');   step(); MainLoop; -M $0 < 0 and exec $0;   sub step { $c->delete('all'); $c->createLine($size / 2 - 10, $size, $size / 2, $size - 10, $size / 2 + 10, $size, -fill => 'white' ); for ( @particles ) { my ($ox, $oy, $vx, $vy, $color) = @$_; my $x = $ox + $vx; my $y = $oy + $vy; $c->createRectangle($ox, $oy, $x, $y, -fill => $color, -outline => $color); if( $y < $size ) { $_->[0] = $x; $_->[1] = $y; $_->[3] += 0.006; # gravity :) } else { $_ = undef } } @particles = grep defined, @particles; if( @particles < $maxparticles and --$| ) { push @particles, [ $size >> 1, $size - 10, (1 - rand 2) / 2.5 , -3 - rand 0.05, $colors[rand @colors] ]; } $mw->after(1 => \&step); }
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
#C.2B.2B
C++
#include <iostream> #include <vector>   enum class Piece { empty, black, white };   typedef std::pair<int, int> position;   bool isAttacking(const position &queen, const position &pos) { return queen.first == pos.first || queen.second == pos.second || abs(queen.first - pos.first) == abs(queen.second - pos.second); }   bool place(const int m, const int n, std::vector<position> &pBlackQueens, std::vector<position> &pWhiteQueens) { if (m == 0) { return true; } bool placingBlack = true; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { auto pos = std::make_pair(i, j); for (auto queen : pBlackQueens) { if (queen == pos || !placingBlack && isAttacking(queen, pos)) { goto inner; } } for (auto queen : pWhiteQueens) { if (queen == pos || placingBlack && isAttacking(queen, pos)) { goto inner; } } if (placingBlack) { pBlackQueens.push_back(pos); placingBlack = false; } else { pWhiteQueens.push_back(pos); if (place(m - 1, n, pBlackQueens, pWhiteQueens)) { return true; } pBlackQueens.pop_back(); pWhiteQueens.pop_back(); placingBlack = true; }   inner: {} } } if (!placingBlack) { pBlackQueens.pop_back(); } return false; }   void printBoard(int n, const std::vector<position> &blackQueens, const std::vector<position> &whiteQueens) { std::vector<Piece> board(n * n); std::fill(board.begin(), board.end(), Piece::empty);   for (auto &queen : blackQueens) { board[queen.first * n + queen.second] = Piece::black; } for (auto &queen : whiteQueens) { board[queen.first * n + queen.second] = Piece::white; }   for (size_t i = 0; i < board.size(); ++i) { if (i != 0 && i % n == 0) { std::cout << '\n'; } switch (board[i]) { case Piece::black: std::cout << "B "; break; case Piece::white: std::cout << "W "; break; case Piece::empty: default: int j = i / n; int k = i - j * n; if (j % 2 == k % 2) { std::cout << "x "; } else { std::cout << "* "; } break; } }   std::cout << "\n\n"; }   int main() { std::vector<position> 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 (auto nm : nms) { std::cout << nm.second << " black and " << nm.second << " white queens on a " << nm.first << " x " << nm.first << " board:\n"; std::vector<position> blackQueens, whiteQueens; if (place(nm.second, nm.first, blackQueens, whiteQueens)) { printBoard(nm.first, blackQueens, whiteQueens); } else { std::cout << "No solution exists.\n\n"; } }   return 0; }
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
#C.23
C#
using System; using System.Linq;   class Program { const string Lower = "abcdefghijklmnopqrstuvwxyz"; const string Upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; const string Digits = "0123456789"; const string Symbols = "!\"#$%&'()*+,-./:;<=>?@[]^_{|}~"; static readonly string[] Full = {Lower, Upper, Digits, Symbols, Lower + Upper + Digits + Symbols};   const string Similar = "Il1O05S2Z"; static readonly string[] Excluded = Full.Select(x => new string(x.Except(Similar).ToArray())).ToArray();   static Random _rng = new Random(); static string[] _symbolSet = Full;   static void Main(string[] args) { int length = 12, count = 1; try { foreach (var x in args.Select(arg => arg.Split(':'))) { switch (x[0]) { case "-l": length = int.Parse(x[1]); break; case "-c": count = int.Parse(x[1]); break; case "-s": _rng = new Random(x[1].GetHashCode()); break; case "-x": _symbolSet = bool.Parse(x[1]) ? Excluded : Full; break; default: throw new FormatException("Could not parse arguments"); } } } catch { ShowUsage(); return; } try { for (int i = 0; i < count; i++) Console.WriteLine(GeneratePass(length)); } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); } }   static void ShowUsage() { Console.WriteLine("Usage: PASSGEN [-l:length] [-c:count] [-s:seed] [-x:(true|false)]"); Console.WriteLine("\t-l: the length of the generated passwords"); Console.WriteLine("\t-c: the number of passwords to generate"); Console.WriteLine("\t-s: seed for the random number generator"); Console.WriteLine("\t-x: exclude similar characters: " + Similar); Console.WriteLine("Example: PASSGEN -l:10 -c:5 -s:\"Sample Seed\" -x:true"); }   static string GeneratePass(int length) { var minLength = _symbolSet.Length - 1; if(length < minLength) throw new Exception("password length must be " + minLength + " or greater");   int[] usesRemaining = Enumerable.Repeat(1, _symbolSet.Length).ToArray(); usesRemaining[minLength] = length - minLength; var password = new char[length]; for (int ii = 0; ii < length; ii++) { int set = _rng.Next(0, _symbolSet.Length); if (usesRemaining[set] > 0) { usesRemaining[set]--; password[ii] = _symbolSet[set][_rng.Next(0, _symbolSet[set].Length)]; } else ii--; } return new string(password); } }
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
#Raku
Raku
.say for <a b c>.permutations
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.
#Nim
Nim
import imageman   const Width = 81   proc peano(points: var seq[Point]; x, y, lg, i1, i2: int) =   if lg == 1: points.add ((Width - x) * 10, (Width - y) * 10) return   let lg = lg div 3 points.peano(x + 2 * i1 * lg, y + 2 * i1 * lg, lg, i1, i2) points.peano(x + (i1 - i2 + 1) * lg, y + (i1 + i2) * lg, lg, i1, 1 - i2) points.peano(x + lg, y + lg, lg, i1, 1 - i2) points.peano(x + (i1 + i2) * lg, y + (i1 - i2 + 1) * lg, lg, 1 - i1, 1 - i2) points.peano(x + 2 * i2 * lg, y + 2 * (1-i2) * lg, lg, i1, i2) points.peano(x + (1 + i2 - i1) * lg, y + (2 - i1 - i2) * lg, lg, i1, i2) points.peano(x + 2 * (1 - i1) * lg, y + 2 * (1 - i1) * lg, lg, i1, i2) points.peano(x + (2 - i1 - i2) * lg, y + (1 + i2 - i1) * lg, lg, 1 - i1, i2) points.peano(x + 2 * (1 - i2) * lg, y + 2 * i2 * lg, lg, 1 - i1, i2)     var points: seq[Point] points.peano(0, 0, Width, 0, 0) var image = initImage[ColorRGBU](820, 820) let color = ColorRGBU([byte 255, 255, 0]) for i in 1..points.high: image.drawLine(points[i - 1], points[i], color) image.savePNG("peano.png", compression = 9)
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.
#Perl
Perl
use SVG; use List::Util qw(max min);   use constant pi => 2 * atan2(1, 0);   # Compute the curve with a Lindemayer-system my %rules = ( L => 'LFRFL-F-RFLFR+F+LFRFL', R => 'RFLFR+F+LFRFL-F-RFLFR' ); my $peano = 'L'; $peano =~ s/([LR])/$rules{$1}/eg for 1..4;   # Draw the curve in SVG ($x, $y) = (0, 0); $theta = pi/2; $r = 4;   for (split //, $peano) { if (/F/) { push @X, sprintf "%.0f", $x; push @Y, sprintf "%.0f", $y; $x += $r * cos($theta); $y += $r * sin($theta); } elsif (/\+/) { $theta += pi/2; } elsif (/\-/) { $theta -= pi/2; } }   $max = max(@X,@Y); $xt = -min(@X)+10; $yt = -min(@Y)+10; $svg = SVG->new(width=>$max+20, height=>$max+20); $points = $svg->get_path(x=>\@X, y=>\@Y, -type=>'polyline'); $svg->rect(width=>"100%", height=>"100%", style=>{'fill'=>'black'}); $svg->polyline(%$points, style=>{'stroke'=>'orange', 'stroke-width'=>1}, transform=>"translate($xt,$yt)");   open $fh, '>', 'peano_curve.svg'; print $fh $svg->xmlify(-namespace=>'svg'); close $fh;
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).
#Go
Go
  package main import "fmt" import "math/rand" func main(){ var a1,a2,a3,y,match,j,k int var inp string y=1 for y==1{ fmt.Println("Enter your sequence:") fmt.Scanln(&inp) var Ai [3] int var user [3] int for j=0;j<3;j++{ if(inp[j]==104){ user[j]=1 }else{ user[j]=0 } } for k=0;k<3;k++{ Ai[k]=rand.Intn(2) } for user[0]==Ai[0]&&user[1]==Ai[1]&&user[2]==Ai[2]{ for k=0;k<3;k++{ Ai[k]=rand.Intn(2) } } fmt.Println("You gave the sequence:") printht(user) fmt.Println() fmt.Println("The computer generated sequence is:") printht(Ai) fmt.Println() a1=rand.Intn(2) a2=rand.Intn(2) a3=rand.Intn(2) fmt.Print("The generated sequence is:") printh(a1) printh(a2) printh(a3) match=0 for match==0{ if(matches(user,a1,a2,a3)==1){ fmt.Println() fmt.Println("You have won!!!") match=1 }else if(matches(Ai,a1,a2,a3)==1){ fmt.Println() fmt.Println("You lost!! Computer wins") match=1 }else{ a1=a2 a2=a3 a3=rand.Intn(2) printh(a3) } } fmt.Println("Do you want to continue(0/1):") fmt.Scanln(&y) } } func printht(a [3] int) int{ var i int for i=0;i<3;i++{ if(a[i]==1){ fmt.Print("h") }else{ fmt.Print("t") } } return 1 } func printh(a int) int{ if(a==1){ fmt.Print("h") }else{ fmt.Print("t") } return 1 } func matches(a [3] int,p int,q int,r int) int{ if(a[0]==p&&a[1]==q&&a[2]==r){ return 1 }else{ return 0 } }  
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.
#F.C5.8Drmul.C3.A6
Fōrmulæ
package main   import ( "fmt" "math/big" )   func main() { sequence() bank() rump() }   func sequence() { // exact computations using big.Rat var v, v1 big.Rat v1.SetInt64(2) v.SetInt64(-4) n := 2 c111 := big.NewRat(111, 1) c1130 := big.NewRat(1130, 1) c3000 := big.NewRat(3000, 1) var t2, t3 big.Rat r := func() (vn big.Rat) { vn.Add(vn.Sub(c111, t2.Quo(c1130, &v)), t3.Quo(c3000, t3.Mul(&v, &v1))) return } fmt.Println(" n sequence value") for _, x := range []int{3, 4, 5, 6, 7, 8, 20, 30, 50, 100} { for ; n < x; n++ { v1, v = v, r() } f, _ := v.Float64() fmt.Printf("%3d %19.16f\n", n, f) } }   func bank() { // balance as integer multiples of e and whole dollars using big.Int var balance struct{ e, d big.Int } // initial balance balance.e.SetInt64(1) balance.d.SetInt64(-1) // compute balance over 25 years var m, one big.Int one.SetInt64(1) for y := 1; y <= 25; y++ { m.SetInt64(int64(y)) balance.e.Mul(&m, &balance.e) balance.d.Mul(&m, &balance.d) balance.d.Sub(&balance.d, &one) } // sum account components using big.Float var e, ef, df, b big.Float e.SetPrec(100).SetString("2.71828182845904523536028747135") ef.SetInt(&balance.e) df.SetInt(&balance.d) b.Add(b.Mul(&e, &ef), &df) fmt.Printf("Bank balance after 25 years: $%.2f\n", &b) }   func rump() { a, b := 77617., 33096. fmt.Printf("Rump f(%g, %g): %g\n", a, b, f(a, b)) }   func f(a, b float64) float64 { // computations done with big.Float with enough precision to give // a correct answer. fp := func(x float64) *big.Float { return big.NewFloat(x).SetPrec(128) } a1 := fp(a) b1 := fp(b) a2 := new(big.Float).Mul(a1, a1) b2 := new(big.Float).Mul(b1, b1) b4 := new(big.Float).Mul(b2, b2) b6 := new(big.Float).Mul(b2, b4) b8 := new(big.Float).Mul(b4, b4) two := fp(2) t1 := fp(333.75) t1.Mul(t1, b6) t21 := fp(11) t21.Mul(t21.Mul(t21, a2), b2) t23 := fp(121) t23.Mul(t23, b4) t2 := new(big.Float).Sub(t21, b6) t2.Mul(a2, t2.Sub(t2.Sub(t2, t23), two)) t3 := fp(5.5) t3.Mul(t3, b8) t4 := new(big.Float).Mul(two, b1) t4.Quo(a1, t4) s := new(big.Float).Add(t1, t2) f64, _ := s.Add(s.Add(s, t3), t4).Float64() return f64 }
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.
#Raku
Raku
use Lingua::EN::Numbers;   sub pell (Int $n) {   my $y = my $x = Int(sqrt $n); my $z = 1; my $r = 2 * $x;   my ($e1, $e2) = (1, 0); my ($f1, $f2) = (0, 1);   loop { $y = $r * $z - $y; $z = Int(($n - $y²) / $z); $r = Int(($x + $y) / $z);   ($e1, $e2) = ($e2, $r * $e2 + $e1); ($f1, $f2) = ($f2, $r * $f2 + $f1);   my $A = $e2 + $x * $f2; my $B = $f2;   if ($A² - $n * $B² == 1) { return ($A, $B); } } }   for 61, 109, 181, 277, 8941 -> $n { next if $n.sqrt.narrow ~~ Int; my ($x, $y) = pell($n); printf "x² - %sy² = 1 for:\n\tx = %s\n\ty = %s\n\n", $n, |($x, $y)».&comma; }
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
#C
C
#include <stdint.h> #include <stdlib.h> #include <stdio.h> #include <time.h> #include <gmp.h>   mpz_t* partition(uint64_t n) { mpz_t *pn = (mpz_t *)malloc((n + 2) * sizeof(mpz_t)); mpz_init_set_ui(pn[0], 1); mpz_init_set_ui(pn[1], 1); for (uint64_t i = 2; i < n + 2; i ++) { mpz_init(pn[i]); for (uint64_t k = 1, penta; ; k++) { penta = k * (3 * k - 1) >> 1; if (penta >= i) break; if (k & 1) mpz_add(pn[i], pn[i], pn[i - penta]); else mpz_sub(pn[i], pn[i], pn[i - penta]); penta += k; if (penta >= i) break; if (k & 1) mpz_add(pn[i], pn[i], pn[i - penta]); else mpz_sub(pn[i], pn[i], pn[i - penta]); } } mpz_t *tmp = &pn[n + 1]; for (uint64_t i = 0; i < n + 1; i ++) mpz_clear(pn[i]); free(pn); return tmp; }   int main(int argc, char const *argv[]) { clock_t start = clock(); mpz_t *p = partition(6666); gmp_printf("%Zd\n", p); printf("Elapsed time: %.04f seconds\n", (double)(clock() - start) / (double)CLOCKS_PER_SEC); return 0; }
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.
#AutoHotkey
AutoHotkey
N1 := 11, N2 := 4, N3 := 40, N4 := 151 Z := (2*N4 - 7*N3 - 8*N2 + 6*N1) / 7 X := (N3 - 2*N1 - Z) / 2 MsgBox,, Pascal's Triangle, %X%`n%Z%
http://rosettacode.org/wiki/Particle_fountain
Particle fountain
Implement a particle fountain. Emulate a fountain of water droplets in a gravitational field being sprayed up and then falling back down. The particle fountain should be generally ordered but individually chaotic; the particles should be going mostly in the same direction, but should have slightly different vectors. Your fountain should have at least several hundred particles in motion at any one time, and ideally several thousand. It is optional to have the individual particle interact with each other. If at all possible, link to a short video clip of your fountain in action. Off-site link to a demo video
#Phix
Phix
-- -- demo\rosetta\Particle_fountain.exw -- ================================== -- with javascript_semantics include pGUI.e Ihandle dlg, canvas cdCanvas cddbuffer, cdcanvas constant title = "Particle fountain" constant help_text = """ Uparrow increases the saturation of the particle colors, downarrow decreases saturation until they all become white. PageUp sprays the particles out at a wider angle/spread, PageDown makes the jet narrower. Space toggles reciprocation (wobble) on and off (straight up). Left arrow decreases the angle range for reciprocation, right arrow increases the angle range for reciprocation. Press the "q" key to quit. """ constant particlenum = 3000 -- each particle is {x,y,color,life,dx,dy} sequence particles = repeat({0,0,0,0,0,0},particlenum) atom t1 = time()+1 integer fps = 0 bool reciprocate = true atom range = 1.5, spread = 1.5, saturation = 0.4, start = time(), df = 0.0001 function redraw_cb(Ihandle /*ih*/, integer /*posx*/, /*posy*/) integer {w, h} = IupGetIntInt(canvas, "DRAWSIZE") cdCanvasActivate(cddbuffer) cdCanvasClear(cddbuffer) for i=1 to length(particles) do atom {x,y,color,life} = particles[i] if life>0 then cdCanvasPixel(cddbuffer, x, h/10-y, color) end if end for cdCanvasFlush(cddbuffer) return IUP_DEFAULT end function function map_cb(Ihandle ih) cdcanvas = cdCreateCanvas(CD_IUP, ih) cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas) cdCanvasSetBackground(cddbuffer, CD_BLACK) return IUP_DEFAULT end function function timer_cb(Ihandle /*ih*/) integer {w, h} = IupGetIntInt(canvas, "DRAWSIZE") fps += 1 df = time()-start start = time() for i=1 to particlenum do atom {x,y,color,life,dx,dy} = particles[i] if life<=0 then if rnd()<df then life = 2.5 -- time to live x = w/2 -- starting position x y = h/10 -- and y -- randomize velocity so points reach different heights: atom r = iff(reciprocate?range*sin(time()):0) dx = (spread*rnd()-spread/2+r)*50 -- starting velocity x dy = (rnd()-2.9) * h/20.5 -- and y color = hsv_to_rgb(round(remainder(time(),5)/5,100), saturation, 1) end if else if y>h/10 and dy>0 then dy *= -0.3 -- "bounce" end if dy += (h/10)*df -- adjust velocity x += dx*df -- adjust position x y += dy*df*8 -- and y life -= df end if particles[i] = {x,y,color,life,dx,dy} end for IupRedraw(canvas) if time()>t1 then IupSetStrAttribute(dlg,"TITLE","%s (%d, %d fps/s [%dx%d])",{title,particlenum,fps,w,h}) t1 = time()+1 fps = 0 end if return IUP_DEFAULT end function function key_cb(Ihandle /*dlg*/, atom c) if c=K_ESC or lower(c)='q' then return IUP_CLOSE elsif c=K_F1 then IupMessage(title,help_text) elsif c=K_UP then saturation = min(saturation+0.1,1) elsif c=K_DOWN then saturation = max(saturation-0.1,0) elsif c=K_PGUP then spread = min(spread+0.1,5) elsif c=K_PGDN then spread = max(spread-0.1,0.2) elsif c=K_RIGHT then range = min(range+0.1,2) elsif c=K_LEFT then range = max(range-0.1,0.1) elsif c=K_SP then reciprocate = not reciprocate end if return IUP_CONTINUE end function procedure main() IupOpen() canvas = IupGLCanvas("RASTERSIZE=400x300") IupSetCallbacks({canvas}, {"ACTION", Icallback("redraw_cb"), "MAP_CB", Icallback("map_cb")}) dlg = IupDialog(canvas,`TITLE="%s"`,{title}) IupSetCallback(dlg, "KEY_CB", Icallback("key_cb")) Ihandle timer = IupTimer(Icallback("timer_cb"), 1000/25) IupShowXY(dlg,IUP_CENTER,IUP_CENTER) IupSetAttribute(canvas, "RASTERSIZE", NULL) if platform()!=JS then IupMainLoop() IupClose() end if end procedure main()
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
#D
D
import std.array; import std.math; import std.stdio; import std.typecons;   enum Piece { empty, black, white, }   alias position = Tuple!(int, "i", int, "j");   bool place(int m, int n, ref position[] pBlackQueens, ref position[] pWhiteQueens) { if (m == 0) { return true; } bool placingBlack = true; foreach (i; 0..n) { inner: foreach (j; 0..n) { auto pos = position(i, j); foreach (queen; pBlackQueens) { if (queen == pos || !placingBlack && isAttacking(queen, pos)) { continue inner; } } foreach (queen; pWhiteQueens) { if (queen == pos || placingBlack && isAttacking(queen, pos)) { continue inner; } } if (placingBlack) { pBlackQueens ~= pos; placingBlack = false; } else { pWhiteQueens ~= pos; if (place(m - 1, n, pBlackQueens, pWhiteQueens)) { return true; } pBlackQueens.length--; pWhiteQueens.length--; placingBlack = true; } } } if (!placingBlack) { pBlackQueens.length--; } return false; }   bool isAttacking(position queen, position pos) { return queen.i == pos.i || queen.j == pos.j || abs(queen.i - pos.i) == abs(queen.j - pos.j); }   void printBoard(int n, position[] blackQueens, position[] whiteQueens) { auto board = uninitializedArray!(Piece[])(n * n); board[] = Piece.empty;   foreach (queen; blackQueens) { board[queen.i * n + queen.j] = Piece.black; } foreach (queen; whiteQueens) { board[queen.i * n + queen.j] = Piece.white; } foreach (i,b; board) { if (i != 0 && i % n == 0) { writeln; } final switch (b) { case Piece.black: write("B "); break; case Piece.white: write("W "); break; case Piece.empty: int j = i / n; int k = i - j * n;   if (j % 2 == k % 2) { write("• "w); } else { write("◦ "w); } break; } } writeln('\n'); }   void main() { auto 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], ]; foreach (nm; nms) { writefln("%d black and %d white queens on a %d x %d board:", nm[1], nm[1], nm[0], nm[0]); position[] blackQueens; position[] whiteQueens; if (place(nm[1], nm[0], blackQueens, whiteQueens)) { printBoard(nm[0], blackQueens, whiteQueens); } else { writeln("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
#C.2B.2B
C++
#include <iostream> #include <string> #include <algorithm> #include <ctime>   const std::string CHR[] = { "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz", "0123456789", "!\"#$%&'()*+,-./:;<=>?@[]^_{|}~" }; const std::string UNS = "O0l1I5S2Z";   std::string createPW( int len, bool safe ) { std::string pw; char t; for( int x = 0; x < len; x += 4 ) { for( int y = x; y < x + 4 && y < len; y++ ) { do { t = CHR[y % 4].at( rand() % CHR[y % 4].size() ); } while( safe && UNS.find( t ) != UNS.npos ); pw.append( 1, t ); } } std::random_shuffle( pw.begin(), pw.end() ); return pw; } void generate( int len, int count, bool safe ) { for( int c = 0; c < count; c++ ) { std::cout << createPW( len, safe ) << "\n"; } std::cout << "\n\n"; } int main( int argc, char* argv[] ){ if( argv[1][1] == '?' || argc < 5 ) { std::cout << "Syntax: PWGEN length count safe seed /?\n" "length:\tthe length of the password(min 4)\n" "count:\thow many passwords should be generated\n" "safe:\t1 will exclude visually similar characters, 0 won't\n" "seed:\tnumber to seed the random generator or 0\n" "/?\tthis text\n\n"; } else { int l = atoi( argv[1] ), c = atoi( argv[2] ), e = atoi( argv[3] ), s = atoi( argv[4] ); if( l < 4 ) { std::cout << "Passwords must be at least 4 characters long.\n\n"; } else { if (s == 0) { std::srand( time( NULL ) ); } else { std::srand( unsigned( s ) ); } generate( l, c, e != 0 ); } } return 0; }
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
#RATFOR
RATFOR
# Heap’s algorithm for generating permutations. Algorithm 2 in # Robert Sedgewick, 1977. Permutation generation methods. ACM # Comput. Surv. 9, 2 (June 1977), 137-164.   define(n, 3) define(n_minus_1, 2)   implicit none   integer a(1:n)   integer c(1:n) integer i, k integer tmp   10000 format ('(', I1, n_minus_1(' ', I1), ')')   # Initialize the data to be permuted. do i = 1, n { a(i) = i }   # What follows is a non-recursive Heap’s algorithm as presented by # Sedgewick. Sedgewick neglects to fully initialize c, so I have # corrected for that. Also I compute k without branching, by instead # doing a little arithmetic. do i = 1, n { c(i) = 1 } i = 2 write (*, 10000) a while (i <= n) { if (c(i) < i) { k = mod (i, 2) + ((1 - mod (i, 2)) * c(i)) tmp = a(i) a(i) = a(k) a(k) = tmp c(i) = c(i) + 1 i = 2 write (*, 10000) a } else { c(i) = 1 i = i + 1 } }   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.
#Phix
Phix
-- -- demo\rosetta\peano_curve.exw -- ============================ -- -- Draws a peano curve. Space key toggles between switchback and meander curves. -- with javascript_semantics include pGUI.e Ihandle dlg, canvas cdCanvas cddbuffer, cdcanvas bool meander = false -- space toggles (false==draw switchback curve) constant width = 81 sequence points = {} -- switchback peano: -- -- There are (as per wp) four shapes to draw: -- -- 1: +-v ^ 2: ^ v-+ 3: v ^-+ 2: +-^ v -- | | | | | | | | | | | | -- ^ v-+ +-v ^ +-^ v v ^-+ -- -- 1 starts bottom left, ends top right -- 2 starts bottom right, ends top left -- 3 starts top left, ends bottom right -- 4 starts top right, ends bottom left -- -- given the centre point (think {1,1}), and using {0,0} as the bottom left: -- constant shapes = {{{-1,-1},{-1,0},{-1,+1},{0,+1},{0,0},{0,-1},{+1,-1},{+1,0},{+1,+1}}, {{+1,-1},{+1,0},{+1,+1},{0,+1},{0,0},{0,-1},{-1,-1},{-1,0},{-1,+1}}, -- (== sq_mul(shapes[1],{-1,0})) {{-1,+1},{-1,0},{-1,-1},{0,-1},{0,0},{0,+1},{+1,+1},{+1,0},{+1,-1}}, -- (== reverse(shapes[2])) {{+1,+1},{+1,0},{+1,-1},{0,-1},{0,0},{0,+1},{-1,+1},{-1,0},{-1,-1}}} -- (== reverse(shapes[1])) constant subshapes = {{1,2,1,3,4,3,1,2,1}, {2,1,2,4,3,4,2,1,2}, -- == sq_sub({3,3,3,7,7,7,3,3,3},subshapes[1]) {3,4,3,1,2,1,3,4,3}, -- == sq_sub(5,subshapes[2]) {4,3,4,2,1,2,4,3,4}} -- == sq_sub(5,subshapes[1]) -- As noted, it should theoretically be possible to simplify/shorten/remove/inline those tables procedure switchback_peano(integer x, y, level, shape) -- (written from scratch, with a nod to the meander algorithm [below]) if level<=1 then points = append(points, {x*10, y*10}) return end if level /= 3 for i=1 to 9 do integer {dx,dy} = shapes[shape][i] switchback_peano(x+dx*level,y+dy*level,level,subshapes[shape][i]) end for end procedure procedure meander_peano(integer x, y, lg, i1, i2) -- (translated from Go) if lg=1 then integer px := (width-x) * 10, py := (width-y) * 10 points = append(points, {px, py}) return end if lg /= 3 meander_peano(x+2*i1*lg, y+2*i1*lg, lg, i1, i2) meander_peano(x+(i1-i2+1)*lg, y+(i1+i2)*lg, lg, i1, 1-i2) meander_peano(x+lg, y+lg, lg, i1, 1-i2) meander_peano(x+(i1+i2)*lg, y+(i1-i2+1)*lg, lg, 1-i1, 1-i2) meander_peano(x+2*i2*lg, y+2*(1-i2)*lg, lg, i1, i2) meander_peano(x+(1+i2-i1)*lg, y+(2-i1-i2)*lg, lg, i1, i2) meander_peano(x+2*(1-i1)*lg, y+2*(1-i1)*lg, lg, i1, i2) meander_peano(x+(2-i1-i2)*lg, y+(1+i2-i1)*lg, lg, 1-i1, i2) meander_peano(x+2*(1-i2)*lg, y+2*i2*lg, lg, 1-i1, i2) end procedure function redraw_cb(Ihandle /*ih*/, integer /*posx*/, /*posy*/) if length(points)=0 then if meander then meander_peano(0, 0, width, 0, 0) else switchback_peano(41, 41, width, 1) end if end if cdCanvasActivate(cddbuffer) cdCanvasBegin(cddbuffer, CD_OPEN_LINES) for i=1 to length(points) do integer {x,y} = points[i] cdCanvasVertex(cddbuffer, x, y) end for cdCanvasEnd(cddbuffer) cdCanvasFlush(cddbuffer) return IUP_DEFAULT end function function map_cb(Ihandle ih) cdcanvas = cdCreateCanvas(CD_IUP, ih) cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas) cdCanvasSetBackground(cddbuffer, CD_WHITE) cdCanvasSetForeground(cddbuffer, CD_MAGENTA) return IUP_DEFAULT end function function key_cb(Ihandle /*ih*/, atom c) if c=K_ESC then return IUP_CLOSE end if if c=' ' then meander = not meander points = {} cdCanvasClear(cddbuffer) IupUpdate(canvas) end if return IUP_CONTINUE end function procedure main() IupOpen() canvas = IupCanvas("RASTERSIZE=822x822") IupSetCallbacks(canvas, {"MAP_CB", Icallback("map_cb"), "ACTION", Icallback("redraw_cb")}) dlg = IupDialog(canvas,`TITLE="Peano Curve"`) IupSetAttribute(dlg, "DIALOGFRAME", "YES") -- no resize here IupSetCallback(dlg, "KEY_CB", Icallback("key_cb")) IupShow(dlg) if platform()!=JS then IupMainLoop() IupClose() end if 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).
#Haskell
Haskell
import qualified Data.List as L import System.IO import System.Random   data CoinToss = H | T deriving (Read, Show, Eq)   parseToss :: String -> [CoinToss] parseToss [] = [] parseToss (s:sx) | s == 'h' || s == 'H' = H : parseToss sx | s == 't' || s == 'T' = T : parseToss sx | otherwise = parseToss sx   notToss :: CoinToss -> CoinToss notToss H = T notToss T = H   instance Random CoinToss where random g = let (b, gb) = random g in (if b then H else T, gb) randomR = undefined   prompt :: (Read a) => String -> String -> (String -> Maybe a) -> IO a prompt msg err parse = do putStrLn msg line <- getLine let ans = parse line case ans of Nothing -> do putStrLn err prompt msg err parse Just ansB -> return ansB   showCat :: (Show a) => [a] -> String showCat = concatMap show   data Winner = Player | CPU   -- This may never terminate. runToss :: (RandomGen g) => [CoinToss] -> [CoinToss] -> g -> ([CoinToss], Winner) runToss player cpu gen = let stream = randoms gen run ss@(s:sx) | L.isPrefixOf player ss = player | L.isPrefixOf cpu ss = cpu | otherwise = s : run sx winner = run stream in if L.isSuffixOf player winner then (winner, Player) else (winner, CPU)   game :: (RandomGen g, Num a, Show a) => Bool -> a -> a -> g -> IO () game cpuTurn playerScore cpuScore gen = do putStrLn $ "\nThe current score is CPU: " ++ show cpuScore ++ ", You: " ++ show playerScore   let (genA, genB) = split gen promptPlayer check = prompt "Pick 3 coin sides: " "Invalid input." $ \s -> let tosses = parseToss s in if check tosses then Just tosses else Nothing promptCpu x = putStrLn $ "I have chosen: " ++ showCat x   (tosses, winner) <- if cpuTurn then do let cpuChoice = take 3 $ randoms gen promptCpu cpuChoice playerChoice <- promptPlayer $ \n -> n /= cpuChoice && 3 == length n return $ runToss playerChoice cpuChoice genA else do playerChoice <- promptPlayer $ \n -> 3 == length n let cpuChoice = case playerChoice of [a,b,_] -> [notToss b, a, b] promptCpu cpuChoice return $ runToss playerChoice cpuChoice genA   putStrLn $ "The sequence tossed was: " ++ showCat tosses   case winner of Player -> do putStrLn "You win!" game (not cpuTurn) (playerScore + 1) cpuScore genB CPU -> do putStrLn "I win!" game (not cpuTurn) playerScore (cpuScore + 1) genB   main :: IO () main = do hSetBuffering stdin LineBuffering stdgen <- getStdGen let (cpuFirst, genA) = random stdgen game cpuFirst 0 0 genA
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.
#Go
Go
package main   import ( "fmt" "math/big" )   func main() { sequence() bank() rump() }   func sequence() { // exact computations using big.Rat var v, v1 big.Rat v1.SetInt64(2) v.SetInt64(-4) n := 2 c111 := big.NewRat(111, 1) c1130 := big.NewRat(1130, 1) c3000 := big.NewRat(3000, 1) var t2, t3 big.Rat r := func() (vn big.Rat) { vn.Add(vn.Sub(c111, t2.Quo(c1130, &v)), t3.Quo(c3000, t3.Mul(&v, &v1))) return } fmt.Println(" n sequence value") for _, x := range []int{3, 4, 5, 6, 7, 8, 20, 30, 50, 100} { for ; n < x; n++ { v1, v = v, r() } f, _ := v.Float64() fmt.Printf("%3d %19.16f\n", n, f) } }   func bank() { // balance as integer multiples of e and whole dollars using big.Int var balance struct{ e, d big.Int } // initial balance balance.e.SetInt64(1) balance.d.SetInt64(-1) // compute balance over 25 years var m, one big.Int one.SetInt64(1) for y := 1; y <= 25; y++ { m.SetInt64(int64(y)) balance.e.Mul(&m, &balance.e) balance.d.Mul(&m, &balance.d) balance.d.Sub(&balance.d, &one) } // sum account components using big.Float var e, ef, df, b big.Float e.SetPrec(100).SetString("2.71828182845904523536028747135") ef.SetInt(&balance.e) df.SetInt(&balance.d) b.Add(b.Mul(&e, &ef), &df) fmt.Printf("Bank balance after 25 years: $%.2f\n", &b) }   func rump() { a, b := 77617., 33096. fmt.Printf("Rump f(%g, %g): %g\n", a, b, f(a, b)) }   func f(a, b float64) float64 { // computations done with big.Float with enough precision to give // a correct answer. fp := func(x float64) *big.Float { return big.NewFloat(x).SetPrec(128) } a1 := fp(a) b1 := fp(b) a2 := new(big.Float).Mul(a1, a1) b2 := new(big.Float).Mul(b1, b1) b4 := new(big.Float).Mul(b2, b2) b6 := new(big.Float).Mul(b2, b4) b8 := new(big.Float).Mul(b4, b4) two := fp(2) t1 := fp(333.75) t1.Mul(t1, b6) t21 := fp(11) t21.Mul(t21.Mul(t21, a2), b2) t23 := fp(121) t23.Mul(t23, b4) t2 := new(big.Float).Sub(t21, b6) t2.Mul(a2, t2.Sub(t2.Sub(t2, t23), two)) t3 := fp(5.5) t3.Mul(t3, b8) t4 := new(big.Float).Mul(two, b1) t4.Quo(a1, t4) s := new(big.Float).Add(t1, t2) f64, _ := s.Add(s.Add(s, t3), t4).Float64() return f64 }
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.
#REXX
REXX
/*REXX program to solve Pell's equation for the smallest solution of positive integers. */ numeric digits 2200 /*ensure enough decimal digs for answer*/ parse arg $ /*obtain optional arguments from the CL*/ if $=='' | $=="," then $= 61 109 181 277 /*Not specified? Then use the defaults*/ d= 28 /*used for aligning the output numbers.*/ do j=1 for words($); #= word($, j) /*process all the numbers in the list. */ parse value pells(#) with x y /*extract the two values of X and Y.*/ cx= comma(x); Lcx= length(cx); cy= comma(y); Lcy= length(cy) say 'x^2 -'right(#, max(4, length(#))) "* y^2 == 1" , ' when x='right(cx, max(d, Lcx)) " and y="right(cy, max(d, Lcy)) end /*j*/ exit 0 /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ comma: parse arg ?; do jc=length(?)-3 to 1 by -3; ?= insert(',', ?, jc); end; return ? floor: procedure; parse arg x; _= x % 1; return _ - (x < 0) * (x \= _) /*──────────────────────────────────────────────────────────────────────────────────────*/ iSqrt: procedure; parse arg x; r= 0; q= 1; do while q<=x; q= q * 4; end do while q>1; q= q%4; _= x-r-q; r= r%2; if _>=0 then do; x= _; r= r+q; end; end return r /*R: is the integer square root of X. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ pells: procedure; parse arg n; x= iSqrt(n); y=x /*obtain arg; obtain integer sqrt of N*/ parse value 1 0 with e1 e2 1 f2 f1 /*assign values for: E1, E2, and F2, F1*/ z= 1; r= x + x do until ( (e2 + x*f2)**2 - n*f2*f2) == 1 y= r*z - y; z= floor( (n - y*y) / z) r= floor( (x + y ) / z) parse value e2 r*e2 + e1 with e1 e2 parse value f2 r*f2 + f1 with f1 f2 end /*until*/ return e2 + x * f2 f2
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
#11l
11l
F is_prime(a) R !(a < 2 | any((2 .. Int(a ^ 0.5)).map(x -> @a % x == 0)))   F generate_primes(n) V r = [2] V i = 3 L I is_prime(i) r.append(i) I r.len == n L.break i += 2 R r   V primes = generate_primes(50'000)   F find_combo(k, x, m, n, &combo) I k >= m I sum(combo.map(idx -> :primes[idx])) == x print(‘Partitioned #5 with #2 #.: ’.format(x, m, I m > 1 {‘primes’} E ‘prime ’), end' ‘’) L(i) 0 .< m print(:primes[combo[i]], end' I i < m - 1 {‘+’} E "\n") R 1B E L(j) 0 .< n I k == 0 | j > combo[k - 1] combo[k] = j I find_combo(k + 1, x, m, n, &combo) R 1B R 0B   F partition(x, m) V n = :primes.filter(a -> a <= @x).len V combo = [0] * m I !find_combo(0, x, m, n, &combo) print(‘Partitioned #5 with #2 #.: (not possible)’.format(x, m, I m > 1 {‘primes’} E ‘prime ’))   V data = [(99809, 1), (18, 2), (19, 3), (20, 4), (2017, 24), (22699, 1), (22699, 2), (22699, 3), (22699, 4), (40355, 3)]   L(n, cnt) data partition(n, cnt)
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
#C.2B.2B
C++
#include <chrono> #include <iostream> #include <vector> #include <gmpxx.h>   using big_int = mpz_class;   big_int partitions(int n) { std::vector<big_int> p(n + 1); p[0] = 1; for (int i = 1; i <= n; ++i) { for (int k = 1;; ++k) { int j = (k * (3*k - 1))/2; if (j > i) break; if (k & 1) p[i] += p[i - j]; else p[i] -= p[i - j]; j = (k * (3*k + 1))/2; if (j > i) break; if (k & 1) p[i] += p[i - j]; else p[i] -= p[i - j]; } } return p[n]; }   int main() { auto start = std::chrono::steady_clock::now(); auto result = partitions(6666); auto end = std::chrono::steady_clock::now(); std::chrono::duration<double, std::milli> ms(end - start); std::cout << result << '\n'; std::cout << "elapsed time: " << ms.count() << " milliseconds\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.
#BBC_BASIC
BBC BASIC
INSTALL @lib$ + "ARRAYLIB"   REM Describe the puzzle as a set of simultaneous equations: REM a + b = 151 REM a - c = 40 REM -b + c + d = 0 REM e + f = 40 REM -c + f + g = 0 REM -d + g + h = 0 REM e - x = 11 REM f - y = 11 REM g - y = 4 REM h - z = 4 REM x - y + z = 0 REM So we have 11 equations in 11 unknowns.   REM We can represent these equations as a matrix and a vector: DIM matrix(10,10), vector(10) matrix() = \ a, b, c, d, e, f, g, h, x, y, z \ 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 vector() = 151, 40, 0, 40, 0, 0, 11, 11, 4, 4, 0   REM Now solve the simultaneous equations: PROC_invert(matrix()) vector() = matrix().vector()   PRINT "X = " ; vector(8) PRINT "Y = " ; vector(9) PRINT "Z = " ; vector(10)
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.
#C
C
  /* Pascal's pyramid solver * * [top] * [ ] [ ] * [mid] [ ] [ ] * [ ] [ ] [ ] [ ] * [ x ] [ a ] [ y ] [ b ] [ z ] * x + z = y * * This solution makes use of a little bit of mathematical observation, * such as the fact that top = 4(a+b) + 7(x+z) and mid = 2x + 2a + z. */   #include <stdio.h> #include <math.h>   void pascal(int a, int b, int mid, int top, int* x, int* y, int* z) { double ytemp = (top - 4 * (a + b)) / 7.; if(fmod(ytemp, 1.) >= 0.0001) { x = 0; return; } *y = ytemp; *x = mid - 2 * a - *y; *z = *y - *x; } int main() { int a = 11, b = 4, mid = 40, top = 151; int x, y, z; pascal(a, b, mid, top, &x, &y, &z); if(x != 0) printf("x: %d, y: %d, z: %d\n", x, y, z); else printf("No solution\n");   return 0; }  
http://rosettacode.org/wiki/Particle_fountain
Particle fountain
Implement a particle fountain. Emulate a fountain of water droplets in a gravitational field being sprayed up and then falling back down. The particle fountain should be generally ordered but individually chaotic; the particles should be going mostly in the same direction, but should have slightly different vectors. Your fountain should have at least several hundred particles in motion at any one time, and ideally several thousand. It is optional to have the individual particle interact with each other. If at all possible, link to a short video clip of your fountain in action. Off-site link to a demo video
#Raku
Raku
use NativeCall; use SDL2::Raw;   my int ($w, $h) = 800, 800; my SDL_Window $window; my SDL_Renderer $renderer;   my int $particlenum = 3000;     SDL_Init(VIDEO); $window = SDL_CreateWindow( "Raku Particle System!", SDL_WINDOWPOS_CENTERED_MASK, SDL_WINDOWPOS_CENTERED_MASK, $w, $h, RESIZABLE ); $renderer = SDL_CreateRenderer( $window, -1, ACCELERATED );   SDL_ClearError();   my num @positions = 0e0 xx ($particlenum * 2); my num @velocities = 0e0 xx ($particlenum * 2); my num @lifetimes = 0e0 xx $particlenum;   my CArray[int32] $points .= new; my int $numpoints; my Num $saturation = 4e-1; my Num $spread = 15e-1; my &reciprocate = sub { 0 } my $range = 1.5;   sub update (num \df) { my int $xidx = 0; my int $yidx = 1; my int $pointidx = 0; loop (my int $idx = 0; $idx < $particlenum; $idx = $idx + 1) { my int $willdraw = 0; if (@lifetimes[$idx] <= 0e0) { if (rand < df) { @lifetimes[$idx] = 25e-1; # time to live @positions[$xidx] = ($w / 20e0).Num; # starting position x @positions[$yidx] = ($h / 10).Num; # and y @velocities[$xidx] = ($spread * rand - $spread/2 + reciprocate()) * 10; # starting velocity x @velocities[$yidx] = (rand - 2.9e0) * $h / 20.5; # and y (randomized slightly so points reach different heights) $willdraw = 1; } } else { if @positions[$yidx] > $h / 10 && @velocities[$yidx] > 0 { @velocities[$yidx] = @velocities[$yidx] * -0.3e0; # "bounce" }   @velocities[$yidx] = @velocities[$yidx] + $h/10.Num * df; # adjust velocity @positions[$xidx] = @positions[$xidx] + @velocities[$xidx] * df; # adjust position x @positions[$yidx] = @positions[$yidx] + @velocities[$yidx] * df; # and y   @lifetimes[$idx] = @lifetimes[$idx] - df; $willdraw = 1; }   if ($willdraw) { $points[$pointidx++] = (@positions[$xidx] * 10).floor; # gather all of the points that $points[$pointidx++] = (@positions[$yidx] * 10).floor; # are still going to be rendered }   $xidx = $xidx + 2; $yidx = $xidx + 1; } $numpoints = ($pointidx - 1) div 2; }   sub render { SDL_SetRenderDrawColor($renderer, 0x0, 0x0, 0x0, 0xff); SDL_RenderClear($renderer);   SDL_SetRenderDrawColor($renderer, |hsv2rgb(((now % 5) / 5).round(.01), $saturation, 1), 0x7f); SDL_RenderDrawPoints($renderer, $points, $numpoints);   SDL_RenderPresent($renderer); }   enum KEY_CODES ( K_UP => 82, K_DOWN => 81, K_LEFT => 80, K_RIGHT => 79, K_SPACE => 44, K_PGUP => 75, K_PGDN => 78, K_Q => 20, );   say q:to/DOCS/; Use UP and DOWN arrow keys to modify the saturation of the particle colors. Use PAGE UP and PAGE DOWN keys to modify the "spread" of the particles. Toggle reciprocation off / on with the SPACE bar. Use LEFT and RIGHT arrow keys to modify angle range for reciprocation. Press the "q" key to quit. DOCS   my $event = SDL_Event.new;   my num $df = 0.0001e0;   main: loop { my $start = now;   while SDL_PollEvent($event) { my $casted_event = SDL_CastEvent($event);   given $casted_event { when *.type == QUIT { last main; } when *.type == WINDOWEVENT { if .event == RESIZED { $w = .data1; $h = .data2; } } when *.type == KEYDOWN { if KEY_CODES(.scancode) -> $comm { given $comm { when 'K_UP' { $saturation = (($saturation + .1) min 1e0) } when 'K_DOWN' { $saturation = (($saturation - .1) max 0e0) } when 'K_PGUP' { $spread = (($spread + .1) min 5e0) } when 'K_PGDN' { $spread = (($spread - .1) max 2e-1) } when 'K_RIGHT' { $range = (($range + .1) min 2e0) } when 'K_LEFT' { $range = (($range - .1) max 1e-1) } when 'K_SPACE' { &reciprocate = reciprocate() == 0 ?? sub { $range * sin(now) } !! sub { 0 } } when 'K_Q' { last main } } } } } }   update($df);   render();   $df = (now - $start).Num;   print fps(); }   say '';   sub fps { state $fps-frames = 0; state $fps-now = now; state $fps = ''; $fps-frames++; if now - $fps-now >= 1 { $fps = [~] "\r", ' ' x 20, "\r", sprintf "FPS: %5.1f ", ($fps-frames / (now - $fps-now)); $fps-frames = 0; $fps-now = now; } $fps }   sub hsv2rgb ( $h, $s, $v ){ state %cache; %cache{"$h|$s|$v"} //= do { my $c = $v * $s; my $x = $c * (1 - abs( (($h*6) % 2) - 1 ) ); my $m = $v - $c; [(do given $h { when 0..^1/6 { $c, $x, 0 } when 1/6..^1/3 { $x, $c, 0 } when 1/3..^1/2 { 0, $c, $x } when 1/2..^2/3 { 0, $x, $c } when 2/3..^5/6 { $x, 0, $c } when 5/6..1 { $c, 0, $x } } ).map: ((*+$m) * 255).Int] } }
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
#Fortran
Fortran
program peaceful_queens_elements_generator use, intrinsic :: iso_fortran_env, only: int64 use, intrinsic :: iso_fortran_env, only: error_unit   implicit none   ! 64-bit integers, for boards up to 8-by-8. integer, parameter :: kind8x8 = int64   ! 128-bit integers, for boards up to 11-by-11. ! This value is correct for gfortran. integer, parameter :: kind11x11 = 16   integer(kind = kind11x11), parameter :: one = 1 integer(kind = kind11x11), parameter :: two = 2   integer, parameter :: n_max = 11   integer(kind = kind11x11) :: rook1_masks(0 : n_max - 1) integer(kind = kind11x11) :: rook2_masks(0 : n_max - 1) integer(kind = kind11x11) :: bishop1_masks(0 : (2 * n_max) - 4) integer(kind = kind11x11) :: bishop2_masks(0 : (2 * n_max) - 4)   ! Combines rook1_masks and rook2_masks. integer(kind = kind11x11) :: rook_masks(0 : (2 * n_max) - 1)   ! Combines bishop1_masks and bishop2_masks. integer(kind = kind11x11) :: bishop_masks(0 : (4 * n_max) - 7)   ! Combines rook and bishop masks. integer(kind = kind11x11) :: queen_masks(0 : (6 * n_max) - 7)   character(len = 16), parameter :: s_kind8x8 = "kind8x8 " character(len = 16), parameter :: s_kind11x11 = "kind11x11 "   character(200) :: arg integer :: arg_count   integer :: m, n, max_solutions integer :: board_kind   arg_count = command_argument_count () if (arg_count /= 3) then call get_command_argument (0, arg) write (error_unit, '("Usage: ", A, " M N MAX_SOLUTIONS")') trim (arg) stop 1 end if   call get_command_argument (1, arg) read (arg, *) m if (m < 1) then write (error_unit, '("M must be between 1 or greater.")') stop 2 end if   call get_command_argument (2, arg) read (arg, *) n if (n < 3 .or. 11 < n) then write (error_unit, '("N must be between 3 and ", I0, ", inclusive.")') n_max stop 2 end if   call get_command_argument (3, arg) read (arg, *) max_solutions   write (*, '("module peaceful_queens_elements")') write (*, '()') write (*, '(" use, intrinsic :: iso_fortran_env, only: int64")') write (*, '()') write (*, '(" implicit none")') write (*, '(" private")') write (*, '()') write (*, '(" integer, parameter, public :: m = ", I0)') m write (*, '(" integer, parameter, public :: n = ", I0)') n write (*, '(" integer, parameter, public :: max_solutions = ", I0)') max_solutions write (*, '()') if (n <= 8) then write (*, '("  ! 64-bit integers, for boards up to 8-by-8.")') write (*, '(" integer, parameter, private :: kind8x8 = int64")') else write (*, '("  ! 128-bit integers, for boards up to 11-by-11.")') write (*, '(" integer, parameter, private :: kind11x11 = ", I0)') kind11x11 end if write (*, '(" integer, parameter, public :: board_kind = ", A)') trim (s_kindnxn (n)) write (*, '()') write (*, '()') write (*, '(" public :: rooks1_attack_check")') write (*, '(" public :: rooks2_attack_check")') write (*, '(" public :: rooks_attack_check")') write (*, '(" public :: bishops1_attack_check")') write (*, '(" public :: bishops2_attack_check")') write (*, '(" public :: bishops_attack_check")') write (*, '(" public :: queens_attack_check")') write (*, '()') write (*, '(" public :: board_rotate90")') write (*, '(" public :: board_rotate180")') write (*, '(" public :: board_rotate270")') write (*, '(" public :: board_reflect1")') write (*, '(" public :: board_reflect2")') write (*, '(" public :: board_reflect3")') write (*, '(" public :: board_reflect4")') write (*, '()')   call write_rook1_masks call write_rook2_masks call write_bishop1_masks call write_bishop2_masks call write_rook_masks call write_bishop_masks call write_queen_masks   write (*, '("contains")') write (*, '()')   call write_rooks1_attack_check call write_rooks2_attack_check call write_bishops1_attack_check call write_bishops2_attack_check call write_rooks_attack_check call write_bishops_attack_check call write_queens_attack_check   call write_board_rotate90 call write_board_rotate180 call write_board_rotate270 call write_board_reflect1 call write_board_reflect2 call write_board_reflect3 call write_board_reflect4   call write_insert_zeros call write_reverse_insert_zeros   write (*, '("end module peaceful_queens_elements")')   contains   subroutine write_rook1_masks integer :: i   call fill_masks (n) do i = 0, n - 1 write (*, '(" integer(kind = ", A, "), parameter :: rook1_mask_",& & I0, "x", I0, "_", I0, " = int (z''", Z0.32, "'', kind & &= ", A, ")")') trim (s_kindnxn (n)), n, n, i,& & rook1_masks(i), trim (s_kindnxn (n)) end do write (*, '()') end subroutine write_rook1_masks   subroutine write_rook2_masks integer :: i   call fill_masks (n) do i = 0, n - 1 write (*, '(" integer(kind = ", A, "), parameter :: rook2_mask_",& & I0, "x", I0, "_", I0, " = int (z''", Z0.32, "'', kind & &= ", A, ")")') trim (s_kindnxn (n)), n, n, i,& & rook2_masks(i), trim (s_kindnxn (n)) end do write (*, '()') end subroutine write_rook2_masks   subroutine write_bishop1_masks integer :: i   call fill_masks (n) do i = 0, (2 * n) - 4 write (*, '(" integer(kind = ", A, "), parameter :: bishop1_mask_",& & I0, "x", I0, "_", I0, " = int (z''", Z0.32, "'', kind & &= ", A, ")")') trim (s_kindnxn (n)), n, n, i,& & bishop1_masks(i), trim (s_kindnxn (n)) end do write (*, '()') end subroutine write_bishop1_masks   subroutine write_bishop2_masks integer :: i   call fill_masks (n) do i = 0, (2 * n) - 4 write (*, '(" integer(kind = ", A, "), parameter :: bishop2_mask_",& & I0, "x", I0, "_", I0, " = int (z''", Z0.32, "'', kind & &= ", A, ")")') trim (s_kindnxn (n)), n, n, i,& & bishop2_masks(i), trim (s_kindnxn (n)) end do write (*, '()') end subroutine write_bishop2_masks   subroutine write_rook_masks integer :: i   call fill_masks (n) do i = 0, (2 * n) - 1 write (*, '(" integer(kind = ", A, "), parameter :: rook_mask_",& & I0, "x", I0, "_", I0, " = int (z''", Z0.32, "'', kind & &= ", A, ")")') trim (s_kindnxn (n)), n, n, i,& & rook_masks(i), trim (s_kindnxn (n)) end do write (*, '()') end subroutine write_rook_masks   subroutine write_bishop_masks integer :: i   call fill_masks (n) do i = 0, (4 * n) - 7 write (*, '(" integer(kind = ", A, "), parameter :: bishop_mask_",& & I0, "x", I0, "_", I0, " = int (z''", Z0.32, "'', kind & &= ", A, ")")') trim (s_kindnxn (n)), n, n, i,& & bishop_masks(i), trim (s_kindnxn (n)) end do write (*, '()') end subroutine write_bishop_masks   subroutine write_queen_masks integer :: i   call fill_masks (n) do i = 0, (6 * n) - 7 write (*, '(" integer(kind = ", A, "), parameter :: queen_mask_",& & I0, "x", I0, "_", I0, " = int (z''", Z0.32, "'', kind & &= ", A, ")")') trim (s_kindnxn (n)), n, n, i,& & queen_masks(i), trim (s_kindnxn (n)) end do write (*, '()') end subroutine write_queen_masks   subroutine write_rooks1_attack_check integer :: i   write (*, '(" elemental function rooks1_attack_check (army1, army2) result (attacking)")') write (*, '(" integer(kind = ", A, "), value :: army1, army2")') trim (s_kindnxn (n)) write (*, '(" logical :: attacking")') write (*, '()') write (*, '(" attacking = ((iand (army1, rook1_mask_", I0, "x", I0,& & "_0) /= 0) .and. (iand (army2, rook1_mask_", I0, "x", I0, "_0) /=& & 0)) .or. &")') n, n, n, n do i = 1, n - 1 write (*, '(" & ((iand (army1, rook1_mask_", I0, "x",& & I0, "_", I0, ") /= 0) .and. (iand (army2, rook1_mask_", I0,& & "x", I0, "_", I0, ") /= 0))")', advance = 'no') n, n, i, n, n, i if (i /= n - 1) then write (*, '(" .or. &")') else write (*, '()') end if end do write (*, '(" end function rooks1_attack_check")') write (*, '()') end subroutine write_rooks1_attack_check   subroutine write_rooks2_attack_check integer :: i   write (*, '(" elemental function rooks2_attack_check (army1, army2) result (attacking)")') write (*, '(" integer(kind = ", A, "), value :: army1, army2")') trim (s_kindnxn (n)) write (*, '(" logical :: attacking")') write (*, '()') write (*, '(" attacking = ((iand (army1, rook2_mask_", I0, "x", I0,& & "_0) /= 0) .and. (iand (army2, rook2_mask_", I0, "x", I0, "_0) /=& & 0)) .or. &")') n, n, n, n do i = 1, n - 1 write (*, '(" & ((iand (army1, rook2_mask_", I0, "x",& & I0, "_", I0, ") /= 0) .and. (iand (army2, rook2_mask_", I0,& & "x", I0, "_", I0, ") /= 0))")', advance = 'no') n, n, i, n, n, i if (i /= n - 1) then write (*, '(" .or. &")') else write (*, '()') end if end do write (*, '(" end function rooks2_attack_check")') write (*, '()') end subroutine write_rooks2_attack_check   subroutine write_bishops1_attack_check integer :: i   write (*, '(" elemental function bishops1_attack_check (army1, army2) result (attacking)")') write (*, '(" integer(kind = ", A, "), value :: army1, army2")') trim (s_kindnxn (n)) write (*, '(" logical :: attacking")') write (*, '()') write (*, '(" attacking = ((iand (army1, bishop1_mask_", I0, "x", I0,& & "_0) /= 0) .and. (iand (army2, bishop1_mask_", I0, "x", I0, "_0) /=& & 0)) .or. &")') n, n, n, n do i = 1, (2 * n) - 4 write (*, '(" & ((iand (army1, bishop1_mask_", I0, "x",& & I0, "_", I0, ") /= 0) .and. (iand (army2, bishop1_mask_", I0,& & "x", I0, "_", I0, ") /= 0))")', advance = 'no') n, n, i, n, n, i if (i /= (2 * n) - 4) then write (*, '(" .or. &")') else write (*, '()') end if end do write (*, '(" end function bishops1_attack_check")') write (*, '()') end subroutine write_bishops1_attack_check   subroutine write_bishops2_attack_check integer :: i   write (*, '(" elemental function bishops2_attack_check (army1, army2) result (attacking)")') write (*, '(" integer(kind = ", A, "), value :: army1, army2")') trim (s_kindnxn (n)) write (*, '(" logical :: attacking")') write (*, '()') write (*, '(" attacking = ((iand (army1, bishop2_mask_", I0, "x", I0,& & "_0) /= 0) .and. (iand (army2, bishop2_mask_", I0, "x", I0, "_0) /=& & 0)) .or. &")') n, n, n, n do i = 1, (2 * n) - 4 write (*, '(" & ((iand (army1, bishop2_mask_", I0, "x",& & I0, "_", I0, ") /= 0) .and. (iand (army2, bishop2_mask_", I0,& & "x", I0, "_", I0, ") /= 0))")', advance = 'no') n, n, i, n, n, i if (i /= (2 * n) - 4) then write (*, '(" .or. &")') else write (*, '()') end if end do write (*, '(" end function bishops2_attack_check")') write (*, '()') end subroutine write_bishops2_attack_check   subroutine write_rooks_attack_check integer :: i   write (*, '(" elemental function rooks_attack_check (army1, army2) result (attacking)")') write (*, '(" integer(kind = ", A, "), value :: army1, army2")') trim (s_kindnxn (n)) write (*, '(" logical :: attacking")') write (*, '()') write (*, '(" attacking = ((iand (army1, rook_mask_", I0, "x", I0,& & "_0) /= 0) .and. (iand (army2, rook_mask_", I0, "x", I0, "_0) /=& & 0)) .or. &")') n, n, n, n do i = 1, (2 * n) - 1 write (*, '(" & ((iand (army1, rook_mask_", I0, "x",& & I0, "_", I0, ") /= 0) .and. (iand (army2, rook_mask_", I0,& & "x", I0, "_", I0, ") /= 0))")', advance = 'no') n, n, i, n, n, i if (i /= (2 * n) - 1) then write (*, '(" .or. &")') else write (*, '()') end if end do write (*, '(" end function rooks_attack_check")') write (*, '()') end subroutine write_rooks_attack_check   subroutine write_bishops_attack_check integer :: i   write (*, '(" elemental function bishops_attack_check (army1, army2) result (attacking)")') write (*, '(" integer(kind = ", A, "), value :: army1, army2")') trim (s_kindnxn (n)) write (*, '(" logical :: attacking")') write (*, '()') write (*, '(" attacking = ((iand (army1, bishop_mask_", I0, "x", I0,& & "_0) /= 0) .and. (iand (army2, bishop_mask_", I0, "x", I0, "_0) /=& & 0)) .or. &")') n, n, n, n do i = 1, (4 * n) - 7 write (*, '(" & ((iand (army1, bishop_mask_", I0, "x",& & I0, "_", I0, ") /= 0) .and. (iand (army2, bishop_mask_", I0,& & "x", I0, "_", I0, ") /= 0))")', advance = 'no') n, n, i, n, n, i if (i /= (4 * n) - 7) then write (*, '(" .or. &")') else write (*, '()') end if end do write (*, '(" end function bishops_attack_check")') write (*, '()') end subroutine write_bishops_attack_check   subroutine write_queens_attack_check integer :: i   write (*, '(" elemental function queens_attack_check (army1, army2) result (attacking)")') write (*, '(" integer(kind = ", A, "), value :: army1, army2")') trim (s_kindnxn (n)) write (*, '(" logical :: attacking")') write (*, '()') write (*, '(" attacking = ((iand (army1, queen_mask_", I0, "x", I0,& & "_0) /= 0) .and. (iand (army2, queen_mask_", I0, "x", I0, "_0) /=& & 0)) .or. &")') n, n, n, n do i = 1, (6 * n) - 7 write (*, '(" & ((iand (army1, queen_mask_", I0, "x",& & I0, "_", I0, ") /= 0) .and. (iand (army2, queen_mask_", I0,& & "x", I0, "_", I0, ") /= 0))")', advance = 'no') n, n, i, n, n, i if (i /= (6 * n) - 7) then write (*, '(" .or. &")') else write (*, '()') end if end do write (*, '(" end function queens_attack_check")') write (*, '()') end subroutine write_queens_attack_check   subroutine write_board_rotate90 integer :: i, j   write (*, '(" elemental function board_rotate90 (a) result (b)")') write (*, '(" integer(kind = ", A, "), value :: a")') trim (s_kindnxn (n)) write (*, '(" integer(kind = ", A, ") :: b")') trim (s_kindnxn (n)) write (*, '()') write (*, '("  ! Rotation 90 degrees in one of the orientations.")') write (*, '()') do i = 0, n - 1 if (i == 0) then write (*, '(" b = ")', advance = 'no') else write (*, '(" & ")', advance = 'no') do j = 1, i write (*, '(" ")', advance = 'no') end do end if if (i /= n - 1) then write (*, '("ior (ishft (reverse_insert_zeros_", I0, " (ishft& & (iand (rook1_mask_", I0, "x", I0, "_", I0, ", a), ",& & I0, ")), ", I0, "), &")') n, n, n, i, -i * n, i else write (*, '(" ishft (reverse_insert_zeros_", I0, " (ishft& & (iand (rook1_mask_", I0, "x", I0, "_", I0, ", a), ",& & I0, ")), ", I0, ")")', advance = 'no') n, n, n, i, -i * n, i do j = 1, n - 1 write (*, '(")")', advance = 'no') end do write (*, '()') end if end do write (*, '(" end function board_rotate90")') write (*, '()') end subroutine write_board_rotate90   subroutine write_board_rotate180 write (*, '(" elemental function board_rotate180 (a) result (b)")') write (*, '(" integer(kind = ", A, "), value :: a")') trim (s_kindnxn (n)) write (*, '(" integer(kind = ", A, ") :: b")') trim (s_kindnxn (n)) write (*, '()') write (*, '("  ! Rotation 180 degrees.")') write (*, '()') write (*, '(" b = board_reflect1 (board_reflect2 (a))")') write (*, '(" end function board_rotate180")') write (*, '()') end subroutine write_board_rotate180   subroutine write_board_rotate270 integer :: i, j   write (*, '(" elemental function board_rotate270 (a) result (b)")') write (*, '(" integer(kind = ", A, "), value :: a")') trim (s_kindnxn (n)) write (*, '(" integer(kind = ", A, ") :: b")') trim (s_kindnxn (n)) write (*, '()') write (*, '("  ! Rotation 270 degrees in one of the orientations.")') write (*, '()') do i = 0, n - 1 if (i == 0) then write (*, '(" b = ")', advance = 'no') else write (*, '(" & ")', advance = 'no') do j = 1, i write (*, '(" ")', advance = 'no') end do end if if (i /= n - 1) then write (*, '("ior (ishft (insert_zeros_", I0, " (ishft& & (iand (rook1_mask_", I0, "x", I0, "_", I0, ", a), ",& & I0, ")), ", I0, "), &")') n, n, n, i, -i * n, n - 1 - i else write (*, '(" ishft (insert_zeros_", I0, " (ishft& & (iand (rook1_mask_", I0, "x", I0, "_", I0, ", a), ",& & I0, ")), ", I0, ")")', advance = 'no') n, n, n, i, -i * n, n - 1 - i do j = 1, n - 1 write (*, '(")")', advance = 'no') end do write (*, '()') end if end do write (*, '(" end function board_rotate270")') write (*, '()') end subroutine write_board_rotate270   subroutine write_board_reflect1 integer :: i, j   write (*, '(" elemental function board_reflect1 (a) result (b)")') write (*, '(" integer(kind = ", A, "), value :: a")') trim (s_kindnxn (n)) write (*, '(" integer(kind = ", A, ") :: b")') trim (s_kindnxn (n)) write (*, '()') write (*, '("  ! Reflection of rows or columns.")') write (*, '()') do i = 0, n - 1 if (i == 0) then write (*, '(" b = ")', advance = 'no') else write (*, '(" & ")', advance = 'no') do j = 1, i write (*, '(" ")', advance = 'no') end do end if if (i /= n - 1) then write (*, '("ior (ishft (iand (rook2_mask_", I0, "x", I0, "_", I0, ", a), ", I0, "), &")') & & n, n, i, (n - 1) - (2 * i) else write (*, '("ishft (iand (rook2_mask_", I0, "x", I0, "_", I0, ", a), ", I0, ")")', advance = 'no') & & n, n, i, (n - 1) - (2 * i) do j = 1, n - 1 write (*, '(")")', advance = 'no') end do write (*, '()') end if end do write (*, '(" end function board_reflect1")') write (*, '()') end subroutine write_board_reflect1   subroutine write_board_reflect2 integer :: i, j   write (*, '(" elemental function board_reflect2 (a) result (b)")') write (*, '(" integer(kind = ", A, "), value :: a")') trim (s_kindnxn (n)) write (*, '(" integer(kind = ", A, ") :: b")') trim (s_kindnxn (n)) write (*, '()') write (*, '("  ! Reflection of rows or columns.")') write (*, '()') do i = 0, n - 1 if (i == 0) then write (*, '(" b = ")', advance = 'no') else write (*, '(" & ")', advance = 'no') do j = 1, i write (*, '(" ")', advance = 'no') end do end if if (i /= n - 1) then write (*, '("ior (ishft (iand (rook1_mask_", I0, "x", I0, "_", I0, ", a), ", I0, "), &")') & & n, n, i, n * ((n - 1) - (2 * i)) else write (*, '("ishft (iand (rook1_mask_", I0, "x", I0, "_", I0, ", a), ", I0, ")")', advance = 'no') & & n, n, i, n * ((n - 1) - (2 * i)) do j = 1, n - 1 write (*, '(")")', advance = 'no') end do write (*, '()') end if end do write (*, '(" end function board_reflect2")') write (*, '()') end subroutine write_board_reflect2   subroutine write_board_reflect3 integer :: i, j   write (*, '(" elemental function board_reflect3 (a) result (b)")') write (*, '(" integer(kind = ", A, "), value :: a")') trim (s_kindnxn (n)) write (*, '(" integer(kind = ", A, ") :: b")') trim (s_kindnxn (n)) write (*, '()') write (*, '("  ! Reflection around one of the two main diagonals.")') write (*, '()') do i = 0, n - 1 if (i == 0) then write (*, '(" b = ")', advance = 'no') else write (*, '(" & ")', advance = 'no') do j = 1, i write (*, '(" ")', advance = 'no') end do end if if (i /= n - 1) then write (*, '("ior (ishft (insert_zeros_", I0, " (ishft& & (iand (rook1_mask_", I0, "x", I0, "_", I0, ", a), ",& & I0, ")), ", I0, "), &")') n, n, n, i, -i * n, i else write (*, '(" ishft (insert_zeros_", I0, " (ishft& & (iand (rook1_mask_", I0, "x", I0, "_", I0, ", a), ",& & I0, ")), ", I0, ")")', advance = 'no') n, n, n, i, -i * n, i do j = 1, n - 1 write (*, '(")")', advance = 'no') end do write (*, '()') end if end do write (*, '(" end function board_reflect3")') write (*, '()') end subroutine write_board_reflect3   subroutine write_board_reflect4 integer :: i, j   write (*, '(" elemental function board_reflect4 (a) result (b)")') write (*, '(" integer(kind = ", A, "), value :: a")') trim (s_kindnxn (n)) write (*, '(" integer(kind = ", A, ") :: b")') trim (s_kindnxn (n)) write (*, '()') write (*, '("  ! Reflection around one of the two main diagonals.")') write (*, '()') do i = 0, n - 1 if (i == 0) then write (*, '(" b = ")', advance = 'no') else write (*, '(" & ")', advance = 'no') do j = 1, i write (*, '(" ")', advance = 'no') end do end if if (i /= n - 1) then write (*, '("ior (ishft (reverse_insert_zeros_", I0, " (ishft& & (iand (rook1_mask_", I0, "x", I0, "_", I0, ", a), ",& & I0, ")), ", I0, "), &")') n, n, n, i, -i * n, n - 1 - i else write (*, '(" ishft (reverse_insert_zeros_", I0, " (ishft& & (iand (rook1_mask_", I0, "x", I0, "_", I0, ", a), ",& & I0, ")), ", I0, ")")', advance = 'no') n, n, n, i, -i * n, n - 1 - i do j = 1, n - 1 write (*, '(")")', advance = 'no') end do write (*, '()') end if end do write (*, '(" end function board_reflect4")') write (*, '()') end subroutine write_board_reflect4   subroutine write_insert_zeros integer :: i, j   write (*, '(" elemental function insert_zeros_", I0, " (a) result (b)")') n write (*, '(" integer(kind = ", A, "), value :: a")') trim (s_kindnxn (n)) write (*, '(" integer(kind = ", A, ") :: b")') trim (s_kindnxn (n)) write (*, '()') do i = 0, n - 1 if (i == 0) then write (*, '(" b = ")', advance = 'no') else write (*, '(" & ")', advance = 'no') do j = 1, i write (*, '(" ")', advance = 'no') end do end if if (i /= n - 1) then write (*, '("ior (ishft (ibits (a, ", I0, ", 1), ", I0, "), &")') i, i * n else write (*, '("ishft (ibits (a, ", I0, ", 1), ", I0, ")")', advance = 'no') i, i * n do j = 1, n - 1 write (*, '(")")', advance = 'no') end do write (*, '()') end if end do write (*, '(" end function insert_zeros_", I0)') n write (*, '()') end subroutine write_insert_zeros   subroutine write_reverse_insert_zeros integer :: i, j   write (*, '(" elemental function reverse_insert_zeros_", I0, " (a) result (b)")') n write (*, '(" integer(kind = ", A, "), value :: a")') trim (s_kindnxn (n)) write (*, '(" integer(kind = ", A, ") :: b")') trim (s_kindnxn (n)) write (*, '()') do i = 0, n - 1 if (i == 0) then write (*, '(" b = ")', advance = 'no') else write (*, '(" & ")', advance = 'no') do j = 1, i write (*, '(" ")', advance = 'no') end do end if if (i /= n - 1) then write (*, '("ior (ishft (ibits (a, ", I0, ", 1), ", I0, "), &")') n - 1 - i, i * n else write (*, '("ishft (ibits (a, ", I0, ", 1), ", I0, ")")', advance = 'no') n - 1 - i, i * n do j = 1, n - 1 write (*, '(")")', advance = 'no') end do write (*, '()') end if end do write (*, '(" end function reverse_insert_zeros_", I0)') n write (*, '()') end subroutine write_reverse_insert_zeros   function s_kindnxn (n) result (s) integer, intent(in) :: n character(len = 16) :: s   if (n <= 8) then s = s_kind8x8 else s = s_kind11x11 end if end function s_kindnxn   subroutine fill_masks (n) integer, intent(in) :: n   call fill_rook1_masks (n) call fill_rook2_masks (n) call fill_bishop1_masks (n) call fill_bishop2_masks (n) call fill_rook_masks (n) call fill_bishop_masks (n) call fill_queen_masks (n) end subroutine fill_masks   subroutine fill_rook1_masks (n) integer, intent(in) :: n   integer :: i integer(kind = kind11x11) :: mask   mask = (two ** n) - 1 do i = 0, n - 1 rook1_masks(i) = mask mask = ishft (mask, n) end do end subroutine fill_rook1_masks   subroutine fill_rook2_masks (n) integer, intent(in) :: n   integer :: i integer(kind = kind11x11) :: mask   mask = 0 do i = 0, n - 1 mask = ior (ishft (mask, n), one) end do do i = 0, n - 1 rook2_masks(i) = mask mask = ishft (mask, 1) end do end subroutine fill_rook2_masks   subroutine fill_bishop1_masks (n) integer, intent(in) :: n   integer :: i, j, k integer(kind = kind11x11) :: mask0, mask1   ! Masks for diagonals. Put them in order from most densely ! populated to least densely populated.   do k = 0, n - 2 mask0 = 0 mask1 = 0 do i = k, n - 1 j = i - k mask0 = ior (mask0, ishft (one, i + (j * n))) mask1 = ior (mask1, ishft (one, j + (i * n))) end do if (k == 0) then bishop1_masks(0) = mask0 else bishop1_masks((2 * k) - 1) = mask0 bishop1_masks(2 * k) = mask1 end if end do end subroutine fill_bishop1_masks   subroutine fill_bishop2_masks (n) integer, intent(in) :: n   integer :: i, j, k integer :: i1, j1 integer(kind = kind11x11) :: mask0, mask1   ! Masks for skew diagonals. Put them in order from most densely ! populated to least densely populated.   do k = 0, n - 2 mask0 = 0 mask1 = 0 do i = k, n - 1 j = i - k i1 = n - 1 - i j1 = n - 1 - j mask0 = ior (mask0, ishft (one, j + (i1 * n))) mask1 = ior (mask1, ishft (one, i + (j1 * n))) end do if (k == 0) then bishop2_masks(0) = mask0 else bishop2_masks((2 * k) - 1) = mask0 bishop2_masks(2 * k) = mask1 end if end do end subroutine fill_bishop2_masks   subroutine fill_rook_masks (n) integer, intent(in) :: n   rook_masks(0 : n - 1) = rook1_masks rook_masks(n : (2 * n) - 1) = rook2_masks end subroutine fill_rook_masks   subroutine fill_bishop_masks (n) integer, intent(in) :: n   integer :: i   ! Put the masks in order from most densely populated to least ! densely populated.   do i = 0, (2 * n) - 4 bishop_masks(2 * i) = bishop1_masks(i) bishop_masks((2 * i) + 1) = bishop2_masks(i) end do end subroutine fill_bishop_masks   subroutine fill_queen_masks (n) integer, intent(in) :: n   queen_masks(0 : (2 * n) - 1) = rook_masks queen_masks(2 * n : (6 * n) - 7) = bishop_masks end subroutine fill_queen_masks   end program peaceful_queens_elements_generator
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
#Ceylon
Ceylon
  module rosetta.passwordgenerator "1.0.0" { import ceylon.random "1.2.2"; }    
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
#REXX
REXX
/*REXX pgm generates/displays all permutations of N different objects taken M at a time.*/ parse arg things bunch inbetweenChars names /*obtain optional arguments from the CL*/ if things=='' | things=="," then things= 3 /*Not specified? Then use the default.*/ if bunch=='' | bunch=="," then bunch= things /* " " " " " " */ /* ╔════════════════════════════════════════════════════════════════╗ */ /* ║ inBetweenChars (optional) defaults to a [null]. ║ */ /* ║ names (optional) defaults to digits (and letters).║ */ /* ╚════════════════════════════════════════════════════════════════╝ */ call permSets things, bunch, inBetweenChars, names exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ p: return word( arg(1), 1) /*P function (Pick first arg of many).*/ /*──────────────────────────────────────────────────────────────────────────────────────*/ permSets: procedure; parse arg x,y,between,uSyms /*X things taken Y at a time. */ @.=; sep= /*X can't be > length(@0abcs). */ @abc = 'abcdefghijklmnopqrstuvwxyz'; @abcU= @abc; upper @abcU @abcS = @abcU || @abc; @0abcS= 123456789 || @abcS   do k=1 for x /*build a list of permutation symbols. */ _= p(word(uSyms, k) p(substr(@0abcS, k, 1) k) ) /*get/generate a symbol.*/ if length(_)\==1 then sep= '_' /*if not 1st character, then use sep. */ $.k= _ /*append the character to symbol list. */ end /*k*/   if between=='' then between= sep /*use the appropriate separator chars. */ call .permSet 1 /*start with the first permutation. */ return /* [↓] this is a recursive subroutine.*/ .permSet: procedure expose $. @. between x y; parse arg ? if ?>y then do; _= @.1; do j=2 for y-1 _= _ || between || @.j end /*j*/ say _ end else do q=1 for x /*build the permutation recursively. */ do k=1 for ?-1; if @.k==$.q then iterate q end /*k*/ @.?= $.q; call .permSet ?+1 end /*q*/ return
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.
#Processing
Processing
  //Abhishek Ghosh, 28th June 2022   void Peano(int x, int y, int lg, int i1, int i2) {   if (lg == 1) { ellipse(x,y,1,1); return; }   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); }   void setup(){ size(1000,1000); Peano(0, 0, 1000, 0, 0); }  
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).
#J
J
require 'format/printf numeric'   randomize '' NB. randomize seed for new session   Vals=: 'HT' NB. valid values input=: 1!:1@<&1: NB. get input from user prompt=: input@echo NB. prompt user for input checkInput=: 'Choose 3 H/Ts' assert (Vals e.~ ]) , 3 = # getUserSeq=: (] [ checkInput)@toupper@prompt choose1st=: Vals {~ 3 ?@$ 2: NB. computer chooses 1st choose2nd=: (0 1 1=1 0 1{])&.(Vals&i.) NB. computer chooses 2nd   playPenney=: verb define if. ?2 do. NB. randomize first chooser Comp=. choose1st '' 'Computer chose %s' printf <Comp You=. getUserSeq 'Choose a sequence of three coin tosses (H/T):' 'Choose a different sequence to computer' assert You -.@-: Comp else. You=. getUserSeq 'Choose a sequence of three coin tosses (H/T):' Comp=. choose2nd You 'Computer chose %s ' printf <Comp end. Tosses=. Vals {~ 100 ?@$ 2 Result=. (Comp,:You) {.@I.@E."1 Tosses 'Toss sequence is %s' printf < (3 + <./ Result) {. Tosses echo ('No result';'You win!';'Computer won!') {::~ *-/ Result )
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.
#Icon_and_Unicon
Icon and Unicon
# # Pathological floating point problems # procedure main() sequence() chaotic() end   # # First task, sequence convergence # link printf procedure sequence() local l := [2, -4] local iters := [3, 4, 5, 6, 7, 8, 20, 30, 50, 100, 200] local i, j, k local n := 1   write("Sequence convergence") # Demonstrate the convergence problem with various precision values every k := (100 | 300) do { n := 10^k write("\n", k, " digits of intermediate precision")   # numbers are scaled up using large integer powers of 10 every i := !iters do { l := [2 * n, -4 * n] printf("i: %3d", i)   every j := 3 to i do { # build out a list of intermediate passes # order of scaling operations matters put(l, 111 * n - (1130 * n * n / l[j - 1]) + (3000 * n * n * n / (l[j - 1] * l[j - 2]))) } # down scale the result to a real # some precision may be lost in the final display printf(" %20.16r\n", l[i] * 1.0 / n) } } end   # # Task 2, chaotic bank of Euler # procedure chaotic() local euler, e, scale, show, y, d   write("\nChaotic Banking Society of Euler") # format the number for listing, string form, way overboard on digits euler := "2718281828459045235360287471352662497757247093699959574966967627724076630353_ 547594571382178525166427427466391932003059921817413596629043572900334295260_ 595630738132328627943490763233829880753195251019011573834187930702154089149_ 934884167509244761460668082264800168477411853742345442437107539077744992069_ 551702761838606261331384583000752044933826560297606737113200709328709127443_ 747047230696977209310141692836819025515108657463772111252389784425056953696_ 770785449969967946864454905987931636889230098793127736178215424999229576351_ 482208269895193668033182528869398496465105820939239829488793320362509443117_ 301238197068416140397019837679320683282376464804295311802328782509819455815_ 301756717361332069811250996181881593041690351598888519345807273866738589422_ 879228499892086805825749279610484198444363463244968487560233624827041978623_ 209002160990235304369941849146314093431738143640546253152096183690888707016_ 768396424378140592714563549061303107208510383750510115747704171898610687396_ 9655212671546889570350354"   # precise math with long integers, string form just for pretty listing e := integer(euler)   # 1000 digits after the decimal for scaling intermediates and service fee scale := 10^1000   # initial deposit - $1 d := e - scale   # show balance with 16 digits show := 10^16 write("Starting balance: $", d * show / scale * 1.0 / show, "...")   # wait 25 years, with only a trivial $1 service fee every y := 1 to 25 do { d := d * y - scale }   # show final balance with 4 digits after the decimal (truncation) show := 10^4 write("Balance after ", y, " years: $", d * show / scale * 1.0 / show) end
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.
#Ruby
Ruby
def solve_pell(n) x = Integer.sqrt(n) y = x z = 1 r = 2*x e1, e2 = 1, 0 f1, f2 = 0, 1   loop do y = r*z - y z = (n - y*y) / z r = (x + y) / z e1, e2 = e2, r*e2 + e1 f1, f2 = f2, r*f2 + f1 a, b = e2 + x*f2, f2 break a, b if a*a - n*b*b == 1 end end   [61, 109, 181, 277].each {|n| puts "x*x - %3s*y*y = 1 for x = %-21s and y = %s" % [n, *solve_pell(n)]}  
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
C
#include <assert.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h>   typedef struct bit_array_tag { uint32_t size; uint32_t* array; } bit_array;   bool bit_array_create(bit_array* b, uint32_t size) { uint32_t* array = calloc((size + 31)/32, sizeof(uint32_t)); if (array == NULL) return false; b->size = size; b->array = array; return true; }   void bit_array_destroy(bit_array* b) { free(b->array); b->array = NULL; }   void bit_array_set(bit_array* b, uint32_t index, bool value) { assert(index < b->size); uint32_t* p = &b->array[index >> 5]; uint32_t bit = 1 << (index & 31); if (value) *p |= bit; else *p &= ~bit; }   bool bit_array_get(const bit_array* b, uint32_t index) { assert(index < b->size); uint32_t bit = 1 << (index & 31); return (b->array[index >> 5] & bit) != 0; }   typedef struct sieve_tag { uint32_t limit; bit_array not_prime; } sieve;   bool sieve_create(sieve* s, uint32_t limit) { if (!bit_array_create(&s->not_prime, limit + 1)) return false; bit_array_set(&s->not_prime, 0, true); bit_array_set(&s->not_prime, 1, true); for (uint32_t p = 2; p * p <= limit; ++p) { if (bit_array_get(&s->not_prime, p) == false) { for (uint32_t q = p * p; q <= limit; q += p) bit_array_set(&s->not_prime, q, true); } } s->limit = limit; return true; }   void sieve_destroy(sieve* s) { bit_array_destroy(&s->not_prime); }   bool is_prime(const sieve* s, uint32_t n) { assert(n <= s->limit); return bit_array_get(&s->not_prime, n) == false; }   bool find_prime_partition(const sieve* s, uint32_t number, uint32_t count, uint32_t min_prime, uint32_t* p) { if (count == 1) { if (number >= min_prime && is_prime(s, number)) { *p = number; return true; } return false; } for (uint32_t prime = min_prime; prime < number; ++prime) { if (!is_prime(s, prime)) continue; if (find_prime_partition(s, number - prime, count - 1, prime + 1, p + 1)) { *p = prime; return true; } } return false; }   void print_prime_partition(const sieve* s, uint32_t number, uint32_t count) { assert(count > 0); uint32_t* primes = malloc(count * sizeof(uint32_t)); if (primes == NULL) { fprintf(stderr, "Out of memory\n"); return; } if (!find_prime_partition(s, number, count, 2, primes)) { printf("%u cannot be partitioned into %u primes.\n", number, count); } else { printf("%u = %u", number, primes[0]); for (uint32_t i = 1; i < count; ++i) printf(" + %u", primes[i]); printf("\n"); } free(primes); }   int main() { const uint32_t limit = 100000; sieve s = { 0 }; if (!sieve_create(&s, limit)) { fprintf(stderr, "Out of memory\n"); return 1; } print_prime_partition(&s, 99809, 1); print_prime_partition(&s, 18, 2); print_prime_partition(&s, 19, 3); print_prime_partition(&s, 20, 4); print_prime_partition(&s, 2017, 24); print_prime_partition(&s, 22699, 1); print_prime_partition(&s, 22699, 2); print_prime_partition(&s, 22699, 3); print_prime_partition(&s, 22699, 4); print_prime_partition(&s, 40355, 3); sieve_destroy(&s); 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
#Delphi
Delphi
  program Partition_function_P;   {$APPTYPE CONSOLE}   uses System.SysUtils, Velthuis.BigIntegers, System.Diagnostics;   var p: TArray<BigInteger>; pd: TArray<Integer>;   function PartiDiffDiff(n: Integer): Integer; begin if n and 1 = 1 then exit((n + 1) div 2); Result := n + 1; end;   function partDiff(n: Integer): Integer; begin if n < 2 then exit(1);   pd[n] := pd[n - 1] + PartiDiffDiff(n - 1); Result := pd[n]; end;   procedure partitionP(n: Integer); begin if n < 2 then exit;   var psum: BigInteger := 0; for var i := 1 to n do begin var pdi := partDiff(i); if pdi > n then Break;   var sign: Int64 := -1;   if (i - 1) mod 4 < 2 then sign := 1;   var t: BigInteger := BigInteger(p[n - pdi]) * BigInteger(sign); psum := psum + t; end; p[n] := psum; end;   begin var stopwatch := TStopwatch.Create; const n = 6666; SetLength(p, n + 1); SetLength(pd, n + 1); stopwatch.Start; p[0] := 1; pd[0] := 1; p[1] := 1; pd[1] := 1; for var i := 2 to n do partitionP(i); stopwatch.Stop; writeln(format('p[%d] = %s', [n, p[n].ToString])); writeln('Took ', stopwatch.ElapsedMilliseconds, 'ms'); Readln; end.
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.
#C.23
C#
  using System;   namespace Pyramid_of_Numbers { class Program { public static void Main(string[] args) { // Set console properties Console.Title = " Pyramid of Numbers / Pascal's triangle Puzzle"; Console.SetBufferSize(80,1000); Console.SetWindowSize(80,60); Console.ForegroundColor = ConsoleColor.Green;     // Main Program Loop ConsoleKeyInfo k = new ConsoleKeyInfo('Y', ConsoleKey.Y,true,true,true); while (k.Key == ConsoleKey.Y) { Console.Clear();   Console.WriteLine("----------------------------------------------"); Console.WriteLine(" Pyramid of Numbers / Pascal's triangle Puzzle"); Console.WriteLine("----------------------------------------------"); Console.WriteLine();       // // Declare new Pyramid array // int r = 5;// Number of rows int [,] Pyramid = new int[r,r];   // Set initial Pyramid values for (int i = 0; i < r; i++) { for(int j = 0; j < r; j++) { Pyramid[i,j] = 0; } } // Show info on created array Console.WriteLine(" Pyramid has " + r + " rows"); Console.WriteLine("--------------------------------------------");   // Enter Pyramid values for(int i = 0; i <= r-1; i++) { Console.WriteLine(" Enter " + (i+1).ToString() + ". row values:"); Console.WriteLine("--------------------------------------------");   for(int j = 0; j < i+1; j++) { Console.Write(" " + (j+1).ToString() + ". value = "); int v = int.Parse(Console.ReadLine());   Pyramid[i,j] = v; } Console.WriteLine("--------------------------------------------"); }   // // Show initial Pyramid values // Console.WriteLine(); Console.WriteLine(" Initial Pyramid Values "); Console.WriteLine();   // Show Pyramid values for(int i = 0; i <= r-1; i++) { for(int j = 0; j < i+1; j++) { Console.Write("{0,4}",Pyramid[i,j]); } Console.WriteLine(); } Console.WriteLine("--------------------------------------------");   // Find solution Solve_Pyramid(Pyramid);   Console.WriteLine(); Console.Write(" Start new calculation <Y/N> . . . "); k = Console.ReadKey(true); } }   // // Solve Function // public static void Solve_Pyramid(int [,] Pyramid) { int r = 5; // Number of rows   // Calculate Y int a = Pyramid[r-1,1]; int b = Pyramid[r-1,3]; int c = Pyramid[0,0];   int y = (c - (4*a) - (4*b))/7; Pyramid[r-1,2] = y;     // Create copy of Pyramid int [,] Pyramid_Copy = new int[r,r]; Array.Copy(Pyramid,Pyramid_Copy,r*r);   int n = 0; // solution counter for(int x = 0; x < y + 1; x++) { for(int z = 0; z < y + 1; z++) { if( (x+z) == y) { Pyramid[r-1,0] = x; Pyramid[r-1,r-1] = z;   // Recalculate Pyramid values for(int i = r-1; i > 0; i--) { for(int j = 0; j < i; j++) { Pyramid[i-1,j] = Pyramid[i,j]+Pyramid[i,j+1]; } }     // Compare Pyramid values bool solved = true; for(int i = 0; i < r-1; i++) { for(int j = 0; j < i+1; j++) { if(Pyramid_Copy[i,j]>0) { if(Pyramid[i,j] != Pyramid_Copy[i,j]) { solved = false; i = r; break; } } } }   if(solved) { n++; Console.WriteLine(); Console.WriteLine(" Solved Pyramid Values no." + n); Console.WriteLine();   // Show Pyramid values for(int i = 0; i <= r-1; i++) { for(int j = 0; j < i+1; j++) { Console.Write("{0,4}",Pyramid[i,j]); } Console.WriteLine(); } Console.WriteLine(); Console.WriteLine(" X = " + Pyramid[r-1,0] + " " + " Y = " + Pyramid[r-1,2] + " " + " Z = " + Pyramid[r-1,4]); Console.WriteLine(); Console.WriteLine("--------------------------------------------"); }   Array.Copy(Pyramid_Copy,Pyramid,r*r); } } }   if(n == 0) { Console.WriteLine(); Console.WriteLine(" Pyramid has no solution "); Console.WriteLine(); } }   } }  
http://rosettacode.org/wiki/Particle_fountain
Particle fountain
Implement a particle fountain. Emulate a fountain of water droplets in a gravitational field being sprayed up and then falling back down. The particle fountain should be generally ordered but individually chaotic; the particles should be going mostly in the same direction, but should have slightly different vectors. Your fountain should have at least several hundred particles in motion at any one time, and ideally several thousand. It is optional to have the individual particle interact with each other. If at all possible, link to a short video clip of your fountain in action. Off-site link to a demo video
#Wren
Wren
import "dome" for Window, Platform, Process import "graphics" for Canvas, Color import "math" for Math, Point import "random" for Random import "input" for Keyboard import "./dynamic" for Struct   var Start = Platform.time var Rand = Random.new()   var fields = [ "particleNum", "positions", "velocities", "lifetimes", "points", "numPoints", "saturation", "spread", "range", "reciprocate" ] var ParticleFountain = Struct.create("ParticleFountain", fields)   class ParticleDisplay { construct new(particleNum, width, height) { Window.resize(width, height) Canvas.resize(width, height) Window.title = "Wren Particle System!" _pn = particleNum _w = width _h = height _df = 1 / 200 // say _pf = ParticleFountain.new( _pn, // particleNum List.filled(_pn * 2, 0), // positions List.filled(_pn * 2, 0), // velocities List.filled(_pn, 0), // lifetimes List.filled(_pn, null), // points 0, // numPoints 0.4, // saturation 1.5, // spread 1.5, // range false // reciprocate ) for (i in 0..._pn) _pf.points[i] = Point.new(0, 0) }   init() { Canvas.cls() _frames = 0 }   updatePF() { var xidx = 0 var yidx = 1 var pointIdx = 0 var recip = Fn.new { _pf.reciprocate ? _pf.range * Math.sin(Platform.time/1000) : 0 } for (idx in 0..._pf.particleNum) { var willDraw = false if (_pf.lifetimes[idx] <= 0) { if (Rand.float() < _df) { _pf.lifetimes[idx] = 2.5 // time to live _pf.positions[xidx] = _w / 20 // starting position x _pf.positions[yidx] = _h / 10 // and y   // starting velocities x and y // randomized slightly so points reach different heights _pf.velocities[xidx] = 10 * (_pf.spread * Rand.float() - _pf.spread / 2 + recip.call()) _pf.velocities[yidx] = (Rand.float() - 2.9) * _h / 20.5 _willDraw = true } } else { if (_pf.positions[yidx] > _h/10 && _pf.velocities[yidx] > 0) { _pf.velocities[yidx] = _pf.velocities[yidx] * (-0.3) // bounce } _pf.velocities[yidx] = _pf.velocities[yidx] + _df * _h / 10 // adjust velocity _pf.positions[xidx] = _pf.positions[xidx] + _pf.velocities[xidx] * _df // adjust position x _pf.positions[yidx] = _pf.positions[yidx] + _pf.velocities[yidx] * _df // and y _pf.lifetimes[idx] = _pf.lifetimes[idx] - _df willDraw = true } if (willDraw) { // gather all the points that are going to be rendered _pf.points[pointIdx] = Point.new((_pf.positions[xidx] * 10).floor, (_pf.positions[yidx] * 10).floor) pointIdx = pointIdx + 1 } xidx = xidx + 2 yidx = xidx + 1 _pf.numPoints = pointIdx } }   update() { if (Keyboard["Up"].justPressed) { _pf.saturation = Math.min(_pf.saturation + 0.1, 1) } else if (Keyboard["Down"].justPressed) { _pf.saturation = Math.max(_pf.saturation - 0.1, 0) } else if (Keyboard["PageUp"].justPressed) { _pf.spread = Math.min(_pf.spread + 1, 50) } else if (Keyboard["PageDown"].justPressed) { _pf.spread = Math.max(_pf.spread - 0.1, 0.2) } else if (Keyboard["Left"].justPressed) { _pf.range = Math.min(_pf.range + 0.1, 12) } else if (Keyboard["Right"].justPressed) { _pf.range = Math.max(_pf.range - 0.1, 0.1) } else if (Keyboard["Space"].justPressed) { _pf.reciprocate = !_pf.reciprocate } else if (Keyboard["Q"].justPressed) { Process.exit() } updatePF() }   draw(alpha) { var c = Color.hsv((Platform.time % 5) * 72, _pf.saturation, 0.5, 0x7f) for (i in 0..._pf.numPoints) { Canvas.pset(_pf.points[i].x, _pf.points[i].y, c) } _frames = _frames + 1 var now = Platform.time if (now - Start >= 1) { Start = now Window.title = "Wren Particle System! (FPS = %(_frames))" _frames = 0 } } }   System.print("""   Use UP and DOWN arrow keys to modify the saturation of the particle colors. Use PAGE UP and PAGE DOWN keys to modify the "spread" of the particles. Toggle reciprocation off / on with the SPACE bar. Use LEFT and RIGHT arrow keys to modify angle range for reciprocation. Press the "q" key to quit. """)   var Game = ParticleDisplay.new(3000, 800, 800)
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
#Go
Go
package main   import "fmt"   const ( empty = iota black white )   const ( bqueen = 'B' wqueen = 'W' bbullet = '•' wbullet = '◦' )   type position struct{ i, j int }   func iabs(i int) int { if i < 0 { return -i } return i }   func place(m, n int, pBlackQueens, pWhiteQueens *[]position) bool { if m == 0 { return true } placingBlack := true for i := 0; i < n; i++ { inner: for j := 0; j < n; j++ { pos := position{i, j} for _, queen := range *pBlackQueens { if queen == pos || !placingBlack && isAttacking(queen, pos) { continue inner } } for _, queen := range *pWhiteQueens { if queen == pos || placingBlack && isAttacking(queen, pos) { continue inner } } if placingBlack { *pBlackQueens = append(*pBlackQueens, pos) placingBlack = false } else { *pWhiteQueens = append(*pWhiteQueens, pos) if place(m-1, n, pBlackQueens, pWhiteQueens) { return true } *pBlackQueens = (*pBlackQueens)[0 : len(*pBlackQueens)-1] *pWhiteQueens = (*pWhiteQueens)[0 : len(*pWhiteQueens)-1] placingBlack = true } } } if !placingBlack { *pBlackQueens = (*pBlackQueens)[0 : len(*pBlackQueens)-1] } return false }   func isAttacking(queen, pos position) bool { if queen.i == pos.i { return true } if queen.j == pos.j { return true } if iabs(queen.i-pos.i) == iabs(queen.j-pos.j) { return true } return false }   func printBoard(n int, blackQueens, whiteQueens []position) { board := make([]int, n*n) for _, queen := range blackQueens { board[queen.i*n+queen.j] = black } for _, queen := range whiteQueens { board[queen.i*n+queen.j] = white }   for i, b := range board { if i != 0 && i%n == 0 { fmt.Println() } switch b { case black: fmt.Printf("%c ", bqueen) case white: fmt.Printf("%c ", wqueen) case empty: if i%2 == 0 { fmt.Printf("%c ", bbullet) } else { fmt.Printf("%c ", wbullet) } } } fmt.Println("\n") }   func main() { nms := [][2]int{ {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 _, nm := range nms { n, m := nm[0], nm[1] fmt.Printf("%d black and %d white queens on a %d x %d board:\n", m, m, n, n) var blackQueens, whiteQueens []position if place(m, n, &blackQueens, &whiteQueens) { printBoard(n, blackQueens, whiteQueens) } else { fmt.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
#Clojure
Clojure
(ns pwdgen.core (:require [clojure.set :refer [difference]] [clojure.tools.cli :refer [parse-opts]]) (:gen-class))   (def minimum-length 4) (def cli-options [["-c" "--count NUMBER" "Number of passwords to generate"  :default 1  :parse-fn #(Integer/parseInt %)] ["-l" "--length NUMBER" "Length of the generated passwords"  :default 8  :parse-fn #(Integer/parseInt %)  :validate [#(<= minimum-length %) (str "Must be greater than or equal to " minimum-length)]] ["-x", "--exclude-similar" "Exclude similar characters"] ["-h" "--help"]])   (def lowercase (map char (range (int \a) (inc (int \z))))) (def uppercase (map char (range (int \A) (inc (int \Z))))) (def numbers (map char (range (int \0) (inc (int \9))))) (def specials (remove (set (concat lowercase uppercase numbers [\` \\])) (map char (range (int \!) (inc (int \~)))))) (def similar #{\I \l \1 \| \O \0 \5 \S \2 \Z})   (defn sanitize [coll options] (if (:exclude-similar options) (into '() (difference (set coll) similar)) coll))   (defn generate-password [options] (let [upper (rand-nth (sanitize uppercase options)) lower (rand-nth (sanitize lowercase options)) number (rand-nth (sanitize numbers options)) special (rand-nth (sanitize specials options)) combined (shuffle (sanitize (concat lowercase uppercase numbers specials) options))] (shuffle (into (list upper lower number special) (take (- (:length options) minimum-length) combined)))))   (defn -main [& args] (let [{:keys [options summary]} (parse-opts args cli-options)] (if (:help options) (println summary) (dotimes [n (:count options)] (println (apply str (generate-password options)))))))
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
#Ring
Ring
  load "stdlib.ring"   list = 1:4 lenList = len(list) permut = [] for perm = 1 to factorial(len(list)) for i = 1 to len(list) add(permut,list[i]) next perm(list) next for n = 1 to len(permut)/lenList for m = (n-1)*lenList+1 to n*lenList see "" + permut[m] if m < n*lenList see "," ok next see nl next   func perm a elementcount = len(a) if elementcount < 1 then return ok pos = elementcount-1 while a[pos] >= a[pos+1] pos -= 1 if pos <= 0 permutationReverse(a, 1, elementcount) return ok end last = elementcount while a[last] <= a[pos] last -= 1 end temp = a[pos] a[pos] = a[last] a[last] = temp permReverse(a, pos+1, elementcount)   func permReverse a, first, last while first < last temp = a[first] a[first] = a[last] a[last] = temp first += 1 last -= 1 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.
#Prolog
Prolog
main:- write_peano_curve('peano_curve.svg', 656, 4).   write_peano_curve(File, Size, Order):- open(File, write, Stream), format(Stream, "<svg xmlns='http://www.w3.org/2000/svg' width='~d' height='~d'>\n", [Size, Size]), write(Stream, "<rect width='100%' height='100%' fill='white'/>\n"), peano_curve(Stream, "L", 8, 8, 8, 90, Order), write(Stream, "</svg>\n"), close(Stream).   peano_curve(Stream, Axiom, X, Y, Length, Angle, Order):- write(Stream, "<path stroke-width='1' stroke='black' fill='none' d='"), format(Stream, 'M~g,~g\n', [X, Y]), rewrite(Axiom, Order, S), string_chars(S, Chars), execute(Stream, X, Y, Length, Angle, Chars), write(Stream, "'/>\n").   rewrite(S, 0, S):-!. rewrite(S0, N, S):- string_chars(S0, Chars0), rewrite1(Chars0, '', S1), N1 is N - 1, rewrite(S1, N1, S).   rewrite1([], S, S):-!. rewrite1([C|Chars], T, S):- rewrite2(C, X), string_concat(T, X, T1), rewrite1(Chars, T1, S).   rewrite2('L', "LFRFL-F-RFLFR+F+LFRFL"):-!. rewrite2('R', "RFLFR+F+LFRFL-F-RFLFR"):-!. rewrite2(X, X).   execute(_, _, _, _, _, []):-!. execute(Stream, X, Y, Length, Angle, ['F'|Chars]):- !, Theta is (pi * Angle) / 180.0, X1 is X + Length * cos(Theta), Y1 is Y + Length * sin(Theta), format(Stream, 'L~g,~g\n', [X1, Y1]), execute(Stream, X1, Y1, Length, Angle, Chars). execute(Stream, X, Y, Length, Angle, ['+'|Chars]):- !, Angle1 is (Angle + 90) mod 360, execute(Stream, X, Y, Length, Angle1, Chars). execute(Stream, X, Y, Length, Angle, ['-'|Chars]):- !, Angle1 is (Angle - 90) mod 360, execute(Stream, X, Y, Length, Angle1, Chars). execute(Stream, X, Y, Length, Angle, [_|Chars]):- execute(Stream, X, Y, Length, Angle, Chars).
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).
#Java
Java
import java.util.*;   public class PenneysGame {   public static void main(String[] args) { Random rand = new Random();   String compChoice = "", playerChoice; if (rand.nextBoolean()) {   for (int i = 0; i < 3; i++) compChoice += "HT".charAt(rand.nextInt(2)); System.out.printf("Computer chooses %s%n", compChoice);   playerChoice = prompt(compChoice);   } else {   playerChoice = prompt(compChoice);   compChoice = "T"; if (playerChoice.charAt(1) == 'T') compChoice = "H"; compChoice += playerChoice.substring(0, 2); System.out.printf("Computer chooses %s%n", compChoice); }   String tossed = ""; while (true) { tossed += "HT".charAt(rand.nextInt(2)); System.out.printf("Tossed %s%n" , tossed); if (tossed.endsWith(playerChoice)) { System.out.println("You win!"); break; } if (tossed.endsWith(compChoice)) { System.out.println("Computer wins!"); break; } } }   private static String prompt(String otherChoice) { Scanner sc = new Scanner(System.in); String s; do { System.out.print("Choose a sequence: "); s = sc.nextLine().trim().toUpperCase(); } while (!s.matches("[HT]{3}") || s.equals(otherChoice)); return s; } }
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.
#J
J
vn=: 111 +(_1130 % _1&{) + (3000 % _1&{ * _2&{)
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.
#Rust
Rust
  use num_bigint::{ToBigInt, BigInt}; use num_traits::{Zero, One}; //use std::mem::replace in the loop if you want this to be more efficient   fn main() { test(61u64); test(109u64); test(181u64); test(277u64); }   struct Pair { v1: BigInt, v2: BigInt, }   impl Pair { pub fn make_pair(a: &BigInt, b: &BigInt) -> Pair { Pair { v1: a.clone(), v2: b.clone(), } }   }   fn solve_pell(n: u64) -> Pair{ let x: BigInt = ((n as f64).sqrt()).to_bigint().unwrap(); if x.clone() * x.clone() == n.to_bigint().unwrap() { Pair::make_pair(&One::one(), &Zero::zero()) } else { let mut y: BigInt = x.clone(); let mut z: BigInt = One::one(); let mut r: BigInt = ( &z + &z) * x.clone(); let mut e: Pair = Pair::make_pair(&One::one(), &Zero::zero()); let mut f: Pair = Pair::make_pair(&Zero::zero() ,&One::one()); let mut a: BigInt = Zero::zero(); let mut b: BigInt = Zero::zero(); while &a * &a - n * &b * &b != One::one() { //println!("{} {} {}", y, z, r); y = &r * &z - &y; z = (n - &y * &y) / &z; r = (&x + &y) / &z;   e = Pair::make_pair(&e.v2, &(&r * &e.v2 + &e.v1)); f = Pair::make_pair(&f.v2, &(&r * &f.v2 + &f.v1)); a = &e.v2 + &x * &f.v2; b = f.v2.clone(); } let pa = &a; let pb = &b; Pair::make_pair(&pa.clone(), &pb.clone()) } }   fn test(n: u64) { let r: Pair = solve_pell(n); println!("x^2 - {} * y^2 = 1 for x = {} and y = {}", n, r.v1, r.v2); }  
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.
#Scala
Scala
def pellFermat(n: Int): (BigInt,BigInt) = { import scala.math.{sqrt, floor}   val x = BigInt(floor(sqrt(n)).toInt)   var i = 0   // Use the Continued Fractions method def converge(y:BigInt, z:BigInt, r:BigInt, e1:BigInt, e2:BigInt, f1:BigInt, f2:BigInt ) : (BigInt,BigInt) = {   val a = f2 * x + e2 val b = f2   if (a * a - n * b * b == 1) { return (a, b) }   val yh = r * z - y val zh = (n - yh * yh) / z val rh = (x + yh) / zh   converge(yh,zh,rh,e2,e1 + e2 * rh,f2,f1 + f2 * rh) }   converge(x,BigInt("1"),x << 1,BigInt("1"),BigInt("0"),BigInt("0"),BigInt("1")) }   val nums = List(61,109,181,277) val solutions = nums.map{pellFermat(_)}   { println("For Pell's Equation, x\u00b2 - ny\u00b2 = 1\n") (nums zip solutions).foreach{ case (n, (x,y)) => println(s"n = $n, x = $x, y = $y")} }
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.23
C#
using System; using System.Collections; using System.Collections.Generic; using static System.Linq.Enumerable;   public static class Rosetta { static void Main() { foreach ((int x, int n) in new [] { (99809, 1), (18, 2), (19, 3), (20, 4), (2017, 24), (22699, 1), (22699, 2), (22699, 3), (22699, 4), (40355, 3) }) { Console.WriteLine(Partition(x, n)); } }   public static string Partition(int x, int n) { if (x < 1 || n < 1) throw new ArgumentOutOfRangeException("Parameters must be positive."); string header = $"{x} with {n} {(n == 1 ? "prime" : "primes")}: "; int[] primes = SievePrimes(x).ToArray(); if (primes.Length < n) return header + "not enough primes"; int[] solution = CombinationsOf(n, primes).FirstOrDefault(c => c.Sum() == x); return header + (solution == null ? "not possible" : string.Join("+", solution); }   static IEnumerable<int> SievePrimes(int bound) { if (bound < 2) yield break; yield return 2;   BitArray composite = new BitArray((bound - 1) / 2); int limit = ((int)(Math.Sqrt(bound)) - 1) / 2; for (int i = 0; i < limit; i++) { if (composite[i]) continue; int prime = 2 * i + 3; yield return prime; for (int j = (prime * prime - 2) / 2; j < composite.Count; j += prime) composite[j] = true; } for (int i = limit; i < composite.Count; i++) { if (!composite[i]) yield return 2 * i + 3; } }   static IEnumerable<int[]> CombinationsOf(int count, int[] input) { T[] result = new T[count]; foreach (int[] indices in Combinations(input.Length, count)) { for (int i = 0; i < count; i++) result[i] = input[indices[i]]; yield return result; } }   static IEnumerable<int[]> Combinations(int n, int k) { var result = new int[k]; var stack = new Stack<int>(); stack.Push(0); while (stack.Count > 0) { int index = stack.Count - 1; int value = stack.Pop(); while (value < n) { result[index++] = value++; stack.Push(value); if (index == k) { yield return result; break; } } } }   }
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
#Elixir
Elixir
  use Bitwise, skip_operators: true   defmodule Partition do def init(), do:  :ets.new :pN, [:set, :named_table, :private]   def gpentagonals(), do: Stream.unfold {1, 0}, &next/1 defp next({m, n}) do a = case rem m, 2 do 0 -> div m, 2 1 -> m end {n, {m + 1, n + a}} end   def p(0), do: 1 def p(n) do case :ets.lookup :pN, n do [{^n, val}] -> val [] -> {val, _} = gpentagonals() |> Stream.drop(1) |> Stream.take_while(fn m -> m <= n end) |> Stream.map(fn g -> p(n - g) end) |> Enum.reduce({0, 0}, fn n, {a, sgn} -> { a + (if sgn < 2, do: n, else: -n), band(sgn + 1, 3) } end)  :ets.insert :pN, {n, val} val end end end   Partition.init IO.puts Partition.p 6666  
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
#Erlang
Erlang
  -mode(compile).   main(_) -> ets:new(pN, [set, named_table, protected]), io:format("~w~n", [p(6666)]).   p(0) -> 1; p(N) -> case ets:lookup(pN, N) of [{N, Pn}] -> Pn; [] -> Terms = [p(N - G) || G <- gpentagonals(N)], Pn = sum_partitions(Terms), ets:insert(pN, {N, Pn}), Pn end.   sum_partitions(Terms) -> sum_partitions(Terms, 0, 0). sum_partitions([], _, Sum) -> Sum; sum_partitions([N|Ns], Sgn, Sum) -> Summand = case Sgn < 2 of true -> N; false -> -N end, sum_partitions(Ns, (Sgn+1) band 3, Sum + Summand).   gpentagonals(Max) -> gpentagonals(1, Max, [0]). gpentagonals(M, Max, Ps = [N|_]) -> GP = N + case M rem 2 of 0 -> M div 2; 1 -> M end, if GP > Max -> tl(lists:reverse(Ps)); true -> gpentagonals(M + 1, Max, [GP|Ps]) end.  
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.
#C.2B.2B
C++
#include <iostream> #include <iomanip>   inline int sign(int i) { return i < 0 ? -1 : i > 0; }   inline int& E(int *x, int row, int col) { return x[row * (row + 1) / 2 + col]; }   int iter(int *v, int *diff) { // 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 for (auto i = 1u; i < 5u; i++) for (auto j = 0u; j <= i; j++) { 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); }   for (auto i = 0u; i < 4u; i++) for (auto j = 0u; j < i; j++) 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 done uint sum; int e = 0; for (auto i = sum = 0u; i < 15u; i++) { sum += !!sign(e = diff[i]);   // 1/5-ish feedback strength on average. These numbers are highly magical, depending on nodes' connectivities if (e >= 4 || e <= -4) v[i] += e / 5; else if (rand() < RAND_MAX / 4) v[i] += sign(e); } return sum; }   void show(int *x) { for (auto i = 0u; i < 5u; i++) for (auto j = 0u; j <= i; j++) std::cout << std::setw(4u) << *(x++) << (j < i ? ' ' : '\n'); }   int main() { int v[15] = { 0 }, diff[15] = { 0 }; for (auto i = 1u, s = 1u; s; i++) { s = iter(v, diff); std::cout << "pass " << i << ": " << s << std::endl; } show(v);   return 0; }
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
#Java
Java
import java.util.ArrayList; import java.util.Arrays; import java.util.List;   public class Peaceful { enum Piece { Empty, Black, White, }   public static class Position { public int x, y;   public Position(int x, int y) { this.x = x; this.y = y; }   @Override public boolean equals(Object obj) { if (obj instanceof Position) { Position pos = (Position) obj; return pos.x == x && pos.y == y; } return false; } }   private static boolean place(int m, int n, List<Position> pBlackQueens, List<Position> pWhiteQueens) { if (m == 0) { return true; } boolean placingBlack = true; for (int i = 0; i < n; ++i) { inner: for (int j = 0; j < n; ++j) { Position pos = new Position(i, j); for (Position queen : pBlackQueens) { if (pos.equals(queen) || !placingBlack && isAttacking(queen, pos)) { continue inner; } } for (Position queen : pWhiteQueens) { if (pos.equals(queen) || placingBlack && isAttacking(queen, pos)) { continue inner; } } if (placingBlack) { pBlackQueens.add(pos); placingBlack = false; } else { pWhiteQueens.add(pos); if (place(m - 1, n, pBlackQueens, pWhiteQueens)) { return true; } pBlackQueens.remove(pBlackQueens.size() - 1); pWhiteQueens.remove(pWhiteQueens.size() - 1); placingBlack = true; } } } if (!placingBlack) { pBlackQueens.remove(pBlackQueens.size() - 1); } return false; }   private static boolean isAttacking(Position queen, Position pos) { return queen.x == pos.x || queen.y == pos.y || Math.abs(queen.x - pos.x) == Math.abs(queen.y - pos.y); }   private static void printBoard(int n, List<Position> blackQueens, List<Position> whiteQueens) { Piece[] board = new Piece[n * n]; Arrays.fill(board, Piece.Empty);   for (Position queen : blackQueens) { board[queen.x + n * queen.y] = Piece.Black; } for (Position queen : whiteQueens) { board[queen.x + n * queen.y] = Piece.White; } for (int i = 0; i < board.length; ++i) { if ((i != 0) && i % n == 0) { System.out.println(); }   Piece b = board[i]; if (b == Piece.Black) { System.out.print("B "); } else if (b == Piece.White) { System.out.print("W "); } else { int j = i / n; int k = i - j * n; if (j % 2 == k % 2) { System.out.print("• "); } else { System.out.print("◦ "); } } } System.out.println('\n'); }   public static void main(String[] args) { List<Position> nms = List.of( new Position(2, 1), new Position(3, 1), new Position(3, 2), new Position(4, 1), new Position(4, 2), new Position(4, 3), new Position(5, 1), new Position(5, 2), new Position(5, 3), new Position(5, 4), new Position(5, 5), new Position(6, 1), new Position(6, 2), new Position(6, 3), new Position(6, 4), new Position(6, 5), new Position(6, 6), new Position(7, 1), new Position(7, 2), new Position(7, 3), new Position(7, 4), new Position(7, 5), new Position(7, 6), new Position(7, 7) ); for (Position nm : nms) { int m = nm.y; int n = nm.x; System.out.printf("%d black and %d white queens on a %d x %d board:\n", m, m, n, n); List<Position> blackQueens = new ArrayList<>(); List<Position> whiteQueens = new ArrayList<>(); if (place(m, n, blackQueens, whiteQueens)) { printBoard(n, blackQueens, whiteQueens); } else { System.out.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
#Commodore_BASIC
Commodore BASIC
1 rem password generator 2 rem rosetta code 10 g$(1)="abcdefghijklmnopqrstuvwxyz" 15 g$(2)="ABCDEFGHIJKLMNOPQRSTUVWXYZ" 20 g$(3)="0123456789" 25 g$(4)="<>!@#$%^&*()[];:'.?/" 30 print chr$(147);chr$(14) 35 print "Password Generator":print 40 print "Press H for help, or any":print "other key to begin.":print 45 get k$:if k$="" then 45 50 if k$="h" then gosub 500 60 print chr$(147) 65 input "Enter password length: (6-30)";pl 70 if pl<6 or pl>30 then print "Out of range.":goto 65 75 print:input "How many passwords (1-20)";np 80 if np<1 or np>20 then print "Out of range.":goto 75 85 if np>10 then dim pw$(np) 90 if np*pl > 100 then print:print "Um... Ok, this might take a bit." 100 for pc=1 to np 105 for i=1 to 4:g(i)=0:next 110 tp$="" 112 for i=1 to pl 115 cg=int(rnd(1)*4)+1 120 cc=int(rnd(1)*len(g$(cg)))+1 125 tp$=tp$+mid$(g$(cg),cc,1) 130 g(cg)=g(cg)+1 135 next i 140 for i=1 to 4 145 if g(i)=0 then goto 110 150 next i 155 pw$(pc)=tp$ 160 next pc 200 print chr$(147);"Password list:":print 205 for pc=1 to np:print pc;chr$(157);".";tab(6);pw$(pc):next pc 210 print:print "Again? (y/n)"; 215 get k$:if k$<>"y" and k$<>"n" then 215 220 if k$="y" then clr:goto 10 225 end 500 rem *** help *** 505 print chr$(147);"This program will generate a password" 510 print "made up of each of the following" 515 print "character types:":print 520 print " - Uppercase Letter (A-Z)" 525 print " - Lowercase Letter (a-z)" 530 print " - Number (0-9)" 535 print " - Punctuation and Other Symbols" 540 print " (e.g. # $ ! & [ . ;, etc.)" 545 print 550 print "You may choose how many total characters"; 555 print "(up to 30) should be in the password, " 560 print "and how many passwords (up to 20) should"; 565 print "be generated. The program ensures that " 570 print "there is at least one character from " 575 print "each of the character types in each " 580 print "password." 585 print 590 print "Note: You can edit the character lists" 595 print "on lines 10-25 to customize the" 600 print "selection pool." 605 print 610 print "Press any key to begin." 615 get k$:if k$="" then 615 620 return
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
#Ring_2
Ring
    Another Solution   // Permutations -- Bert Mariani 2020-07-12 // Ask User for number of digits to permutate    ? "Enter permutations number : " Give n n = number(n) x = 1:n // array    ? "Permutations are : " count = 0   nPermutation(1,n) //===>>> START    ? " " // ? = print  ? "Exiting of the program... "  ? "Enter to Exit : " Give m // To Exit CMD window   //====================== // Returns true only if uniq number on row   Func Place(k,i)   for j=1 to k-1 if x[j] = i // Two numbers in same row return 0 ok next   return 1   //====================== Func nPermutation(k, n)   for i = 1 to n if( Place(k,i)) //===>>> Call x[k] = i if(k=n) See nl for i= 1 to n See " "+ x[i] next See " "+ (count++) else nPermutation(k+1,n) //===>>> Call RECURSION ok ok next return      
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.
#Python
Python
  import turtle as tt import inspect   stack = [] # Mark the current stacks in run. def peano(iterations=1): global stack   # The turtle Ivan: ivan = tt.Turtle(shape = "classic", visible = True)     # The app window: screen = tt.Screen() screen.title("Desenhin do Peano") screen.bgcolor("#232323") screen.delay(0) # Speed on drawing (if higher, more slow) screen.setup(width=0.95, height=0.9)   # The size of each step walked (here, named simply "walk"). It's not a pixel scale. This may stay still: walk = 1   def screenlength(k): # A function to make the image good to see (without it would result in a partial image). # This will guarantee that we can see the the voids and it's steps. if k != 0: length = screenlength(k-1) return 2*length + 1 else: return 0   kkkj = screenlength(iterations) screen.setworldcoordinates(-1, -1, kkkj + 1, kkkj + 1) ivan.color("#EEFFFF", "#FFFFFF")     # The magic \(^-^)/: def step1(k): global stack stack.append(len(inspect.stack())) if k != 0: ivan.left(90) step2(k - 1) ivan.forward(walk) ivan.right(90) step1(k - 1) ivan.forward(walk) step1(k - 1) ivan.right(90) ivan.forward(walk) step2(k - 1) ivan.left(90) def step2(k): global stack stack.append(len(inspect.stack())) if k != 0: ivan.right(90) step1(k - 1) ivan.forward(walk) ivan.left(90) step2(k - 1) ivan.forward(walk) step2(k - 1) ivan.left(90) ivan.forward(walk) step1(k - 1) ivan.right(90)   # Making the program work: ivan.left(90) step2(iterations)   tt.done()   if __name__ == "__main__": peano(4) import pylab as P # This plot, after closing the drawing window, the "stack" graphic. P.plot(stack) P.show()  
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).
#Julia
Julia
  const SLEN = 3   autobet() = randbool(SLEN) function autobet(ob::BitArray{1}) rlen = length(ob) 2 < rlen || return ~ob 3 < rlen || return [~ob[2], ob[1:2]] opt = falses(rlen) opt[1] = true opt[end-1:end] = true ob != opt || return ~opt return opt end autobet(ob::Array{Bool,1}) = autobet(convert(BitArray{1}, ob))   function pgencode{T<:String}(a::T) b = uppercase(a) 0 < length(b) || return trues(0)  !ismatch(r"[^HT]+", b) || error(@sprintf "%s is not a HT sequence" a) b = split(b, "") b .== "H" end pgdecode(a::BitArray{1}) = join([i ? "H" : "T" for i in a], "")   function humanbet() b = "" while length(b) != SLEN || ismatch(r"[^HT]+", b) print("Your bet? ") b = uppercase(chomp(readline())) end return b 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).
#Kotlin
Kotlin
// version 1.2.10   import java.util.Random   val rand = Random()   val optimum = mapOf( "HHH" to "THH", "HHT" to "THH", "HTH" to "HHT", "HTT" to "HHT", "THH" to "TTH", "THT" to "TTH", "TTH" to "HTT", "TTT" to "HTT" )   fun getUserSequence(): String { println("A sequence of three H or T should be entered") var userSeq: String do { print("Enter your sequence: ") userSeq = readLine()!!.toUpperCase() } while (userSeq.length != 3 || userSeq.any { it != 'H' && it != 'T' }) return userSeq }   fun getComputerSequence(userSeq: String = ""): String { val compSeq = if(userSeq == "") String(CharArray(3) { if (rand.nextInt(2) == 0) 'T' else 'H' }) else optimum[userSeq]!! println("Computer's sequence: $compSeq") return compSeq }   fun main(args: Array<String>) { var userSeq: String var compSeq: String val r = rand.nextInt(2) if (r == 0) { println("You go first") userSeq = getUserSequence() println() compSeq = getComputerSequence(userSeq) } else { println("Computer goes first") compSeq = getComputerSequence() println() userSeq = getUserSequence() }   println() val coins = StringBuilder() while (true) { val coin = if (rand.nextInt(2) == 0) 'H' else 'T' coins.append(coin) println("Coins flipped: $coins") val len = coins.length if (len >= 3) { val seq = coins.substring(len - 3, len) if (seq == userSeq) { println("\nYou win!") return } else if (seq == compSeq) { println("\nComputer wins!") return } } Thread.sleep(2000) // wait two seconds for next flip } }  
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.
#Java
Java
import java.math.BigDecimal; import java.math.RoundingMode;   public class FPProblems { public static void wrongConvergence() { int[] INDEXES = new int[] { 3, 4, 5, 6, 7, 8, 20, 30, 50, 100 };   // Standard 64-bit floating point double[] fpValues = new double[100]; fpValues[0] = 2.0; fpValues[1] = -4.0; for (int i = 2; i < fpValues.length; i++) { fpValues[i] = 111.0 - 1130.0 / fpValues[i - 1] + 3000.0 / (fpValues[i - 1] * fpValues[i - 2]); }   // Using rational representation BigRational[] brValues = new BigRational[100]; brValues[0] = BigRational.valueOf(2); brValues[1] = BigRational.valueOf(-4); for (int i = 2; i < brValues.length; i++) { // Using intermediate values for better readability BigRational clause2 = BigRational.valueOf(1130).divide(brValues[i - 1]); BigRational clause3 = BigRational.valueOf(3000).divide(brValues[i - 1].multiply(brValues[i - 2])); brValues[i] = BigRational.valueOf(111).subtract(clause2).add(clause3); }   System.out.println("Wrong Convergence Sequence"); for (int n : INDEXES) { BigDecimal value = brValues[n - 1].toBigDecimal(16, RoundingMode.HALF_UP); System.out.println(" For index " + n + ", FP value is " + fpValues[n - 1] + ", and rounded BigRational value is " + value.toPlainString()); }   return; }   public static void chaoticBankSociety() { System.out.println("Chaotic Bank Society"); double balance = Math.E - 1.0;   // Calculate e using first 1000 terms of the reciprocal of factorials formula BigRational e = BigRational.ONE; BigRational d = BigRational.ONE; for (int i = 1; i < 1000; i++) { d = d.multiply(BigRational.valueOf(i)); e = e.add(d.reciprocal()); } System.out.println("DEBUG: e=" + e.toBigDecimal(100, RoundingMode.HALF_UP).toPlainString());   // Alternatively, // BigRational e = BigRational.valueOf(Math.E);   BigRational brBalance = e.subtract(BigRational.ONE); for (int year = 1; year <= 25; year++) { balance = (balance * year) - 1.0; brBalance = brBalance.multiply(BigRational.valueOf(year)).subtract(BigRational.ONE); BigDecimal bdValue = brBalance.toBigDecimal(16, RoundingMode.HALF_UP); System.out.println(" Year=" + year + ", FP balance=" + balance + ", BigRational balance=" + bdValue.toPlainString()); } }   public static void siegfriedRump() { System.out.println("Siegfried Rump formula"); double fpValue; { double a = 77617.0; double b = 33096.0; fpValue = 333.75 * Math.pow(b, 6) + a * a * (11.0 * a * a * b * b - Math.pow(b, 6) - 121.0 * Math.pow(b, 4) - 2.0) + 5.5 * Math.pow(b, 8) + a / (2.0 * b); }   BigRational brValue; { BigRational a = BigRational.valueOf(77617); BigRational b = BigRational.valueOf(33096); BigRational clause1 = BigRational.valueOf(333.75).multiply(b.pow(6)); BigRational clause2a = BigRational.valueOf(11).multiply(a).multiply(a).multiply(b).multiply(b); BigRational clause2b = b.pow(6).add(BigRational.valueOf(121).multiply(b.pow(4))).add(BigRational.valueOf(2)); BigRational clause2 = a.multiply(a).multiply(clause2a.subtract(clause2b)); BigRational clause3 = BigRational.valueOf(5.5).multiply(b.pow(8)); BigRational clause4 = a.divide(b.multiply(BigRational.valueOf(2))); brValue = clause1.add(clause2).add(clause3).add(clause4); }   System.out.println(" FP value is " + fpValue); System.out.println(" BigRational rounded value is " + brValue.toBigDecimal(64, RoundingMode.HALF_UP).toPlainString()); System.out.println(" BigRational full value is " + brValue.toString()); }   public static void main(String... args) { wrongConvergence();   System.out.println(); chaoticBankSociety();   System.out.println(); siegfriedRump(); } }