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 Uni...
#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 pla...
#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" %...
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 pro...
#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)...
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 p...
#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] !...
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 ...
#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(d...
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...
#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 expressio...
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 Gener...
#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 Gener...
#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...
#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[,]...
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 =...
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 elemen...
#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...
#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 |...
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, ...
#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, ...
#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 ...
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....
#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 }, ...
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 ...
#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 ...
#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); ...
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. ...
#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)...
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. ...
#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, re...
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)...
#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 = po...
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...
#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 ...
#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, blackQu...
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 ch...
#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...
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 Uni...
#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 ...
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 pla...
#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...
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 pla...
#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...
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 pro...
#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 m...
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 p...
#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("1115dd800feaacefdf481f1f907...
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 ...
#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() { // concu...
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...
#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 =...
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...
#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 < ...
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 Gener...
#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...
#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); ...
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"; ...
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 elemen...
#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) ...
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...
#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-1...
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, ...
#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) 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, ...
#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) ...
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....
#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])->...
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 ...
#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 ...
#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. ...
#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...
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)...
#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 ...
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)...
#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)...
#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 ...
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...
#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...
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 ...
#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 })) )...
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 ch...
#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...
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 Uni...
#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 ->...
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 pla...
#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 ...
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 pla...
#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...
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 pro...
#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 ...
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 p...
#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 cha...
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 ...
#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 ...
#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))) ...
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...
#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 :...
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...
#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; ...
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...
#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 *...
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 Gener...
#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 rig...
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 Gener...
#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,s...
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 bo...
#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 ...
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 chec...
#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...
#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] (bi...
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 e...
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"   tCo...
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 elemen...
#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=...
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...
#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. ...
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, ...
#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, ...
#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, ...
#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"}; fin...
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....
#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), ...
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 ...
#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 ...
#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 ...
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. ...
#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, ...
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)...
#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; ...
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)...
#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)...
#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] ...
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...
#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_problem...
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 ch...
#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 = """!"#$%...
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 Uni...
#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 pla...
#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("...
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 pro...
#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 pro...
#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 p...
#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 ["1115dd800feaacefdf481f1...
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 ...
#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;   immu...
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...
#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...
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...
#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  : ( "+" | "-" | "*" ...
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...
#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 ...
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...
#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...
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 Gener...
#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 ...
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 bo...
#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) tr...
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 chec...
#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 ...
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 chec...
#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...
#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...
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 int...
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 = ?...
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 elemen...
#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 ...
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...
#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:...
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, ...
#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, ...
#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); } }