task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Parametric_polymorphism
Parametric polymorphism
Parametric Polymorphism type variables Task Write a small example for a type declaration that is parametric over another type, together with a short bit of code (and its type signature) that uses it. A good example is a container type, let's say a binary tree, together with some function that traverses the tree, ...
#Julia
Julia
module BinaryTrees   mutable struct BinaryTree{V} v::V l::Union{BinaryTree{V}, Nothing} r::Union{BinaryTree{V}, Nothing} end   BinaryTree(v) = BinaryTree(v, nothing, nothing)   map(f, bt::BinaryTree) = BinaryTree(f(bt.v), map(f, bt.l), map(f, bt.r)) map(f, bt::Nothing) = nothing   let inttree = BinaryTree( ...
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....
#EchoLisp
EchoLisp
  (require 'hash) (string-delimiter "")   (define (^ a b ) (expt a b)) ;; add this not-native function (define-syntax-rule (r-assoc? op) (= op "^")) (define-syntax-rule (l-assoc? op) (not ( = op "^" ))) (define PRECEDENCES (list->hash '(("+" . 2) ("-" . 2) ("*" . 3) ("/" . 3) ("//" . 3) ("^" . 4)) (make-hash)))   ;...
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 ...
#Groovy
Groovy
def fs = { fn, values -> values.collect { fn(it) } } def f1 = { v -> v * 2 } def f2 = { v -> v ** 2 } def fsf1 = fs.curry(f1) def fsf2 = fs.curry(f2)
http://rosettacode.org/wiki/Partial_function_application
Partial function application
Partial function application   is the ability to take a function of many parameters and apply arguments to some of the parameters to create a new function that needs only the application of the remaining arguments to produce the equivalent of applying all arguments to the original function. E.g: Given values v1, v2 ...
#Haskell
Haskell
fs = map f1 = (* 2) f2 = (^ 2)   fsf1 = fs f1 fsf2 = fs f2   main :: IO () main = do print $ fsf1 [0, 1, 2, 3] -- prints [0, 2, 4, 6] print $ fsf2 [0, 1, 2, 3] -- prints [0, 1, 4, 9] print $ fsf1 [2, 4, 6, 8] -- prints [4, 8, 12, 16] print $ fsf2 [2, 4, 6, 8] -- prints [4, 16, 36, 64]
http://rosettacode.org/wiki/Partition_an_integer_x_into_n_primes
Partition an integer x into n primes
Task Partition a positive integer   X   into   N   distinct primes. Or, to put it in another way: Find   N   unique primes such that they add up to   X. Show in the output section the sum   X   and the   N   primes in ascending order separated by plus (+) signs: •   partition 99809 with 1 prime. ...
#Prolog
Prolog
prime_partition(N, 1, [N], Min):- is_prime(N), N > Min, !. prime_partition(N, K, [P|Rest], Min):- K > 1, is_prime(P), P > Min, P < N, K1 is K - 1, N1 is N - P, prime_partition(N1, K1, Rest, P), !.   prime_partition(N, K, Primes):- prime_partition(N, K, Primes, 1).   print...
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)...
#Wren
Wren
import "/big" for BigInt   var p = [] var pd = []   var partDiffDiff = Fn.new { |n| (n&1 == 1) ? (n + 1)/2 : n + 1 }   var partDiff = Fn.new { |n| if (n < 2) return 1 pd[n] = pd[n-1] + partDiffDiff.call(n-1) return pd[n] }   var partitionsP = Fn.new { |n| if (n < 2) return var psum = BigInt.zero ...
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...
#Picat
Picat
import cp.   go => puzzle(T, X, Y,Z), foreach(TT in T) println(TT) end, println([x=X,y=Y,z=Z]), nl, fail, % are there any more solutions? nl.   % Port of the Prolog solution puzzle(Ts, X, Y, Z) :- Ts = [ [151], [_, _], [40, _, _], [_, _, _, _], [X, 1...
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...
#PicoLisp
PicoLisp
(be number (@N @Max) (^ @C (box 0)) (repeat) (or ((^ @ (>= (val (-> @C)) (-> @Max))) T (fail)) ((^ @N (inc (-> @C)))) ) )   (be + (@A @B @Sum) (^ @ (-> @A)) (^ @ (-> @B)) (^ @Sum (+ (-> @A) (-> @B))) )   (be + (@A @B @Sum) (^ @ (-> @A)) (^ @ (-> @Sum)) (^ @B (- (-> @Sum) (-> @A)))...
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...
#Lua
Lua
function randPW (length) local index, pw, rnd = 0, "" local chars = { "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz", "0123456789", "!\"#$%&'()*+,-./:;<=>?@[]^_{|}~" } repeat index = index + 1 rnd = math.random(chars[index]:len()) if ma...
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...
#True_BASIC
True BASIC
SUB SWAP(vb1, vb2) LET temp = vb1 LET vb1 = vb2 LET vb2 = temp END SUB   LET n = 4 DIM a(4) DIM c(4)   FOR i = 1 TO n LET a(i) = i NEXT i PRINT   DO FOR i = 1 TO n PRINT a(i); NEXT i PRINT LET i = n DO LET i = i - 1 LOOP UNTIL (i = 0) OR (a(i) < a(i + 1)) LET j = i + 1 ...
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...
#zkl
zkl
fcn coinToss{ (0).random(2) and "H" or "T" } // (0).random(2) --> 0<=r<2 reg myBet, yourBet; if(coinToss()=="H"){ // The toss says I go first myBet=(3).pump(String,coinToss); println("I bet ",myBet); yourBet=ask("Your bet of three (H/T): ")[0,3].toUpper(); }else{ yourBet=ask("Your bet of three (H/T): ")[0,3...
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...
#Sidef
Sidef
func series (n) { var (u, v) = (2, -4) (n-2).times { (u, v) = (v, 111 - 1130/v + 3000/(v * u)) } return v }   [(3..8)..., 20, 30, 50, 100].each {|n| printf("n = %3d -> %s\n", n, series(n)) }
http://rosettacode.org/wiki/Parallel_brute_force
Parallel brute force
Task Find, through brute force, the five-letter passwords corresponding with the following SHA-256 hashes: 1. 1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad 2. 3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b 3. 74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f Your p...
#Common_Lisp
Common Lisp
(defpackage #:parallel-brute-force (:use #:cl #:lparallel))   (in-package #:parallel-brute-force)   (defparameter *alphabet* "abcdefghijklmnopqrstuvwxyz") (defparameter *hash0* "1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad") (defparameter *hash1* "3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d...
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 ...
#Delphi
Delphi
  program Parallel_calculations;   {$APPTYPE CONSOLE}   uses System.SysUtils, System.Threading, Velthuis.BigIntegers;   function IsPrime(n: BigInteger): Boolean; var i: BigInteger; begin if n <= 1 then exit(False);   i := 2; while i < BigInteger.Sqrt(n) do begin if n mod i = 0 then exit(Fa...
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...
#C
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h>   void die(const char *msg) { fprintf(stderr, "%s", msg); abort(); }   #define MAX_D 256 double stack[MAX_D]; int depth;   void push(double v) { if (depth >= MAX_D) die("stack overflow\n"); stack[depth++] = v; }   double pop() { if (!dept...
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...
#F.23
F#
  // Pancake numbers. Nigel Galloway: October 28th., 2020 let pKake z=let n=[for n in 1..z-1->Array.ofList([n.. -1..0]@[n+1..z-1])] let e=let rec fG n g=match g with 0->n |_->fG (n*g) (g-1) in fG 1 z let rec fN i g l=match (Set.count g)-e with 0->(i,List.last l) ...
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...
#EchoLisp
EchoLisp
  (require 'hash) (require 'tree)   (define OPS (make-hash)) (hash-set OPS "^" '( 4 #f)) ;; right assoc (hash-set OPS "*" '( 3 #t)) ;; left assoc (hash-set OPS "/" '( 3 #t)) (hash-set OPS "+" '( 2 #t)) (hash-set OPS "-" '( 2 #t))   ;; helpers (define (is-right-par? token) (string=? token ")")) (define (is-left-par...
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...
#D
D
import std.stdio, std.bigint;   enum uint nMax = 250; enum uint nBranches = 4;   __gshared BigInt[nMax + 1] rooted = [1.BigInt, 1.BigInt /*...*/], unrooted = [1.BigInt, 1.BigInt /*...*/];   void tree(in uint br, in uint n, in uint l, in uint inSum, in BigInt cnt) nothrow { __gsh...
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...
#Action.21
Action!
INCLUDE "D2:CHARTEST.ACT" ;from the Action! Tool Kit   DEFINE CHAR_COUNT="26"   BYTE FUNC IsPangram(CHAR ARRAY t) BYTE ARRAY tab(CHAR_COUNT) BYTE i,c   FOR i=0 TO CHAR_COUNT-1 DO tab(i)=0 OD   FOR i=1 TO t(0) DO c=ToLower(t(i)) IF c>='a AND c<='z THEN tab(c-'a)=1 FI OD   FOR i=0 TO CHA...
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...
#ActionScript
ActionScript
function pangram(k:string):Boolean { var lowerK:String = k.toLowerCase(); var has:Object = {}   for (var i:Number=0; i<=k.length-1; i++) { has[lowerK.charAt(i)] = true; }   var result:Boolean = true;   for (var ch:String='a'; ch <= 'z'; ch=String.fromCharCode(ch.charCodeAt(0)+1)) { result = result...
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...
#Common_Lisp
Common Lisp
(defun pascal-lower (n &aux (a (make-array (list n n) :initial-element 0))) (dotimes (i n) (setf (aref a i 0) 1)) (dotimes (i (1- n) a) (dotimes (j (1- n)) (setf (aref a (1+ i) (1+ j)) (+ (aref a i j) (aref a i (1+ j)))))))   (defun pascal-upper (n ...
http://rosettacode.org/wiki/Parameterized_SQL_statement
Parameterized SQL statement
SQL injection Using a SQL update statement like this one (spacing is optional): UPDATE players SET name = 'Smith, Steve', score = 42, active = TRUE WHERE jerseyNum = 99 Non-parameterized SQL is the GoTo statement of database programming. Don't do it, and make sure your coworkers don't either.
#Huginn
Huginn
import Database as db; import Algorithms as algo; import FileSystem as fs;   main() { dbPath = "/tmp/parametrized-sql.sqlite"; fs.remove( dbPath ); fs.open( dbPath, fs.OPEN_MODE.WRITE ); conn = db.connect( "sqlite3:///" + dbPath );   // Setup... conn.query( "CREATE TABLE Players (\n" "\tname VARCHAR...
http://rosettacode.org/wiki/Parameterized_SQL_statement
Parameterized SQL statement
SQL injection Using a SQL update statement like this one (spacing is optional): UPDATE players SET name = 'Smith, Steve', score = 42, active = TRUE WHERE jerseyNum = 99 Non-parameterized SQL is the GoTo statement of database programming. Don't do it, and make sure your coworkers don't either.
#Java
Java
  import java.sql.DriverManager; import java.sql.Connection; import java.sql.PreparedStatement;   public class DBDemo{ private String protocol; //set this to some connection protocol like "jdbc:sqlserver://" private String dbName; //set this to the name of your database private String username; private St...
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...
#BCPL
BCPL
get "libhdr"   let pascal(n) be for i=0 to n-1 $( let c = 1 for j=1 to 2*(n-1-i) do wrch(' ') for k=0 to i $( writef("%I3 ",c) c := c*(i-k)/(k+1) $) wrch('*N') $)   let start() be pascal(8)
http://rosettacode.org/wiki/Parse_an_IP_Address
Parse an IP Address
The purpose of this task is to demonstrate parsing of text-format IP addresses, using IPv4 and IPv6. Taking the following as inputs: 127.0.0.1 The "localhost" IPv4 address 127.0.0.1:80 The "localhost" IPv4 address, with a specified port (80) ::1 The "localhost" IPv6 address [::1]:80 The "localhost" IPv6...
#Julia
Julia
  const testdata = ["127.0.0.1", "127.0.0.1:80", "::1", "[::1]:80", "2605:2700:0:3::4713:93e3", "[2605:2700:0:3::4713:93e3]:80", "::ffff:192.168.173.22", "[::ffff:192.168.173.22]:80", "1::", "[1::]:80", "::", "[::]:80"]   maybev4(ip) = search(ip, '.') > 0 && length(...
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...
#Kotlin
Kotlin
// version 1.1.3   import java.math.BigInteger   enum class AddressSpace { IPv4, IPv6, Invalid }   data class IPAddressComponents( val address: BigInteger, val addressSpace: AddressSpace, val port: Int // -1 denotes 'not specified' )   val INVALID = IPAddressComponents(BigInteger.ZERO, AddressSpace.Invalid...
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, ...
#Kotlin
Kotlin
// version 1.0.6   class BinaryTree<T>(var value: T) { var left : BinaryTree<T>? = null var right: BinaryTree<T>? = null   fun <U> map(f: (T) -> U): BinaryTree<U> { val tree = BinaryTree<U>(f(value)) if (left != null) tree.left = left?.map(f) if (right != null) tree.right = right?...
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....
#F.23
F#
type ast = | Num of int | Add of ast * ast | Sub of ast * ast | Mul of ast * ast | Div of ast * ast | Exp of ast * ast   let (|Int|_|) = System.Int32.TryParse >> function | (true, v) -> Some(v) | (false, _) -> None   let rec parse = function | [] -> failwith "Not enough tokens" | (Int ...
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 ...
#Icon_and_Unicon
Icon and Unicon
link printf   procedure main() fsf1 := partial(fs,f1) fsf2 := partial(fs,f2) every s := [ 0, 1, 2, 3 ] | [ 2, 4, 6, 8 ] do { printf("\ns  := %s\n",list2string(s)) printf("fsf1(s) := %s\n",list2string(fsf1(s))) printf("fsf2(s) := %s\n",list2string(fsf2(s))) ...
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. ...
#Python
Python
from itertools import combinations as cmb     def isP(n): if n == 2: return True if n % 2 == 0: return False return all(n % x > 0 for x in range(3, int(n ** 0.5) + 1, 2))     def genP(n): p = [2] p.extend([x for x in range(3, n + 1, 2) if isP(x)]) return p     data = [ (99809...
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...
#Prolog
Prolog
:- use_module(library(clpfd)).   puzzle(Ts, X, Y, Z) :- Ts = [ [151], [_, _], [40, _, _], [_, _, _, _], [X, 11, Y, 4, Z]], Y #= X + Z, triangle(Ts), append(Ts, Vs), Vs ins 0..sup, label(Vs).   triangle([T|Ts]) :- ( Ts = [N|_] -> triangle_(T, N), triangle(Ts) ; true ).   t...
http://rosettacode.org/wiki/Password_generator
Password generator
Create a password generation program which will generate passwords containing random ASCII characters from the following groups: lower-case letters: a ──► z upper-case letters: A ──► Z digits: 0 ──► 9 other printable characters:  !"#$%&'()*+,-./:;<=>?@[]^_{|}~ (the above ch...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
(* Length is the Length of the password, num is the number you want, \ and similar=1 if you want similar characters, 0 if not. True and \ False, should work in place of 1/0 *) pwgen[length_Integer: 5, num_Integer: 1, similars_Boolean: 1] := pwgenerator[length, num, similars] = Module[{list, valid, validchars, simi...
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...
#Ursala
Ursala
#import std   permutations =   ~&itB^?a( # are both the input argument list and its tail non-empty? @ahPfatPRD *= refer ^C( # yes, recursively generate all permutations of the tail, and for each one ~&a, # insert the head at the first position ~&ar&& ~&arh...
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...
#Stata
Stata
clear set obs 100 gen n=_n gen v=. replace v=2 in 1 replace v=-4 in 2 replace v=111-1130/v[_n-1]+3000/(v[_n-1]*v[_n-2]) in 3/l format %20.16f v list if inlist(n,3,4,5,6,7,8,20,30,50,100), noobs
http://rosettacode.org/wiki/Pathological_floating_point_problems
Pathological floating point problems
Most programmers are familiar with the inexactness of floating point calculations in a binary processor. The classic example being: 0.1 + 0.2 = 0.30000000000000004 In many situations the amount of error in such calculations is very small and can be overlooked or eliminated with rounding. There are pathological pro...
#Swift
Swift
extension Numeric where Self: Strideable { @inlinable public func power(_ n: Self) -> Self { return stride(from: 0, to: n, by: 1).lazy.map({_ in self }).reduce(1, *) } }   protocol PathologicalFloat: SignedNumeric, Strideable, ExpressibleByFloatLiteral { static var e: Self { get }   static func /(_ lhs: S...
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...
#D
D
import std.digest.sha; import std.parallelism; import std.range; import std.stdio;   // Find the five lower-case letter strings representing the following sha256 hashes immutable p1 = cast(ubyte[32]) x"1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad"; immutable p2 = cast(ubyte[32]) x"3a7bd3e2360a3d29ee...
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 ...
#Erlang
Erlang
  -module( parallel_calculations ).   -export( [fun_results/2, task/0] ).   fun_results( Fun, Datas ) -> My_pid = erlang:self(), Pids = [fun_spawn( Fun, X, My_pid ) || X <- Datas], [fun_receive(X) || X <- Pids].   task() -> Numbers = [12757923, 12878611, 12757923, 15808973, 15780709, 197622519], Resul...
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...
#C.23
C#
using System; using System.Collections.Generic; using System.Linq; using System.Globalization; using System.Threading;   namespace RPNEvaluator { class RPNEvaluator { static void Main(string[] args) { Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;   s...
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...
#FreeBASIC
FreeBASIC
  Function pancake(n As Integer) As Integer Dim As Integer gap = 2, sum = 2, adj = -1 While (sum < n) adj += 1 gap = gap * 2 - 1 sum += gap Wend Return n + adj End Function   For n As Integer = 1 To 20 Print Using "p(##) = ## "; n; pancake(n); If n Mod 5 = 0 Then ? Next...
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...
#Go
Go
package main   import "fmt"   func pancake(n int) int { gap, sum, adj := 2, 2, -1 for sum < n { adj++ gap = gap*2 - 1 sum += gap } return n + adj }   func main() { for i := 0; i < 4; i++ { for j := 1; j < 6; j++ { n := i*5 + j fmt.Printf("p(%2d...
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...
#Java
Java
public class Pancake { private static int pancake(int n) { int gap = 2; int sum = 2; int adj = -1; while (sum < n) { adj++; gap = 2 * gap - 1; sum += gap; } return n + adj; }   public static void main(String[] args) { ...
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...
#F.23
F#
open System   type action = Shift | ReduceStack | ReduceInput   type State (input : string list, stack : string list, output : string list) = member x.Input with get() = input member x.Stack with get() = stack member x.Output with get() = output   member x.report act = let markTop = function | [...
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...
#FreeBASIC
FreeBASIC
' version 31-12-2016 ' compile with: fbc -s console ' uses gmp, translation from pascal   #Include Once "gmp.bi"   Const As Integer max_n = 500, branch = 4   Dim Shared As mpz_ptr rooted(), unrooted(), c() Dim Shared As mpz_ptr cnt, tmp   Sub tree(br As UInteger, n As UInteger, l As UInteger, sum As UInteger, cnt As mp...
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...
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO; with Ada.Strings.Maps; use Ada.Strings.Maps; with Ada.Characters.Handling; use Ada.Characters.Handling; procedure pangram is   function ispangram(txt: String) return Boolean is (Is_Subset(To_Set(Span => ('a','z')), To_Set(To_Lower(txt))));   begin put_line(Boolean'Image(isp...
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...
#D
D
import std.stdio, std.bigint, std.range, std.algorithm;   auto binomialCoeff(in uint n, in uint k) pure nothrow { BigInt result = 1; foreach (immutable i; 1 .. k + 1) result = result * (n - i + 1) / i; return result; }   auto pascalUpp(in uint n) pure nothrow { return n.iota.map!(i => n.iota.map...
http://rosettacode.org/wiki/Parameterized_SQL_statement
Parameterized SQL statement
SQL injection Using a SQL update statement like this one (spacing is optional): UPDATE players SET name = 'Smith, Steve', score = 42, active = TRUE WHERE jerseyNum = 99 Non-parameterized SQL is the GoTo statement of database programming. Don't do it, and make sure your coworkers don't either.
#Julia
Julia
using SQLite   name = "Smith, Steve" jerseys = Dict("Smith, Steve" => 99) sqlbool(tf::Bool) = if(tf) "TRUE" else "FALSE" end   db = SQLite.DB() # no filename given, so create an in-memory temporary SQLite.execute!(db, "create table players (id integer primary key, name text, ...
http://rosettacode.org/wiki/Parameterized_SQL_statement
Parameterized SQL statement
SQL injection Using a SQL update statement like this one (spacing is optional): UPDATE players SET name = 'Smith, Steve', score = 42, active = TRUE WHERE jerseyNum = 99 Non-parameterized SQL is the GoTo statement of database programming. Don't do it, and make sure your coworkers don't either.
#Kotlin
Kotlin
// Version 1.2.41   import java.sql.DriverManager import java.sql.Connection   fun main(args: Array<String>) { val url = "jdbc:mysql://localhost:3306/test" val username = "example" val password = "password123" val conn = DriverManager.getConnection(url, username, password) val query = conn.prepareSt...
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...
#Befunge
Befunge
0" :swor fo rebmuN">:#,_&> 55+, v v01*p00-1:g00.:<1p011p00:\-1_v#:< >g:1+10p/48*,:#^_$ 55+,1+\: ^>$$@
http://rosettacode.org/wiki/Parse_an_IP_Address
Parse an IP Address
The purpose of this task is to demonstrate parsing of text-format IP addresses, using IPv4 and IPv6. Taking the following as inputs: 127.0.0.1 The "localhost" IPv4 address 127.0.0.1:80 The "localhost" IPv4 address, with a specified port (80) ::1 The "localhost" IPv6 address [::1]:80 The "localhost" IPv6...
#Nim
Nim
import net, sequtils, strscans, strutils   const NoPort = -1   func parseIpAddressAndPort(str: string): tuple[ipAddr: IpAddress; port: int] = var ipString: string var port: int if str.scanf("[$+]:$i", ipString, port): # IP v6 address with port. return (ipString.parseIpAddress(), port) if '.' in str and ...
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...
#Perl
Perl
sub parse_v4 { my ($ip, $port) = @_; my @quad = split(/\./, $ip);   return unless @quad == 4; for (@quad) { return if ($_ > 255) }   if (!length $port) { $port = -1 } elsif ($port =~ /^(\d+)$/) { $port = $1 } else { return }   my $h = join '' => map(sprintf("%02x", $_), @quad); retur...
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, ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
f[a_] := Join[a, a] f[{1, 2, 3}] f[{"1", "2", "3"}] f[{1.1, 2.1, 3.1}] f[G[1, "a", Pi]] g[x_] := x^2 g[2] g[3.5] g[Pi] g["a"]
http://rosettacode.org/wiki/Parametric_polymorphism
Parametric polymorphism
Parametric Polymorphism type variables Task Write a small example for a type declaration that is parametric over another type, together with a short bit of code (and its type signature) that uses it. A good example is a container type, let's say a binary tree, together with some function that traverses the tree, ...
#Mercury
Mercury
:- type tree(A) ---> empty ; node(A, tree(A), tree(A)).   :- func map(func(A) = B, tree(A)) = tree(B).   map(_, empty) = empty. map(F, node(A, Left, Right)) = node(F(A), map(F, Left), map(F, Right)).
http://rosettacode.org/wiki/Parametric_polymorphism
Parametric polymorphism
Parametric Polymorphism type variables Task Write a small example for a type declaration that is parametric over another type, together with a short bit of code (and its type signature) that uses it. A good example is a container type, let's say a binary tree, together with some function that traverses the tree, ...
#Nim
Nim
import strutils, sugar   type Tree[T] = ref object value: T left, right: Tree[T]     proc newTree[T](value = default(T)): Tree[T] = ## Create a tree with a single node with the given value. Tree[T](value: value)     proc map[T, U](tree: Tree[T]; f: (T) -> U): Tree[U] = ## Apply function "f" to each element of...
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, ...
#Objective-C
Objective-C
@interface Tree<T> : NSObject { T value; Tree<T> *left; Tree<T> *right; }   - (void)replaceAll:(T)v; @end   @implementation Tree - (void)replaceAll:(id)v { value = v; [left replaceAll:v]; [right replaceAll:v]; } @end
http://rosettacode.org/wiki/Parsing/RPN_to_infix_conversion
Parsing/RPN to infix conversion
Parsing/RPN to infix conversion You are encouraged to solve this task according to the task description, using any language you may know. Task Create a program that takes an RPN representation of an expression formatted as a space separated sequence of tokens and generates the equivalent expression in infix notation....
#Go
Go
package main   import ( "fmt" "strings" )   var tests = []string{ "3 4 2 * 1 5 - 2 3 ^ ^ / +", "1 2 + 3 4 + ^ 5 6 + ^", }   var opa = map[string]struct { prec int rAssoc bool }{ "^": {4, true}, "*": {3, false}, "/": {3, false}, "+": {2, false}, "-": {2, false}, }   const nP...
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 ...
#J
J
fs=:1 :'u"0 y' f1=:*&2 f2=:^&2 fsf1=:f1 fs fsf2=:f2 fs
http://rosettacode.org/wiki/Partial_function_application
Partial function application
Partial function application   is the ability to take a function of many parameters and apply arguments to some of the parameters to create a new function that needs only the application of the remaining arguments to produce the equivalent of applying all arguments to the original function. E.g: Given values v1, v2 ...
#Java
Java
import java.util.Arrays;   public class PartialApplication { interface IntegerFunction { int call(int arg); }   // Original method fs(f, s). static int[] fs(IntegerFunction f, int[] s) { int[] r = new int[s.length]; for (int i = 0; i < s.length; i++) r[i] = f.call(s[i]); return r; }   interface Seque...
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. ...
#Racket
Racket
#lang racket (require math/number-theory)   (define memoised-next-prime (let ((m# (make-hash))) (λ (P) (hash-ref! m# P (λ () (next-prime P))))))   (define (partition-X-into-N-primes X N) (define (partition-x-into-n-primes-starting-at-P x n P result) (cond ((= n x 0) result) ((or (= n 0) (= x 0) (>...
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. ...
#Raku
Raku
use Math::Primesieve; my $sieve = Math::Primesieve.new;   # short circuit for '1' partition multi partition ( Int $number, 1 ) { $number.is-prime ?? $number !! () }   multi partition ( Int $number, Int $parts where * > 0 = 2 ) { my @these = $sieve.primes($number); for @these.combinations($parts) { .return if .s...
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...
#PureBasic
PureBasic
; Known; ; A. ; [ 151] ; [a ][b ] ; [40][c ][d ] ; [e ][f ][g ][h ] ; [ X][11][ Y][ 4][ Z] ; ; B. ; Y = X + Z   Procedure.i SolveForZ(x) Protected a,b,c,d,e,f,g,h,z For z=0 To 20 e=x+11: f=11+(x+z): g=(x+z)+4: h=4+z If e+f=40 c=f+g : d=g+h: a=40+c: b=c+d If a+b=151 ...
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...
#Nim
Nim
import os, parseopt, random, sequtils, strformat, strutils   const Symbols = toSeq("!\"#$%&'()*+,-./:;<=>?@[]^_{|}~")     proc passGen(passLength = 10, count = 1, seed = 0, excludeSimilars = false): seq[string] = ## Generate a sequence of passwords.   # Initialize the random n...
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...
#VBA
VBA
Public Sub Permute(n As Integer, Optional printem As Boolean = True) 'Generate, count and print (if printem is not false) all permutations of first n integers Dim P() As Integer Dim t As Integer, i As Integer, j As Integer, k As Integer Dim count As Long Dim Last As Boolean   If n <= 1 Then   Debug.Print "Please gi...
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...
#TI-83_BASIC
TI-83 BASIC
u(1)=2 u(2)=-4
http://rosettacode.org/wiki/Pathological_floating_point_problems
Pathological floating point problems
Most programmers are familiar with the inexactness of floating point calculations in a binary processor. The classic example being: 0.1 + 0.2 = 0.30000000000000004 In many situations the amount of error in such calculations is very small and can be overlooked or eliminated with rounding. There are pathological pro...
#Visual_Basic_.NET
Visual Basic .NET
Imports System.Globalization Imports System.Numerics Imports Numerics   #Const USE_BIGRATIONAL = True #Const BANDED_ROWS = True #Const INCREASED_LIMITS = True   #If Not USE_BIGRATIONAL Then ' Mock structure to make test code work. Structure BigRational Overrides Function ToString() As String Return "NOT USI...
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...
#Delphi
Delphi
  program Parallel_Brute_Force;   {$APPTYPE CONSOLE}   uses System.SysUtils, System.Threading, DCPsha256;   function Sha256(W: string): string; var HashDigest: array[0..31] of byte; d, i: Byte; begin Result := ''; with TDCP_sha256.Create(nil) do begin Init; UpdateStr(W); final(HashDigest[0])...
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 ...
#F.23
F#
open System open PrimeDecomp // Has the decompose function from the Prime decomposition task   let data = [112272537195293L; 112582718962171L; 112272537095293L; 115280098190773L; 115797840077099L; 1099726829285419L] let decomp num = decompose num 2L   let largestMinPrimeFactor (numbers: int64 list) = let decompDeta...
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 ...
#Factor
Factor
  USING: io kernel fry locals sequences arrays math.primes.factors math.parser channels threads prettyprint ; IN: <filename>   :: map-parallel ( seq quot -- newseq ) <channel> :> ch seq [ '[ _ quot call ch to ] "factors" spawn ] { } map-as dup length [ ch from ] replicate nip ;   { 576460752303423487 576460...
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...
#C.2B.2B
C++
#include <vector> #include <string> #include <sstream> #include <iostream> #include <cmath> #include <algorithm> #include <iterator> #include <cstdlib>   double rpn(const std::string &expr){ std::istringstream iss(expr); std::vector<double> stack; std::cout << "Input\tOperation\tStack after" << std::endl; std::...
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...
#Julia
Julia
function pancake(len) gap, gapsum, adj = 2, 2, -1 while gapsum < len adj += 1 gap = gap * 2 - 1 gapsum += gap end return len + adj end   for i in 1:25 print("pancake(", lpad(i, 2), ") = ", rpad(pancake(i), 5)) i % 5 == 0 && println() end  
http://rosettacode.org/wiki/Pancake_numbers
Pancake numbers
Adrian Monk has problems and an assistant, Sharona Fleming. Sharona can deal with most of Adrian's problems except his lack of punctuality paying her remuneration. 2 pay checks down and she prepares him pancakes for breakfast. Knowing that he will be unable to eat them unless they are stacked in ascending order of size...
#Kotlin
Kotlin
fun pancake(n: Int): Int { var gap = 2 var sum = 2 var adj = -1 while (sum < n) { adj++ gap = gap * 2 - 1 sum += gap } return n + adj }   fun main() { (1 .. 20).map {"p(%2d) = %2d".format(it, pancake(it))} val lines = results.chunked(5).map { it.joinToString(" ")...
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...
#MAD
MAD
NORMAL MODE IS INTEGER VECTOR VALUES ROW = $5(2HP[,I2,4H] = ,I2,S2)*$   INTERNAL FUNCTION(N) ENTRY TO P. GAP = 2 ADJ = -1 THROUGH LOOP, FOR SUM=2, GAP, SUM.GE.N ADJ = ADJ + 1 LOOP GAP = GAP * 2 - 1 FUNCTIO...
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...
#Nim
Nim
import strformat, strutils   func pancake(n: int): int = var gap, sumGaps = 2 pg = 1 adj = -1 while sumGaps < n: inc adj inc pg, gap swap pg, gap inc sumGaps, gap result = n + adj   var line = "" for n in 1..20: line.addSep(" ") line.add &"p({n:>2}) = {pancake(n):>2}" if n mod ...
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...
#Perl
Perl
use strict; use warnings; use feature 'say';   sub pancake { my($n) = @_; my ($gap, $sum, $adj) = (2, 2, -1); while ($sum < $n) { $sum += $gap = $gap * 2 - 1 and $adj++ } $n + $adj; }   my $out; $out .= sprintf "p(%2d) = %2d ", $_, pancake $_ for 1..20; say $out =~ s/.{1,55}\K /\n/gr;   # Maximum number...
http://rosettacode.org/wiki/Palindromic_gapful_numbers
Palindromic gapful numbers
Palindromic gapful numbers You are encouraged to solve this task according to the task description, using any language you may know. Numbers   (positive integers expressed in base ten)   that are (evenly) divisible by the number formed by the first and last digit are known as   gapful numbers. Evenly divisible   mea...
#AppleScript
AppleScript
on doTask() set part1 to {"First 20 palindromic gapful numbers > 100 ending with each digit from 1 to 9:"} set part2 to {"86th to 100th such:"} set part3 to {"991st to 1000th:"} set astid to AppleScript's text item delimiters set AppleScript's text item delimiters to " " repeat with endDigit fr...
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...
#Fortran
Fortran
MODULE COMPILER !At least of arithmetic expressions. INTEGER KBD,MSG !I/O units.   INTEGER ENUFF !How long s a piece of string? PARAMETER (ENUFF = 66) !This long. CHARACTER*(ENUFF) RP !Holds the Reverse Polish Notation. INTEGER LR !And this is its length.   INTEGER OP...
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...
#Go
Go
package main   import ( "fmt" "math/big" )   const branches = 4 const nMax = 500   var rooted, unrooted [nMax + 1]big.Int var c [branches]big.Int var tmp = new(big.Int) var one = big.NewInt(1)   func tree(br, n, l, sum int, cnt *big.Int) { for b := br + 1; b <= branches; b++ { sum += n if su...
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...
#ALGOL_68
ALGOL 68
# init pangram: # INT la = ABS "a", lz = ABS "z"; INT ua = ABS "A", uz = ABS "Z"; IF lz-la+1 > bits width THEN put(stand error, "Exception: insufficient bits in word for task"); stop FI;   PROC is a pangram = (STRING test)BOOL: ( BITS a2z := BIN(ABS(2r1 SHL (lz-la))-1); # assume: ASCII & Binary # FOR i TO UPB t...
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...
#Delphi
Delphi
defmodule Pascal do defp ij(n), do: for i <- 1..n, j <- 1..n, do: {i,j}   def upper_triangle(n) do Enum.reduce(ij(n), Map.new, fn {i,j},acc -> val = cond do i==1 -> 1 j<i -> 0 true -> Map.get(acc, {i-1, j-1}) + Map.get(acc, {i, j-1}) end Map.put...
http://rosettacode.org/wiki/Parameterized_SQL_statement
Parameterized SQL statement
SQL injection Using a SQL update statement like this one (spacing is optional): UPDATE players SET name = 'Smith, Steve', score = 42, active = TRUE WHERE jerseyNum = 99 Non-parameterized SQL is the GoTo statement of database programming. Don't do it, and make sure your coworkers don't either.
#M2000_Interpreter
M2000 Interpreter
  Module Parametrized_Sql { Base "rosetta" ' warning erase database if found it in current directory Execute "rosetta", {create table players (name VarChar(64), score Float, active Integer, jerseyNum Integer);} Append "rosetta", "players","name",0,FALSE,99 sql$={ UPDATE players SET name = '{0}', score = {1}, ...
http://rosettacode.org/wiki/Parameterized_SQL_statement
Parameterized SQL statement
SQL injection Using a SQL update statement like this one (spacing is optional): UPDATE players SET name = 'Smith, Steve', score = 42, active = TRUE WHERE jerseyNum = 99 Non-parameterized SQL is the GoTo statement of database programming. Don't do it, and make sure your coworkers don't either.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Needs["DatabaseLink`"]; conn=OpenSQLConnection[JDBC["ODBC(DSN)","testdb"],"Username"->"John","Password"->"JohnsPassword"]; SQLExecute[conn,"UPDATE players SET name = `1`, score = `2`, active = `3` WHERE jerseyNum = `4`", {SQLArgument["Smith, Steve",42,True,99]}] CloseSQLConnection[conn];
http://rosettacode.org/wiki/Parameterized_SQL_statement
Parameterized SQL statement
SQL injection Using a SQL update statement like this one (spacing is optional): UPDATE players SET name = 'Smith, Steve', score = 42, active = TRUE WHERE jerseyNum = 99 Non-parameterized SQL is the GoTo statement of database programming. Don't do it, and make sure your coworkers don't either.
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols nobinary   import java.sql.   -- ============================================================================= class RParameterizedSQLSimple public   properties indirect connexion = Connection   properties inheritable constant DRIVER = "org...
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...
#BQN
BQN
Pascal ← {(0⊸∾+∾⟜0)⍟(↕𝕩)⋈1}   •Show¨Pascal 6
http://rosettacode.org/wiki/Parse_an_IP_Address
Parse an IP Address
The purpose of this task is to demonstrate parsing of text-format IP addresses, using IPv4 and IPv6. Taking the following as inputs: 127.0.0.1 The "localhost" IPv4 address 127.0.0.1:80 The "localhost" IPv4 address, with a specified port (80) ::1 The "localhost" IPv6 address [::1]:80 The "localhost" IPv6...
#Phix
Phix
with javascript_semantics function parse_ip(string txt) sequence r integer dot = find('.',txt), colon = find(':',txt), openbr = find('[',txt), closebr = find(']',txt) if (colon=5 and txt[1..4] = "http") or (colon=6 and txt[1..5] = "https") then txt = trim(txt...
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, ...
#OCaml
OCaml
type 'a tree = Empty | Node of 'a * 'a tree * 'a tree   (** val map_tree : ('a -> 'b) -> 'a tree -> 'b tree *) let rec map_tree f = function | Empty -> Empty | Node (x,l,r) -> Node (f x, map_tree f l, map_tree f r)
http://rosettacode.org/wiki/Parametric_polymorphism
Parametric polymorphism
Parametric Polymorphism type variables Task Write a small example for a type declaration that is parametric over another type, together with a short bit of code (and its type signature) that uses it. A good example is a container type, let's say a binary tree, together with some function that traverses the tree, ...
#Phix
Phix
<-------- object ---------> | | +-atom +-sequence | | +-integer +-string
http://rosettacode.org/wiki/Parametric_polymorphism
Parametric polymorphism
Parametric Polymorphism type variables Task Write a small example for a type declaration that is parametric over another type, together with a short bit of code (and its type signature) that uses it. A good example is a container type, let's say a binary tree, together with some function that traverses the tree, ...
#PicoLisp
PicoLisp
(de mapTree (Tree Fun) (set Tree (Fun (car Tree))) (and (cadr Tree) (mapTree @ Fun)) (and (cddr Tree) (mapTree @ Fun)) )
http://rosettacode.org/wiki/Parametric_polymorphism
Parametric polymorphism
Parametric Polymorphism type variables Task Write a small example for a type declaration that is parametric over another type, together with a short bit of code (and its type signature) that uses it. A good example is a container type, let's say a binary tree, together with some function that traverses the tree, ...
#Racket
Racket
  #lang typed/racket   (define-type (Tree A) (U False (Node A)))   (struct: (A) Node ([val : A] [left : (Tree A)] [right : (Tree A)]) #:transparent)   (: tree-map (All (A B) (A -> B) (Tree A) -> (Tree B))) (define (tree-map f tree) (match tree [#f #f] [(Node val left right) (Node (f val) (tree-map f ...
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....
#Groovy
Groovy
class PostfixToInfix { static class Expression { final static String ops = "-+/*^"   String op, ex int precedence = 3   Expression(String e) { ex = e }   Expression(String e1, String e2, String o) { ex = String.format "%s %s %s", e1, o, e2 ...
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 ...
#JavaScript
JavaScript
var f1 = function (x) { return x * 2; }, f2 = function (x) { return x * x; },   fs = function (f, s) { return function (s) { return s.map(f); } },   fsf1 = fs(f1), fsf2 = fs(f2);   // Test [ fsf1([0, 1, 2, 3]), fsf2([0, 1, 2, 3]),   fsf1([2, 4,...
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. ...
#REXX
REXX
/*REXX program partitions integer(s) (greater than unity) into N primes. */ parse arg what /*obtain an optional list from the C.L.*/   do until what=='' /*possibly process a series of integers*/ parse var what x n what; parse var x x '-...
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...
#Python
Python
# Pyramid solver # [151] # [ ] [ ] # [ 40] [ ] [ ] # [ ] [ ] [ ] [ ] #[ X ] [ 11] [ Y ] [ 4 ] [ Z ] # X -Y + Z = 0   def combine( snl, snr ):   cl = {} if isinstance(snl, int): cl['1'] = snl elif isinstance(snl, string): cl[snl] = 1 else: cl.update( snl)   if isinst...
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...
#OCaml
OCaml
let lower = "abcdefghijklmnopqrstuvwxyz" let upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" let digit = "0123456789" let other = "!\034#$%&'()*+,-./:;<=>?@[]^_{|}~"   let visually_similar = "Il1O05S2Z"     let mk_pwd len readable = let get_char i = match i mod 4 with | 0 -> lower.[Random.int (String.length lower)] ...
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...
#VBScript
VBScript
  'permutation ,recursive a=array("Hello",1,True,3.141592) cnt=0 perm a,0 wscript.echo vbcrlf &"Count " & cnt   sub print(a) s="" for i=0 to ubound(a): s=s &" " & a(i): next: wscript.echo s : cnt=cnt+1 : end sub sub swap(a,b) t=a: a=b :b=t: end sub   sub perm(byval a,i) if i=ubound(a) then print a: ...
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...
#Wren
Wren
import "/big" for BigRat import "/fmt" for Fmt   var LIMIT = 100 var bigE = BigRat.fromDecimal("2.71828182845904523536028747135266249775724709369995")   // v(n) sequence task var c1 = BigRat.new(111) var c2 = BigRat.new(1130) var c3 = BigRat.new(3000) var v1 = BigRat.two var v2 = BigRat.new(-4) for (i in 3..LIMIT) { ...
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...
#Erlang
Erlang
  #! /usr/bin/escript -mode(compile). -export([cracker/4, supervisor/3]).   hexdigit(N) when (N >= 0) and (N =< 9) -> N + $0; hexdigit(N) when (N >= 10) and (N < 16) -> N - 10 + $a.   hexbyte(N) -> [hexdigit(N bsr 4), hexdigit(N band 15)].   match(Key, Hash) -> B = crypto:hash(sha256, Key), Hash == lists:append...
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 ...
#Fortran
Fortran
  program Primes   use ISO_FORTRAN_ENV   implicit none   integer(int64), dimension(7) :: data = (/2099726827, 15780709, 1122725370, 15808973, 576460741, 12878611, 12757923/) integer(int64), dimension(100) :: outprimes integer(int64) :: largest_factor = 0, largest = 0, minim = 0, val = 0 integer(...
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...
#Ceylon
Ceylon
import ceylon.collection {   ArrayList }   shared void run() {   value ops = map { "+" -> plus<Float>, "*" -> times<Float>, "-" -> ((Float a, Float b) => a - b), "/" -> ((Float a, Float b) => a / b), "^" -> ((Float a, Float b) => a ^ b) };   void printTableRow(String|Float token, String description, {Floa...
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...
#Phix
Phix
with javascript_semantics function pancake(integer n) integer gap = 2, sum_gaps = gap, adj = -1 while sum_gaps<n do adj += 1 gap = gap*2-1 sum_gaps += gap end while n += adj return n end function sequence t = tagset(20), r = columnize({t,apply(t,pancake)}), ...
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...
#Python
Python
"""Pancake numbers. Requires Python>=3.7.""" import time   from collections import deque from operator import itemgetter from typing import Tuple   Pancakes = Tuple[int, ...]     def flip(pancakes: Pancakes, position: int) -> Pancakes: """Flip the stack of pancakes at the given position.""" return tuple([*rever...
http://rosettacode.org/wiki/Palindromic_gapful_numbers
Palindromic gapful numbers
Palindromic gapful numbers You are encouraged to solve this task according to the task description, using any language you may know. Numbers   (positive integers expressed in base ten)   that are (evenly) divisible by the number formed by the first and last digit are known as   gapful numbers. Evenly divisible   mea...
#C
C
#include <stdbool.h> #include <stdio.h> #include <stdint.h>   typedef uint64_t integer;   integer reverse(integer n) { integer rev = 0; while (n > 0) { rev = rev * 10 + (n % 10); n /= 10; } return rev; }   typedef struct palgen_tag { integer power; integer next; int digit; ...