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/Number_reversal_game
Number reversal game
Task Given a jumbled list of the numbers   1   to   9   that are definitely   not   in ascending order. Show the list,   and then ask the player how many digits from the left to reverse. Reverse those digits,   then ask again,   until all the digits end up in ascending order. The score is the count of the reversals needed to attain the ascending order. Note: Assume the player's input does not need extra validation. Related tasks   Sorting algorithms/Pancake sort   Pancake sorting.   Topswops
#OCaml
OCaml
let swap ar i j = let tmp = ar.(i) in ar.(i) <- ar.(j); ar.(j) <- tmp   let shuffle ar = for i = pred(Array.length ar) downto 1 do let j = Random.int (i + 1) in swap ar i j done   let reversal ar n = for i = 0 to pred(n/2) do let j = (pred n) - i in swap ar i j done   let sorted ar = try let prev = ref ar.(0) in for i = 1 to pred(Array.length ar) do if ar.(i) < !prev then raise Exit; prev := ar.(i) done; (true) with Exit -> (false)   let () = print_endline "\ Number Reversal Game Sort the numbers in ascending order by repeatedly flipping sets of numbers from the left."; Random.self_init(); let nums = Array.init 9 (fun i -> succ i) in while sorted nums do shuffle nums done; let n = ref 1 in while not(sorted nums) do Printf.printf "#%2d: " !n; Array.iter (Printf.printf " %d") nums; print_newline(); let r = read_int() in reversal nums r; incr n; done; print_endline "Congratulations!"; Printf.printf "You took %d attempts to put the digits in order.\n" !n; ;;
http://rosettacode.org/wiki/Null_object
Null object
Null (or nil) is the computer science concept of an undefined or unbound object. Some languages have an explicit way to access the null object, and some don't. Some languages distinguish the null object from undefined values, and some don't. Task Show how to access null in your language by checking to see if an object is equivalent to the null object. This task is not about whether a variable is defined. The task is about "null"-like values in various languages, which may or may not be related to the defined-ness of variables in your language.
#Smalltalk
Smalltalk
object isNil ifTrue: [ "true block" ] ifFalse: [ "false block" ]. nil isNil ifTrue: [ 'true!' displayNl ]. "output: true!" foo isNil ifTrue: [ 'ouch' displayNl ]. x := (foo == nil). x := foo isNil
http://rosettacode.org/wiki/Null_object
Null object
Null (or nil) is the computer science concept of an undefined or unbound object. Some languages have an explicit way to access the null object, and some don't. Some languages distinguish the null object from undefined values, and some don't. Task Show how to access null in your language by checking to see if an object is equivalent to the null object. This task is not about whether a variable is defined. The task is about "null"-like values in various languages, which may or may not be related to the defined-ness of variables in your language.
#Standard_ML
Standard ML
datatype 'a option = NONE | SOME of 'a
http://rosettacode.org/wiki/One-dimensional_cellular_automata
One-dimensional cellular automata
Assume an array of cells with an initial distribution of live and dead cells, and imaginary cells off the end of the array having fixed values. Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation. If, in the following table, a live cell is represented by 1 and a dead cell by 0 then to generate the value of the cell at a particular index in the array of cellular values you use the following table: 000 -> 0 # 001 -> 0 # 010 -> 0 # Dies without enough neighbours 011 -> 1 # Needs one neighbour to survive 100 -> 0 # 101 -> 1 # Two neighbours giving birth 110 -> 1 # Needs one neighbour to survive 111 -> 0 # Starved to death.
#Quackery
Quackery
[ stack 0 ] is cells ( --> s )   [ dup size cells replace 0 swap witheach [ char # = | 1 << ] ] is setup ( $ --> n )   [ 0 swap cells share times [ dup i >> 7 & [ table 0 0 0 1 0 1 1 0 ] rot 1 << | swap ] drop 1 << ] is nextline ( n --> n )   [ cells share times [ dup i 1+ bit & iff [ char # ] else [ char _ ] emit ] cr drop ] is echoline ( n --> )   [ setup [ dup echoline dup nextline tuck = until ] echoline ] is automate ( $ --> )   $ "_###_##_#_#_#_#__#__" automate
http://rosettacode.org/wiki/One-dimensional_cellular_automata
One-dimensional cellular automata
Assume an array of cells with an initial distribution of live and dead cells, and imaginary cells off the end of the array having fixed values. Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation. If, in the following table, a live cell is represented by 1 and a dead cell by 0 then to generate the value of the cell at a particular index in the array of cellular values you use the following table: 000 -> 0 # 001 -> 0 # 010 -> 0 # Dies without enough neighbours 011 -> 1 # Needs one neighbour to survive 100 -> 0 # 101 -> 1 # Two neighbours giving birth 110 -> 1 # Needs one neighbour to survive 111 -> 0 # Starved to death.
#R
R
set.seed(15797, kind="Mersenne-Twister")   maxgenerations = 10 cellcount = 20 offendvalue = FALSE   ## Cells are alive if TRUE, dead if FALSE universe <- c(offendvalue, sample( c(TRUE, FALSE), cellcount, replace=TRUE), offendvalue)   ## List of patterns in which the cell stays alive stayingAlive <- lapply(list(c(1,1,0), c(1,0,1), c(0,1,0)), as.logical)   ## x : length 3 logical vector ## map: list of length 3 logical vectors that map to patterns ## in which x stays alive deadOrAlive <- function(x, map) list(x) %in% map   cellularAutomata <- function(x, map) { c(x[1], apply(embed(x, 3), 1, deadOrAlive, map=map), x[length(x)]) }   deadOrAlive2string <- function(x) { paste(ifelse(x, '#', '_'), collapse="") }   for (i in 1:maxgenerations) { universe <- cellularAutomata(universe, stayingAlive) cat(format(i, width=3), deadOrAlive2string(universe), "\n") }
http://rosettacode.org/wiki/Numerical_integration
Numerical integration
Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods: rectangular left right midpoint trapezium Simpson's composite Your functions should take in the upper and lower bounds (a and b), and the number of approximations to make in that range (n). Assume that your example already has a function that gives values for ƒ(x) . Simpson's method is defined by the following pseudo-code: Pseudocode: Simpson's method, composite procedure quad_simpson_composite(f, a, b, n) h := (b - a) / n sum1 := f(a + h/2) sum2 := 0 loop on i from 1 to (n - 1) sum1 := sum1 + f(a + h * i + h/2) sum2 := sum2 + f(a + h * i)   answer := (h / 6) * (f(a) + f(b) + 4*sum1 + 2*sum2) Demonstrate your function by showing the results for:   ƒ(x) = x3,       where   x   is     [0,1],       with           100 approximations.   The exact result is     0.25               (or 1/4)   ƒ(x) = 1/x,     where   x   is   [1,100],     with        1,000 approximations.   The exact result is     4.605170+     (natural log of 100)   ƒ(x) = x,         where   x   is   [0,5000],   with 5,000,000 approximations.   The exact result is   12,500,000   ƒ(x) = x,         where   x   is   [0,6000],   with 6,000,000 approximations.   The exact result is   18,000,000 See also   Active object for integrating a function of real time.   Special:PrefixIndex/Numerical integration for other integration methods.
#SequenceL
SequenceL
import <Utilities/Conversion.sl>; import <Utilities/Sequence.sl>;   integrateLeft(f, a, b, n) := let h := (b - a) / n; vals[x] := f(x) foreach x within (0 ... (n-1)) * h + a; in h * sum(vals);   integrateRight(f, a, b, n) := let h := (b - a) / n; vals[x] := f(x+h) foreach x within (0 ... (n-1)) * h + a; in h * sum(vals);   integrateMidpoint(f, a, b, n) := let h := (b - a) / n; vals[x] := f(x+h/2.0) foreach x within (0 ... (n-1)) * h + a; in h * sum(vals);   integrateTrapezium(f, a, b, n) := let h := (b - a) / n; vals[i] := 2.0 * f(a + i * h) foreach i within 1 ... n-1; in h * (sum(vals) + f(a) + f(b)) / 2.0;   integrateSimpsons(f, a, b, n) := let h := (b - a) / n; vals1[i] := f(a + h * i + h / 2.0) foreach i within 0 ... n-1; vals2[i] := f(a + h * i) foreach i within 1 ... n-1; in h / 6.0 * (f(a) + f(b) + 4.0 * sum(vals1) + 2.0 * sum(vals2));   xCubed(x) := x^3; xInverse(x) := 1/x; identity(x) := x;   tests[method] := [method(xCubed, 0.0, 1.0, 100), method(xInverse, 1.0, 100.0, 1000), method(identity, 0.0, 5000.0, 5000000), method(identity, 0.0, 6000.0, 6000000)] foreach method within [integrateLeft, integrateRight, integrateMidpoint, integrateTrapezium, integrateSimpsons];   //String manipulation for ouput display. main := let heading := [["Func", "Range\t", "L-Rect\t", "R-Rect\t", "M-Rect\t", "Trapezium", "Simpson"]]; ranges := [["0 - 1\t", "1 - 100\t", "0 - 5000", "0 - 6000"]]; funcs := [["x^3", "1/x", "x", "x"]]; in delimit(delimit(heading ++ transpose(funcs ++ ranges ++ trimEndZeroes(floatToString(tests, 8))), '\t'), '\n');   trimEndZeroes(x(1)) := x when size(x) = 0 else x when x[size(x)] /= '0' else trimEndZeroes(x[1...size(x)-1]);
http://rosettacode.org/wiki/Number_names
Number names
Task Show how to spell out a number in English. You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less). Support for inputs other than positive integers (like zero, negative integers, and floating-point numbers) is optional. Related task   Spelling of ordinal numbers.
#Nim
Nim
import strutils, algorithm   const tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"] small = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"] huge = ["", "", "million", "billion", "trillion", "quadrillion", "quintillion", "sextillion", "septillion", "octillion", "nonillion", "decillion"]   # Forward reference. proc spellInteger(n: int64): string   proc nonzero(c: string; n: int64; connect = ""): string = if n == 0: "" else: connect & c & spellInteger(n)   proc lastAnd(num: string): string = if ',' in num: let pos = num.rfind(',') var (pre, last) = if pos >= 0: (num[0 ..< pos], num[pos+1 .. num.high]) else: ("", num) if " and " notin last: last = " and" & last result = [pre, ",", last].join() else: result = num   proc big(e, n: int64): string = if e == 0: spellInteger(n) elif e == 1: spellInteger(n) & " thousand" else: spellInteger(n) & " " & huge[e]   iterator base1000Rev(n: int64): int64 = var n = n while n != 0: let r = n mod 1000 n = n div 1000 yield r   proc spellInteger(n: int64): string = if n < 0: "minus " & spellInteger(-n) elif n < 20: small[int(n)] elif n < 100: let a = n div 10 let b = n mod 10 tens[int(a)] & nonzero("-", b) elif n < 1000: let a = n div 100 let b = n mod 100 small[int(a)] & " hundred" & nonzero(" ", b, " and") else: var sq = newSeq[string]() var e = 0 for x in base1000Rev(n): if x > 0: sq.add big(e, x) inc e reverse sq lastAnd(sq.join(", "))   for n in [0, -3, 5, -7, 11, -13, 17, -19, 23, -29]: echo align($n, 4)," -> ",spellInteger(n)   var n = 201021002001 while n != 0: echo align($n, 14)," -> ",spellInteger(n) n = n div -10
http://rosettacode.org/wiki/Number_reversal_game
Number reversal game
Task Given a jumbled list of the numbers   1   to   9   that are definitely   not   in ascending order. Show the list,   and then ask the player how many digits from the left to reverse. Reverse those digits,   then ask again,   until all the digits end up in ascending order. The score is the count of the reversals needed to attain the ascending order. Note: Assume the player's input does not need extra validation. Related tasks   Sorting algorithms/Pancake sort   Pancake sorting.   Topswops
#Oforth
Oforth
import: console   : reversalGame | l n | doWhile: [ ListBuffer new ->l while(l size 9 <>) [ 9 rand dup l include ifFalse: [ l add ] else: [ drop ] ] l sort l == ]   0 while(l sort l <>) [ System.Out "List is " << l << " ==> how many digits from left to reverse : " <- System.Console askln asInteger dup ifNull: [ drop continue ] ->n 1+ l left(n) reverse l right(l size n -) + ->l ] "You won ! Your score is :" . println ;
http://rosettacode.org/wiki/Null_object
Null object
Null (or nil) is the computer science concept of an undefined or unbound object. Some languages have an explicit way to access the null object, and some don't. Some languages distinguish the null object from undefined values, and some don't. Task Show how to access null in your language by checking to see if an object is equivalent to the null object. This task is not about whether a variable is defined. The task is about "null"-like values in various languages, which may or may not be related to the defined-ness of variables in your language.
#Swift
Swift
let maybeInt: Int? = nil
http://rosettacode.org/wiki/Null_object
Null object
Null (or nil) is the computer science concept of an undefined or unbound object. Some languages have an explicit way to access the null object, and some don't. Some languages distinguish the null object from undefined values, and some don't. Task Show how to access null in your language by checking to see if an object is equivalent to the null object. This task is not about whether a variable is defined. The task is about "null"-like values in various languages, which may or may not be related to the defined-ness of variables in your language.
#Tailspin
Tailspin
  templates mightBeNothing when <=0> do !VOID when <=1> do 'something' ! end mightBeNothing   1 -> mightBeNothing -> 'Produced $;. ' -> !OUT::write   0 -> mightBeNothing -> 'Won''t execute this' -> !OUT::write 2 -> mightBeNothing -> 'Won''t execute this' -> !OUT::write   // capture the transform in a list to continue computation when no result is emitted [1 -> mightBeNothing] -> \( when <=[]> 'Produced nothing. ' ! otherwise 'Produced $(1);. ' ! \) -> !OUT::write   [0 -> mightBeNothing] -> \( when <=[]> 'Produced nothing. ' ! otherwise 'Produced $(1);. ' ! \) -> !OUT::write   [2 -> mightBeNothing] -> \( when <=[]> 'Produced nothing. ' ! otherwise 'Produced $(1);. ' ! \) -> !OUT::write  
http://rosettacode.org/wiki/Null_object
Null object
Null (or nil) is the computer science concept of an undefined or unbound object. Some languages have an explicit way to access the null object, and some don't. Some languages distinguish the null object from undefined values, and some don't. Task Show how to access null in your language by checking to see if an object is equivalent to the null object. This task is not about whether a variable is defined. The task is about "null"-like values in various languages, which may or may not be related to the defined-ness of variables in your language.
#Tcl
Tcl
if {$value eq ""} ...
http://rosettacode.org/wiki/One-dimensional_cellular_automata
One-dimensional cellular automata
Assume an array of cells with an initial distribution of live and dead cells, and imaginary cells off the end of the array having fixed values. Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation. If, in the following table, a live cell is represented by 1 and a dead cell by 0 then to generate the value of the cell at a particular index in the array of cellular values you use the following table: 000 -> 0 # 001 -> 0 # 010 -> 0 # Dies without enough neighbours 011 -> 1 # Needs one neighbour to survive 100 -> 0 # 101 -> 1 # Two neighbours giving birth 110 -> 1 # Needs one neighbour to survive 111 -> 0 # Starved to death.
#Racket
Racket
#lang racket   (define (update cells) (for/list ([crowding (map + (append '(0) (drop-right cells 1)) cells (append (drop cells 1) '(0)))]) (if (= 2 crowding) 1 0)))   (define (life-of cells time) (unless (zero? time) (displayln cells) (life-of (update cells) (sub1 time))))   (life-of '(0 1 1 1 0 1 1 0 1 0 1 0 1 0 1 0 0 1 0 0) 10)   #| (0 1 1 1 0 1 1 0 1 0 1 0 1 0 1 0 0 1 0 0) (0 1 0 1 1 1 1 1 0 1 0 1 0 1 0 0 0 0 0 0) (0 0 1 1 0 0 0 1 1 0 1 0 1 0 0 0 0 0 0 0) (0 0 1 1 0 0 0 1 1 1 0 1 0 0 0 0 0 0 0 0) (0 0 1 1 0 0 0 1 0 1 1 0 0 0 0 0 0 0 0 0) (0 0 1 1 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0) (0 0 1 1 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0) (0 0 1 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0) (0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0) (0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0) |#
http://rosettacode.org/wiki/One-dimensional_cellular_automata
One-dimensional cellular automata
Assume an array of cells with an initial distribution of live and dead cells, and imaginary cells off the end of the array having fixed values. Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation. If, in the following table, a live cell is represented by 1 and a dead cell by 0 then to generate the value of the cell at a particular index in the array of cellular values you use the following table: 000 -> 0 # 001 -> 0 # 010 -> 0 # Dies without enough neighbours 011 -> 1 # Needs one neighbour to survive 100 -> 0 # 101 -> 1 # Two neighbours giving birth 110 -> 1 # Needs one neighbour to survive 111 -> 0 # Starved to death.
#Raku
Raku
class Automaton { has $.rule; has @.cells; has @.code = $!rule.fmt('%08b').flip.comb».Int;   method gist { "|{ @!cells.map({+$_ ?? '#' !! ' '}).join }|" }   method succ { self.new: :$!rule, :@!code, :cells( @!code[ 4 «*« @!cells.rotate(-1)  »+« 2 «*« @!cells  »+«  @!cells.rotate(1) ] ) } }   # The rule proposed for this task is rule 0b01101000 = 104   my @padding = 0 xx 5; my Automaton $a .= new: rule => 104, cells => flat @padding, '111011010101'.comb, @padding ; say $a++ for ^10;     # Rule 104 is not particularly interesting so here is [[wp:Rule 90|Rule 90]], # which shows a [[wp:Sierpinski Triangle|Sierpinski Triangle]].   say ''; @padding = 0 xx 25; $a = Automaton.new: :rule(90), :cells(flat @padding, 1, @padding);   say $a++ for ^20;
http://rosettacode.org/wiki/Numerical_integration
Numerical integration
Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods: rectangular left right midpoint trapezium Simpson's composite Your functions should take in the upper and lower bounds (a and b), and the number of approximations to make in that range (n). Assume that your example already has a function that gives values for ƒ(x) . Simpson's method is defined by the following pseudo-code: Pseudocode: Simpson's method, composite procedure quad_simpson_composite(f, a, b, n) h := (b - a) / n sum1 := f(a + h/2) sum2 := 0 loop on i from 1 to (n - 1) sum1 := sum1 + f(a + h * i + h/2) sum2 := sum2 + f(a + h * i)   answer := (h / 6) * (f(a) + f(b) + 4*sum1 + 2*sum2) Demonstrate your function by showing the results for:   ƒ(x) = x3,       where   x   is     [0,1],       with           100 approximations.   The exact result is     0.25               (or 1/4)   ƒ(x) = 1/x,     where   x   is   [1,100],     with        1,000 approximations.   The exact result is     4.605170+     (natural log of 100)   ƒ(x) = x,         where   x   is   [0,5000],   with 5,000,000 approximations.   The exact result is   12,500,000   ƒ(x) = x,         where   x   is   [0,6000],   with 6,000,000 approximations.   The exact result is   18,000,000 See also   Active object for integrating a function of real time.   Special:PrefixIndex/Numerical integration for other integration methods.
#Sidef
Sidef
func sum(f, start, from, to) { var s = 0; RangeNum(start, to, from-start).each { |i| s += f(i); } return s }   func leftrect(f, a, b, n) { var h = ((b - a) / n); h * sum(f, a, a+h, b-h); }   func rightrect(f, a, b, n) { var h = ((b - a) / n); h * sum(f, a+h, a + 2*h, b); }   func midrect(f, a, b, n) { var h = ((b - a) / n); h * sum(f, a + h/2, a + h + h/2, b - h/2) }   func trapez(f, a, b, n) { var h = ((b - a) / n); h/2 * (f(a) + f(b) + sum({ f(_)*2 }, a+h, a + 2*h, b-h)); }   func simpsons(f, a, b, n) { var h = ((b - a) / n); var h2 = h/2;   var sum1 = f(a + h2); var sum2 = 0;   sum({|i| sum1 += f(i + h2); sum2 += f(i); 0 }, a+h, a+h+h, b-h); h/6 * (f(a) + f(b) + 4*sum1 + 2*sum2); }   func tryem(label, f, a, b, n, exact) { say "\n#{label}\n in [#{a}..#{b}] / #{n}";   say(' exact result: ', exact); say(' rectangle method left: ', leftrect(f, a, b, n)); say(' rectangle method right: ', rightrect(f, a, b, n)); say(' rectangle method mid: ', midrect(f, a, b, n)); say('composite trapezoidal rule: ', trapez(f, a, b, n)); say(' quadratic simpsons rule: ', simpsons(f, a, b, n)); }   tryem('x^3', { _ ** 3 }, 0, 1, 100, 0.25); tryem('1/x', { 1 / _ }, 1, 100, 1000, log(100)); tryem('x', { _ }, 0, 5_000, 5_000_000, 12_500_000); tryem('x', { _ }, 0, 6_000, 6_000_000, 18_000_000);
http://rosettacode.org/wiki/Number_names
Number names
Task Show how to spell out a number in English. You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less). Support for inputs other than positive integers (like zero, negative integers, and floating-point numbers) is optional. Related task   Spelling of ordinal numbers.
#Objeck
Objeck
  class NumberNames { small : static : String[]; tens : static : String[]; big : static : String[];   function : Main(args : String[]) ~ Nil { small := ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]; tens := ["twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]; big := ["thousand", "million", "billion", "trillion"];   Int2Text(900000001)->PrintLine(); Int2Text(1234567890)->PrintLine(); Int2Text(-987654321)->PrintLine(); Int2Text(0)->PrintLine(); }   function : native : Int2Text(number : Int) ~ String { num := 0; outP := ""; unit := 0; tmpLng1 := 0;   if (number = 0) { return "zero"; };   num := number->Abs();   while(true) { tmpLng1 := num % 100; if (tmpLng1 >= 1 & tmpLng1 <= 19) { tmp := String->New(); tmp->Append(small[tmpLng1 - 1]); tmp->Append(" "); tmp->Append(outP); outP := tmp; } else if (tmpLng1 >= 20 & tmpLng1 <= 99) { if (tmpLng1 % 10 = 0) { tmp := String->New(); tmp->Append(tens[(tmpLng1 / 10) - 2]); tmp->Append(" "); tmp->Append(outP); outP := tmp; } else { tmp := String->New(); tmp->Append(tens[(tmpLng1 / 10) - 2]); tmp->Append( "-"); tmp->Append(small[(tmpLng1 % 10) - 1]); tmp->Append(" "); tmp->Append(outP); outP := tmp; }; };   tmpLng1 := (num % 1000) / 100; if (tmpLng1 <> 0) { tmp := String->New(); tmp->Append(small[tmpLng1 - 1]); tmp->Append(" hundred "); tmp->Append(outP); outP := tmp; };   num /= 1000; if (num = 0) { break; };   tmpLng1 := num % 1000; if (tmpLng1 <> 0) { tmp := String->New(); tmp->Append(big[unit]); tmp->Append(" "); tmp->Append(outP); outP := tmp; }; unit+=1; };   if (number < 0) { tmp := String->New(); tmp->Append("negative "); tmp->Append(outP); outP := tmp; };   return outP->Trim(); } }  
http://rosettacode.org/wiki/Number_reversal_game
Number reversal game
Task Given a jumbled list of the numbers   1   to   9   that are definitely   not   in ascending order. Show the list,   and then ask the player how many digits from the left to reverse. Reverse those digits,   then ask again,   until all the digits end up in ascending order. The score is the count of the reversals needed to attain the ascending order. Note: Assume the player's input does not need extra validation. Related tasks   Sorting algorithms/Pancake sort   Pancake sorting.   Topswops
#Oz
Oz
declare proc {Main} proc {Loop N Xs} if {Not {IsSorted Xs}} then Num NewXs in {System.printInfo N#": "} {System.print Xs} {System.printInfo " -- Reverse how many? "} Num = {String.toInt {ReadLine}} NewXs = {Append {Reverse {List.take Xs Num}} {List.drop Xs Num}} {Loop N+1 NewXs} else {System.showInfo "You took "#N#" tries to put the digits in order."} end end fun {EnsureShuffled Xs} Ys = {Shuffle Xs} in if {Not {IsSorted Ys}} then Ys else {EnsureShuffled Xs} end end in {Loop 0 {EnsureShuffled {List.number 1 9 1}}} end   fun {IsSorted Xs} {Sort Xs Value.'<'} == Xs end   local class TextFile from Open.file Open.text end StdIn = {New TextFile init(name:stdin)} in fun {ReadLine} {StdIn getS($)} end end   fun {Shuffle Xs} {FoldL Xs fun {$ Z _} {Pick {Diff Xs Z}}|Z end nil} end   fun {Pick Xs} {Nth Xs {OS.rand} mod {Length Xs} + 1} end   fun {Diff Xs Ys} {FoldL Ys List.subtract Xs} end in {Main}
http://rosettacode.org/wiki/Null_object
Null object
Null (or nil) is the computer science concept of an undefined or unbound object. Some languages have an explicit way to access the null object, and some don't. Some languages distinguish the null object from undefined values, and some don't. Task Show how to access null in your language by checking to see if an object is equivalent to the null object. This task is not about whether a variable is defined. The task is about "null"-like values in various languages, which may or may not be related to the defined-ness of variables in your language.
#Ursa
Ursa
# the type at declaration doesn't matter decl int x   set x null if (= x null) out "x is null" endl console else out "x is not null" endl console end if
http://rosettacode.org/wiki/Null_object
Null object
Null (or nil) is the computer science concept of an undefined or unbound object. Some languages have an explicit way to access the null object, and some don't. Some languages distinguish the null object from undefined values, and some don't. Task Show how to access null in your language by checking to see if an object is equivalent to the null object. This task is not about whether a variable is defined. The task is about "null"-like values in various languages, which may or may not be related to the defined-ness of variables in your language.
#VBA
VBA
Public Sub Main() Dim c As VBA.Collection   ' initial state: Nothing Debug.Print c Is Nothing   ' create an instance Set c = New VBA.Collection Debug.Print Not c Is Nothing   ' release the instance Set c = Nothing Debug.Print c Is Nothing End Sub
http://rosettacode.org/wiki/Null_object
Null object
Null (or nil) is the computer science concept of an undefined or unbound object. Some languages have an explicit way to access the null object, and some don't. Some languages distinguish the null object from undefined values, and some don't. Task Show how to access null in your language by checking to see if an object is equivalent to the null object. This task is not about whether a variable is defined. The task is about "null"-like values in various languages, which may or may not be related to the defined-ness of variables in your language.
#Visual_Basic
Visual Basic
  Public Sub Main() Dim c As VBA.Collection   ' initial state: Nothing Debug.Assert c Is Nothing   ' create an instance Set c = New VBA.Collection Debug.Assert Not c Is Nothing   ' release the instance Set c = Nothing Debug.Assert c Is Nothing   End Sub  
http://rosettacode.org/wiki/One-dimensional_cellular_automata
One-dimensional cellular automata
Assume an array of cells with an initial distribution of live and dead cells, and imaginary cells off the end of the array having fixed values. Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation. If, in the following table, a live cell is represented by 1 and a dead cell by 0 then to generate the value of the cell at a particular index in the array of cellular values you use the following table: 000 -> 0 # 001 -> 0 # 010 -> 0 # Dies without enough neighbours 011 -> 1 # Needs one neighbour to survive 100 -> 0 # 101 -> 1 # Two neighbours giving birth 110 -> 1 # Needs one neighbour to survive 111 -> 0 # Starved to death.
#Red
Red
Red [ Purpose: "One-dimensional cellular automata" Author: "Joe Smith" ]   vals: [0 1 0] kill: [[0 0] [#[none] 0] [0 #[none]]] evo: function [petri] [ new-petri: copy petri while [petri/1] [ if all [petri/-1 = 1 petri/2 = 1] [new-petri/1: select vals petri/1] if find/only kill reduce [petri/-1 petri/2] [new-petri/1: 0] petri: next petri new-petri: next new-petri ] petri: head petri new-petri: head new-petri clear insert petri new-petri ]   display: function [petri] [ print replace/all (replace/all to-string petri "0" "_") "1" "#" petri ]   loop 10 [ evo display [1 1 1 0 1 1 0 1 0 1 0 1 0 1 0 0 1 0] ]  
http://rosettacode.org/wiki/Numerical_integration
Numerical integration
Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods: rectangular left right midpoint trapezium Simpson's composite Your functions should take in the upper and lower bounds (a and b), and the number of approximations to make in that range (n). Assume that your example already has a function that gives values for ƒ(x) . Simpson's method is defined by the following pseudo-code: Pseudocode: Simpson's method, composite procedure quad_simpson_composite(f, a, b, n) h := (b - a) / n sum1 := f(a + h/2) sum2 := 0 loop on i from 1 to (n - 1) sum1 := sum1 + f(a + h * i + h/2) sum2 := sum2 + f(a + h * i)   answer := (h / 6) * (f(a) + f(b) + 4*sum1 + 2*sum2) Demonstrate your function by showing the results for:   ƒ(x) = x3,       where   x   is     [0,1],       with           100 approximations.   The exact result is     0.25               (or 1/4)   ƒ(x) = 1/x,     where   x   is   [1,100],     with        1,000 approximations.   The exact result is     4.605170+     (natural log of 100)   ƒ(x) = x,         where   x   is   [0,5000],   with 5,000,000 approximations.   The exact result is   12,500,000   ƒ(x) = x,         where   x   is   [0,6000],   with 6,000,000 approximations.   The exact result is   18,000,000 See also   Active object for integrating a function of real time.   Special:PrefixIndex/Numerical integration for other integration methods.
#Standard_ML
Standard ML
fun integrate (f, a, b, steps, meth) = let val h = (b - a) / real steps fun helper (i, s) = if i >= steps then s else helper (i+1, s + meth (f, a + h * real i, h)) in h * helper (0, 0.0) end   fun leftRect (f, x, _) = f x fun midRect (f, x, h) = f (x + h / 2.0) fun rightRect (f, x, h) = f (x + h) fun trapezium (f, x, h) = (f x + f (x + h)) / 2.0 fun simpson (f, x, h) = (f x + 4.0 * f (x + h / 2.0) + f (x + h)) / 6.0   fun square x = x * x     val rl = integrate (square, 0.0, 1.0, 10, left_rect ) val rm = integrate (square, 0.0, 1.0, 10, mid_rect ) val rr = integrate (square, 0.0, 1.0, 10, right_rect) val t = integrate (square, 0.0, 1.0, 10, trapezium ) val s = integrate (square, 0.0, 1.0, 10, simpson )
http://rosettacode.org/wiki/Number_names
Number names
Task Show how to spell out a number in English. You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less). Support for inputs other than positive integers (like zero, negative integers, and floating-point numbers) is optional. Related task   Spelling of ordinal numbers.
#Objective-C
Objective-C
#import <Foundation/Foundation.h>   int main() { @autoreleasepool {   NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init]; numberFormatter.numberStyle = NSNumberFormatterSpellOutStyle; numberFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];   for (NSNumber *n in @[@900000001, @1234567890, @-987654321, @0, @3.14]) { NSLog(@"%@", [numberFormatter stringFromNumber:n]); }   } return 0; }
http://rosettacode.org/wiki/Number_reversal_game
Number reversal game
Task Given a jumbled list of the numbers   1   to   9   that are definitely   not   in ascending order. Show the list,   and then ask the player how many digits from the left to reverse. Reverse those digits,   then ask again,   until all the digits end up in ascending order. The score is the count of the reversals needed to attain the ascending order. Note: Assume the player's input does not need extra validation. Related tasks   Sorting algorithms/Pancake sort   Pancake sorting.   Topswops
#PARI.2FGP
PARI/GP
game()={ my(v=numtoperm(9,random(9!-1)),score,in,t); \\ Create vector with 1..9, excluding the one sorted in ascending order while(v!=vecsort(v), print(concat(concat([""],v))); in=input(); for(i=0,in\2-1, t=v[9-i]; v[9-i]=v[10-in+i]; v[10-in+i]=t ); score++ ); score };
http://rosettacode.org/wiki/Null_object
Null object
Null (or nil) is the computer science concept of an undefined or unbound object. Some languages have an explicit way to access the null object, and some don't. Some languages distinguish the null object from undefined values, and some don't. Task Show how to access null in your language by checking to see if an object is equivalent to the null object. This task is not about whether a variable is defined. The task is about "null"-like values in various languages, which may or may not be related to the defined-ness of variables in your language.
#Wart
Wart
(not nil)  
http://rosettacode.org/wiki/Null_object
Null object
Null (or nil) is the computer science concept of an undefined or unbound object. Some languages have an explicit way to access the null object, and some don't. Some languages distinguish the null object from undefined values, and some don't. Task Show how to access null in your language by checking to see if an object is equivalent to the null object. This task is not about whether a variable is defined. The task is about "null"-like values in various languages, which may or may not be related to the defined-ness of variables in your language.
#Wren
Wren
// Declare a variable without giving it an explicit value. var s   // We can now check for nullness in one of these ways. System.print(s) System.print(s == null) System.print(s is Null) System.print(s.type == Null)   // Similarly, if we define this function without giving it a return value. var f = Fn.new { System.print("I'm a function with no explicit return value.") }   // And now call it. var g = f.call() // We find that the return value is null. System.print(g)
http://rosettacode.org/wiki/One-dimensional_cellular_automata
One-dimensional cellular automata
Assume an array of cells with an initial distribution of live and dead cells, and imaginary cells off the end of the array having fixed values. Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation. If, in the following table, a live cell is represented by 1 and a dead cell by 0 then to generate the value of the cell at a particular index in the array of cellular values you use the following table: 000 -> 0 # 001 -> 0 # 010 -> 0 # Dies without enough neighbours 011 -> 1 # Needs one neighbour to survive 100 -> 0 # 101 -> 1 # Two neighbours giving birth 110 -> 1 # Needs one neighbour to survive 111 -> 0 # Starved to death.
#Retro
Retro
# 1D Cellular Automota   Assume an array of cells with an initial distribution of live and dead cells, and imaginary cells off the end of the array having fixed values.   Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbors in the current generation.   If, in the following table, a live cell is represented by 1 and a dead cell by 0 then to generate the value of the cell at a particular index in the array of cellular values you use the following table:   000 -> 0 # 001 -> 0 # 010 -> 0 # Dies without enough neighbours 011 -> 1 # Needs one neighbour to survive 100 -> 0 # 101 -> 1 # Two neighbours giving birth 110 -> 1 # Needs one neighbour to survive 111 -> 0 # Starved to death.   I had originally written an implementation of this in RETRO 11. For RETRO 12 I took advantage of new language features and some further considerations into the rules for this task.   The first word, `string,` inlines a string to `here`. I'll use this to setup the initial input.   ~~~ :string, (s-) [ , ] s:for-each #0 , ; ~~~   The next two lines setup an initial generation and a buffer for the evolved generation. In this case, `This` is the current generation and `Next` reflects the next step in the evolution.   ~~~ 'This d:create '.###.##.#.#.#.#..#.. string,   'Next d:create '.................... string, ~~~   I use `display` to show the current generation.   ~~~ :display (-) &This s:put nl ; ~~~   As might be expected, `update` copies the `Next` generation to the `This` generation, setting things up for the next cycle.   ~~~ :update (-) &Next &This dup s:length copy ; ~~~   The word `group` extracts a group of three cells. This data will be passed to `evolve` for processing.   ~~~ :group (a-nnn) [ fetch ] [ n:inc fetch ] [ n:inc n:inc fetch ] tri ; ~~~   I use `evolve` to decide how a cell should change, based on its initial state with relation to its neighbors.   In the prior implementation this part was much more complex as I tallied things up and had separate conditions for each combination. This time I take advantage of the fact that only cells with two neighbors will be alive in the next generation. So the process is:   - take the data from `group` - compare to `$#` (for living cells) - add the flags - if the result is `#-2`, the cell should live - otherwise it'll be dead   ~~~ :evolve (nnn-c) [ $# eq? ] tri@ + + #-2 eq? [ $# ] [ $. ] choose ; ~~~   For readability I separated out the next few things. `at` takes an index and returns the address in `This` starting with the index.   ~~~ :at (n-na) &This over + ; ~~~   The `record` word adds the evolved value to a buffer. In this case my `generation` code will set the buffer to `Next`.   ~~~ :record (c-) buffer:add n:inc ; ~~~   And now to tie it all together. Meet `generation`, the longest bit of code in this sample. It has several bits:   - setup a new buffer pointing to `Next`   - this also preserves the old buffer   - setup a loop for each cell in `This`   - initial loop index at -1, to ensure proper dummy state for first cell - get length of `This` generation   - perform a loop for each item in the generation, updating `Next` as it goes   - copy `Next` to `This` using `update`.   ~~~ :generation (-) [ &Next buffer:set #-1 &This s:length [ at group evolve record ] times drop update ] buffer:preserve ; ~~~   The last bit is a helper. It takes a number of generations and displays the state, then runs a `generation`.   ~~~ :generations (n-) [ display generation ] times ; ~~~   And a text. The output should be:   .###.##.#.#.#.#..#.. .#.#####.#.#.#...... ..##...##.#.#....... ..##...###.#........ ..##...#.##......... ..##....###......... ..##....#.#......... ..##.....#.......... ..##................ ..##................   ~~~ #10 generations ~~~
http://rosettacode.org/wiki/Nonoblock
Nonoblock
Nonoblock is a chip off the old Nonogram puzzle. Given The number of cells in a row. The size of each, (space separated), connected block of cells to fit in the row, in left-to right order. Task show all possible positions. show the number of positions of the blocks for the following cases within the row. show all output on this page. use a "neat" diagram of the block positions. Enumerate the following configurations   5   cells   and   [2, 1]   blocks   5   cells   and   []   blocks   (no blocks)   10   cells   and   [8]   blocks   15   cells   and   [2, 3, 2, 3]   blocks   5   cells   and   [2, 3]   blocks   (should give some indication of this not being possible) Example Given a row of five cells and a block of two cells followed by a block of one cell - in that order, the example could be shown as: |_|_|_|_|_| # 5 cells and [2, 1] blocks And would expand to the following 3 possible rows of block positions: |A|A|_|B|_| |A|A|_|_|B| |_|A|A|_|B| Note how the sets of blocks are always separated by a space. Note also that it is not necessary for each block to have a separate letter. Output approximating This: |#|#|_|#|_| |#|#|_|_|#| |_|#|#|_|#| This would also work: ##.#. ##..# .##.# An algorithm Find the minimum space to the right that is needed to legally hold all but the leftmost block of cells (with a space between blocks remember). The leftmost cell can legitimately be placed in all positions from the LHS up to a RH position that allows enough room for the rest of the blocks. for each position of the LH block recursively compute the position of the rest of the blocks in the remaining space to the right of the current placement of the LH block. (This is the algorithm used in the Nonoblock#Python solution). Reference The blog post Nonogram puzzle solver (part 1) Inspired this task and donated its Nonoblock#Python solution.
#11l
11l
F nonoblocks([Int] &blocks, Int cells) -> [[(Int, Int)]] [[(Int, Int)]] r I blocks.empty | blocks[0] == 0 r [+]= [(0, 0)] E assert(sum(blocks) + blocks.len - 1 <= cells, ‘Those blocks will not fit in those cells’) V (blength, brest) = (blocks[0], blocks[1..]) V minspace4rest = sum(brest.map(b -> 1 + b))   L(bpos) 0 .. cells - minspace4rest - blength I brest.empty r [+]= [(bpos, blength)] E V offset = bpos + blength + 1 L(subpos) nonoblocks(&brest, cells - offset) V rest = subpos.map((bp, bl) -> (@offset + bp, bl)) V vec = [(bpos, blength)] [+] rest r [+]= vec R r   F pblock(vec, cells) ‘Prettyprints each run of blocks with a different letter A.. for each block of filled cells’ V vector = [‘_’] * cells L(bp_bl) vec V ch = L.index + ‘A’.code V (bp, bl) = bp_bl L(i) bp .< bp + bl vector[i] = I vector[i] == ‘_’ {Char(code' ch)} E Char(‘?’) R ‘|’vector.join(‘|’)‘|’   L(blocks, cells) [ ([2, 1], 5), ([Int](), 5), ([8], 10), ([2, 3, 2, 3], 15) ] print("\nConfiguration:\n #. ## #. cells and #. blocks".format(pblock([(Int, Int)](), cells), cells, blocks)) print(‘ Possibilities:’) V nb = nonoblocks(&blocks, cells) L(vector) nb print(‘ ’pblock(vector, cells)) print(‘ A total of #. Possible configurations.’.format(nb.len))
http://rosettacode.org/wiki/Numerical_integration
Numerical integration
Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods: rectangular left right midpoint trapezium Simpson's composite Your functions should take in the upper and lower bounds (a and b), and the number of approximations to make in that range (n). Assume that your example already has a function that gives values for ƒ(x) . Simpson's method is defined by the following pseudo-code: Pseudocode: Simpson's method, composite procedure quad_simpson_composite(f, a, b, n) h := (b - a) / n sum1 := f(a + h/2) sum2 := 0 loop on i from 1 to (n - 1) sum1 := sum1 + f(a + h * i + h/2) sum2 := sum2 + f(a + h * i)   answer := (h / 6) * (f(a) + f(b) + 4*sum1 + 2*sum2) Demonstrate your function by showing the results for:   ƒ(x) = x3,       where   x   is     [0,1],       with           100 approximations.   The exact result is     0.25               (or 1/4)   ƒ(x) = 1/x,     where   x   is   [1,100],     with        1,000 approximations.   The exact result is     4.605170+     (natural log of 100)   ƒ(x) = x,         where   x   is   [0,5000],   with 5,000,000 approximations.   The exact result is   12,500,000   ƒ(x) = x,         where   x   is   [0,6000],   with 6,000,000 approximations.   The exact result is   18,000,000 See also   Active object for integrating a function of real time.   Special:PrefixIndex/Numerical integration for other integration methods.
#Stata
Stata
mata function integrate(f,a,b,n,u,v) { s = 0 h = (b-a)/n m = length(u) for (i=0; i<n; i++) { x = a+i*h for (j=1; j<=m; j++) s = s+v[j]*(*f)(x+h*u[j]) } return(s*h) }   function log_(x) { return(log(x)) }   function id(x) { return(x) }   function cube(x) { return(x*x*x) }   function inv(x) { return(1/x) }   function test(f,a,b,n) { return(integrate(f,a,b,n,(0,1),(1,0)), integrate(f,a,b,n,(0,1),(0,1)), integrate(f,a,b,n,(0.5),(1)), integrate(f,a,b,n,(0,1),(0.5,0.5)), integrate(f,a,b,n,(0,1/2,1),(1/6,4/6,1/6))) }   test(&cube(),0,1,100) test(&inv(),1,100,1000) test(&id(),0,5000,5000000) test(&id(),0,6000,6000000) end
http://rosettacode.org/wiki/Number_names
Number names
Task Show how to spell out a number in English. You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less). Support for inputs other than positive integers (like zero, negative integers, and floating-point numbers) is optional. Related task   Spelling of ordinal numbers.
#OCaml
OCaml
let div_mod n d = (n / d, n mod d) let join = String.concat ", " ;;   let rec nonzero = function | _, 0 -> "" | c, n -> c ^ (spell_integer n)   and tens n = [| ""; ""; "twenty"; "thirty"; "forty"; "fifty"; "sixty"; "seventy"; "eighty"; "ninety" |].(n)   and small n = [| "zero"; "one"; "two"; "three"; "four"; "five"; "six"; "seven"; "eight"; "nine"; "ten"; "eleven"; "twelve"; "thirteen"; "fourteen"; "fifteen"; "sixteen";"seventeen"; "eighteen"; "nineteen" |].(n)   and bl = [| ""; ""; "m"; "b"; "tr"; "quadr"; "quint"; "sext"; "sept"; "oct"; "non"; "dec" |]   and big = function | 0, n -> (spell_integer n) | 1, n -> (spell_integer n) ^ " thousand" | e, n -> (spell_integer n) ^ " " ^ bl.(e) ^ "illion"   and uff acc = function | 0 -> List.rev acc | n -> let a, b = div_mod n 1000 in uff (b::acc) a   and spell_integer = function | n when n < 0 -> invalid_arg "spell_integer: negative input" | n when n < 20 -> small n | n when n < 100 -> let a, b = div_mod n 10 in (tens a) ^ nonzero("-", b) | n when n < 1000 -> let a, b = div_mod n 100 in (small a) ^ " hundred" ^ nonzero(" ", b) | n -> let seg = (uff [] n) in let _, segn = (* just add the index of the item in the list *) List.fold_left (fun (i,acc) v -> (succ i, (i,v)::acc)) (0,[]) seg in let fsegn = (* remove right part "zero" *) List.filter (function (_,0) -> false | _ -> true) segn in join(List.map big fsegn) ;;
http://rosettacode.org/wiki/Number_reversal_game
Number reversal game
Task Given a jumbled list of the numbers   1   to   9   that are definitely   not   in ascending order. Show the list,   and then ask the player how many digits from the left to reverse. Reverse those digits,   then ask again,   until all the digits end up in ascending order. The score is the count of the reversals needed to attain the ascending order. Note: Assume the player's input does not need extra validation. Related tasks   Sorting algorithms/Pancake sort   Pancake sorting.   Topswops
#Pascal
Pascal
  program NumberReversalGame;   procedure PrintList(list: array of integer); var i: integer; begin for i := low(list) to high(list) do begin Write(list[i]); if i < high(list) then Write(', '); end; WriteLn; end;   procedure Swap(var list: array of integer; i, j: integer); var buf: integer; begin buf := list[i]; list[i] := list[j]; list[j] := buf; end;   procedure ShuffleList(var list: array of integer); var i, j, n: integer; begin Randomize;   for n := 0 to 99 do begin i := Random(high(list)+1); j := Random(high(list)+1); Swap(list, i, j); end; end;   procedure ReverseList(var list: array of integer; j: integer); var i: integer; begin i := low(list);   while i < j do begin Swap(list, i, j); i += 1; j -= 1; end; end;   function IsOrdered(list: array of integer): boolean; var i: integer; begin IsOrdered := true; i:= high(list);   while i > 0 do begin if list[i] <> (list[i-1] + 1) then begin IsOrdered:= false; break; end; i -= 1; end; end;     var list: array [0..8] of integer = (1, 2, 3, 4, 5, 6, 7, 8, 9); n: integer; moves: integer; begin   WriteLn('Number Reversal Game'); WriteLn; WriteLn('Sort the following list in ascending order by reversing the first n digits'); WriteLn('from the left.'); WriteLn;   ShuffleList(list); PrintList(list);   moves := 0;   while not IsOrdered(list) do begin WriteLn('How many digits from the left will you reverse?'); Write('> '); Read(n);   ReverseList(list, n-1); PrintList(list); moves += 1; end;   WriteLn; WriteLn('Congratulations you made it in just ', moves, ' moves!'); WriteLn; end.  
http://rosettacode.org/wiki/Null_object
Null object
Null (or nil) is the computer science concept of an undefined or unbound object. Some languages have an explicit way to access the null object, and some don't. Some languages distinguish the null object from undefined values, and some don't. Task Show how to access null in your language by checking to see if an object is equivalent to the null object. This task is not about whether a variable is defined. The task is about "null"-like values in various languages, which may or may not be related to the defined-ness of variables in your language.
#zkl
zkl
if(Void == n) ... return(Void)
http://rosettacode.org/wiki/One-dimensional_cellular_automata
One-dimensional cellular automata
Assume an array of cells with an initial distribution of live and dead cells, and imaginary cells off the end of the array having fixed values. Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation. If, in the following table, a live cell is represented by 1 and a dead cell by 0 then to generate the value of the cell at a particular index in the array of cellular values you use the following table: 000 -> 0 # 001 -> 0 # 010 -> 0 # Dies without enough neighbours 011 -> 1 # Needs one neighbour to survive 100 -> 0 # 101 -> 1 # Two neighbours giving birth 110 -> 1 # Needs one neighbour to survive 111 -> 0 # Starved to death.
#REXX
REXX
/*REXX program generates & displays N generations of one─dimensional cellular automata. */ parse arg $ gens . /*obtain optional arguments from the CL*/ if $=='' | $=="," then $=001110110101010 /*Not specified? Then use the default.*/ if gens=='' | gens=="," then gens=40 /* " " " " " " */   do #=0 for gens /* process the one-dimensional cells.*/ say " generation" right(#,length(gens)) ' ' translate($, "#·", 10) @=0 /* [↓] generation.*/ do j=2 for length($) - 1; x=substr($, j-1, 3) /*obtain the cell.*/ if x==011 | x==101 | x==110 then @=overlay(1, @, j) /*the cell lives. */ else @=overlay(0, @, j) /* " " dies. */ end /*j*/   if $==@ then do; say right('repeats', 40); leave; end /*does it repeat? */ $=@ /*now use the next generation of cells.*/ end /*#*/ /*stick a fork in it, we're all done. */
http://rosettacode.org/wiki/Nonoblock
Nonoblock
Nonoblock is a chip off the old Nonogram puzzle. Given The number of cells in a row. The size of each, (space separated), connected block of cells to fit in the row, in left-to right order. Task show all possible positions. show the number of positions of the blocks for the following cases within the row. show all output on this page. use a "neat" diagram of the block positions. Enumerate the following configurations   5   cells   and   [2, 1]   blocks   5   cells   and   []   blocks   (no blocks)   10   cells   and   [8]   blocks   15   cells   and   [2, 3, 2, 3]   blocks   5   cells   and   [2, 3]   blocks   (should give some indication of this not being possible) Example Given a row of five cells and a block of two cells followed by a block of one cell - in that order, the example could be shown as: |_|_|_|_|_| # 5 cells and [2, 1] blocks And would expand to the following 3 possible rows of block positions: |A|A|_|B|_| |A|A|_|_|B| |_|A|A|_|B| Note how the sets of blocks are always separated by a space. Note also that it is not necessary for each block to have a separate letter. Output approximating This: |#|#|_|#|_| |#|#|_|_|#| |_|#|#|_|#| This would also work: ##.#. ##..# .##.# An algorithm Find the minimum space to the right that is needed to legally hold all but the leftmost block of cells (with a space between blocks remember). The leftmost cell can legitimately be placed in all positions from the LHS up to a RH position that allows enough room for the rest of the blocks. for each position of the LH block recursively compute the position of the rest of the blocks in the remaining space to the right of the current placement of the LH block. (This is the algorithm used in the Nonoblock#Python solution). Reference The blog post Nonogram puzzle solver (part 1) Inspired this task and donated its Nonoblock#Python solution.
#Action.21
Action!
DEFINE MAX_BLOCKS="10" DEFINE NOT_FOUND="255"   BYTE FUNC GetBlockAtPos(BYTE p BYTE ARRAY blocks,pos INT count) INT i FOR i=0 TO count-1 DO IF p>=pos(i) AND p<pos(i)+blocks(i) THEN RETURN (i) FI OD RETURN (NOT_FOUND)   PROC PrintResult(BYTE cells BYTE ARRAY blocks,pos INT count) BYTE i,b   Print("[") FOR i=0 TO cells-1 DO b=GetBlockAtPos(i,blocks,pos,count) IF b=NOT_FOUND THEN Put('.) ELSE Put(b+'A) FI OD PrintE("]") RETURN   BYTE FUNC LeftMostPos(BYTE cells BYTE ARRAY blocks,pos INT count,startFrom) INT i   FOR i=startFrom TO count-1 DO pos(i)=pos(i-1)+blocks(i-1)+1 IF pos(i)+blocks(i)>cells THEN RETURN (0) FI OD RETURN (1)   BYTE FUNC MoveToRight(BYTE cells BYTE ARRAY blocks,pos INT count,startFrom) pos(startFrom)==+1 IF pos(startFrom)+blocks(startFrom)>cells THEN RETURN (0) FI RETURN (LeftMostPos(cells,blocks,pos,count,startFrom+1))   PROC Process(BYTE cells BYTE ARRAY blocks INT count) BYTE ARRAY pos(MAX_BLOCKS) BYTE success INT current   IF count=0 THEN PrintResult(cells,blocks,pos,count) RETURN FI   pos(0)=0 success=LeftMostPos(cells,blocks,pos,count,1) IF success=0 THEN PrintE("No solutions") RETURN FI current=count-1 WHILE success DO PrintResult(cells,blocks,pos,count) DO success=MoveToRight(cells,blocks,pos,count,current) IF success THEN current=count-1 ELSE current==-1 IF current<0 THEN EXIT FI FI UNTIL success OD OD RETURN   PROC Test(BYTE cells BYTE ARRAY blocks INT count) BYTE CH=$02FC ;Internal hardware value for last key pressed INT i   PrintB(cells) Print(" cells [") FOR i=0 TO count-1 DO PrintB(blocks(i)) IF i<count-1 THEN Put(32) FI OD PrintE("]")   Process(cells,blocks,count)   PutE() PrintE("Press any key to continue...") DO UNTIL CH#$FF OD CH=$FF PutE() RETURN   PROC Main() BYTE ARRAY t1=[2 1],t2=[],t3=[8],t4=[2 3 2 3],t5=[2 3]   Test(5,t1,2) Test(5,t2,0) Test(10,t3,1) Test(15,t4,4) Test(5,t5,2) RETURN
http://rosettacode.org/wiki/Numerical_integration
Numerical integration
Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods: rectangular left right midpoint trapezium Simpson's composite Your functions should take in the upper and lower bounds (a and b), and the number of approximations to make in that range (n). Assume that your example already has a function that gives values for ƒ(x) . Simpson's method is defined by the following pseudo-code: Pseudocode: Simpson's method, composite procedure quad_simpson_composite(f, a, b, n) h := (b - a) / n sum1 := f(a + h/2) sum2 := 0 loop on i from 1 to (n - 1) sum1 := sum1 + f(a + h * i + h/2) sum2 := sum2 + f(a + h * i)   answer := (h / 6) * (f(a) + f(b) + 4*sum1 + 2*sum2) Demonstrate your function by showing the results for:   ƒ(x) = x3,       where   x   is     [0,1],       with           100 approximations.   The exact result is     0.25               (or 1/4)   ƒ(x) = 1/x,     where   x   is   [1,100],     with        1,000 approximations.   The exact result is     4.605170+     (natural log of 100)   ƒ(x) = x,         where   x   is   [0,5000],   with 5,000,000 approximations.   The exact result is   12,500,000   ƒ(x) = x,         where   x   is   [0,6000],   with 6,000,000 approximations.   The exact result is   18,000,000 See also   Active object for integrating a function of real time.   Special:PrefixIndex/Numerical integration for other integration methods.
#Swift
Swift
public enum IntegrationType : CaseIterable { case rectangularLeft case rectangularRight case rectangularMidpoint case trapezium case simpson }   public func integrate( from: Double, to: Double, n: Int, using: IntegrationType = .simpson, f: (Double) -> Double ) -> Double { let integrationFunc: (Double, Double, Int, (Double) -> Double) -> Double   switch using { case .rectangularLeft: integrationFunc = integrateRectL case .rectangularRight: integrationFunc = integrateRectR case .rectangularMidpoint: integrationFunc = integrateRectMid case .trapezium: integrationFunc = integrateTrapezium case .simpson: integrationFunc = integrateSimpson }   return integrationFunc(from, to, n, f) }   private func integrateRectL(from: Double, to: Double, n: Int, f: (Double) -> Double) -> Double { let h = (to - from) / Double(n) var x = from var sum = 0.0   while x <= to - h { sum += f(x) x += h }   return h * sum }   private func integrateRectR(from: Double, to: Double, n: Int, f: (Double) -> Double) -> Double { let h = (to - from) / Double(n) var x = from var sum = 0.0   while x <= to - h { sum += f(x + h) x += h }   return h * sum }   private func integrateRectMid(from: Double, to: Double, n: Int, f: (Double) -> Double) -> Double { let h = (to - from) / Double(n) var x = from var sum = 0.0   while x <= to - h { sum += f(x + h / 2.0) x += h }   return h * sum }   private func integrateTrapezium(from: Double, to: Double, n: Int, f: (Double) -> Double) -> Double { let h = (to - from) / Double(n) var sum = f(from) + f(to)   for i in 1..<n { sum += 2 * f(from + Double(i) * h) }   return h * sum / 2 }   private func integrateSimpson(from: Double, to: Double, n: Int, f: (Double) -> Double) -> Double { let h = (to - from) / Double(n) var sum1 = 0.0 var sum2 = 0.0   for i in 0..<n { sum1 += f(from + h * Double(i) + h / 2.0) }   for i in 1..<n { sum2 += f(from + h * Double(i)) }   return h / 6.0 * (f(from) + f(to) + 4.0 * sum1 + 2.0 * sum2) }   let types = IntegrationType.allCases   print("f(x) = x^3:", types.map({ integrate(from: 0, to: 1, n: 100, using: $0, f: { pow($0, 3) }) })) print("f(x) = 1 / x:", types.map({ integrate(from: 1, to: 100, n: 1000, using: $0, f: { 1 / $0 }) })) print("f(x) = x, 0 -> 5_000:", types.map({ integrate(from: 0, to: 5_000, n: 5_000_000, using: $0, f: { $0 }) })) print("f(x) = x, 0 -> 6_000:", types.map({ integrate(from: 0, to: 6_000, n: 6_000_000, using: $0, f: { $0 }) }))
http://rosettacode.org/wiki/Number_names
Number names
Task Show how to spell out a number in English. You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less). Support for inputs other than positive integers (like zero, negative integers, and floating-point numbers) is optional. Related task   Spelling of ordinal numbers.
#PARI.2FGP
PARI/GP
Eng(n:int)={ my(tmp,s=""); if (n >= 1000000, tmp = n\1000000; s = Str(s, Eng(tmp), " million"); n -= tmp * 1000000; if (!n, return(s)); s = Str(s, " ") ); if (n >= 1000, tmp = n\1000; s = Str(s, Eng(tmp), " thousand"); n -= tmp * 1000; if (!n, return(s)); s = Str(s, " ") ); if (n >= 100, tmp = n\100; s = Str(s, Edigit(tmp), " hundred"); n -= tmp * 100; if (!n, return(s)); s = Str(s, " ") ); if (n < 20, return (Str(s, ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "ninteen"][n])) ); tmp = n\10; s = Str(s, [0, "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"][tmp]); n -= tmp * 10; if (n, Str(s, "-", Edigit(n)), s) }; Edigit(n)={ ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine"][n] };
http://rosettacode.org/wiki/Number_reversal_game
Number reversal game
Task Given a jumbled list of the numbers   1   to   9   that are definitely   not   in ascending order. Show the list,   and then ask the player how many digits from the left to reverse. Reverse those digits,   then ask again,   until all the digits end up in ascending order. The score is the count of the reversals needed to attain the ascending order. Note: Assume the player's input does not need extra validation. Related tasks   Sorting algorithms/Pancake sort   Pancake sorting.   Topswops
#Perl
Perl
use List::Util qw(shuffle);   my $turn = 0; my @jumble = shuffle 1..9;   while ( join('', @jumble) eq '123456789' ) { @jumble = shuffle 1..9; }   until ( join('', @jumble) eq '123456789' ) { $turn++; printf "%2d: @jumble - Flip how many digits ? ", $turn;   my $d = <>;   @jumble[0..$d-1] = reverse @jumble[0..$d-1]; }   print " @jumble\n"; print "You won in $turn turns.\n";
http://rosettacode.org/wiki/One-dimensional_cellular_automata
One-dimensional cellular automata
Assume an array of cells with an initial distribution of live and dead cells, and imaginary cells off the end of the array having fixed values. Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation. If, in the following table, a live cell is represented by 1 and a dead cell by 0 then to generate the value of the cell at a particular index in the array of cellular values you use the following table: 000 -> 0 # 001 -> 0 # 010 -> 0 # Dies without enough neighbours 011 -> 1 # Needs one neighbour to survive 100 -> 0 # 101 -> 1 # Two neighbours giving birth 110 -> 1 # Needs one neighbour to survive 111 -> 0 # Starved to death.
#Ring
Ring
  # Project : One-dimensional cellular automata   rule = ["0", "0", "0", "1", "0", "1", "1", "0"] now = "01110110101010100100"   for generation = 0 to 9 see "generation " + generation + ": " + now + nl nxt = "" for cell = 1 to len(now) str = "bintodec(" + '"' +substr("0"+now+"0", cell, 3) + '"' + ")" eval("p=" + str) nxt = nxt + rule[p+1] next temp = nxt nxt = now now = temp next   func bintodec(bin) binsum = 0 for n=1 to len(bin) binsum = binsum + number(bin[n]) *pow(2, len(bin)-n) next return binsum  
http://rosettacode.org/wiki/Nonoblock
Nonoblock
Nonoblock is a chip off the old Nonogram puzzle. Given The number of cells in a row. The size of each, (space separated), connected block of cells to fit in the row, in left-to right order. Task show all possible positions. show the number of positions of the blocks for the following cases within the row. show all output on this page. use a "neat" diagram of the block positions. Enumerate the following configurations   5   cells   and   [2, 1]   blocks   5   cells   and   []   blocks   (no blocks)   10   cells   and   [8]   blocks   15   cells   and   [2, 3, 2, 3]   blocks   5   cells   and   [2, 3]   blocks   (should give some indication of this not being possible) Example Given a row of five cells and a block of two cells followed by a block of one cell - in that order, the example could be shown as: |_|_|_|_|_| # 5 cells and [2, 1] blocks And would expand to the following 3 possible rows of block positions: |A|A|_|B|_| |A|A|_|_|B| |_|A|A|_|B| Note how the sets of blocks are always separated by a space. Note also that it is not necessary for each block to have a separate letter. Output approximating This: |#|#|_|#|_| |#|#|_|_|#| |_|#|#|_|#| This would also work: ##.#. ##..# .##.# An algorithm Find the minimum space to the right that is needed to legally hold all but the leftmost block of cells (with a space between blocks remember). The leftmost cell can legitimately be placed in all positions from the LHS up to a RH position that allows enough room for the rest of the blocks. for each position of the LH block recursively compute the position of the rest of the blocks in the remaining space to the right of the current placement of the LH block. (This is the algorithm used in the Nonoblock#Python solution). Reference The blog post Nonogram puzzle solver (part 1) Inspired this task and donated its Nonoblock#Python solution.
#AutoHotkey
AutoHotkey
;------------------------------------------- NonoBlock(cells, blocks){ result := [], line := "" for i, v in blocks B .= v ", " output := cells " cells and [" Trim(B, ", ") "] blocks`n"   if ((Arr := NonoBlockCreate(cells, blocks)) = "Error") return output "No Solution`n" for i, v in arr line.= v ";" result[line] := true result := NonoBlockRecurse(Arr, result) output .= NonoBlockShow(result) return output } ;------------------------------------------- ; create cells+1 size array, stack blocks to left with one gap in between ; gaps are represented by negative number ; stack extra gaps to far left ; for example : 6 cells and [2, 1] blocks ; returns [-2, 2, -1, 1, 0, 0, 0] NonoBlockCreate(cells, blocks){ Arr := [], B := blocks.Count() if !B ; no blocks return [0-cells, 0] for i, v in blocks{ total += v Arr.InsertAt(1, blocks[B-A_Index+1]) Arr.InsertAt(1, -1) } if (cells < total + B-1) ; not possible return "Error" Arr[1] := total + B-1 - cells loop % cells - Arr.Count() + 1 Arr.Push(0) return Arr } ;------------------------------------------- ; shift negative numbers from left to right recursively. ; preserve at least one gap between blocks. ; [-2, 2, -1, 1, 0, 0, 0] ; [-1, 2, -2, 1, 0, 0, 0] NonoBlockRecurse(Arr, result, pos:= 1){ i := pos-1 while (i < Arr.count()) { if ((B:=Arr[++i])>=0) || (B=-1 && i>1) continue if (i=Arr.count()-1) return result Arr[i] := ++B, Arr[i+2] := Arr[i+2] -1 result := NonoBlockRecurse(Arr.Clone(), result, i) line := [] for k, v in Arr line.=v ";" result[line] := true } return result } ;------------------------------------------- ; represent positve numbers by a block of "#", negative nubmers by a block of "." NonoBlockShow(result){ for line in result{ i := A_Index nLine := "" for j, val in StrSplit(line, ";") loop % Abs(val) nLine .= val > 0 ? "#" : "." output .= nLine "`n" } Sort, output, U return output } ;-------------------------------------------
http://rosettacode.org/wiki/Numerical_integration
Numerical integration
Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods: rectangular left right midpoint trapezium Simpson's composite Your functions should take in the upper and lower bounds (a and b), and the number of approximations to make in that range (n). Assume that your example already has a function that gives values for ƒ(x) . Simpson's method is defined by the following pseudo-code: Pseudocode: Simpson's method, composite procedure quad_simpson_composite(f, a, b, n) h := (b - a) / n sum1 := f(a + h/2) sum2 := 0 loop on i from 1 to (n - 1) sum1 := sum1 + f(a + h * i + h/2) sum2 := sum2 + f(a + h * i)   answer := (h / 6) * (f(a) + f(b) + 4*sum1 + 2*sum2) Demonstrate your function by showing the results for:   ƒ(x) = x3,       where   x   is     [0,1],       with           100 approximations.   The exact result is     0.25               (or 1/4)   ƒ(x) = 1/x,     where   x   is   [1,100],     with        1,000 approximations.   The exact result is     4.605170+     (natural log of 100)   ƒ(x) = x,         where   x   is   [0,5000],   with 5,000,000 approximations.   The exact result is   12,500,000   ƒ(x) = x,         where   x   is   [0,6000],   with 6,000,000 approximations.   The exact result is   18,000,000 See also   Active object for integrating a function of real time.   Special:PrefixIndex/Numerical integration for other integration methods.
#Tcl
Tcl
package require Tcl 8.5   proc leftrect {f left right} { $f $left } proc midrect {f left right} { set mid [expr {($left + $right) / 2.0}] $f $mid } proc rightrect {f left right} { $f $right } proc trapezium {f left right} { expr {([$f $left] + [$f $right]) / 2.0} } proc simpson {f left right} { set mid [expr {($left + $right) / 2.0}] expr {([$f $left] + 4*[$f $mid] + [$f $right]) / 6.0} }   proc integrate {f a b steps method} { set delta [expr {1.0 * ($b - $a) / $steps}] set total 0.0 for {set i 0} {$i < $steps} {incr i} { set left [expr {$a + $i * $delta}] set right [expr {$left + $delta}] set total [expr {$total + $delta * [$method $f $left $right]}] } return $total }   interp alias {} sin {} ::tcl::mathfunc::sin proc square x {expr {$x*$x}} proc def_int {f a b} { switch -- $f { sin {set lambda {x {expr {-cos($x)}}}} square {set lambda {x {expr {$x**3/3.0}}}} } return [expr {[apply $lambda $b] - [apply $lambda $a]}] }   set a 0 set b [expr {4*atan(1)}] set steps 10   foreach func {square sin} { puts "integral of ${func}(x) from $a to $b in $steps steps" set actual [def_int $func $a $b] foreach method {leftrect midrect rightrect trapezium simpson} { set int [integrate $func $a $b $steps $method] set diff [expr {($int - $actual) * 100.0 / $actual}] puts [format "  %-10s  %s\t(%.1f%%)" $method $int $diff] } }
http://rosettacode.org/wiki/Number_names
Number names
Task Show how to spell out a number in English. You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less). Support for inputs other than positive integers (like zero, negative integers, and floating-point numbers) is optional. Related task   Spelling of ordinal numbers.
#Pascal
Pascal
program NumberNames(output);   const smallies: array[1..19] of string = ('one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'); tens: array[2..9] of string = ('twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety');   function domaxies(number: int64): string; const maxies: array[0..5] of string = (' thousand', ' million', ' billion', ' trillion', ' quadrillion', ' quintillion'); begin domaxies := ''; if number >= 0 then domaxies := maxies[number]; end;   function doHundreds( number: int64): string; begin doHundreds := ''; if number > 99 then begin doHundreds := smallies[number div 100]; doHundreds := doHundreds + ' hundred'; number := number mod 100; if number > 0 then doHundreds := doHundreds + ' and '; end; if number >= 20 then begin doHundreds := doHundreds + tens[number div 10]; number := number mod 10; if number > 0 then doHundreds := doHundreds + '-'; end; if (0 < number) and (number < 20) then doHundreds := doHundreds + smallies[number]; end;   function spell(number: int64): string; var scaleFactor: int64 = 1000000000000000000; maxieStart, h: int64; begin spell := ''; maxieStart := 5; if number < 20 then spell := smallies[number]; while scaleFactor > 0 do begin if number > scaleFactor then begin h := number div scaleFactor; spell := spell + doHundreds(h) + domaxies(maxieStart); number := number mod scaleFactor; if number > 0 then spell := spell + ', '; end; scaleFactor := scaleFactor div 1000; dec(maxieStart); end; end;   begin writeln(99, ': ', spell(99)); writeln(234, ': ', spell(234)); writeln(7342, ': ', spell(7342)); writeln(32784, ': ', spell(32784)); writeln(234345, ': ', spell(234345)); writeln(2343451, ': ', spell(2343451)); writeln(23434534, ': ', spell(23434534)); writeln(234345456, ': ', spell(234345456)); writeln(2343454569, ': ', spell(2343454569)); writeln(2343454564356, ': ', spell(2343454564356)); writeln(2345286538456328, ': ', spell(2345286538456328)); end.
http://rosettacode.org/wiki/Number_reversal_game
Number reversal game
Task Given a jumbled list of the numbers   1   to   9   that are definitely   not   in ascending order. Show the list,   and then ask the player how many digits from the left to reverse. Reverse those digits,   then ask again,   until all the digits end up in ascending order. The score is the count of the reversals needed to attain the ascending order. Note: Assume the player's input does not need extra validation. Related tasks   Sorting algorithms/Pancake sort   Pancake sorting.   Topswops
#Phix
Phix
puts(1,"Given a jumbled list of the numbers 1 to 9,\n") puts(1,"you must select how many digits from the left to reverse.\n") puts(1,"Your goal is to get the digits in order with 1 on the left and 9 on the right.\n")   constant inums = tagset(9) sequence nums integer turns = 0, flip   while 1 do nums = shuffle(inums) if nums!=inums then exit end if end while   while 1 do printf(1,"%2d : %d %d %d %d %d %d %d %d %d ",turns&nums) if nums=inums then exit end if flip = prompt_number(" -- How many numbers should be flipped? ",{1,9}) nums[1..flip] = reverse(nums[1..flip]) turns += 1 end while   printf(1,"\nYou took %d turns to put the digits in order.", turns)
http://rosettacode.org/wiki/One-dimensional_cellular_automata
One-dimensional cellular automata
Assume an array of cells with an initial distribution of live and dead cells, and imaginary cells off the end of the array having fixed values. Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation. If, in the following table, a live cell is represented by 1 and a dead cell by 0 then to generate the value of the cell at a particular index in the array of cellular values you use the following table: 000 -> 0 # 001 -> 0 # 010 -> 0 # Dies without enough neighbours 011 -> 1 # Needs one neighbour to survive 100 -> 0 # 101 -> 1 # Two neighbours giving birth 110 -> 1 # Needs one neighbour to survive 111 -> 0 # Starved to death.
#Ruby
Ruby
def evolve(ary) ([0]+ary+[0]).each_cons(3).map{|a,b,c| a+b+c == 2 ? 1 : 0} end   def printit(ary) puts ary.join.tr("01",".#") end   ary = [0,1,1,1,0,1,1,0,1,0,1,0,1,0,1,0,0,1,0,0] printit ary until ary == (new = evolve(ary)) printit ary = new end
http://rosettacode.org/wiki/Nonoblock
Nonoblock
Nonoblock is a chip off the old Nonogram puzzle. Given The number of cells in a row. The size of each, (space separated), connected block of cells to fit in the row, in left-to right order. Task show all possible positions. show the number of positions of the blocks for the following cases within the row. show all output on this page. use a "neat" diagram of the block positions. Enumerate the following configurations   5   cells   and   [2, 1]   blocks   5   cells   and   []   blocks   (no blocks)   10   cells   and   [8]   blocks   15   cells   and   [2, 3, 2, 3]   blocks   5   cells   and   [2, 3]   blocks   (should give some indication of this not being possible) Example Given a row of five cells and a block of two cells followed by a block of one cell - in that order, the example could be shown as: |_|_|_|_|_| # 5 cells and [2, 1] blocks And would expand to the following 3 possible rows of block positions: |A|A|_|B|_| |A|A|_|_|B| |_|A|A|_|B| Note how the sets of blocks are always separated by a space. Note also that it is not necessary for each block to have a separate letter. Output approximating This: |#|#|_|#|_| |#|#|_|_|#| |_|#|#|_|#| This would also work: ##.#. ##..# .##.# An algorithm Find the minimum space to the right that is needed to legally hold all but the leftmost block of cells (with a space between blocks remember). The leftmost cell can legitimately be placed in all positions from the LHS up to a RH position that allows enough room for the rest of the blocks. for each position of the LH block recursively compute the position of the rest of the blocks in the remaining space to the right of the current placement of the LH block. (This is the algorithm used in the Nonoblock#Python solution). Reference The blog post Nonogram puzzle solver (part 1) Inspired this task and donated its Nonoblock#Python solution.
#C
C
#include <stdio.h> #include <string.h>   void nb(int cells, int total_block_size, int* blocks, int block_count, char* output, int offset, int* count) { if (block_count == 0) { printf("%2d  %s\n", ++*count, output); return; } int block_size = blocks[0]; int max_pos = cells - (total_block_size + block_count - 1); total_block_size -= block_size; cells -= block_size + 1; ++blocks; --block_count; for (int i = 0; i <= max_pos; ++i, --cells) { memset(output + offset, '.', max_pos + block_size); memset(output + offset + i, '#', block_size); nb(cells, total_block_size, blocks, block_count, output, offset + block_size + i + 1, count); } }   void nonoblock(int cells, int* blocks, int block_count) { printf("%d cells and blocks [", cells); for (int i = 0; i < block_count; ++i) printf(i == 0 ? "%d" : ", %d", blocks[i]); printf("]:\n"); int total_block_size = 0; for (int i = 0; i < block_count; ++i) total_block_size += blocks[i]; if (cells < total_block_size + block_count - 1) { printf("no solution\n"); return; } char output[cells + 1]; memset(output, '.', cells); output[cells] = '\0'; int count = 0; nb(cells, total_block_size, blocks, block_count, output, 0, &count); }   int main() { int blocks1[] = {2, 1}; nonoblock(5, blocks1, 2); printf("\n");   nonoblock(5, NULL, 0); printf("\n");   int blocks2[] = {8}; nonoblock(10, blocks2, 1); printf("\n");   int blocks3[] = {2, 3, 2, 3}; nonoblock(15, blocks3, 4); printf("\n");   int blocks4[] = {2, 3}; nonoblock(5, blocks4, 2);   return 0; }
http://rosettacode.org/wiki/Numerical_integration
Numerical integration
Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods: rectangular left right midpoint trapezium Simpson's composite Your functions should take in the upper and lower bounds (a and b), and the number of approximations to make in that range (n). Assume that your example already has a function that gives values for ƒ(x) . Simpson's method is defined by the following pseudo-code: Pseudocode: Simpson's method, composite procedure quad_simpson_composite(f, a, b, n) h := (b - a) / n sum1 := f(a + h/2) sum2 := 0 loop on i from 1 to (n - 1) sum1 := sum1 + f(a + h * i + h/2) sum2 := sum2 + f(a + h * i)   answer := (h / 6) * (f(a) + f(b) + 4*sum1 + 2*sum2) Demonstrate your function by showing the results for:   ƒ(x) = x3,       where   x   is     [0,1],       with           100 approximations.   The exact result is     0.25               (or 1/4)   ƒ(x) = 1/x,     where   x   is   [1,100],     with        1,000 approximations.   The exact result is     4.605170+     (natural log of 100)   ƒ(x) = x,         where   x   is   [0,5000],   with 5,000,000 approximations.   The exact result is   12,500,000   ƒ(x) = x,         where   x   is   [0,6000],   with 6,000,000 approximations.   The exact result is   18,000,000 See also   Active object for integrating a function of real time.   Special:PrefixIndex/Numerical integration for other integration methods.
#TI-89_BASIC
TI-89 BASIC
#import std #import nat #import flo   (integral_by "m") ("f","a","b","n") =   iprod ^(* ! div\float"n" minus/"b" "a",~&) ("m" "f")*ytp (ari successor "n")/"a" "b"
http://rosettacode.org/wiki/Number_names
Number names
Task Show how to spell out a number in English. You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less). Support for inputs other than positive integers (like zero, negative integers, and floating-point numbers) is optional. Related task   Spelling of ordinal numbers.
#Perl
Perl
use Lingua::EN::Numbers 'num2en';   print num2en(123456789), "\n";
http://rosettacode.org/wiki/Number_reversal_game
Number reversal game
Task Given a jumbled list of the numbers   1   to   9   that are definitely   not   in ascending order. Show the list,   and then ask the player how many digits from the left to reverse. Reverse those digits,   then ask again,   until all the digits end up in ascending order. The score is the count of the reversals needed to attain the ascending order. Note: Assume the player's input does not need extra validation. Related tasks   Sorting algorithms/Pancake sort   Pancake sorting.   Topswops
#PHP
PHP
class ReversalGame { private $numbers;   public function __construct() { $this->initialize(); }   public function play() { $i = 0; $moveCount = 0; while (true) { echo json_encode($this->numbers) . "\n"; echo "Please enter an index to reverse from 2 to 9. Enter 99 to quit\n"; $i = intval(rtrim(fgets(STDIN), "\n")); if ($i == 99) { break; } if ($i < 2 || $i > 9) { echo "Invalid input\n"; } else { $moveCount++; $this->reverse($i); if ($this->isSorted()) { echo "Congratulations you solved this in $moveCount moves!\n"; break; } }   } }   private function reverse($position) { array_splice($this->numbers, 0, $position, array_reverse(array_slice($this->numbers, 0, $position))); }   private function isSorted() { for ($i = 0; $i < count($this->numbers) - 1; ++$i) { if ($this->numbers[$i] > $this->numbers[$i + 1]) { return false; } } return true; }   private function initialize() { $this->numbers = range(1, 9); while ($this->isSorted()) { shuffle($this->numbers); } }   }   $game = new ReversalGame(); $game->play();  
http://rosettacode.org/wiki/One-dimensional_cellular_automata
One-dimensional cellular automata
Assume an array of cells with an initial distribution of live and dead cells, and imaginary cells off the end of the array having fixed values. Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation. If, in the following table, a live cell is represented by 1 and a dead cell by 0 then to generate the value of the cell at a particular index in the array of cellular values you use the following table: 000 -> 0 # 001 -> 0 # 010 -> 0 # Dies without enough neighbours 011 -> 1 # Needs one neighbour to survive 100 -> 0 # 101 -> 1 # Two neighbours giving birth 110 -> 1 # Needs one neighbour to survive 111 -> 0 # Starved to death.
#Rust
Rust
fn get_new_state(windowed: &[bool]) -> bool { match windowed { [false, true, true] | [true, true, false] => true, _ => false } }   fn next_gen(cell: &mut [bool]) { let mut v = Vec::with_capacity(cell.len()); v.push(cell[0]); for i in cell.windows(3) { v.push(get_new_state(i)); } v.push(cell[cell.len() - 1]); cell.copy_from_slice(&v); }   fn print_cell(cell: &[bool]) { for v in cell { print!("{} ", if *v {'#'} else {' '}); } println!(); }   fn main() {   const MAX_GENERATION: usize = 10; const CELLS_LENGTH: usize = 30;   let mut cell: [bool; CELLS_LENGTH] = rand::random();   for i in 1..=MAX_GENERATION { print!("Gen {:2}: ", i); print_cell(&cell); next_gen(&mut cell); } }  
http://rosettacode.org/wiki/Nonoblock
Nonoblock
Nonoblock is a chip off the old Nonogram puzzle. Given The number of cells in a row. The size of each, (space separated), connected block of cells to fit in the row, in left-to right order. Task show all possible positions. show the number of positions of the blocks for the following cases within the row. show all output on this page. use a "neat" diagram of the block positions. Enumerate the following configurations   5   cells   and   [2, 1]   blocks   5   cells   and   []   blocks   (no blocks)   10   cells   and   [8]   blocks   15   cells   and   [2, 3, 2, 3]   blocks   5   cells   and   [2, 3]   blocks   (should give some indication of this not being possible) Example Given a row of five cells and a block of two cells followed by a block of one cell - in that order, the example could be shown as: |_|_|_|_|_| # 5 cells and [2, 1] blocks And would expand to the following 3 possible rows of block positions: |A|A|_|B|_| |A|A|_|_|B| |_|A|A|_|B| Note how the sets of blocks are always separated by a space. Note also that it is not necessary for each block to have a separate letter. Output approximating This: |#|#|_|#|_| |#|#|_|_|#| |_|#|#|_|#| This would also work: ##.#. ##..# .##.# An algorithm Find the minimum space to the right that is needed to legally hold all but the leftmost block of cells (with a space between blocks remember). The leftmost cell can legitimately be placed in all positions from the LHS up to a RH position that allows enough room for the rest of the blocks. for each position of the LH block recursively compute the position of the rest of the blocks in the remaining space to the right of the current placement of the LH block. (This is the algorithm used in the Nonoblock#Python solution). Reference The blog post Nonogram puzzle solver (part 1) Inspired this task and donated its Nonoblock#Python solution.
#C.23
C#
using System; using System.Linq; using System.Text;   public static class Nonoblock { public static void Main() { Positions(5, 2,1); Positions(5); Positions(10, 8); Positions(15, 2,3,2,3); Positions(5, 2,3); }   public static void Positions(int cells, params int[] blocks) { if (cells < 0 || blocks == null || blocks.Any(b => b < 1)) throw new ArgumentOutOfRangeException(); Console.WriteLine($"{cells} cells with [{string.Join(", ", blocks)}]"); if (blocks.Sum() + blocks.Length - 1 > cells) { Console.WriteLine("No solution"); return; } var spaces = new int[blocks.Length + 1]; int total = -1; for (int i = 0; i < blocks.Length; i++) { total += blocks[i] + 1; spaces[i+1] = total; } spaces[spaces.Length - 1] = cells - 1; var sb = new StringBuilder(string.Join(".", blocks.Select(b => new string('#', b))).PadRight(cells, '.')); Iterate(sb, spaces, spaces.Length - 1, 0); Console.WriteLine(); }   private static void Iterate(StringBuilder output, int[] spaces, int index, int offset) { Console.WriteLine(output.ToString()); if (index <= 0) return; int count = 0; while (output[spaces[index] - offset] != '#') { count++; output.Remove(spaces[index], 1); output.Insert(spaces[index-1], '.'); spaces[index-1]++; Iterate(output, spaces, index - 1, 1); } if (offset == 0) return; spaces[index-1] -= count; output.Remove(spaces[index-1], count); output.Insert(spaces[index] - count, ".", count); }   }
http://rosettacode.org/wiki/Numerical_integration
Numerical integration
Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods: rectangular left right midpoint trapezium Simpson's composite Your functions should take in the upper and lower bounds (a and b), and the number of approximations to make in that range (n). Assume that your example already has a function that gives values for ƒ(x) . Simpson's method is defined by the following pseudo-code: Pseudocode: Simpson's method, composite procedure quad_simpson_composite(f, a, b, n) h := (b - a) / n sum1 := f(a + h/2) sum2 := 0 loop on i from 1 to (n - 1) sum1 := sum1 + f(a + h * i + h/2) sum2 := sum2 + f(a + h * i)   answer := (h / 6) * (f(a) + f(b) + 4*sum1 + 2*sum2) Demonstrate your function by showing the results for:   ƒ(x) = x3,       where   x   is     [0,1],       with           100 approximations.   The exact result is     0.25               (or 1/4)   ƒ(x) = 1/x,     where   x   is   [1,100],     with        1,000 approximations.   The exact result is     4.605170+     (natural log of 100)   ƒ(x) = x,         where   x   is   [0,5000],   with 5,000,000 approximations.   The exact result is   12,500,000   ƒ(x) = x,         where   x   is   [0,6000],   with 6,000,000 approximations.   The exact result is   18,000,000 See also   Active object for integrating a function of real time.   Special:PrefixIndex/Numerical integration for other integration methods.
#Ursala
Ursala
#import std #import nat #import flo   (integral_by "m") ("f","a","b","n") =   iprod ^(* ! div\float"n" minus/"b" "a",~&) ("m" "f")*ytp (ari successor "n")/"a" "b"
http://rosettacode.org/wiki/Number_names
Number names
Task Show how to spell out a number in English. You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less). Support for inputs other than positive integers (like zero, negative integers, and floating-point numbers) is optional. Related task   Spelling of ordinal numbers.
#Phix
Phix
-- -- demo\rosetta\Number_names.exw -- ----------------------------- -- with javascript_semantics constant twenties = {"zero","one","two","three","four","five","six","seven","eight","nine","ten", "eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"} function twenty(integer n) return twenties[mod(n,20)+1] end function constant decades = {"twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"} function decade(integer n) return decades[mod(n,10)-1] end function function hundred(integer n) if n<20 then return twenty(n) elsif mod(n,10)=0 then return decade(mod(floor(n/10),10)) end if return decade(floor(n/10)) & '-' & twenty(mod(n,10)) end function function thousand(integer n, string withand) if n<100 then return withand & hundred(n) elsif mod(n,100)=0 then return withand & twenty(floor(n/100))&" hundred" end if return twenty(floor(n/100)) & " hundred and " & hundred(mod(n,100)) end function constant orders = {{power(10,15),"quadrillion"}, {power(10,12),"trillion"}, {power(10,9),"billion"}, {power(10,6),"million"}, {power(10,3),"thousand"}} function triplet(atom n) string res = "" for i=1 to length(orders) do {atom order, string name} = orders[i] atom high = floor(n/order), low = mod(n,order) if high!=0 then res &= thousand(high,"")&' '&name end if n = low if low=0 then exit end if if length(res) and high!=0 then res &= ", " end if end for if n!=0 or res="" then res &= thousand(floor(n),iff(res=""?"":"and ")) n = abs(mod(n,1)) if n>1e-6 then res &= " point" for i=1 to 10 do integer t = floor(n*10.0000001) res &= ' '&twenties[t+1] n = n*10-t if abs(n)<1e-6 then exit end if end for end if end if return res end function global function spell(atom n) string res = "" if n<0 then res = "minus " n = -n end if res &= triplet(n) return res end function global constant samples = {99, 300, 310, 417,1_501, 12_609, 200000000000100, 999999999999999, -123456787654321,102003000400005,1020030004,102003,102,1,0,-1,-99, -1501,1234,12.34,10000001.2,1E-3,-2.7182818, 201021002001,-20102100200,2010210020,-201021002,20102100,-2010210, 201021,-20102,2010,-201,20,-2} global function smartp(atom n) if n=floor(n) then return sprintf("%d",n) end if string res = sprintf("%18.8f",n) if find('.',res) then res = trim_tail(res,"0") end if return res end function procedure main() for i=1 to length(samples) do atom si = samples[i] printf(1,"%18s %s\n",{smartp(si),spell(si)}) end for end procedure if include_file()=1 then main() {} = wait_key() end if
http://rosettacode.org/wiki/Number_reversal_game
Number reversal game
Task Given a jumbled list of the numbers   1   to   9   that are definitely   not   in ascending order. Show the list,   and then ask the player how many digits from the left to reverse. Reverse those digits,   then ask again,   until all the digits end up in ascending order. The score is the count of the reversals needed to attain the ascending order. Note: Assume the player's input does not need extra validation. Related tasks   Sorting algorithms/Pancake sort   Pancake sorting.   Topswops
#PicoLisp
PicoLisp
(load "@lib/simul.l")   (de reversalGame () (let (Lst (shuffle (range 1 9)) Cnt 0) (while (apply < Lst) (setq Lst (shuffle Lst)) ) (loop (printsp Lst) (T (apply < Lst) Cnt) (NIL (num? (read))) (setq Lst (flip Lst @)) (inc 'Cnt) ) ) )
http://rosettacode.org/wiki/One-dimensional_cellular_automata
One-dimensional cellular automata
Assume an array of cells with an initial distribution of live and dead cells, and imaginary cells off the end of the array having fixed values. Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation. If, in the following table, a live cell is represented by 1 and a dead cell by 0 then to generate the value of the cell at a particular index in the array of cellular values you use the following table: 000 -> 0 # 001 -> 0 # 010 -> 0 # Dies without enough neighbours 011 -> 1 # Needs one neighbour to survive 100 -> 0 # 101 -> 1 # Two neighbours giving birth 110 -> 1 # Needs one neighbour to survive 111 -> 0 # Starved to death.
#Scala
Scala
def cellularAutomata(s: String) = { def it = Iterator.iterate(s) ( generation => ("_%s_" format generation).iterator sliding 3 map (_ count (_ == '#')) map Map(2 -> "#").withDefaultValue("_") mkString )   (it drop 1) zip it takeWhile Function.tupled(_ != _) map (_._2) foreach println }
http://rosettacode.org/wiki/Nonoblock
Nonoblock
Nonoblock is a chip off the old Nonogram puzzle. Given The number of cells in a row. The size of each, (space separated), connected block of cells to fit in the row, in left-to right order. Task show all possible positions. show the number of positions of the blocks for the following cases within the row. show all output on this page. use a "neat" diagram of the block positions. Enumerate the following configurations   5   cells   and   [2, 1]   blocks   5   cells   and   []   blocks   (no blocks)   10   cells   and   [8]   blocks   15   cells   and   [2, 3, 2, 3]   blocks   5   cells   and   [2, 3]   blocks   (should give some indication of this not being possible) Example Given a row of five cells and a block of two cells followed by a block of one cell - in that order, the example could be shown as: |_|_|_|_|_| # 5 cells and [2, 1] blocks And would expand to the following 3 possible rows of block positions: |A|A|_|B|_| |A|A|_|_|B| |_|A|A|_|B| Note how the sets of blocks are always separated by a space. Note also that it is not necessary for each block to have a separate letter. Output approximating This: |#|#|_|#|_| |#|#|_|_|#| |_|#|#|_|#| This would also work: ##.#. ##..# .##.# An algorithm Find the minimum space to the right that is needed to legally hold all but the leftmost block of cells (with a space between blocks remember). The leftmost cell can legitimately be placed in all positions from the LHS up to a RH position that allows enough room for the rest of the blocks. for each position of the LH block recursively compute the position of the rest of the blocks in the remaining space to the right of the current placement of the LH block. (This is the algorithm used in the Nonoblock#Python solution). Reference The blog post Nonogram puzzle solver (part 1) Inspired this task and donated its Nonoblock#Python solution.
#C.2B.2B
C++
  #include <iomanip> #include <iostream> #include <algorithm> #include <numeric> #include <string> #include <vector>   typedef std::pair<int, std::vector<int> > puzzle;   class nonoblock { public: void solve( std::vector<puzzle>& p ) { for( std::vector<puzzle>::iterator i = p.begin(); i != p.end(); i++ ) { counter = 0; std::cout << " Puzzle: " << ( *i ).first << " cells and blocks [ "; for( std::vector<int>::iterator it = ( *i ).second.begin(); it != ( *i ).second.end(); it++ ) std::cout << *it << " "; std::cout << "] "; int s = std::accumulate( ( *i ).second.begin(), ( *i ).second.end(), 0 ) + ( ( *i ).second.size() > 0 ? ( *i ).second.size() - 1 : 0 ); if( ( *i ).first - s < 0 ) { std::cout << "has no solution!\n\n\n"; continue; } std::cout << "\n Possible configurations:\n\n"; std::string b( ( *i ).first, '-' ); solve( *i, b, 0 ); std::cout << "\n\n"; } }   private: void solve( puzzle p, std::string n, int start ) { if( p.second.size() < 1 ) { output( n ); return; } std::string temp_string; int offset, this_block_size = p.second[0];   int space_need_for_others = std::accumulate( p.second.begin() + 1, p.second.end(), 0 ); space_need_for_others += p.second.size() - 1;   int space_for_curr_block = p.first - space_need_for_others - std::accumulate( p.second.begin(), p.second.begin(), 0 );   std::vector<int> v1( p.second.size() - 1 ); std::copy( p.second.begin() + 1, p.second.end(), v1.begin() ); puzzle p1 = std::make_pair( space_need_for_others, v1 );   for( int a = 0; a < space_for_curr_block; a++ ) { temp_string = n;   if( start + this_block_size > n.length() ) return;   for( offset = start; offset < start + this_block_size; offset++ ) temp_string.at( offset ) = 'o';   if( p1.first ) solve( p1, temp_string, offset + 1 ); else output( temp_string );   start++; } } void output( std::string s ) { char b = 65 - ( s.at( 0 ) == '-' ? 1 : 0 ); bool f = false; std::cout << std::setw( 3 ) << ++counter << "\t|"; for( std::string::iterator i = s.begin(); i != s.end(); i++ ) { b += ( *i ) == 'o' && f ? 1 : 0; std::cout << ( ( *i ) == 'o' ? b : '_' ) << "|"; f = ( *i ) == '-' ? true : false; } std::cout << "\n"; }   unsigned counter; };   int main( int argc, char* argv[] ) { std::vector<puzzle> problems; std::vector<int> blocks; blocks.push_back( 2 ); blocks.push_back( 1 ); problems.push_back( std::make_pair( 5, blocks ) ); blocks.clear(); problems.push_back( std::make_pair( 5, blocks ) ); blocks.push_back( 8 ); problems.push_back( std::make_pair( 10, blocks ) ); blocks.clear(); blocks.push_back( 2 ); blocks.push_back( 3 ); problems.push_back( std::make_pair( 5, blocks ) ); blocks.push_back( 2 ); blocks.push_back( 3 ); problems.push_back( std::make_pair( 15, blocks ) );   nonoblock nn; nn.solve( problems );   return 0; }  
http://rosettacode.org/wiki/Non-decimal_radices/Input
Non-decimal radices/Input
It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.) This task requires parsing of such a string (which may be assumed to contain nothing else) using the language's built-in facilities if possible. Parsing of decimal strings is required, parsing of other formats is optional but should be shown (i.e., if the language can parse in base-19 then that should be illustrated). The solutions may assume that the base of the number in the string is known. In particular, if your language has a facility to guess the base of a number by looking at a prefix (e.g. "0x" for hexadecimal) or other distinguishing syntax as it parses it, please show that. The reverse operation is in task Non-decimal radices/Output For general number base conversion, see Non-decimal radices/Convert.
#11l
11l
V s = ‘100’ L(base) 2..20 print(‘String '#.' in base #. is #. in base 10’.format(s, base, Int(s, radix' base)))
http://rosettacode.org/wiki/Numerical_integration
Numerical integration
Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods: rectangular left right midpoint trapezium Simpson's composite Your functions should take in the upper and lower bounds (a and b), and the number of approximations to make in that range (n). Assume that your example already has a function that gives values for ƒ(x) . Simpson's method is defined by the following pseudo-code: Pseudocode: Simpson's method, composite procedure quad_simpson_composite(f, a, b, n) h := (b - a) / n sum1 := f(a + h/2) sum2 := 0 loop on i from 1 to (n - 1) sum1 := sum1 + f(a + h * i + h/2) sum2 := sum2 + f(a + h * i)   answer := (h / 6) * (f(a) + f(b) + 4*sum1 + 2*sum2) Demonstrate your function by showing the results for:   ƒ(x) = x3,       where   x   is     [0,1],       with           100 approximations.   The exact result is     0.25               (or 1/4)   ƒ(x) = 1/x,     where   x   is   [1,100],     with        1,000 approximations.   The exact result is     4.605170+     (natural log of 100)   ƒ(x) = x,         where   x   is   [0,5000],   with 5,000,000 approximations.   The exact result is   12,500,000   ƒ(x) = x,         where   x   is   [0,6000],   with 6,000,000 approximations.   The exact result is   18,000,000 See also   Active object for integrating a function of real time.   Special:PrefixIndex/Numerical integration for other integration methods.
#VBA
VBA
Option Explicit Option Base 1   Function Quad(ByVal f As String, ByVal a As Double, _ ByVal b As Double, ByVal n As Long, _ ByVal u As Variant, ByVal v As Variant) As Double Dim m As Long, h As Double, x As Double, s As Double, i As Long, j As Long m = UBound(u) h = (b - a) / n s = 0# For i = 1 To n x = a + (i - 1) * h For j = 1 To m s = s + v(j) * Application.Run(f, x + h * u(j)) Next Next Quad = s * h End Function   Function f1fun(x As Double) As Double f1fun = x ^ 3 End Function   Function f2fun(x As Double) As Double f2fun = 1 / x End Function   Function f3fun(x As Double) As Double f3fun = x End Function   Sub Test() Dim fun, f, coef, c Dim i As Long, j As Long, s As Double   fun = Array(Array("f1fun", 0, 1, 100, 1 / 4), _ Array("f2fun", 1, 100, 1000, Log(100)), _ Array("f3fun", 0, 5000, 50000, 5000 ^ 2 / 2), _ Array("f3fun", 0, 6000, 60000, 6000 ^ 2 / 2))   coef = Array(Array("Left rect. ", Array(0, 1), Array(1, 0)), _ Array("Right rect. ", Array(0, 1), Array(0, 1)), _ Array("Midpoint ", Array(0.5), Array(1)), _ Array("Trapez. ", Array(0, 1), Array(0.5, 0.5)), _ Array("Simpson ", Array(0, 0.5, 1), Array(1 / 6, 4 / 6, 1 / 6)))   For i = 1 To UBound(fun) f = fun(i) Debug.Print f(1) For j = 1 To UBound(coef) c = coef(j) s = Quad(f(1), f(2), f(3), f(4), c(2), c(3)) Debug.Print " " + c(1) + ": ", s, (s - f(5)) / f(5) Next j Next i End Sub
http://rosettacode.org/wiki/Number_names
Number names
Task Show how to spell out a number in English. You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less). Support for inputs other than positive integers (like zero, negative integers, and floating-point numbers) is optional. Related task   Spelling of ordinal numbers.
#PHP
PHP
$orderOfMag = array('Hundred', 'Thousand,', 'Million,', 'Billion,', 'Trillion,'); $smallNumbers = array('Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen'); $decades = array('', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety');   function NumberToEnglish($num, $count = 0){ global $orderOfMag, $smallNumbers, $decades; $isLast = true; $str = '';   if ($num < 0){ $str = 'Negative '; $num = abs($num); }   (int) $thisPart = substr((string) $num, -3);   if (strlen((string) $num) > 3){ // Number still too big, work on a smaller chunk $str .= NumberToEnglish((int) substr((string) $num, 0, strlen((string) $num) - 3), $count + 1); $isLast = false; }   // do translation stuff if (($count == 0 || $isLast) && ($str == '' || $str == 'Negative ')) // This is either a very small number or the most significant digits of the number. Either way we don't want a preceeding "and" $and = ''; else $and = ' and ';   if ($thisPart > 99){ // Hundreds part of the number chunk $str .= ($isLast ? '' : ' ') . "{$smallNumbers[$thisPart/100]} {$orderOfMag[0]}";   if(($thisPart %= 100) == 0){ // There is nothing else to do for this chunk (was a multiple of 100) $str .= " {$orderOfMag[$count]}"; return $str; } $and = ' and '; // Set up our and string to the word "and" since there is something in the hundreds place of this chunk }   if ($thisPart >= 20){ // Tens part of the number chunk $str .= "{$and}{$decades[$thisPart /10]}"; $and = ' '; // Make sure we don't have any extranious "and"s if(($thisPart %= 10) == 0) return $str . ($count != 0 ? " {$orderOfMag[$count]}" : ''); }   if ($thisPart < 20 && $thisPart > 0) // Ones part of the number chunk return $str . "{$and}{$smallNumbers[(int) $thisPart]} " . ($count != 0 ? $orderOfMag[$count] : ''); elseif ($thisPart == 0 && strlen($thisPart) == 1) // The number is zero return $str . "{$smallNumbers[(int)$thisPart]}"; }
http://rosettacode.org/wiki/Number_reversal_game
Number reversal game
Task Given a jumbled list of the numbers   1   to   9   that are definitely   not   in ascending order. Show the list,   and then ask the player how many digits from the left to reverse. Reverse those digits,   then ask again,   until all the digits end up in ascending order. The score is the count of the reversals needed to attain the ascending order. Note: Assume the player's input does not need extra validation. Related tasks   Sorting algorithms/Pancake sort   Pancake sorting.   Topswops
#PL.2FI
PL/I
  digits: procedure options (main); /* 23 April 2010 */ declare s character (9) varying; declare i fixed binary; declare digit character (1);   restart: put skip list ('In this game, you are given a group of digits.'); put skip list ('You will specify one of those digits.'); put skip list ('The computer will then reverse the digits up to the one you nominate.'); put skip list ('Your task is to repeat this process a number of times until all the digits'); put skip list ('are in order, left to right, 1 to 9.'); put skip list ('Here are your digits');   redo: s = ''; do until (length(s) = 9); digit = trim ( fixed(trunc (1+random()*9) ) ); if index(s, digit) = 0 then s = s || digit; end; if s = '123456789' then go to redo;   loop: do forever; put skip list (s); if s = '123456789' then leave; get edit (digit) (a(1)); i = index(s, digit); if i = 0 then do; put skip list ('invalid request'); iterate loop; end; s = reverse( substr(s, 1, i) ) || substr(s, i+1, length(s)-i); end; put skip list ('Congratulations'); go to restart; end digits;  
http://rosettacode.org/wiki/One-dimensional_cellular_automata
One-dimensional cellular automata
Assume an array of cells with an initial distribution of live and dead cells, and imaginary cells off the end of the array having fixed values. Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation. If, in the following table, a live cell is represented by 1 and a dead cell by 0 then to generate the value of the cell at a particular index in the array of cellular values you use the following table: 000 -> 0 # 001 -> 0 # 010 -> 0 # Dies without enough neighbours 011 -> 1 # Needs one neighbour to survive 100 -> 0 # 101 -> 1 # Two neighbours giving birth 110 -> 1 # Needs one neighbour to survive 111 -> 0 # Starved to death.
#Scheme
Scheme
(define (next-generation left petri-dish right) (if (null? petri-dish) (list) (cons (if (= (+ left (car petri-dish) (if (null? (cdr petri-dish)) right (cadr petri-dish))) 2) 1 0) (next-generation (car petri-dish) (cdr petri-dish) right))))   (define (display-evolution petri-dish generations) (if (not (zero? generations)) (begin (display petri-dish) (newline) (display-evolution (next-generation 0 petri-dish 0) (- generations 1)))))   (display-evolution (list 1 1 1 0 1 1 0 1 0 1 0 1 0 1 0 0 1 0) 10)
http://rosettacode.org/wiki/Nonoblock
Nonoblock
Nonoblock is a chip off the old Nonogram puzzle. Given The number of cells in a row. The size of each, (space separated), connected block of cells to fit in the row, in left-to right order. Task show all possible positions. show the number of positions of the blocks for the following cases within the row. show all output on this page. use a "neat" diagram of the block positions. Enumerate the following configurations   5   cells   and   [2, 1]   blocks   5   cells   and   []   blocks   (no blocks)   10   cells   and   [8]   blocks   15   cells   and   [2, 3, 2, 3]   blocks   5   cells   and   [2, 3]   blocks   (should give some indication of this not being possible) Example Given a row of five cells and a block of two cells followed by a block of one cell - in that order, the example could be shown as: |_|_|_|_|_| # 5 cells and [2, 1] blocks And would expand to the following 3 possible rows of block positions: |A|A|_|B|_| |A|A|_|_|B| |_|A|A|_|B| Note how the sets of blocks are always separated by a space. Note also that it is not necessary for each block to have a separate letter. Output approximating This: |#|#|_|#|_| |#|#|_|_|#| |_|#|#|_|#| This would also work: ##.#. ##..# .##.# An algorithm Find the minimum space to the right that is needed to legally hold all but the leftmost block of cells (with a space between blocks remember). The leftmost cell can legitimately be placed in all positions from the LHS up to a RH position that allows enough room for the rest of the blocks. for each position of the LH block recursively compute the position of the rest of the blocks in the remaining space to the right of the current placement of the LH block. (This is the algorithm used in the Nonoblock#Python solution). Reference The blog post Nonogram puzzle solver (part 1) Inspired this task and donated its Nonoblock#Python solution.
#D
D
import std.stdio, std.array, std.algorithm, std.exception, std.conv, std.concurrency, std.range;   struct Solution { uint pos, len; }   Generator!(Solution[]) nonoBlocks(in uint[] blocks, in uint cells) { return new typeof(return)({ if (blocks.empty || blocks[0] == 0) { yield([Solution(0, 0)]); } else { enforce(blocks.sum + blocks.length - 1 <= cells, "Those blocks cannot fit in those cells."); immutable firstBl = blocks[0]; const restBl = blocks.dropOne;   // The other blocks need space. immutable minS = restBl.map!(b => b + 1).sum;   // Slide the start position from left to max RH // index allowing for other blocks. foreach (immutable bPos; 0 .. cells - minS - firstBl + 1) { if (restBl.empty) { // No other blocks to the right so just yield // this one. yield([Solution(bPos, firstBl)]); } else { // More blocks to the right so create a sub-problem // of placing the restBl blocks in the cells one // space to the right of the RHS of this block. immutable offset = bPos + firstBl + 1; immutable newCells = cells - offset;   // Recursive call to nonoBlocks yields multiple // sub-positions. foreach (const subPos; nonoBlocks(restBl, newCells)) { // Remove the offset from sub block positions. auto rest = subPos.map!(sol => Solution(offset + sol.pos, sol.len));   // Yield this block plus sub blocks positions. yield(Solution(bPos, firstBl) ~ rest.array); } } } } }); }     /// Pretty prints each run of blocks with a /// different letter for each block of filled cells. string show(in Solution[] vec, in uint nCells) pure { auto result = ['_'].replicate(nCells); foreach (immutable i, immutable sol; vec) foreach (immutable j; sol.pos .. sol.pos + sol.len) result[j] = (result[j] == '_') ? to!char('A' + i) : '?'; return '[' ~ result ~ ']'; }   void main() { static struct Problem { uint[] blocks; uint nCells; }   immutable Problem[] problems = [{[2, 1], 5}, {[], 5}, {[8], 10}, {[2, 3, 2, 3], 15}, {[4, 3], 10}, {[2, 1], 5}, {[3, 1], 10}, {[2, 3], 5}];   foreach (immutable prob; problems) { writefln("Configuration (%d cells and %s blocks):", prob.nCells, prob.blocks); show([], prob.nCells).writeln; "Possibilities:".writeln; auto nConfigs = 0; foreach (const sol; nonoBlocks(prob.tupleof)) { show(sol, prob.nCells).writeln; nConfigs++; } writefln("A total of %d possible configurations.", nConfigs); writeln; } }
http://rosettacode.org/wiki/Non-decimal_radices/Input
Non-decimal radices/Input
It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.) This task requires parsing of such a string (which may be assumed to contain nothing else) using the language's built-in facilities if possible. Parsing of decimal strings is required, parsing of other formats is optional but should be shown (i.e., if the language can parse in base-19 then that should be illustrated). The solutions may assume that the base of the number in the string is known. In particular, if your language has a facility to guess the base of a number by looking at a prefix (e.g. "0x" for hexadecimal) or other distinguishing syntax as it parses it, please show that. The reverse operation is in task Non-decimal radices/Output For general number base conversion, see Non-decimal radices/Convert.
#Ada
Ada
with Ada.Text_IO; procedure Numbers is package Int_IO is new Ada.Text_IO.Integer_IO (Integer); package Float_IO is new Ada.Text_IO.Float_IO (Float); begin Int_IO.Put (Integer'Value ("16#ABCF123#")); Ada.Text_IO.New_Line; Int_IO.Put (Integer'Value ("8#7651#")); Ada.Text_IO.New_Line; Int_IO.Put (Integer'Value ("2#1010011010#")); Ada.Text_IO.New_Line; Float_IO.Put (Float'Value ("16#F.FF#E+2")); Ada.Text_IO.New_Line; end Numbers;
http://rosettacode.org/wiki/Non-decimal_radices/Input
Non-decimal radices/Input
It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.) This task requires parsing of such a string (which may be assumed to contain nothing else) using the language's built-in facilities if possible. Parsing of decimal strings is required, parsing of other formats is optional but should be shown (i.e., if the language can parse in base-19 then that should be illustrated). The solutions may assume that the base of the number in the string is known. In particular, if your language has a facility to guess the base of a number by looking at a prefix (e.g. "0x" for hexadecimal) or other distinguishing syntax as it parses it, please show that. The reverse operation is in task Non-decimal radices/Output For general number base conversion, see Non-decimal radices/Convert.
#Aime
Aime
o_integer(alpha("f4240", 16)); o_byte('\n'); o_integer(alpha("224000000", 5)); o_byte('\n'); o_integer(alpha("11110100001001000000", 2)); o_byte('\n');   o_integer(alpha("03641100", 0)); o_byte('\n'); o_integer(alpha("0xf4240", 0)); o_byte('\n');
http://rosettacode.org/wiki/Numerical_integration
Numerical integration
Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods: rectangular left right midpoint trapezium Simpson's composite Your functions should take in the upper and lower bounds (a and b), and the number of approximations to make in that range (n). Assume that your example already has a function that gives values for ƒ(x) . Simpson's method is defined by the following pseudo-code: Pseudocode: Simpson's method, composite procedure quad_simpson_composite(f, a, b, n) h := (b - a) / n sum1 := f(a + h/2) sum2 := 0 loop on i from 1 to (n - 1) sum1 := sum1 + f(a + h * i + h/2) sum2 := sum2 + f(a + h * i)   answer := (h / 6) * (f(a) + f(b) + 4*sum1 + 2*sum2) Demonstrate your function by showing the results for:   ƒ(x) = x3,       where   x   is     [0,1],       with           100 approximations.   The exact result is     0.25               (or 1/4)   ƒ(x) = 1/x,     where   x   is   [1,100],     with        1,000 approximations.   The exact result is     4.605170+     (natural log of 100)   ƒ(x) = x,         where   x   is   [0,5000],   with 5,000,000 approximations.   The exact result is   12,500,000   ƒ(x) = x,         where   x   is   [0,6000],   with 6,000,000 approximations.   The exact result is   18,000,000 See also   Active object for integrating a function of real time.   Special:PrefixIndex/Numerical integration for other integration methods.
#Wren
Wren
import "/fmt" for Fmt   var integrate = Fn.new { |a, b, n, f| var h = (b - a) / n var sum = List.filled(5, 0) for (i in 0...n) { var x = a + i * h sum[0] = sum[0] + f.call(x) sum[1] = sum[1] + f.call(x + h/2) sum[2] = sum[2] + f.call(x + h) sum[3] = sum[3] + (f.call(x) + f.call(x+h))/2 sum[4] = sum[4] + (f.call(x) + 4 * f.call(x + h/2) + f.call(x + h))/6 } var methods = ["LeftRect ", "MidRect ", "RightRect", "Trapezium", "Simpson "] for (i in 0..4) Fmt.print("$s = $h", methods[i], sum[i] * h) System.print() }   integrate.call(0, 1, 100) { |v| v * v * v } integrate.call(1, 100, 1000) { |v| 1 / v } integrate.call(0, 5000, 5000000) { |v| v } integrate.call(0, 6000, 6000000) { |v| v }  
http://rosettacode.org/wiki/Non-decimal_radices/Output
Non-decimal radices/Output
Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal. Task Print a small range of integers in some different bases, as supported by standard routines of your programming language. Note This is distinct from Number base conversion as a user-defined conversion function is not asked for.) The reverse operation is Common number base parsing.
#11l
11l
V n = 33 print(bin(n)‘ ’String(n, radix' 8)‘ ’n‘ ’hex(n))
http://rosettacode.org/wiki/Number_names
Number names
Task Show how to spell out a number in English. You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less). Support for inputs other than positive integers (like zero, negative integers, and floating-point numbers) is optional. Related task   Spelling of ordinal numbers.
#PicoLisp
PicoLisp
(de numName (N) (cond ((=0 N) "zero") ((lt0 N) (pack "minus " (numName (- N)))) (T (numNm N)) ) )   (de numNm (N) (cond ((=0 N)) ((> 14 N) (get '("one" "two" "three" "four" "five" "six" "seven" "eight" "nine" "ten" "eleven" "twelve" "thirteen") N) ) ((= 15 N) "fifteen") ((= 18 N) "eighteen") ((> 20 N) (pack (numNm (% N 10)) "teen")) ((> 100 N) (pack (get '("twen" "thir" "for" "fif" "six" "seven" "eigh" "nine") (dec (/ N 10))) "ty" (unless (=0 (% N 10)) (pack "-" (numNm (% N 10))) ) ) ) ((rank N '((100 . "hundred") (1000 . "thousand") (1000000 . "million"))) (pack (numNm (/ N (car @))) " " (cdr @) " " (numNm (% N (car @)))) ) ) )
http://rosettacode.org/wiki/Number_reversal_game
Number reversal game
Task Given a jumbled list of the numbers   1   to   9   that are definitely   not   in ascending order. Show the list,   and then ask the player how many digits from the left to reverse. Reverse those digits,   then ask again,   until all the digits end up in ascending order. The score is the count of the reversals needed to attain the ascending order. Note: Assume the player's input does not need extra validation. Related tasks   Sorting algorithms/Pancake sort   Pancake sorting.   Topswops
#PowerShell
PowerShell
  #adding the below function to the previous users submission to prevent the small #chance of getting an array that is in ascending order.   #Full disclosure: I am an infrastructure engineer, not a dev. My code is likely #bad.   function generateArray{ $fArray = 1..9 | Get-Random -Count 9 if (-join $fArray -eq -join @(1..9)){ generateArray } return $fArray } $array = generateArray   #everything below is untouched from original submission $nTries = 0 While(-join $Array -ne -join @(1..9)){ $nTries++ $nReverse = Read-Host -Prompt "[$Array] -- How many digits to reverse? " [Array]::Reverse($Array,0,$nReverse) } "$Array" "Your score: $nTries"  
http://rosettacode.org/wiki/One-dimensional_cellular_automata
One-dimensional cellular automata
Assume an array of cells with an initial distribution of live and dead cells, and imaginary cells off the end of the array having fixed values. Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation. If, in the following table, a live cell is represented by 1 and a dead cell by 0 then to generate the value of the cell at a particular index in the array of cellular values you use the following table: 000 -> 0 # 001 -> 0 # 010 -> 0 # Dies without enough neighbours 011 -> 1 # Needs one neighbour to survive 100 -> 0 # 101 -> 1 # Two neighbours giving birth 110 -> 1 # Needs one neighbour to survive 111 -> 0 # Starved to death.
#Seed7
Seed7
$ include "seed7_05.s7i";   const string: start is "_###_##_#_#_#_#__#__";   const proc: main is func local var string: g0 is start; var string: g1 is start; var integer: generation is 0; var integer: i is 0; begin writeln(g0); for generation range 0 to 9 do for i range 2 to pred(length(g0)) do if g0[i-1] <> g0[i+1] then g1 @:= [i] g0[i]; elsif g0[i] = '_' then g1 @:= [i] g0[i-1]; else g1 @:= [i] '_' end if; end for; writeln(g1); g0 := g1; end for; end func;
http://rosettacode.org/wiki/One-dimensional_cellular_automata
One-dimensional cellular automata
Assume an array of cells with an initial distribution of live and dead cells, and imaginary cells off the end of the array having fixed values. Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation. If, in the following table, a live cell is represented by 1 and a dead cell by 0 then to generate the value of the cell at a particular index in the array of cellular values you use the following table: 000 -> 0 # 001 -> 0 # 010 -> 0 # Dies without enough neighbours 011 -> 1 # Needs one neighbour to survive 100 -> 0 # 101 -> 1 # Two neighbours giving birth 110 -> 1 # Needs one neighbour to survive 111 -> 0 # Starved to death.
#SequenceL
SequenceL
import <Utilities/Conversion.sl>;   main(args(2)) := run(args[1], stringToInt(args[2])) when size(args) = 2 else "Usage error: exec <initialCells> <generations>";   stringToCells(string(1))[i] := 0 when string[i] = '_' else 1; cellsToString(cells(1))[i] := '#' when cells[i] = 1 else '_';   run(cellsString(1), generations) := runHelper(stringToCells(cellsString), generations, cellsString);   runHelper(cells(1), generations, result(1)) := let nextCells := step(cells); in result when generations = 0 else runHelper(nextCells, generations - 1, result ++ "\n" ++ cellsToString(nextCells));   step(cells(1))[i] := let left := cells[i-1] when i > 1 else 0; right := cells[i + 1] when i < size(cells) else 0; in 1 when (left + cells[i] + right) = 2 else 0;
http://rosettacode.org/wiki/Nonoblock
Nonoblock
Nonoblock is a chip off the old Nonogram puzzle. Given The number of cells in a row. The size of each, (space separated), connected block of cells to fit in the row, in left-to right order. Task show all possible positions. show the number of positions of the blocks for the following cases within the row. show all output on this page. use a "neat" diagram of the block positions. Enumerate the following configurations   5   cells   and   [2, 1]   blocks   5   cells   and   []   blocks   (no blocks)   10   cells   and   [8]   blocks   15   cells   and   [2, 3, 2, 3]   blocks   5   cells   and   [2, 3]   blocks   (should give some indication of this not being possible) Example Given a row of five cells and a block of two cells followed by a block of one cell - in that order, the example could be shown as: |_|_|_|_|_| # 5 cells and [2, 1] blocks And would expand to the following 3 possible rows of block positions: |A|A|_|B|_| |A|A|_|_|B| |_|A|A|_|B| Note how the sets of blocks are always separated by a space. Note also that it is not necessary for each block to have a separate letter. Output approximating This: |#|#|_|#|_| |#|#|_|_|#| |_|#|#|_|#| This would also work: ##.#. ##..# .##.# An algorithm Find the minimum space to the right that is needed to legally hold all but the leftmost block of cells (with a space between blocks remember). The leftmost cell can legitimately be placed in all positions from the LHS up to a RH position that allows enough room for the rest of the blocks. for each position of the LH block recursively compute the position of the rest of the blocks in the remaining space to the right of the current placement of the LH block. (This is the algorithm used in the Nonoblock#Python solution). Reference The blog post Nonogram puzzle solver (part 1) Inspired this task and donated its Nonoblock#Python solution.
#EchoLisp
EchoLisp
  ;; size is the remaining # of cells ;; blocks is the list of remaining blocks size ;; cells is a stack where we push 0 = space or block size. (define (nonoblock size blocks into: cells) (cond ((and (empty? blocks) (= 0 size)) (print-cells (stack->list cells)))   ((<= size 0) #f) ;; no hope - cut search ((> (apply + blocks) size) #f) ;; no hope - cut search   (else (push cells 0) ;; space (nonoblock (1- size) blocks cells) (pop cells)   (when (!empty? blocks) (when (stack-empty? cells) ;; first one (no space is allowed) (push cells (first blocks)) (nonoblock (- size (first blocks)) (rest blocks) cells) (pop cells))   (push cells 0) ;; add space before (push cells (first blocks)) (nonoblock (- size (first blocks) 1) (rest blocks) cells) (pop cells) (pop cells)))))   (string-delimiter "") (define block-symbs #( ? 📦 💣 💊 🍒 🌽 📘 📙 💰 🍯 ))   (define (print-cells cells) (writeln (string-append "|" (for/string ((cell cells)) (if (zero? cell) "_" (for/string ((i cell)) [block-symbs cell]))) "|")))   (define (task nonotest) (for ((test nonotest)) (define size (first test)) (define blocks (second test)) (printf "\n size:%d blocks:%d" size blocks) (if (> (+ (apply + blocks)(1- (length blocks))) size) (writeln "❌ no solution for" size blocks) (nonoblock size blocks (stack 'cells)))))  
http://rosettacode.org/wiki/Non-decimal_radices/Input
Non-decimal radices/Input
It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.) This task requires parsing of such a string (which may be assumed to contain nothing else) using the language's built-in facilities if possible. Parsing of decimal strings is required, parsing of other formats is optional but should be shown (i.e., if the language can parse in base-19 then that should be illustrated). The solutions may assume that the base of the number in the string is known. In particular, if your language has a facility to guess the base of a number by looking at a prefix (e.g. "0x" for hexadecimal) or other distinguishing syntax as it parses it, please show that. The reverse operation is in task Non-decimal radices/Output For general number base conversion, see Non-decimal radices/Convert.
#ALGOL_68
ALGOL 68
main: ( FILE fbuf; STRING sbuf;   OP FBUF = (STRING in sbuf)REF FILE: ( sbuf := in sbuf; associate(fbuf, sbuf); fbuf );   BITS num;   getf(FBUF("0123459"), ($10r7d$, num)); printf(($gl$, ABS num)); # prints 123459 #   getf(FBUF("abcf123"), ($16r7d$, num)); printf(($gl$, ABS num)); # prints 180154659 #   getf(FBUF("7651"), ($8r4d$, num)); printf(($gl$, ABS num)); # prints 4009 #   getf(FBUF("1010011010"), ($2r10d$, num)); printf(($gl$, ABS num)) # prints 666 #   )
http://rosettacode.org/wiki/Numerical_integration
Numerical integration
Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods: rectangular left right midpoint trapezium Simpson's composite Your functions should take in the upper and lower bounds (a and b), and the number of approximations to make in that range (n). Assume that your example already has a function that gives values for ƒ(x) . Simpson's method is defined by the following pseudo-code: Pseudocode: Simpson's method, composite procedure quad_simpson_composite(f, a, b, n) h := (b - a) / n sum1 := f(a + h/2) sum2 := 0 loop on i from 1 to (n - 1) sum1 := sum1 + f(a + h * i + h/2) sum2 := sum2 + f(a + h * i)   answer := (h / 6) * (f(a) + f(b) + 4*sum1 + 2*sum2) Demonstrate your function by showing the results for:   ƒ(x) = x3,       where   x   is     [0,1],       with           100 approximations.   The exact result is     0.25               (or 1/4)   ƒ(x) = 1/x,     where   x   is   [1,100],     with        1,000 approximations.   The exact result is     4.605170+     (natural log of 100)   ƒ(x) = x,         where   x   is   [0,5000],   with 5,000,000 approximations.   The exact result is   12,500,000   ƒ(x) = x,         where   x   is   [0,6000],   with 6,000,000 approximations.   The exact result is   18,000,000 See also   Active object for integrating a function of real time.   Special:PrefixIndex/Numerical integration for other integration methods.
#XPL0
XPL0
include c:\cxpl\codes; \intrinsic 'code' declarations   func real Func(FN, X); \Return F(X) for function number FN int FN; real X; [case FN of 1: return X*X*X; 2: return 1.0/X; 3: return X other return 0.0; ];   func Integrate(A, B, FN, N); \Display area under curve for function FN real A, B; int FN, N; \limits A, B, and number of slices N real DX, X, Area; \delta X int I; [DX:= (B-A)/float(N); X:= A; Area:= 0.0; \rectangular left for I:= 1 to N do [Area:= Area + Func(FN,X)*DX; X:= X+DX]; RlOut(0, Area); X:= A; Area:= 0.0; \rectangular right for I:= 1 to N do [X:= X+DX; Area:= Area + Func(FN,X)*DX]; RlOut(0, Area); X:= A+DX/2.0; Area:= 0.0; \rectangular mid point for I:= 1 to N do [Area:= Area + Func(FN,X)*DX; X:= X+DX]; RlOut(0, Area); X:= A; Area:= 0.0; \trapezium for I:= 1 to N do [Area:= Area + (Func(FN,X)+Func(FN,X+DX))/2.0*DX; X:= X+DX]; RlOut(0, Area); X:= A; Area:= 0.0; \Simpson's rule for I:= 1 to N do [Area:= Area + DX/6.0*(Func(FN,X) + 4.0*Func(FN,(X+X+DX)/2.0) + Func(FN,X+DX)); X:= X+DX]; RlOut(0, Area); CrLf(0); ];   [Format(9,6); Integrate(0.0, 1.0, 1, 100); Integrate(1.0, 100.0, 2, 1000); Integrate(0.0, 5000.0, 3, 5_000_000); Integrate(0.0, 6000.0, 3, 6_000_000); ]
http://rosettacode.org/wiki/Non-decimal_radices/Output
Non-decimal radices/Output
Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal. Task Print a small range of integers in some different bases, as supported by standard routines of your programming language. Note This is distinct from Number base conversion as a user-defined conversion function is not asked for.) The reverse operation is Common number base parsing.
#Action.21
Action!
INCLUDE "D2:PRINTF.ACT" ;from the Action! Tool Kit   PROC Main() CARD ARRAY v=[6502 1977 2021 256 1024 12345 9876 1111 0 16] BYTE i,LMARGIN=$52,old   old=LMARGIN LMARGIN=0 ;remove left margin on the screen Put(125) PutE() ;clear the screen   FOR i=0 TO 9 DO PrintF("(dec) %D = (hex) %H = (oct) %O%E",v(i),v(i),v(i)) OD   LMARGIN=old ;restore left margin on the screen RETURN
http://rosettacode.org/wiki/Non-decimal_radices/Output
Non-decimal radices/Output
Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal. Task Print a small range of integers in some different bases, as supported by standard routines of your programming language. Note This is distinct from Number base conversion as a user-defined conversion function is not asked for.) The reverse operation is Common number base parsing.
#Ada
Ada
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; with Ada.Text_IO; use Ada.Text_IO;   procedure Test_Integer_Text_IO is begin for I in 1..33 loop Put (I, Width =>3, Base=> 10); Put (I, Width =>7, Base=> 16); Put (I, Width =>6, Base=> 8); New_Line; end loop; end Test_Integer_Text_IO;
http://rosettacode.org/wiki/Number_names
Number names
Task Show how to spell out a number in English. You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less). Support for inputs other than positive integers (like zero, negative integers, and floating-point numbers) is optional. Related task   Spelling of ordinal numbers.
#PL.2FI
PL/I
declare integer_names (0:20) character (9) varying static initial ('zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen', 'twenty' ); declare x(10) character (7) varying static initial ('ten', 'twenty', 'thirty', 'fourty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety', 'hundred'); declare y(0:5) character (10) varying static initial ('', '', ' thousand ', ' million ', ' billion ', ' trillion '); declare (i, j, m, t) fixed binary (31); declare (units, tens, hundreds, thousands) fixed binary (7); declare (h, v, value) character (200) varying; declare (d, k, n) fixed decimal (15); declare three_digits fixed decimal (3);   value = ''; i = 5; k = n; do d = 1000000000000 repeat d/1000 while (d > 0); i = i - 1; three_digits = k/d; k = mod(k, d); if three_digits = 0 then iterate;   units = mod(three_digits, 10); t = three_digits / 10; tens = mod(t, 10); hundreds = three_digits / 100; m = mod(three_digits, 100); if m <= 20 then v = integer_names(m); else if units = 0 then v = ''; else v = integer_names(units); if tens >= 2 & units ^= 0 then v = x(tens) || v; else if tens > 2 & units = 0 then v = v || x(tens);   if units + tens = 0 then if n > 0 then v = ''; if hundreds > 0 then h = integer_names(hundreds) || ' hundred '; else h = ''; if three_digits > 100 & (tens + units > 0) then v = 'and ' || v; if i = 1 & value ^= '' & three_digits <= 9 then v = 'and ' || v; value = value ||h || v || y(i); end; put skip edit (trim(N), ' = ', value) (a);
http://rosettacode.org/wiki/Number_reversal_game
Number reversal game
Task Given a jumbled list of the numbers   1   to   9   that are definitely   not   in ascending order. Show the list,   and then ask the player how many digits from the left to reverse. Reverse those digits,   then ask again,   until all the digits end up in ascending order. The score is the count of the reversals needed to attain the ascending order. Note: Assume the player's input does not need extra validation. Related tasks   Sorting algorithms/Pancake sort   Pancake sorting.   Topswops
#Prolog
Prolog
play :- random_numbers(L), do_turn(0,L), !.   do_turn(N, L) :- print_list(L), how_many_to_flip(F), flip(L,F,[],Lnew), succ(N,N1), sorted(N1,Lnew).   how_many_to_flip(F) :- read_line_to_codes(user_input, Line), number_codes(F, Line), between(1,9,F).   flip(L,0,C,R) :- append(C,L,R). flip([Ln|T],N,C,R) :- dif(N,0), succ(N0,N), flip(T,N0,[Ln|C],R).   sorted(N,L) :- sort(L,L) -> print_list(L), format('-> ~p~n', N) ; do_turn(N,L).   random_numbers(L) :- random_permutation([1,2,3,4,5,6,7,8,9],L).   print_list(L) :- atomic_list_concat(L, ' ', Lf), format('(~w) ',Lf).
http://rosettacode.org/wiki/One-dimensional_cellular_automata
One-dimensional cellular automata
Assume an array of cells with an initial distribution of live and dead cells, and imaginary cells off the end of the array having fixed values. Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation. If, in the following table, a live cell is represented by 1 and a dead cell by 0 then to generate the value of the cell at a particular index in the array of cellular values you use the following table: 000 -> 0 # 001 -> 0 # 010 -> 0 # Dies without enough neighbours 011 -> 1 # Needs one neighbour to survive 100 -> 0 # 101 -> 1 # Two neighbours giving birth 110 -> 1 # Needs one neighbour to survive 111 -> 0 # Starved to death.
#Sidef
Sidef
var seq = "_###_##_#_#_#_#__#__"; var x = '';   loop { seq.tr!('01', '_#'); say seq; seq.tr!('_#', '01'); seq.gsub!(/(?<=(.))(.)(?=(.))/, {|s1,s2,s3| s1 == s3 ? (s1 ? 1-s2 : 0) : s2}); (x != seq) && (x = seq) || break; }
http://rosettacode.org/wiki/Nonoblock
Nonoblock
Nonoblock is a chip off the old Nonogram puzzle. Given The number of cells in a row. The size of each, (space separated), connected block of cells to fit in the row, in left-to right order. Task show all possible positions. show the number of positions of the blocks for the following cases within the row. show all output on this page. use a "neat" diagram of the block positions. Enumerate the following configurations   5   cells   and   [2, 1]   blocks   5   cells   and   []   blocks   (no blocks)   10   cells   and   [8]   blocks   15   cells   and   [2, 3, 2, 3]   blocks   5   cells   and   [2, 3]   blocks   (should give some indication of this not being possible) Example Given a row of five cells and a block of two cells followed by a block of one cell - in that order, the example could be shown as: |_|_|_|_|_| # 5 cells and [2, 1] blocks And would expand to the following 3 possible rows of block positions: |A|A|_|B|_| |A|A|_|_|B| |_|A|A|_|B| Note how the sets of blocks are always separated by a space. Note also that it is not necessary for each block to have a separate letter. Output approximating This: |#|#|_|#|_| |#|#|_|_|#| |_|#|#|_|#| This would also work: ##.#. ##..# .##.# An algorithm Find the minimum space to the right that is needed to legally hold all but the leftmost block of cells (with a space between blocks remember). The leftmost cell can legitimately be placed in all positions from the LHS up to a RH position that allows enough room for the rest of the blocks. for each position of the LH block recursively compute the position of the rest of the blocks in the remaining space to the right of the current placement of the LH block. (This is the algorithm used in the Nonoblock#Python solution). Reference The blog post Nonogram puzzle solver (part 1) Inspired this task and donated its Nonoblock#Python solution.
#Elixir
Elixir
defmodule Nonoblock do def solve(cell, blocks) do width = Enum.sum(blocks) + length(blocks) - 1 if cell < width do raise "Those blocks will not fit in those cells" else nblocks(cell, blocks, "") end end   defp nblocks(cell, _, position) when cell<=0, do: display(String.slice(position, 0..cell-1)) defp nblocks(cell, blocks, position) when length(blocks)==0 or hd(blocks)==0, do: display(position <> String.duplicate(".", cell)) defp nblocks(cell, blocks, position) do rest = cell - Enum.sum(blocks) - length(blocks) + 2 [bl | brest] = blocks Enum.reduce(0..rest-1, 0, fn i,acc -> acc + nblocks(cell-i-bl-1, brest, position <> String.duplicate(".", i) <> String.duplicate("#",bl) <> ".") end) end   defp display(str) do IO.puts nonocell(str) 1 # number of positions end   def nonocell(str) do # "##.###..##" -> "|A|A|_|B|B|B|_|_|C|C|" slist = String.to_char_list(str) |> Enum.chunk_by(&(&1==?.)) |> Enum.map(&List.to_string(&1)) chrs = Enum.map(?A..?Z, &List.to_string([&1])) result = nonocell_replace(slist, chrs, "") |> String.replace(".", "_") |> String.split("") |> Enum.join("|") "|" <> result end   defp nonocell_replace([], _, result), do: result defp nonocell_replace([h|t], chrs, result) do if String.first(h) == "#" do [c | rest] = chrs nonocell_replace(t, rest, result <> String.replace(h, "#", c)) else nonocell_replace(t, chrs, result <> h) end end end   conf = [{ 5, [2, 1]}, { 5, []}, {10, [8]}, {15, [2, 3, 2, 3]}, { 5, [2, 3]} ] Enum.each(conf, fn {cell, blocks} -> try do IO.puts "Configuration:" IO.puts "#{Nonoblock.nonocell(String.duplicate(".",cell))} # #{cell} cells and #{inspect blocks} blocks" IO.puts "Possibilities:" count = Nonoblock.solve(cell, blocks) IO.puts "A total of #{count} Possible configurations.\n" rescue e in RuntimeError -> IO.inspect e end end)
http://rosettacode.org/wiki/Nonoblock
Nonoblock
Nonoblock is a chip off the old Nonogram puzzle. Given The number of cells in a row. The size of each, (space separated), connected block of cells to fit in the row, in left-to right order. Task show all possible positions. show the number of positions of the blocks for the following cases within the row. show all output on this page. use a "neat" diagram of the block positions. Enumerate the following configurations   5   cells   and   [2, 1]   blocks   5   cells   and   []   blocks   (no blocks)   10   cells   and   [8]   blocks   15   cells   and   [2, 3, 2, 3]   blocks   5   cells   and   [2, 3]   blocks   (should give some indication of this not being possible) Example Given a row of five cells and a block of two cells followed by a block of one cell - in that order, the example could be shown as: |_|_|_|_|_| # 5 cells and [2, 1] blocks And would expand to the following 3 possible rows of block positions: |A|A|_|B|_| |A|A|_|_|B| |_|A|A|_|B| Note how the sets of blocks are always separated by a space. Note also that it is not necessary for each block to have a separate letter. Output approximating This: |#|#|_|#|_| |#|#|_|_|#| |_|#|#|_|#| This would also work: ##.#. ##..# .##.# An algorithm Find the minimum space to the right that is needed to legally hold all but the leftmost block of cells (with a space between blocks remember). The leftmost cell can legitimately be placed in all positions from the LHS up to a RH position that allows enough room for the rest of the blocks. for each position of the LH block recursively compute the position of the rest of the blocks in the remaining space to the right of the current placement of the LH block. (This is the algorithm used in the Nonoblock#Python solution). Reference The blog post Nonogram puzzle solver (part 1) Inspired this task and donated its Nonoblock#Python solution.
#Go
Go
package main   import ( "fmt" "strings" )   func printBlock(data string, le int) { a := []byte(data) sumBytes := 0 for _, b := range a { sumBytes += int(b - 48) } fmt.Printf("\nblocks %c, cells %d\n", a, le) if le-sumBytes <= 0 { fmt.Println("No solution") return } prep := make([]string, len(a)) for i, b := range a { prep[i] = strings.Repeat("1", int(b-48)) } for _, r := range genSequence(prep, le-sumBytes+1) { fmt.Println(r[1:]) } }   func genSequence(ones []string, numZeros int) []string { if len(ones) == 0 { return []string{strings.Repeat("0", numZeros)} } var result []string for x := 1; x < numZeros-len(ones)+2; x++ { skipOne := ones[1:] for _, tail := range genSequence(skipOne, numZeros-x) { result = append(result, strings.Repeat("0", x)+ones[0]+tail) } } return result }   func main() { printBlock("21", 5) printBlock("", 5) printBlock("8", 10) printBlock("2323", 15) printBlock("23", 5) }
http://rosettacode.org/wiki/Non-transitive_dice
Non-transitive dice
Let our dice select numbers on their faces with equal probability, i.e. fair dice. Dice may have more or less than six faces. (The possibility of there being a 3D physical shape that has that many "faces" that allow them to be fair dice, is ignored for this task - a die with 3 or 33 defined sides is defined by the number of faces and the numbers on each face). Throwing dice will randomly select a face on each die with equal probability. To show which die of dice thrown multiple times is more likely to win over the others: calculate all possible combinations of different faces from each die Count how many times each die wins a combination Each combination is equally likely so the die with more winning face combinations is statistically more likely to win against the other dice. If two dice X and Y are thrown against each other then X likely to: win, lose, or break-even against Y can be shown as: X > Y, X < Y, or X = Y respectively. Example 1 If X is the three sided die with 1, 3, 6 on its faces and Y has 2, 3, 4 on its faces then the equal possibility outcomes from throwing both, and the winners is: X Y Winner = = ====== 1 2 Y 1 3 Y 1 4 Y 3 2 X 3 3 - 3 4 Y 6 2 X 6 3 X 6 4 X TOTAL WINS: X=4, Y=4 Both die will have the same statistical probability of winning, i.e.their comparison can be written as X = Y Transitivity In mathematics transitivity are rules like: if a op b and b op c then a op c If, for example, the op, (for operator), is the familiar less than, <, and it's applied to integers we get the familiar if a < b and b < c then a < c Non-transitive dice These are an ordered list of dice where the '>' operation between successive dice pairs applies but a comparison between the first and last of the list yields the opposite result, '<'. (Similarly '<' successive list comparisons with a final '>' between first and last is also non-transitive). Three dice S, T, U with appropriate face values could satisfy S < T, T < U and yet S > U To be non-transitive. Notes The order of numbers on the faces of a die is not relevant. For example, three faced die described with face numbers of 1, 2, 3 or 2, 1, 3 or any other permutation are equivalent. For the purposes of the task show only the permutation in lowest-first sorted order i.e. 1, 2, 3 (and remove any of its perms). A die can have more than one instance of the same number on its faces, e.g. 2, 3, 3, 4 Rotations: Any rotation of non-transitive dice from an answer is also an answer. You may optionally compute and show only one of each such rotation sets, ideally the first when sorted in a natural way. If this option is used then prominently state in the output that rotations of results are also solutions. Task ==== Find all the ordered lists of three non-transitive dice S, T, U of the form S < T, T < U and yet S > U; where the dice are selected from all four-faced die , (unique w.r.t the notes), possible by having selections from the integers one to four on any dies face. Solution can be found by generating all possble individual die then testing all possible permutations, (permutations are ordered), of three dice for non-transitivity. Optional stretch goal Find lists of four non-transitive dice selected from the same possible dice from the non-stretch goal. Show the results here, on this page. References The Most Powerful Dice - Numberphile Video. Nontransitive dice - Wikipedia.
#F.23
F#
  // Non-transitive dice. Nigel Galloway: August 9th., 2020 let die=[for n0 in [1..4] do for n1 in [n0..4] do for n2 in [n1..4] do for n3 in [n2..4]->[n0;n1;n2;n3]] let N=seq{for n in die->(n,[for g in die do if (seq{for n in n do for g in g->compare n g}|>Seq.sum<0) then yield g])}|>Map.ofSeq let n3=seq{for d1 in die do for d2 in N.[d1] do for d3 in N.[d2] do if List.contains d1 N.[d3] then yield (d1,d2,d3)} let n4=seq{for d1 in die do for d2 in N.[d1] do for d3 in N.[d2] do for d4 in N.[d3] do if List.contains d1 N.[d4] then yield (d1,d2,d3,d4)} n3|>Seq.iter(fun(d1,d2,d3)->printfn "%A<%A; %A<%A; %A>%A\n" d1 d2 d2 d3 d1 d3) n4|>Seq.iter(fun(d1,d2,d3,d4)->printfn "%A<%A; %A<%A; %A<%A; %A>%A" d1 d2 d2 d3 d3 d4 d1 d4)
http://rosettacode.org/wiki/Non-decimal_radices/Input
Non-decimal radices/Input
It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.) This task requires parsing of such a string (which may be assumed to contain nothing else) using the language's built-in facilities if possible. Parsing of decimal strings is required, parsing of other formats is optional but should be shown (i.e., if the language can parse in base-19 then that should be illustrated). The solutions may assume that the base of the number in the string is known. In particular, if your language has a facility to guess the base of a number by looking at a prefix (e.g. "0x" for hexadecimal) or other distinguishing syntax as it parses it, please show that. The reverse operation is in task Non-decimal radices/Output For general number base conversion, see Non-decimal radices/Convert.
#Arturo
Arturo
print to :integer "10" ; 10   print from.hex "10" ; 16 print from.octal "120" ; 80 print from.binary "10101" ; 21
http://rosettacode.org/wiki/Non-decimal_radices/Input
Non-decimal radices/Input
It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.) This task requires parsing of such a string (which may be assumed to contain nothing else) using the language's built-in facilities if possible. Parsing of decimal strings is required, parsing of other formats is optional but should be shown (i.e., if the language can parse in base-19 then that should be illustrated). The solutions may assume that the base of the number in the string is known. In particular, if your language has a facility to guess the base of a number by looking at a prefix (e.g. "0x" for hexadecimal) or other distinguishing syntax as it parses it, please show that. The reverse operation is in task Non-decimal radices/Output For general number base conversion, see Non-decimal radices/Convert.
#AutoHotkey
AutoHotkey
REM VAL parses decimal strings: PRINT VAL("0") PRINT VAL("123456789") PRINT VAL("-987654321")   REM EVAL can be used to parse binary and hexadecimal strings: PRINT EVAL("%10101010") PRINT EVAL("%1111111111") PRINT EVAL("&ABCD") PRINT EVAL("&FFFFFFFF")
http://rosettacode.org/wiki/Numerical_integration
Numerical integration
Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods: rectangular left right midpoint trapezium Simpson's composite Your functions should take in the upper and lower bounds (a and b), and the number of approximations to make in that range (n). Assume that your example already has a function that gives values for ƒ(x) . Simpson's method is defined by the following pseudo-code: Pseudocode: Simpson's method, composite procedure quad_simpson_composite(f, a, b, n) h := (b - a) / n sum1 := f(a + h/2) sum2 := 0 loop on i from 1 to (n - 1) sum1 := sum1 + f(a + h * i + h/2) sum2 := sum2 + f(a + h * i)   answer := (h / 6) * (f(a) + f(b) + 4*sum1 + 2*sum2) Demonstrate your function by showing the results for:   ƒ(x) = x3,       where   x   is     [0,1],       with           100 approximations.   The exact result is     0.25               (or 1/4)   ƒ(x) = 1/x,     where   x   is   [1,100],     with        1,000 approximations.   The exact result is     4.605170+     (natural log of 100)   ƒ(x) = x,         where   x   is   [0,5000],   with 5,000,000 approximations.   The exact result is   12,500,000   ƒ(x) = x,         where   x   is   [0,6000],   with 6,000,000 approximations.   The exact result is   18,000,000 See also   Active object for integrating a function of real time.   Special:PrefixIndex/Numerical integration for other integration methods.
#Yabasic
Yabasic
// Rosetta Code problem: https://rosettacode.org/wiki/Numerical_integration // by Jjuanhdez, 06/2022   print "function range steps leftrect midrect rightrect trap simpson " frmt$ = "%1.10f" print "f(x) = x^3 0 - 1 100 "; Integrate(0.0, 1.0, 1, 100) print "f(x) = 1/x 1 - 100 1000 "; Integrate(1.0, 100.0, 2, 1000) frmt$ = "%8.3f" print "f(x) = x 0 - 5000 5000000 "; Integrate(0.0, 5000.0, 3, 5000000) print "f(x) = x 0 - 6000 6000000 "; Integrate(0.0, 6000.0, 3, 6000000) end   sub Func(FN, X) //Return F(X) for function number FN switch FN case 1 return X ^ 3 case 2 return 1.0 / X case 3 return X default return 0.0 end switch end sub   sub Integrate(A, B, FN, N) //Display area under curve for function FN // A, B, FN limits A, B, and number of slices N   DX = (B-A)/N X = A Area = 0.0 //rectangular left for i = 1 to N Area = Area + Func(FN,X)*DX X = X + DX next i print str$(Area, frmt$); X = A Area = 0.0 //rectangular right for i = 1 to N X = X + DX Area = Area + Func(FN,X)*DX next i print " "; print str$(Area, frmt$); X = A + DX / 2.0 Area = 0.0 //rectangular mid point for i = 1 to N Area = Area + Func(FN,X)*DX X = X + DX next i print " "; print str$(Area, frmt$); X = A Area = 0.0 //trapezium for i = 1 to N Area = Area + (Func(FN,X)+Func(FN,X + DX))/2.0*DX X = X + DX next i print " "; print str$(Area, frmt$); X = A Area = 0.0 //Simpson's rule for i = 1 to N Area = Area + DX/6.0*(Func(FN,X) + 4.0*Func(FN,(X+X + DX)/2.0) + Func(FN,X + DX)) X = X + DX next i print " "; print str$(Area, frmt$) end sub
http://rosettacode.org/wiki/Non-decimal_radices/Output
Non-decimal radices/Output
Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal. Task Print a small range of integers in some different bases, as supported by standard routines of your programming language. Note This is distinct from Number base conversion as a user-defined conversion function is not asked for.) The reverse operation is Common number base parsing.
#Aime
Aime
o_xinteger(16, 1000000); o_byte('\n'); o_xinteger(5, 1000000); o_byte('\n'); o_xinteger(2, 1000000); o_byte('\n');
http://rosettacode.org/wiki/Non-decimal_radices/Output
Non-decimal radices/Output
Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal. Task Print a small range of integers in some different bases, as supported by standard routines of your programming language. Note This is distinct from Number base conversion as a user-defined conversion function is not asked for.) The reverse operation is Common number base parsing.
#ALGOL_68
ALGOL 68
main:( FOR i TO 33 DO printf(($10r6d," "16r6d," "8r6dl$, BIN i, BIN i, BIN i)) OD )
http://rosettacode.org/wiki/Number_names
Number names
Task Show how to spell out a number in English. You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less). Support for inputs other than positive integers (like zero, negative integers, and floating-point numbers) is optional. Related task   Spelling of ordinal numbers.
#PL.2FM
PL/M
100H: BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS; EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT; PRINT: PROCEDURE (S); DECLARE S ADDRESS; CALL BDOS(9,S); END PRINT;   DECLARE FCB$NAME LITERALLY '5DH'; /* CP/M STORES COMMAND ARGUMENT HERE */   /* READ ASCII NUMBER */ READ$NUMBER: PROCEDURE (PTR) ADDRESS; DECLARE PTR ADDRESS, C BASED PTR BYTE, RSLT ADDRESS; RSLT = 0; DO WHILE '0' <= C AND C <= '9'; RSLT = RSLT * 10 + C - '0'; PTR = PTR + 1; END; RETURN RSLT; END;   /* SPELL 16-BIT NUMBER */ SPELL: PROCEDURE (N); DECLARE N ADDRESS; IF N=0 THEN DO; CALL PRINT(.'ZERO$'); RETURN; END; SMALL: PROCEDURE (N) ADDRESS; DECLARE N BYTE; DO CASE N; RETURN .'$'; RETURN .'ONE$'; RETURN .'TWO$'; RETURN .'THREE$'; RETURN .'FOUR$'; RETURN .'FIVE$'; RETURN .'SIX$'; RETURN .'SEVEN$'; RETURN .'EIGHT$'; RETURN .'NINE$'; RETURN .'TEN$'; RETURN .'ELEVEN$'; RETURN .'TWELVE$'; RETURN .'THIRTEEN$'; RETURN .'FOURTEEN$'; RETURN .'FIFTEEN$'; RETURN .'SIXTEEN$'; RETURN .'SEVENTEEN$'; RETURN .'EIGHTEEN$'; RETURN .'NINETEEN$'; END; END SMALL; TEENS: PROCEDURE (N) ADDRESS; DECLARE N BYTE; DO CASE N-2; RETURN .'TWENTY$'; RETURN .'THIRTY$'; RETURN .'FORTY$'; RETURN .'FIFTY$'; RETURN .'SIXTY$'; RETURN .'SEVENTY$'; RETURN .'EIGHTY$'; RETURN .'NINETY$'; END; END TEENS; LESS$100: PROCEDURE (N); DECLARE N BYTE; IF N >= 20 THEN DO; CALL PRINT(TEENS(N/10)); N = N MOD 10; IF N > 0 THEN CALL PRINT(.'-$'); END; CALL PRINT(SMALL(N)); END LESS$100; LESS$1000: PROCEDURE (N); DECLARE N ADDRESS; IF N >= 100 THEN DO; CALL LESS$100(N/100); CALL PRINT(.' HUNDRED$'); N = N MOD 100; IF N > 0 THEN CALL PRINT(.' $'); END; CALL LESS$100(N); END LESS$1000; IF N >= 1000 THEN DO; CALL LESS$1000(N/1000); CALL PRINT(.' THOUSAND$'); N = N MOD 1000; IF N > 0 THEN CALL PRINT(.' $'); END; CALL LESS$1000(N); END SPELL;   CALL SPELL(READ$NUMBER(FCB$NAME)); CALL EXIT; EOF
http://rosettacode.org/wiki/Number_reversal_game
Number reversal game
Task Given a jumbled list of the numbers   1   to   9   that are definitely   not   in ascending order. Show the list,   and then ask the player how many digits from the left to reverse. Reverse those digits,   then ask again,   until all the digits end up in ascending order. The score is the count of the reversals needed to attain the ascending order. Note: Assume the player's input does not need extra validation. Related tasks   Sorting algorithms/Pancake sort   Pancake sorting.   Topswops
#PureBasic
PureBasic
Dim MyList(9)   Declare is_list_sorted()   If OpenConsole() Define score, indata, i, txt$   For i=1 To 9 ;- Initiate the list MyList(i)=i Next While is_list_sorted() For i=1 To 9 ;- Do a Fisher–Yates shuffle Swap MyList(i), MyList(Random(i)+1) Next Wend   ;- Start the Game Repeat score+1 txt$=RSet(str(score), 3)+": " ;- Show current list For i=1 To 9 txt$+str(MyList(i))+" " Next Repeat ;- Get input & swap Print(txt$+"| How many numbers should be flipped? "): indata=Val(Input()) Until indata>=1 And indata<=9 ;- Verify the input For i=1 To (indata/2) Swap MyList(i),MyList(indata-i+1) Next Until is_list_sorted()   ;- Present result & wait for users input before closing down PrintN(#CRLF$+"You did it in "+str(score)+" moves") Print("Press ENTER to exit"): Input() CloseConsole() EndIf   Procedure is_list_sorted() Protected i Shared MyList() For i=1 To 9 If MyList(i)<>i ProcedureReturn #False EndIf Next ProcedureReturn #True EndProcedure
http://rosettacode.org/wiki/One-dimensional_cellular_automata
One-dimensional cellular automata
Assume an array of cells with an initial distribution of live and dead cells, and imaginary cells off the end of the array having fixed values. Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation. If, in the following table, a live cell is represented by 1 and a dead cell by 0 then to generate the value of the cell at a particular index in the array of cellular values you use the following table: 000 -> 0 # 001 -> 0 # 010 -> 0 # Dies without enough neighbours 011 -> 1 # Needs one neighbour to survive 100 -> 0 # 101 -> 1 # Two neighbours giving birth 110 -> 1 # Needs one neighbour to survive 111 -> 0 # Starved to death.
#Tcl
Tcl
proc evolve {a} { set new [list] for {set i 0} {$i < [llength $a]} {incr i} { lappend new [fate $a $i] } return $new }   proc fate {a i} { return [expr {[sum $a $i] == 2}] }   proc sum {a i} { set sum 0 set start [expr {$i - 1 < 0 ? 0 : $i - 1}] set end [expr {$i + 1 >= [llength $a] ? $i : $i + 1}] for {set j $start} {$j <= $end} {incr j} { incr sum [lindex $a $j] } return $sum }   proc print {a} { puts [string map {0 _ 1 #} [join $a ""]] }   proc parse {s} { return [split [string map {_ 0 # 1} $s] ""] }   set array [parse "_###_##_#_#_#_#__#__"] print $array while {[set new [evolve $array]] ne $array} { set array $new print $array }
http://rosettacode.org/wiki/Nonoblock
Nonoblock
Nonoblock is a chip off the old Nonogram puzzle. Given The number of cells in a row. The size of each, (space separated), connected block of cells to fit in the row, in left-to right order. Task show all possible positions. show the number of positions of the blocks for the following cases within the row. show all output on this page. use a "neat" diagram of the block positions. Enumerate the following configurations   5   cells   and   [2, 1]   blocks   5   cells   and   []   blocks   (no blocks)   10   cells   and   [8]   blocks   15   cells   and   [2, 3, 2, 3]   blocks   5   cells   and   [2, 3]   blocks   (should give some indication of this not being possible) Example Given a row of five cells and a block of two cells followed by a block of one cell - in that order, the example could be shown as: |_|_|_|_|_| # 5 cells and [2, 1] blocks And would expand to the following 3 possible rows of block positions: |A|A|_|B|_| |A|A|_|_|B| |_|A|A|_|B| Note how the sets of blocks are always separated by a space. Note also that it is not necessary for each block to have a separate letter. Output approximating This: |#|#|_|#|_| |#|#|_|_|#| |_|#|#|_|#| This would also work: ##.#. ##..# .##.# An algorithm Find the minimum space to the right that is needed to legally hold all but the leftmost block of cells (with a space between blocks remember). The leftmost cell can legitimately be placed in all positions from the LHS up to a RH position that allows enough room for the rest of the blocks. for each position of the LH block recursively compute the position of the rest of the blocks in the remaining space to the right of the current placement of the LH block. (This is the algorithm used in the Nonoblock#Python solution). Reference The blog post Nonogram puzzle solver (part 1) Inspired this task and donated its Nonoblock#Python solution.
#J
J
nonoblock=:4 :0 s=. 1+(1+x)-+/1+y pad=.1+(#~ s >+/"1)((1+#y)#s) #: i.s^1+#y ~.pad (_1}.1 }. ,. #&, 0 ,. 1 + i.@#@])"1]y,0 )   neat=: [: (#~ # $ 0 1"_)@": {&(' ',65}.a.)&.>
http://rosettacode.org/wiki/Non-transitive_dice
Non-transitive dice
Let our dice select numbers on their faces with equal probability, i.e. fair dice. Dice may have more or less than six faces. (The possibility of there being a 3D physical shape that has that many "faces" that allow them to be fair dice, is ignored for this task - a die with 3 or 33 defined sides is defined by the number of faces and the numbers on each face). Throwing dice will randomly select a face on each die with equal probability. To show which die of dice thrown multiple times is more likely to win over the others: calculate all possible combinations of different faces from each die Count how many times each die wins a combination Each combination is equally likely so the die with more winning face combinations is statistically more likely to win against the other dice. If two dice X and Y are thrown against each other then X likely to: win, lose, or break-even against Y can be shown as: X > Y, X < Y, or X = Y respectively. Example 1 If X is the three sided die with 1, 3, 6 on its faces and Y has 2, 3, 4 on its faces then the equal possibility outcomes from throwing both, and the winners is: X Y Winner = = ====== 1 2 Y 1 3 Y 1 4 Y 3 2 X 3 3 - 3 4 Y 6 2 X 6 3 X 6 4 X TOTAL WINS: X=4, Y=4 Both die will have the same statistical probability of winning, i.e.their comparison can be written as X = Y Transitivity In mathematics transitivity are rules like: if a op b and b op c then a op c If, for example, the op, (for operator), is the familiar less than, <, and it's applied to integers we get the familiar if a < b and b < c then a < c Non-transitive dice These are an ordered list of dice where the '>' operation between successive dice pairs applies but a comparison between the first and last of the list yields the opposite result, '<'. (Similarly '<' successive list comparisons with a final '>' between first and last is also non-transitive). Three dice S, T, U with appropriate face values could satisfy S < T, T < U and yet S > U To be non-transitive. Notes The order of numbers on the faces of a die is not relevant. For example, three faced die described with face numbers of 1, 2, 3 or 2, 1, 3 or any other permutation are equivalent. For the purposes of the task show only the permutation in lowest-first sorted order i.e. 1, 2, 3 (and remove any of its perms). A die can have more than one instance of the same number on its faces, e.g. 2, 3, 3, 4 Rotations: Any rotation of non-transitive dice from an answer is also an answer. You may optionally compute and show only one of each such rotation sets, ideally the first when sorted in a natural way. If this option is used then prominently state in the output that rotations of results are also solutions. Task ==== Find all the ordered lists of three non-transitive dice S, T, U of the form S < T, T < U and yet S > U; where the dice are selected from all four-faced die , (unique w.r.t the notes), possible by having selections from the integers one to four on any dies face. Solution can be found by generating all possble individual die then testing all possible permutations, (permutations are ordered), of three dice for non-transitivity. Optional stretch goal Find lists of four non-transitive dice selected from the same possible dice from the non-stretch goal. Show the results here, on this page. References The Most Powerful Dice - Numberphile Video. Nontransitive dice - Wikipedia.
#Factor
Factor
USING: grouping io kernel math math.combinatorics math.ranges prettyprint sequences ;   : possible-dice ( n -- seq ) [ [1,b] ] [ selections ] bi [ [ <= ] monotonic? ] filter ;   : cmp ( seq seq -- n ) [ - sgn ] cartesian-map concat sum ;   : non-transitive? ( seq -- ? ) [ 2 clump [ first2 cmp neg? ] all? ] [ [ last ] [ first ] bi cmp neg? and ] bi ;   : find-non-transitive ( #sides #dice -- seq ) [ possible-dice ] [ <k-permutations> ] bi* [ non-transitive? ] filter ;   ! Task "Number of eligible 4-sided dice: " write 4 possible-dice length . nl   "All ordered lists of 3 non-transitive dice with 4 sides:" print 4 3 find-non-transitive . nl   "All ordered lists of 4 non-transitive dice with 4 sides:" print 4 4 find-non-transitive .
http://rosettacode.org/wiki/Non-transitive_dice
Non-transitive dice
Let our dice select numbers on their faces with equal probability, i.e. fair dice. Dice may have more or less than six faces. (The possibility of there being a 3D physical shape that has that many "faces" that allow them to be fair dice, is ignored for this task - a die with 3 or 33 defined sides is defined by the number of faces and the numbers on each face). Throwing dice will randomly select a face on each die with equal probability. To show which die of dice thrown multiple times is more likely to win over the others: calculate all possible combinations of different faces from each die Count how many times each die wins a combination Each combination is equally likely so the die with more winning face combinations is statistically more likely to win against the other dice. If two dice X and Y are thrown against each other then X likely to: win, lose, or break-even against Y can be shown as: X > Y, X < Y, or X = Y respectively. Example 1 If X is the three sided die with 1, 3, 6 on its faces and Y has 2, 3, 4 on its faces then the equal possibility outcomes from throwing both, and the winners is: X Y Winner = = ====== 1 2 Y 1 3 Y 1 4 Y 3 2 X 3 3 - 3 4 Y 6 2 X 6 3 X 6 4 X TOTAL WINS: X=4, Y=4 Both die will have the same statistical probability of winning, i.e.their comparison can be written as X = Y Transitivity In mathematics transitivity are rules like: if a op b and b op c then a op c If, for example, the op, (for operator), is the familiar less than, <, and it's applied to integers we get the familiar if a < b and b < c then a < c Non-transitive dice These are an ordered list of dice where the '>' operation between successive dice pairs applies but a comparison between the first and last of the list yields the opposite result, '<'. (Similarly '<' successive list comparisons with a final '>' between first and last is also non-transitive). Three dice S, T, U with appropriate face values could satisfy S < T, T < U and yet S > U To be non-transitive. Notes The order of numbers on the faces of a die is not relevant. For example, three faced die described with face numbers of 1, 2, 3 or 2, 1, 3 or any other permutation are equivalent. For the purposes of the task show only the permutation in lowest-first sorted order i.e. 1, 2, 3 (and remove any of its perms). A die can have more than one instance of the same number on its faces, e.g. 2, 3, 3, 4 Rotations: Any rotation of non-transitive dice from an answer is also an answer. You may optionally compute and show only one of each such rotation sets, ideally the first when sorted in a natural way. If this option is used then prominently state in the output that rotations of results are also solutions. Task ==== Find all the ordered lists of three non-transitive dice S, T, U of the form S < T, T < U and yet S > U; where the dice are selected from all four-faced die , (unique w.r.t the notes), possible by having selections from the integers one to four on any dies face. Solution can be found by generating all possble individual die then testing all possible permutations, (permutations are ordered), of three dice for non-transitivity. Optional stretch goal Find lists of four non-transitive dice selected from the same possible dice from the non-stretch goal. Show the results here, on this page. References The Most Powerful Dice - Numberphile Video. Nontransitive dice - Wikipedia.
#Go
Go
package main   import ( "fmt" "sort" )   func fourFaceCombs() (res [][4]int) { found := make([]bool, 256) for i := 1; i <= 4; i++ { for j := 1; j <= 4; j++ { for k := 1; k <= 4; k++ { for l := 1; l <= 4; l++ { c := [4]int{i, j, k, l} sort.Ints(c[:]) key := 64*(c[0]-1) + 16*(c[1]-1) + 4*(c[2]-1) + (c[3] - 1) if !found[key] { found[key] = true res = append(res, c) } } } } } return }   func cmp(x, y [4]int) int { xw := 0 yw := 0 for i := 0; i < 4; i++ { for j := 0; j < 4; j++ { if x[i] > y[j] { xw++ } else if y[j] > x[i] { yw++ } } } if xw < yw { return -1 } else if xw > yw { return 1 } return 0 }   func findIntransitive3(cs [][4]int) (res [][3][4]int) { var c = len(cs) for i := 0; i < c; i++ { for j := 0; j < c; j++ { for k := 0; k < c; k++ { first := cmp(cs[i], cs[j]) if first == -1 { second := cmp(cs[j], cs[k]) if second == -1 { third := cmp(cs[i], cs[k]) if third == 1 { res = append(res, [3][4]int{cs[i], cs[j], cs[k]}) } } } } } } return }   func findIntransitive4(cs [][4]int) (res [][4][4]int) { c := len(cs) for i := 0; i < c; i++ { for j := 0; j < c; j++ { for k := 0; k < c; k++ { for l := 0; l < c; l++ { first := cmp(cs[i], cs[j]) if first == -1 { second := cmp(cs[j], cs[k]) if second == -1 { third := cmp(cs[k], cs[l]) if third == -1 { fourth := cmp(cs[i], cs[l]) if fourth == 1 { res = append(res, [4][4]int{cs[i], cs[j], cs[k], cs[l]}) } } } } } } } } return }   func main() { combs := fourFaceCombs() fmt.Println("Number of eligible 4-faced dice", len(combs)) it3 := findIntransitive3(combs) fmt.Printf("\n%d ordered lists of 3 non-transitive dice found, namely:\n", len(it3)) for _, a := range it3 { fmt.Println(a) } it4 := findIntransitive4(combs) fmt.Printf("\n%d ordered lists of 4 non-transitive dice found, namely:\n", len(it4)) for _, a := range it4 { fmt.Println(a) } }
http://rosettacode.org/wiki/Non-decimal_radices/Input
Non-decimal radices/Input
It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.) This task requires parsing of such a string (which may be assumed to contain nothing else) using the language's built-in facilities if possible. Parsing of decimal strings is required, parsing of other formats is optional but should be shown (i.e., if the language can parse in base-19 then that should be illustrated). The solutions may assume that the base of the number in the string is known. In particular, if your language has a facility to guess the base of a number by looking at a prefix (e.g. "0x" for hexadecimal) or other distinguishing syntax as it parses it, please show that. The reverse operation is in task Non-decimal radices/Output For general number base conversion, see Non-decimal radices/Convert.
#BBC_BASIC
BBC BASIC
REM VAL parses decimal strings: PRINT VAL("0") PRINT VAL("123456789") PRINT VAL("-987654321")   REM EVAL can be used to parse binary and hexadecimal strings: PRINT EVAL("%10101010") PRINT EVAL("%1111111111") PRINT EVAL("&ABCD") PRINT EVAL("&FFFFFFFF")
http://rosettacode.org/wiki/Non-decimal_radices/Input
Non-decimal radices/Input
It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.) This task requires parsing of such a string (which may be assumed to contain nothing else) using the language's built-in facilities if possible. Parsing of decimal strings is required, parsing of other formats is optional but should be shown (i.e., if the language can parse in base-19 then that should be illustrated). The solutions may assume that the base of the number in the string is known. In particular, if your language has a facility to guess the base of a number by looking at a prefix (e.g. "0x" for hexadecimal) or other distinguishing syntax as it parses it, please show that. The reverse operation is in task Non-decimal radices/Output For general number base conversion, see Non-decimal radices/Convert.
#C
C
#include <stdio.h>   int main() { int num;   sscanf("0123459", "%d", &num); printf("%d\n", num); /* prints 123459 */   sscanf("abcf123", "%x", &num); printf("%d\n", num); /* prints 180154659 */   sscanf("7651", "%o", &num); printf("%d\n", num); /* prints 4009 */   /* binary not supported */   return 0; }
http://rosettacode.org/wiki/Numerical_integration
Numerical integration
Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods: rectangular left right midpoint trapezium Simpson's composite Your functions should take in the upper and lower bounds (a and b), and the number of approximations to make in that range (n). Assume that your example already has a function that gives values for ƒ(x) . Simpson's method is defined by the following pseudo-code: Pseudocode: Simpson's method, composite procedure quad_simpson_composite(f, a, b, n) h := (b - a) / n sum1 := f(a + h/2) sum2 := 0 loop on i from 1 to (n - 1) sum1 := sum1 + f(a + h * i + h/2) sum2 := sum2 + f(a + h * i)   answer := (h / 6) * (f(a) + f(b) + 4*sum1 + 2*sum2) Demonstrate your function by showing the results for:   ƒ(x) = x3,       where   x   is     [0,1],       with           100 approximations.   The exact result is     0.25               (or 1/4)   ƒ(x) = 1/x,     where   x   is   [1,100],     with        1,000 approximations.   The exact result is     4.605170+     (natural log of 100)   ƒ(x) = x,         where   x   is   [0,5000],   with 5,000,000 approximations.   The exact result is   12,500,000   ƒ(x) = x,         where   x   is   [0,6000],   with 6,000,000 approximations.   The exact result is   18,000,000 See also   Active object for integrating a function of real time.   Special:PrefixIndex/Numerical integration for other integration methods.
#zkl
zkl
fcn integrate(F,f,a,b,steps){ h:=(b - a) / steps; h*(0).reduce(steps,'wrap(s,i){ F(f, h*i + a, h) + s },0.0); }   fcn rectangularLeft(f,x) { f(x) } fcn rectangularMiddle(f,x,h){ f(x+h/2) } fcn rectangularRight(f,x,h) { f(x+h) } fcn trapezium(f,x,h) { (f(x) + f(x+h))/2 } fcn simpson(f,x,h) { (f(x) + 4.0*f(x+h/2) + f(x+h))/6 }   args:=T( T(fcn(x){ x.pow(3) }, 0.0, 1.0, 10), T(fcn(x){ 1.0 / x }, 1.0, 100.0, 1000), T(fcn(x){ x }, 0.0, 5000.0, 0d5_000_000), T(fcn(x){ x }, 0.0, 6000.0, 0d6_000_000) ); fs:=T(rectangularLeft,rectangularMiddle,rectangularRight, trapezium,simpson); names:=fs.pump(List,"name",'+(":"),"%-18s".fmt);   foreach a in (args){ names.zipWith('wrap(nm,f){ "%s %f".fmt(nm,integrate(f,a.xplode())).println() }, fs); println(); }
http://rosettacode.org/wiki/Non-decimal_radices/Output
Non-decimal radices/Output
Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal. Task Print a small range of integers in some different bases, as supported by standard routines of your programming language. Note This is distinct from Number base conversion as a user-defined conversion function is not asked for.) The reverse operation is Common number base parsing.
#ALGOL_W
ALGOL W
begin  % print some numbers in hex % for i := 0 until 20 do write( intbase16( i ) ) end.
http://rosettacode.org/wiki/Non-decimal_radices/Output
Non-decimal radices/Output
Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal. Task Print a small range of integers in some different bases, as supported by standard routines of your programming language. Note This is distinct from Number base conversion as a user-defined conversion function is not asked for.) The reverse operation is Common number base parsing.
#AutoHotkey
AutoHotkey
MsgBox % BC("FF",16,3) ; -> 100110 in base 3 = FF in hex = 256 in base 10   BC(NumStr,InputBase=8,OutputBase=10) { Static S = 12345678901234567890123456789012345678901234567890123456789012345 DllCall("msvcrt\_i64toa","Int64",DllCall("msvcrt\_strtoui64","Str",NumStr,"Uint",0,"UInt",InputBase,"CDECLInt64"),"Str",S,"UInt",OutputBase,"CDECL") Return S }
http://rosettacode.org/wiki/Number_names
Number names
Task Show how to spell out a number in English. You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less). Support for inputs other than positive integers (like zero, negative integers, and floating-point numbers) is optional. Related task   Spelling of ordinal numbers.
#PowerBASIC
PowerBASIC
FUNCTION int2Text (number AS QUAD) AS STRING IF 0 = number THEN FUNCTION = "zero" EXIT FUNCTION END IF   DIM num AS QUAD, outP AS STRING, unit AS LONG DIM tmpLng1 AS QUAD   DIM small(1 TO 19) AS STRING, tens(7) AS STRING, big(5) AS STRING   DIM tmpInt AS LONG, dcnt AS LONG   ARRAY ASSIGN small() = "one", "two", "three", "four", "five", "six", _ "seven", "eight", "nine", "ten", "eleven", _ "twelve", "thirteen", "fourteen", "fifteen", _ "sixteen", "seventeen", "eighteen", "nineteen" ARRAY ASSIGN tens() = "twenty", "thirty", "forty", "fifty", "sixty", _ "seventy", "eighty", "ninety" ARRAY ASSIGN big() = "thousand", "million", "billion", "trillion", _ "quadrillion", "quintillion"   num = ABS(number)   DO tmpLng1 = num MOD 100 SELECT CASE tmpLng1 CASE 1 TO 19 outP = small(tmpLng1) + " " + outP CASE 20 TO 99 SELECT CASE tmpLng1 MOD 10 CASE 0 outP = tens((tmpLng1 \ 10) - 2) + " " + outP CASE ELSE outP = tens((tmpLng1 \ 10) - 2) + "-" + small(tmpLng1 MOD 10) + " " + outP END SELECT END SELECT   tmpLng1 = (num MOD 1000) \ 100 IF tmpLng1 THEN outP = small(tmpLng1) + " hundred " + outP END IF   num = num \ 1000 IF num < 1 THEN EXIT DO   tmpLng1 = num MOD 1000 IF tmpLng1 THEN outP = big(unit) + " " + outP   unit = unit + 1 LOOP   IF number < 0 THEN outP = "negative " + outP   FUNCTION = RTRIM$(outP) END FUNCTION     FUNCTION PBMAIN () AS LONG DIM n AS QUAD   #IF %DEF(%PB_CC32) INPUT "Gimme a number! ", n #ELSE n = VAL(INPUTBOX$("Gimme a number!", "Now!")) #ENDIF  ? int2Text(n) END FUNCTION
http://rosettacode.org/wiki/Number_reversal_game
Number reversal game
Task Given a jumbled list of the numbers   1   to   9   that are definitely   not   in ascending order. Show the list,   and then ask the player how many digits from the left to reverse. Reverse those digits,   then ask again,   until all the digits end up in ascending order. The score is the count of the reversals needed to attain the ascending order. Note: Assume the player's input does not need extra validation. Related tasks   Sorting algorithms/Pancake sort   Pancake sorting.   Topswops
#Python
Python
''' number reversal game Given a jumbled list of the numbers 1 to 9 Show the list. Ask the player how many digits from the left to reverse. Reverse those digits then ask again. until all the digits end up in ascending order.   '''   import random   print(__doc__) data, trials = list('123456789'), 0 while data == sorted(data): random.shuffle(data) while data != sorted(data): trials += 1 flip = int(input('#%2i: LIST: %r Flip how many?: ' % (trials, ' '.join(data)))) data[:flip] = reversed(data[:flip])   print('\nYou took %2i attempts to put the digits in order!' % trials)
http://rosettacode.org/wiki/One-dimensional_cellular_automata
One-dimensional cellular automata
Assume an array of cells with an initial distribution of live and dead cells, and imaginary cells off the end of the array having fixed values. Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation. If, in the following table, a live cell is represented by 1 and a dead cell by 0 then to generate the value of the cell at a particular index in the array of cellular values you use the following table: 000 -> 0 # 001 -> 0 # 010 -> 0 # Dies without enough neighbours 011 -> 1 # Needs one neighbour to survive 100 -> 0 # 101 -> 1 # Two neighbours giving birth 110 -> 1 # Needs one neighbour to survive 111 -> 0 # Starved to death.
#Ursala
Ursala
#import std #import nat   rule = -$<0,0,0,&,0,&,&,0>@rSS zipp0*ziD iota8   step = rule*+ swin3+ :/0+ --<0>   evolve "n" = @iNC ~&x+ rep"n" ^C/step@h ~&   #show+   example = ~&?(`#!,`.!)** evolve10 <0,&,&,&,0,&,&,0,&,0,&,0,&,0,0,&,0,0>
http://rosettacode.org/wiki/Nonoblock
Nonoblock
Nonoblock is a chip off the old Nonogram puzzle. Given The number of cells in a row. The size of each, (space separated), connected block of cells to fit in the row, in left-to right order. Task show all possible positions. show the number of positions of the blocks for the following cases within the row. show all output on this page. use a "neat" diagram of the block positions. Enumerate the following configurations   5   cells   and   [2, 1]   blocks   5   cells   and   []   blocks   (no blocks)   10   cells   and   [8]   blocks   15   cells   and   [2, 3, 2, 3]   blocks   5   cells   and   [2, 3]   blocks   (should give some indication of this not being possible) Example Given a row of five cells and a block of two cells followed by a block of one cell - in that order, the example could be shown as: |_|_|_|_|_| # 5 cells and [2, 1] blocks And would expand to the following 3 possible rows of block positions: |A|A|_|B|_| |A|A|_|_|B| |_|A|A|_|B| Note how the sets of blocks are always separated by a space. Note also that it is not necessary for each block to have a separate letter. Output approximating This: |#|#|_|#|_| |#|#|_|_|#| |_|#|#|_|#| This would also work: ##.#. ##..# .##.# An algorithm Find the minimum space to the right that is needed to legally hold all but the leftmost block of cells (with a space between blocks remember). The leftmost cell can legitimately be placed in all positions from the LHS up to a RH position that allows enough room for the rest of the blocks. for each position of the LH block recursively compute the position of the rest of the blocks in the remaining space to the right of the current placement of the LH block. (This is the algorithm used in the Nonoblock#Python solution). Reference The blog post Nonogram puzzle solver (part 1) Inspired this task and donated its Nonoblock#Python solution.
#Java
Java
import java.util.*; import static java.util.Arrays.stream; import static java.util.stream.Collectors.toList;   public class Nonoblock {   public static void main(String[] args) { printBlock("21", 5); printBlock("", 5); printBlock("8", 10); printBlock("2323", 15); printBlock("23", 5); }   static void printBlock(String data, int len) { int sumChars = data.chars().map(c -> Character.digit(c, 10)).sum(); String[] a = data.split("");   System.out.printf("%nblocks %s, cells %s%n", Arrays.toString(a), len); if (len - sumChars <= 0) { System.out.println("No solution"); return; }   List<String> prep = stream(a).filter(x -> !"".equals(x)) .map(x -> repeat(Character.digit(x.charAt(0), 10), "1")) .collect(toList());   for (String r : genSequence(prep, len - sumChars + 1)) System.out.println(r.substring(1)); }   // permutation generator, translated from Python via D static List<String> genSequence(List<String> ones, int numZeros) { if (ones.isEmpty()) return Arrays.asList(repeat(numZeros, "0"));   List<String> result = new ArrayList<>(); for (int x = 1; x < numZeros - ones.size() + 2; x++) { List<String> skipOne = ones.stream().skip(1).collect(toList()); for (String tail : genSequence(skipOne, numZeros - x)) result.add(repeat(x, "0") + ones.get(0) + tail); } return result; }   static String repeat(int n, String s) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < n; i++) sb.append(s); return sb.toString(); } }
http://rosettacode.org/wiki/Non-transitive_dice
Non-transitive dice
Let our dice select numbers on their faces with equal probability, i.e. fair dice. Dice may have more or less than six faces. (The possibility of there being a 3D physical shape that has that many "faces" that allow them to be fair dice, is ignored for this task - a die with 3 or 33 defined sides is defined by the number of faces and the numbers on each face). Throwing dice will randomly select a face on each die with equal probability. To show which die of dice thrown multiple times is more likely to win over the others: calculate all possible combinations of different faces from each die Count how many times each die wins a combination Each combination is equally likely so the die with more winning face combinations is statistically more likely to win against the other dice. If two dice X and Y are thrown against each other then X likely to: win, lose, or break-even against Y can be shown as: X > Y, X < Y, or X = Y respectively. Example 1 If X is the three sided die with 1, 3, 6 on its faces and Y has 2, 3, 4 on its faces then the equal possibility outcomes from throwing both, and the winners is: X Y Winner = = ====== 1 2 Y 1 3 Y 1 4 Y 3 2 X 3 3 - 3 4 Y 6 2 X 6 3 X 6 4 X TOTAL WINS: X=4, Y=4 Both die will have the same statistical probability of winning, i.e.their comparison can be written as X = Y Transitivity In mathematics transitivity are rules like: if a op b and b op c then a op c If, for example, the op, (for operator), is the familiar less than, <, and it's applied to integers we get the familiar if a < b and b < c then a < c Non-transitive dice These are an ordered list of dice where the '>' operation between successive dice pairs applies but a comparison between the first and last of the list yields the opposite result, '<'. (Similarly '<' successive list comparisons with a final '>' between first and last is also non-transitive). Three dice S, T, U with appropriate face values could satisfy S < T, T < U and yet S > U To be non-transitive. Notes The order of numbers on the faces of a die is not relevant. For example, three faced die described with face numbers of 1, 2, 3 or 2, 1, 3 or any other permutation are equivalent. For the purposes of the task show only the permutation in lowest-first sorted order i.e. 1, 2, 3 (and remove any of its perms). A die can have more than one instance of the same number on its faces, e.g. 2, 3, 3, 4 Rotations: Any rotation of non-transitive dice from an answer is also an answer. You may optionally compute and show only one of each such rotation sets, ideally the first when sorted in a natural way. If this option is used then prominently state in the output that rotations of results are also solutions. Task ==== Find all the ordered lists of three non-transitive dice S, T, U of the form S < T, T < U and yet S > U; where the dice are selected from all four-faced die , (unique w.r.t the notes), possible by having selections from the integers one to four on any dies face. Solution can be found by generating all possble individual die then testing all possible permutations, (permutations are ordered), of three dice for non-transitivity. Optional stretch goal Find lists of four non-transitive dice selected from the same possible dice from the non-stretch goal. Show the results here, on this page. References The Most Powerful Dice - Numberphile Video. Nontransitive dice - Wikipedia.
#Haskell
Haskell
{-# language LambdaCase #-} import Data.List import Control.Monad   newtype Dice = Dice [Int]   instance Show Dice where show (Dice s) = "(" ++ unwords (show <$> s) ++ ")"   instance Eq Dice where d1 == d2 = d1 `compare` d2 == EQ   instance Ord Dice where Dice d1 `compare` Dice d2 = (add $ compare <$> d1 <*> d2) `compare` 0 where add = sum . map (\case {LT -> -1; EQ -> 0; GT -> 1})   dices n = Dice <$> (nub $ sort <$> replicateM n [1..n])   nonTrans dice = filter (\x -> last x < head x) . go where go 0 = [] go 1 = sequence [dice] go n = do (a:as) <- go (n-1) b <- filter (< a) dice return (b:a:as)
http://rosettacode.org/wiki/Non-decimal_radices/Input
Non-decimal radices/Input
It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.) This task requires parsing of such a string (which may be assumed to contain nothing else) using the language's built-in facilities if possible. Parsing of decimal strings is required, parsing of other formats is optional but should be shown (i.e., if the language can parse in base-19 then that should be illustrated). The solutions may assume that the base of the number in the string is known. In particular, if your language has a facility to guess the base of a number by looking at a prefix (e.g. "0x" for hexadecimal) or other distinguishing syntax as it parses it, please show that. The reverse operation is in task Non-decimal radices/Output For general number base conversion, see Non-decimal radices/Convert.
#C.23
C#
using System;   class Program { static void Main() { var value = "100"; var fromBases = new[] { 2, 8, 10, 16 }; var toBase = 10; foreach (var fromBase in fromBases) { Console.WriteLine("{0} in base {1} is {2} in base {3}", value, fromBase, Convert.ToInt32(value, fromBase), toBase); } } }