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/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
#Stata
Stata
perm 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).
#Ruby
Ruby
Toss = [:Heads, :Tails]   def yourChoice puts "Enter your choice (H/T)" choice = [] 3.times do until (c = $stdin.getc.upcase) == "H" or c == "T" end choice << (c=="H" ? Toss[0] : Toss[1]) end puts "You chose #{choice.join(' ')}" choice end   loop do puts "\n%s I start, %s you start ..... %s" % [*Toss, coin = Toss.sample] if coin == Toss[0] myC = Toss.shuffle << Toss.sample puts "I chose #{myC.join(' ')}" yC = yourChoice else yC = yourChoice myC = Toss - [yC[1]] + yC.first(2) puts "I chose #{myC.join(' ')}" end   seq = Array.new(3){Toss.sample} print seq.join(' ') loop do puts "\n I win!" or break if seq == myC puts "\n You win!" or break if seq == yC seq.push(Toss.sample).shift print " #{seq[-1]}" end 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.
#Racket
Racket
#lang racket   (define current-do-exact-calculations? (make-parameter exact->inexact))   (define (x n) (if (current-do-exact-calculations?) n (exact->inexact n)))   (define (decimal.18 n) (regexp-replace #px"0+$" (real->decimal-string n 18) ""))   (define (task-1 n) (let ((c_1 (x 111)) (c_2 (x -1130)) (c_3 (x 3000))) (let loop ((v_n-2 (x 2)) (v_n-1 (x -4)) (n (- n 2))) (if (= n 0) v_n-1 (loop v_n-1 (+ c_1 (/ c_2 v_n-1) (/ c_3 (* v_n-1 v_n-2))) (- n 1))))))   (define (task-2) ; chaotic bank (define e (if (current-do-exact-calculations?) #e2.71828182845904523536028747135266249775724709369995 (exp 1))) (for/fold ((b (- e 1))) ((y (in-range 1 26))) (- (* b y) 1)))   (define (task-3 a b) (+ (* (x #e333.75) (expt b 6)) (* (expt a 2) (- (* 11 (expt a 2) (expt b 2)) (expt b 6) (* 121 (expt b 4)) 2)) (* (x #e5.5) (expt b 8)) (/ a (* b 2))))   (define (all-tests) (let ((classic-sum (+ (x #e0.2) (x #e0.1)))) (printf "Classic example: ~a = ~a~%" classic-sum (decimal.18 classic-sum)))   (displayln "TASK 1") (for ((n (in-list '(3 4 5 6 7 8 20 30 50 100)))) (printf "n=~a\t~a~%" n (decimal.18 (task-1 n))))   (printf "TASK 2: balance after 25 years = ~a~%" (decimal.18 (task-2)))   (let ((t3 (task-3 77617 33096))) (printf "TASK 3: f(77617, 33096) = ~a = ~a~%" t3 (decimal.18 t3))))   (module+ main (displayln "INEXACT (Floating Point) NUMBERS") (parameterize ([current-do-exact-calculations? #f]) (all-tests)) (newline)   (displayln "EXACT (Rational) NUMBERS") (parameterize ([current-do-exact-calculations? #t]) (all-tests)))
http://rosettacode.org/wiki/Parallel_brute_force
Parallel brute force
Task Find, through brute force, the five-letter passwords corresponding with the following SHA-256 hashes: 1. 1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad 2. 3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b 3. 74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f Your program should naively iterate through all possible passwords consisting only of five lower-case ASCII English letters. It should use concurrent or parallel processing, if your language supports that feature. You may calculate SHA-256 hashes by calling a library or through a custom implementation. Print each matching password, along with its SHA-256 hash. Related task: SHA-256
#C
C
// $ gcc -o parabrutfor parabrutfor.c -fopenmp -lssl -lcrypto // $ export OMP_NUM_THREADS=4 // $ ./parabrutfor   #include <stdio.h> #include <stdlib.h> #include <string.h> #include <omp.h> #include <openssl/sha.h>   typedef unsigned char byte;   int matches(byte *a, byte* b) { for (int i = 0; i < 32; i++) if (a[i] != b[i]) return 0; return 1; }     byte* StringHashToByteArray(const char* s) { byte* hash = (byte*) malloc(32); char two[3]; two[2] = 0; for (int i = 0; i < 32; i++) { two[0] = s[i * 2]; two[1] = s[i * 2 + 1]; hash[i] = (byte)strtol(two, 0, 16); } return hash; }   void printResult(byte* password, byte* hash) { char sPass[6]; memcpy(sPass, password, 5); sPass[5] = 0; printf("%s => ", sPass); for (int i = 0; i < SHA256_DIGEST_LENGTH; i++) printf("%02x", hash[i]); printf("\n"); }   int main(int argc, char **argv) {   #pragma omp parallel {   #pragma omp for for (int a = 0; a < 26; a++) { byte password[5] = { 97 + a }; byte* one = StringHashToByteArray("1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad"); byte* two = StringHashToByteArray("3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b"); byte* three = StringHashToByteArray("74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f"); for (password[1] = 97; password[1] < 123; password[1]++) for (password[2] = 97; password[2] < 123; password[2]++) for (password[3] = 97; password[3] < 123; password[3]++) for (password[4] = 97; password[4] < 123; password[4]++) { byte *hash = SHA256(password, 5, 0); if (matches(one, hash) || matches(two, hash) || matches(three, hash)) printResult(password, hash); } free(one); free(two); free(three); } }   return 0; }
http://rosettacode.org/wiki/Parallel_calculations
Parallel calculations
Many programming languages allow you to specify computations to be run in parallel. While Concurrent computing is focused on concurrency, the purpose of this task is to distribute time-consuming calculations on as many CPUs as possible. Assume we have a collection of numbers, and want to find the one with the largest minimal prime factor (that is, the one that contains relatively large factors). To speed up the search, the factorization should be done in parallel using separate threads or processes, to take advantage of multi-core CPUs. Show how this can be formulated in your language. Parallelize the factorization of those numbers, then search the returned list of numbers and factors for the largest minimal factor, and return that number and its prime factors. For the prime number decomposition you may use the solution of the Prime decomposition task.
#C.23
C#
using System; using System.Collections.Generic; using System.Linq;   class Program { public static List<int> PrimeFactors(int number) { var primes = new List<int>(); for (int div = 2; div <= number; div++) { while (number % div == 0) { primes.Add(div); number = number / div; } } return primes; }   static void Main(string[] args) { int[] n = { 12757923, 12878611, 12757923, 15808973, 15780709, 197622519 }; // Calculate each of those numbers' prime factors, in parallel var factors = n.AsParallel().Select(PrimeFactors).ToList(); // Make a new list showing the smallest factor for each var smallestFactors = factors.Select(thisNumbersFactors => thisNumbersFactors.Min()).ToList(); // Find the index that corresponds with the largest of those factors int biggestFactor = smallestFactors.Max(); int whatIndexIsThat = smallestFactors.IndexOf(biggestFactor); Console.WriteLine("{0} has the largest minimum prime factor: {1}", n[whatIndexIsThat], biggestFactor); Console.WriteLine(string.Join(" ", factors[whatIndexIsThat])); } }
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm
Parsing/RPN calculator algorithm
Task Create a stack-based evaluator for an expression in   reverse Polish notation (RPN)   that also shows the changes in the stack as each individual token is processed as a table. Assume an input of a correct, space separated, string of tokens of an RPN expression Test with the RPN expression generated from the   Parsing/Shunting-yard algorithm   task:         3 4 2 * 1 5 - 2 3 ^ ^ / + Print or display the output here Notes   ^   means exponentiation in the expression above.   /   means division. See also   Parsing/Shunting-yard algorithm for a method of generating an RPN from an infix expression.   Several solutions to 24 game/Solve make use of RPN evaluators (although tracing how they work is not a part of that task).   Parsing/RPN to infix conversion.   Arithmetic evaluation.
#ANSI_Standard_BASIC
ANSI Standard BASIC
1000 DECLARE EXTERNAL SUB rpn 1010 PUBLIC NUMERIC R(64)  ! stack 1020 PUBLIC STRING expn$  ! for keyboard input 1030 PUBLIC NUMERIC i, lenn, n, true, false  ! global values 1040 LET true = -1 1050 LET false = 0 1060 DO 1070 PRINT "enter an RPN expression:" 1080 INPUT expn$ 1090 IF LEN( expn$ ) = 0 THEN EXIT DO 1100 PRINT "expn: ";expn$ 1110 CALL rpn( expn$ ) 1120 LOOP 1130 END 1140 ! 1150 ! interpret reverse polish (postfix) expression 1160 EXTERNAL SUB rpn( expn$ ) 1170 DECLARE EXTERNAL FUNCTION is_digit, get_number 1180 DECLARE EXTERNAL SUB print_stack 1190 DECLARE STRING ch$ 1200 LET expn$ = expn$ & " "  ! must terminate line with space 1210 LET lenn = LEN( expn$ ) 1220 LET i = 0 1230 LET n = 1 1240 LET R(n) = 0.0  ! push zero for unary operations 1250 DO 1260 IF i >= lenn THEN EXIT DO  ! at end of line 1270 LET i = i + 1 1280 IF expn$(i:i) <> " " THEN  ! skip white spaces 1290 IF is_digit( expn$(i:i) ) = true THEN  ! push number onto stack 1300 LET n = n + 1 1310 LET R(n) = get_number 1320 CALL print_stack 1330 ELSEIF expn$(i:i) = "+" then  ! add and pop stack 1340 IF n < 2 THEN 1350 PRINT "stack underflow" 1360 ELSE 1370 LET R(n-1) = R(n-1) + R(n) 1380 LET n = n - 1 1390 CALL print_stack 1400 END IF 1410 ELSEIF expn$(i:i) = "-" then  ! subtract and pop stack 1420 IF n < 2 THEN 1430 PRINT "stack underflow" 1440 ELSE 1450 LET R(n-1) = R(n-1) - R(n) 1460 LET n = n - 1 1470 CALL print_stack 1480 END IF 1490 ELSEIF expn$(i:i) = "*" then  ! multiply and pop stack 1500 IF n < 2 THEN 1510 PRINT "stack underflow" 1520 ELSE 1530 LET R(n-1) = R(n-1) * R(n) 1540 LET n = n - 1 1550 CALL print_stack 1560 END IF 1570 ELSEIF expn$(i:i) = "/" THEN  ! divide and pop stack 1580 IF n < 2 THEN 1590 PRINT "stack underflow" 1600 ELSE 1610 LET R(n-1) = R(n-1) / R(n) 1620 LET n = n - 1 1630 CALL print_stack 1640 END IF 1650 ELSEIF expn$(i:i) = "^" THEN  ! raise to power and pop stack 1660 IF n < 2 THEN 1670 PRINT "stack underflow" 1680 ELSE 1690 LET R(n-1) = R(n-1) ^ R(n) 1700 LET n = n - 1 1710 CALL print_stack 1720 END IF 1730 ELSE 1740 PRINT REPEAT$( " ", i+5 ); "^ error" 1750 EXIT DO 1760 END IF 1770 END IF 1780 LOOP 1790 PRINT "result: "; R(n)  ! end of main program 1800 END SUB 1810 ! 1820 ! extract a number from a string 1830 EXTERNAL FUNCTION get_number 1840 DECLARE EXTERNAL FUNCTION is_digit 1850 LET j = 1  ! start of number string 1860 DECLARE STRING number$  ! buffer for conversion 1870 DO  ! get integer part 1880 LET number$(j:j) = expn$(i:i) 1890 LET i = i + 1 1900 LET j = j + 1 1910 IF is_digit( expn$(i:i) ) = false THEN 1920 IF expn$(i:i) = "." then 1930 LET number$(j:j) = expn$(i:i)  ! include decimal point 1940 LET i = i + 1 1950 LET j = j + 1 1960 DO WHILE is_digit( expn$(i:i) ) = true  ! get fractional part 1970 LET number$(j:j) = expn$(i:i) 1980 LET i = i + 1 1990 LET j = j + 1 2000 LOOP 2010 END IF 2020 EXIT DO 2030 END IF 2040 LOOP 2050 LET get_number = VAL( number$ ) 2060 END FUNCTION 2070 ! 2080 ! check for digit character 2090 EXTERNAL FUNCTION is_digit( ch$ ) 2100 IF "0" <= expn$(i:i) AND expn$(i:i) <= "9" THEN 2110 LET is_digit = true 2120 ELSE 2130 LET is_digit = false 2140 END IF 2150 END FUNCTION 2160 ! 2170 EXTERNAL SUB print_stack 2180 PRINT expn$(i:i);" "; 2190 FOR ptr=n TO 2 STEP -1 2200 PRINT USING "-----%.####":R(ptr); 2210 NEXT ptr 2220 PRINT 2230 END SUB
http://rosettacode.org/wiki/Parsing/Shunting-yard_algorithm
Parsing/Shunting-yard algorithm
Task Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output as each individual token is processed. Assume an input of a correct, space separated, string of tokens representing an infix expression Generate a space separated output string representing the RPN Test with the input string: 3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3 print and display the output here. Operator precedence is given in this table: operator precedence associativity operation ^ 4 right exponentiation * 3 left multiplication / 3 left division + 2 left addition - 2 left subtraction Extra credit Add extra text explaining the actions and an optional comment for the action on receipt of each token. Note The handling of functions and arguments is not required. See also Parsing/RPN calculator algorithm for a method of calculating a final value from this output RPN expression. Parsing/RPN to infix conversion.
#C.2B.2B
C++
cl /EHsc /W4 /Ox /std:c++17 /utf-8 a.cpp clang++ -Wall -pedantic-errors -O3 -std=c++17 a.cpp
http://rosettacode.org/wiki/Parsing/Shunting-yard_algorithm
Parsing/Shunting-yard algorithm
Task Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output as each individual token is processed. Assume an input of a correct, space separated, string of tokens representing an infix expression Generate a space separated output string representing the RPN Test with the input string: 3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3 print and display the output here. Operator precedence is given in this table: operator precedence associativity operation ^ 4 right exponentiation * 3 left multiplication / 3 left division + 2 left addition - 2 left subtraction Extra credit Add extra text explaining the actions and an optional comment for the action on receipt of each token. Note The handling of functions and arguments is not required. See also Parsing/RPN calculator algorithm for a method of calculating a final value from this output RPN expression. Parsing/RPN to infix conversion.
#Note_1
Note 1
cl /EHsc /W4 /Ox /std:c++17 /utf-8 a.cpp clang++ -Wall -pedantic-errors -O3 -std=c++17 a.cpp
http://rosettacode.org/wiki/Pascal_matrix_generation
Pascal matrix generation
A pascal matrix is a two-dimensional square matrix holding numbers from   Pascal's triangle,   also known as   binomial coefficients   and which can be shown as   nCr. Shown below are truncated   5-by-5   matrices   M[i, j]   for   i,j   in range   0..4. A Pascal upper-triangular matrix that is populated with   jCi: [[1, 1, 1, 1, 1], [0, 1, 2, 3, 4], [0, 0, 1, 3, 6], [0, 0, 0, 1, 4], [0, 0, 0, 0, 1]] A Pascal lower-triangular matrix that is populated with   iCj   (the transpose of the upper-triangular matrix): [[1, 0, 0, 0, 0], [1, 1, 0, 0, 0], [1, 2, 1, 0, 0], [1, 3, 3, 1, 0], [1, 4, 6, 4, 1]] A Pascal symmetric matrix that is populated with   i+jCi: [[1, 1, 1, 1, 1], [1, 2, 3, 4, 5], [1, 3, 6, 10, 15], [1, 4, 10, 20, 35], [1, 5, 15, 35, 70]] Task Write functions capable of generating each of the three forms of   n-by-n   matrices. Use those functions to display upper, lower, and symmetric Pascal   5-by-5   matrices on this page. The output should distinguish between different matrices and the rows of each matrix   (no showing a list of 25 numbers assuming the reader should split it into rows). Note The   Cholesky decomposition   of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size.
#C.23
C#
using System;   public static class PascalMatrixGeneration { public static void Main() { Print(GenerateUpper(5)); Console.WriteLine(); Print(GenerateLower(5)); Console.WriteLine(); Print(GenerateSymmetric(5)); }   static int[,] GenerateUpper(int size) { int[,] m = new int[size, size]; for (int c = 0; c < size; c++) m[0, c] = 1; for (int r = 1; r < size; r++) { for (int c = r; c < size; c++) { m[r, c] = m[r-1, c-1] + m[r, c-1]; } } return m; }   static int[,] GenerateLower(int size) { int[,] m = new int[size, size]; for (int r = 0; r < size; r++) m[r, 0] = 1; for (int c = 1; c < size; c++) { for (int r = c; r < size; r++) { m[r, c] = m[r-1, c-1] + m[r-1, c]; } } return m; }   static int[,] GenerateSymmetric(int size) { int[,] m = new int[size, size]; for (int i = 0; i < size; i++) m[0, i] = m[i, 0] = 1; for (int r = 1; r < size; r++) { for (int c = 1; c < size; c++) { m[r, c] = m[r-1, c] + m[r, c-1]; } } return m; }   static void Print(int[,] matrix) { string[,] m = ToString(matrix); int width = m.Cast<string>().Select(s => s.Length).Max(); int rows = matrix.GetLength(0), columns = matrix.GetLength(1); for (int row = 0; row < rows; row++) { Console.WriteLine("|" + string.Join(" ", Range(0, columns).Select(column => m[row, column].PadLeft(width, ' '))) + "|"); } }   static string[,] ToString(int[,] matrix) { int rows = matrix.GetLength(0), columns = matrix.GetLength(1); string[,] m = new string[rows, columns]; for (int r = 0; r < rows; r++) { for (int c = 0; c < columns; c++) { m[r, c] = matrix[r, c].ToString(); } } return m; }   }
http://rosettacode.org/wiki/Parameterized_SQL_statement
Parameterized SQL statement
SQL injection Using a SQL update statement like this one (spacing is optional): UPDATE players SET name = 'Smith, Steve', score = 42, active = TRUE WHERE jerseyNum = 99 Non-parameterized SQL is the GoTo statement of database programming. Don't do it, and make sure your coworkers don't either.
#C.23
C#
using System.Data.Sql; using System.Data.SqlClient;   namespace ConsoleApplication1 { class Program { static void Main(string[] args) { SqlConnection tConn = new SqlConnection("ConnectionString");   SqlCommand tCommand = new SqlCommand(); tCommand.Connection = tConn; tCommand.CommandText = "UPDATE players SET name = @name, score = @score, active = @active WHERE jerseyNum = @jerseyNum";   tCommand.Parameters.Add(new SqlParameter("@name", System.Data.SqlDbType.VarChar).Value = "Smith, Steve"); tCommand.Parameters.Add(new SqlParameter("@score", System.Data.SqlDbType.Int).Value = "42"); tCommand.Parameters.Add(new SqlParameter("@active", System.Data.SqlDbType.Bit).Value = true); tCommand.Parameters.Add(new SqlParameter("@jerseyNum", System.Data.SqlDbType.Int).Value = "99");   tCommand.ExecuteNonQuery(); } } }
http://rosettacode.org/wiki/Pascal%27s_triangle
Pascal's triangle
Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is either 1 or the sum of the two elements right above it. For example, the next row of the triangle would be:   1   (since the first element of each row doesn't have two elements above it)   4   (1 + 3)   6   (3 + 3)   4   (3 + 1)   1   (since the last element of each row doesn't have two elements above it) So the triangle now looks like this: 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 Each row   n   (starting with row   0   at the top) shows the coefficients of the binomial expansion of   (x + y)n. Task Write a function that prints out the first   n   rows of the triangle   (with   f(1)   yielding the row consisting of only the element 1). This can be done either by summing elements from the previous rows or using a binary coefficient or combination function. Behavior for   n ≤ 0   does not need to be uniform, but should be noted. See also Evaluate binomial coefficients
#AWK
AWK
$ awk 'BEGIN{for(i=0;i<6;i++){c=1;r=c;for(j=0;j<i;j++){c*=(i-j)/(j+1);r=r" "c};print r}}'
http://rosettacode.org/wiki/Parse_an_IP_Address
Parse an IP Address
The purpose of this task is to demonstrate parsing of text-format IP addresses, using IPv4 and IPv6. Taking the following as inputs: 127.0.0.1 The "localhost" IPv4 address 127.0.0.1:80 The "localhost" IPv4 address, with a specified port (80) ::1 The "localhost" IPv6 address [::1]:80 The "localhost" IPv6 address, with a specified port (80) 2605:2700:0:3::4713:93e3 Rosetta Code's primary server's public IPv6 address [2605:2700:0:3::4713:93e3]:80 Rosetta Code's primary server's public IPv6 address, with a specified port (80) Task Emit each described IP address as a hexadecimal integer representing the address, the address space, and the port number specified, if any. In languages where variant result types are clumsy, the result should be ipv4 or ipv6 address number, something which says which address space was represented, port number and something that says if the port was specified. Example 127.0.0.1   has the address number   7F000001   (2130706433 decimal) in the ipv4 address space. ::ffff:127.0.0.1   represents the same address in the ipv6 address space where it has the address number   FFFF7F000001   (281472812449793 decimal). ::1   has address number   1   and serves the same purpose in the ipv6 address space that   127.0.0.1   serves in the ipv4 address space.
#Haskell
Haskell
import Data.List (isInfixOf) import Numeric (showHex) import Data.Char (isDigit)   data IPChunk = IPv6Chunk String | IPv4Chunk (String, String) | IPv6WithPort [IPChunk] String | IPv6NoPort [IPChunk] | IPv4WithPort IPChunk String | IPv4NoPort IPChunk | IPInvalid | IPZeroSection | IPUndefinedWithPort String | IPUndefinedNoPort   instance Show IPChunk where show (IPv6Chunk a) = a show (IPv4Chunk (a,b)) = a ++ b show (IPv6WithPort a p) = "IPv6 " ++ concatMap show a ++ " port " ++ p show (IPv6NoPort a) = "IPv6 " ++ concatMap show a ++ " no port" show (IPv4WithPort a p) = "IPv4 " ++ show a ++ " port " ++ p show (IPv4NoPort a) = "IPv4 " ++ show a show IPInvalid = "Invalid IP address"   isIPInvalid IPInvalid = True isIPInvalid _ = False   isIPZeroSection IPZeroSection = True isIPZeroSection _ = False   splitOn _ [] = [] splitOn x xs = let (a, b) = break (== x) xs in a : splitOn x (drop 1 b)   count x = length . filter (== x)   between a b x = x >= a && x <= b   none f = all (not . f)   parse1 [] = IPInvalid parse1 "::" = IPUndefinedNoPort parse1 ('[':':':':':']':':':ps) = if portIsValid ps then IPUndefinedWithPort ps else IPInvalid parse1 ('[':xs) = if "]:" `isInfixOf` xs then let (a, b) = break (== ']') xs in if tail b == ":" then IPInvalid else IPv6WithPort (map chunk (splitOn ':' a)) (drop 2 b) else IPInvalid parse1 xs | count ':' xs <= 1 && count '.' xs == 3 = let (a, b) = break (== ':') xs in case b of "" -> IPv4NoPort (chunk a) (':':ps) -> IPv4WithPort (chunk a) ps _ -> IPInvalid | count ':' xs > 1 && count '.' xs <= 3 = IPv6NoPort (map chunk (splitOn ':' xs))   chunk [] = IPZeroSection chunk xs | '.' `elem` xs = case splitOn '.' xs of [a,b,c,d] -> let [e,f,g,h] = map read [a,b,c,d] in if all (between 0 255) [e,f,g,h] then let [i,j,k,l] = map (\n -> fill 2 $ showHex n "") [e,f,g,h] in IPv4Chunk (i ++ j, k ++ l) else IPInvalid | ':' `notElem` xs && between 1 4 (length xs) && all (`elem` "0123456789abcdef") xs = IPv6Chunk (fill 4 xs) | otherwise = IPInvalid   fill n xs = replicate (n - length xs) '0' ++ xs   parse2 IPInvalid = IPInvalid parse2 (IPUndefinedWithPort p) = IPv6WithPort (replicate 8 zeroChunk) p parse2 IPUndefinedNoPort = IPv6NoPort (replicate 8 zeroChunk) parse2 a = case a of IPv6WithPort xs p -> if none isIPInvalid xs && portIsValid p then let ys = complete xs in if countChunks ys == 8 then IPv6WithPort ys p else IPInvalid else IPInvalid IPv6NoPort xs -> if none isIPInvalid xs then let ys = complete xs in if countChunks ys == 8 then IPv6NoPort ys else IPInvalid else IPInvalid IPv4WithPort (IPv4Chunk a) p -> if portIsValid p then IPv4WithPort (IPv4Chunk a) p else IPInvalid IPv4NoPort (IPv4Chunk a) -> IPv4NoPort (IPv4Chunk a) _ -> IPInvalid   zeroChunk = IPv6Chunk "0000"   portIsValid a = all isDigit a && between 0 65535 (read a)   complete xs = case break isIPZeroSection xs of (_, [IPZeroSection]) -> [] (ys, []) -> ys ([], (IPZeroSection:IPZeroSection:ys)) -> if any isIPZeroSection ys || countChunks ys > 7 then [] else replicate (8 - countChunks ys) zeroChunk ++ ys (ys, (IPZeroSection:zs)) -> if any isIPZeroSection zs || countChunks ys + countChunks zs > 7 then [] else ys ++ replicate (8 - countChunks ys - countChunks zs) zeroChunk ++ zs _ -> []   countChunks xs = foldl f 0 xs where f n (IPv4Chunk _) = n + 2 f n (IPv6Chunk _) = n + 1   ip = parse2 . parse1   main = mapM_ (putStrLn . show . ip) ["127.0.0.1", -- loop back "127.0.0.1:80", -- loop back +port "::1", -- loop back "[::1]:80", -- loop back +port "2605:2700:0:3::4713:93e3", -- Rosetta Code "[2605:2700:0:3::4713:93e3]:80"] -- Rosetta Code  
http://rosettacode.org/wiki/Parametric_polymorphism
Parametric polymorphism
Parametric Polymorphism type variables Task Write a small example for a type declaration that is parametric over another type, together with a short bit of code (and its type signature) that uses it. A good example is a container type, let's say a binary tree, together with some function that traverses the tree, say, a map-function that operates on every element of the tree. This language feature only applies to statically-typed languages.
#F.23
F#
  namespace RosettaCode   type BinaryTree<'T> = | Element of 'T | Tree of 'T * BinaryTree<'T> * BinaryTree<'T> member this.Map(f) = match this with | Element(x) -> Element(f x) | Tree(x,left,right) -> Tree((f x), left.Map(f), right.Map(f))
http://rosettacode.org/wiki/Parametric_polymorphism
Parametric polymorphism
Parametric Polymorphism type variables Task Write a small example for a type declaration that is parametric over another type, together with a short bit of code (and its type signature) that uses it. A good example is a container type, let's say a binary tree, together with some function that traverses the tree, say, a map-function that operates on every element of the tree. This language feature only applies to statically-typed languages.
#Fortran
Fortran
MODULE SORTSEARCH !Genuflect towards Prof. D. Knuth.   INTERFACE FIND !Binary chop search, not indexed. MODULE PROCEDURE 1 FINDI4, !I: of integers. 2 FINDF4,FINDF8, !F: of numbers. 3 FINDTTI2,FINDTTI4 !T: of texts. END INTERFACE FIND   CONTAINS INTEGER FUNCTION FINDI4(THIS,NUMB,N) !Binary chopper. Find i such that THIS = NUMB(i) USE ASSISTANCE !Only for the trace stuff. INTENT(IN) THIS,NUMB,N !Imply read-only, but definitely no need for any "copy-back". INTEGER*4 THIS,NUMB(1:*) !Where is THIS in array NUMB(1:N)? INTEGER N !The count. In other versions, it is supplied by the index. INTEGER L,R,P !Fingers. Chop away. L = 0 !Establish outer bounds. R = N + 1 !One before, and one after, the first and last. 1 P = (R - L)/2 !Probe point offset. Beware integer overflow with (L + R)/2. IF (P.LE.0) THEN !Aha! Nowhere! And THIS follows NUMB(L). FINDI4 = -L !Having -L rather than 0 (or other code) might be of interest. RETURN !Finished. END IF !So much for exhaustion. P = P + L !Convert from offset to probe point. IF (THIS - NUMB(P)) 3,4,2 !Compare to the probe point. 2 L = P !Shift the left bound up: THIS follows NUMB(P). GO TO 1 !Another chop. 3 R = P !Shift the right bound down: THIS precedes NUMB(P). GO TO 1 !Try again. Caught it! THIS = NUMB(P) 4 FINDI4 = P !So, THIS is found, here! END FUNCTION FINDI4 !On success, THIS = NUMB(FINDI4); no fancy index here...   END MODULE SORTSEARCH
http://rosettacode.org/wiki/Parsing/RPN_to_infix_conversion
Parsing/RPN to infix conversion
Parsing/RPN to infix conversion You are encouraged to solve this task according to the task description, using any language you may know. Task Create a program that takes an RPN representation of an expression formatted as a space separated sequence of tokens and generates the equivalent expression in infix notation. Assume an input of a correct, space separated, string of tokens Generate a space separated output string representing the same expression in infix notation Show how the major datastructure of your algorithm changes with each new token parsed. Test with the following input RPN strings then print and display the output here. RPN input sample output 3 4 2 * 1 5 - 2 3 ^ ^ / + 3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3 1 2 + 3 4 + ^ 5 6 + ^ ( ( 1 + 2 ) ^ ( 3 + 4 ) ) ^ ( 5 + 6 ) Operator precedence and operator associativity is given in this table: operator precedence associativity operation ^ 4 right exponentiation * 3 left multiplication / 3 left division + 2 left addition - 2 left subtraction See also   Parsing/Shunting-yard algorithm   for a method of generating an RPN from an infix expression.   Parsing/RPN calculator algorithm   for a method of calculating a final value from this output RPN expression.   Postfix to infix   from the RubyQuiz site.
#C.2B.2B
C++
  #include <iostream> #include <stack> #include <string> #include <map> #include <set>   using namespace std;   struct Entry_ { string expr_; string op_; };   bool PrecedenceLess(const string& lhs, const string& rhs, bool assoc) { static const map<string, int> KNOWN({ { "+", 1 }, { "-", 1 }, { "*", 2 }, { "/", 2 }, { "^", 3 } }); static const set<string> ASSOCIATIVE({ "+", "*" }); return (KNOWN.count(lhs) ? KNOWN.find(lhs)->second : 0) < (KNOWN.count(rhs) ? KNOWN.find(rhs)->second : 0) + (assoc && !ASSOCIATIVE.count(rhs) ? 1 : 0); } void Parenthesize(Entry_* old, const string& token, bool assoc) { if (!old->op_.empty() && PrecedenceLess(old->op_, token, assoc)) old->expr_ = '(' + old->expr_ + ')'; }   void AddToken(stack<Entry_>* stack, const string& token) { if (token.find_first_of("0123456789") != string::npos) stack->push(Entry_({ token, string() })); // it's a number, no operator else { // it's an operator if (stack->size() < 2) cout<<"Stack underflow"; auto rhs = stack->top(); Parenthesize(&rhs, token, false); stack->pop(); auto lhs = stack->top(); Parenthesize(&lhs, token, true); stack->top().expr_ = lhs.expr_ + ' ' + token + ' ' + rhs.expr_; stack->top().op_ = token; } }     string ToInfix(const string& src) { stack<Entry_> stack; for (auto start = src.begin(), p = src.begin(); ; ++p) { if (p == src.end() || *p == ' ') { if (p > start) AddToken(&stack, string(start, p)); if (p == src.end()) break; start = p + 1; } } if (stack.size() != 1) cout<<"Incomplete expression"; return stack.top().expr_; }   int main(void) { try { cout << ToInfix("3 4 2 * 1 5 - 2 3 ^ ^ / +") << "\n"; cout << ToInfix("1 2 + 3 4 + ^ 5 6 + ^") << "\n"; return 0; } catch (...) { cout << "Failed\n"; return -1; } }  
http://rosettacode.org/wiki/Partial_function_application
Partial function application
Partial function application   is the ability to take a function of many parameters and apply arguments to some of the parameters to create a new function that needs only the application of the remaining arguments to produce the equivalent of applying all arguments to the original function. E.g: Given values v1, v2 Given f(param1, param2) Then partial(f, param1=v1) returns f'(param2) And f(param1=v1, param2=v2) == f'(param2=v2) (for any value v2) Note that in the partial application of a parameter, (in the above case param1), other parameters are not explicitly mentioned. This is a recurring feature of partial function application. Task Create a function fs( f, s ) that takes a function, f( n ), of one value and a sequence of values s. Function fs should return an ordered sequence of the result of applying function f to every value of s in turn. Create function f1 that takes a value and returns it multiplied by 2. Create function f2 that takes a value and returns it squared. Partially apply f1 to fs to form function fsf1( s ) Partially apply f2 to fs to form function fsf2( s ) Test fsf1 and fsf2 by evaluating them with s being the sequence of integers from 0 to 3 inclusive and then the sequence of even integers from 2 to 8 inclusive. Notes In partially applying the functions f1 or f2 to fs, there should be no explicit mention of any other parameters to fs, although introspection of fs within the partial applicator to find its parameters is allowed. This task is more about how results are generated rather than just getting results.
#Egison
Egison
  (define $fs (map $1 $2))   (define $f1 (* $ 2)) (define $f2 (power $ 2))   (define $fsf1 (fs f1 $)) (define $fsf2 (fs f2 $))   (test (fsf1 {0 1 2 3})) (test (fsf2 {0 1 2 3})) (test (fsf1 {2 4 6 8})) (test (fsf2 {2 4 6 8}))  
http://rosettacode.org/wiki/Partial_function_application
Partial function application
Partial function application   is the ability to take a function of many parameters and apply arguments to some of the parameters to create a new function that needs only the application of the remaining arguments to produce the equivalent of applying all arguments to the original function. E.g: Given values v1, v2 Given f(param1, param2) Then partial(f, param1=v1) returns f'(param2) And f(param1=v1, param2=v2) == f'(param2=v2) (for any value v2) Note that in the partial application of a parameter, (in the above case param1), other parameters are not explicitly mentioned. This is a recurring feature of partial function application. Task Create a function fs( f, s ) that takes a function, f( n ), of one value and a sequence of values s. Function fs should return an ordered sequence of the result of applying function f to every value of s in turn. Create function f1 that takes a value and returns it multiplied by 2. Create function f2 that takes a value and returns it squared. Partially apply f1 to fs to form function fsf1( s ) Partially apply f2 to fs to form function fsf2( s ) Test fsf1 and fsf2 by evaluating them with s being the sequence of integers from 0 to 3 inclusive and then the sequence of even integers from 2 to 8 inclusive. Notes In partially applying the functions f1 or f2 to fs, there should be no explicit mention of any other parameters to fs, although introspection of fs within the partial applicator to find its parameters is allowed. This task is more about how results are generated rather than just getting results.
#Elena
Elena
import system'collections; import system'routines; import extensions;   public program() { var partial := (afs,af => (s => afs(af, s)));   var fs := (f,s => s.selectBy:(x => f(x)).summarize(new ArrayList()).toArray()); var f1 := (x => x * 2); var f2 := (x => x * x);   var fsf1 := partial(fs, f1); var fsf2 := partial(fs, f2);   console.printLine(fsf1(new int[]{2,4,6,8}).toString()); console.printLine(fsf2(new int[]{2,4,6,8}).toString()) }
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
#Nim
Nim
import math, sugar   const N = 100_000   # Fill a sieve of Erathostenes. var isPrime {.noInit.}: array[2..N, bool] for item in isPrime.mitems: item = true for n in 2..int(sqrt(N.toFloat)): if isPrime[n]: for k in countup(n * n, N, n): isPrime[k] = false   # Build list of primes. let primes = collect(newSeq): for n in 2..N: if isPrime[n]: n     proc partition(n, k: int; start = 0): seq[int] = ## Partition "n" in "k" primes starting at position "start" in "primes". ## Return the list of primes or an empty list if partitionning is impossible.   if k == 1: return if isPrime[n] and n >= primes[start]: @[n] else: @[]   for i in start..primes.high: let a = primes[i] if n - a <= 1: break result = partition(n - a, k - 1, i + 1) if result.len != 0: return a & result     when isMainModule:   import strutils   func plural(k: int): string = if k <= 1: "" else: "s"   for (n, k) in [(99809, 1), (18, 2), (19, 3), (20, 4), (2017, 24), (22699, 1), (22699, 2), (22699, 3), (22699, 4), (40355, 3)]: let part = partition(n, k) if part.len == 0: echo n, " cannot be partitionned into ", k, " prime", plural(k) else: echo n, " = ", part.join(" + ")
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
#PARI.2FGP
PARI/GP
partDistinctPrimes(x,n,mn=2)= { if(n==1, return(if(isprime(x) && mn<=x, [x], 0))); if((x-n)%2, if(mn>2, return(0)); my(t=partDistinctPrimes(x-2,n-1,3)); return(if(t, concat(2,t), 0)) ); if(n==2, forprime(p=mn,(x-1)\2, if(isprime(x-p), return([p,x-p])) ); return(0) ); if(n<1, return(if(n, 0, [])));   \\ x is the sum of 3 or more odd primes my(t); forprime(p=mn,(x-1)\n, t=partDistinctPrimes(x-p,n-1,p+2); if(t, return(concat(p,t))) ); 0; } displayNicely(x,n)= { printf("Partitioned%6d with%3d prime", x, n); if(n!=1, print1("s")); my(t=partDistinctPrimes(x,n)); if(t===0, print(": (not possible)"); return); if(#t, print1(": "t[1])); for(i=2,#t, print1("+"t[i])); print(); } V=[[99809,1], [18,2], [19,3], [20,4], [2017,24], [22699,1], [22699,2], [22699,3], [22699,4], [40355,3]]; for(i=1,#V, call(displayNicely, V[i]))
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
#Python
Python
from itertools import islice   def posd(): "diff between position numbers. 1, 2, 3... interleaved with 3, 5, 7..." count, odd = 1, 3 while True: yield count yield odd count, odd = count + 1, odd + 2   def pos_gen(): "position numbers. 1 3 2 5 7 4 9 ..." val = 1 diff = posd() while True: yield val val += next(diff)   def plus_minus(): "yield (list_offset, sign) or zero for Partition calc" n, sign = 0, [1, 1] p_gen = pos_gen() out_on = next(p_gen) while True: n += 1 if n == out_on: next_sign = sign.pop(0) if not sign: sign = [-next_sign] * 2 yield -n, next_sign out_on = next(p_gen) else: yield 0   def part(n): "Partition numbers" p = [1] p_m = plus_minus() mods = [] for _ in range(n): next_plus_minus = next(p_m) if next_plus_minus: mods.append(next_plus_minus) p.append(sum(p[offset] * sign for offset, sign in mods)) return p[-1]   print("(Intermediaries):") print(" posd:", list(islice(posd(), 10))) print(" pos_gen:", list(islice(pos_gen(), 10))) print(" plus_minus:", list(islice(plus_minus(), 15))) print("\nPartitions:", [part(x) for x in range(15)])
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.
#PARI.2FGP
PARI/GP
  Pascals_triangle_puzzle(topvalue=151,leftsidevalue=40,bottomvalue1=11,bottomvalue2=4) = { y=(topvalue-(4*(bottomvalue1+bottomvalue2)))/7; x=leftsidevalue-(y+2*bottomvalue1); z=y-x; print(x","y","z); }  
http://rosettacode.org/wiki/Peaceful_chess_queen_armies
Peaceful chess queen armies
In chess, a queen attacks positions from where it is, in straight lines up-down and left-right as well as on both its diagonals. It attacks only pieces not of its own colour. ⇖ ⇑ ⇗ ⇐ ⇐ ♛ ⇒ ⇒ ⇙ ⇓ ⇘ ⇙ ⇓ ⇘ ⇓ The goal of Peaceful chess queen armies is to arrange m black queens and m white queens on an n-by-n square grid, (the board), so that no queen attacks another of a different colour. Task Create a routine to represent two-colour queens on a 2-D board. (Alternating black/white background colours, Unicode chess pieces and other embellishments are not necessary, but may be used at your discretion). Create a routine to generate at least one solution to placing m equal numbers of black and white queens on an n square board. Display here results for the m=4, n=5 case. References Peaceably Coexisting Armies of Queens (Pdf) by Robert A. Bosch. Optima, the Mathematical Programming Socity newsletter, issue 62. A250000 OEIS
#Wren
Wren
import "/dynamic" for Enum, Tuple   var Piece = Enum.create("Piece", ["empty", "black", "white"])   var Pos = Tuple.create("Pos", ["x", "y"])   var isAttacking = Fn.new { |q, pos| return q.x == pos.x || q.y == pos.y || (q.x - pos.x).abs == (q.y - pos.y).abs }   var place // recursive place = Fn.new { |m, n, blackQueens, whiteQueens| if (m == 0) return true var placingBlack = true for (i in 0...n) { for (j in 0...n) { var pos = Pos.new(i, j) var inner = false for (queen in blackQueens) { var equalPos = queen.x == pos.x && queen.y == pos.y if (equalPos || !placingBlack && isAttacking.call(queen, pos)) { inner = true break } } if (!inner) { for (queen in whiteQueens) { var equalPos = queen.x == pos.x && queen.y == pos.y if (equalPos || placingBlack && isAttacking.call(queen, pos)) { inner = true break } } if (!inner) { if (placingBlack) { blackQueens.add(pos) placingBlack = false } else { whiteQueens.add(pos) if (place.call(m-1, n, blackQueens, whiteQueens)) return true blackQueens.removeAt(-1) whiteQueens.removeAt(-1) placingBlack = true } } } } } if (!placingBlack) blackQueens.removeAt(-1) return false }   var printBoard = Fn.new { |n, blackQueens, whiteQueens| var board = List.filled(n * n, 0) for (queen in blackQueens) board[queen.x * n + queen.y] = Piece.black for (queen in whiteQueens) board[queen.x * n + queen.y] = Piece.white var i = 0 for (b in board) { if (i != 0 && i%n == 0) System.print() if (b == Piece.black) { System.write("B ") } else if (b == Piece.white) { System.write("W ") } else { var j = (i/n).floor var k = i - j*n if (j%2 == k%2) { System.write("• ") } else { System.write("◦ ") } } i = i + 1 } System.print("\n") }   var nms = [ Pos.new(2, 1), Pos.new(3, 1), Pos.new(3, 2), Pos.new(4, 1), Pos.new(4, 2), Pos.new(4, 3), Pos.new(5, 1), Pos.new(5, 2), Pos.new(5, 3), Pos.new(5, 4), Pos.new(5, 5), Pos.new(6, 1), Pos.new(6, 2), Pos.new(6, 3), Pos.new(6, 4), Pos.new(6, 5), Pos.new(6, 6), Pos.new(7, 1), Pos.new(7, 2), Pos.new(7, 3), Pos.new(7, 4), Pos.new(7, 5), Pos.new(7, 6), Pos.new(7, 7) ] for (p in nms) { System.print("%(p.y) black and %(p.y) white queens on a %(p.x) x %(p.x) board:") var blackQueens = [] var whiteQueens = [] if (place.call(p.y, p.x, blackQueens, whiteQueens)) { printBoard.call(p.x, blackQueens, whiteQueens) } else { System.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
#JavaScript
JavaScript
String.prototype.shuffle = function() { return this.split('').sort(() => Math.random() - .5).join(''); }   function createPwd(opts = {}) { let len = opts.len || 5, // password length num = opts.num || 1, // number of outputs noSims = opts.noSims == false ? false : true, // exclude similar? out = [], cur, i;   let chars = [ 'abcdefghijkmnopqrstuvwxyz'.split(''), 'ABCDEFGHJKLMNPQRTUVWXY'.split(''), '346789'.split(''), '!"#$%&()*+,-./:;<=>?@[]^_{|}'.split('') ];   if (!noSims) { chars[0].push('l'); chars[1] = chars[1].concat('IOSZ'.split('')); chars[2] = chars[2].concat('1250'.split('')); }   if (len < 4) { console.log('Password length changed to 4 (minimum)'); len = 4; }   while (out.length < num) { cur = ''; // basic requirement for (i = 0; i < 4; i++) cur += chars[i][Math.floor(Math.random() * chars[i].length)];   while (cur.length < len) { let rnd = Math.floor(Math.random() * chars.length); cur += chars[rnd][Math.floor(Math.random() * chars[rnd].length)]; } out.push(cur); }   for (i = 0; i < out.length; i++) out[i] = out[i].shuffle();   if (out.length == 1) return out[0]; return out; }   // testing console.log( createPwd() ); console.log( createPwd( {len: 20}) ); console.log( createPwd( {len: 20, num: 2}) ); console.log( createPwd( {len: 20, num: 2, noSims: false}) );  
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
#Swift
Swift
func perms<T>(var ar: [T]) -> [[T]] { return heaps(&ar, ar.count) }   func heaps<T>(inout ar: [T], n: Int) -> [[T]] { return n == 1 ? [ar] : Swift.reduce(0..<n, [[T]]()) { (var shuffles, i) in shuffles.extend(heaps(&ar, n - 1)) swap(&ar[n % 2 == 0 ? i : 0], &ar[n - 1]) return shuffles } }   perms([1, 2, 3]) // [[1, 2, 3], [2, 1, 3], [3, 1, 2], [1, 3, 2], [2, 3, 1], [3, 2, 1]]
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).
#Rust
Rust
  extern crate rand;   use std::io::{stdin, stdout, Write}; use std::thread; use std::time::Duration;   use rand::Rng;   fn toss_coin<R: Rng>(rng: &mut R, print: bool) -> char { let c = if rng.gen() { 'H' } else { 'T' }; if print { print!("{}", c); stdout().flush().expect("Could not flush stdout"); } c }   fn gen_sequence<R: Rng>(rng: &mut R, seed: Option<&str>) -> String { let mut seq = String::new(); match seed { Some(s) => { let mut iter = s.chars(); let c0 = iter.next().unwrap(); let next = if c0 == 'H' { 'T' } else { 'H' }; seq.push(next); seq.push(c0); seq.push(iter.next().unwrap()); } None => { for _ in 0..3 { seq.push(toss_coin(rng, false)) } } } seq }   fn read_sequence(used_seq: Option<&str>) -> String { let mut seq = String::new(); loop { seq.clear(); println!("Please, enter sequence of 3 coins: H (heads) or T (tails): "); stdin().read_line(&mut seq).expect("failed to read line"); seq = seq.trim().to_uppercase(); // do the cheapest test first if seq.len() == 3 && seq.chars().all(|c| c == 'H' || c == 'T') && seq != used_seq.unwrap_or("") { return seq; }   println!("Please enter correct sequence!"); } }   fn main() { let mut rng = rand::thread_rng();   println!("--Penney's game--"); loop { let useq: String; let aiseq: String; if rng.gen::<bool>() { println!("You choose first!"); useq = read_sequence(None); println!("Your sequence: {}", useq); aiseq = gen_sequence(&mut rng, Some(&useq)); println!("My sequence: {}", aiseq); } else { println!("I choose first!"); aiseq = gen_sequence(&mut rng, None); println!("My sequence: {}", aiseq); useq = read_sequence(Some(&aiseq)); println!("Your sequence: {}", useq); } println!("Tossing coins..."); let mut coins = String::new(); for _ in 0..2 { // toss first 2 coins coins.push(toss_coin(&mut rng, true)); thread::sleep(Duration::from_millis(500)); } loop { coins.push(toss_coin(&mut rng, true)); thread::sleep(Duration::from_millis(500)); if coins.contains(&useq) { println!("\nYou win!"); break; } if coins.contains(&aiseq) { println!("\nI win!"); break; } }   println!(" Play again? 'Y' to play, 'Q' to exit."); let mut input = String::new(); stdin().read_line(&mut input).expect("failed to read line"); match input.trim_start().chars().next().unwrap() { 'Y' | 'y' => continue, _ => break, } } }    
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).
#Tcl
Tcl
package require Tcl 8.6   oo::class create Player { variable who seq seen idx   constructor {name sequence} { set who $name set seq $sequence set seen {} set idx end-[expr {[string length $seq] - 1}] }   method pick {} { return $seq }   method name {} { return $who }   method match {digit} { append seen $digit return [expr {[string range $seen $idx end] eq $seq}] } }   oo::class create HumanPlayer { superclass Player constructor {length {otherPlayersSelection ""}} { fconfigure stdout -buffering none while true { puts -nonewline "What do you pick? (length $length): " if {[gets stdin pick] < 0} exit set pick [regsub -all {[^HT]} [string map {0 H 1 T h H t T} $pick] ""] if {[string length $pick] eq $length} break puts "That's not a legal pick!" } set name "Human" if {[incr ::humans] > 1} {append name " #$::humans"} next $name $pick } }   oo::class create RobotPlayer { superclass Player constructor {length {otherPlayersSelection ""}} { if {$otherPlayersSelection eq ""} { set pick "" for {set i 0} {$i < $length} {incr i} { append pick [lindex {H T} [expr {int(rand()*2)}]] } } else { if {$length != 3} { error "lengths other than 3 not implemented" } lassign [split $otherPlayersSelection ""] a b c set pick [string cat [string map {H T T H} $b] $a $b] } set name "Robot" if {[incr ::robots] > 1} {append name " #$::robots"} puts "$name picks $pick" next $name $pick } }   proc game {length args} { puts "Let's play Penney's Game!"   # instantiate the players set picks {} set players {} while {[llength $args]} { set idx [expr {int(rand()*[llength $args])}] set p [[lindex $args $idx] new $length {*}$picks] set args [lreplace $args $idx $idx] lappend players $p lappend picks [$p pick] }   # sanity check if {[llength $picks] != [llength [lsort -unique $picks]]} { puts "Two players picked the same thing; that's illegal" }   # do the game loop while 1 { set coin [lindex {H T} [expr {int(rand()*2)}]] puts "Coin flip [incr counter] is $coin" foreach p $players { if {[$p match $coin]} { puts "[$p name] has won!" return } } } }   game 3 HumanPlayer RobotPlayer
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.
#Raku
Raku
say '1st: Convergent series'; my @series = 2.FatRat, -4, { 111 - 1130 / $^v + 3000 / ( $^v * $^u ) } ... *; for flat 3..8, 20, 30, 50, 100 -> $n {say "n = {$n.fmt("%3d")} @series[$n-1]"};   say "\n2nd: Chaotic bank society"; sub postfix:<!> (Int $n) { [*] 2..$n } # factorial operator my $years = 25; my $balance = sum map { 1 / FatRat.new($_!) }, 1 .. $years + 15; # Generate e-1 to sufficient precision with a Taylor series put "Starting balance, \$(e-1): \$$balance"; for 1..$years -> $i { $balance = $i * $balance - 1 } printf("After year %d, you will have \$%1.16g in your account.\n", $years, $balance);   print "\n3rd: Rump's example: f(77617.0, 33096.0) = "; sub f (\a, \b) { 333.75*b⁶ + a²*( 11*a²*b² - b⁶ - 121*b⁴ - 2 ) + 5.5*b⁸ + a/(2*b) } say f(77617.0, 33096.0).fmt("%0.16g");
http://rosettacode.org/wiki/Parallel_brute_force
Parallel brute force
Task Find, through brute force, the five-letter passwords corresponding with the following SHA-256 hashes: 1. 1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad 2. 3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b 3. 74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f Your program should naively iterate through all possible passwords consisting only of five lower-case ASCII English letters. It should use concurrent or parallel processing, if your language supports that feature. You may calculate SHA-256 hashes by calling a library or through a custom implementation. Print each matching password, along with its SHA-256 hash. Related task: SHA-256
#C.23
C#
using System; using System.Linq; using System.Text; using System.Threading.Tasks;   class Program { static void Main(string[] args) { Parallel.For(0, 26, a => { byte[] password = new byte[5]; byte[] hash; byte[] one = StringHashToByteArray("1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad"); byte[] two = StringHashToByteArray("3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b"); byte[] three = StringHashToByteArray("74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f"); password[0] = (byte)(97 + a); var sha = System.Security.Cryptography.SHA256.Create(); for (password[1] = 97; password[1] < 123; password[1]++) for (password[2] = 97; password[2] < 123; password[2]++) for (password[3] = 97; password[3] < 123; password[3]++) for (password[4] = 97; password[4] < 123; password[4]++) { hash = sha.ComputeHash(password); if (matches(one, hash) || matches(two, hash) || matches(three, hash)) Console.WriteLine(Encoding.ASCII.GetString(password) + " => " + BitConverter.ToString(hash).ToLower().Replace("-", "")); } }); } static byte[] StringHashToByteArray(string s) { return Enumerable.Range(0, s.Length / 2).Select(i => (byte)Convert.ToInt16(s.Substring(i * 2, 2), 16)).ToArray(); } static bool matches(byte[] a, byte[] b) { for (int i = 0; i < 32; i++) if (a[i] != b[i]) return false; return true; } }
http://rosettacode.org/wiki/Parallel_calculations
Parallel calculations
Many programming languages allow you to specify computations to be run in parallel. While Concurrent computing is focused on concurrency, the purpose of this task is to distribute time-consuming calculations on as many CPUs as possible. Assume we have a collection of numbers, and want to find the one with the largest minimal prime factor (that is, the one that contains relatively large factors). To speed up the search, the factorization should be done in parallel using separate threads or processes, to take advantage of multi-core CPUs. Show how this can be formulated in your language. Parallelize the factorization of those numbers, then search the returned list of numbers and factors for the largest minimal factor, and return that number and its prime factors. For the prime number decomposition you may use the solution of the Prime decomposition task.
#C.2B.2B
C++
#include <iostream> #include <iterator> #include <vector> #include <ppl.h> // MSVC++ #include <concurrent_vector.h> // MSVC++   struct Factors { int number; std::vector<int> primes; };   const int data[] = { 12757923, 12878611, 12878893, 12757923, 15808973, 15780709, 197622519 };   int main() { // concurrency-safe container replaces std::vector<> Concurrency::concurrent_vector<Factors> results;   // parallel algorithm replaces std::for_each() Concurrency::parallel_for_each(std::begin(data), std::end(data), [&](int n) { Factors factors; factors.number = n; for (int f = 2; n > 1; ++f) { while (n % f == 0) { factors.primes.push_back(f); n /= f; } } results.push_back(factors); // add factorization to results }); // end of parallel calculations   // find largest minimal prime factor in results auto max = std::max_element(results.begin(), results.end(), [](const Factors &a, const Factors &b) { return a.primes.front() < b.primes.front(); });   // print number(s) and factorization std::for_each(results.begin(), results.end(), [&](const Factors &f) { if (f.primes.front() == max->primes.front()) { std::cout << f.number << " = [ "; std::copy(f.primes.begin(), f.primes.end(), std::ostream_iterator<int>(std::cout, " ")); std::cout << "]\n"; } }); return 0; }
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm
Parsing/RPN calculator algorithm
Task Create a stack-based evaluator for an expression in   reverse Polish notation (RPN)   that also shows the changes in the stack as each individual token is processed as a table. Assume an input of a correct, space separated, string of tokens of an RPN expression Test with the RPN expression generated from the   Parsing/Shunting-yard algorithm   task:         3 4 2 * 1 5 - 2 3 ^ ^ / + Print or display the output here Notes   ^   means exponentiation in the expression above.   /   means division. See also   Parsing/Shunting-yard algorithm for a method of generating an RPN from an infix expression.   Several solutions to 24 game/Solve make use of RPN evaluators (although tracing how they work is not a part of that task).   Parsing/RPN to infix conversion.   Arithmetic evaluation.
#ANTLR
ANTLR
  grammar rpnC ; // // rpn Calculator // // Nigel Galloway - April 7th., 2012 // @members { Stack<Double> s = new Stack<Double>(); } rpn : (WS* (num|op) (WS | WS* NEWLINE {System.out.println(s.pop());}))*; num : '-'? Digit+ ('.' Digit+)? {s.push(Double.parseDouble($num.text));}; Digit : '0'..'9'; op : '-' {double x = s.pop(); s.push(s.pop() - x);} | '/' {double x = s.pop(); s.push(s.pop() / x);} | '*' {s.push(s.pop() * s.pop());} | '^' {double x = s.pop(); s.push(Math.pow(s.pop(), x));} | '+' {s.push(s.pop() + s.pop());}; WS : (' ' | '\t'){skip()}; NEWLINE : '\r'? '\n';  
http://rosettacode.org/wiki/Pancake_numbers
Pancake numbers
Adrian Monk has problems and an assistant, Sharona Fleming. Sharona can deal with most of Adrian's problems except his lack of punctuality paying her remuneration. 2 pay checks down and she prepares him pancakes for breakfast. Knowing that he will be unable to eat them unless they are stacked in ascending order of size she leaves him only a skillet which he can insert at any point in the pile and flip all the above pancakes, repeating until the pile is sorted. Sharona has left the pile of n pancakes such that the maximum number of flips is required. Adrian is determined to do this in as few flips as possible. This sequence n->p(n) is known as the Pancake numbers. The task is to determine p(n) for n = 1 to 9, and for each show an example requiring p(n) flips. Sorting_algorithms/Pancake_sort actually performs the sort some giving the number of flips used. How do these compare with p(n)? Few people know p(20), generously I shall award an extra credit for anyone doing more than p(16). References Bill Gates and the pancake problem A058986
#AWK
AWK
  # syntax: GAWK -f PANCAKE_NUMBERS.AWK # converted from C BEGIN { for (i=0; i<4; i++) { for (j=1; j<6; j++) { n = i * 5 + j printf("p(%2d) = %2d ",n,main(n)) } printf("\n") } exit(0) } function main(n, adj,gap,sum) { gap = 2 sum = 2 adj = -1 while (sum < n) { adj++ gap = gap * 2 - 1 sum += gap } return(n + adj) }  
http://rosettacode.org/wiki/Parsing/Shunting-yard_algorithm
Parsing/Shunting-yard algorithm
Task Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output as each individual token is processed. Assume an input of a correct, space separated, string of tokens representing an infix expression Generate a space separated output string representing the RPN Test with the input string: 3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3 print and display the output here. Operator precedence is given in this table: operator precedence associativity operation ^ 4 right exponentiation * 3 left multiplication / 3 left division + 2 left addition - 2 left subtraction Extra credit Add extra text explaining the actions and an optional comment for the action on receipt of each token. Note The handling of functions and arguments is not required. See also Parsing/RPN calculator algorithm for a method of calculating a final value from this output RPN expression. Parsing/RPN to infix conversion.
#Note_2
Note 2
cl /EHsc /W4 /Ox /std:c++17 /utf-8 a.cpp clang++ -Wall -pedantic-errors -O3 -std=c++17 a.cpp
http://rosettacode.org/wiki/Pascal_matrix_generation
Pascal matrix generation
A pascal matrix is a two-dimensional square matrix holding numbers from   Pascal's triangle,   also known as   binomial coefficients   and which can be shown as   nCr. Shown below are truncated   5-by-5   matrices   M[i, j]   for   i,j   in range   0..4. A Pascal upper-triangular matrix that is populated with   jCi: [[1, 1, 1, 1, 1], [0, 1, 2, 3, 4], [0, 0, 1, 3, 6], [0, 0, 0, 1, 4], [0, 0, 0, 0, 1]] A Pascal lower-triangular matrix that is populated with   iCj   (the transpose of the upper-triangular matrix): [[1, 0, 0, 0, 0], [1, 1, 0, 0, 0], [1, 2, 1, 0, 0], [1, 3, 3, 1, 0], [1, 4, 6, 4, 1]] A Pascal symmetric matrix that is populated with   i+jCi: [[1, 1, 1, 1, 1], [1, 2, 3, 4, 5], [1, 3, 6, 10, 15], [1, 4, 10, 20, 35], [1, 5, 15, 35, 70]] Task Write functions capable of generating each of the three forms of   n-by-n   matrices. Use those functions to display upper, lower, and symmetric Pascal   5-by-5   matrices on this page. The output should distinguish between different matrices and the rows of each matrix   (no showing a list of 25 numbers assuming the reader should split it into rows). Note The   Cholesky decomposition   of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size.
#C.2B.2B
C++
#include <iostream> #include <vector>   typedef std::vector<std::vector<int>> vv;   vv pascal_upper(int n) { vv matrix(n); for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { if (i > j) matrix[i].push_back(0); else if (i == j || i == 0) matrix[i].push_back(1); else matrix[i].push_back(matrix[i - 1][j - 1] + matrix[i][j - 1]); } } return matrix; }   vv pascal_lower(int n) { vv matrix(n); for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { if (i < j) matrix[i].push_back(0); else if (i == j || j == 0) matrix[i].push_back(1); else matrix[i].push_back(matrix[i - 1][j - 1] + matrix[i - 1][j]); } } return matrix; }   vv pascal_symmetric(int n) { vv matrix(n); for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { if (i == 0 || j == 0) matrix[i].push_back(1); else matrix[i].push_back(matrix[i][j - 1] + matrix[i - 1][j]); } } return matrix; }     void print_matrix(vv matrix) { for (std::vector<int> v: matrix) { for (int i: v) { std::cout << " " << i; } std::cout << std::endl; } }   int main() { std::cout << "PASCAL UPPER MATRIX" << std::endl; print_matrix(pascal_upper(5)); std::cout << "PASCAL LOWER MATRIX" << std::endl; print_matrix(pascal_lower(5)); std::cout << "PASCAL SYMMETRIC MATRIX" << std::endl; print_matrix(pascal_symmetric(5)); }
http://rosettacode.org/wiki/Parameterized_SQL_statement
Parameterized SQL statement
SQL injection Using a SQL update statement like this one (spacing is optional): UPDATE players SET name = 'Smith, Steve', score = 42, active = TRUE WHERE jerseyNum = 99 Non-parameterized SQL is the GoTo statement of database programming. Don't do it, and make sure your coworkers don't either.
#C.2B.2B
C++
#include <QtSql> #include <iostream>   // Command line arguments: data-source user password // Obviously in a real application the password would be obtained in a secure manner.   int main(int argc, char *argv[]) { if (argc != 4) { std::cerr << "Usage: " << argv[0] << " data-source user password\n"; return 1; } QSqlDatabase db = QSqlDatabase::addDatabase("QODBC"); db.setDatabaseName(argv[1]); if (!db.open(argv[2], argv[3])) { auto error = db.lastError(); std::cerr << "Cannot connect to data source: " << error.text().toStdString() << '\n'; } else { std::cout << "Connected to data source.\n"; QSqlQuery query(db); query.prepare("UPDATE players SET name = ?, score = ?, active = ? WHERE jerseyNum = ?"); query.bindValue(0, "Smith, Steve"); query.bindValue(1, 42); query.bindValue(2, true); query.bindValue(3, 99); if (!query.exec()) { auto error = db.lastError(); std::cerr << "Cannot update database: " << error.text().toStdString() << '\n'; } else { std::cout << "Update succeeded.\n"; } } return 0; }
http://rosettacode.org/wiki/Pascal%27s_triangle
Pascal's triangle
Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is either 1 or the sum of the two elements right above it. For example, the next row of the triangle would be:   1   (since the first element of each row doesn't have two elements above it)   4   (1 + 3)   6   (3 + 3)   4   (3 + 1)   1   (since the last element of each row doesn't have two elements above it) So the triangle now looks like this: 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 Each row   n   (starting with row   0   at the top) shows the coefficients of the binomial expansion of   (x + y)n. Task Write a function that prints out the first   n   rows of the triangle   (with   f(1)   yielding the row consisting of only the element 1). This can be done either by summing elements from the previous rows or using a binary coefficient or combination function. Behavior for   n ≤ 0   does not need to be uniform, but should be noted. See also Evaluate binomial coefficients
#BASIC
BASIC
DIM i AS Integer DIM row AS Integer DIM nrows AS Integer DIM values(100) AS Integer   INPUT "Number of rows: "; nrows values(1) = 1 PRINT TAB((nrows)*3);" 1" FOR row = 2 TO nrows PRINT TAB((nrows-row)*3+1); FOR i = row TO 1 STEP -1 values(i) = values(i) + values(i-1) PRINT USING "##### "; values(i); NEXT i PRINT NEXT row
http://rosettacode.org/wiki/Parse_an_IP_Address
Parse an IP Address
The purpose of this task is to demonstrate parsing of text-format IP addresses, using IPv4 and IPv6. Taking the following as inputs: 127.0.0.1 The "localhost" IPv4 address 127.0.0.1:80 The "localhost" IPv4 address, with a specified port (80) ::1 The "localhost" IPv6 address [::1]:80 The "localhost" IPv6 address, with a specified port (80) 2605:2700:0:3::4713:93e3 Rosetta Code's primary server's public IPv6 address [2605:2700:0:3::4713:93e3]:80 Rosetta Code's primary server's public IPv6 address, with a specified port (80) Task Emit each described IP address as a hexadecimal integer representing the address, the address space, and the port number specified, if any. In languages where variant result types are clumsy, the result should be ipv4 or ipv6 address number, something which says which address space was represented, port number and something that says if the port was specified. Example 127.0.0.1   has the address number   7F000001   (2130706433 decimal) in the ipv4 address space. ::ffff:127.0.0.1   represents the same address in the ipv6 address space where it has the address number   FFFF7F000001   (281472812449793 decimal). ::1   has address number   1   and serves the same purpose in the ipv6 address space that   127.0.0.1   serves in the ipv4 address space.
#Icon_and_Unicon
Icon and Unicon
link printf, hexcvt   procedure main() L := ["192.168.0.1", # private "127.0.0.1", # loop back "127.0.0.1:80", # loop back +port "2001:db8:85a3:0:0:8a2e:370:7334", # doc, IPv6 for 555-1234 "2001:db8:85a3::8a2e:370:7334", # doc "::1", # loop back "[::1]:80", # loop back +port "::", # unspecified "::ffff:192.168.0.1", # transition "2605:2700:0:3::4713:93e3", # RC "[2605:2700:0:3::4713:93e3]:80", # RC "::ffff:71.19.147.227", # RC transition "[::ffff:71.19.147.227]:80", # RC transition +port "[2001:db8:85a3:8d3:1319:8a2e:370:7348]:443", # doc +port "256.0.0.0", # invalid "g::1"] # invalid   every x := !L do { if x ? (ip := ipmatch(), port := portmatch(), pos(0)) then { if i := IPv4decode(ip) then printf("%s is the IPv4 address = x'%s'",x,i) else if i := IPv6decode(ip) then printf("%s is the IPv6 address = x'%s'",x,i) else { printf("%s is not a valid IP address\n",x) next } if \port then printf(" port=%s\n",port) else printf("\n") } else printf("%s is not an IP address\n",x) } end     procedure ipmatch() #: match an ip v4/v6 address static c4,c6 initial { c4 := &digits ++ '.' c6 := &digits ++ 'abcdef:' } suspend (="[" || ( (="::ffff:" || tab(many(c4))) | tab(many(c6)) ) || ="]") | ( ="::ffff:" || tab(many(c4))) | tab(many(c6|c4)) end   procedure portmatch() #: match a port number return (=":",0 < (65536 > tab(many(&digits)))) | &null end   procedure IPv4decode(s) #: match IPv4 to hex string s ? ( ip := (0 <= (256 > tab(many(&digits)))), ip *:= 256, =".", ip +:= (0 <= (256 > tab(many(&digits)))), ip *:= 256, =".", ip +:= (0 <= (256 > tab(many(&digits)))), ip *:= 256, =".", ip +:= (0 <= (256 > tab(many(&digits)))), return right(hexstring(ip,,&lcase),8) ) end   procedure IPv6decode(s) #: IPv6 to hex string s ?:= 2(="[", tab(-1), ="]") # remove any [] if find(".",s) then # transitional s ? ( tab(many(':0')), ="ffff:", return right("ffff" || IPv4decode(tab(0)),32,"0") ) else { h := t := "" s ? { while x := tab(find(":")) do { # head if *x <= 4 then h ||:= right(x,4,"0") if ="::" then break else move(1) } while x := tab(find(":")|0) do { # tail if *x <= 4 then t ||:= right(x,4,"0") move(1) | break } if x := h || repl("0",32-(*h+*t)) || t then # and insides return x } } end
http://rosettacode.org/wiki/Parametric_polymorphism
Parametric polymorphism
Parametric Polymorphism type variables Task Write a small example for a type declaration that is parametric over another type, together with a short bit of code (and its type signature) that uses it. A good example is a container type, let's say a binary tree, together with some function that traverses the tree, say, a map-function that operates on every element of the tree. This language feature only applies to statically-typed languages.
#Go
Go
package main   import "fmt"   func average(c intCollection) float64 { var sum, count int c.mapElements(func(n int) { sum += n count++ }) return float64(sum) / float64(count) }   func main() { t1 := new(binaryTree) t2 := new(bTree) a1 := average(t1) a2 := average(t2) fmt.Println("binary tree average:", a1) fmt.Println("b-tree average:", a2) }   type intCollection interface { mapElements(func(int)) }   type binaryTree struct { // dummy representation details left, right bool }   func (t *binaryTree) mapElements(visit func(int)) { // dummy implementation if t.left == t.right { visit(3) visit(1) visit(4) } }   type bTree struct { // dummy representation details buckets int }   func (t *bTree) mapElements(visit func(int)) { // dummy implementation if t.buckets >= 0 { visit(1) visit(5) visit(9) } }
http://rosettacode.org/wiki/Parametric_polymorphism
Parametric polymorphism
Parametric Polymorphism type variables Task Write a small example for a type declaration that is parametric over another type, together with a short bit of code (and its type signature) that uses it. A good example is a container type, let's say a binary tree, together with some function that traverses the tree, say, a map-function that operates on every element of the tree. This language feature only applies to statically-typed languages.
#Groovy
Groovy
class Tree<T> { T value Tree<T> left Tree<T> right   Tree(T value = null, Tree<T> left = null, Tree<T> right = null) { this.value = value this.left = left this.right = right }   void replaceAll(T value) { this.value = value left?.replaceAll(value) right?.replaceAll(value) } }
http://rosettacode.org/wiki/Parsing/RPN_to_infix_conversion
Parsing/RPN to infix conversion
Parsing/RPN to infix conversion You are encouraged to solve this task according to the task description, using any language you may know. Task Create a program that takes an RPN representation of an expression formatted as a space separated sequence of tokens and generates the equivalent expression in infix notation. Assume an input of a correct, space separated, string of tokens Generate a space separated output string representing the same expression in infix notation Show how the major datastructure of your algorithm changes with each new token parsed. Test with the following input RPN strings then print and display the output here. RPN input sample output 3 4 2 * 1 5 - 2 3 ^ ^ / + 3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3 1 2 + 3 4 + ^ 5 6 + ^ ( ( 1 + 2 ) ^ ( 3 + 4 ) ) ^ ( 5 + 6 ) Operator precedence and operator associativity is given in this table: operator precedence associativity operation ^ 4 right exponentiation * 3 left multiplication / 3 left division + 2 left addition - 2 left subtraction See also   Parsing/Shunting-yard algorithm   for a method of generating an RPN from an infix expression.   Parsing/RPN calculator algorithm   for a method of calculating a final value from this output RPN expression.   Postfix to infix   from the RubyQuiz site.
#Common_Lisp
Common Lisp
  ;;;; Parsing/RPN to infix conversion (defstruct (node (:print-function print-node)) opr infix) (defun print-node (node stream depth) (format stream "opr:=~A infix:=\"~A\"" (node-opr node) (node-infix node)))   (defconstant OPERATORS '((#\^ . 4) (#\* . 3) (#\/ . 3) (#\+ . 2) (#\- . 2)))   ;;; (char,char[,boolean])->boolean (defun higher-p (opp opc &optional (left-node-p nil)) (or (> (cdr (assoc opp OPERATORS)) (cdr (assoc opc OPERATORS))) (and left-node-p (char= opp #\^) (char= opc #\^))))   ;;; string->list (defun string-split (expr) (let ((p (position #\Space expr))) (if (null p) (list expr) (append (list (subseq expr 0 p)) (string-split (subseq expr (1+ p)))))))   ;;; string->string (defun parse (expr) (let ((stack '())) (format t "TOKEN STACK~%") (dolist (tok (string-split expr)) (if (assoc (char tok 0) OPERATORS) ; operator? (push (make-node :opr (char tok 0) :infix (infix (char tok 0) (pop stack) (pop stack))) stack) (push tok stack))   ;; print stack at each token (format t "~3,A" tok) (dotimes (i (length stack)) (format t "~8,T[~D] ~A~%" i (nth i stack))))   ;; print final infix expression (if (= (length stack) 1) (format nil "~A" (node-infix (first stack))) (format nil "syntax error in ~A" expr))))   ;;; (char,node,node)->string (defun infix (operator rightn leftn)   ;; (char,node[,boolean]->string (defun string-node (operator anode &optional (left-node-p nil)) (if (stringp anode) anode (if (higher-p operator (node-opr anode) left-node-p) (format nil "( ~A )" (node-infix anode)) (node-infix anode))))   (concatenate 'string (string-node operator leftn t) (format nil " ~A " operator) (string-node operator rightn)))   ;;; nil->[printed infix expressions] (defun main () (let ((expressions '("3 4 2 * 1 5 - 2 3 ^ ^ / +" "1 2 + 3 4 + ^ 5 6 + ^" "3 4 ^ 2 9 ^ ^ 2 5 ^ ^"))) (dolist (expr expressions) (format t "~%Parsing:\"~A\"~%" expr) (format t "RPN:\"~A\" INFIX:\"~A\"~%" expr (parse expr)))))  
http://rosettacode.org/wiki/Partial_function_application
Partial function application
Partial function application   is the ability to take a function of many parameters and apply arguments to some of the parameters to create a new function that needs only the application of the remaining arguments to produce the equivalent of applying all arguments to the original function. E.g: Given values v1, v2 Given f(param1, param2) Then partial(f, param1=v1) returns f'(param2) And f(param1=v1, param2=v2) == f'(param2=v2) (for any value v2) Note that in the partial application of a parameter, (in the above case param1), other parameters are not explicitly mentioned. This is a recurring feature of partial function application. Task Create a function fs( f, s ) that takes a function, f( n ), of one value and a sequence of values s. Function fs should return an ordered sequence of the result of applying function f to every value of s in turn. Create function f1 that takes a value and returns it multiplied by 2. Create function f2 that takes a value and returns it squared. Partially apply f1 to fs to form function fsf1( s ) Partially apply f2 to fs to form function fsf2( s ) Test fsf1 and fsf2 by evaluating them with s being the sequence of integers from 0 to 3 inclusive and then the sequence of even integers from 2 to 8 inclusive. Notes In partially applying the functions f1 or f2 to fs, there should be no explicit mention of any other parameters to fs, although introspection of fs within the partial applicator to find its parameters is allowed. This task is more about how results are generated rather than just getting results.
#F.23
F#
  let fs f s = List.map f s let f1 n = n * 2 let f2 n = n * n   let fsf1 = fs f1 let fsf2 = fs f2   printfn "%A" (fsf1 [0; 1; 2; 3]) printfn "%A" (fsf1 [2; 4; 6; 8]) printfn "%A" (fsf2 [0; 1; 2; 3]) printfn "%A" (fsf2 [2; 4; 6; 8])  
http://rosettacode.org/wiki/Partial_function_application
Partial function application
Partial function application   is the ability to take a function of many parameters and apply arguments to some of the parameters to create a new function that needs only the application of the remaining arguments to produce the equivalent of applying all arguments to the original function. E.g: Given values v1, v2 Given f(param1, param2) Then partial(f, param1=v1) returns f'(param2) And f(param1=v1, param2=v2) == f'(param2=v2) (for any value v2) Note that in the partial application of a parameter, (in the above case param1), other parameters are not explicitly mentioned. This is a recurring feature of partial function application. Task Create a function fs( f, s ) that takes a function, f( n ), of one value and a sequence of values s. Function fs should return an ordered sequence of the result of applying function f to every value of s in turn. Create function f1 that takes a value and returns it multiplied by 2. Create function f2 that takes a value and returns it squared. Partially apply f1 to fs to form function fsf1( s ) Partially apply f2 to fs to form function fsf2( s ) Test fsf1 and fsf2 by evaluating them with s being the sequence of integers from 0 to 3 inclusive and then the sequence of even integers from 2 to 8 inclusive. Notes In partially applying the functions f1 or f2 to fs, there should be no explicit mention of any other parameters to fs, although introspection of fs within the partial applicator to find its parameters is allowed. This task is more about how results are generated rather than just getting results.
#Factor
Factor
USING: kernel math prettyprint sequences ; IN: rosetta-code.partial-function-application   ALIAS: fs map : f1 ( n -- m ) 2 * ; : f2 ( n -- m ) dup * ; : fsf1 ( s -- s' ) [ f1 ] fs ; : fsf2 ( s -- s' ) [ f2 ] fs ;   { 0 1 2 3 } [ fsf1 . ] [ fsf2 . ] bi { 2 4 6 8 } [ fsf1 . ] [ fsf2 . ] bi
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
#Perl
Perl
use ntheory ":all";   sub prime_partition { my($num, $parts) = @_; return is_prime($num) ? [$num] : undef if $parts == 1; my @p = @{primes($num)}; my $r; forcomb { lastfor, $r = [@p[@_]] if vecsum(@p[@_]) == $num; } @p, $parts; $r; }   foreach my $test ([18,2], [19,3], [20,4], [99807,1], [99809,1], [2017,24], [22699,1], [22699,2], [22699,3], [22699,4], [40355,3]) { my $partar = prime_partition(@$test); printf "Partition %5d into %2d prime piece%s %s\n", $test->[0], $test->[1], ($test->[1] == 1) ? ": " : "s:", defined($partar) ? join("+",@$partar) : "not possible"; }
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
#Racket
Racket
#lang racket   (require math/number-theory)   (define σ (let ((memo (make-hash))) (λ (z) (hash-ref! memo z (λ () (apply + (divisors z)))))))   (define p (let ((memo (make-hash '((0 . 1))))) (λ (n) (hash-ref! memo n (λ () (let ((r (if (zero? n) 1 (/ (for/sum ((k (in-range (sub1 n) -1 -1))) (* (σ (- n k)) (p k))) n)))) (when (zero? (modulo n 1000)) (displayln (cons n r) (current-error-port))) r))))))   (map p (range 1 30)) (p 666) (p 1000) (p 10000)
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
#Raku
Raku
my @P = 1, { p(++$) } … *; my @i = lazy [\+] flat 1, ( (1 .. *) Z (1 .. *).map: * × 2 + 1 ); sub p ($n) { sum @P[$n X- @i[^(@i.first: * > $n, :k)]] Z× (flat (1, 1, -1, -1) xx *) }   put @P[^26]; put @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
#REXX
REXX
/*REXX program calculates and displays a specific value (or a range of) partitionsP(N).*/ numeric digits 1000 /*able to handle some ginormous numbers*/ parse arg lo hi . /*obtain optional arguments from the CL*/ if lo=='' | lo=="," then lo= 0 /*Not specified? Then use the default.*/ if hi=='' | hi=="," then hi= lo /* " " " " " " */ @.= 0; @.0= 1; @.1= 1; @.2= 2; @.3= 3; @.4= 5 /*assign default value and low values. */ !.= @.;  !.1= 1; !.3= 1; !.5= 1; !.7= 1; !.9= 1 /*assign default value and even digits.*/ w= length( commas(hi) ) /*W: is used for aligning the index. */   do j=lo to hi /*compute a range of partitionsP. */ say right( commas(j), w) ' ' commas( partP(j) ) end /*j*/ exit 0 /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ commas: parse arg ?; do jc=length(?)-3 to 1 by -3; ?=insert(',', ?, jc); end; return ? /*──────────────────────────────────────────────────────────────────────────────────────*/ partP: procedure expose @. !.; parse arg n /*obtain number (index) for computation*/ if @.n\==0 then return @.n /*Is it already computed? Return it. */ #= 0 /*initialize part P number.*/ do k=1 for n; z= n - (k*3 - 1) * k % 2 /*compute the partition P num*/ if z<0 then leave /*Is Z negative? Then leave.*/ if @.z==0 then x= partP(z) /*use recursion if not known.*/ else x= @.z /*use the pre─computed number*/ z= z - k /*subtract index (K) from Z. */ if z<0 then y= 0 /*Is Z negative? Then set Y=0*/ else if @.z==0 then y= partP(z) /*use recursion if not known.*/ else y= @.z /*use the pre─computed number*/ if k//2 then #= # + x + y /*Odd? Then sum X and Y.*/ else #= # - (x + y) /*Even? " subtract " " " */ end /*k*/ @.n= #; return # /*define and return partitionsP of 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.
#Perl
Perl
# set up triangle my $rows = 5; my @tri = map { [ map { {x=>0,z=>0,v=>0,rhs=>undef} } 1..$_ ] } 1..$rows; $tri[0][0]{rhs} = 151; $tri[2][0]{rhs} = 40; $tri[4][0]{x} = 1; $tri[4][1]{v} = 11; $tri[4][2]{x} = 1; $tri[4][2]{z} = 1; $tri[4][3]{v} = 4; $tri[4][4]{z} = 1;   # aggregate from bottom to top for my $row ( reverse 0..@tri-2 ) { for my $col ( 0..@{$tri[$row]}-1 ){ $tri[$row][$col]{$_} = $tri[$row+1][$col]{$_}+$tri[$row+1][$col+1]{$_} for 'x','z','v'; } } # find equations my @eqn; for my $row ( @tri ) { for my $col ( @$row ){ push @eqn, [ $$col{x}, $$col{z}, $$col{rhs}-$$col{v} ] if defined $$col{rhs}; } } # print equations print "Equations:\n"; print " x + z = y\n"; printf "%d x + %d z = %d\n", @$_ for @eqn; # solve my $f = $eqn[0][1] / $eqn[1][1]; $eqn[0][$_] -= $f * $eqn[1][$_] for 0..2; $f = $eqn[1][0] / $eqn[0][0]; $eqn[1][$_] -= $f * $eqn[0][$_] for 0..2; # print solution print "Solution:\n"; my $x = $eqn[0][2]/$eqn[0][0]; my $z = $eqn[1][2]/$eqn[1][1]; my $y = $x+$z; printf "x=%d, y=%d, z=%d\n", $x, $y, $z;  
http://rosettacode.org/wiki/Peaceful_chess_queen_armies
Peaceful chess queen armies
In chess, a queen attacks positions from where it is, in straight lines up-down and left-right as well as on both its diagonals. It attacks only pieces not of its own colour. ⇖ ⇑ ⇗ ⇐ ⇐ ♛ ⇒ ⇒ ⇙ ⇓ ⇘ ⇙ ⇓ ⇘ ⇓ The goal of Peaceful chess queen armies is to arrange m black queens and m white queens on an n-by-n square grid, (the board), so that no queen attacks another of a different colour. Task Create a routine to represent two-colour queens on a 2-D board. (Alternating black/white background colours, Unicode chess pieces and other embellishments are not necessary, but may be used at your discretion). Create a routine to generate at least one solution to placing m equal numbers of black and white queens on an n square board. Display here results for the m=4, n=5 case. References Peaceably Coexisting Armies of Queens (Pdf) by Robert A. Bosch. Optima, the Mathematical Programming Socity newsletter, issue 62. A250000 OEIS
#zkl
zkl
fcn isAttacked(q, x,y) // ( (r,c), x,y ) : is queen at r,c attacked by q@(x,y)? { r,c:=q; (r==x or c==y or r+c==x+y or r-c==x-y) } fcn isSafe(r,c,qs) // queen safe at (r,c)?, qs=( (r,c),(r,c)..) { ( not qs.filter1(isAttacked,r,c) ) } fcn isEmpty(r,c,qs){ (not (qs and qs.filter1('wrap([(x,y)]){ r==x and c==y })) ) } fcn _peacefulQueens(N,M,qa,qb){ //--> False | (True,((r,c)..),((r,c)..) ) // qa,qb --> // ( (r,c),(r,c).. ), solution so far to last good spot if(qa.len()==M==qb.len()) return(True,qa,qb); n, x,y := N, 0,0; if(qa) x,y = qa[-1]; else n=(N+1)/2; // first queen, first quadrant only foreach r in ([x..n-1]){ foreach c in ([y..n-1]){ if(isEmpty(r,c,qa) and isSafe(r,c,qb)){ qc,qd := qa.append(T(r,c)), self.fcn(N,M, qb,qc); if(qd) return( if(qd[0]==True) qd else T(qc,qd) ); } } y=0 } False }   fcn peacefulQueens(N=5,M=4){ # NxN board, M white and black queens qs:=_peacefulQueens(N,M, T,T); println("Solution for %dx%d board with %d black and %d white queens:".fmt(N,N,M,M)); if(not qs)println("None"); else{ z:=Data(Void,"-"*N*N); foreach r,c in (qs[1]){ z[r*N + c]="W" } foreach r,c in (qs[2]){ z[r*N + c]="B" } z.text.pump(Void,T(Void.Read,N-1),"println"); } }
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
#Julia
Julia
function passgen(len::Integer; simchars::Bool=true)::String if len < 4; error("length must be at least 4") end # Definitions DIGIT = collect('0':'9') UPPER = collect('A':'Z') LOWER = collect('a':'z') OTHER = collect("!\"#\$%&'()*+,-./:;<=>?@[]^_{|}~") if !simchars setdiff!(DIGIT, ['0', '1', '2', '5']) setdiff!(UPPER, ['O', 'I', 'Z', 'S']) setdiff!(LOWER, [ 'l']) end ALL = union(DIGIT, UPPER, LOWER, OTHER)   chars = collect(rand(set) for set in (DIGIT, UPPER, LOWER, OTHER)) len -= 4 append!(chars, rand(ALL, len))   return join(shuffle!(chars)) end   function passgen(io::IO, len::Int=8, npass::Int=1; seed::Int=-1, simchars::Bool=true)::Vector{String} if seed > -1; srand(seed) end passwords = collect(passgen(len; simchars=simchars) for i in 1:npass) writedlm(io, passwords, '\n') return passwords end   passgen(stdout, 10, 12; seed = 1)
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
#Tailspin
Tailspin
  templates permutations when <=1> do [1] ! otherwise def n: $; templates expand def p: $; 1..$n -> \(def k: $; [$p(1..$k-1)..., $n, $p($k..last)...] !\) ! end expand $n - 1 -> permutations -> expand ! end permutations   def alpha: ['ABCD'...]; [ $alpha::length -> permutations -> '$alpha($)...;' ] -> !OUT::write  
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).
#UNIX_Shell
UNIX Shell
#!/bin/bash main() { printf $'Penney\'s Game\n\n' printf 'Flipping to see who goes first ... '   if [[ $(flip) == H ]]; then printf 'I do.\n' p2=$(choose_sequence) printf 'I choose: %s\n' "$p2" else printf 'You do.\n' fi   while true; do read -p 'Enter your three-flip sequence: ' p1 p1=$(tr a-z A-Z <<<"$p1") case "$p1" in "$p2") printf 'Sequence must be different from mine\n';; [HT][HT][HT]) break;; *) printf $'Sequence must be three H\'s or T\'s\n';; esac done   if [ -z "$p2" ]; then p2=$(choose_sequence "$p1") printf 'I choose: %s\n' "$p2" fi   printf '\nHere we go.  %s, you win; %s, I win.\n' "$p1" "$p2" printf 'Flips:'   flips= while true; do flip=$(flip) printf ' %s' "$flip" flips+=$flip case "$flips" in *$p1) printf $'\nYou win!\n'; exit 0;; *$p2) printf $'\nI win!\n'; exit 1;; esac done }   choose_sequence() { local result if (( $# )); then case "$1" in  ?[Hh]?) result=T;; *) result=H;; esac result+="${1%?}" else result=$(flip)$(flip)$(flip) fi printf '%s\n' "$result" }   flip() { if (( RANDOM % 2 )); then printf '%s\n' H else printf '%s\n' T fi }   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).
#VBA
VBA
  Option Explicit   Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long) Private Const HT As String = "H T"   Public Sub PenneysGame() Dim S$, YourSeq$, ComputeSeq$, i&, Seq$, WhoWin$, flag As Boolean   Do S = WhoWillBeFirst(Choice("Who will be first")) If S = "ABORT" Then Exit Do Debug.Print S; " start" YourSeq = Choice("Your sequence", 3) If YourSeq Like "*ABORT*" Then Exit Do Debug.Print "Your sequence : " & YourSeq ComputeSeq = vbNullString For i = 1 To 3 ComputeSeq = ComputeSeq & Random Next i Debug.Print "Computer sequence : " & ComputeSeq Seq = vbNullString Do Seq = Seq & Random Debug.Print Seq Sleep 1000 Loop While Not Winner(ComputeSeq, YourSeq, Seq, WhoWin) Debug.Print WhoWin; " win" If MsgBox(WhoWin & " win" & vbCrLf & "Play again?", vbYesNo) = vbNo Then flag = True Debug.Print "" Loop While Not flag Debug.Print "Game over" End Sub   Private Function WhoWillBeFirst(YourChoice As String) As String Dim S$ S = Random Select Case YourChoice Case "ABORT": WhoWillBeFirst = YourChoice Case Else: WhoWillBeFirst = IIf(S = YourChoice, "You", "Computer") End Select End Function   Private Function Choice(Title As String, Optional Seq As Integer) As String Dim S$, i&, t$ If Seq = 0 Then Seq = 1 t = Title For i = 1 To Seq S = vbNullString Do S = InputBox("Choose between H or T : ", t) If StrPtr(S) = 0 Then S = "Abort" S = UCase(S) Loop While S <> "H" And S <> "T" And S <> "ABORT" Choice = Choice & S t = Title & " " & Choice If Choice Like "*ABORT*" Then Exit For Next i End Function   Private Function Random() As String Randomize Timer Random = Split(HT, " ")(CInt(Rnd)) End Function   Private Function Winner(Cs$, Ys$, S$, W$) As Boolean If Len(S) < 3 Then Winner = False Else If Right(S, 3) = Cs And Right(S, 3) = Ys Then Winner = True W = "Computer & you" ElseIf Right(S, 3) = Cs And Right(S, 3) <> Ys Then Winner = True W = "Computer" ElseIf Right(S, 3) = Ys And Right(S, 3) <> Cs Then Winner = True W = "You" End If End If End Function
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.
#REXX
REXX
/*REXX pgm (pathological FP problem): a sequence that might converge to a wrong limit. */ parse arg digs show . /*obtain optional arguments from the CL*/ if digs=='' | digs=="," then digs= 150 /*Not specified? Then use the default.*/ if show=='' | show=="," then show= 20 /* " " " " " " */ numeric digits digs /*have REXX use "digs" decimal digits. */ #= 2 4 5 6 7 8 9 20 30 50 100 /*the indices to display value of V.n */ fin= word(#, words(#) ) /*find the last (largest) index number.*/ w= length(fin) /* " " length (in dec digs) of FIN.*/ v.1= 2 /*the value of the first V element. */ v.2=-4 /* " " " " second " " */ do n=3 to fin; nm1= n-1; nm2= n-2 /*compute some values of the V elements*/ v.n= 111 - 1130/v.nm1 + 3000/(v.nm1*v.nm2) /* " a value of a " element.*/ /*display digs past the dec. point───┐ */ if wordpos(n, #)\==0 then say 'v.'left(n, w) "=" format(v.n, , show) end /*n*/ /*stick a fork in it, we're all done. */
http://rosettacode.org/wiki/Parallel_brute_force
Parallel brute force
Task Find, through brute force, the five-letter passwords corresponding with the following SHA-256 hashes: 1. 1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad 2. 3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b 3. 74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f Your program should naively iterate through all possible passwords consisting only of five lower-case ASCII English letters. It should use concurrent or parallel processing, if your language supports that feature. You may calculate SHA-256 hashes by calling a library or through a custom implementation. Print each matching password, along with its SHA-256 hash. Related task: SHA-256
#C.2B.2B
C++
#include <atomic> #include <cstdio> #include <cstring> #include <future> #include <iostream> #include <sstream> #include <string> #include <vector>   #include <openssl/sha.h>   struct sha256 { unsigned char digest[SHA256_DIGEST_LENGTH]; void compute(const char* str, int len) { SHA256((const unsigned char*)str, len, digest); } bool parse(const std::string& hash) { if (hash.length() != 2 * SHA256_DIGEST_LENGTH) { std::cerr << "Invalid SHA-256 hash\n"; return false; } const char* p = hash.c_str(); for (int i = 0; i < SHA256_DIGEST_LENGTH; ++i, p += 2) { unsigned int x; if (sscanf(p, "%2x", &x) != 1) { std::cerr << "Cannot parse SHA-256 hash\n"; return false; } digest[i] = x; } return true; } };   bool operator==(const sha256& a, const sha256& b) { return memcmp(a.digest, b.digest, SHA256_DIGEST_LENGTH) == 0; }   bool next_password(std::string& passwd, size_t start) { size_t len = passwd.length(); for (size_t i = len - 1; i >= start; --i) { char c = passwd[i]; if (c < 'z') { ++passwd[i]; return true; } passwd[i] = 'a'; } return false; }   class password_finder { public: password_finder(int); void find_passwords(const std::vector<std::string>&);   private: int length; void find_passwords(char); std::vector<std::string> hashes; std::vector<sha256> digests; std::atomic<size_t> count; };   password_finder::password_finder(int len) : length(len) {}   void password_finder::find_passwords(char ch) { std::string passwd(length, 'a'); passwd[0] = ch; sha256 digest; while (count > 0) { digest.compute(passwd.c_str(), length); for (int m = 0; m < hashes.size(); ++m) { if (digest == digests[m]) { --count; std::ostringstream out; out << "password: " << passwd << ", hash: " << hashes[m] << '\n'; std::cout << out.str(); break; } } if (!next_password(passwd, 1)) break; } }   void password_finder::find_passwords(const std::vector<std::string>& h) { hashes = h; digests.resize(hashes.size()); for (int i = 0; i < hashes.size(); ++i) { if (!digests[i].parse(hashes[i])) return; } count = hashes.size(); std::vector<std::future<void>> futures; const int n = 26; for (int i = 0; i < n; ++i) { char c = 'a' + i; futures.push_back( std::async(std::launch::async, [this, c]() { find_passwords(c); })); } }   int main() { std::vector<std::string> hashes{ "1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad", "3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b", "74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f"}; password_finder pf(5); pf.find_passwords(hashes); return 0; }
http://rosettacode.org/wiki/Parallel_calculations
Parallel calculations
Many programming languages allow you to specify computations to be run in parallel. While Concurrent computing is focused on concurrency, the purpose of this task is to distribute time-consuming calculations on as many CPUs as possible. Assume we have a collection of numbers, and want to find the one with the largest minimal prime factor (that is, the one that contains relatively large factors). To speed up the search, the factorization should be done in parallel using separate threads or processes, to take advantage of multi-core CPUs. Show how this can be formulated in your language. Parallelize the factorization of those numbers, then search the returned list of numbers and factors for the largest minimal factor, and return that number and its prime factors. For the prime number decomposition you may use the solution of the Prime decomposition task.
#Clojure
Clojure
(use '[clojure.contrib.lazy-seqs :only [primes]])   (defn lpf [n] [n (or (last (for [p (take-while #(<= (* % %) n) primes)  :when (zero? (rem n p))] p)) 1)])   (->> (range 2 100000) (pmap lpf) (apply max-key second) println time)
http://rosettacode.org/wiki/Parallel_calculations
Parallel calculations
Many programming languages allow you to specify computations to be run in parallel. While Concurrent computing is focused on concurrency, the purpose of this task is to distribute time-consuming calculations on as many CPUs as possible. Assume we have a collection of numbers, and want to find the one with the largest minimal prime factor (that is, the one that contains relatively large factors). To speed up the search, the factorization should be done in parallel using separate threads or processes, to take advantage of multi-core CPUs. Show how this can be formulated in your language. Parallelize the factorization of those numbers, then search the returned list of numbers and factors for the largest minimal factor, and return that number and its prime factors. For the prime number decomposition you may use the solution of the Prime decomposition task.
#Common_Lisp
Common Lisp
(ql:quickload '(lparallel))   (setf lparallel:*kernel* (lparallel:make-kernel 4)) ;; Configure for your system.   (defun factor (n &optional (acc '())) (when (> n 1) (loop with max-d = (isqrt n) for d = 2 then (if (evenp d) (1+ d) (+ d 2)) do (cond ((> d max-d) (return (cons (list n 1) acc))) ((zerop (rem n d)) (return (factor (truncate n d) (if (eq d (caar acc)) (cons (list (caar acc) (1+ (cadar acc))) (cdr acc)) (cons (list d 1) acc)))))))))   (defun max-minimum-factor (numbers) (lparallel:pmap-reduce (lambda (n) (cons n (apply #'min (mapcar #'car (factor n))))) (lambda (a b) (if (> (cdr a) (cdr b)) a b)) numbers))   (defun print-max-factor (pair) (format t "~a has the largest minimum factor ~a~%" (car pair) (cdr pair)))
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm
Parsing/RPN calculator algorithm
Task Create a stack-based evaluator for an expression in   reverse Polish notation (RPN)   that also shows the changes in the stack as each individual token is processed as a table. Assume an input of a correct, space separated, string of tokens of an RPN expression Test with the RPN expression generated from the   Parsing/Shunting-yard algorithm   task:         3 4 2 * 1 5 - 2 3 ^ ^ / + Print or display the output here Notes   ^   means exponentiation in the expression above.   /   means division. See also   Parsing/Shunting-yard algorithm for a method of generating an RPN from an infix expression.   Several solutions to 24 game/Solve make use of RPN evaluators (although tracing how they work is not a part of that task).   Parsing/RPN to infix conversion.   Arithmetic evaluation.
#AutoHotkey
AutoHotkey
evalRPN("3 4 2 * 1 5 - 2 3 ^ ^ / +") evalRPN(s){ stack := [] out := "For RPN expression: '" s "'`r`n`r`nTOKEN`t`tACTION`t`t`tSTACK`r`n" Loop Parse, s If A_LoopField is number t .= A_LoopField else { If t stack.Insert(t) , out .= t "`tPush num onto top of stack`t" stackShow(stack) "`r`n" , t := "" If InStr("+-/*^", l := A_LoopField) { a := stack.Remove(), b := stack.Remove() stack.Insert( l = "+" ? b + a :l = "-" ? b - a :l = "*" ? b * a :l = "/" ? b / a :l = "^" ? b **a :0 ) out .= l "`tApply op " l " to top of stack`t" stackShow(stack) "`r`n" } } r := stack.Remove() out .= "`r`n The final output value is: '" r "'" clipboard := out return r } StackShow(stack){ for each, value in stack out .= A_Space value return subStr(out, 2) }
http://rosettacode.org/wiki/Pancake_numbers
Pancake numbers
Adrian Monk has problems and an assistant, Sharona Fleming. Sharona can deal with most of Adrian's problems except his lack of punctuality paying her remuneration. 2 pay checks down and she prepares him pancakes for breakfast. Knowing that he will be unable to eat them unless they are stacked in ascending order of size she leaves him only a skillet which he can insert at any point in the pile and flip all the above pancakes, repeating until the pile is sorted. Sharona has left the pile of n pancakes such that the maximum number of flips is required. Adrian is determined to do this in as few flips as possible. This sequence n->p(n) is known as the Pancake numbers. The task is to determine p(n) for n = 1 to 9, and for each show an example requiring p(n) flips. Sorting_algorithms/Pancake_sort actually performs the sort some giving the number of flips used. How do these compare with p(n)? Few people know p(20), generously I shall award an extra credit for anyone doing more than p(16). References Bill Gates and the pancake problem A058986
#C
C
#include <stdio.h>   int pancake(int n) { int gap = 2, sum = 2, adj = -1; while (sum < n) { adj++; gap = gap * 2 - 1; sum += gap; } return n + adj; }   int main() { int i, j; for (i = 0; i < 4; i++) { for (j = 1; j < 6; j++) { int n = i * 5 + j; printf("p(%2d) = %2d ", n, pancake(n)); } printf("\n"); } return 0; }
http://rosettacode.org/wiki/Pancake_numbers
Pancake numbers
Adrian Monk has problems and an assistant, Sharona Fleming. Sharona can deal with most of Adrian's problems except his lack of punctuality paying her remuneration. 2 pay checks down and she prepares him pancakes for breakfast. Knowing that he will be unable to eat them unless they are stacked in ascending order of size she leaves him only a skillet which he can insert at any point in the pile and flip all the above pancakes, repeating until the pile is sorted. Sharona has left the pile of n pancakes such that the maximum number of flips is required. Adrian is determined to do this in as few flips as possible. This sequence n->p(n) is known as the Pancake numbers. The task is to determine p(n) for n = 1 to 9, and for each show an example requiring p(n) flips. Sorting_algorithms/Pancake_sort actually performs the sort some giving the number of flips used. How do these compare with p(n)? Few people know p(20), generously I shall award an extra credit for anyone doing more than p(16). References Bill Gates and the pancake problem A058986
#C.2B.2B
C++
#include <iomanip> #include <iostream>   int pancake(int n) { int gap = 2, sum = 2, adj = -1; while (sum < n) { adj++; gap = gap * 2 - 1; sum += gap; } return n + adj; }   int main() { for (int i = 0; i < 4; i++) { for (int j = 1; j < 6; j++) { int n = i * 5 + j; std::cout << "p(" << std::setw(2) << n << ") = " << std::setw(2) << pancake(n) << " "; } std::cout << '\n'; } return 0; }
http://rosettacode.org/wiki/Parsing/Shunting-yard_algorithm
Parsing/Shunting-yard algorithm
Task Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output as each individual token is processed. Assume an input of a correct, space separated, string of tokens representing an infix expression Generate a space separated output string representing the RPN Test with the input string: 3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3 print and display the output here. Operator precedence is given in this table: operator precedence associativity operation ^ 4 right exponentiation * 3 left multiplication / 3 left division + 2 left addition - 2 left subtraction Extra credit Add extra text explaining the actions and an optional comment for the action on receipt of each token. Note The handling of functions and arguments is not required. See also Parsing/RPN calculator algorithm for a method of calculating a final value from this output RPN expression. Parsing/RPN to infix conversion.
#Ceylon
Ceylon
import ceylon.collection {   ArrayList }   abstract class Token(String|Integer data) of IntegerLiteral | Operator | leftParen | rightParen { string => data.string; } class IntegerLiteral(shared Integer integer) extends Token(integer) {} class Operator extends Token {   shared Integer precedence; shared Boolean rightAssoc;   shared new plus extends Token("+") { precedence = 2; rightAssoc = false; } shared new minus extends Token("-") { precedence = 2; rightAssoc = false; } shared new times extends Token("*") { precedence = 3; rightAssoc = false; } shared new divides extends Token("/") { precedence = 3; rightAssoc = false; } shared new power extends Token("^") { precedence = 4; rightAssoc = true; }   shared Boolean below(Operator other) => !rightAssoc && precedence <= other.precedence || rightAssoc && precedence < other.precedence; } object leftParen extends Token("(") {} object rightParen extends Token(")") {}     shared void run() {   function shunt(String input) {   function tokenize(String input) => input.split().map((String element) => switch(element.trimmed) case("(") leftParen case(")") rightParen case("+") Operator.plus case("-") Operator.minus case("*") Operator.times case("/") Operator.divides case("^") Operator.power else IntegerLiteral(parseInteger(element) else 0)); // no error handling   value outputQueue = ArrayList<Token>(); value operatorStack = ArrayList<Token>();   void report(String action) { print("``action.padTrailing(22)`` | ``" ".join(outputQueue).padTrailing(25)`` | ``" ".join(operatorStack).padTrailing(10)``"); }   print("input is ``input``\n"); print("Action | Output Queue | Operators' Stack -----------------------|---------------------------|-----------------");   for(token in tokenize(input)) { switch(token) case(is IntegerLiteral) { outputQueue.offer(token); report("``token`` from input to queue"); } case(leftParen) { operatorStack.push(token); report("``token`` from input to stack"); } case(rightParen){ while(exists top = operatorStack.pop(), top != leftParen) { outputQueue.offer(top); report("``top`` from stack to queue"); } } case(is Operator) { while(exists top = operatorStack.top, is Operator top, token.below(top)) { operatorStack.pop(); outputQueue.offer(top); report("``top`` from stack to queue"); } operatorStack.push(token); report("``token`` from input to stack"); } } while(exists top = operatorStack.pop()) { outputQueue.offer(top); report("``top`` from stack to queue"); } return " ".join(outputQueue); }   value rpn = shunt("3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3"); assert(rpn == "3 4 2 * 1 5 - 2 3 ^ ^ / +"); print("\nthe result is ``rpn``"); }
http://rosettacode.org/wiki/Parsing/Shunting-yard_algorithm
Parsing/Shunting-yard algorithm
Task Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output as each individual token is processed. Assume an input of a correct, space separated, string of tokens representing an infix expression Generate a space separated output string representing the RPN Test with the input string: 3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3 print and display the output here. Operator precedence is given in this table: operator precedence associativity operation ^ 4 right exponentiation * 3 left multiplication / 3 left division + 2 left addition - 2 left subtraction Extra credit Add extra text explaining the actions and an optional comment for the action on receipt of each token. Note The handling of functions and arguments is not required. See also Parsing/RPN calculator algorithm for a method of calculating a final value from this output RPN expression. Parsing/RPN to infix conversion.
#Common_Lisp
Common Lisp
;;;; Parsing/infix to RPN conversion (defconstant operators "^*/+-") (defconstant precedence '(-4 3 3 2 2))   (defun operator-p (op) "string->integer|nil: Returns operator precedence index or nil if not operator." (and (= (length op) 1) (position (char op 0) operators)))   (defun has-priority (op2 op1) "(string,string)->boolean: True if op2 has output priority over op1." (defun prec (op) (nth (operator-p op) precedence)) (or (and (plusp (prec op1)) (<= (prec op1) (abs (prec op2)))) (and (minusp (prec op1)) (< (- (prec op1)) (abs (prec op2))))))   (defun string-split (expr) "string->list: Tokenize a space separated string." (let* ((p (position #\Space expr)) (tok (if p (subseq expr 0 p) expr))) (if p (append (list tok) (string-split (subseq expr (1+ p)))) (list tok))))   (defun classify (tok) "nil|string->symbol: Classify a token." (cond ((null tok) 'NOL) ((operator-p tok) 'OPR) ((string= tok "(") 'LPR) ((string= tok ")") 'RPR) (t 'LIT)))   ;;; transitions when op2 is dont care (defconstant trans1D '((LIT GO) (LPR ENTER))) ;;; transitions when we check op2 also (defconstant trans2D '((OPR ((NOL ENTER) (LPR ENTER) (OPR (lambda (op1 op2) (if (has-priority op2 op1) 'LEAVE 'ENTER))))) (RPR ((NOL "mismatched parentheses") (LPR CLEAR) (OPR LEAVE))) (NOL ((NOL nil) (LPR "mismatched parentheses") (OPR LEAVE)))))   (defun do-signal (op1 op2) "(nil|string,nil|string)->symbol|string|nil: Emit a signal based on state of inputq and opstack. A nil return is a successful lookup (on nil,nil) because all input combinations are specified." (let ((sig (or (cadr (assoc (classify op1) trans1D)) (cadr (assoc (classify op2) (cadr (assoc (classify op1) trans2D))))))) (if (or (null sig) (symbolp sig) (stringp sig)) sig (funcall (coerce sig 'function) op1 op2))))   (defun rpn (expr) "string->string: Parse infix expression into rpn." (format t "TOKEN TOS SIGNAL OPSTACK OUTPUTQ~%")   ;; iterate until both stacks empty (do* ((input (string-split expr)) (opstack nil) (outputq "") (sig (do-signal (first input) (first opstack)) (do-signal (first input) (first opstack)))) ((null sig) ; until ;; print last closing frame (format t "~A~7,T~A~14,T~A~25,T~A~38,T~A~%" nil nil nil opstack outputq) (subseq outputq 1)) ; return final infix expression   ;; print opening frame (format t "~A~7,T~A~14,T" (first input) (first opstack)) (format t (if (stringp sig) "\"~A\"" "~A") sig)   ;; switch state (let ((output (case sig (GO (pop input)) (ENTER (push (pop input) opstack) nil) (LEAVE (pop opstack)) (CLEAR (pop input) (pop opstack) nil) (otherwise (pop input) (pop opstack) (if (stringp sig) sig "unknown signal"))))) (when output (setf outputq (concatenate 'string outputq " " output))))   ;; print closing frame (format t "~25,T~A~38,T~A~%" opstack outputq))) ; end-do   (defun main (&optional (xtra nil)) "nil->[printed rpn expressions]: Main function." (let ((expressions '("3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3" "( ( 1 + 2 ) ^ ( 3 + 4 ) ) ^ ( 5 + 6 )" "( ( 3 ^ 4 ) ^ 2 ^ 9 ) ^ 2 ^ 5" "3 + 4 * ( 5 - 6 ) ) 4 * 9"))) (dolist (expr (if xtra expressions (list (car expressions)))) (format t "~%INFIX:\"~A\"~%" expr) (format t "RPN:\"~A\"~%" (rpn expr)))))  
http://rosettacode.org/wiki/Paraffins
Paraffins
This organic chemistry task is essentially to implement a tree enumeration algorithm. Task Enumerate, without repetitions and in order of increasing size, all possible paraffin molecules (also known as alkanes). Paraffins are built up using only carbon atoms, which has four bonds, and hydrogen, which has one bond.   All bonds for each atom must be used, so it is easiest to think of an alkane as linked carbon atoms forming the "backbone" structure, with adding hydrogen atoms linking the remaining unused bonds. In a paraffin, one is allowed neither double bonds (two bonds between the same pair of atoms), nor cycles of linked carbons.   So all paraffins with   n   carbon atoms share the empirical formula     CnH2n+2 But for all   n ≥ 4   there are several distinct molecules ("isomers") with the same formula but different structures. The number of isomers rises rather rapidly when   n   increases. In counting isomers it should be borne in mind that the four bond positions on a given carbon atom can be freely interchanged and bonds rotated (including 3-D "out of the paper" rotations when it's being observed on a flat diagram),   so rotations or re-orientations of parts of the molecule (without breaking bonds) do not give different isomers.   So what seem at first to be different molecules may in fact turn out to be different orientations of the same molecule. Example With   n = 3   there is only one way of linking the carbons despite the different orientations the molecule can be drawn;   and with   n = 4   there are two configurations:   a   straight   chain:     (CH3)(CH2)(CH2)(CH3)   a branched chain:       (CH3)(CH(CH3))(CH3) Due to bond rotations, it doesn't matter which direction the branch points in. The phenomenon of "stereo-isomerism" (a molecule being different from its mirror image due to the actual 3-D arrangement of bonds) is ignored for the purpose of this task. The input is the number   n   of carbon atoms of a molecule (for instance 17). The output is how many different different paraffins there are with   n   carbon atoms (for instance   24,894   if   n = 17). The sequence of those results is visible in the OEIS entry:     oeis:A00602 number of n-node unrooted quartic trees; number of n-carbon alkanes C(n)H(2n+2) ignoring stereoisomers. The sequence is (the index starts from zero, and represents the number of carbon atoms): 1, 1, 1, 1, 2, 3, 5, 9, 18, 35, 75, 159, 355, 802, 1858, 4347, 10359, 24894, 60523, 148284, 366319, 910726, 2278658, 5731580, 14490245, 36797588, 93839412, 240215803, 617105614, 1590507121, 4111846763, 10660307791, 27711253769, ... Extra credit Show the paraffins in some way. A flat 1D representation, with arrays or lists is enough, for instance: *Main> all_paraffins 1 [CCP H H H H] *Main> all_paraffins 2 [BCP (C H H H) (C H H H)] *Main> all_paraffins 3 [CCP H H (C H H H) (C H H H)] *Main> all_paraffins 4 [BCP (C H H (C H H H)) (C H H (C H H H)), CCP H (C H H H) (C H H H) (C H H H)] *Main> all_paraffins 5 [CCP H H (C H H (C H H H)) (C H H (C H H H)), CCP H (C H H H) (C H H H) (C H H (C H H H)), CCP (C H H H) (C H H H) (C H H H) (C H H H)] *Main> all_paraffins 6 [BCP (C H H (C H H (C H H H))) (C H H (C H H (C H H H))), BCP (C H H (C H H (C H H H))) (C H (C H H H) (C H H H)), BCP (C H (C H H H) (C H H H)) (C H (C H H H) (C H H H)), CCP H (C H H H) (C H H (C H H H)) (C H H (C H H H)), CCP (C H H H) (C H H H) (C H H H) (C H H (C H H H))] Showing a basic 2D ASCII-art representation of the paraffins is better; for instance (molecule names aren't necessary): methane ethane propane isobutane   H H H H H H H H H │ │ │ │ │ │ │ │ │ H ─ C ─ H H ─ C ─ C ─ H H ─ C ─ C ─ C ─ H H ─ C ─ C ─ C ─ H │ │ │ │ │ │ │ │ │ H H H H H H H │ H │ H ─ C ─ H │ H Links   A paper that explains the problem and its solution in a functional language: http://www.cs.wright.edu/~tkprasad/courses/cs776/paraffins-turner.pdf   A Haskell implementation: https://github.com/ghc/nofib/blob/master/imaginary/paraffins/Main.hs   A Scheme implementation: http://www.ccs.neu.edu/home/will/Twobit/src/paraffins.scm   A Fortress implementation:         (this site has been closed) http://java.net/projects/projectfortress/sources/sources/content/ProjectFortress/demos/turnersParaffins0.fss?rev=3005
#11l
11l
V nMax = 250 V nBranches = 4 V rooted = [BigInt(0)] * (nMax + 1) V unrooted = [BigInt(0)] * (nMax + 1) rooted[0] = BigInt(1) rooted[1] = BigInt(1) unrooted[0] = BigInt(1) unrooted[1] = BigInt(1)   F choose(m, k) I k == 1 R m V result = m L(i) 1 .< k result = result * (m + i) I/ (i + 1) R result   F tree(br, n, l, sum, cnt) V s = 0 L(b) br + 1 .. :nBranches s = sum + (b - br) * n I s > :nMax {R}   V c = choose(:rooted[n], b - br) * cnt   I l * 2 < s {:unrooted[s] += c} I b == :nBranches {R}  :rooted[s] += c L(m) (n - 1 .< 0).step(-1) tree(b, m, l, s, c)   F bicenter(s) I (s [&] 1) == 0  :unrooted[s] += :rooted[s I/ 2] * (:rooted[s I/ 2] + 1) I/ 2   L(n) 1 .. nMax tree(0, n, n, 1, BigInt(1)) bicenter(n) print(n‘: ’unrooted[n])
http://rosettacode.org/wiki/Pangram_checker
Pangram checker
Pangram checker You are encouraged to solve this task according to the task description, using any language you may know. A pangram is a sentence that contains all the letters of the English alphabet at least once. For example:   The quick brown fox jumps over the lazy dog. Task Write a function or method to check a sentence to see if it is a   pangram   (or not)   and show its use. Related tasks   determine if a string has all the same characters   determine if a string has all unique characters
#11l
11l
F is_pangram(sentence) R Set(sentence.lowercase().filter(ch -> ch C ‘a’..‘z’)).len == 26   L(sentence) [‘The quick brown fox jumps over the lazy dog.’, ‘The quick brown fox jumped over the lazy dog.’] print(‘'#.' is #.a pangram’.format(sentence, ‘not ’ * !is_pangram(sentence)))
http://rosettacode.org/wiki/Pascal_matrix_generation
Pascal matrix generation
A pascal matrix is a two-dimensional square matrix holding numbers from   Pascal's triangle,   also known as   binomial coefficients   and which can be shown as   nCr. Shown below are truncated   5-by-5   matrices   M[i, j]   for   i,j   in range   0..4. A Pascal upper-triangular matrix that is populated with   jCi: [[1, 1, 1, 1, 1], [0, 1, 2, 3, 4], [0, 0, 1, 3, 6], [0, 0, 0, 1, 4], [0, 0, 0, 0, 1]] A Pascal lower-triangular matrix that is populated with   iCj   (the transpose of the upper-triangular matrix): [[1, 0, 0, 0, 0], [1, 1, 0, 0, 0], [1, 2, 1, 0, 0], [1, 3, 3, 1, 0], [1, 4, 6, 4, 1]] A Pascal symmetric matrix that is populated with   i+jCi: [[1, 1, 1, 1, 1], [1, 2, 3, 4, 5], [1, 3, 6, 10, 15], [1, 4, 10, 20, 35], [1, 5, 15, 35, 70]] Task Write functions capable of generating each of the three forms of   n-by-n   matrices. Use those functions to display upper, lower, and symmetric Pascal   5-by-5   matrices on this page. The output should distinguish between different matrices and the rows of each matrix   (no showing a list of 25 numbers assuming the reader should split it into rows). Note The   Cholesky decomposition   of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size.
#Clojure
Clojure
(defn binomial-coeff [n k] (reduce #(quot (* %1 (inc (- n %2))) %2) 1 (range 1 (inc k))))   (defn pascal-upper [n] (map (fn [i] (map (fn [j] (binomial-coeff j i)) (range n))) (range n)))   (defn pascal-lower [n] (map (fn [i] (map (fn [j] (binomial-coeff i j)) (range n))) (range n)))   (defn pascal-symmetric [n] (map (fn [i] (map (fn [j] (binomial-coeff (+ i j) i)) (range n))) (range n)))   (defn pascal-matrix [n] (println "Upper:") (run! println (pascal-upper n)) (println) (println "Lower:") (run! println (pascal-lower n)) (println) (println "Symmetric:") (run! println (pascal-symmetric n)))
http://rosettacode.org/wiki/Parameterized_SQL_statement
Parameterized SQL statement
SQL injection Using a SQL update statement like this one (spacing is optional): UPDATE players SET name = 'Smith, Steve', score = 42, active = TRUE WHERE jerseyNum = 99 Non-parameterized SQL is the GoTo statement of database programming. Don't do it, and make sure your coworkers don't either.
#Clojure
Clojure
(require '[clojure.java.jdbc :as sql]) ; Using h2database for this simple example. (def db {:classname "org.h2.Driver"  :subprotocol "h2:file"  :subname "db/my-dbname"})   (sql/update! db :players {:name "Smith, Steve" :score 42 :active true} ["jerseyNum = ?" 99])   ; As an alternative to update!, use execute! (sql/execute! db ["UPDATE players SET name = ?, score = ?, active = ? WHERE jerseyNum = ?" "Smith, Steve" 42 true 99])
http://rosettacode.org/wiki/Parameterized_SQL_statement
Parameterized SQL statement
SQL injection Using a SQL update statement like this one (spacing is optional): UPDATE players SET name = 'Smith, Steve', score = 42, active = TRUE WHERE jerseyNum = 99 Non-parameterized SQL is the GoTo statement of database programming. Don't do it, and make sure your coworkers don't either.
#F.23
F#
open System.Data.SqlClient   [<EntryPoint>] let main argv = use tConn = new SqlConnection("ConnectionString")   use tCommand = new SqlCommand() tCommand.Connection <- tConn tCommand.CommandText <- "UPDATE players SET name = @name, score = @score, active = @active WHERE jerseyNum = @jerseyNum"   tCommand.Parameters.Add(SqlParameter("@name", System.Data.SqlDbType.VarChar).Value = box "Smith, Steve") |> ignore tCommand.Parameters.Add(SqlParameter("@score", System.Data.SqlDbType.Int).Value = box 42) |> ignore tCommand.Parameters.Add(SqlParameter("@active", System.Data.SqlDbType.Bit).Value = box true) |> ignore tCommand.Parameters.Add(SqlParameter("@jerseyNum", System.Data.SqlDbType.Int).Value = box 99) |> ignore   tCommand.ExecuteNonQuery() |> ignore 0
http://rosettacode.org/wiki/Pascal%27s_triangle
Pascal's triangle
Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is either 1 or the sum of the two elements right above it. For example, the next row of the triangle would be:   1   (since the first element of each row doesn't have two elements above it)   4   (1 + 3)   6   (3 + 3)   4   (3 + 1)   1   (since the last element of each row doesn't have two elements above it) So the triangle now looks like this: 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 Each row   n   (starting with row   0   at the top) shows the coefficients of the binomial expansion of   (x + y)n. Task Write a function that prints out the first   n   rows of the triangle   (with   f(1)   yielding the row consisting of only the element 1). This can be done either by summing elements from the previous rows or using a binary coefficient or combination function. Behavior for   n ≤ 0   does not need to be uniform, but should be noted. See also Evaluate binomial coefficients
#Batch_File
Batch File
@echo off setlocal enabledelayedexpansion ::The Main Thing... cls echo. set row=15 call :pascal echo. pause exit /b 0 ::/The Main Thing. ::The Functions... :pascal set /a prev=%row%-1 for /l %%I in (0,1,%prev%) do ( set c=1&set r= for /l %%K in (0,1,%row%) do ( if not !c!==0 ( call :numstr !c! set r=!r!!space!!c! ) set /a c=!c!*^(%%I-%%K^)/^(%%K+1^) ) echo !r! ) goto :EOF   :numstr ::This function returns the number of whitespaces to be applied on each numbers. set cnt=0&set proc=%1&set space= :loop set currchar=!proc:~%cnt%,1! if not "!currchar!"=="" set /a cnt+=1&goto loop set /a numspaces=5-!cnt! for /l %%A in (1,1,%numspaces%) do set "space=!space! " goto :EOF ::/The Functions.
http://rosettacode.org/wiki/Parse_an_IP_Address
Parse an IP Address
The purpose of this task is to demonstrate parsing of text-format IP addresses, using IPv4 and IPv6. Taking the following as inputs: 127.0.0.1 The "localhost" IPv4 address 127.0.0.1:80 The "localhost" IPv4 address, with a specified port (80) ::1 The "localhost" IPv6 address [::1]:80 The "localhost" IPv6 address, with a specified port (80) 2605:2700:0:3::4713:93e3 Rosetta Code's primary server's public IPv6 address [2605:2700:0:3::4713:93e3]:80 Rosetta Code's primary server's public IPv6 address, with a specified port (80) Task Emit each described IP address as a hexadecimal integer representing the address, the address space, and the port number specified, if any. In languages where variant result types are clumsy, the result should be ipv4 or ipv6 address number, something which says which address space was represented, port number and something that says if the port was specified. Example 127.0.0.1   has the address number   7F000001   (2130706433 decimal) in the ipv4 address space. ::ffff:127.0.0.1   represents the same address in the ipv6 address space where it has the address number   FFFF7F000001   (281472812449793 decimal). ::1   has address number   1   and serves the same purpose in the ipv6 address space that   127.0.0.1   serves in the ipv4 address space.
#J
J
parseaddr=:3 :0 if. '.' e. y do. if. +./'::' E. y do. parsehybrid y else. parseipv4 y end. else. parseipv6 y end. )   parseipv4=:3 :0 'addr port'=. 2{.<;._2 y,'::' 4,((4#256)#._&".;._1'.',addr),_".port )   parseipv6=:3 :0 'addr port'=. 2{.<;._2 (y-.'['),']]' split=. I. '::' E. addr a1=. 8{. dfh;._2 (split {. addr),8#':' a2=._8{. dfh;._1 (8#':'),split }. addr 6,(65536x#.a1+a2),_".port-.':' )   parsehybrid=:3 :0 'kludge port'=. 2{.<;._2 (tolower y-.'['),']]' addr=. _1 {:: <;._2 kludge,':' assert. (kludge-:'::ffff:',addr) +. kludge-: '::',addr 6,(16bffff00000000+1{parseipv4 addr),_".port-.':' )   fmt=:3 :0 port=. '' ((#y){.'v';'addr';'port')=. y 'ipv',(":v),' ',(hfd addr),(#port)#' ',":port )
http://rosettacode.org/wiki/Parametric_polymorphism
Parametric polymorphism
Parametric Polymorphism type variables Task Write a small example for a type declaration that is parametric over another type, together with a short bit of code (and its type signature) that uses it. A good example is a container type, let's say a binary tree, together with some function that traverses the tree, say, a map-function that operates on every element of the tree. This language feature only applies to statically-typed languages.
#Haskell
Haskell
data Tree a = Empty | Node a (Tree a) (Tree a)   mapTree :: (a -> b) -> Tree a -> Tree b mapTree f Empty = Empty mapTree f (Node x l r) = Node (f x) (mapTree f l) (mapTree f r)
http://rosettacode.org/wiki/Parametric_polymorphism
Parametric polymorphism
Parametric Polymorphism type variables Task Write a small example for a type declaration that is parametric over another type, together with a short bit of code (and its type signature) that uses it. A good example is a container type, let's say a binary tree, together with some function that traverses the tree, say, a map-function that operates on every element of the tree. This language feature only applies to statically-typed languages.
#Icon_and_Unicon
Icon and Unicon
procedure main() bTree := [1, [2, [4, [7]], [5]], [3, [6, [8], [9]]]] mapTree(bTree, write) bTree := [1, ["two", ["four", [7]], [5]], [3, ["six", ["eight"], [9]]]] mapTree(bTree, write) end   procedure mapTree(tree, f) every f(\tree[1]) | mapTree(!tree[2:0], f) end
http://rosettacode.org/wiki/Parametric_polymorphism
Parametric polymorphism
Parametric Polymorphism type variables Task Write a small example for a type declaration that is parametric over another type, together with a short bit of code (and its type signature) that uses it. A good example is a container type, let's say a binary tree, together with some function that traverses the tree, say, a map-function that operates on every element of the tree. This language feature only applies to statically-typed languages.
#Inform_7
Inform 7
Polymorphism is a room.   To find (V - K) in (L - list of values of kind K): repeat with N running from 1 to the number of entries in L: if entry N in L is V: say "Found [V] at entry [N] in [L]."; stop; say "Did not find [V] in [L]."   When play begins: find "needle" in {"parrot", "needle", "rutabaga"}; find 6 in {2, 3, 4}; end the story.
http://rosettacode.org/wiki/Parsing/RPN_to_infix_conversion
Parsing/RPN to infix conversion
Parsing/RPN to infix conversion You are encouraged to solve this task according to the task description, using any language you may know. Task Create a program that takes an RPN representation of an expression formatted as a space separated sequence of tokens and generates the equivalent expression in infix notation. Assume an input of a correct, space separated, string of tokens Generate a space separated output string representing the same expression in infix notation Show how the major datastructure of your algorithm changes with each new token parsed. Test with the following input RPN strings then print and display the output here. RPN input sample output 3 4 2 * 1 5 - 2 3 ^ ^ / + 3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3 1 2 + 3 4 + ^ 5 6 + ^ ( ( 1 + 2 ) ^ ( 3 + 4 ) ) ^ ( 5 + 6 ) Operator precedence and operator associativity is given in this table: operator precedence associativity operation ^ 4 right exponentiation * 3 left multiplication / 3 left division + 2 left addition - 2 left subtraction See also   Parsing/Shunting-yard algorithm   for a method of generating an RPN from an infix expression.   Parsing/RPN calculator algorithm   for a method of calculating a final value from this output RPN expression.   Postfix to infix   from the RubyQuiz site.
#D
D
import std.stdio, std.string, std.array;   void parseRPN(in string e) { enum nPrec = 9; static struct Info { int prec; bool rAssoc; } immutable /*static*/ opa = ["^": Info(4, true), "*": Info(3, false), "/": Info(3, false), "+": Info(2, false), "-": Info(2, false)];   writeln("\nPostfix input: ", e); static struct Sf { int prec; string expr; } Sf[] stack; foreach (immutable tok; e.split()) { writeln("Token: ", tok); if (tok in opa) { immutable op = opa[tok]; immutable rhs = stack.back; stack.popBack(); auto lhs = &stack.back; if (lhs.prec < op.prec || (lhs.prec == op.prec && op.rAssoc)) lhs.expr = "(" ~ lhs.expr ~ ")"; lhs.expr ~= " " ~ tok ~ " "; lhs.expr ~= (rhs.prec < op.prec || (rhs.prec == op.prec && !op.rAssoc)) ? "(" ~ rhs.expr ~ ")" : rhs.expr; lhs.prec = op.prec; } else stack ~= Sf(nPrec, tok); foreach (immutable f; stack) writefln(`  %d "%s"`, f.prec, f.expr); } writeln("Infix result: ", stack[0].expr); }   void main() { foreach (immutable test; ["3 4 2 * 1 5 - 2 3 ^ ^ / +", "1 2 + 3 4 + ^ 5 6 + ^"]) parseRPN(test); }
http://rosettacode.org/wiki/Partial_function_application
Partial function application
Partial function application   is the ability to take a function of many parameters and apply arguments to some of the parameters to create a new function that needs only the application of the remaining arguments to produce the equivalent of applying all arguments to the original function. E.g: Given values v1, v2 Given f(param1, param2) Then partial(f, param1=v1) returns f'(param2) And f(param1=v1, param2=v2) == f'(param2=v2) (for any value v2) Note that in the partial application of a parameter, (in the above case param1), other parameters are not explicitly mentioned. This is a recurring feature of partial function application. Task Create a function fs( f, s ) that takes a function, f( n ), of one value and a sequence of values s. Function fs should return an ordered sequence of the result of applying function f to every value of s in turn. Create function f1 that takes a value and returns it multiplied by 2. Create function f2 that takes a value and returns it squared. Partially apply f1 to fs to form function fsf1( s ) Partially apply f2 to fs to form function fsf2( s ) Test fsf1 and fsf2 by evaluating them with s being the sequence of integers from 0 to 3 inclusive and then the sequence of even integers from 2 to 8 inclusive. Notes In partially applying the functions f1 or f2 to fs, there should be no explicit mention of any other parameters to fs, although introspection of fs within the partial applicator to find its parameters is allowed. This task is more about how results are generated rather than just getting results.
#FunL
FunL
fs = map f1 = (* 2) f2 = (^ 2)   fsf1 = fs.curry( f1 ) fsf2 = fs.curry( f2 )   println( fsf1(0..3) ) println( fsf2(0..3) ) println( fsf1(2..8 by 2) ) println( fsf2(2..8 by 2) )
http://rosettacode.org/wiki/Partial_function_application
Partial function application
Partial function application   is the ability to take a function of many parameters and apply arguments to some of the parameters to create a new function that needs only the application of the remaining arguments to produce the equivalent of applying all arguments to the original function. E.g: Given values v1, v2 Given f(param1, param2) Then partial(f, param1=v1) returns f'(param2) And f(param1=v1, param2=v2) == f'(param2=v2) (for any value v2) Note that in the partial application of a parameter, (in the above case param1), other parameters are not explicitly mentioned. This is a recurring feature of partial function application. Task Create a function fs( f, s ) that takes a function, f( n ), of one value and a sequence of values s. Function fs should return an ordered sequence of the result of applying function f to every value of s in turn. Create function f1 that takes a value and returns it multiplied by 2. Create function f2 that takes a value and returns it squared. Partially apply f1 to fs to form function fsf1( s ) Partially apply f2 to fs to form function fsf2( s ) Test fsf1 and fsf2 by evaluating them with s being the sequence of integers from 0 to 3 inclusive and then the sequence of even integers from 2 to 8 inclusive. Notes In partially applying the functions f1 or f2 to fs, there should be no explicit mention of any other parameters to fs, although introspection of fs within the partial applicator to find its parameters is allowed. This task is more about how results are generated rather than just getting results.
#Go
Go
package main   import "fmt"   // Using a method bound to a function type:   // fn is a simple function taking an integer and returning another. type fn func(int) int   // fs applies fn to each argument returning all results. func (f fn) fs(s ...int) (r []int) { for _, i := range s { r = append(r, f(i)) } return r }   // Two simple functions for demonstration. func f1(i int) int { return i * 2 } func f2(i int) int { return i * i }   // Another way:   // addn returns a function that adds n to a sequence of numbers func addn(n int) func(...int) []int { return func(s ...int) []int { var r []int for _, i := range s { r = append(r, n+i) } return r } }   func main() { // Turning a method into a function bound to it's reciever: fsf1 := fn(f1).fs fsf2 := fn(f2).fs // Or using a function that returns a function: fsf3 := addn(100)   s := []int{0, 1, 2, 3} fmt.Println("For s =", s) fmt.Println(" fsf1:", fsf1(s...)) // Called with a slice fmt.Println(" fsf2:", fsf2(0, 1, 2, 3)) // ... or with individual arguments fmt.Println(" fsf3:", fsf3(0, 1, 2, 3)) fmt.Println(" fsf2(fsf1):", fsf2(fsf1(s...)...))   s = []int{2, 4, 6, 8} fmt.Println("For s =", s) fmt.Println(" fsf1:", fsf1(2, 4, 6, 8)) fmt.Println(" fsf2:", fsf2(s...)) fmt.Println(" fsf3:", fsf3(s...)) fmt.Println(" fsf3(fsf1):", fsf3(fsf1(s...)...)) }
http://rosettacode.org/wiki/Partition_an_integer_x_into_n_primes
Partition an integer x into n primes
Task Partition a positive integer   X   into   N   distinct primes. Or, to put it in another way: Find   N   unique primes such that they add up to   X. Show in the output section the sum   X   and the   N   primes in ascending order separated by plus (+) signs: •   partition 99809 with 1 prime. •   partition 18 with 2 primes. •   partition 19 with 3 primes. •   partition 20 with 4 primes. •   partition 2017 with 24 primes. •   partition 22699 with 1, 2, 3, and 4 primes. •   partition 40355 with 3 primes. The output could/should be shown in a format such as: Partitioned 19 with 3 primes: 3+5+11   Use any spacing that may be appropriate for the display.   You need not validate the input(s).   Use the lowest primes possible;   use  18 = 5+13,   not   18 = 7+11.   You only need to show one solution. This task is similar to factoring an integer. Related tasks   Count in factors   Prime decomposition   Factors of an integer   Sieve of Eratosthenes   Primality by trial division   Factors of a Mersenne number   Factors of a Mersenne number   Sequence of primes by trial division
#Phix
Phix
with javascript_semantics requires("1.0.2") -- (join(fmt)) function partition(integer v, n, idx=0) if n=1 then return iff(is_prime(v)?{v}:0) end if while true do idx += 1 integer np = get_prime(idx) if np>=floor(v/2) then exit end if object res = partition(v-np, n-1, idx) if sequence(res) then res = prepend(res,np) return res end if end while return 0 end function constant tests = {{99809, 1}, {18, 2}, {19, 3}, {20, 4}, {2017, 24}, {22699, 1}, {22699, 2}, {22699, 3}, {22699, 4}, {40355, 3}} for i=1 to length(tests) do integer {v,n} = tests[i] object res = partition(v,n) res = iff(res=0?"not possible":join(res," + ",fmt:="%d")) printf(1,"Partition %d into %d primes: %s\n",{v,n,res}) end for
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
#Rust
Rust
// [dependencies] // rug = "1.11"   use rug::Integer;   fn partitions(n: usize) -> Integer { let mut p = Vec::with_capacity(n + 1); p.push(Integer::from(1)); for i in 1..=n { let mut num = Integer::from(0); let mut k = 1; loop { let mut j = (k * (3 * k - 1)) / 2; if j > i { break; } if (k & 1) == 1 { num += &p[i - j]; } else { num -= &p[i - j]; } j += k; if j > i { break; } if (k & 1) == 1 { num += &p[i - j]; } else { num -= &p[i - j]; } k += 1; } p.push(num); } p[n].clone() }   fn main() { use std::time::Instant; let n = 6666; let now = Instant::now(); let result = partitions(n); let time = now.elapsed(); println!("P({}) = {}", n, result); println!("elapsed time: {} microseconds", time.as_micros()); }
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
#Sidef
Sidef
say partitions(6666) # very fast
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
#Swift
Swift
import BigInt   func partitions(n: Int) -> BigInt { var p = [BigInt(1)]   for i in 1...n { var num = BigInt(0) var k = 1   while true { var j = (k * (3 * k - 1)) / 2   if j > i { break }   if k & 1 == 1 { num += p[i - j] } else { num -= p[i - j] }   j += k   if j > i { break }   if k & 1 == 1 { num += p[i - j] } else { num -= p[i - j] }   k += 1 }   p.append(num) }   return p[n] }   print("partitions(6666) = \(partitions(n: 6666))")
http://rosettacode.org/wiki/Pascal%27s_triangle/Puzzle
Pascal's triangle/Puzzle
This puzzle involves a Pascals Triangle, also known as a Pyramid of Numbers. [ 151] [ ][ ] [40][ ][ ] [ ][ ][ ][ ] [ X][11][ Y][ 4][ Z] Each brick of the pyramid is the sum of the two bricks situated below it. Of the three missing numbers at the base of the pyramid, the middle one is the sum of the other two (that is, Y = X + Z). Task Write a program to find a solution to this puzzle.
#Phix
Phix
-- -- demo\rosetta\Pascal_triangle_Puzzle.exw -- ======================================= -- -- I approached this with a view to solving general pyramid puzzles, not just the one given. -- -- This little ditty converts the pyramid to rules quite nicely, then uses a modified copy -- of solveN() from Solving_coin_problems#Phix to solve those simultaneous equations. -- with javascript_semantics sequence pyramid = {{151}, {"",""}, {40,"",""}, {"","","",""}, {"x",11,"y",4,"z"}} sequence rules = {} -- each cell in the pyramid is either an integer final value or an equation. -- initially the equations are strings, we substitute all with triplets of -- the form {k,x,z} ie k+l*x+m*z, and known values < last row become rules. for r=5 to 1 by -1 do for c=1 to length(pyramid[r]) do object prc = pyramid[r][c], equ if prc="x" then prc = {0,1,0} -- ie 0 + one x elsif prc="y" then prc = {0,1,1} -- ie 0 + one x plus one z elsif prc="z" then prc = {0,0,1} -- ie 0 + one z else if prc="" or r<=4 then -- examples: x+11 is {0,1,0}+{11,0,0} -> {11,1,0}, -- 11+y is {11,0,0}+{0,1,1} -> {11,1,1}, -- 40=""+"" is {40,0,0}={22,2,1} ==> {18,2,1} equ = sq_add(pyramid[r+1][c],pyramid[r+1][c+1]) end if if prc="" then prc = equ else prc = {prc,0,0} if r<=4 then equ[1] = prc[1]-equ[1] rules = append(rules,equ) end if end if end if pyramid[r][c] = prc end for end for ppOpt({pp_Nest,1,pp_StrFmt,2,pp_IntCh,false}) ?"equations" pp(pyramid) ?"rules" pp(rules) -- {18,2,1} === 18=2x+z -- {73,5,6} === 73=5x+6z puts(1,"=====\n") assert(length(rules)==2) -- more work needed!? -- modified copy of solveN() from Solving_coin_problems.exw as promised, a -- bit of a sledgehammer to crack a peanut is the phrase you are looking for: function solveN(sequence rules) -- -- Based on https://mathcs.clarku.edu/~djoyce/ma105/simultaneous.html -- aka the ancient Chinese Jiuzhang suanshu ~100 B.C. (!!) -- -- Example (not related to the task problem): -- rules = {{18,1,1},{38,1,5}}, ie 18==x+y, 38==x+5y -- ==> {13,5}, ie x=13, y=5 -- -- In the elimination phase, both x have multipliers of 1, ie both rii and rij are 1, -- so we can ignore the two sq_mul and just do [sq_sub] (38=x+5y)-(18=x+y)==>(20=4y). -- Obviously therefore y is 5 and substituting backwards x is 13. -- -- Example2 (taken from the task problem): -- rules = {{18,2,1},{73,5,6}}, ie 18==2x+z, 73==5x+6z -- ==> {{18,2,1},{56,0,7}}, ie rules[2]:=rules[2]*2-rules[1]*5 (eliminate) -- ==> {{18,2,1},8}, ie rules[2]:=56/7, aka z:=8 (substitute) -- ==> {{10,2,0},8}, ie rules[1]-=1z (substitute) -- ==> {5,8}, ie rules[1]:=10/2, aka x:=5 (substitute) -- ==> {5,8}, ie x=5, z=8 -- sequence ri, rj integer l = length(rules), rii, rji rules = deep_copy(rules) for i=1 to l do -- successively eliminate (grow lower left triangle of 0s) ri = rules[i] assert(length(ri)=l+1) rii = ri[i+1] assert(rii!=0) -- (see note below) for j=i+1 to l do rj = rules[j] rji = rj[i+1] if rji!=0 then rj = sq_sub(sq_mul(rj,rii),sq_mul(ri,rji)) assert(rj[i+1]==0) -- (job done) rules[j] = rj end if end for end for for i=l to 1 by -1 do -- then substitute each backwards ri = rules[i] rii = ri[1]/ri[i+1] -- (all else should be 0) rules[i] = rii for j=i-1 to 1 by -1 do rj = rules[j] rji = rj[i+1] if rji!=0 then rules[j] = 0 rj[1] -= rji*rii rj[i+1] = 0 rules[j] = rj end if end for end for return rules end function -- Obviously these next two lines directly embody knowledge from the task, and -- would need changing for an even slightly different version of the problem: integer {x,z} = solveN(rules), y = x+z -- (as per task desc) printf(1,"x=%d, y=%d, z=%d\n",{x,y,z}) -- finally evaluate all the equations and print it. for r=1 to length(pyramid) do for c=1 to length(pyramid[r]) do integer {k, l, m} = pyramid[r][c] pyramid[r][c] = k+l*x+m*z end for end for pp(pyramid)
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
#Kotlin
Kotlin
// version 1.1.4-3   import java.util.Random import java.io.File   val r = Random() val rr = Random() // use a separate generator for shuffles val ls = System.getProperty("line.separator")   var lower = "abcdefghijklmnopqrstuvwxyz" var upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" var digit = "0123456789" var other = """!"#$%&'()*+,-./:;<=>?@[]^_{|}~"""   val exclChars = arrayOf( "'I', 'l' and '1'", "'O' and '0' ", "'5' and 'S' ", "'2' and 'Z' " )   fun String.shuffle(): String { val sb = StringBuilder(this) var n = sb.length while (n > 1) { val k = rr.nextInt(n--) val t = sb[n] sb[n] = sb[k] sb[k] = t } return sb.toString() }   fun generatePasswords(pwdLen: Int, pwdNum: Int, toConsole: Boolean, toFile: Boolean) { val sb = StringBuilder() val ll = lower.length val ul = upper.length val dl = digit.length val ol = other.length val tl = ll + ul + dl + ol var fw = if (toFile) File("pwds.txt").writer() else null   if (toConsole) println("\nThe generated passwords are:") for (i in 0 until pwdNum) { sb.setLength(0) sb.append(lower[r.nextInt(ll)]) sb.append(upper[r.nextInt(ul)]) sb.append(digit[r.nextInt(dl)]) sb.append(other[r.nextInt(ol)])   for (j in 0 until pwdLen - 4) { val k = r.nextInt(tl) sb.append(when (k) { in 0 until ll -> lower[k] in ll until ll + ul -> upper[k - ll] in ll + ul until tl - ol -> digit[k - ll - ul] else -> other[tl - 1 - k] }) } var pwd = sb.toString() repeat(5) { pwd = pwd.shuffle() } // shuffle 5 times say if (toConsole) println(" ${"%2d".format(i + 1)}: $pwd") if (toFile) { fw!!.write(pwd) if (i < pwdNum - 1) fw.write(ls) } } if (toFile) { println("\nThe generated passwords have been written to the file pwds.txt") fw!!.close() } }   fun printHelp() { println(""" |This program generates up to 99 passwords of between 5 and 20 characters in |length. | |You will be prompted for the values of all parameters when the program is run |- there are no command line options to memorize. | |The passwords can either be written to the console or to a file (pwds.txt), |or both. | |The passwords must contain at least one each of the following character types: | lower-case letters : a -> z | upper-case letters : A -> Z | digits  : 0 -> 9 | other characters  :  !"#$%&'()*+,-./:;<=>?@[]^_{|}~ | |Optionally, a seed can be set for the random generator |(any non-zero Long integer) otherwise the default seed will be used. |Even if the same seed is set, the passwords won't necessarily be exactly |the same on each run as additional random shuffles are always performed. | |You can also specify that various sets of visually similar characters |will be excluded (or not) from the passwords, namely: Il1 O0 5S 2Z | |Finally, the only command line options permitted are -h and -help which |will display this page and then exit. | |Any other command line parameters will simply be ignored and the program |will be run normally. | """.trimMargin()) }   fun main(args: Array<String>) { if (args.size == 1 && (args[0] == "-h" || args[0] == "-help")) { printHelp() return }   println("Please enter the following and press return after each one")   var pwdLen: Int? do { print(" Password length (5 to 20)  : ") pwdLen = readLine()!!.toIntOrNull() ?: 0 } while (pwdLen !in 5..20)   var pwdNum: Int? do { print(" Number to generate (1 to 99)  : ") pwdNum = readLine()!!.toIntOrNull() ?: 0 } while (pwdNum !in 1..99)   var seed: Long? do { print(" Seed value (0 to use default) : ") seed = readLine()!!.toLongOrNull() } while (seed == null) if (seed != 0L) r.setSeed(seed)   println(" Exclude the following visually similar characters") for (i in 0..3) { var yn: String do { print(" ${exclChars[i]} y/n : ") yn = readLine()!!.toLowerCase() } while (yn != "y" && yn != "n") if (yn == "y") { when (i) { 0 -> { upper = upper.replace("I", "") lower = lower.replace("l", "") digit = digit.replace("1", "") }   1 -> { upper = upper.replace("O", "") digit = digit.replace("0", "") }   2 -> { upper = upper.replace("S", "") digit = digit.replace("5", "") }   3 -> { upper = upper.replace("Z", "") digit = digit.replace("2", "") } } } }   var toConsole: Boolean? do { print(" Write to console y/n : ") val t = readLine()!! toConsole = if (t == "y") true else if (t == "n") false else null } while (toConsole == null)   var toFile: Boolean? = true if (toConsole) { do { print(" Write to file y/n : ") val t = readLine()!! toFile = if (t == "y") true else if (t == "n") false else null } while (toFile == null) }   generatePasswords(pwdLen!!, pwdNum!!, toConsole, toFile!!) }
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
#Tcl
Tcl
package require struct::list   # Make the sequence of digits to be permuted set n [lindex $argv 0] for {set i 1} {$i <= $n} {incr i} {lappend sequence $i}   # Iterate over the permutations, printing as we go struct::list foreachperm p $sequence { puts $p }
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).
#Wren
Wren
import "random" for Random import "io" for Stdin, Stdout import "timer" for Timer import "/str" for Str   var rand = Random.new()   var optimum = { "HHH": "THH", "HHT": "THH", "HTH": "HHT", "HTT": "HHT", "THH": "TTH", "THT": "TTH", "TTH": "HTT", "TTT": "HTT" }   var getUserSequence = Fn.new { System.print("A sequence of three H or T should be entered") var userSeq while (true) { System.write("Enter your sequence: ") Stdout.flush() userSeq = Str.upper(Stdin.readLine()) if (userSeq.count == 3 && userSeq.all { |c| c == "H" || c == "T" }) break } return userSeq }   var getComputerSequence = Fn.new { |userSeq| var compSeq if (userSeq == "") { var chars = List.filled(3, null) for (i in 0..2) chars[i] = (rand.int(2) == 0) ? "T" : "H" compSeq = chars.join() } else { compSeq = optimum[userSeq] } System.print("Computer's sequence: %(compSeq)") return compSeq }   var userSeq var compSeq var r = rand.int(2) if (r == 0) { System.print("You go first") userSeq = getUserSequence.call() System.print() compSeq = getComputerSequence.call(userSeq) } else { System.print("Computer goes first") compSeq = getComputerSequence.call("") System.print() userSeq = getUserSequence.call() } System.print() var coins = "" while (true) { var coin = (rand.int(2) == 0) ? "H" : "T" coins = coins + coin System.print("Coins flipped: %(coins)") var len = coins.count if (len >= 3) { var seq = coins[len-3...len] if (seq == userSeq) { System.print("\nYou win!") return } else if (seq == compSeq) { System.print("\nCompter wins!") return } } Timer.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.
#Ring
Ring
  # Project : Pathological floating point problems   decimals(8) v = list(100) v[1] = 2 v[2] = -4 for n = 3 to 100 v[n] = (111 - 1130 / v[n-1]) + 3000 / (v[n-1] * v[n-2]) if n < 9 or n = 20 or n = 30 or n = 50 or n = 100 see "n = " + n + " " + v[n] + nl ok next  
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.
#Ruby
Ruby
ar = [0, 2, -4] 100.times{ar << (111 - 1130.quo(ar[-1])+ 3000.quo(ar[-1]*ar[-2])) }   [3, 4, 5, 6, 7, 8, 20, 30, 50, 100].each do |n| puts "%3d -> %0.16f" % [n, ar[n]] end  
http://rosettacode.org/wiki/Parallel_brute_force
Parallel brute force
Task Find, through brute force, the five-letter passwords corresponding with the following SHA-256 hashes: 1. 1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad 2. 3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b 3. 74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f Your program should naively iterate through all possible passwords consisting only of five lower-case ASCII English letters. It should use concurrent or parallel processing, if your language supports that feature. You may calculate SHA-256 hashes by calling a library or through a custom implementation. Print each matching password, along with its SHA-256 hash. Related task: SHA-256
#Clojure
Clojure
(ns rosetta.brute-force (:require [clojure.math.combinatorics :refer [selections]]) ;; https://github.com/clojure/math.combinatorics (:import [java.util Arrays] [java.security MessageDigest]))   ;;https://rosettacode.org/wiki/Parallel_Brute_Force   (def targets ;; length = 5 ["1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad" "3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b" "74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f"])   ;; HELPER/UTIL fns ;;=================   (defn digest "Given a byte-array <bs> returns its hash (also a byte-array)." ^bytes [^MessageDigest md ^bytes bs] (.digest md bs))   (defn char-range "Helper fn for easily producing character ranges." [start end] (map char (range (int start) (inc (int end)))))   (def low-case-eng-bytes "Our search-space (all lower case english characters converted to bytes)." (map byte (char-range \a \z)))   (defn hex->bytes "Converts a hex string to a byte-array." ^bytes [^String hex] (let [len (.length hex) ret (byte-array (/ len 2))] (run! (fn [i] (aset ret (/ i 2) ^byte (unchecked-add-int (bit-shift-left (Character/digit (.charAt hex i) 16) 4) (Character/digit (.charAt hex (inc i)) 16)))) (range 0 len 2)) ret))   (defn bytes->hex "Converts a byte-array to a hex string." [^bytes bs] (.toString ^StringBuilder (areduce bs idx ret (StringBuilder.) (doto ret (.append (format "%02x" (aget bs idx)))))))   ;; MAIN LOGIC ;;===========   (defn check-candidate "Checks whether the SHA256 hash of <candidate> (a list of 5 bytes), matches <target>. If it does, returns that hash as a hex-encoded String. Otherwise returns nil." [^bytes target sha256 candidate] (let [candidate-bytes (byte-array candidate) ^bytes candidate-hash (sha256 candidate-bytes)] (when (Arrays/equals target candidate-hash) (let [answer (String. candidate-bytes)] (println "Answer found for:" (bytes->hex candidate-hash) "=>" answer) answer))))   (defn sha256-brute-force "Top level function. Returns a list with the 3 answers." [space hex-hashes] (->> hex-hashes (map hex->bytes) ;; convert the hex strings to bytes (pmap ;; parallel map the checker-fn (fn [target-bytes] (let [message-digest (MessageDigest/getInstance "SHA-256") ;; new digest instance per thread sha256 (partial digest message-digest)] (some (partial check-candidate target-bytes sha256) (selections space 5)))))))  
http://rosettacode.org/wiki/Parallel_calculations
Parallel calculations
Many programming languages allow you to specify computations to be run in parallel. While Concurrent computing is focused on concurrency, the purpose of this task is to distribute time-consuming calculations on as many CPUs as possible. Assume we have a collection of numbers, and want to find the one with the largest minimal prime factor (that is, the one that contains relatively large factors). To speed up the search, the factorization should be done in parallel using separate threads or processes, to take advantage of multi-core CPUs. Show how this can be formulated in your language. Parallelize the factorization of those numbers, then search the returned list of numbers and factors for the largest minimal factor, and return that number and its prime factors. For the prime number decomposition you may use the solution of the Prime decomposition task.
#D
D
ulong[] decompose(ulong n) pure nothrow { typeof(return) result; for (ulong i = 2; n >= i * i; i++) for (; n % i == 0; n /= i) result ~= i; if (n != 1) result ~= n; return result; }   void main() { import std.stdio, std.algorithm, std.parallelism, std.typecons;   immutable ulong[] data = [ 2UL^^59-1, 2UL^^59-1, 2UL^^59-1, 112_272_537_195_293UL, 115_284_584_522_153, 115_280_098_190_773, 115_797_840_077_099, 112_582_718_962_171, 112_272_537_095_293, 1_099_726_829_285_419];   //auto factors = taskPool.amap!(n => tuple(decompose(n), n))(data); //static enum genPair = (ulong n) pure => tuple(decompose(n), n); static genPair(ulong n) pure { return tuple(decompose(n), n); } auto factors = taskPool.amap!genPair(data);   auto pairs = factors.map!(p => tuple(p[0].reduce!min, p[1])); writeln("N. with largest min factor: ", pairs.reduce!max[1]); }
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm
Parsing/RPN calculator algorithm
Task Create a stack-based evaluator for an expression in   reverse Polish notation (RPN)   that also shows the changes in the stack as each individual token is processed as a table. Assume an input of a correct, space separated, string of tokens of an RPN expression Test with the RPN expression generated from the   Parsing/Shunting-yard algorithm   task:         3 4 2 * 1 5 - 2 3 ^ ^ / + Print or display the output here Notes   ^   means exponentiation in the expression above.   /   means division. See also   Parsing/Shunting-yard algorithm for a method of generating an RPN from an infix expression.   Several solutions to 24 game/Solve make use of RPN evaluators (although tracing how they work is not a part of that task).   Parsing/RPN to infix conversion.   Arithmetic evaluation.
#BBC_BASIC
BBC BASIC
@% = &60B RPN$ = "3 4 2 * 1 5 - 2 3 ^ ^ / +"   DIM Stack(1000) SP% = 0   FOR i% = 1 TO LEN(RPN$) Token$ = MID$(RPN$,i%,1) IF Token$ <> " " THEN PRINT Token$ " :"; CASE Token$ OF WHEN "+": PROCpush(FNpop + FNpop) WHEN "-": PROCpush(-FNpop + FNpop) WHEN "*": PROCpush(FNpop * FNpop) WHEN "/": n = FNpop : PROCpush(FNpop / n) WHEN "^": n = FNpop : PROCpush(FNpop ^ n) WHEN "0","1","2","3","4","5","6","7","8","9": PROCpush(VALMID$(RPN$,i%)) WHILE ASCMID$(RPN$,i%)>=48 AND ASCMID$(RPN$,1)<=57 i% += 1 ENDWHILE ENDCASE FOR j% = SP%-1 TO 0 STEP -1 : PRINT Stack(j%); : NEXT PRINT ENDIF NEXT i% END   DEF PROCpush(n) IF SP% > DIM(Stack(),1) ERROR 100, "Stack full" Stack(SP%) = n SP% += 1 ENDPROC   DEF FNpop IF SP% = 0 ERROR 100, "Stack empty" SP% -= 1 = Stack(SP%)
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm
Parsing/RPN calculator algorithm
Task Create a stack-based evaluator for an expression in   reverse Polish notation (RPN)   that also shows the changes in the stack as each individual token is processed as a table. Assume an input of a correct, space separated, string of tokens of an RPN expression Test with the RPN expression generated from the   Parsing/Shunting-yard algorithm   task:         3 4 2 * 1 5 - 2 3 ^ ^ / + Print or display the output here Notes   ^   means exponentiation in the expression above.   /   means division. See also   Parsing/Shunting-yard algorithm for a method of generating an RPN from an infix expression.   Several solutions to 24 game/Solve make use of RPN evaluators (although tracing how they work is not a part of that task).   Parsing/RPN to infix conversion.   Arithmetic evaluation.
#Bracmat
Bracmat
( ( show = line a . \n:?line & whl ' (!arg:%?a ?arg&!a " " !line:?line) & put$(str$!line) ) & :?stack & map $ ( ( = a b . show$(!arg !stack) & (  !arg  : ( "+" | "-" | "*" | "/" | "^" ) & !stack:%?a %?b ?stack & ( !arg:"+"&!a+!b | !arg:"-"&-1*!a+!b | !arg:"*"&!a*!b | !arg:"/"&!a*!b^-1 | !a^!b ) | !arg )  !stack  : ?stack ) . vap$((=.!arg).get'(,STR)." ") ) & out$!stack )
http://rosettacode.org/wiki/Pancake_numbers
Pancake numbers
Adrian Monk has problems and an assistant, Sharona Fleming. Sharona can deal with most of Adrian's problems except his lack of punctuality paying her remuneration. 2 pay checks down and she prepares him pancakes for breakfast. Knowing that he will be unable to eat them unless they are stacked in ascending order of size she leaves him only a skillet which he can insert at any point in the pile and flip all the above pancakes, repeating until the pile is sorted. Sharona has left the pile of n pancakes such that the maximum number of flips is required. Adrian is determined to do this in as few flips as possible. This sequence n->p(n) is known as the Pancake numbers. The task is to determine p(n) for n = 1 to 9, and for each show an example requiring p(n) flips. Sorting_algorithms/Pancake_sort actually performs the sort some giving the number of flips used. How do these compare with p(n)? Few people know p(20), generously I shall award an extra credit for anyone doing more than p(16). References Bill Gates and the pancake problem A058986
#Cowgol
Cowgol
include "cowgol.coh";   sub pancake(n: uint8): (r: uint8) is var gap: uint8 := 2; var sum: uint8 := 2; var adj: int8 := -1;   while sum < n loop adj := adj + 1; gap := gap * 2 - 1; sum := sum + gap; end loop;   r := n + adj as uint8; end sub;   # print 2-digit number sub print2(n: uint8) is if n<10 then print_char(' '); else print_char(n/10 + '0'); end if; print_char(n%10 + '0'); end sub;   # print item sub print_item(n: uint8) is print("p("); print2(n); print(") = "); print2(pancake(n)); print(" "); end sub;   var i: uint8 := 0; while i < 4 loop var j: uint8 := 1; while j < 6 loop print_item(i*5 + j); j := j + 1; end loop; print_nl(); i := i + 1; end loop;
http://rosettacode.org/wiki/Pancake_numbers
Pancake numbers
Adrian Monk has problems and an assistant, Sharona Fleming. Sharona can deal with most of Adrian's problems except his lack of punctuality paying her remuneration. 2 pay checks down and she prepares him pancakes for breakfast. Knowing that he will be unable to eat them unless they are stacked in ascending order of size she leaves him only a skillet which he can insert at any point in the pile and flip all the above pancakes, repeating until the pile is sorted. Sharona has left the pile of n pancakes such that the maximum number of flips is required. Adrian is determined to do this in as few flips as possible. This sequence n->p(n) is known as the Pancake numbers. The task is to determine p(n) for n = 1 to 9, and for each show an example requiring p(n) flips. Sorting_algorithms/Pancake_sort actually performs the sort some giving the number of flips used. How do these compare with p(n)? Few people know p(20), generously I shall award an extra credit for anyone doing more than p(16). References Bill Gates and the pancake problem A058986
#D
D
import std.stdio;   int pancake(int n) { int gap = 2, sum = 2, adj = -1; while (sum < n) { adj++; gap = 2 * gap - 1; sum += gap; } return n + adj; }   void main() { foreach (i; 0..4) { foreach (j; 1..6) { int n = 5 * i + j; writef("p(%2d) = %2d ", n, pancake(n)); } writeln; } }
http://rosettacode.org/wiki/Parsing/Shunting-yard_algorithm
Parsing/Shunting-yard algorithm
Task Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output as each individual token is processed. Assume an input of a correct, space separated, string of tokens representing an infix expression Generate a space separated output string representing the RPN Test with the input string: 3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3 print and display the output here. Operator precedence is given in this table: operator precedence associativity operation ^ 4 right exponentiation * 3 left multiplication / 3 left division + 2 left addition - 2 left subtraction Extra credit Add extra text explaining the actions and an optional comment for the action on receipt of each token. Note The handling of functions and arguments is not required. See also Parsing/RPN calculator algorithm for a method of calculating a final value from this output RPN expression. Parsing/RPN to infix conversion.
#D
D
import std.container; import std.stdio;   void main() { string infix = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3"; writeln("infix: ", infix); writeln("postfix: ", infixToPostfix(infix)); }   string infixToPostfix(string infix) { import std.array;   /* To find out the precedence, we take the index of the token in the ops string and divide by 2 (rounding down). This will give us: 0, 0, 1, 1, 2 */ immutable ops = ["+", "-", "/", "*", "^"];   auto sb = appender!string; SList!int stack;   // split the input on whitespace foreach (token; infix.split) { if (token.empty) { continue; }   int idx = ops.indexOf(token);   // check for operator if (idx != -1) { while (!stack.empty) { int prec2 = stack.peek / 2; int prec1 = idx / 2; if (prec2 > prec1 || (prec2 == prec1 && token != "^")) { sb.put(ops[stack.pop]); sb.put(' '); } else { break; } } stack.push(idx); } else if (token == "(") { stack.push(-2); // -2 stands for '(' } else if (token == ")") { // until '(' on stack, pop operators. while (stack.peek != -2) { sb.put(ops[stack.pop]); sb.put(' '); } stack.pop(); } else { sb.put(token); sb.put(' '); } }   while (!stack.empty) { sb.put(ops[stack.pop]); sb.put(' '); }   return sb.data; }   // Find the first index of the specified value, or -1 if not found. int indexOf(T)(const T[] a, const T v) { foreach(i,e; a) { if (e == v) { return i; } } return -1; }   // Convienience for adding a new element void push(T)(ref SList!T s, T v) { s.insertFront(v); }   // Convienience for accessing the top element auto peek(T)(SList!T s) { return s.front; }   // Convienience for removing and returning the top element auto pop(T)(ref SList!T s) { auto v = s.front; s.removeFront; return v; }
http://rosettacode.org/wiki/Paraffins
Paraffins
This organic chemistry task is essentially to implement a tree enumeration algorithm. Task Enumerate, without repetitions and in order of increasing size, all possible paraffin molecules (also known as alkanes). Paraffins are built up using only carbon atoms, which has four bonds, and hydrogen, which has one bond.   All bonds for each atom must be used, so it is easiest to think of an alkane as linked carbon atoms forming the "backbone" structure, with adding hydrogen atoms linking the remaining unused bonds. In a paraffin, one is allowed neither double bonds (two bonds between the same pair of atoms), nor cycles of linked carbons.   So all paraffins with   n   carbon atoms share the empirical formula     CnH2n+2 But for all   n ≥ 4   there are several distinct molecules ("isomers") with the same formula but different structures. The number of isomers rises rather rapidly when   n   increases. In counting isomers it should be borne in mind that the four bond positions on a given carbon atom can be freely interchanged and bonds rotated (including 3-D "out of the paper" rotations when it's being observed on a flat diagram),   so rotations or re-orientations of parts of the molecule (without breaking bonds) do not give different isomers.   So what seem at first to be different molecules may in fact turn out to be different orientations of the same molecule. Example With   n = 3   there is only one way of linking the carbons despite the different orientations the molecule can be drawn;   and with   n = 4   there are two configurations:   a   straight   chain:     (CH3)(CH2)(CH2)(CH3)   a branched chain:       (CH3)(CH(CH3))(CH3) Due to bond rotations, it doesn't matter which direction the branch points in. The phenomenon of "stereo-isomerism" (a molecule being different from its mirror image due to the actual 3-D arrangement of bonds) is ignored for the purpose of this task. The input is the number   n   of carbon atoms of a molecule (for instance 17). The output is how many different different paraffins there are with   n   carbon atoms (for instance   24,894   if   n = 17). The sequence of those results is visible in the OEIS entry:     oeis:A00602 number of n-node unrooted quartic trees; number of n-carbon alkanes C(n)H(2n+2) ignoring stereoisomers. The sequence is (the index starts from zero, and represents the number of carbon atoms): 1, 1, 1, 1, 2, 3, 5, 9, 18, 35, 75, 159, 355, 802, 1858, 4347, 10359, 24894, 60523, 148284, 366319, 910726, 2278658, 5731580, 14490245, 36797588, 93839412, 240215803, 617105614, 1590507121, 4111846763, 10660307791, 27711253769, ... Extra credit Show the paraffins in some way. A flat 1D representation, with arrays or lists is enough, for instance: *Main> all_paraffins 1 [CCP H H H H] *Main> all_paraffins 2 [BCP (C H H H) (C H H H)] *Main> all_paraffins 3 [CCP H H (C H H H) (C H H H)] *Main> all_paraffins 4 [BCP (C H H (C H H H)) (C H H (C H H H)), CCP H (C H H H) (C H H H) (C H H H)] *Main> all_paraffins 5 [CCP H H (C H H (C H H H)) (C H H (C H H H)), CCP H (C H H H) (C H H H) (C H H (C H H H)), CCP (C H H H) (C H H H) (C H H H) (C H H H)] *Main> all_paraffins 6 [BCP (C H H (C H H (C H H H))) (C H H (C H H (C H H H))), BCP (C H H (C H H (C H H H))) (C H (C H H H) (C H H H)), BCP (C H (C H H H) (C H H H)) (C H (C H H H) (C H H H)), CCP H (C H H H) (C H H (C H H H)) (C H H (C H H H)), CCP (C H H H) (C H H H) (C H H H) (C H H (C H H H))] Showing a basic 2D ASCII-art representation of the paraffins is better; for instance (molecule names aren't necessary): methane ethane propane isobutane   H H H H H H H H H │ │ │ │ │ │ │ │ │ H ─ C ─ H H ─ C ─ C ─ H H ─ C ─ C ─ C ─ H H ─ C ─ C ─ C ─ H │ │ │ │ │ │ │ │ │ H H H H H H H │ H │ H ─ C ─ H │ H Links   A paper that explains the problem and its solution in a functional language: http://www.cs.wright.edu/~tkprasad/courses/cs776/paraffins-turner.pdf   A Haskell implementation: https://github.com/ghc/nofib/blob/master/imaginary/paraffins/Main.hs   A Scheme implementation: http://www.ccs.neu.edu/home/will/Twobit/src/paraffins.scm   A Fortress implementation:         (this site has been closed) http://java.net/projects/projectfortress/sources/sources/content/ProjectFortress/demos/turnersParaffins0.fss?rev=3005
#C
C
#include <stdio.h>   #define MAX_N 33 /* max number of tree nodes */ #define BRANCH 4 /* max number of edges a single node can have */   /* The basic idea: a paraffin molecule can be thought as a simple tree with each node being a carbon atom. Counting molecules is thus the problem of counting free (unrooted) trees of given number of nodes.   An unrooted tree needs to be uniquely represented, so we need a way to cannonicalize equivalent free trees. For that, we need to first define the cannonical form of rooted trees. Since rooted trees can be constructed by a root node and up to BRANCH rooted subtrees that are arranged in some definite order, we can define it thusly: * Given the root of a tree, the weight of each of its branches is the number of nodes contained in that branch; * A cannonical rooted tree would have its direct subtrees ordered in descending order by weight; * In case multiple subtrees are the same weight, they are ordered by some unstated, but definite, order (this code doesn't really care what the ordering is; it only counts the number of choices in such a case, not enumerating individual trees.)   A rooted tree of N nodes can then be constructed by adding smaller, cannonical rooted trees to a root node, such that: * Each subtree has fewer than BRANCH branches (since it must have an empty slot for an edge to connect to the new root); * Weight of those subtrees added later are no higher than earlier ones; * Their weight total N-1. A rooted tree so constructed would be itself cannonical.   For an unrooted tree, we can define the radius of any of its nodes: it's the maximum weight of any of the subtrees if this node is used as the root. A node is the center of a tree if it has the smallest radius among all the nodes. A tree can have either one or two such centers; if two, they must be adjacent (cf. Knuth, tAoCP 2.3.4.4).   An important fact is that, a node in a tree is its sole center, IFF its radius times 2 is no greater than the sum of the weights of all branches (ibid). While we are making rooted trees, we can add such trees encountered to the count of cannonical unrooted trees.   A bi-centered unrooted tree with N nodes can be made by joining two trees, each with N/2 nodes and fewer than BRANCH subtrees, at root. The pair must be ordered in aforementioned implicit way so that the product is cannonical. */   typedef unsigned long long xint; #define FMT "llu"   xint rooted[MAX_N] = {1, 1, 0}; xint unrooted[MAX_N] = {1, 1, 0};   /* choose k out of m possible values; chosen values may repeat, but the ordering of them does not matter. It's binomial(m + k - 1, k) */ xint choose(xint m, xint k) { xint i, r;   if (k == 1) return m; for (r = m, i = 1; i < k; i++) r = r * (m + i) / (i + 1); return r; }   /* constructing rooted trees of BR branches at root, with at most N radius, and SUM nodes in the partial tree already built. It's recursive, and CNT and L carry down the number of combinations and the tree radius already encountered. */ void tree(xint br, xint n, xint cnt, xint sum, xint l) { xint b, c, m, s;   for (b = br + 1; b <= BRANCH; b++) { s = sum + (b - br) * n; if (s >= MAX_N) return;   /* First B of BR branches are all of weight n; the rest are at most of weight N-1 */ c = choose(rooted[n], b - br) * cnt;   /* This partial tree is singly centered as is */ if (l * 2 < s) unrooted[s] += c;   /* Trees saturate at root can't be used as building blocks for larger trees, so forget them */ if (b == BRANCH) return; rooted[s] += c;   /* Build the rest of the branches */ for (m = n; --m; ) tree(b, m, c, s, l); } }   void bicenter(int s) { if (s & 1) return;   /* Pick two of the half-size building blocks, allowing repetition. */ unrooted[s] += rooted[s/2] * (rooted[s/2] + 1) / 2; }   int main() { xint n; for (n = 1; n < MAX_N; n++) { tree(0, n, 1, 1, n); bicenter(n); printf("%"FMT": %"FMT"\n", n, unrooted[n]); }   return 0; }
http://rosettacode.org/wiki/Pangram_checker
Pangram checker
Pangram checker You are encouraged to solve this task according to the task description, using any language you may know. A pangram is a sentence that contains all the letters of the English alphabet at least once. For example:   The quick brown fox jumps over the lazy dog. Task Write a function or method to check a sentence to see if it is a   pangram   (or not)   and show its use. Related tasks   determine if a string has all the same characters   determine if a string has all unique characters
#360_Assembly
360 Assembly
* Pangram RC 11/08/2015 PANGRAM CSECT USING PANGRAM,R12 LR R12,R15 BEGIN LA R9,SENTENCE LA R6,4 LOOPI LA R10,ALPHABET loop on sentences LA R7,26 LOOPJ LA R5,0 loop on letters LR R11,R9 LA R8,60 LOOPK MVC BUFFER+1(1),0(R10) loop in sentence CLC 0(1,R10),0(R11) if alphabet[j=sentence[i] BNE NEXTK LA R5,1 found NEXTK LA R11,1(R11) next character BCT R8,LOOPK LTR R5,R5 if found BNZ NEXTJ MVI BUFFER,C'?' not found B PRINT NEXTJ LA R10,1(R10) next letter BCT R7,LOOPJ MVC BUFFER(2),=CL2'OK' PRINT MVC BUFFER+3(60),0(R9) XPRNT BUFFER,80 NEXTI LA R9,60(R9) next sentence BCT R6,LOOPI RETURN XR R15,R15 BR R14 ALPHABET DC CL26'ABCDEFGHIJKLMNOPQRSTUVWXYZ' SENTENCE DC CL60'THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG.' DC CL60'THE FIVE BOXING WIZARDS DUMP QUICKLY.' DC CL60'HEAVY BOXES PERFORM WALTZES AND JIGS.' DC CL60'PACK MY BOX WITH FIVE DOZEN LIQUOR JUGS.' BUFFER DC CL80' ' YREGS END PANGRAM
http://rosettacode.org/wiki/Pangram_checker
Pangram checker
Pangram checker You are encouraged to solve this task according to the task description, using any language you may know. A pangram is a sentence that contains all the letters of the English alphabet at least once. For example:   The quick brown fox jumps over the lazy dog. Task Write a function or method to check a sentence to see if it is a   pangram   (or not)   and show its use. Related tasks   determine if a string has all the same characters   determine if a string has all unique characters
#ACL2
ACL2
(defun contains-each (needles haystack) (if (endp needles) t (and (member (first needles) haystack) (contains-each (rest needles) haystack))))   (defun pangramp (str) (contains-each (coerce "abcdefghijklmnopqrstuvwxyz" 'list) (coerce (string-downcase str) 'list)))
http://rosettacode.org/wiki/Pascal_matrix_generation
Pascal matrix generation
A pascal matrix is a two-dimensional square matrix holding numbers from   Pascal's triangle,   also known as   binomial coefficients   and which can be shown as   nCr. Shown below are truncated   5-by-5   matrices   M[i, j]   for   i,j   in range   0..4. A Pascal upper-triangular matrix that is populated with   jCi: [[1, 1, 1, 1, 1], [0, 1, 2, 3, 4], [0, 0, 1, 3, 6], [0, 0, 0, 1, 4], [0, 0, 0, 0, 1]] A Pascal lower-triangular matrix that is populated with   iCj   (the transpose of the upper-triangular matrix): [[1, 0, 0, 0, 0], [1, 1, 0, 0, 0], [1, 2, 1, 0, 0], [1, 3, 3, 1, 0], [1, 4, 6, 4, 1]] A Pascal symmetric matrix that is populated with   i+jCi: [[1, 1, 1, 1, 1], [1, 2, 3, 4, 5], [1, 3, 6, 10, 15], [1, 4, 10, 20, 35], [1, 5, 15, 35, 70]] Task Write functions capable of generating each of the three forms of   n-by-n   matrices. Use those functions to display upper, lower, and symmetric Pascal   5-by-5   matrices on this page. The output should distinguish between different matrices and the rows of each matrix   (no showing a list of 25 numbers assuming the reader should split it into rows). Note The   Cholesky decomposition   of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size.
#CLU
CLU
matrix = array[array[int]]   make_matrix = proc (gen: proctype (int,int,matrix) returns (int), size: int) returns (matrix) m: matrix := matrix$fill_copy(0, size, array[int]$fill(0, size, 0)) for y: int in int$from_to(0, size-1) do for x: int in int$from_to(0, size-1) do m[y][x] := gen(x,y,m) end end return(m) end make_matrix   lower = proc (x,y: int, m: matrix) returns (int) if x>y then return(0) elseif x=y | x=0 then return(1) else return( m[y-1][x-1] + m[y-1][x] ) end end lower   upper = proc (x,y: int, m: matrix) returns (int) if x<y then return(0) elseif x=y | y=0 then return(1) else return( m[y-1][x-1] + m[y][x-1] ) end end upper   symmetric = proc (x,y: int, m: matrix) returns (int) if x=0 | y=0 then return(1) else return(m[y][x-1] + m[y-1][x]) end end symmetric   print_matrix = proc (s: stream, m: matrix, w: int) for line: array[int] in matrix$elements(m) do for item: int in array[int]$elements(line) do stream$putright(s, int$unparse(item), w) stream$putc(s, ' ') end stream$putl(s, "") end end print_matrix   start_up = proc () po: stream := stream$primary_output()   stream$putl(po, "Upper-triangular matrix:") print_matrix(po, make_matrix(upper,5), 1)   stream$putl(po, "\nLower-triangular matrix:") print_matrix(po, make_matrix(lower,5), 1)   stream$putl(po, "\nSymmetric matrix:") print_matrix(po, make_matrix(symmetric,5), 2) end start_up
http://rosettacode.org/wiki/Parameterized_SQL_statement
Parameterized SQL statement
SQL injection Using a SQL update statement like this one (spacing is optional): UPDATE players SET name = 'Smith, Steve', score = 42, active = TRUE WHERE jerseyNum = 99 Non-parameterized SQL is the GoTo statement of database programming. Don't do it, and make sure your coworkers don't either.
#Go
Go
package main   import ( "database/sql" "fmt"   _ "github.com/mattn/go-sqlite3" )   func main() { db, _ := sql.Open("sqlite3", "rc.db") defer db.Close() db.Exec(`create table players (name, score, active, jerseyNum)`) db.Exec(`insert into players values ("",0,0,"99")`) db.Exec(`insert into players values ("",0,0,"100")`)   // Parameterized db.Exec(`update players set name=?, score=?, active=? where jerseyNum=?`, "Smith, Steve", 42, true, "99")   rows, _ := db.Query("select * from players") var ( name string score int active bool jerseyNum string ) for rows.Next() { rows.Scan(&name, &score, &active, &jerseyNum) fmt.Printf("%3s %12s %3d %t\n", jerseyNum, name, score, active) } rows.Close() }
http://rosettacode.org/wiki/Parameterized_SQL_statement
Parameterized SQL statement
SQL injection Using a SQL update statement like this one (spacing is optional): UPDATE players SET name = 'Smith, Steve', score = 42, active = TRUE WHERE jerseyNum = 99 Non-parameterized SQL is the GoTo statement of database programming. Don't do it, and make sure your coworkers don't either.
#Haskell
Haskell
module Main (main) where   import Database.HDBC (IConnection, commit, run, toSql)   updatePlayers :: IConnection a => a -> String -> Int -> Bool -> Int -> IO Bool updatePlayers conn name score active jerseyNum = do rowCount <- run conn "UPDATE players\ \ SET name = ?, score = ?, active = ?\ \ WHERE jerseyNum = ?" [ toSql name , toSql score , toSql active , toSql jerseyNum ] commit conn return $ rowCount == 1   main :: IO () main = undefined
http://rosettacode.org/wiki/Pascal%27s_triangle
Pascal's triangle
Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is either 1 or the sum of the two elements right above it. For example, the next row of the triangle would be:   1   (since the first element of each row doesn't have two elements above it)   4   (1 + 3)   6   (3 + 3)   4   (3 + 1)   1   (since the last element of each row doesn't have two elements above it) So the triangle now looks like this: 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 Each row   n   (starting with row   0   at the top) shows the coefficients of the binomial expansion of   (x + y)n. Task Write a function that prints out the first   n   rows of the triangle   (with   f(1)   yielding the row consisting of only the element 1). This can be done either by summing elements from the previous rows or using a binary coefficient or combination function. Behavior for   n ≤ 0   does not need to be uniform, but should be noted. See also Evaluate binomial coefficients
#BBC_BASIC
BBC BASIC
nrows% = 10   colwidth% = 4 @% = colwidth% : REM Set column width FOR row% = 1 TO nrows% PRINT SPC(colwidth%*(nrows% - row%)/2); acc% = 1 FOR element% = 1 TO row% PRINT acc%; acc% = acc% * (row% - element%) / element% + 0.5 NEXT PRINT NEXT row%
http://rosettacode.org/wiki/Parse_an_IP_Address
Parse an IP Address
The purpose of this task is to demonstrate parsing of text-format IP addresses, using IPv4 and IPv6. Taking the following as inputs: 127.0.0.1 The "localhost" IPv4 address 127.0.0.1:80 The "localhost" IPv4 address, with a specified port (80) ::1 The "localhost" IPv6 address [::1]:80 The "localhost" IPv6 address, with a specified port (80) 2605:2700:0:3::4713:93e3 Rosetta Code's primary server's public IPv6 address [2605:2700:0:3::4713:93e3]:80 Rosetta Code's primary server's public IPv6 address, with a specified port (80) Task Emit each described IP address as a hexadecimal integer representing the address, the address space, and the port number specified, if any. In languages where variant result types are clumsy, the result should be ipv4 or ipv6 address number, something which says which address space was represented, port number and something that says if the port was specified. Example 127.0.0.1   has the address number   7F000001   (2130706433 decimal) in the ipv4 address space. ::ffff:127.0.0.1   represents the same address in the ipv6 address space where it has the address number   FFFF7F000001   (281472812449793 decimal). ::1   has address number   1   and serves the same purpose in the ipv6 address space that   127.0.0.1   serves in the ipv4 address space.
#Java
Java
  import java.util.regex.Matcher; import java.util.regex.Pattern;   public class ParseIPAddress {   public static void main(String[] args) { String [] tests = new String[] {"192.168.0.1", "127.0.0.1", "256.0.0.1", "127.0.0.1:80", "::1", "[::1]:80", "[32e::12f]:80", "2605:2700:0:3::4713:93e3", "[2605:2700:0:3::4713:93e3]:80", "2001:db8:85a3:0:0:8a2e:370:7334"}; System.out.printf("%-40s %-32s  %s%n", "Test Case", "Hex Address", "Port"); for ( String ip : tests ) { try { String [] parsed = parseIP(ip); System.out.printf("%-40s %-32s  %s%n", ip, parsed[0], parsed[1]); } catch (IllegalArgumentException e) { System.out.printf("%-40s Invalid address:  %s%n", ip, e.getMessage()); } } }   private static final Pattern IPV4_PAT = Pattern.compile("^(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)(?::(\\d+)){0,1}$"); private static final Pattern IPV6_DOUBL_COL_PAT = Pattern.compile("^\\[{0,1}([0-9a-f:]*)::([0-9a-f:]*)(?:\\]:(\\d+)){0,1}$"); private static String ipv6Pattern; static { ipv6Pattern = "^\\[{0,1}"; for ( int i = 1 ; i <= 7 ; i ++ ) { ipv6Pattern += "([0-9a-f]+):"; } ipv6Pattern += "([0-9a-f]+)(?:\\]:(\\d+)){0,1}$"; } private static final Pattern IPV6_PAT = Pattern.compile(ipv6Pattern);   private static String[] parseIP(String ip) { String hex = ""; String port = "";   // IPV4 Matcher ipv4Matcher = IPV4_PAT.matcher(ip); if ( ipv4Matcher.matches() ) { for ( int i = 1 ; i <= 4 ; i++ ) { hex += toHex4(ipv4Matcher.group(i)); } if ( ipv4Matcher.group(5) != null ) { port = ipv4Matcher.group(5); } return new String[] {hex, port}; }   // IPV6, double colon Matcher ipv6DoubleColonMatcher = IPV6_DOUBL_COL_PAT.matcher(ip); if ( ipv6DoubleColonMatcher.matches() ) { String p1 = ipv6DoubleColonMatcher.group(1); if ( p1.isEmpty() ) { p1 = "0"; } String p2 = ipv6DoubleColonMatcher.group(2); if ( p2.isEmpty() ) { p2 = "0"; } ip = p1 + getZero(8 - numCount(p1) - numCount(p2)) + p2; if ( ipv6DoubleColonMatcher.group(3) != null ) { ip = "[" + ip + "]:" + ipv6DoubleColonMatcher.group(3); } }   // IPV6 Matcher ipv6Matcher = IPV6_PAT.matcher(ip); if ( ipv6Matcher.matches() ) { for ( int i = 1 ; i <= 8 ; i++ ) { hex += String.format("%4s", toHex6(ipv6Matcher.group(i))).replace(" ", "0"); } if ( ipv6Matcher.group(9) != null ) { port = ipv6Matcher.group(9); } return new String[] {hex, port}; }   throw new IllegalArgumentException("ERROR 103: Unknown address: " + ip); }   private static int numCount(String s) { return s.split(":").length; }   private static String getZero(int count) { StringBuilder sb = new StringBuilder(); sb.append(":"); while ( count > 0 ) { sb.append("0:"); count--; } return sb.toString(); }   private static String toHex4(String s) { int val = Integer.parseInt(s); if ( val < 0 || val > 255 ) { throw new IllegalArgumentException("ERROR 101: Invalid value : " + s); } return String.format("%2s", Integer.toHexString(val)).replace(" ", "0"); }   private static String toHex6(String s) { int val = Integer.parseInt(s, 16); if ( val < 0 || val > 65536 ) { throw new IllegalArgumentException("ERROR 102: Invalid hex value : " + s); } return s; }   }  
http://rosettacode.org/wiki/Parametric_polymorphism
Parametric polymorphism
Parametric Polymorphism type variables Task Write a small example for a type declaration that is parametric over another type, together with a short bit of code (and its type signature) that uses it. A good example is a container type, let's say a binary tree, together with some function that traverses the tree, say, a map-function that operates on every element of the tree. This language feature only applies to statically-typed languages.
#J
J
public class Tree<T>{ private T value; private Tree<T> left; private Tree<T> right;   public void replaceAll(T value){ this.value = value; if (left != null) left.replaceAll(value); if (right != null) right.replaceAll(value); } }
http://rosettacode.org/wiki/Parametric_polymorphism
Parametric polymorphism
Parametric Polymorphism type variables Task Write a small example for a type declaration that is parametric over another type, together with a short bit of code (and its type signature) that uses it. A good example is a container type, let's say a binary tree, together with some function that traverses the tree, say, a map-function that operates on every element of the tree. This language feature only applies to statically-typed languages.
#Java
Java
public class Tree<T>{ private T value; private Tree<T> left; private Tree<T> right;   public void replaceAll(T value){ this.value = value; if (left != null) left.replaceAll(value); if (right != null) right.replaceAll(value); } }