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/Flipping_bits_game
Flipping bits game
The game Given an   N×N   square array of zeroes or ones in an initial configuration,   and a target configuration of zeroes and ones. The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered columns at once   (as one move). In an inversion.   any  1  becomes  0,   and any  0  becomes  1  for that whole row or column. Task Create a program to score for the Flipping bits game. The game should create an original random target configuration and a starting configuration. Ensure that the starting position is never the target position. The target position must be guaranteed as reachable from the starting position.   (One possible way to do this is to generate the start position by legal flips from a random target position.   The flips will always be reversible back to the target from the given start position). The number of moves taken so far should be shown. Show an example of a short game here, on this page, for a   3×3   array of bits.
#Perl
Perl
#!perl use strict; use warnings qw(FATAL all);   my $n = shift(@ARGV) || 4; if( $n < 2 or $n > 26 ) { die "You can't play a size $n game\n"; }   my $n2 = $n*$n;   my (@rows, @cols); for my $i ( 0 .. $n-1 ) { my $row = my $col = "\x00" x $n2; vec($row, $i * $n + $_, 8) ^= 1 for 0 .. $n-1; vec($col, $i + $_ * $n, 8) ^= 1 for 0 .. $n-1; push @rows, $row; push @cols, $col; }   my $goal = "0" x $n2; int(rand(2)) or (vec($goal, $_, 8) ^= 1) for 0 .. $n2-1; my $start = $goal; { for(@rows, @cols) { $start ^= $_ if int rand 2; } redo if $start eq $goal; }   my @letters = ('a'..'z')[0..$n-1]; sub to_strings { my $board = shift; my @result = join(" ", " ", @letters); for( 0 .. $n-1 ) { my $res = sprintf("%2d ",$_+1); $res .= join " ", split //, substr $board, $_*$n, $n; push @result, $res; } \@result; }   my $fmt; my ($stext, $etext) = ("Starting board", "Ending board"); my $re = join "|", reverse 1 .. $n, @letters; my $moves_so_far = 0; while( 1 ) { my ($from, $to) = (to_strings($start), to_strings($goal)); unless( $fmt ) { my $len = length $from->[0]; $len = length($stext) if $len < length $stext; $fmt = join($len, "%", "s%", "s\n"); } printf $fmt, $stext, $etext; printf $fmt, $from->[$_], $to->[$_] for 0 .. $n; last if $start eq $goal; INPUT_LOOP: { printf "Move #%s: Type one or more row numbers and/or column letters: ", $moves_so_far+1; my $input = <>; die unless defined $input; my $did_one; for( $input =~ /($re)/gi ) { $did_one = 1; if( /\d/ ) { $start ^= $rows[$_-1]; } else { $_ = ord(lc) - ord('a'); $start ^= $cols[$_]; } ++$moves_so_far; } redo INPUT_LOOP unless $did_one; } } print "You won after $moves_so_far moves.\n";
http://rosettacode.org/wiki/First_power_of_2_that_has_leading_decimal_digits_of_12
First power of 2 that has leading decimal digits of 12
(This task is taken from a   Project Euler   problem.) (All numbers herein are expressed in base ten.) 27   =   128   and   7   is the first power of   2   whose leading decimal digits are   12. The next power of   2   whose leading decimal digits are   12   is   80, 280   =   1208925819614629174706176. Define     p(L,n)     to be the nth-smallest value of   j   such that the base ten representation of   2j   begins with the digits of   L . So p(12, 1) = 7 and p(12, 2) = 80 You are also given that: p(123, 45)   =   12710 Task   find:   p(12, 1)   p(12, 2)   p(123, 45)   p(123, 12345)   p(123, 678910)   display the results here, on this page.
#Perl
Perl
use strict; use warnings; use feature 'say'; use feature 'state';   use POSIX qw(fmod); use Perl6::GatherTake;   use constant ln2ln10 => log(2) / log(10);   sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r }   sub ordinal_digit { my($d) = $_[0] =~ /(.)$/; $d eq '1' ? 'st' : $d eq '2' ? 'nd' : $d eq '3' ? 'rd' : 'th' }   sub startswith12 { my($nth) = @_; state $i = 0; state $n = 0; while (1) { next unless '1.2' eq substr(( 10 ** fmod(++$i * ln2ln10, 1) ), 0, 3); return $i if ++$n eq $nth; } }   sub startswith123 { my $pre = '1.23'; my ($this, $count) = (0, 0);   gather { while (1) { if ($this == 196) { $this = 289; $this = 485 unless $pre eq substr(( 10 ** fmod(($count+$this) * ln2ln10, 1) ), 0, 4); } elsif ($this == 485) { $this = 196; $this = 485 unless $pre eq substr(( 10 ** fmod(($count+$this) * ln2ln10, 1) ), 0, 4); } elsif ($this == 289) { $this = 196 } elsif ($this == 90) { $this = 289 } elsif ($this == 0) { $this = 90; } take $count += $this; } } }   my $start_123 = startswith123(); # lazy list   sub p { my($prefix,$nth) = @_; $prefix eq '12' ? startswith12($nth) : $start_123->[$nth-1]; }   for ([12, 1], [12, 2], [123, 45], [123, 12345], [123, 678910]) { my($prefix,$nth) = @$_; printf "%-15s %9s power of two (2^n) that starts with %5s is at n = %s\n", "p($prefix, $nth):", comma($nth) . ordinal_digit($nth), "'$prefix'", comma p($prefix, $nth); }
http://rosettacode.org/wiki/First-class_functions/Use_numbers_analogously
First-class functions/Use numbers analogously
In First-class functions, a language is showing how its manipulation of functions is similar to its manipulation of other types. This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers. Write a program to create an ordered collection of a mixture of literally typed and expressions producing a real number, together with another ordered collection of their multiplicative inverses. Try and use the following pseudo-code to generate the numbers for the ordered collections: x = 2.0 xi = 0.5 y = 4.0 yi = 0.25 z = x + y zi = 1.0 / ( x + y ) Create a function multiplier, that given two numbers as arguments returns a function that when called with one argument, returns the result of multiplying the two arguments to the call to multiplier that created it and the argument in the call: new_function = multiplier(n1,n2) # where new_function(m) returns the result of n1 * n2 * m Applying the multiplier of a number and its inverse from the two ordered collections of numbers in pairs, show that the result in each case is one. Compare and contrast the resultant program with the corresponding entry in First-class functions. They should be close. To paraphrase the task description: Do what was done before, but with numbers rather than functions
#Objeck
Objeck
use Collection.Generic;   class FirstClass { function : Main(args : String[]) ~ Nil { x := 2.0; xi := 0.5; y := 4.0; yi := 0.25; z := x + y; zi := 1.0 / (x + y);   numlist := CompareVector->New()<FloatHolder>; numlist->AddBack(x); numlist->AddBack(y); numlist->AddBack(z);   numlisti := Vector->New()<FloatHolder>; numlisti->AddBack(xi); numlisti->AddBack(yi); numlisti->AddBack(zi);   each(i : numlist) { v := numlist->Get(i); vi := numlisti->Get(i); mult := Multiplier(v, vi); r := mult(0.5); "{$v} * {$vi} * 0.5 = {$r}"->PrintLine(); }; }   function : Multiplier(a : FloatHolder, b : FloatHolder) ~ (FloatHolder) ~ FloatHolder { return \(FloatHolder) ~ FloatHolder : (c) => a * b * c; } }  
http://rosettacode.org/wiki/Flow-control_structures
Flow-control structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task Document common flow-control structures. One common example of a flow-control structure is the   goto   construct. Note that   Conditional Structures   and   Loop Structures   have their own articles/categories. Related tasks   Conditional Structures   Loop Structures
#PHP
PHP
<?php goto a; echo 'Foo';   a: echo 'Bar'; ?>
http://rosettacode.org/wiki/Flow-control_structures
Flow-control structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task Document common flow-control structures. One common example of a flow-control structure is the   goto   construct. Note that   Conditional Structures   and   Loop Structures   have their own articles/categories. Related tasks   Conditional Structures   Loop Structures
#PicoLisp
PicoLisp
  LEAVE The LEAVE statement terminates execution of a loop. Execution resumes at the next statement after the loop. ITERATE The ITERATE statement causes the next iteration of the loop to commence. Any statements between ITERATE and the end of the loop are not executed. STOP Terminates execution of either a task or the entire program. SIGNAL FINISH Terminates execution of a program in a nice way. SIGNAL statement SIGNAL <condition> raises the named condition. The condition may be one of the hardware or software conditions such as OVERFLOW, UNDERFLOW, ZERODIVIDE, SUBSCRIPTRANGE, STRINGRANGE, etc, or a user-defined condition. CALL The CALL statement causes control to transfer to the named subroutine. SELECT The SELECT statement permits the execution of just one of a list of statements (or groups of statements). It is sort of like a computed GOTO. GO TO The GO TO statement causes control to be transferred to the named statement. It can also be used to transfer control to any one of an array of labelled statements. (This form is superseded by SELECT, above.) [GO TO can also be spelled as GOTO].  
http://rosettacode.org/wiki/Floyd%27s_triangle
Floyd's triangle
Floyd's triangle   lists the natural numbers in a right triangle aligned to the left where the first row is   1     (unity) successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above. The first few lines of a Floyd triangle looks like this: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Task Write a program to generate and display here the first   n   lines of a Floyd triangle. (Use   n=5   and   n=14   rows). Ensure that when displayed in a mono-space font, the numbers line up in vertical columns as shown and that only one space separates numbers of the last row.
#ERRE
ERRE
  PROGRAM FLOYD   ! ! for rosettacode.org !   BEGIN N=14 NUM=1 LAST=(N^2-N+2) DIV 2 FOR ROW=1 TO N DO FOR J=1 TO ROW DO US$=STRING$(LEN(STR$(LAST-1+J))-1,"#") WRITE(US$;NUM;) PRINT(" ";) NUM+=1 END FOR PRINT END FOR END PROGRAM  
http://rosettacode.org/wiki/Floyd%27s_triangle
Floyd's triangle
Floyd's triangle   lists the natural numbers in a right triangle aligned to the left where the first row is   1     (unity) successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above. The first few lines of a Floyd triangle looks like this: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Task Write a program to generate and display here the first   n   lines of a Floyd triangle. (Use   n=5   and   n=14   rows). Ensure that when displayed in a mono-space font, the numbers line up in vertical columns as shown and that only one space separates numbers of the last row.
#Excel
Excel
floydTriangle =LAMBDA(n, IF(0 < n, LET( ixs, SEQUENCE( n, n, 0, 1 ), x, MOD(ixs, n), y, QUOTIENT(ixs, n),   IF(x > y, "", x + 1 + QUOTIENT( y * (1 + y), 2 ) ) ), "" ) )
http://rosettacode.org/wiki/Floyd-Warshall_algorithm
Floyd-Warshall algorithm
The Floyd–Warshall algorithm is an algorithm for finding shortest paths in a weighted graph with positive or negative edge weights. Task Find the lengths of the shortest paths between all pairs of vertices of the given directed graph. Your code may assume that the input has already been checked for loops, parallel edges and negative cycles. Print the pair, the distance and (optionally) the path. Example pair dist path 1 -> 2 -1 1 -> 3 -> 4 -> 2 1 -> 3 -2 1 -> 3 1 -> 4 0 1 -> 3 -> 4 2 -> 1 4 2 -> 1 2 -> 3 2 2 -> 1 -> 3 2 -> 4 4 2 -> 1 -> 3 -> 4 3 -> 1 5 3 -> 4 -> 2 -> 1 3 -> 2 1 3 -> 4 -> 2 3 -> 4 2 3 -> 4 4 -> 1 3 4 -> 2 -> 1 4 -> 2 -1 4 -> 2 4 -> 3 1 4 -> 2 -> 1 -> 3 See also Floyd-Warshall Algorithm - step by step guide (youtube)
#Nim
Nim
import sequtils, strformat   type Weight = tuple[src, dest, value: int] Weights = seq[Weight]     #---------------------------------------------------------------------------------------------------   proc printResult(dist: seq[seq[float]]; next: seq[seq[int]]) =   echo "pair dist path" for i in 0..next.high: for j in 0..next.high: if i != j: var u = i + 1 let v = j + 1 var path = fmt"{u} -> {v} {dist[i][j].toInt:2d} {u}" while true: u = next[u-1][v-1] path &= fmt" -> {u}" if u == v: break echo path     #---------------------------------------------------------------------------------------------------   proc floydWarshall(weights: Weights; numVertices: Positive) =   var dist = repeat(repeat(Inf, numVertices), numVertices) for w in weights: dist[w.src - 1][w.dest - 1] = w.value.toFloat   var next = repeat(newSeq[int](numVertices), numVertices) for i in 0..<numVertices: for j in 0..<numVertices: if i != j: next[i][j] = j + 1   for k in 0..<numVertices: for i in 0..<numVertices: for j in 0..<numVertices: if dist[i][j] > dist[i][k] + dist[k][j]: dist[i][j] = dist[i][k] + dist[k][j] next[i][j] = next[i][k]   printResult(dist, next)     #———————————————————————————————————————————————————————————————————————————————————————————————————   let weights: Weights = @[(1, 3, -2), (2, 1, 4), (2, 3, 3), (3, 4, 2), (4, 2, -1)] let numVertices = 4   floydWarshall(weights, numVertices)
http://rosettacode.org/wiki/Function_definition
Function definition
A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract from showing how functions are created and values returned). Related task   Function prototype
#SNUSP
SNUSP
+1>++2=@\=>+++3=@\==@\=.=# prints '6' | | \=itoa=@@@+@+++++# \=======!\==!/===?\<# \>+<-/
http://rosettacode.org/wiki/Function_definition
Function definition
A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract from showing how functions are created and values returned). Related task   Function prototype
#SPARK
SPARK
package Functions is function Multiply (A, B : Integer) return Integer; --# pre A * B in Integer; -- See note below --# return A * B; -- Implies commutativity on Multiply arguments end Functions;
http://rosettacode.org/wiki/Forward_difference
Forward difference
Task Provide code that produces a list of numbers which is the   nth  order forward difference, given a non-negative integer (specifying the order) and a list of numbers. The first-order forward difference of a list of numbers   A   is a new list   B,   where   Bn = An+1 - An. List   B   should have one fewer element as a result. The second-order forward difference of   A   will be: tdefmodule Diff do def forward(arr,i\\1) do forward(arr,[],i) end def forward([_|[]],diffs,i) do if i == 1 do IO.inspect diffs else forward(diffs,[],i-1) end end def forward([val1|[val2|vals]],diffs,i) do forward([val2|vals],diffs++[val2-val1],i) end end The same as the first-order forward difference of   B. That new list will have two fewer elements than   A   and one less than   B. The goal of this task is to repeat this process up to the desired order. For a more formal description, see the related   Mathworld article. Algorithmic options Iterate through all previous forward differences and re-calculate a new array each time. Use this formula (from Wikipedia): Δ n [ f ] ( x ) = ∑ k = 0 n ( n k ) ( − 1 ) n − k f ( x + k ) {\displaystyle \Delta ^{n}[f](x)=\sum _{k=0}^{n}{n \choose k}(-1)^{n-k}f(x+k)} (Pascal's Triangle   may be useful for this option.)
#PHP
PHP
<?php   function forwardDiff($anArray, $times = 1) { if ($times <= 0) { return $anArray; } for ($accumilation = array(), $i = 1, $j = count($anArray); $i < $j; ++$i) { $accumilation[] = $anArray[$i] - $anArray[$i - 1]; } if ($times === 1) { return $accumilation; } return forwardDiff($accumilation, $times - 1); }   class ForwardDiffExample extends PweExample {   function _should_run_empty_array_for_single_elem() { $expected = array($this->rand()->int()); $this->spec(forwardDiff($expected))->shouldEqual(array()); }   function _should_give_diff_of_two_elem_as_single_elem() { $twoNums = array($this->rand()->int(), $this->rand()->int()); $expected = array($twoNums[1] - $twoNums[0]); $this->spec(forwardDiff($twoNums))->shouldEqual($expected); }   function _should_compute_correct_forward_diff_for_longer_arrays() { $diffInput = array(10, 2, 9, 6, 5); $expected = array(-8, 7, -3, -1); $this->spec(forwardDiff($diffInput))->shouldEqual($expected); }   function _should_apply_more_than_once_if_specified() { $diffInput = array(4, 6, 9, 3, 4); $expectedAfter1 = array(2, 3, -6, 1); $expectedAfter2 = array(1, -9, 7); $this->spec(forwardDiff($diffInput, 1))->shouldEqual($expectedAfter1); $this->spec(forwardDiff($diffInput, 2))->shouldEqual($expectedAfter2); }   function _should_return_array_unaltered_if_no_times() { $this->spec(forwardDiff($expected = array(1,2,3), 0))->shouldEqual($expected); }   }
http://rosettacode.org/wiki/Formatted_numeric_output
Formatted numeric output
Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
#SQL
SQL
DECLARE @n INT SELECT @n=123 SELECT SUBSTRING(CONVERT(CHAR(5), 10000+@n),2,4) AS FourDigits   SET @n=5 print "TwoDigits: " + SUBSTRING(CONVERT(CHAR(3), 100+@n),2,2) --Output: 05
http://rosettacode.org/wiki/Formatted_numeric_output
Formatted numeric output
Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
#Standard_ML
Standard ML
print (StringCvt.padLeft #"0" 9 (Real.fmt (StringCvt.FIX (SOME 3)) 7.125) ^ "\n")
http://rosettacode.org/wiki/Four_bit_adder
Four bit adder
Task "Simulate" a four-bit adder. This design can be realized using four 1-bit full adders. Each of these 1-bit full adders can be built with two half adders and an   or   gate. ; Finally a half adder can be made using an   xor   gate and an   and   gate. The   xor   gate can be made using two   nots,   two   ands   and one   or. Not,   or   and   and,   the only allowed "gates" for the task, can be "imitated" by using the bitwise operators of your language. If there is not a bit type in your language, to be sure that the   not   does not "invert" all the other bits of the basic type   (e.g. a byte)   we are not interested in,   you can use an extra   nand   (and   then   not)   with the constant   1   on one input. Instead of optimizing and reducing the number of gates used for the final 4-bit adder,   build it in the most straightforward way,   connecting the other "constructive blocks",   in turn made of "simpler" and "smaller" ones. Schematics of the "constructive blocks" (Xor gate with ANDs, ORs and NOTs)            (A half adder)                   (A full adder)                             (A 4-bit adder)         Solutions should try to be as descriptive as possible, making it as easy as possible to identify "connections" between higher-order "blocks". It is not mandatory to replicate the syntax of higher-order blocks in the atomic "gate" blocks, i.e. basic "gate" operations can be performed as usual bitwise operations, or they can be "wrapped" in a block in order to expose the same syntax of higher-order blocks, at implementers' choice. To test the implementation, show the sum of two four-bit numbers (in binary).
#Prolog
Prolog
% binary 4 bit adder chip simulation   b_not(in(hi), out(lo)) :- !. % not(1) = 0 b_not(in(lo), out(hi)). % not(0) = 1   b_and(in(hi,hi), out(hi)) :- !. % and(1,1) = 1 b_and(in(_,_), out(lo)). % and(anything else) = 0   b_or(in(hi,_), out(hi)) :- !. % or(1,any) = 1 b_or(in(_,hi), out(hi)) :- !. % or(any,1) = 1 b_or(in(_,_), out(lo)). % or(anything else) = 0   b_xor(in(A,B), out(O)) :- b_not(in(A), out(NotA)), b_not(in(B), out(NotB)), b_and(in(A,NotB), out(P)), b_and(in(NotA,B), out(Q)), b_or(in(P,Q), out(O)).   b_half_adder(in(A,B), s(S), c(C)) :- b_xor(in(A,B),out(S)), b_and(in(A,B),out(C)).   b_full_adder(in(A,B,Ci), s(S), c(C1)) :- b_half_adder(in(Ci, A), s(S0), c(C0)), b_half_adder(in(S0, B), s(S), c(C)), b_or(in(C0,C), out(C1)).   b_4_bit_adder(in(A0,A1,A2,A3), in(B0,B1,B2,B3), out(S0,S1,S2,S3), c(V)) :- b_full_adder(in(A0,B0,lo), s(S0), c(C0)), b_full_adder(in(A1,B1,C0), s(S1), c(C1)), b_full_adder(in(A2,B2,C1), s(S2), c(C2)), b_full_adder(in(A3,B3,C2), s(S3), c(V)).   test_add(A,B,T) :- b_4_bit_adder(A, B, R, C), writef('%w + %w is %w %w \t(%w)\n', [A,B,R,C,T]).   go :- test_add(in(hi,lo,lo,lo), in(hi,lo,lo,lo), '1 + 1 = 2'), test_add(in(lo,hi,lo,lo), in(lo,hi,lo,lo), '2 + 2 = 4'), test_add(in(hi,lo,hi,lo), in(hi,lo,lo,hi), '5 + 9 = 14'), test_add(in(hi,hi,lo,hi), in(hi,lo,lo,hi), '11 + 9 = 20'), test_add(in(lo,lo,lo,hi), in(lo,lo,lo,hi), '8 + 8 = 16'), test_add(in(hi,hi,hi,hi), in(hi,lo,lo,lo), '15 + 1 = 16').
http://rosettacode.org/wiki/Fivenum
Fivenum
Many big data or scientific programs use boxplots to show distributions of data.   In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM.   It can be useful to save large arrays as arrays with five numbers to save memory. For example, the   R   programming language implements Tukey's five-number summary as the fivenum function. Task Given an array of numbers, compute the five-number summary. Note While these five numbers can be used to draw a boxplot,   statistical packages will typically need extra data. Moreover, while there is a consensus about the "box" of the boxplot,   there are variations among statistical packages for the whiskers.
#JavaScript
JavaScript
  function median(arr) { let mid = Math.floor(arr.length / 2); return (arr.length % 2 == 0) ? (arr[mid-1] + arr[mid]) / 2 : arr[mid]; }   Array.prototype.fiveNums = function() { this.sort(function(a, b) { return a - b} ); let mid = Math.floor(this.length / 2), loQ = (this.length % 2 == 0) ? this.slice(0, mid) : this.slice(0, mid+1), hiQ = this.slice(mid); return [ this[0], median(loQ), median(this), median(hiQ), this[this.length-1] ]; }   // testing let test = [15, 6, 42, 41, 7, 36, 49, 40, 39, 47, 43]; console.log( test.fiveNums() );   test = [0, 0, 1, 2, 63, 61, 27, 13]; console.log( test.fiveNums() );   test = [ 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578]; console.log( test.fiveNums() );  
http://rosettacode.org/wiki/Find_the_missing_permutation
Find the missing permutation
ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB Listed above are   all-but-one   of the permutations of the symbols   A,   B,   C,   and   D,   except   for one permutation that's   not   listed. Task Find that missing permutation. Methods Obvious method: enumerate all permutations of A, B, C, and D, and then look for the missing permutation. alternate method: Hint: if all permutations were shown above, how many times would A appear in each position? What is the parity of this number? another alternate method: Hint: if you add up the letter values of each column, does a missing letter A, B, C, and D from each column cause the total value for each column to be unique? Related task   Permutations)
#Aime
Aime
void paste(record r, index x, text p, integer a) { p = insert(p, -1, a); x.delete(a); if (~x) { x.vcall(paste, -1, r, x, p); } else { r[p] = 0; } x[a] = 0; }   integer main(void) { record r; list l; index x;   l.bill(0, "ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", "ADCB", "CDAB", "DABC", "BCAD", "CADB", "CDBA", "CBAD", "ABDC", "ADBC", "BDCA", "DCBA", "BACD", "BADC", "BDAC", "CBDA", "DBCA", "DCAB");   x['A'] = x['B'] = x['C'] = x['D'] = 0;   x.vcall(paste, -1, r, x, "");   l.ucall(r_delete, 1, r);   o_(r.low, "\n");   return 0; }
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month
Find the last Sunday of each month
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 2013-05-26 2013-06-30 2013-07-28 2013-08-25 2013-09-29 2013-10-27 2013-11-24 2013-12-29 Related tasks Day of the week Five weekends Last Friday of each month
#AutoHotkey
AutoHotkey
InputBox, Year, , Enter a year., , 300, 135 Date := Year . "0101"   while SubStr(Date, 1, 4) = Year { FormatTime, WD, % Date, WDay if (WD = 1) MM := LTrim(SubStr(Date, 5, 2), "0"), Day%MM% := SubStr(Date, 7, 2) Date += 1, Days }   Gui, Font, S10, Courier New Gui, Add, Text, , % "Last Sundays of " Year ":`n---------------------"   Loop, 12 { FormatTime, Month, % Year (A_Index > 9 ? "" : "0") A_Index, MMMM Gui, Add, Text, y+1, % Month (StrLen(Month) > 7 ? "" : "`t") "`t" Day%A_Index% }   Gui, Show return
http://rosettacode.org/wiki/Find_the_intersection_of_two_lines
Find the intersection of two lines
[1] Task Find the point of intersection of two lines in 2D. The 1st line passes though   (4,0)   and   (6,10) . The 2nd line passes though   (0,3)   and   (10,7) .
#AWK
AWK
  # syntax: GAWK -f FIND_THE_INTERSECTION_OF_TWO_LINES.AWK # converted from Ring BEGIN { intersect(4,0,6,10,0,3,10,7) exit(0) } function intersect(xa,ya,xb,yb,xc,yc,xd,yd, errors,x,y) { printf("the 1st line passes through (%g,%g) and (%g,%g)\n",xa,ya,xb,yb) printf("the 2nd line passes through (%g,%g) and (%g,%g)\n",xc,yc,xd,yd) if (xb-xa == 0) { print("error: xb-xa=0") ; errors++ } if (xd-xc == 0) { print("error: xd-xc=0") ; errors++ } if (errors > 0) { print("") return(0) } printf("the two lines are:\n") printf("yab=%g+x*%g\n",ya-xa*((yb-ya)/(xb-xa)),(yb-ya)/(xb-xa)) printf("ycd=%g+x*%g\n",yc-xc*((yd-yc)/(xd-xc)),(yd-yc)/(xd-xc)) x = ((yc-xc*((yd-yc)/(xd-xc)))-(ya-xa*((yb-ya)/(xb-xa))))/(((yb-ya)/(xb-xa))-((yd-yc)/(xd-xc))) printf("x=%g\n",x) y = ya-xa*((yb-ya)/(xb-xa))+x*((yb-ya)/(xb-xa)) printf("yab=%g\n",y) printf("ycd=%g\n",yc-xc*((yd-yc)/(xd-xc))+x*((yd-yc)/(xd-xc))) printf("intersection: %g,%g\n\n",x,y) return(1) }  
http://rosettacode.org/wiki/Find_the_intersection_of_a_line_with_a_plane
Find the intersection of a line with a plane
Finding the intersection of an infinite ray with a plane in 3D is an important topic in collision detection. Task Find the point of intersection for the infinite ray with direction   (0, -1, -1)   passing through position   (0, 0, 10)   with the infinite plane with a normal vector of   (0, 0, 1)   and which passes through [0, 0, 5].
#Arturo
Arturo
define :vector [x, y, z][]   addv: function [v1 :vector, v2 :vector]-> to :vector @[v1\x+v2\x, v1\y+v2\y, v1\z+v2\z]   subv: function [v1 :vector, v2 :vector]-> to :vector @[v1\x-v2\x, v1\y-v2\y, v1\z-v2\z]   mulv: function [v1 :vector, v2 :vector :floating][ if? is? :vector v2 -> return sum @[v1\x*v2\x v1\y*v2\y v1\z*v2\z] else -> return to :vector @[v1\x*v2, v1\y*v2, v1\z*v2] ]   intersect: function [lV, lP, pV, pP][ tdenom: mulv pV lV if zero? tdenom -> return to :vector @[∞, ∞, ∞] t: (mulv pV subv pP lP) / tdenom return addv mulv lV t lP ]   coords: intersect to :vector @[0.0, neg 1.0, neg 1.0] to :vector @[0.0, 0.0, 10.0] to :vector @[0.0, 0.0, 1.0] to :vector @[0.0, 0.0, 5.0]   print ["Intersection at:" coords]
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) The   FizzBuzz   problem was presented as the lowest level of comprehension required to illustrate adequacy. Also see   (a blog)   dont-overthink-fizzbuzz   (a blog)   fizzbuzz-the-programmers-stairway-to-heaven
#ABAP
ABAP
DATA: tab TYPE TABLE OF string.   tab = VALUE #( FOR i = 1 WHILE i <= 100 ( COND string( LET r3 = i MOD 3 r5 = i MOD 5 IN WHEN r3 = 0 AND r5 = 0 THEN |FIZZBUZZ| WHEN r3 = 0 THEN |FIZZ| WHEN r5 = 0 THEN |BUZZ| ELSE i ) ) ).   cl_demo_output=>write( tab ). cl_demo_output=>display( ).
http://rosettacode.org/wiki/Five_weekends
Five weekends
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays. Task Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar). Show the number of months with this property (there should be 201). Show at least the first and last five dates, in order. Algorithm suggestions Count the number of Fridays, Saturdays, and Sundays in every month. Find all of the 31-day months that begin on Friday. Extra credit Count and/or show all of the years which do not have at least one five-weekend month (there should be 29). Related tasks Day of the week Last Friday of each month Find last sunday of each month
#C
C
#include <stdio.h> #include <time.h>   static const char *months[] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}; static int long_months[] = {0, 2, 4, 6, 7, 9, 11};   int main() { int n = 0, y, i, m; struct tm t = {0}; printf("Months with five weekends:\n"); for (y = 1900; y <= 2100; y++) { for (i = 0; i < 7; i++) { m = long_months[i]; t.tm_year = y-1900; t.tm_mon = m; t.tm_mday = 1; if (mktime(&t) == -1) { /* date not supported */ printf("Error: %d %s\n", y, months[m]); continue; } if (t.tm_wday == 5) { /* Friday */ printf("  %d %s\n", y, months[m]); n++; } } } printf("%d total\n", n); return 0; }
http://rosettacode.org/wiki/First_perfect_square_in_base_n_with_n_unique_digits
First perfect square in base n with n unique digits
Find the first perfect square in a given base N that has at least N digits and exactly N significant unique digits when expressed in base N. E.G. In base 10, the first perfect square with at least 10 unique digits is 1026753849 (32043²). You may use analytical methods to reduce the search space, but the code must do a search. Do not use magic numbers or just feed the code the answer to verify it is correct. Task Find and display here, on this page, the first perfect square in base N, with N significant unique digits when expressed in base N, for each of base 2 through 12. Display each number in the base N for which it was calculated. (optional) Do the same for bases 13 through 16. (stretch goal) Continue on for bases 17 - ?? (Big Integer math) See also OEIS A260182: smallest square that is pandigital in base n. Related task Casting out nines
#Haskell
Haskell
import Control.Monad (guard) import Data.List (find, unfoldr) import Data.Char (intToDigit) import qualified Data.Set as Set import Text.Printf (printf)   digits :: Integral a => a -> a -> [a] digits b = unfoldr (((>>) . guard . (0 /=)) <*> (pure . ((,) <$> (`mod` b) <*> (`div` b))))   sequenceForBaseN :: Integral a => a -> [a] sequenceForBaseN b = unfoldr (\(v, n) -> Just (v, (v + n, n + 2))) (i ^ 2, i * 2 + 1) where i = succ (round $ sqrt (realToFrac (b ^ pred b)))   searchSequence :: Integral a => a -> Maybe a searchSequence b = find ((digitsSet ==) . Set.fromList . digits b) (sequenceForBaseN b) where digitsSet = Set.fromList [0 .. pred b]   display :: Integer -> Integer -> String display b n = map (intToDigit . fromIntegral) $ reverse $ digits b n   main :: IO () main = mapM_ (\b -> case searchSequence b of Just n -> printf "Base %2d: %8s² -> %16s\n" b (display b (squareRootValue n)) (display b n) Nothing -> pure ()) [2 .. 16] where squareRootValue = round . sqrt . realToFrac
http://rosettacode.org/wiki/First-class_functions
First-class functions
A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming: Create new functions from preexisting functions at run-time Store functions in collections Use functions as arguments to other functions Use functions as return values of other functions Task Write a program to create an ordered collection A of functions of a real number. At least one function should be built-in and at least one should be user-defined; try using the sine, cosine, and cubing functions. Fill another collection B with the inverse of each function in A. Implement function composition as in Functional Composition. Finally, demonstrate that the result of applying the composition of each function in A and its inverse in B to a value, is the original value. (Within the limits of computational accuracy). (A solution need not actually call the collections "A" and "B". These names are only used in the preceding paragraph for clarity.) Related task First-class Numbers
#Ceylon
Ceylon
module rosetta "1.0.0" { import ceylon.numeric "1.2.1"; }
http://rosettacode.org/wiki/First-class_functions
First-class functions
A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming: Create new functions from preexisting functions at run-time Store functions in collections Use functions as arguments to other functions Use functions as return values of other functions Task Write a program to create an ordered collection A of functions of a real number. At least one function should be built-in and at least one should be user-defined; try using the sine, cosine, and cubing functions. Fill another collection B with the inverse of each function in A. Implement function composition as in Functional Composition. Finally, demonstrate that the result of applying the composition of each function in A and its inverse in B to a value, is the original value. (Within the limits of computational accuracy). (A solution need not actually call the collections "A" and "B". These names are only used in the preceding paragraph for clarity.) Related task First-class Numbers
#Clojure
Clojure
  (use 'clojure.contrib.math) (let [fns [#(Math/sin %) #(Math/cos %) (fn [x] (* x x x))] inv [#(Math/asin %) #(Math/acos %) #(expt % 1/3)]] (map #(% 0.5) (map #(comp %1 %2) fns inv)))  
http://rosettacode.org/wiki/Forest_fire
Forest fire
This page uses content from Wikipedia. The original article was at Forest-fire model. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Implement the Drossel and Schwabl definition of the forest-fire model. It is basically a 2D   cellular automaton   where each cell can be in three distinct states (empty, tree and burning) and evolves according to the following rules (as given by Wikipedia) A burning cell turns into an empty cell A tree will burn if at least one neighbor is burning A tree ignites with probability   f   even if no neighbor is burning An empty space fills with a tree with probability   p Neighborhood is the   Moore neighborhood;   boundary conditions are so that on the boundary the cells are always empty ("fixed" boundary condition). At the beginning, populate the lattice with empty and tree cells according to a specific probability (e.g. a cell has the probability 0.5 to be a tree). Then, let the system evolve. Task's requirements do not include graphical display or the ability to change parameters (probabilities   p   and   f )   through a graphical or command line interface. Related tasks   See   Conway's Game of Life   See   Wireworld.
#Haskell
Haskell
import Control.Monad (replicateM, unless) import Data.List (tails, transpose) import System.Random (randomRIO)   data Cell = Empty | Tree | Fire deriving (Eq)   instance Show Cell where show Empty = " " show Tree = "T" show Fire = "$"   randomCell :: IO Cell randomCell = fmap ([Empty, Tree] !!) (randomRIO (0, 1) :: IO Int)   randomChance :: IO Double randomChance = randomRIO (0, 1.0) :: IO Double   rim :: a -> [[a]] -> [[a]] rim b = fmap (fb b) . (fb =<< rb) where fb = (.) <$> (:) <*> (flip (++) . return) rb = fst . unzip . zip (repeat b) . head   take3x3 :: [[a]] -> [[[a]]] take3x3 = concatMap (transpose . fmap take3) . take3 where take3 = init . init . takeWhile (not . null) . fmap (take 3) . tails   list2Mat :: Int -> [a] -> [[a]] list2Mat n = takeWhile (not . null) . fmap (take n) . iterate (drop n)   evolveForest :: Int -> Int -> Int -> IO () evolveForest m n k = do let s = m * n fs <- replicateM s randomCell let nextState xs = do ts <- replicateM s randomChance vs <- replicateM s randomChance let rv [r1, [l, c, r], r3] newTree fire | c == Fire = Empty | c == Tree && Fire `elem` concat [r1, [l, r], r3] = Fire | c == Tree && 0.01 >= fire = Fire | c == Empty && 0.1 >= newTree = Tree | otherwise = c return $ zipWith3 rv xs ts vs evolve i xs = unless (i > k) $ do let nfs = nextState $ take3x3 $ rim Empty $ list2Mat n xs putStrLn ("\n>>>>>> " ++ show i ++ ":") mapM_ (putStrLn . concatMap show) $ list2Mat n xs nfs >>= evolve (i + 1) evolve 1 fs   main :: IO () main = evolveForest 6 50 3
http://rosettacode.org/wiki/First_class_environments
First class environments
According to Wikipedia, "In computing, a first-class object ... is an entity that can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable". Often this term is used in the context of "first class functions". In an analogous way, a programming language may support "first class environments". The environment is minimally, the set of variables accessible to a statement being executed. Change the environments and the same statement could produce different results when executed. Often an environment is captured in a closure, which encapsulates a function together with an environment. That environment, however, is not first-class, as it cannot be created, passed etc. independently from the function's code. Therefore, a first class environment is a set of variable bindings which can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable. It is like a closure without code. A statement must be able to be executed within a stored first class environment and act according to the environment variable values stored within. Task Build a dozen environments, and a single piece of code to be run repeatedly in each of these environments. Each environment contains the bindings for two variables:   a value in the Hailstone sequence, and   a count which is incremented until the value drops to 1. The initial hailstone values are 1 through 12, and the count in each environment is zero. When the code runs, it calculates the next hailstone step in the current environment (unless the value is already 1) and counts the steps. Then it prints the current value in a tabular form. When all hailstone values dropped to 1, processing stops, and the total number of hailstone steps for each environment is printed.
#PicoLisp
PicoLisp
(let Envs (mapcar '((N) (list (cons 'N N) (cons 'Cnt 0))) # Build environments (range 1 12) ) (while (find '((E) (job E (> N 1))) Envs) # Until all values are 1: (for E Envs (job E # Use environment 'E' (prin (align 4 N)) (unless (= 1 N) (inc 'Cnt) # Increment step count (setq N (if (bit? 1 N) # Calculate next hailstone value (inc (* N 3)) (/ N 2) ) ) ) ) ) (prinl) ) (prinl (need 48 '=)) (for E Envs # For each environment 'E' (job E (prin (align 4 Cnt)) ) ) # print the step count (prinl) )
http://rosettacode.org/wiki/First_class_environments
First class environments
According to Wikipedia, "In computing, a first-class object ... is an entity that can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable". Often this term is used in the context of "first class functions". In an analogous way, a programming language may support "first class environments". The environment is minimally, the set of variables accessible to a statement being executed. Change the environments and the same statement could produce different results when executed. Often an environment is captured in a closure, which encapsulates a function together with an environment. That environment, however, is not first-class, as it cannot be created, passed etc. independently from the function's code. Therefore, a first class environment is a set of variable bindings which can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable. It is like a closure without code. A statement must be able to be executed within a stored first class environment and act according to the environment variable values stored within. Task Build a dozen environments, and a single piece of code to be run repeatedly in each of these environments. Each environment contains the bindings for two variables:   a value in the Hailstone sequence, and   a count which is incremented until the value drops to 1. The initial hailstone values are 1 through 12, and the count in each environment is zero. When the code runs, it calculates the next hailstone step in the current environment (unless the value is already 1) and counts the steps. Then it prints the current value in a tabular form. When all hailstone values dropped to 1, processing stops, and the total number of hailstone steps for each environment is printed.
#Python
Python
environments = [{'cnt':0, 'seq':i+1} for i in range(12)]   code = ''' print('% 4d' % seq, end='') if seq != 1: cnt += 1 seq = 3 * seq + 1 if seq & 1 else seq // 2 '''   while any(env['seq'] > 1 for env in environments): for env in environments: exec(code, globals(), env) print()   print('Counts') for env in environments: print('% 4d' % env['cnt'], end='') print()
http://rosettacode.org/wiki/First_class_environments
First class environments
According to Wikipedia, "In computing, a first-class object ... is an entity that can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable". Often this term is used in the context of "first class functions". In an analogous way, a programming language may support "first class environments". The environment is minimally, the set of variables accessible to a statement being executed. Change the environments and the same statement could produce different results when executed. Often an environment is captured in a closure, which encapsulates a function together with an environment. That environment, however, is not first-class, as it cannot be created, passed etc. independently from the function's code. Therefore, a first class environment is a set of variable bindings which can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable. It is like a closure without code. A statement must be able to be executed within a stored first class environment and act according to the environment variable values stored within. Task Build a dozen environments, and a single piece of code to be run repeatedly in each of these environments. Each environment contains the bindings for two variables:   a value in the Hailstone sequence, and   a count which is incremented until the value drops to 1. The initial hailstone values are 1 through 12, and the count in each environment is zero. When the code runs, it calculates the next hailstone step in the current environment (unless the value is already 1) and counts the steps. Then it prints the current value in a tabular form. When all hailstone values dropped to 1, processing stops, and the total number of hailstone steps for each environment is printed.
#R
R
code <- quote( if (n == 1) n else { count <- count + 1; n <- if (n %% 2 == 1) 3 * n + 1 else n/2 })   eprint <- function(envs, var="n") cat(paste(sprintf("%4d", sapply(envs, `[[`, var)), collapse=" "), "\n")   envs <- mapply(function(...) list2env(list(...)), n=1:12, count=0)   while (any(sapply(envs, eval, expr=code) > 1)) {eprint(envs)} eprint(envs)   cat("\nCounts:\n") eprint(envs, "count")
http://rosettacode.org/wiki/Flatten_a_list
Flatten a list
Task Write a function to flatten the nesting in an arbitrary list of values. Your program should work on the equivalent of this list: [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []] Where the correct result would be the list: [1, 2, 3, 4, 5, 6, 7, 8] Related task   Tree traversal
#D.C3.A9j.C3.A0_Vu
Déjà Vu
(flatten): for i in copy: i if = :list type dup: (flatten)   flatten l: [ (flatten) l ]     !. flatten [ [ 1 ] 2 [ [ 3 4 ] 5 ] [ [ [] ] ] [ [ [ 6 ] ] ] 7 8 [] ]
http://rosettacode.org/wiki/Flipping_bits_game
Flipping bits game
The game Given an   N×N   square array of zeroes or ones in an initial configuration,   and a target configuration of zeroes and ones. The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered columns at once   (as one move). In an inversion.   any  1  becomes  0,   and any  0  becomes  1  for that whole row or column. Task Create a program to score for the Flipping bits game. The game should create an original random target configuration and a starting configuration. Ensure that the starting position is never the target position. The target position must be guaranteed as reachable from the starting position.   (One possible way to do this is to generate the start position by legal flips from a random target position.   The flips will always be reversible back to the target from the given start position). The number of moves taken so far should be shown. Show an example of a short game here, on this page, for a   3×3   array of bits.
#Phix
Phix
integer w, h   string board, target   procedure new_board() board = "" h = prompt_number("Enter number of rows(1..9):",{1,9}) w = prompt_number("Enter number of columns(1..26):",{1,26}) string line = "" for j=1 to w do line &= 'A'+j-1 end for board = " "&line&"\n" for i=1 to h do line = '0'+i&" " for j=1 to w do line &= '0'+rand(2)-1 end for board &= line&"\n" end for end procedure   procedure show_bt() sequence sb = split(board,'\n'), st = split(target,'\n') printf(1,"board:%s target:%s\n",{sb[1],st[1]}) for i=2 to length(sb)-1 do printf(1,"  %s  %s\n",{sb[i],st[i]}) end for end procedure   procedure flip(integer ch, bool bShow=true) integer k if ch>='A' and ch<='A'+w-1 then -- flip_column ch = ch-'A'+1 for i=1 to h do k = 2+ch+i*(w+3) board[k] = '0'+'1'-board[k] end for k = 2+ch elsif ch>='1' and ch<='0'+h then -- flip_row ch -= '0' for i=1 to w do k = 2+i+(ch)*(w+3) board[k] = '0'+'1'-board[k] end for k = 1+(ch)*(w+3) else  ?9/0 -- sanity check end if if bShow then integer wasch = board[k] board[k] = '*' show_bt() board[k] = wasch end if end procedure   procedure scramble_board() integer lim = 10000 while 1 do for i=1 to lim do if rand(2)=1 then flip('A'-1+rand(w),false) else flip('0'+rand(h),false) end if end for if board!=target then exit end if lim -= 1 -- sidestep the degenerate 1x1 case end while end procedure   function solve_board() -- not guaranteed optimal (the commented-out length check clogs it on larger boards) string original = board, moves sequence next = {{0,board,""}}, legal_moves = tagset('A'+w-1,'A')&tagset('0'+h,'1') atom t2 = time()+2 -- in case board is illegal/unsolveable while time()<t2 do for lm=1 to length(legal_moves) do integer c = legal_moves[lm] {?,board,moves} = next[1] flip(c,false) moves &= c if board = target then board = original return moves end if next = append(next,{sum(sq_eq(board,target)),board,moves}) for i=length(next) to 3 by -1 do if next[i][1]<=next[i-1][1] then exit end if -- if length(next[i][3])>length(next[i-1][3]) then exit end if {next[i-1],next[i]} = {next[i],next[i-1]} end for end for next = next[2..$] end while board = original return 0 end function   constant ESC = #1B   procedure main() integer moves = 0, solves = 0, ch bool took_hint = false new_board() target = board scramble_board() show_bt() object soln = solve_board() while 1 do string solve = iff(string(soln)?sprintf(" solveable in %d,",length(soln)):"") printf(1,"moves taken %d,%s enter your move (A..%c or 1..%c) or ?:",{moves,solve,'A'+w-1,'0'+h}) while 1 do ch = upper(wait_key()) if ch<=#FF then exit end if -- (ignore control keys) end while printf(1,"%c\n",ch) if (ch>='A' and ch<='A'+w-1) or (ch>='1' and ch<='0'+h) then flip(ch) if board=target then printf(1,"\nWell %s!\n\n",{iff(took_hint?"cheated","done")}) exit end if moves += 1 soln = iff(string(soln) and ch=soln[1]?soln[2..$]:solve_board()) elsif string(soln) and (ch='H' -- (nb consumed above if w>=8) or ch='.') then took_hint = true printf(1,"hint: %c\n",soln[1]) elsif ch='Q' -- (nb consumed above if w>=17) or ch=ESC then exit elsif string(soln) and (ch='S' -- (nb consumed above if w>=19) or ch='!') then for i=1 to length(soln) do printf(1,"auto-solving, move %d:\n",i) flip(soln[i]) sleep(2) end for exit else puts(1,"press ") if string(soln) then puts(1,"'!' (or 's' if width<19) to solve the board automatically,\n") puts(1," '.' (or 'h' if width<8) to show hint,\n") end if puts(1," escape (or 'q' if width<17) to quit\n") end if end while end procedure main()
http://rosettacode.org/wiki/Flipping_bits_game
Flipping bits game
The game Given an   N×N   square array of zeroes or ones in an initial configuration,   and a target configuration of zeroes and ones. The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered columns at once   (as one move). In an inversion.   any  1  becomes  0,   and any  0  becomes  1  for that whole row or column. Task Create a program to score for the Flipping bits game. The game should create an original random target configuration and a starting configuration. Ensure that the starting position is never the target position. The target position must be guaranteed as reachable from the starting position.   (One possible way to do this is to generate the start position by legal flips from a random target position.   The flips will always be reversible back to the target from the given start position). The number of moves taken so far should be shown. Show an example of a short game here, on this page, for a   3×3   array of bits.
#PL.2FI
PL/I
(subscriptrange, stringrange, stringsize): flip: procedure options (main); declare n fixed binary;   put skip list ('This is the bit-flipping game. What size of board do you want?'); get list (n); put skip list ('Your task is to change your board so as match the board on the right (the objective)');   begin; declare initial(n,n) bit (1), objective(n,n) bit (1); declare (i, j, k, move) fixed binary; declare ch character(1); declare alphabet character (26) initial ('abcdefghijklmnopqrstuvwxyz');   on subrg begin; put skip list ('Your row or column ' || trim(ch) || ' is out of range'); stop; end;   initial, objective = iand(random()*99, 1) = 1;   /* Set up the objective array: */ do i = 1 to n-1; j = random()*n+1; objective(j,*) = ^objective(j,*); j = random()*n+1; objective(*,j) = ^objective(*,j); end;   do move = 0 by 1; put skip edit ( center('You', n*3), center('The objective', 3*n+4) ) (x(3), a); put skip edit ( (substr(alphabet, i, 1) do i = 1 to n) ) (x(5), (n) a(3)); put edit ( (substr(alphabet, i, 1) do i = 1 to n) ) (x(3), (n) a(3)); do i = 1 to n; put skip edit (i, initial(i,*), objective(i,*)) ((n+1) f(3), x(3), (n) F(3)); end;   if all(initial = objective) then leave;   put skip(2) list ('Please type a row number or column letter whose bits you want to flip: '); get edit (ch) (L); put edit (ch) (a); k = index(alphabet, ch); if k > 0 then initial(*, k) = ^initial(*,k); /* Flip column k */ else initial(ch,*) = ^initial(ch,*); /* Flip row ch */ end; put skip(2) list ('Congratulations. You solved it in ' || trim(move) || ' moves.'); end;   end flip;
http://rosettacode.org/wiki/First_power_of_2_that_has_leading_decimal_digits_of_12
First power of 2 that has leading decimal digits of 12
(This task is taken from a   Project Euler   problem.) (All numbers herein are expressed in base ten.) 27   =   128   and   7   is the first power of   2   whose leading decimal digits are   12. The next power of   2   whose leading decimal digits are   12   is   80, 280   =   1208925819614629174706176. Define     p(L,n)     to be the nth-smallest value of   j   such that the base ten representation of   2j   begins with the digits of   L . So p(12, 1) = 7 and p(12, 2) = 80 You are also given that: p(123, 45)   =   12710 Task   find:   p(12, 1)   p(12, 2)   p(123, 45)   p(123, 12345)   p(123, 678910)   display the results here, on this page.
#Phix
Phix
with javascript_semantics function p(integer L, n) atom logof2 = log10(2) integer places = trunc(log10(L)), nfound = 0, i = 1 while true do atom a = i * logof2, b = trunc(power(10,a-trunc(a)+places)) if L == b then nfound += 1 if nfound == n then exit end if end if i += 1 end while return i end function constant tests = {{12, 1}, {12, 2}, {123, 45}, {123, 12345}, {123, 678910}} include ordinal.e include mpfr.e mpz z = mpz_init() atom t0 = time() for i=1 to length(tests)-(2*(platform()=JS)) do integer {L,n} = tests[i], pln = p(L,n) mpz_ui_pow_ui(z,2,pln) integer digits = mpz_sizeinbase(z,10) string st = iff(digits>2e6?sprintf("%,d digits",digits): shorten(mpz_get_str(z),"digits",5)) printf(1,"The %d%s power of 2 that starts with %d is %d [i.e. %s]\n",{n,ord(n),L,pln,st}) end for ?elapsed(time()-t0)
http://rosettacode.org/wiki/First-class_functions/Use_numbers_analogously
First-class functions/Use numbers analogously
In First-class functions, a language is showing how its manipulation of functions is similar to its manipulation of other types. This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers. Write a program to create an ordered collection of a mixture of literally typed and expressions producing a real number, together with another ordered collection of their multiplicative inverses. Try and use the following pseudo-code to generate the numbers for the ordered collections: x = 2.0 xi = 0.5 y = 4.0 yi = 0.25 z = x + y zi = 1.0 / ( x + y ) Create a function multiplier, that given two numbers as arguments returns a function that when called with one argument, returns the result of multiplying the two arguments to the call to multiplier that created it and the argument in the call: new_function = multiplier(n1,n2) # where new_function(m) returns the result of n1 * n2 * m Applying the multiplier of a number and its inverse from the two ordered collections of numbers in pairs, show that the result in each case is one. Compare and contrast the resultant program with the corresponding entry in First-class functions. They should be close. To paraphrase the task description: Do what was done before, but with numbers rather than functions
#OCaml
OCaml
# let x = 2.0;;   # let y = 4.0;;   # let z = x +. y;;   # let coll = [ x; y; z];;   # let inv_coll = List.map (fun x -> 1.0 /. x) coll;;   # let multiplier n1 n2 = (fun t -> n1 *. n2 *. t);;   (* create a list of new functions *) # let func_list = List.map2 (fun n inv -> (multiplier n inv)) coll inv_coll;;   # List.map (fun f -> f 0.5) func_list;; - : float list = [0.5; 0.5; 0.5]   (* or just apply the generated function immediately... *) # List.map2 (fun n inv -> (multiplier n inv) 0.5) coll inv_coll;; - : float list = [0.5; 0.5; 0.5]
http://rosettacode.org/wiki/First-class_functions/Use_numbers_analogously
First-class functions/Use numbers analogously
In First-class functions, a language is showing how its manipulation of functions is similar to its manipulation of other types. This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers. Write a program to create an ordered collection of a mixture of literally typed and expressions producing a real number, together with another ordered collection of their multiplicative inverses. Try and use the following pseudo-code to generate the numbers for the ordered collections: x = 2.0 xi = 0.5 y = 4.0 yi = 0.25 z = x + y zi = 1.0 / ( x + y ) Create a function multiplier, that given two numbers as arguments returns a function that when called with one argument, returns the result of multiplying the two arguments to the call to multiplier that created it and the argument in the call: new_function = multiplier(n1,n2) # where new_function(m) returns the result of n1 * n2 * m Applying the multiplier of a number and its inverse from the two ordered collections of numbers in pairs, show that the result in each case is one. Compare and contrast the resultant program with the corresponding entry in First-class functions. They should be close. To paraphrase the task description: Do what was done before, but with numbers rather than functions
#Oforth
Oforth
: multiplier(n1, n2) #[ n1 n2 * * ] ;   : firstClassNum | x xi y yi z zi | 2.0 ->x 0.5 ->xi 4.0 ->y 0.25 ->yi x y + ->z x y + inv ->zi [ x, y, z ] [ xi, yi, zi ] zipWith(#multiplier) map(#[ 0.5 swap perform ] ) . ;
http://rosettacode.org/wiki/Flow-control_structures
Flow-control structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task Document common flow-control structures. One common example of a flow-control structure is the   goto   construct. Note that   Conditional Structures   and   Loop Structures   have their own articles/categories. Related tasks   Conditional Structures   Loop Structures
#PL.2FI
PL/I
  LEAVE The LEAVE statement terminates execution of a loop. Execution resumes at the next statement after the loop. ITERATE The ITERATE statement causes the next iteration of the loop to commence. Any statements between ITERATE and the end of the loop are not executed. STOP Terminates execution of either a task or the entire program. SIGNAL FINISH Terminates execution of a program in a nice way. SIGNAL statement SIGNAL <condition> raises the named condition. The condition may be one of the hardware or software conditions such as OVERFLOW, UNDERFLOW, ZERODIVIDE, SUBSCRIPTRANGE, STRINGRANGE, etc, or a user-defined condition. CALL The CALL statement causes control to transfer to the named subroutine. SELECT The SELECT statement permits the execution of just one of a list of statements (or groups of statements). It is sort of like a computed GOTO. GO TO The GO TO statement causes control to be transferred to the named statement. It can also be used to transfer control to any one of an array of labelled statements. (This form is superseded by SELECT, above.) [GO TO can also be spelled as GOTO].  
http://rosettacode.org/wiki/Flow-control_structures
Flow-control structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task Document common flow-control structures. One common example of a flow-control structure is the   goto   construct. Note that   Conditional Structures   and   Loop Structures   have their own articles/categories. Related tasks   Conditional Structures   Loop Structures
#Pop11
Pop11
while condition1 do while condition2 do if condition3 then quitloop(2); endif; endwhile; endwhile;
http://rosettacode.org/wiki/Floyd%27s_triangle
Floyd's triangle
Floyd's triangle   lists the natural numbers in a right triangle aligned to the left where the first row is   1     (unity) successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above. The first few lines of a Floyd triangle looks like this: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Task Write a program to generate and display here the first   n   lines of a Floyd triangle. (Use   n=5   and   n=14   rows). Ensure that when displayed in a mono-space font, the numbers line up in vertical columns as shown and that only one space separates numbers of the last row.
#F.23
F#
open System   [<EntryPoint>] let main argv = // columns and rows are 0-based, so the input has to be decremented: let maxRow = match UInt32.TryParse(argv.[0]) with | (true, v) when v > 0u -> int (v - 1u) | (_, _) -> failwith "not a positive integer"   let len (n: int) = int (Math.Floor(Math.Log10(float n))) let col0 row = row * (row + 1) / 2 + 1 let col0maxRow = col0 maxRow for row in [0 .. maxRow] do for col in [0 .. row] do let value = (col0 row) + col let pad = String(' ', (len (col0maxRow + col) - len (value) + 1)) printf "%s%d" pad value printfn "" 0
http://rosettacode.org/wiki/Floyd-Warshall_algorithm
Floyd-Warshall algorithm
The Floyd–Warshall algorithm is an algorithm for finding shortest paths in a weighted graph with positive or negative edge weights. Task Find the lengths of the shortest paths between all pairs of vertices of the given directed graph. Your code may assume that the input has already been checked for loops, parallel edges and negative cycles. Print the pair, the distance and (optionally) the path. Example pair dist path 1 -> 2 -1 1 -> 3 -> 4 -> 2 1 -> 3 -2 1 -> 3 1 -> 4 0 1 -> 3 -> 4 2 -> 1 4 2 -> 1 2 -> 3 2 2 -> 1 -> 3 2 -> 4 4 2 -> 1 -> 3 -> 4 3 -> 1 5 3 -> 4 -> 2 -> 1 3 -> 2 1 3 -> 4 -> 2 3 -> 4 2 3 -> 4 4 -> 1 3 4 -> 2 -> 1 4 -> 2 -1 4 -> 2 4 -> 3 1 4 -> 2 -> 1 -> 3 See also Floyd-Warshall Algorithm - step by step guide (youtube)
#ObjectIcon
ObjectIcon
# # Floyd-Warshall algorithm. # # See https://en.wikipedia.org/w/index.php?title=Floyd%E2%80%93Warshall_algorithm&oldid=1082310013 #   import io import ipl.array import ipl.printf   record fw_results (n, distance, next_vertex)   procedure main () local example_graph local fw local u, v   example_graph := [[1, -2.0, 3], [3, +2.0, 4], [4, -1.0, 2], [2, +4.0, 1], [2, +3.0, 3]]   fw := floyd_warshall (example_graph)   printf (" pair distance path\n") printf ("-------------------------------------\n") every u := 1 to fw.n do { every v := 1 to fw.n do { if u ~= v then { printf (" %d -> %d  %4s  %s\n", u, v, string (ref_array (fw.distance, u, v)), path_to_string (find_path (fw.next_vertex, u, v))) } } } end   procedure floyd_warshall (edges) local n, distance, next_vertex local e local i, j, k local dist_ij, dist_ik, dist_kj, dist_ikj   n := max_vertex (edges) distance := create_array ([1, 1], [n, n], &null) next_vertex := create_array ([1, 1], [n, n], &null)   # Initialization. every e := !edges do { ref_array (distance, e[1], e[3]) := e[2] ref_array (next_vertex, e[1], e[3]) := e[3] } every i := 1 to n do { ref_array (distance, i, i) := 0.0 # Distance to self = 0. ref_array (next_vertex, i, i) := i }   # Perform the algorithm. Here &null will play the role of # "infinity": "\" means a value is finite, "/" that it is infinite. every k := 1 to n do { every i := 1 to n do { every j := 1 to n do { dist_ij := ref_array (distance, i, j) dist_ik := ref_array (distance, i, k) dist_kj := ref_array (distance, k, j) if \dist_ik & \dist_kj then { dist_ikj := dist_ik + dist_kj if /dist_ij | dist_ikj < dist_ij then { ref_array (distance, i, j) := dist_ikj ref_array (next_vertex, i, j) := ref_array (next_vertex, i, k) } } } } }   return fw_results (n, distance, next_vertex) end   procedure find_path (next_vertex, u, v) local path   if / (ref_array (next_vertex, u, v)) then { path := [] } else { path := [u] while u ~= v do { u := ref_array (next_vertex, u, v) put (path, u) } } return path end   procedure path_to_string (path) local s   if *path = 0 then { s := "" } else { s := string (path[1]) every s ||:= (" -> " || !path[2 : 0]) } return s end   procedure max_vertex (edges) local e local m   *edges = 0 & stop ("no edges") m := 1 every e := !edges do m := max (m, e[1], e[3]) return m end
http://rosettacode.org/wiki/Function_definition
Function definition
A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract from showing how functions are created and values returned). Related task   Function prototype
#SPL
SPL
multiply(a,b) <= a*b
http://rosettacode.org/wiki/Function_definition
Function definition
A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract from showing how functions are created and values returned). Related task   Function prototype
#SSEM
SSEM
01000000000000100000000000000000 0. -2 to c 00100000000000000000000000000000 1. 4 to CI 01111111111111111111111111111111 2. -2 00000000000001110000000000000000 3. Stop 11100000000000000000000000000000 4. 7
http://rosettacode.org/wiki/Forward_difference
Forward difference
Task Provide code that produces a list of numbers which is the   nth  order forward difference, given a non-negative integer (specifying the order) and a list of numbers. The first-order forward difference of a list of numbers   A   is a new list   B,   where   Bn = An+1 - An. List   B   should have one fewer element as a result. The second-order forward difference of   A   will be: tdefmodule Diff do def forward(arr,i\\1) do forward(arr,[],i) end def forward([_|[]],diffs,i) do if i == 1 do IO.inspect diffs else forward(diffs,[],i-1) end end def forward([val1|[val2|vals]],diffs,i) do forward([val2|vals],diffs++[val2-val1],i) end end The same as the first-order forward difference of   B. That new list will have two fewer elements than   A   and one less than   B. The goal of this task is to repeat this process up to the desired order. For a more formal description, see the related   Mathworld article. Algorithmic options Iterate through all previous forward differences and re-calculate a new array each time. Use this formula (from Wikipedia): Δ n [ f ] ( x ) = ∑ k = 0 n ( n k ) ( − 1 ) n − k f ( x + k ) {\displaystyle \Delta ^{n}[f](x)=\sum _{k=0}^{n}{n \choose k}(-1)^{n-k}f(x+k)} (Pascal's Triangle   may be useful for this option.)
#Picat
Picat
go => L = [90, 47, 58, 29, 22, 32, 55, 5, 55, 73], foreach(I in 1..L.length-1) println([d=I,diffi(L,I)]) end, nl,  % All differences (a sublist to save space) println(alldiffs(L[1..6])), nl.   % Difference of the list diff(L) = Diff => Diff = [L[I]-L[I-1] : I in 2..L.length].   % The i'th list difference diffi(L,D) = Diff => Diff1 = L, foreach(_I in 1..D) Diff1 := diff(Diff1) end, Diff = Diff1.   % all differences alldiffs(L) = Diffs => Diffs1 = [], Diff = L, foreach(_I in 1..L.length-1) Diff := diff(Diff), Diffs1 := Diffs1 ++ [Diff] end, Diffs = Diffs1.
http://rosettacode.org/wiki/Forward_difference
Forward difference
Task Provide code that produces a list of numbers which is the   nth  order forward difference, given a non-negative integer (specifying the order) and a list of numbers. The first-order forward difference of a list of numbers   A   is a new list   B,   where   Bn = An+1 - An. List   B   should have one fewer element as a result. The second-order forward difference of   A   will be: tdefmodule Diff do def forward(arr,i\\1) do forward(arr,[],i) end def forward([_|[]],diffs,i) do if i == 1 do IO.inspect diffs else forward(diffs,[],i-1) end end def forward([val1|[val2|vals]],diffs,i) do forward([val2|vals],diffs++[val2-val1],i) end end The same as the first-order forward difference of   B. That new list will have two fewer elements than   A   and one less than   B. The goal of this task is to repeat this process up to the desired order. For a more formal description, see the related   Mathworld article. Algorithmic options Iterate through all previous forward differences and re-calculate a new array each time. Use this formula (from Wikipedia): Δ n [ f ] ( x ) = ∑ k = 0 n ( n k ) ( − 1 ) n − k f ( x + k ) {\displaystyle \Delta ^{n}[f](x)=\sum _{k=0}^{n}{n \choose k}(-1)^{n-k}f(x+k)} (Pascal's Triangle   may be useful for this option.)
#PicoLisp
PicoLisp
(de fdiff (Lst) (mapcar - (cdr Lst) Lst) )   (for (L (90 47 58 29 22 32 55 5 55 73) L (fdiff L)) (println L) )
http://rosettacode.org/wiki/Formatted_numeric_output
Formatted numeric output
Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
#Stata
Stata
. display %010.3f (57/8) 000007.125
http://rosettacode.org/wiki/Formatted_numeric_output
Formatted numeric output
Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
#Suneido
Suneido
Print(7.125.Pad(9))
http://rosettacode.org/wiki/Four_bit_adder
Four bit adder
Task "Simulate" a four-bit adder. This design can be realized using four 1-bit full adders. Each of these 1-bit full adders can be built with two half adders and an   or   gate. ; Finally a half adder can be made using an   xor   gate and an   and   gate. The   xor   gate can be made using two   nots,   two   ands   and one   or. Not,   or   and   and,   the only allowed "gates" for the task, can be "imitated" by using the bitwise operators of your language. If there is not a bit type in your language, to be sure that the   not   does not "invert" all the other bits of the basic type   (e.g. a byte)   we are not interested in,   you can use an extra   nand   (and   then   not)   with the constant   1   on one input. Instead of optimizing and reducing the number of gates used for the final 4-bit adder,   build it in the most straightforward way,   connecting the other "constructive blocks",   in turn made of "simpler" and "smaller" ones. Schematics of the "constructive blocks" (Xor gate with ANDs, ORs and NOTs)            (A half adder)                   (A full adder)                             (A 4-bit adder)         Solutions should try to be as descriptive as possible, making it as easy as possible to identify "connections" between higher-order "blocks". It is not mandatory to replicate the syntax of higher-order blocks in the atomic "gate" blocks, i.e. basic "gate" operations can be performed as usual bitwise operations, or they can be "wrapped" in a block in order to expose the same syntax of higher-order blocks, at implementers' choice. To test the implementation, show the sum of two four-bit numbers (in binary).
#PureBasic
PureBasic
;Because no representation for a solitary bit is present, bits are stored as bytes. ;Output values from the constructive building blocks is done using pointers (i.e. '*').   Procedure.b notGate(x) ProcedureReturn ~x EndProcedure   Procedure.b xorGate(x,y) ProcedureReturn (x & notGate(y)) | (notGate(x) & y) EndProcedure   Procedure halfadder(a, b, *sum.Byte, *carry.Byte) *sum\b = xorGate(a, b) *carry\b = a & b EndProcedure   Procedure fulladder(a, b, c0, *sum.Byte, *c1.Byte) Protected sum_ac.b, carry_ac.b, carry_sb.b   halfadder(c0, a, @sum_ac, @carry_ac) halfadder(sum_ac, b, *sum, @carry_sb) *c1\b = carry_ac | carry_sb EndProcedure   Procedure fourbitsadder(a0, a1, a2, a3, b0, b1, b2, b3 , *s0.Byte, *s1.Byte, *s2.Byte, *s3.Byte, *v.Byte) Protected.b c1, c2, c3   fulladder(a0, b0, 0, *s0, @c1) fulladder(a1, b1, c1, *s1, @c2) fulladder(a2, b2, c2, *s2, @c3) fulladder(a3, b3, c3, *s3, *v) EndProcedure   ;// Test implementation, map two 4-character strings to the inputs of the fourbitsadder() and display results Procedure.s test_4_bit_adder(a.s,b.s) Protected.b s0, s1, s2, s3, v, i Dim a.b(3) Dim b.b(3) For i = 0 To 3 a(i) = Val(Mid(a, 4 - i, 1)) b(i) = Val(Mid(b, 4 - i, 1)) Next   fourbitsadder(a(0), a(1), a(2), a(3), b(0), b(1), b(2), b(3), @s0, @s1, @s2, @s3, @v) ProcedureReturn a + " + " + b + " = " + Str(s3) + Str(s2) + Str(s1) + Str(s0) + " overflow " + Str(v) EndProcedure   If OpenConsole() PrintN(test_4_bit_adder("0110","1110"))   Print(#CRLF$ + #CRLF$ + "Press ENTER to exit") Input() CloseConsole() EndIf
http://rosettacode.org/wiki/Fivenum
Fivenum
Many big data or scientific programs use boxplots to show distributions of data.   In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM.   It can be useful to save large arrays as arrays with five numbers to save memory. For example, the   R   programming language implements Tukey's five-number summary as the fivenum function. Task Given an array of numbers, compute the five-number summary. Note While these five numbers can be used to draw a boxplot,   statistical packages will typically need extra data. Moreover, while there is a consensus about the "box" of the boxplot,   there are variations among statistical packages for the whiskers.
#Julia
Julia
function mediansorted(x::AbstractVector{T}, i::Integer, l::Integer)::T where T len = l - i + 1 len > zero(len) || throw(ArgumentError("Array slice cannot be empty.")) mid = i + len ÷ 2 return isodd(len) ? x[mid] : (x[mid-1] + x[mid]) / 2 end   function fivenum(x::AbstractVector{T}) where T<:AbstractFloat r = Vector{T}(5) xs = sort(x) mid::Int = length(xs) ÷ 2 lowerend::Int = isodd(length(xs)) ? mid : mid - 1 r[1] = xs[1] r[2] = mediansorted(xs, 1, lowerend) r[3] = mediansorted(xs, 1, endof(xs)) r[4] = mediansorted(xs, mid, endof(xs)) r[end] = xs[end] return r end   for v in ([15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0], [36.0, 40.0, 7.0, 39.0, 41.0, 15.0], [0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578]) println("# ", v, "\n -> ", fivenum(v)) end
http://rosettacode.org/wiki/Fivenum
Fivenum
Many big data or scientific programs use boxplots to show distributions of data.   In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM.   It can be useful to save large arrays as arrays with five numbers to save memory. For example, the   R   programming language implements Tukey's five-number summary as the fivenum function. Task Given an array of numbers, compute the five-number summary. Note While these five numbers can be used to draw a boxplot,   statistical packages will typically need extra data. Moreover, while there is a consensus about the "box" of the boxplot,   there are variations among statistical packages for the whiskers.
#Kotlin
Kotlin
// version 1.2.21   fun median(x: DoubleArray, start: Int, endInclusive: Int): Double { val size = endInclusive - start + 1 require (size > 0) { "Array slice cannot be empty" } val m = start + size / 2 return if (size % 2 == 1) x[m] else (x[m - 1] + x[m]) / 2.0 }   fun fivenum(x: DoubleArray): DoubleArray { require(x.none { it.isNaN() }) { "Unable to deal with arrays containing NaN" } val result = DoubleArray(5) x.sort() result[0] = x[0] result[2] = median(x, 0, x.size - 1) result[4] = x[x.lastIndex] val m = x.size / 2 var lowerEnd = if (x.size % 2 == 1) m else m - 1 result[1] = median(x, 0, lowerEnd) result[3] = median(x, m, x.size - 1) return result }   fun main(args: Array<String>) { var xl = listOf( doubleArrayOf(15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0), doubleArrayOf(36.0, 40.0, 7.0, 39.0, 41.0, 15.0), doubleArrayOf( 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 ) ) xl.forEach { println("${fivenum(it).asList()}\n") } }
http://rosettacode.org/wiki/Find_the_missing_permutation
Find the missing permutation
ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB Listed above are   all-but-one   of the permutations of the symbols   A,   B,   C,   and   D,   except   for one permutation that's   not   listed. Task Find that missing permutation. Methods Obvious method: enumerate all permutations of A, B, C, and D, and then look for the missing permutation. alternate method: Hint: if all permutations were shown above, how many times would A appear in each position? What is the parity of this number? another alternate method: Hint: if you add up the letter values of each column, does a missing letter A, B, C, and D from each column cause the total value for each column to be unique? Related task   Permutations)
#ALGOL_68
ALGOL 68
BEGIN # find the missing permutation in a list using the XOR method of the Raku sample # # the list to find the missing permutation of # []STRING list = ( "ABCD", "CABD", "ACDB", "DACB", "BCDA" , "ACBD", "ADCB", "CDAB", "DABC", "BCAD" , "CADB", "CDBA", "CBAD", "ABDC", "ADBC" , "BDCA", "DCBA", "BACD", "BADC", "BDAC" , "CBDA", "DBCA", "DCAB" ); # sets b to b XOR v and returns b # PRIO XORAB = 1; OP XORAB = ( REF BITS b, BITS v )REF BITS: b := b XOR v;   # loop through each character of each element of the list # FOR c pos FROM LWB list[ LWB list ] TO UPB list[ LWB list ] DO # loop through each element of the list # BITS m := 16r0; FOR l pos FROM LWB list TO UPB list DO m XORAB BIN ABS list[ l pos ][ c pos ] OD; print( ( REPR ABS m ) ) OD END
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month
Find the last Sunday of each month
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 2013-05-26 2013-06-30 2013-07-28 2013-08-25 2013-09-29 2013-10-27 2013-11-24 2013-12-29 Related tasks Day of the week Five weekends Last Friday of each month
#AWK
AWK
  # syntax: GAWK -f FIND_THE_LAST_SUNDAY_OF_EACH_MONTH.AWK [year] BEGIN { split("31,28,31,30,31,30,31,31,30,31,30,31",daynum_array,",") # days per month in non leap year year = (ARGV[1] == "") ? strftime("%Y") : ARGV[1] if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) { daynum_array[2] = 29 } for (m=1; m<=12; m++) { for (d=daynum_array[m]; d>=1; d--) { if (strftime("%a",mktime(sprintf("%d %d %d 0 0 0",year,m,d))) == "Sun") { printf("%04d-%02d-%02d\n",year,m,d) break } } } exit(0) }  
http://rosettacode.org/wiki/Find_the_intersection_of_two_lines
Find the intersection of two lines
[1] Task Find the point of intersection of two lines in 2D. The 1st line passes though   (4,0)   and   (6,10) . The 2nd line passes though   (0,3)   and   (10,7) .
#BASIC
BASIC
0 A = 1:B = 2: HOME : VTAB 21: HGR : HCOLOR= 3: FOR L = A TO B: READ X1(L),Y1(L),X2(L),Y2(L): HPLOT X1(L),Y1(L) TO X2(L),Y2(L): NEXT : DATA4,0,6,10,0,3,10,7 1 GOSUB 5: IF NAN THEN PRINT "THE LINES DO NOT INTERSECT, THEY ARE EITHER PARALLEL OR CO-INCIDENT." 2 IF NOT NAN THEN PRINT "POINT OF INTERSECTION : "X" "Y 3 PRINT CHR$ (13)"HIT ANY KEY TO END PROGRAM": IF NOT NAN THEN FOR K = 0 TO 1 STEP 0:C = C = 0: HCOLOR= 3 * C: HPLOT X,Y: FOR I = 1 TO 30:K = PEEK (49152) > 127: NEXT I,K 4 GET K$: TEXT : END 5 FOR L = A TO B:S$(L) = "NAN": IF X1(L) < > X2(L) THEN S(L) = (Y1(L) - Y2(L)) / (X1(L) - X2(L)):S$(L) = STR$ (S(L)) 6 NEXT L:NAN = S$(A) = S$(B): IF NAN THEN RETURN 7 IF S$(A) = "NAN" AND S$(B) < > "NAN" THEN X = X1(A):Y = (X1(A) - X1(B)) * S(B) + Y1(B): RETURN 8 IF S$(B) = "NAN" AND S$(A) < > "NAN" THEN X = X1(B):Y = (X1(B) - X1(A)) * S(A) + Y1(A): RETURN 9 X = (S(A) * X1(A) - S(B) * X1(B) + Y1(B) - Y1(A)) / (S(A) - S(B)):Y = S(B) * (X - X1(B)) + Y1(B): RETURN
http://rosettacode.org/wiki/Find_the_intersection_of_a_line_with_a_plane
Find the intersection of a line with a plane
Finding the intersection of an infinite ray with a plane in 3D is an important topic in collision detection. Task Find the point of intersection for the infinite ray with direction   (0, -1, -1)   passing through position   (0, 0, 10)   with the infinite plane with a normal vector of   (0, 0, 1)   and which passes through [0, 0, 5].
#AutoHotkey
AutoHotkey
/* ; https://en.wikipedia.org/wiki/Line%E2%80%93plane_intersection#Algebraic_form l = line vector lo = point on the line n = plane normal vector Po = point on the plane   if (l . n) = 0 ; line and plane are parallel. if (Po - lo) . n = 0 ; line is contained in the plane.   (P - Po) . n = 0 ; vector equation of plane. P = lo + l * d ; vector equation of line. ((lo + l * d) - Po) . n = 0 ; Substitute line into plane equation. (l . n) * d + (lo - Po) . n = 0 ; Expanding. d = ((Po - lo) . n) / (l . n) ; solving for d. P = lo + l * ((Po - lo) . n) / (l . n) ; solving P. */   intersectPoint(l, lo, n, Pn ){ if (Vector_dot(Vector_sub(Pn, lo), n) = 0) ; line is contained in the plane return [1] if (Vector_dot(l, n) = 0) ; line and plane are parallel return [0] diff := Vector_Sub(Pn, lo) ; (Po - lo) prod1 := Vector_Dot(diff, n) ; ((Po - lo) . n) prod2 := Vector_Dot(l, n) ; (l . n) d := prod1 / prod2 ; d = ((Po - lo) . n) / (l . n) return Vector_Add(lo, Vector_Mul(l, d)) ; P = lo + l * d }   Vector_Add(v, w){ return [v.1+w.1, v.2+w.2, v.3+w.3] } Vector_Sub(v, w){ return [v.1-w.1, v.2-w.2, v.3-w.3] } Vector_Mul(v, s){ return [s*v.1, s*v.2, s*v.3] } Vector_Dot(v, w){ return v.1*w.1 + v.2*w.2 + v.3*w.3 }
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) The   FizzBuzz   problem was presented as the lowest level of comprehension required to illustrate adequacy. Also see   (a blog)   dont-overthink-fizzbuzz   (a blog)   fizzbuzz-the-programmers-stairway-to-heaven
#ACL2
ACL2
(defun fizzbuzz-r (i) (declare (xargs :measure (nfix (- 100 i)))) (prog2$ (cond ((= (mod i 15) 0) (cw "FizzBuzz~%")) ((= (mod i 5) 0) (cw "Buzz~%")) ((= (mod i 3) 0) (cw "Fizz~%")) (t (cw "~x0~%" i))) (if (zp (- 100 i)) nil (fizzbuzz-r (1+ i)))))   (defun fizzbuzz () (fizzbuzz-r 1))
http://rosettacode.org/wiki/Five_weekends
Five weekends
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays. Task Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar). Show the number of months with this property (there should be 201). Show at least the first and last five dates, in order. Algorithm suggestions Count the number of Fridays, Saturdays, and Sundays in every month. Find all of the 31-day months that begin on Friday. Extra credit Count and/or show all of the years which do not have at least one five-weekend month (there should be 29). Related tasks Day of the week Last Friday of each month Find last sunday of each month
#C.23
C#
using System;   namespace _5_Weekends { class Program { const int FIRST_YEAR = 1900; const int LAST_YEAR = 2100; static int[] _31_MONTHS = { 1, 3, 5, 7, 8, 10, 12 };   static void Main(string[] args) { int totalNum = 0; int totalNo5Weekends = 0;   for (int year = FIRST_YEAR; year <= LAST_YEAR; year++) { bool has5Weekends = false;   foreach (int month in _31_MONTHS) { DateTime firstDay = new DateTime(year, month, 1); if (firstDay.DayOfWeek == DayOfWeek.Friday) { totalNum++; has5Weekends = true; Console.WriteLine(firstDay.ToString("yyyy - MMMM")); } }   if (!has5Weekends) totalNo5Weekends++; } Console.WriteLine("Total 5-weekend months between {0} and {1}: {2}", FIRST_YEAR, LAST_YEAR, totalNum); Console.WriteLine("Total number of years with no 5-weekend months {0}", totalNo5Weekends); } } }
http://rosettacode.org/wiki/First_perfect_square_in_base_n_with_n_unique_digits
First perfect square in base n with n unique digits
Find the first perfect square in a given base N that has at least N digits and exactly N significant unique digits when expressed in base N. E.G. In base 10, the first perfect square with at least 10 unique digits is 1026753849 (32043²). You may use analytical methods to reduce the search space, but the code must do a search. Do not use magic numbers or just feed the code the answer to verify it is correct. Task Find and display here, on this page, the first perfect square in base N, with N significant unique digits when expressed in base N, for each of base 2 through 12. Display each number in the base N for which it was calculated. (optional) Do the same for bases 13 through 16. (stretch goal) Continue on for bases 17 - ?? (Big Integer math) See also OEIS A260182: smallest square that is pandigital in base n. Related task Casting out nines
#J
J
  pandigital=: [ = [: # [: ~. #.inv NB. BASE pandigital Y  
http://rosettacode.org/wiki/First_perfect_square_in_base_n_with_n_unique_digits
First perfect square in base n with n unique digits
Find the first perfect square in a given base N that has at least N digits and exactly N significant unique digits when expressed in base N. E.G. In base 10, the first perfect square with at least 10 unique digits is 1026753849 (32043²). You may use analytical methods to reduce the search space, but the code must do a search. Do not use magic numbers or just feed the code the answer to verify it is correct. Task Find and display here, on this page, the first perfect square in base N, with N significant unique digits when expressed in base N, for each of base 2 through 12. Display each number in the base N for which it was calculated. (optional) Do the same for bases 13 through 16. (stretch goal) Continue on for bases 17 - ?? (Big Integer math) See also OEIS A260182: smallest square that is pandigital in base n. Related task Casting out nines
#Java
Java
import java.math.BigInteger; import java.time.Duration; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set;   public class Program { static final String ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz|"; static byte base, bmo, blim, ic; static long st0; static BigInteger bllim, threshold; static Set<Byte> hs = new HashSet<>(); static Set<Byte> o = new HashSet<>(); static final char[] chars = ALPHABET.toCharArray(); static List<BigInteger> limits; static String ms;   static int indexOf(char c) { for (int i = 0; i < chars.length; ++i) { if (chars[i] == c) { return i; } } return -1; }   // convert BigInteger to string using current base static String toStr(BigInteger b) { BigInteger bigBase = BigInteger.valueOf(base); StringBuilder res = new StringBuilder(); while (b.compareTo(BigInteger.ZERO) > 0) { BigInteger[] divRem = b.divideAndRemainder(bigBase); res.append(chars[divRem[1].intValue()]); b = divRem[0]; } return res.toString(); }   // check for a portion of digits, bailing if uneven static boolean allInQS(BigInteger b) { BigInteger bigBase = BigInteger.valueOf(base); int c = ic; hs.clear(); hs.addAll(o); while (b.compareTo(bllim) > 0) { BigInteger[] divRem = b.divideAndRemainder(bigBase); hs.add(divRem[1].byteValue()); c++;   if (c > hs.size()) { return false; } b = divRem[0]; } return true; }   // check for a portion of digits, all the way to the end static boolean allInS(BigInteger b) { BigInteger bigBase = BigInteger.valueOf(base); hs.clear(); hs.addAll(o); while (b.compareTo(bllim) > 0) { BigInteger[] divRem = b.divideAndRemainder(bigBase); hs.add(divRem[1].byteValue()); b = divRem[0]; } return hs.size() == base; }   // check for all digits, bailing if uneven static boolean allInQ(BigInteger b) { BigInteger bigBase = BigInteger.valueOf(base); int c = 0; hs.clear(); while (b.compareTo(BigInteger.ZERO) > 0) { BigInteger[] divRem = b.divideAndRemainder(bigBase); hs.add(divRem[1].byteValue()); c++; if (c > hs.size()) { return false; } b = divRem[0]; } return true; }   // check for all digits, all the way to the end static boolean allIn(BigInteger b) { BigInteger bigBase = BigInteger.valueOf(base); hs.clear(); while (b.compareTo(BigInteger.ZERO) > 0) { BigInteger[] divRem = b.divideAndRemainder(bigBase); hs.add(divRem[1].byteValue()); b = divRem[0]; } return hs.size() == base; }   // parse a string into a BigInteger, using current base static BigInteger to10(String s) { BigInteger bigBase = BigInteger.valueOf(base); BigInteger res = BigInteger.ZERO; for (int i = 0; i < s.length(); ++i) { char c = s.charAt(i); int idx = indexOf(c); BigInteger bigIdx = BigInteger.valueOf(idx); res = res.multiply(bigBase).add(bigIdx); } return res; }   // returns the minimum value string, optionally inserting extra digit static String fixup(int n) { String res = ALPHABET.substring(0, base); if (n > 0) { StringBuilder sb = new StringBuilder(res); sb.insert(n, n); res = sb.toString(); } return "10" + res.substring(2); }   // checks the square against the threshold, advances various limits when needed static void check(BigInteger sq) { if (sq.compareTo(threshold) > 0) { o.remove((byte) indexOf(ms.charAt(blim))); blim--; ic--; threshold = limits.get(bmo - blim - 1); bllim = to10(ms.substring(0, blim + 1)); } }   // performs all the calculations for the current base static void doOne() { limits = new ArrayList<>(); bmo = (byte) (base - 1); byte dr = 0; if ((base & 1) == 1) { dr = (byte) (base >> 1); } o.clear(); blim = 0; byte id = 0; int inc = 1; long st = System.nanoTime(); byte[] sdr = new byte[bmo]; byte rc = 0; for (int i = 0; i < bmo; i++) { sdr[i] = (byte) ((i * i) % bmo); rc += sdr[i] == dr ? (byte) 1 : (byte) 0; sdr[i] += sdr[i] == 0 ? bmo : (byte) 0; } long i = 0; if (dr > 0) { id = base; for (i = 1; i <= dr; i++) { if (sdr[(int) i] >= dr) { if (id > sdr[(int) i]) { id = sdr[(int) i]; } } } id -= dr; i = 0; } ms = fixup(id); BigInteger sq = to10(ms); BigInteger rt = BigInteger.valueOf((long) (Math.sqrt(sq.doubleValue()) + 1)); sq = rt.multiply(rt); if (base > 9) { for (int j = 1; j < base; j++) { limits.add(to10(ms.substring(0, j) + String.valueOf(chars[bmo]).repeat(base - j + (rc > 0 ? 0 : 1)))); } Collections.reverse(limits); while (sq.compareTo(limits.get(0)) < 0) { rt = rt.add(BigInteger.ONE); sq = rt.multiply(rt); } } BigInteger dn = rt.shiftLeft(1).add(BigInteger.ONE); BigInteger d = BigInteger.ONE; if (base > 3 && rc > 0) { while (sq.remainder(BigInteger.valueOf(bmo)).compareTo(BigInteger.valueOf(dr)) != 0) { rt = rt.add(BigInteger.ONE); sq = sq.add(dn); dn = dn.add(BigInteger.TWO); } // aligns sq to dr inc = bmo / rc; if (inc > 1) { dn = dn.add(rt.multiply(BigInteger.valueOf(inc - 2)).subtract(BigInteger.ONE)); d = BigInteger.valueOf(inc * inc); } dn = dn.add(dn).add(d); } d = d.shiftLeft(1); if (base > 9) { blim = 0; while (sq.compareTo(limits.get(bmo - blim - 1)) < 0) { blim++; } ic = (byte) (blim + 1); threshold = limits.get(bmo - blim - 1); if (blim > 0) { for (byte j = 0; j <= blim; j++) { o.add((byte) indexOf(ms.charAt(j))); } } if (blim > 0) { bllim = to10(ms.substring(0, blim + 1)); } else { bllim = BigInteger.ZERO; } if (base > 5 && rc > 0) while (!allInQS(sq)) { sq = sq.add(dn); dn = dn.add(d); i += 1; check(sq); } else { while (!allInS(sq)) { sq = sq.add(dn); dn = dn.add(d); i += 1; check(sq); } } } else { if (base > 5 && rc > 0) { while (!allInQ(sq)) { sq = sq.add(dn); dn = dn.add(d); i += 1; } } else { while (!allIn(sq)) { sq = sq.add(dn); dn = dn.add(d); i += 1; } } }   rt = rt.add(BigInteger.valueOf(i * inc)); long delta1 = System.nanoTime() - st; Duration dur1 = Duration.ofNanos(delta1); long delta2 = System.nanoTime() - st0; Duration dur2 = Duration.ofNanos(delta2); System.out.printf( "%3d  %2d  %2s %20s -> %-40s %10d %9s  %9s\n", base, inc, (id > 0 ? ALPHABET.substring(id, id + 1) : " "), toStr(rt), toStr(sq), i, format(dur1), format(dur2) ); }   private static String format(Duration d) { int minP = d.toMinutesPart(); int secP = d.toSecondsPart(); int milP = d.toMillisPart(); return String.format("%02d:%02d.%03d", minP, secP, milP); }   public static void main(String[] args) { System.out.println("base inc id root square test count time total"); st0 = System.nanoTime(); for (base = 2; base < 28; ++base) { doOne(); } } }
http://rosettacode.org/wiki/First-class_functions
First-class functions
A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming: Create new functions from preexisting functions at run-time Store functions in collections Use functions as arguments to other functions Use functions as return values of other functions Task Write a program to create an ordered collection A of functions of a real number. At least one function should be built-in and at least one should be user-defined; try using the sine, cosine, and cubing functions. Fill another collection B with the inverse of each function in A. Implement function composition as in Functional Composition. Finally, demonstrate that the result of applying the composition of each function in A and its inverse in B to a value, is the original value. (Within the limits of computational accuracy). (A solution need not actually call the collections "A" and "B". These names are only used in the preceding paragraph for clarity.) Related task First-class Numbers
#CoffeeScript
CoffeeScript
# Functions as values of a variable cube = (x) -> Math.pow x, 3 cuberoot = (x) -> Math.pow x, 1 / 3   # Higher order function compose = (f, g) -> (x) -> f g(x)   # Storing functions in a array fun = [Math.sin, Math.cos, cube] inv = [Math.asin, Math.acos, cuberoot]   # Applying the composition to 0.5 console.log compose(inv[i], fun[i])(0.5) for i in [0..2]​​​​​​​
http://rosettacode.org/wiki/Forest_fire
Forest fire
This page uses content from Wikipedia. The original article was at Forest-fire model. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Implement the Drossel and Schwabl definition of the forest-fire model. It is basically a 2D   cellular automaton   where each cell can be in three distinct states (empty, tree and burning) and evolves according to the following rules (as given by Wikipedia) A burning cell turns into an empty cell A tree will burn if at least one neighbor is burning A tree ignites with probability   f   even if no neighbor is burning An empty space fills with a tree with probability   p Neighborhood is the   Moore neighborhood;   boundary conditions are so that on the boundary the cells are always empty ("fixed" boundary condition). At the beginning, populate the lattice with empty and tree cells according to a specific probability (e.g. a cell has the probability 0.5 to be a tree). Then, let the system evolve. Task's requirements do not include graphical display or the ability to change parameters (probabilities   p   and   f )   through a graphical or command line interface. Related tasks   See   Conway's Game of Life   See   Wireworld.
#Icon_and_Unicon
Icon and Unicon
link graphics,printf   $define EDGE 0 $define EMPTY 1 $define TREE 2 $define FIRE 3   global Colours,Width,Height,ProbTree,ProbFire,ProbInitialTree,Forest,oldForest   procedure main() # forest fire   Height := 400 # Window height Width := 400 # Window width ProbInitialTree := .10 # intial probability of trees ProbTree := .01 # ongoing probability of trees ProbFire := ProbTree/50. # probability of fire Rounds := 500 # rounds to evolve   setup_forest() every 1 to Rounds do { show_forest() evolve_forest() } printf("Forest fire %d x %d rounds=%d p.initial=%r p/f=%r/%r fps=%r\n", Width,Height,Rounds,ProbInitialTree,ProbTree,ProbFire, Rounds/(&time/1000.)) # stats WDone() end   procedure setup_forest() #: setup the forest   Colours := table() # define colours Colours[EDGE] := "black" Colours[EMPTY] := "grey" Colours[TREE] := "green" Colours[FIRE] := "red"   WOpen("label=Forest Fire", "bg=black", "size=" || Width+2 || "," || Height+2) | # add for border stop("Unable to open Window") every !(Forest := list(Height)) := list(Width,EMPTY) # default every ( Forest[1,1 to Width] | Forest[Height,1 to Width] | Forest[1 to Height,1] | Forest[1 to Height,Width] ) := EDGE every r := 2 to Height-1 & c := 2 to Width-1 do if probability(ProbInitialTree) then Forest[r,c] := TREE end   procedure show_forest() #: show Forest - drawn changes only every r := 2 to *Forest-1 & c := 2 to *Forest[r]-1 do if /oldForest | oldForest[r,c] ~= Forest[r,c] then { WAttrib("fg=" || Colours[Forest[r,c]]) DrawPoint(r,c) } end   procedure evolve_forest() #: evolve forest old := oldForest := list(*Forest) # freeze copy every old[i := 1 to *Forest] := copy(Forest[i]) # deep copy   every r := 2 to *Forest-1 & c := 2 to *Forest[r]-1 do Forest[r,c] := case old[r,c] of { # apply rules FIRE : EMPTY TREE : if probability(ProbFire) | ( old[r-1, c-1 to c+1] | old[r,c-1|c+1] | old[r+1,c-1 to c+1] ) = FIRE then FIRE EMPTY: if probability(ProbTree) then TREE } end   procedure probability(P) #: succeed with probability P if ?0 <= P then return end
http://rosettacode.org/wiki/First_class_environments
First class environments
According to Wikipedia, "In computing, a first-class object ... is an entity that can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable". Often this term is used in the context of "first class functions". In an analogous way, a programming language may support "first class environments". The environment is minimally, the set of variables accessible to a statement being executed. Change the environments and the same statement could produce different results when executed. Often an environment is captured in a closure, which encapsulates a function together with an environment. That environment, however, is not first-class, as it cannot be created, passed etc. independently from the function's code. Therefore, a first class environment is a set of variable bindings which can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable. It is like a closure without code. A statement must be able to be executed within a stored first class environment and act according to the environment variable values stored within. Task Build a dozen environments, and a single piece of code to be run repeatedly in each of these environments. Each environment contains the bindings for two variables:   a value in the Hailstone sequence, and   a count which is incremented until the value drops to 1. The initial hailstone values are 1 through 12, and the count in each environment is zero. When the code runs, it calculates the next hailstone step in the current environment (unless the value is already 1) and counts the steps. Then it prints the current value in a tabular form. When all hailstone values dropped to 1, processing stops, and the total number of hailstone steps for each environment is printed.
#Racket
Racket
  #lang racket   (define namespaces (for/list ([i (in-range 1 13)]) (define ns (make-base-namespace)) (eval `(begin (define N ,i) (define count 0)) ns) ns))   (define (get-var-values name) (map (curry namespace-variable-value name #t #f) namespaces))   (define code '(when (> N 1) (set! N (if (even? N) (/ N 2) (+ 1 (* N 3)))) (set! count (add1 count))))   (define (show-nums nums) (for ([n nums]) (display (~a n #:width 4 #:align 'right))) (newline))   (let loop () (define Ns (get-var-values 'N)) (show-nums Ns) (unless (andmap (λ(n) (= n 1)) Ns) (for ([ns namespaces]) (eval code ns)) (loop))) (displayln (make-string (* 4 12) #\=)) (show-nums (get-var-values 'count))  
http://rosettacode.org/wiki/First_class_environments
First class environments
According to Wikipedia, "In computing, a first-class object ... is an entity that can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable". Often this term is used in the context of "first class functions". In an analogous way, a programming language may support "first class environments". The environment is minimally, the set of variables accessible to a statement being executed. Change the environments and the same statement could produce different results when executed. Often an environment is captured in a closure, which encapsulates a function together with an environment. That environment, however, is not first-class, as it cannot be created, passed etc. independently from the function's code. Therefore, a first class environment is a set of variable bindings which can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable. It is like a closure without code. A statement must be able to be executed within a stored first class environment and act according to the environment variable values stored within. Task Build a dozen environments, and a single piece of code to be run repeatedly in each of these environments. Each environment contains the bindings for two variables:   a value in the Hailstone sequence, and   a count which is incremented until the value drops to 1. The initial hailstone values are 1 through 12, and the count in each environment is zero. When the code runs, it calculates the next hailstone step in the current environment (unless the value is already 1) and counts the steps. Then it prints the current value in a tabular form. When all hailstone values dropped to 1, processing stops, and the total number of hailstone steps for each environment is printed.
#Raku
Raku
my $calculator = sub ($n is rw) { return ($n == 1) ?? 1 !! $n %% 2 ?? $n div 2 !! $n * 3 + 1 };   sub next (%this, &get_next) { return %this if %this.<value> == 1; %this.<value>.=&get_next; %this.<count>++; return %this; };   my @hailstones = map { %(value => $_, count => 0) }, 1 .. 12;   while not all( map { $_.<value> }, @hailstones ) == 1 { say [~] map { $_.<value>.fmt("%4s") }, @hailstones; @hailstones[$_].=&next($calculator) for ^@hailstones; }   say 'Counts';   say [~] map { $_.<count>.fmt("%4s") }, @hailstones;
http://rosettacode.org/wiki/Flatten_a_list
Flatten a list
Task Write a function to flatten the nesting in an arbitrary list of values. Your program should work on the equivalent of this list: [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []] Where the correct result would be the list: [1, 2, 3, 4, 5, 6, 7, 8] Related task   Tree traversal
#E
E
def flatten(nested) { def flat := [].diverge() def recur(x) { switch (x) { match list :List { for elem in list { recur(elem) } } match other { flat.push(other) } } } recur(nested) return flat.snapshot() }
http://rosettacode.org/wiki/Flipping_bits_game
Flipping bits game
The game Given an   N×N   square array of zeroes or ones in an initial configuration,   and a target configuration of zeroes and ones. The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered columns at once   (as one move). In an inversion.   any  1  becomes  0,   and any  0  becomes  1  for that whole row or column. Task Create a program to score for the Flipping bits game. The game should create an original random target configuration and a starting configuration. Ensure that the starting position is never the target position. The target position must be guaranteed as reachable from the starting position.   (One possible way to do this is to generate the start position by legal flips from a random target position.   The flips will always be reversible back to the target from the given start position). The number of moves taken so far should be shown. Show an example of a short game here, on this page, for a   3×3   array of bits.
#Python
Python
""" Given a %i by %i sqare array of zeroes or ones in an initial configuration, and a target configuration of zeroes and ones The task is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered columns at once. In an inversion any 1 becomes 0 and any 0 becomes 1 for that whole row or column.   """   from random import randrange from copy import deepcopy from string import ascii_lowercase     try: # 2to3 fix input = raw_input except: pass   N = 3 # N x N Square arrray   board = [[0]* N for i in range(N)]   def setbits(board, count=1): for i in range(count): board[randrange(N)][randrange(N)] ^= 1   def shuffle(board, count=1): for i in range(count): if randrange(0, 2): fliprow(randrange(N)) else: flipcol(randrange(N))     def pr(board, comment=''): print(str(comment)) print(' ' + ' '.join(ascii_lowercase[i] for i in range(N))) print(' ' + '\n '.join(' '.join(['%2s' % j] + [str(i) for i in line]) for j, line in enumerate(board, 1)))   def init(board): setbits(board, count=randrange(N)+1) target = deepcopy(board) while board == target: shuffle(board, count=2 * N) prompt = ' X, T, or 1-%i / %s-%s to flip: ' % (N, ascii_lowercase[0], ascii_lowercase[N-1]) return target, prompt   def fliprow(i): board[i-1][:] = [x ^ 1 for x in board[i-1] ]   def flipcol(i): for row in board: row[i] ^= 1   if __name__ == '__main__': print(__doc__ % (N, N)) target, prompt = init(board) pr(target, 'Target configuration is:') print('') turns = 0 while board != target: turns += 1 pr(board, '%i:' % turns) ans = input(prompt).strip() if (len(ans) == 1 and ans in ascii_lowercase and ascii_lowercase.index(ans) < N): flipcol(ascii_lowercase.index(ans)) elif ans and all(ch in '0123456789' for ch in ans) and 1 <= int(ans) <= N: fliprow(int(ans)) elif ans == 'T': pr(target, 'Target configuration is:') turns -= 1 elif ans == 'X': break else: print(" I don't understand %r... Try again. " "(X to exit or T to show target)\n" % ans[:9]) turns -= 1 else: print('\nWell done!\nBye.')
http://rosettacode.org/wiki/First_power_of_2_that_has_leading_decimal_digits_of_12
First power of 2 that has leading decimal digits of 12
(This task is taken from a   Project Euler   problem.) (All numbers herein are expressed in base ten.) 27   =   128   and   7   is the first power of   2   whose leading decimal digits are   12. The next power of   2   whose leading decimal digits are   12   is   80, 280   =   1208925819614629174706176. Define     p(L,n)     to be the nth-smallest value of   j   such that the base ten representation of   2j   begins with the digits of   L . So p(12, 1) = 7 and p(12, 2) = 80 You are also given that: p(123, 45)   =   12710 Task   find:   p(12, 1)   p(12, 2)   p(123, 45)   p(123, 12345)   p(123, 678910)   display the results here, on this page.
#Python
Python
from math import log, modf, floor   def p(l, n, pwr=2): l = int(abs(l)) digitcount = floor(log(l, 10)) log10pwr = log(pwr, 10) raised, found = -1, 0 while found < n: raised += 1 firstdigits = floor(10**(modf(log10pwr * raised)[0] + digitcount)) if firstdigits == l: found += 1 return raised     if __name__ == '__main__': for l, n in [(12, 1), (12, 2), (123, 45), (123, 12345), (123, 678910)]: print(f"p({l}, {n}) =", p(l, n))
http://rosettacode.org/wiki/First-class_functions/Use_numbers_analogously
First-class functions/Use numbers analogously
In First-class functions, a language is showing how its manipulation of functions is similar to its manipulation of other types. This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers. Write a program to create an ordered collection of a mixture of literally typed and expressions producing a real number, together with another ordered collection of their multiplicative inverses. Try and use the following pseudo-code to generate the numbers for the ordered collections: x = 2.0 xi = 0.5 y = 4.0 yi = 0.25 z = x + y zi = 1.0 / ( x + y ) Create a function multiplier, that given two numbers as arguments returns a function that when called with one argument, returns the result of multiplying the two arguments to the call to multiplier that created it and the argument in the call: new_function = multiplier(n1,n2) # where new_function(m) returns the result of n1 * n2 * m Applying the multiplier of a number and its inverse from the two ordered collections of numbers in pairs, show that the result in each case is one. Compare and contrast the resultant program with the corresponding entry in First-class functions. They should be close. To paraphrase the task description: Do what was done before, but with numbers rather than functions
#Oz
Oz
declare   [X Y Z] = [2.0 4.0 Z=X+Y] [XI YI ZI] = [0.5 0.25 1.0/(X+Y)]   fun {Multiplier A B} fun {$ M} A * B * M end end   in   for N in [X Y Z] I in [XI YI ZI] do {Show {{Multiplier N I} 0.5}} end
http://rosettacode.org/wiki/First-class_functions/Use_numbers_analogously
First-class functions/Use numbers analogously
In First-class functions, a language is showing how its manipulation of functions is similar to its manipulation of other types. This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers. Write a program to create an ordered collection of a mixture of literally typed and expressions producing a real number, together with another ordered collection of their multiplicative inverses. Try and use the following pseudo-code to generate the numbers for the ordered collections: x = 2.0 xi = 0.5 y = 4.0 yi = 0.25 z = x + y zi = 1.0 / ( x + y ) Create a function multiplier, that given two numbers as arguments returns a function that when called with one argument, returns the result of multiplying the two arguments to the call to multiplier that created it and the argument in the call: new_function = multiplier(n1,n2) # where new_function(m) returns the result of n1 * n2 * m Applying the multiplier of a number and its inverse from the two ordered collections of numbers in pairs, show that the result in each case is one. Compare and contrast the resultant program with the corresponding entry in First-class functions. They should be close. To paraphrase the task description: Do what was done before, but with numbers rather than functions
#PARI.2FGP
PARI/GP
multiplier(n1,n2)={ x -> n1 * n2 * x };   test()={ my(x = 2.0, xi = 0.5, y = 4.0, yi = 0.25, z = x + y, zi = 1.0 / ( x + y )); print(multiplier(x,xi)(0.5)); print(multiplier(y,yi)(0.5)); print(multiplier(z,zi)(0.5)); };
http://rosettacode.org/wiki/Flow-control_structures
Flow-control structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task Document common flow-control structures. One common example of a flow-control structure is the   goto   construct. Note that   Conditional Structures   and   Loop Structures   have their own articles/categories. Related tasks   Conditional Structures   Loop Structures
#PureBasic
PureBasic
If OpenConsole() top: i = i + 1 PrintN("Hello world.") If i < 10 Goto top EndIf   Print(#CRLF$ + #CRLF$ + "Press ENTER to exit") Input() CloseConsole() EndIf
http://rosettacode.org/wiki/Flow-control_structures
Flow-control structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task Document common flow-control structures. One common example of a flow-control structure is the   goto   construct. Note that   Conditional Structures   and   Loop Structures   have their own articles/categories. Related tasks   Conditional Structures   Loop Structures
#Python
Python
# Search for an odd factor of a using brute force: for i in range(n): if (n%2) == 0: continue if (n%i) == 0: result = i break else: result = None print "No odd factors found"
http://rosettacode.org/wiki/Floyd%27s_triangle
Floyd's triangle
Floyd's triangle   lists the natural numbers in a right triangle aligned to the left where the first row is   1     (unity) successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above. The first few lines of a Floyd triangle looks like this: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Task Write a program to generate and display here the first   n   lines of a Floyd triangle. (Use   n=5   and   n=14   rows). Ensure that when displayed in a mono-space font, the numbers line up in vertical columns as shown and that only one space separates numbers of the last row.
#Factor
Factor
USING: io kernel math math.functions math.ranges prettyprint sequences ; IN: rosetta-code.floyds-triangle   : floyd. ( n -- ) [ dup 1 - * 2 / 1 + dup 1 ] [ [1,b] ] bi [ [ 2dup [ log10 1 + >integer ] bi@ - [ " " write ] times dup pprint bl [ 1 + ] bi@ ] times nl [ drop dup ] dip ] each nl 3drop ;   5 14 [ floyd. ] bi@
http://rosettacode.org/wiki/Floyd%27s_triangle
Floyd's triangle
Floyd's triangle   lists the natural numbers in a right triangle aligned to the left where the first row is   1     (unity) successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above. The first few lines of a Floyd triangle looks like this: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Task Write a program to generate and display here the first   n   lines of a Floyd triangle. (Use   n=5   and   n=14   rows). Ensure that when displayed in a mono-space font, the numbers line up in vertical columns as shown and that only one space separates numbers of the last row.
#Forth
Forth
: lastn ( rows -- n ) dup 1- * 2/ ; : width ( n -- n ) s>f flog ftrunc f>s 2 + ;   : triangle ( rows -- ) dup lastn 0 rot ( last 0 rows ) 0 do over cr i 1+ 0 do 1+ swap 1+ swap 2dup width u.r loop drop loop 2drop ;  
http://rosettacode.org/wiki/Floyd-Warshall_algorithm
Floyd-Warshall algorithm
The Floyd–Warshall algorithm is an algorithm for finding shortest paths in a weighted graph with positive or negative edge weights. Task Find the lengths of the shortest paths between all pairs of vertices of the given directed graph. Your code may assume that the input has already been checked for loops, parallel edges and negative cycles. Print the pair, the distance and (optionally) the path. Example pair dist path 1 -> 2 -1 1 -> 3 -> 4 -> 2 1 -> 3 -2 1 -> 3 1 -> 4 0 1 -> 3 -> 4 2 -> 1 4 2 -> 1 2 -> 3 2 2 -> 1 -> 3 2 -> 4 4 2 -> 1 -> 3 -> 4 3 -> 1 5 3 -> 4 -> 2 -> 1 3 -> 2 1 3 -> 4 -> 2 3 -> 4 2 3 -> 4 4 -> 1 3 4 -> 2 -> 1 4 -> 2 -1 4 -> 2 4 -> 3 1 4 -> 2 -> 1 -> 3 See also Floyd-Warshall Algorithm - step by step guide (youtube)
#OCaml
OCaml
(* Floyd-Warshall algorithm.   See https://en.wikipedia.org/w/index.php?title=Floyd%E2%80%93Warshall_algorithm&oldid=1082310013 *)   module Square_array =   (* Square arrays with 1-based indexing. *)   struct type 'a t = { n : int; r : 'a Array.t }   let make n fill = let r = Array.make (n * n) fill in { n = n; r = r }   let get arr (i, j) = Array.get arr.r ((i - 1) + (arr.n * (j - 1)))   let set arr (i, j) x = Array.set arr.r ((i - 1) + (arr.n * (j - 1))) x end   module Vertex =   (* A vertex is a positive integer, or 0 for the nil object. *)   struct type t = int   let nil = 0   let print_vertex u = print_int u   let rec print_directed_list lst = match lst with | [] -> () | [u] -> print_vertex u | u :: tail -> begin print_vertex u; print_string " -> "; print_directed_list tail end end   module Edge =   (* A graph edge. *)   struct type t = { u : Vertex.t; weight : Float.t; v : Vertex.t }   let make u weight v = { u = u; weight = weight; v = v } end   module Paths =   (* The "next vertex" array and its operations. *)   struct type t = Vertex.t Square_array.t   let make n = Square_array.make n Vertex.nil   let get = Square_array.get let set = Square_array.set   let path paths u v = (* Path reconstruction. In the finest tradition of the standard List module, this implementation is *not* tail recursive. *) if Square_array.get paths (u, v) = Vertex.nil then [] else let rec build_path paths u v = if u = v then [v] else let i = Square_array.get paths (u, v) in u :: build_path paths i v in build_path paths u v   let print_path paths u v = Vertex.print_directed_list (path paths u v) end   module Distances =   (* The "distance" array and its operations. *)   struct type t = Float.t Square_array.t   let make n = Square_array.make n Float.infinity   let get = Square_array.get let set = Square_array.set end   let find_max_vertex edges = (* This implementation is *not* tail recursive. *) let rec find_max = function | [] -> Vertex.nil | edge :: tail -> max (max Edge.(edge.u) Edge.(edge.v)) (find_max tail) in find_max edges   let floyd_warshall edges = (* This implementation assumes IEEE floating point. The OCaml Float module explicitly specifies 64-bit IEEE floating point. *) let _ = assert (edges <> []) in let n = find_max_vertex edges in let dist = Distances.make n in let next = Paths.make n in let rec read_edges = function | [] -> () | edge :: tail -> let u = Edge.(edge.u) in let v = Edge.(edge.v) in let weight = Edge.(edge.weight) in begin Distances.set dist (u, v) weight; Paths.set next (u, v) v; read_edges tail end in begin   (* Initialization. *)   read_edges edges; for i = 1 to n do (* Distance from a vertex to itself = 0.0 *) Distances.set dist (i, i) 0.0; Paths.set next (i, i) i done;   (* Perform the algorithm. *)   for k = 1 to n do for i = 1 to n do for j = 1 to n do let dist_ij = Distances.get dist (i, j) in let dist_ik = Distances.get dist (i, k) in let dist_kj = Distances.get dist (k, j) in let dist_ikj = dist_ik +. dist_kj in if dist_ikj < dist_ij then begin Distances.set dist (i, j) dist_ikj; Paths.set next (i, j) (Paths.get next (i, k)) end done done done;   (* Return the results, as a 3-tuple. *)   (n, dist, next)   end   let example_graph = [Edge.make 1 (-2.0) 3; Edge.make 3 (+2.0) 4; Edge.make 4 (-1.0) 2; Edge.make 2 (+4.0) 1; Edge.make 2 (+3.0) 3] ;;   let (n, dist, next) = floyd_warshall example_graph ;;   print_string " pair distance path"; print_newline (); print_string "---------------------------------------"; print_newline (); for u = 1 to n do for v = 1 to n do if u <> v then begin print_string " "; Vertex.print_directed_list [u; v]; print_string " "; Printf.printf "%4.1f" (Distances.get dist (u, v)); print_string " "; Paths.print_path next u v; print_newline () end done done ;;
http://rosettacode.org/wiki/Function_definition
Function definition
A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract from showing how functions are created and values returned). Related task   Function prototype
#Standard_ML
Standard ML
val multiply = op *
http://rosettacode.org/wiki/Function_definition
Function definition
A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract from showing how functions are created and values returned). Related task   Function prototype
#Stata
Stata
prog def multiply, return args a b return sca product=`a'*`b' end   multiply 77 13 di r(product)
http://rosettacode.org/wiki/Forward_difference
Forward difference
Task Provide code that produces a list of numbers which is the   nth  order forward difference, given a non-negative integer (specifying the order) and a list of numbers. The first-order forward difference of a list of numbers   A   is a new list   B,   where   Bn = An+1 - An. List   B   should have one fewer element as a result. The second-order forward difference of   A   will be: tdefmodule Diff do def forward(arr,i\\1) do forward(arr,[],i) end def forward([_|[]],diffs,i) do if i == 1 do IO.inspect diffs else forward(diffs,[],i-1) end end def forward([val1|[val2|vals]],diffs,i) do forward([val2|vals],diffs++[val2-val1],i) end end The same as the first-order forward difference of   B. That new list will have two fewer elements than   A   and one less than   B. The goal of this task is to repeat this process up to the desired order. For a more formal description, see the related   Mathworld article. Algorithmic options Iterate through all previous forward differences and re-calculate a new array each time. Use this formula (from Wikipedia): Δ n [ f ] ( x ) = ∑ k = 0 n ( n k ) ( − 1 ) n − k f ( x + k ) {\displaystyle \Delta ^{n}[f](x)=\sum _{k=0}^{n}{n \choose k}(-1)^{n-k}f(x+k)} (Pascal's Triangle   may be useful for this option.)
#PL.2FI
PL/I
  /* Forward differences. */ /* 23 April 2010 */ differences: procedure options (main); declare a(10) fixed(10) static initial (7, 3, 9, 250, 300, 4, 68, 72, 154, 601); declare (i, j, m, n, t, u) fixed binary;   m = hbound(a,1); get (n); if n > m then signal error; put skip edit (a) (F(7)); do i = 1 to n; t = a(i); do j = i+1 to m; u = a(j); a(j) = a(j) - t; t = u; end; put skip edit (a) (F(7)); end; put skip edit ((a(i) do i = n+1 to m)) (F(9));   end differences;  
http://rosettacode.org/wiki/Forward_difference
Forward difference
Task Provide code that produces a list of numbers which is the   nth  order forward difference, given a non-negative integer (specifying the order) and a list of numbers. The first-order forward difference of a list of numbers   A   is a new list   B,   where   Bn = An+1 - An. List   B   should have one fewer element as a result. The second-order forward difference of   A   will be: tdefmodule Diff do def forward(arr,i\\1) do forward(arr,[],i) end def forward([_|[]],diffs,i) do if i == 1 do IO.inspect diffs else forward(diffs,[],i-1) end end def forward([val1|[val2|vals]],diffs,i) do forward([val2|vals],diffs++[val2-val1],i) end end The same as the first-order forward difference of   B. That new list will have two fewer elements than   A   and one less than   B. The goal of this task is to repeat this process up to the desired order. For a more formal description, see the related   Mathworld article. Algorithmic options Iterate through all previous forward differences and re-calculate a new array each time. Use this formula (from Wikipedia): Δ n [ f ] ( x ) = ∑ k = 0 n ( n k ) ( − 1 ) n − k f ( x + k ) {\displaystyle \Delta ^{n}[f](x)=\sum _{k=0}^{n}{n \choose k}(-1)^{n-k}f(x+k)} (Pascal's Triangle   may be useful for this option.)
#Plain_English
Plain English
To add a fraction to some fraction things: Allocate memory for a fraction thing. Put the fraction into the fraction thing's fraction. Append the fraction thing to the fraction things.   To create some fraction things: Add 90-1/2 to the fraction things. Add 47/1 to the fraction things. Add 58/1 to the fraction things. Add 29/1 to the fraction things. Add 22/1 to the fraction things. Add 32/1 to the fraction things. Add 55/1 to the fraction things. Add 5/1 to the fraction things. Add 55/1 to the fraction things. Add 73-1/2 to the fraction things.   To find the difference of some fraction things: If the fraction things' count is less than 2, exit. Get a fraction thing from the fraction things. Loop. If the fraction thing's next is nil, remove the fraction thing from the fraction things; destroy the fraction thing; exit. Put the fraction thing's next's fraction minus the fraction thing's fraction into the fraction thing's fraction. Put the fraction thing's next into the fraction thing. Repeat.   To find the difference of some fraction things given an order: If a counter is past the order, exit. Find the difference of the fraction things. Repeat.   A fraction thing is a thing with a fraction.   An order is a number.   To run: Start up. Create some fraction things. Write "Original list:" on the console. Show the fraction things. Find the difference of the fraction things given 4. Write "Order 4 forward difference:" on the console. Show the fraction things. Destroy the fraction things. Wait for the escape key. Shut down.   To show some fraction things: Get a fraction thing from the fraction things. Loop. If the fraction thing is nil, write "" on the console; exit. Write "" then the fraction thing's fraction on the console without advancing. If the fraction thing's next is not nil, write ", " on the console without advancing. Put the fraction thing's next into the fraction thing. Repeat.
http://rosettacode.org/wiki/Formatted_numeric_output
Formatted numeric output
Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
#Tcl
Tcl
set number 7.342 format "%08.3f" $number
http://rosettacode.org/wiki/Formatted_numeric_output
Formatted numeric output
Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
#TI-89_BASIC
TI-89 BASIC
right("00000" & format(7.12511, "f3"), 9)
http://rosettacode.org/wiki/Four_bit_adder
Four bit adder
Task "Simulate" a four-bit adder. This design can be realized using four 1-bit full adders. Each of these 1-bit full adders can be built with two half adders and an   or   gate. ; Finally a half adder can be made using an   xor   gate and an   and   gate. The   xor   gate can be made using two   nots,   two   ands   and one   or. Not,   or   and   and,   the only allowed "gates" for the task, can be "imitated" by using the bitwise operators of your language. If there is not a bit type in your language, to be sure that the   not   does not "invert" all the other bits of the basic type   (e.g. a byte)   we are not interested in,   you can use an extra   nand   (and   then   not)   with the constant   1   on one input. Instead of optimizing and reducing the number of gates used for the final 4-bit adder,   build it in the most straightforward way,   connecting the other "constructive blocks",   in turn made of "simpler" and "smaller" ones. Schematics of the "constructive blocks" (Xor gate with ANDs, ORs and NOTs)            (A half adder)                   (A full adder)                             (A 4-bit adder)         Solutions should try to be as descriptive as possible, making it as easy as possible to identify "connections" between higher-order "blocks". It is not mandatory to replicate the syntax of higher-order blocks in the atomic "gate" blocks, i.e. basic "gate" operations can be performed as usual bitwise operations, or they can be "wrapped" in a block in order to expose the same syntax of higher-order blocks, at implementers' choice. To test the implementation, show the sum of two four-bit numbers (in binary).
#Python
Python
def xor(a, b): return (a and not b) or (b and not a)   def ha(a, b): return xor(a, b), a and b # sum, carry   def fa(a, b, ci): s0, c0 = ha(ci, a) s1, c1 = ha(s0, b) return s1, c0 or c1 # sum, carry   def fa4(a, b): width = 4 ci = [None] * width co = [None] * width s = [None] * width for i in range(width): s[i], co[i] = fa(a[i], b[i], co[i-1] if i else 0) return s, co[-1]   def int2bus(n, width=4): return [int(c) for c in "{0:0{1}b}".format(n, width)[::-1]]   def bus2int(b): return sum(1 << i for i, bit in enumerate(b) if bit)   def test_fa4(): width = 4 tot = [None] * (width + 1) for a in range(2**width): for b in range(2**width): tot[:width], tot[width] = fa4(int2bus(a), int2bus(b)) assert a + b == bus2int(tot), "totals don't match: %i + %i != %s" % (a, b, tot)     if __name__ == '__main__': test_fa4()
http://rosettacode.org/wiki/Fivenum
Fivenum
Many big data or scientific programs use boxplots to show distributions of data.   In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM.   It can be useful to save large arrays as arrays with five numbers to save memory. For example, the   R   programming language implements Tukey's five-number summary as the fivenum function. Task Given an array of numbers, compute the five-number summary. Note While these five numbers can be used to draw a boxplot,   statistical packages will typically need extra data. Moreover, while there is a consensus about the "box" of the boxplot,   there are variations among statistical packages for the whiskers.
#Lua
Lua
function slice(tbl, low, high) local copy = {}   for i=low or 1, high or #tbl do copy[#copy+1] = tbl[i] end   return copy end   -- assumes that tbl is sorted function median(tbl) m = math.floor(#tbl / 2) + 1 if #tbl % 2 == 1 then return tbl[m] end return (tbl[m-1] + tbl[m]) / 2 end   function fivenum(tbl) table.sort(tbl)   r0 = tbl[1] r2 = median(tbl) r4 = tbl[#tbl]   m = math.floor(#tbl / 2) if #tbl % 2 == 1 then low = m else low = m - 1 end r1 = median(slice(tbl, nil, low+1)) r3 = median(slice(tbl, low+2, nil))   return r0, r1, r2, r3, r4 end   x1 = { {15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0}, {36.0, 40.0, 7.0, 39.0, 41.0, 15.0}, { 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 } }   for i,x in ipairs(x1) do print(fivenum(x)) end
http://rosettacode.org/wiki/Find_the_missing_permutation
Find the missing permutation
ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB Listed above are   all-but-one   of the permutations of the symbols   A,   B,   C,   and   D,   except   for one permutation that's   not   listed. Task Find that missing permutation. Methods Obvious method: enumerate all permutations of A, B, C, and D, and then look for the missing permutation. alternate method: Hint: if all permutations were shown above, how many times would A appear in each position? What is the parity of this number? another alternate method: Hint: if you add up the letter values of each column, does a missing letter A, B, C, and D from each column cause the total value for each column to be unique? Related task   Permutations)
#APL
APL
missing ← ((⊂↓⍳¨⌊/) +⌿∘(⊢∘.=∪∘∊)) ⌷ ∪∘∊
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month
Find the last Sunday of each month
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 2013-05-26 2013-06-30 2013-07-28 2013-08-25 2013-09-29 2013-10-27 2013-11-24 2013-12-29 Related tasks Day of the week Five weekends Last Friday of each month
#Batch_File
Batch File
  @echo off setlocal enabledelayedexpansion set /p yr= Enter year: echo. call:monthdays %yr% list set mm=1 for %%i in (!list!) do ( call:calcdow !yr! !mm! %%i dow set/a lsu=%%i-dow set mf=0!mm! echo !yr!-!mf:~-2!-!lsu! set /a mm+=1 ) pause exit /b   :monthdays yr &list setlocal call:isleap %1 ly for /L %%i in (1,1,12) do ( set /a "nn = 30 + ^!(((%%i & 9) + 6) %% 7) + ^!(%%i ^^ 2) * (ly - 2) set list=!list! !nn! ) endlocal & set %2=%list% exit /b   :calcdow yr mt dy &dow  :: 0=sunday setlocal set/a a=(14-%2)/12,yr=%1-a,m=%2+12*a-2,"dow=(%3+yr+yr/4-yr/100+yr/400+31*m/12)%%7" endlocal & set %~4=%dow% exit /b   :isleap yr &leap  :: remove ^ if not delayed expansion set /a "%2=^!(%1%%4)+(^!^!(%1%%100)-^!^!(%1%%400))" exit /b  
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month
Find the last Sunday of each month
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 2013-05-26 2013-06-30 2013-07-28 2013-08-25 2013-09-29 2013-10-27 2013-11-24 2013-12-29 Related tasks Day of the week Five weekends Last Friday of each month
#BBC_BASIC
BBC BASIC
  INSTALL @lib$+"DATELIB"   INPUT "What year to calculate (YYYY)? " Year%   PRINT '"Last Sundays in ";Year%;" are on:" FOR Month%=1 TO 12 PRINT Year% "-" RIGHT$("0"+STR$Month%,2) "-";FN_dim(Month%,Year%)-FN_dow(FN_mjd(FN_dim(Month%,Year%),Month%,Year%)) NEXT END  
http://rosettacode.org/wiki/Find_the_intersection_of_two_lines
Find the intersection of two lines
[1] Task Find the point of intersection of two lines in 2D. The 1st line passes though   (4,0)   and   (6,10) . The 2nd line passes though   (0,3)   and   (10,7) .
#C
C
  #include<stdlib.h> #include<stdio.h> #include<math.h>   typedef struct{ double x,y; }point;   double lineSlope(point a,point b){   if(a.x-b.x == 0.0) return NAN; else return (a.y-b.y)/(a.x-b.x); }   point extractPoint(char* str){ int i,j,start,end,length; char* holder; point c;   for(i=0;str[i]!=00;i++){ if(str[i]=='(') start = i; if(str[i]==','||str[i]==')') { end = i;   length = end - start;   holder = (char*)malloc(length*sizeof(char));   for(j=0;j<length-1;j++) holder[j] = str[start + j + 1]; holder[j] = 00;   if(str[i]==','){ start = i; c.x = atof(holder); } else c.y = atof(holder); } }   return c; }   point intersectionPoint(point a1,point a2,point b1,point b2){ point c;   double slopeA = lineSlope(a1,a2), slopeB = lineSlope(b1,b2);   if(slopeA==slopeB){ c.x = NAN; c.y = NAN; } else if(isnan(slopeA) && !isnan(slopeB)){ c.x = a1.x; c.y = (a1.x-b1.x)*slopeB + b1.y; } else if(isnan(slopeB) && !isnan(slopeA)){ c.x = b1.x; c.y = (b1.x-a1.x)*slopeA + a1.y; } else{ c.x = (slopeA*a1.x - slopeB*b1.x + b1.y - a1.y)/(slopeA - slopeB); c.y = slopeB*(c.x - b1.x) + b1.y; }   return c; }   int main(int argC,char* argV[]) { point c;   if(argC < 5) printf("Usage : %s <four points specified as (x,y) separated by a space>",argV[0]); else{ c = intersectionPoint(extractPoint(argV[1]),extractPoint(argV[2]),extractPoint(argV[3]),extractPoint(argV[4]));   if(isnan(c.x)) printf("The lines do not intersect, they are either parallel or co-incident."); else printf("Point of intersection : (%lf,%lf)",c.x,c.y); }   return 0; }  
http://rosettacode.org/wiki/Find_the_intersection_of_a_line_with_a_plane
Find the intersection of a line with a plane
Finding the intersection of an infinite ray with a plane in 3D is an important topic in collision detection. Task Find the point of intersection for the infinite ray with direction   (0, -1, -1)   passing through position   (0, 0, 10)   with the infinite plane with a normal vector of   (0, 0, 1)   and which passes through [0, 0, 5].
#C
C
  #include<stdio.h>   typedef struct{ double x,y,z; }vector;   vector addVectors(vector a,vector b){ return (vector){a.x+b.x,a.y+b.y,a.z+b.z}; }   vector subVectors(vector a,vector b){ return (vector){a.x-b.x,a.y-b.y,a.z-b.z}; }   double dotProduct(vector a,vector b){ return a.x*b.x + a.y*b.y + a.z*b.z; }   vector scaleVector(double l,vector a){ return (vector){l*a.x,l*a.y,l*a.z}; }   vector intersectionPoint(vector lineVector, vector linePoint, vector planeNormal, vector planePoint){ vector diff = subVectors(linePoint,planePoint);   return addVectors(addVectors(diff,planePoint),scaleVector(-dotProduct(diff,planeNormal)/dotProduct(lineVector,planeNormal),lineVector)); }   int main(int argC,char* argV[]) { vector lV,lP,pN,pP,iP;   if(argC!=5) printf("Usage : %s <line direction, point on line, normal to plane and point on plane given as (x,y,z) tuples separated by space>"); else{ sscanf(argV[1],"(%lf,%lf,%lf)",&lV.x,&lV.y,&lV.z); sscanf(argV[3],"(%lf,%lf,%lf)",&pN.x,&pN.y,&pN.z);   if(dotProduct(lV,pN)==0) printf("Line and Plane do not intersect, either parallel or line is on the plane"); else{ sscanf(argV[2],"(%lf,%lf,%lf)",&lP.x,&lP.y,&lP.z); sscanf(argV[4],"(%lf,%lf,%lf)",&pP.x,&pP.y,&pP.z);   iP = intersectionPoint(lV,lP,pN,pP);   printf("Intersection point is (%lf,%lf,%lf)",iP.x,iP.y,iP.z); } }   return 0; }  
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) The   FizzBuzz   problem was presented as the lowest level of comprehension required to illustrate adequacy. Also see   (a blog)   dont-overthink-fizzbuzz   (a blog)   fizzbuzz-the-programmers-stairway-to-heaven
#Action.21
Action!
PROC Main() BYTE i,d3,d5   d3=1 d5=1 FOR i=1 TO 100 DO IF d3=0 AND d5=0 THEN Print("FizzBuzz") ELSEIF d3=0 THEN Print("Fizz") ELSEIF d5=0 THEN Print("Buzz") ELSE PrintB(i) FI Put(32)   d3==+1 d5==+1 IF d3=3 THEN d3=0 FI IF d5=5 THEN d5=0 FI OD RETURN
http://rosettacode.org/wiki/Five_weekends
Five weekends
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays. Task Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar). Show the number of months with this property (there should be 201). Show at least the first and last five dates, in order. Algorithm suggestions Count the number of Fridays, Saturdays, and Sundays in every month. Find all of the 31-day months that begin on Friday. Extra credit Count and/or show all of the years which do not have at least one five-weekend month (there should be 29). Related tasks Day of the week Last Friday of each month Find last sunday of each month
#C.2B.2B
C++
#include <vector> #include <boost/date_time/gregorian/gregorian.hpp> #include <algorithm> #include <iostream> #include <iterator> using namespace boost::gregorian ;   void print( const date &d ) { std::cout << d.year( ) << "-" << d.month( ) << "\n" ; }   int main( ) { greg_month longmonths[ ] = {Jan, Mar , May , Jul , Aug , Oct , Dec } ; int monthssize = sizeof ( longmonths ) / sizeof (greg_month ) ; typedef std::vector<date> DateVector ; DateVector weekendmonster ; std::vector<unsigned short> years_without_5we_months ; for ( unsigned short i = 1900 ; i < 2101 ; i++ ) { bool months_found = false ; //does a given year have 5 weekend months ? for ( int j = 0 ; j < monthssize ; j++ ) { date d ( i , longmonths[ j ] , 1 ) ; if ( d.day_of_week( ) == Friday ) { //for the month to have 5 weekends weekendmonster.push_back( d ) ; if ( months_found == false ) months_found = true ; } } if ( months_found == false ) { years_without_5we_months.push_back( i ) ; } } std::cout << "Between 1900 and 2100 , there are " << weekendmonster.size( ) << " months with 5 complete weekends!\n" ; std::cout << "Months with 5 complete weekends are:\n" ; std::for_each( weekendmonster.begin( ) , weekendmonster.end( ) , print ) ; std::cout << years_without_5we_months.size( ) << " years had no months with 5 complete weekends!\n" ; std::cout << "These are:\n" ; std::copy( years_without_5we_months.begin( ) , years_without_5we_months.end( ) , std::ostream_iterator<unsigned short>( std::cout , "\n" ) ) ; std::cout << std::endl ; return 0 ; }
http://rosettacode.org/wiki/First_perfect_square_in_base_n_with_n_unique_digits
First perfect square in base n with n unique digits
Find the first perfect square in a given base N that has at least N digits and exactly N significant unique digits when expressed in base N. E.G. In base 10, the first perfect square with at least 10 unique digits is 1026753849 (32043²). You may use analytical methods to reduce the search space, but the code must do a search. Do not use magic numbers or just feed the code the answer to verify it is correct. Task Find and display here, on this page, the first perfect square in base N, with N significant unique digits when expressed in base N, for each of base 2 through 12. Display each number in the base N for which it was calculated. (optional) Do the same for bases 13 through 16. (stretch goal) Continue on for bases 17 - ?? (Big Integer math) See also OEIS A260182: smallest square that is pandigital in base n. Related task Casting out nines
#JavaScript
JavaScript
(() => { 'use strict';   // allDigitSquare :: Int -> Int const allDigitSquare = base => { const bools = replicate(base, false); return untilSucc( allDigitsUsedAtBase(base, bools), ceil(sqrt(parseInt( '10' + '0123456789abcdef'.slice(2, base), base ))) ); };   // allDigitsUsedAtBase :: Int -> [Bool] -> Int -> Bool const allDigitsUsedAtBase = (base, bools) => n => { // Fusion of representing the square of integer N at a given base // with checking whether all digits of that base contribute to N^2. // Sets the bool at a digit position to True when used. // True if all digit positions have been used. const ds = bools.slice(0); let x = n * n; while (x) { ds[x % base] = true; x = floor(x / base); } return ds.every(x => x) };   // showBaseSquare :: Int -> String const showBaseSquare = b => { const q = allDigitSquare(b); return justifyRight(2, ' ', str(b)) + ' -> ' + justifyRight(8, ' ', showIntAtBase(b, digit, q, '')) + ' -> ' + showIntAtBase(b, digit, q * q, ''); };   // TEST ----------------------------------------------- const main = () => { // 1-12 only - by 15 the squares are truncated by // JS integer limits.   // Returning values through console.log – // in separate events to avoid asynchronous disorder. print('Smallest perfect squares using all digits in bases 2-12:\n') (id > 0 ? chars.substr(id, 1) : " ") print('Base Root Square')   print(showBaseSquare(2)); print(showBaseSquare(3)); print(showBaseSquare(4)); print(showBaseSquare(5)); print(showBaseSquare(6)); print(showBaseSquare(7)); print(showBaseSquare(8)); print(showBaseSquare(9)); print(showBaseSquare(10)); print(showBaseSquare(11)); print(showBaseSquare(12)); };   // GENERIC FUNCTIONS ----------------------------------   const ceil = Math.ceil, floor = Math.floor, sqrt = Math.sqrt;   // Tuple (,) :: a -> b -> (a, b) const Tuple = (a, b) => ({ type: 'Tuple', '0': a, '1': b, length: 2 });   // digit :: Int -> Char const digit = n => // Digit character for given integer. '0123456789abcdef' [n];   // enumFromTo :: (Int, Int) -> [Int] const enumFromTo = (m, n) => Array.from({ length: 1 + n - m }, (_, i) => m + i);   // justifyRight :: Int -> Char -> String -> String const justifyRight = (n, cFiller, s) => n > s.length ? ( s.padStart(n, cFiller) ) : s;   // print :: a -> IO () const print = x => console.log(x)   // quotRem :: Int -> Int -> (Int, Int) const quotRem = (m, n) => Tuple(Math.floor(m / n), m % n);   // replicate :: Int -> a -> [a] const replicate = (n, x) => Array.from({ length: n }, () => x);   // showIntAtBase :: Int -> (Int -> Char) -> Int -> String -> String const showIntAtBase = (base, toChr, n, rs) => { const go = ([n, d], r) => { const r_ = toChr(d) + r; return 0 !== n ? ( go(Array.from(quotRem(n, base)), r_) ) : r_; }; return 1 >= base ? ( 'error: showIntAtBase applied to unsupported base' ) : 0 > n ? ( 'error: showIntAtBase applied to negative number' ) : go(Array.from(quotRem(n, base)), rs); };   // Abbreviation for quick testing - any 2nd arg interpreted as indent size   // sj :: a -> String function sj() { const args = Array.from(arguments); return JSON.stringify.apply( null, 1 < args.length && !isNaN(args[0]) ? [ args[1], null, args[0] ] : [args[0], null, 2] ); }   // str :: a -> String const str = x => x.toString();   // untilSucc :: (Int -> Bool) -> Int -> Int const untilSucc = (p, x) => { // The first in a chain of successive integers // for which p(x) returns true. let v = x; while (!p(v)) v = 1 + v; return v; };   // MAIN --- return main(); })();
http://rosettacode.org/wiki/First-class_functions
First-class functions
A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming: Create new functions from preexisting functions at run-time Store functions in collections Use functions as arguments to other functions Use functions as return values of other functions Task Write a program to create an ordered collection A of functions of a real number. At least one function should be built-in and at least one should be user-defined; try using the sine, cosine, and cubing functions. Fill another collection B with the inverse of each function in A. Implement function composition as in Functional Composition. Finally, demonstrate that the result of applying the composition of each function in A and its inverse in B to a value, is the original value. (Within the limits of computational accuracy). (A solution need not actually call the collections "A" and "B". These names are only used in the preceding paragraph for clarity.) Related task First-class Numbers
#Common_Lisp
Common Lisp
(defun compose (f g) (lambda (x) (funcall f (funcall g x)))) (defun cube (x) (expt x 3)) (defun cube-root (x) (expt x (/ 3)))   (loop with value = 0.5 for func in (list #'sin #'cos #'cube ) for inverse in (list #'asin #'acos #'cube-root) for composed = (compose inverse func) do (format t "~&(~A ∘ ~A)(~A) = ~A~%" inverse func value (funcall composed value)))
http://rosettacode.org/wiki/Forest_fire
Forest fire
This page uses content from Wikipedia. The original article was at Forest-fire model. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Implement the Drossel and Schwabl definition of the forest-fire model. It is basically a 2D   cellular automaton   where each cell can be in three distinct states (empty, tree and burning) and evolves according to the following rules (as given by Wikipedia) A burning cell turns into an empty cell A tree will burn if at least one neighbor is burning A tree ignites with probability   f   even if no neighbor is burning An empty space fills with a tree with probability   p Neighborhood is the   Moore neighborhood;   boundary conditions are so that on the boundary the cells are always empty ("fixed" boundary condition). At the beginning, populate the lattice with empty and tree cells according to a specific probability (e.g. a cell has the probability 0.5 to be a tree). Then, let the system evolve. Task's requirements do not include graphical display or the ability to change parameters (probabilities   p   and   f )   through a graphical or command line interface. Related tasks   See   Conway's Game of Life   See   Wireworld.
#J
J
NB. states: 0 empty, 1 tree, _1 fire dims =:10 10   tessellate=: 0,0,~0,.0,.~ 3 3 >./@,;._3 ] mask=: tessellate dims$1 chance=: 1 :'(> ? bind (dims$0)) bind (mask*m)'   start=: 0.5 chance grow =: 0.01 chance fire =: 0.001 chance   spread=: [: tessellate 0&>   step=: grow [`]@.(|@])"0 >.&0 * _1 ^ fire +. spread   run=:3 :0 forest=. start'' for.i.y do. smoutput ' #o' {~ forest=. step forest end. )
http://rosettacode.org/wiki/First_class_environments
First class environments
According to Wikipedia, "In computing, a first-class object ... is an entity that can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable". Often this term is used in the context of "first class functions". In an analogous way, a programming language may support "first class environments". The environment is minimally, the set of variables accessible to a statement being executed. Change the environments and the same statement could produce different results when executed. Often an environment is captured in a closure, which encapsulates a function together with an environment. That environment, however, is not first-class, as it cannot be created, passed etc. independently from the function's code. Therefore, a first class environment is a set of variable bindings which can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable. It is like a closure without code. A statement must be able to be executed within a stored first class environment and act according to the environment variable values stored within. Task Build a dozen environments, and a single piece of code to be run repeatedly in each of these environments. Each environment contains the bindings for two variables:   a value in the Hailstone sequence, and   a count which is incremented until the value drops to 1. The initial hailstone values are 1 through 12, and the count in each environment is zero. When the code runs, it calculates the next hailstone step in the current environment (unless the value is already 1) and counts the steps. Then it prints the current value in a tabular form. When all hailstone values dropped to 1, processing stops, and the total number of hailstone steps for each environment is printed.
#REXX
REXX
/*REXX pgm illustrates N 1st─class environments (using numbers from a hailstone seq).*/ parse arg n . /*obtain optional argument from the CL.*/ if n=='' | n=="," then n= 12 /*Was N defined? No, then use default.*/ @.= /*initialize the array @. to nulls.*/ do i=1 for n; @.i= i /* " environments to an index. */ end /*i*/ w= length(n) /*width (so far) for columnar output.*/   do forever until @.0; @.0= 1 /* ◄─── process all the environments. */ do k=1 for n; x= hailstone(k) /*obtain next hailstone number in seq. */ w= max(w, length(x)) /*determine the maximum width needed. */ @.k= @.k x /* ◄─── where the rubber meets the road*/ end /*k*/ end /*forever*/ #= 0 /* [↓] display the tabular results. */ do lines=-1 until _=''; _= /*process a line for each environment. */ do j=1 for n /*process each of the environments. */ select /*determine how to process the line. */ when #== 1 then _= _ right(words(@.j) - 1, w) /*environment count.*/ when lines==-1 then _= _ right(j, w) /*the title (header)*/ when lines== 0 then _= _ right('', w, "─") /*the separator line*/ otherwise _= _ right(word(@.j, lines), w) end /*select*/ end /*j*/   if #==1 then #= 2 /*separator line? */ if _='' then #= # + 1 /*Null? Bump the #.*/ if #==1 then _= copies(" "left('', w, "═"), N) /*the foot separator*/ if _\='' then say strip( substr(_, 2), "T") /*display the counts*/ end /*lines*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ hailstone: procedure expose @.; parse arg y; _= word(@.y, words(@.y) ) if _==1 then return ''; @.0= 0; if _//2 then return _*3 + 1; return _%2
http://rosettacode.org/wiki/Flatten_a_list
Flatten a list
Task Write a function to flatten the nesting in an arbitrary list of values. Your program should work on the equivalent of this list: [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []] Where the correct result would be the list: [1, 2, 3, 4, 5, 6, 7, 8] Related task   Tree traversal
#EchoLisp
EchoLisp
  (define (fflatten l) (cond [(null? l) null] [(not (list? l)) (list l)] [else (append (fflatten (first l)) (fflatten (rest l)))]))   ;; (define L' [[1] 2 [[3 4] 5] [[[]]] [[[6]]] 7 8 []])   (fflatten L) ;; use custom function → (1 2 3 4 5 6 7 8) (flatten L) ;; use built-in → (1 2 3 4 5 6 7 8)   ;; Remarks ;; null is the same as () - the empty list - (flatten '(null null null)) → null (flatten '[ () () () ]) → null (flatten null) ❗ error: flatten : expected list : null   ;; The 'reverse' of flatten is group (group '( 4 5 5 5 6 6 7 8 7 7 7 9)) → ((4) (5 5 5) (6 6) (7) (8) (7 7 7) (9))    
http://rosettacode.org/wiki/Flipping_bits_game
Flipping bits game
The game Given an   N×N   square array of zeroes or ones in an initial configuration,   and a target configuration of zeroes and ones. The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered columns at once   (as one move). In an inversion.   any  1  becomes  0,   and any  0  becomes  1  for that whole row or column. Task Create a program to score for the Flipping bits game. The game should create an original random target configuration and a starting configuration. Ensure that the starting position is never the target position. The target position must be guaranteed as reachable from the starting position.   (One possible way to do this is to generate the start position by legal flips from a random target position.   The flips will always be reversible back to the target from the given start position). The number of moves taken so far should be shown. Show an example of a short game here, on this page, for a   3×3   array of bits.
#QB64
QB64
  RANDOMIZE TIMER DIM SHARED cellsPerSide, legalMoves$, startB$, currentB$, targetB$, moveCount   restart DO displayStatus IF currentB$ = targetB$ THEN 'game done! PRINT " Congratulations, done in"; moveCount; " moves." PRINT "": PRINT " Press y for yes, if you want to start over > "; yes$ = getKey$: PRINT yes$: _DELAY .4: vcls IF yes$ = "y" THEN restart ELSE nomore = -1 ELSE 'get next move m$ = " ": PRINT WHILE INSTR(legalMoves$, m$) = 0 PRINT " Press a lettered column or a numbered row to flip (or 0,q,?,!) > "; m$ = getKey$: PRINT m$: _DELAY .4 IF m$ = "!" THEN showSolution = -1: m$ = " ": EXIT WHILE ELSEIF m$ = "?" THEN: m$ = " ": cp CSRLIN, "Hint: " + hint$ ELSEIF m$ = "0" OR m$ = "q" THEN: vcls: CLOSE: END ELSEIF m$ = "" THEN: m$ = " " END IF WEND IF showSolution THEN 'run the solution from hints function showSolution = 0: mv$ = hint$ cp CSRLIN + 1, "For the next move, the AI has chosen: " + mv$ cp CSRLIN + 1, "Running the solution with 4 sec screen delays..." _DELAY 4: vcls WHILE mv$ <> "Done?" moveCount = moveCount + 1: makeMove mv$: displayStatus: mv$ = hint$ cp CSRLIN + 1, "For the next move, the AI has chosen: " + mv$ cp CSRLIN + 1, "Running the solution with 4 sec screen delays..." _DELAY 4: vcls WEND displayStatus cp CSRLIN + 1, "Done! Current board matches Target" cp CSRLIN + 1, "Press y for yes, if you want to start over: > " yes$ = getKey$: PRINT yes$: _DELAY .4: vcls IF yes$ = "y" THEN restart ELSE nomore = -1 ELSE vcls: moveCount = moveCount + 1: makeMove m$ END IF END IF LOOP UNTIL nomore CLOSE   SUB displayStatus COLOR 9: showBoard 2, 2, currentB$, "Current:" COLOR 12: showBoard 2, 2 + 2 * cellsPerSide + 6, targetB$, "Target:" COLOR 13: PRINT: PRINT " Number of moves taken so far is" + STR$(moveCount) COLOR 14 END SUB     FUNCTION hint$ 'compare the currentB to targetB and suggest letter or digit or done FOR i = 1 TO 2 * cellsPerSide 'check cols first then rows as listed in legalMoves$ r$ = MID$(legalMoves$, i, 1) IF i <= cellsPerSide THEN currentbit$ = MID$(currentB$, i, 1): targetBit$ = MID$(targetB$, i, 1) IF currentbit$ <> targetBit$ THEN flag = -1: EXIT FOR ELSE j = i - cellsPerSide currentbit$ = MID$(currentB$, (j - 1) * cellsPerSide + 1, 1) targetBit$ = MID$(targetB$, (j - 1) * cellsPerSide + 1, 1) IF currentbit$ <> targetBit$ THEN flag = -1: EXIT FOR END IF NEXT IF flag THEN hint$ = r$ ELSE hint$ = "Done?" END FUNCTION   SUB restart CLOSE OPEN "Copy Flipping Bits Game.txt" FOR OUTPUT AS #3 cellsPerSide = 0: legalMoves$ = "": moveCount = 0 COLOR 9: cp 3, "Flipping Bits Game, now with AI! b+ 2017-12-18" COLOR 5 cp 5, "You will be presented with a square board marked Current and" cp 6, "another marked Target. The object of the game is to match" cp 7, "the Current board to Target in the least amount of moves." cp 9, "To make a move, enter a letter for a column to flip or" cp 10, "a digit for a row to flip. In a flip, all 1's are" cp 11, "changed to 0's and all 0's changed to 1's." cp 13, "You may enter 0 or q at any time to quit." cp 14, "You may press ? when prompted for move to get a hint." cp 15, "You may press ! to have the program solve the puzzle." COLOR 14: PRINT: PRINT WHILE cellsPerSide < 2 OR cellsPerSide > 9 LOCATE CSRLIN, 13: PRINT "Please press how many cells you want per side 2 to 9 > "; in$ = getKey$: PRINT in$: _DELAY .4 IF in$ = "0" OR in$ = "q" THEN END ELSE cellsPerSide = VAL(in$) WEND vcls FOR i = 1 TO cellsPerSide: legalMoves$ = legalMoves$ + CHR$(96 + i): NEXT FOR i = 1 TO cellsPerSide: legalMoves$ = legalMoves$ + LTRIM$(STR$(i)): NEXT startB$ = startBoard$: currentB$ = startB$: targetB$ = makeTarget$: currentB$ = startB$ END SUB   FUNCTION startBoard$ FOR i = 1 TO cellsPerSide ^ 2: r$ = r$ + LTRIM$(STR$(INT(RND * 2))): NEXT startBoard$ = r$ END FUNCTION   SUB showBoard (row, col, board$, title$) LOCATE row - 1, col: PRINT title$ FOR i = 1 TO cellsPerSide LOCATE row, col + 2 * (i - 1) + 3: PRINT MID$(legalMoves$, i, 1); NEXT PRINT FOR i = 1 TO cellsPerSide LOCATE row + i, col - 1: PRINT STR$(i); FOR j = 1 TO cellsPerSide LOCATE row + i, col + 2 * j: PRINT " " + MID$(board$, (i - 1) * cellsPerSide + j, 1); NEXT PRINT NEXT END SUB   SUB makeMove (move$) ac = ASC(move$) IF ac > 96 THEN 'letter col = ac - 96 FOR i = 1 TO cellsPerSide bit$ = MID$(currentB$, (i - 1) * cellsPerSide + col, 1) IF bit$ = "0" THEN MID$(currentB$, (i - 1) * cellsPerSide + col, 1) = "1" ELSE MID$(currentB$, (i - 1) * cellsPerSide + col, 1) = "0" END IF NEXT ELSE 'number row = ac - 48 FOR i = 1 TO cellsPerSide bit$ = MID$(currentB$, (row - 1) * cellsPerSide + i, 1) IF bit$ = "0" THEN MID$(currentB$, (row - 1) * cellsPerSide + i, 1) = "1" ELSE MID$(currentB$, (row - 1) * cellsPerSide + i, 1) = "0" END IF NEXT END IF END SUB   FUNCTION makeTarget$ WHILE currentB$ = startB$ FOR i = 1 TO cellsPerSide * cellsPerSide m$ = MID$(legalMoves$, INT(RND * LEN(legalMoves$)) + 1, 1): makeMove m$ NEXT WEND makeTarget$ = currentB$ END FUNCTION   SUB cp (row, text$) 'center print at row LOCATE row, (80 - LEN(text$)) / 2: PRINT text$; END SUB   SUB vcls 'print the screen to file then clear it DIM s$(23) FOR lines = 1 TO 23 FOR t = 1 TO 80: scan$ = scan$ + CHR$(SCREEN(lines, t)): NEXT s$(lines) = RTRIM$(scan$): scan$ = "" NEXT FOR fini = 23 TO 1 STEP -1 IF s$(fini) <> "" THEN EXIT FOR NEXT PRINT #3, "" FOR i = 1 TO fini: PRINT #3, s$(i): NEXT PRINT #3, "": PRINT #3, STRING$(80, "-"): CLS END SUB   FUNCTION getKey$ 'just want printable characters k$ = "" WHILE LEN(k$) = 0 k$ = INKEY$ IF LEN(k$) THEN 'press something so respond IF LEN(k$) = 2 OR ASC(k$) > 126 OR ASC(k$) < 32 THEN k$ = "*": BEEP END IF WEND getKey$ = k$ END FUNCTION  
http://rosettacode.org/wiki/Flipping_bits_game
Flipping bits game
The game Given an   N×N   square array of zeroes or ones in an initial configuration,   and a target configuration of zeroes and ones. The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered columns at once   (as one move). In an inversion.   any  1  becomes  0,   and any  0  becomes  1  for that whole row or column. Task Create a program to score for the Flipping bits game. The game should create an original random target configuration and a starting configuration. Ensure that the starting position is never the target position. The target position must be guaranteed as reachable from the starting position.   (One possible way to do this is to generate the start position by legal flips from a random target position.   The flips will always be reversible back to the target from the given start position). The number of moves taken so far should be shown. Show an example of a short game here, on this page, for a   3×3   array of bits.
#Racket
Racket
#lang racket (define (flip-row! pzzl r) (define N (integer-sqrt (bytes-length pzzl))) (for* ((c (in-range N))) (define idx (+ c (* N r))) (bytes-set! pzzl idx (- 1 (bytes-ref pzzl idx)))))   (define (flip-col! pzzl c) (define N (integer-sqrt (bytes-length pzzl))) (for* ((r (in-range N))) (define idx (+ c (* N r))) (bytes-set! pzzl idx (- 1 (bytes-ref pzzl idx)))))   (define (new-game N (flips 10)) (define N2 (sqr N)) (define targ (list->bytes (for/list ((_ N2)) (random 2)))) (define strt (bytes-copy targ)) (for ((_ flips)) (case (random 2) ((0) (flip-col! strt (random N))) ((1) (flip-row! strt (random N))))) (if (equal? strt targ) (new-game N) (values targ strt)))   (define (show-games #:sep (pzl-sep " | ") . pzzls) (define N (integer-sqrt (bytes-length (first pzzls)))) (define caption (string-join (for/list ((c (in-range N))) (~a (add1 c))) "")) (define ruler (string-join (for/list ((c (in-range N))) "-") ""))   (define ((pzzle-row r) p) (string-join (for/list ((c (in-range N))) (~a (bytes-ref p (+ c (* N r))))) ""))   (displayln (string-join (list* (format " ~a" (string-join (for/list ((_ pzzls)) caption) pzl-sep)) (format " ~a" (string-join (for/list ((_ pzzls)) ruler) pzl-sep)) (for/list ((r (in-range N)) (R (in-naturals (char->integer #\a)))) (format "~a ~a" (integer->char R) (string-join (map (pzzle-row r) pzzls) pzl-sep)))) "\n")))   (define (play N) (define-values (end start) (new-game N)) (define (turn n (show? #t)) (cond [(equal? end start) (printf "you won on turn #~a~%" n)] [else (when show? ;; don't show after whitespace (printf "turn #~a~%" n) (show-games start end)) (match (read-char) [(? eof-object?) (printf "sad to see you go :-(~%")] [(? char-whitespace?) (turn n #f)] [(? char-numeric? c) (define cnum (- (char->integer c) (char->integer #\1))) (cond [(< -1 cnum N) (printf "flipping col ~a~%" (add1 cnum)) (flip-col! start cnum) (turn (add1 n))] [else (printf "column number out of range ~a > ~a~%" (add1 cnum) N) (turn n)])] [(? char-lower-case? c) (define rnum (- (char->integer c) (char->integer #\a))) (cond [(< -1 rnum N) (printf "flipping row ~a~%" (add1 rnum)) (flip-row! start rnum) (turn (add1 n))] [else (printf "row number out of range ~a > ~a~%" (add1 rnum) (sub1 N)) (turn n)])] [else (printf "unrecognised character in input: ~s~%" else) (turn n)])])) (turn 0))
http://rosettacode.org/wiki/First_power_of_2_that_has_leading_decimal_digits_of_12
First power of 2 that has leading decimal digits of 12
(This task is taken from a   Project Euler   problem.) (All numbers herein are expressed in base ten.) 27   =   128   and   7   is the first power of   2   whose leading decimal digits are   12. The next power of   2   whose leading decimal digits are   12   is   80, 280   =   1208925819614629174706176. Define     p(L,n)     to be the nth-smallest value of   j   such that the base ten representation of   2j   begins with the digits of   L . So p(12, 1) = 7 and p(12, 2) = 80 You are also given that: p(123, 45)   =   12710 Task   find:   p(12, 1)   p(12, 2)   p(123, 45)   p(123, 12345)   p(123, 678910)   display the results here, on this page.
#Racket
Racket
#lang racket (define (fract-part f) (- f (truncate f)))   (define ln10 (log 10)) (define ln2/ln10 (/ (log 2) ln10))   (define (inexact-p-test L) (let ((digit-shift (let loop ((L (quotient L 10)) (shift 1)) (if (zero? L) shift (loop (quotient L 10) (* 10 shift)))))) (λ (p) (= L (truncate (* digit-shift (exp (* ln10 (fract-part (* p ln2/ln10))))))))))   (define (p L n) (let ((test? (inexact-p-test L))) (let loop ((j 1) (n (sub1 n))) (cond [(not (test? j)) (loop (add1 j) n)] [(zero? n) j] [else (loop (add1 j) (sub1 n))]))))   (module+ main (define (report-p L n) (time (printf "p(~a, ~a) = ~a~%" L n (p L n))))   (report-p 12 1) (report-p 12 2) (report-p 123 45) (report-p 123 12345) (report-p 123 678910))
http://rosettacode.org/wiki/First_power_of_2_that_has_leading_decimal_digits_of_12
First power of 2 that has leading decimal digits of 12
(This task is taken from a   Project Euler   problem.) (All numbers herein are expressed in base ten.) 27   =   128   and   7   is the first power of   2   whose leading decimal digits are   12. The next power of   2   whose leading decimal digits are   12   is   80, 280   =   1208925819614629174706176. Define     p(L,n)     to be the nth-smallest value of   j   such that the base ten representation of   2j   begins with the digits of   L . So p(12, 1) = 7 and p(12, 2) = 80 You are also given that: p(123, 45)   =   12710 Task   find:   p(12, 1)   p(12, 2)   p(123, 45)   p(123, 12345)   p(123, 678910)   display the results here, on this page.
#Raku
Raku
use Lingua::EN::Numbers;   constant $ln2ln10 = log(2) / log(10);   my @startswith12 = ^∞ .grep: { ( 10 ** ($_ * $ln2ln10 % 1) ).substr(0,3) eq '1.2' };   my @startswith123 = lazy gather loop { state $pre = '1.23'; state $count = 0; state $this = 0; given $this { when 196 { $this = 289; my \n = $count + $this; $this = 485 unless ( 10 ** (n * $ln2ln10 % 1) ).substr(0,4) eq $pre; } when 485 { $this = 196; my \n = $count + $this; $this = 485 unless ( 10 ** (n * $ln2ln10 % 1) ).substr(0,4) eq $pre; } when 289 { $this = 196 } when 90 { $this = 289 } when 0 { $this = 90 } } take $count += $this; }   multi p ($prefix where *.chars == 2, $nth) { @startswith12[$nth-1] } multi p ($prefix where *.chars == 3, $nth) { @startswith123[$nth-1] }   # The Task for < 12 1 12 2 123 45 123 12345 123 678910 > -> $prefix, $nth { printf "%-15s %9s power of two (2^n) that starts with %5s is at n = %s\n", "p($prefix, $nth):", comma($nth) ~ ordinal-digit($nth).substr(*-2), "'$prefix'", comma p($prefix, $nth); }
http://rosettacode.org/wiki/First-class_functions/Use_numbers_analogously
First-class functions/Use numbers analogously
In First-class functions, a language is showing how its manipulation of functions is similar to its manipulation of other types. This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers. Write a program to create an ordered collection of a mixture of literally typed and expressions producing a real number, together with another ordered collection of their multiplicative inverses. Try and use the following pseudo-code to generate the numbers for the ordered collections: x = 2.0 xi = 0.5 y = 4.0 yi = 0.25 z = x + y zi = 1.0 / ( x + y ) Create a function multiplier, that given two numbers as arguments returns a function that when called with one argument, returns the result of multiplying the two arguments to the call to multiplier that created it and the argument in the call: new_function = multiplier(n1,n2) # where new_function(m) returns the result of n1 * n2 * m Applying the multiplier of a number and its inverse from the two ordered collections of numbers in pairs, show that the result in each case is one. Compare and contrast the resultant program with the corresponding entry in First-class functions. They should be close. To paraphrase the task description: Do what was done before, but with numbers rather than functions
#Perl
Perl
sub multiplier { my ( $n1, $n2 ) = @_; sub { $n1 * $n2 * $_[0]; }; }   my $x = 2.0; my $xi = 0.5; my $y = 4.0; my $yi = 0.25; my $z = $x + $y; my $zi = 1.0 / ( $x + $y );   my %zip; @zip{ $x, $y, $z } = ( $xi, $yi, $zi );   while ( my ( $number, $inverse ) = each %zip ) { print multiplier( $number, $inverse )->(0.5), "\n"; }  
http://rosettacode.org/wiki/First-class_functions/Use_numbers_analogously
First-class functions/Use numbers analogously
In First-class functions, a language is showing how its manipulation of functions is similar to its manipulation of other types. This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers. Write a program to create an ordered collection of a mixture of literally typed and expressions producing a real number, together with another ordered collection of their multiplicative inverses. Try and use the following pseudo-code to generate the numbers for the ordered collections: x = 2.0 xi = 0.5 y = 4.0 yi = 0.25 z = x + y zi = 1.0 / ( x + y ) Create a function multiplier, that given two numbers as arguments returns a function that when called with one argument, returns the result of multiplying the two arguments to the call to multiplier that created it and the argument in the call: new_function = multiplier(n1,n2) # where new_function(m) returns the result of n1 * n2 * m Applying the multiplier of a number and its inverse from the two ordered collections of numbers in pairs, show that the result in each case is one. Compare and contrast the resultant program with the corresponding entry in First-class functions. They should be close. To paraphrase the task description: Do what was done before, but with numbers rather than functions
#Phix
Phix
with javascript_semantics sequence mtable = {} function multiplier(atom n1, atom n2) mtable = append(mtable,{n1,n2}) return length(mtable) end function function call_multiplier(integer f, atom m) atom {n1,n2} = mtable[f] return n1*n2*m end function constant x = 2, xi = 0.5, y = 4, yi = 0.25, z = x + y, zi = 1 / ( x + y ) ?call_multiplier(multiplier(x,xi),0.5) ?call_multiplier(multiplier(y,yi),0.5) ?call_multiplier(multiplier(z,zi),0.5)
http://rosettacode.org/wiki/Flow-control_structures
Flow-control structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task Document common flow-control structures. One common example of a flow-control structure is the   goto   construct. Note that   Conditional Structures   and   Loop Structures   have their own articles/categories. Related tasks   Conditional Structures   Loop Structures
#Racket
Racket
  #lang racket   ;; some silly boilerplate to mimic the assembly code better (define r0 0) (define (cmp r1 r2) (set! r0 (sgn (- r1 r2)))) (define (je true-label false-label) (if (zero? r0) (true-label) (false-label))) (define (goto label) (label))   (define (gcd %eax %ecx) (define %edx 0) (define (main) (goto loop)) (define (loop) (cmp 0 %ecx) (je end cont)) (define (cont) (set!-values [%eax %edx] (quotient/remainder %eax %ecx)) (set! %eax %ecx) (set! %ecx %edx) (goto loop)) (define (end) (printf "result: ~s\n" %eax) (return %eax)) (main))  
http://rosettacode.org/wiki/Flow-control_structures
Flow-control structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task Document common flow-control structures. One common example of a flow-control structure is the   goto   construct. Note that   Conditional Structures   and   Loop Structures   have their own articles/categories. Related tasks   Conditional Structures   Loop Structures
#Raku
Raku
TOWN: goto TOWN;
http://rosettacode.org/wiki/Floyd%27s_triangle
Floyd's triangle
Floyd's triangle   lists the natural numbers in a right triangle aligned to the left where the first row is   1     (unity) successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above. The first few lines of a Floyd triangle looks like this: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Task Write a program to generate and display here the first   n   lines of a Floyd triangle. (Use   n=5   and   n=14   rows). Ensure that when displayed in a mono-space font, the numbers line up in vertical columns as shown and that only one space separates numbers of the last row.
#Fortran
Fortran
  !-*- mode: compilation; default-directory: "/tmp/" -*- !Compilation started at Tue May 21 22:55:08 ! !a=./f && make $a && OMP_NUM_THREADS=2 $a 1223334444 !gfortran -std=f2008 -Wall -ffree-form -fall-intrinsics f.f08 -o f ! 1 ! 2 3 ! 4 5 6 ! 7 8 9 10 ! 11 12 13 14 15 ! ! ! 1 ! 2 3 ! 4 5 6 ! 7 8 9 10 ! 11 12 13 14 15 ! 16 17 18 19 20 21 ! 22 23 24 25 26 27 28 ! 29 30 31 32 33 34 35 36 ! 37 38 39 40 41 42 43 44 45 ! 46 47 48 49 50 51 52 53 54 55 ! 56 57 58 59 60 61 62 63 64 65 66 ! 67 68 69 70 71 72 73 74 75 76 77 78 ! 79 80 81 82 83 84 85 86 87 88 89 90 91 ! 92 93 94 95 96 97 98 99 100 101 102 103 104 105 ! ! ! !Compilation finished at Tue May 21 22:55:08     program p integer, dimension(2) :: examples = [5, 14] integer :: i do i=1, size(examples) call floyd(examples(i)) write(6, '(/)') end do   contains   subroutine floyd(rows) integer, intent(in) :: rows integer :: n, i, j, k integer, dimension(60) :: L character(len=504) :: fmt n = (rows*(rows+1))/2 ! Gauss's formula do i=1,rows ! compute format of final row L(i) = 2+int(log10(real(n-rows+i))) end do k = 0 do i=1,rows do j=1,i k = k+1 write(fmt,'(a2,i1,a1)')'(i',L(j),')' write(6,fmt,advance='no') k enddo write(6,*) '' end do end subroutine floyd   end program p  
http://rosettacode.org/wiki/Floyd-Warshall_algorithm
Floyd-Warshall algorithm
The Floyd–Warshall algorithm is an algorithm for finding shortest paths in a weighted graph with positive or negative edge weights. Task Find the lengths of the shortest paths between all pairs of vertices of the given directed graph. Your code may assume that the input has already been checked for loops, parallel edges and negative cycles. Print the pair, the distance and (optionally) the path. Example pair dist path 1 -> 2 -1 1 -> 3 -> 4 -> 2 1 -> 3 -2 1 -> 3 1 -> 4 0 1 -> 3 -> 4 2 -> 1 4 2 -> 1 2 -> 3 2 2 -> 1 -> 3 2 -> 4 4 2 -> 1 -> 3 -> 4 3 -> 1 5 3 -> 4 -> 2 -> 1 3 -> 2 1 3 -> 4 -> 2 3 -> 4 2 3 -> 4 4 -> 1 3 4 -> 2 -> 1 4 -> 2 -1 4 -> 2 4 -> 3 1 4 -> 2 -> 1 -> 3 See also Floyd-Warshall Algorithm - step by step guide (youtube)
#Perl
Perl
sub FloydWarshall{ my $edges = shift; my (@dist, @seq); my $num_vert = 0; # insert given dists into dist matrix map { $dist[$_->[0] - 1][$_->[1] - 1] = $_->[2]; $num_vert = $_->[0] if $num_vert < $_->[0]; $num_vert = $_->[1] if $num_vert < $_->[1]; } @$edges; my @vertices = 0..($num_vert - 1); # init sequence/"next" table for my $i(@vertices){ for my $j(@vertices){ $seq[$i][$j] = $j if $i != $j; } } # diagonal of dists matrix #map {$dist[$_][$_] = 0} @vertices; for my $k(@vertices){ for my $i(@vertices){ next unless defined $dist[$i][$k]; for my $j(@vertices){ next unless defined $dist[$k][$j]; if($i != $j && (!defined($dist[$i][$j]) || $dist[$i][$j] > $dist[$i][$k] + $dist[$k][$j])){ $dist[$i][$j] = $dist[$i][$k] + $dist[$k][$j]; $seq[$i][$j] = $seq[$i][$k]; } } } } # print table print "pair dist path\n"; for my $i(@vertices){ for my $j(@vertices){ next if $i == $j; my @path = ($i + 1); while($seq[$path[-1] - 1][$j] != $j){ push @path, $seq[$path[-1] - 1][$j] + 1; } push @path, $j + 1; printf "%d -> %d  %4d  %s\n", $path[0], $path[-1], $dist[$i][$j], join(' -> ', @path); } } }   my $graph = [[1, 3, -2], [2, 1, 4], [2, 3, 3], [3, 4, 2], [4, 2, -1]]; FloydWarshall($graph);
http://rosettacode.org/wiki/Function_definition
Function definition
A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract from showing how functions are created and values returned). Related task   Function prototype
#Swift
Swift
func multiply(a: Double, b: Double) -> Double { return a * b }