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/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
#Ada
Ada
>./last_weekday_in_month sunday 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
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
#ALGOL_68
ALGOL 68
BEGIN # find the last Sunday in each month of a year # # returns true if year is a leap year, false otherwise # # assumes year is in the Gregorian Calendar # PROC is leap year = ( INT year )BOOL: year MOD 400 = 0 OR ( year MOD 4 = 0 AND year MOD 100 /= 0 ); # returns the day of the week of the specified date (d/m/y) # # Sunday = 1 # PROC day of week = ( INT d, m, y )INT: BEGIN INT mm := m; INT yy := y; IF mm <= 2 THEN mm := mm + 12; yy := yy - 1 FI; INT j = yy OVER 100; INT k = yy MOD 100; (d + ( ( mm + 1 ) * 26 ) OVER 10 + k + k OVER 4 + j OVER 4 + 5 * j ) MOD 7 END # day of week # ; # returns an array of the last Sunday of each month in year # PROC last sundays = ( INT year )[]INT: BEGIN [ 1 : 12 ]INT last days := ( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ); IF is leap year( year ) THEN last days[ 2 ] := 29 FI; # for each month, determine the day number of the # # last Sunday # [ 1 : 12 ]INT last; FOR m pos TO 12 DO INT dow := day of week( last days[ m pos ], m pos, year ); IF dow = 0 # Saturday # THEN dow := 7 FI; # calculate the offset for the previous Sunday # last[ m pos ] := ( last days[ m pos ] + 1 ) - dow OD; last END # last sundays # ; # test the last sundays procedure # INT year = 2021; []INT last = last sundays( year ); FOR m pos TO 12 DO print( ( whole( year, 0 ) , IF m pos < 10 THEN "-0" ELSE "-1" FI , whole( m pos MOD 10, 0 ) , "-" , whole( last[ m pos ], 0 ) , newline ) ) OD 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) .
#Ada
Ada
with Ada.Text_IO;   procedure Intersection_Of_Two_Lines is Do_Not_Intersect : exception;   type Line is record a : Float; b : Float; end record;   type Point is record x : Float; y : Float; end record;   function To_Line(p1, p2 : in Point) return Line is a : constant Float := (p1.y - p2.y) / (p1.x - p2.x); b : constant Float := p1.y - (a * p1.x); begin return (a,b); end To_Line;   function Intersection(Left, Right : in Line) return Point is begin if Left.a = Right.a then raise Do_Not_Intersect with "The two lines do not intersect."; end if;   declare b : constant Float := (Right.b - Left.b) / (Left.a - Right.a); begin return (b, Left.a * b + Left.b); end; end Intersection;   A1 : constant Line := To_Line((4.0, 0.0), (6.0, 10.0)); A2 : constant Line := To_Line((0.0, 3.0), (10.0, 7.0)); p : constant Point := Intersection(A1, A2); begin Ada.Text_IO.Put(p.x'Img); Ada.Text_IO.Put_Line(p.y'Img); end Intersection_Of_Two_Lines;  
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
#8080_Assembly
8080 Assembly
  with: n   : num? \ n f -- ) if drop else . then ;   \ is m mod n 0? leave the result twice on the stack : div? \ m n -- f f mod 0 = dup ;   : fizz? \ n -- n f dup 3 div? if "Fizz" . then ;   : buzz? \ n f -- n f over 5 div? if "Buzz" . then or ;   \ print a message as appropriate for the given number: : fizzbuzz \ n -- fizz? buzz? num? space ;   \ iterate from 1 to 100: ' fizzbuzz 1 100 loop cr bye  
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
#AutoHotkey
AutoHotkey
Year := 1900 End_Year := 2100 31_Day_Months = 01,03,05,07,08,10,12   While Year <= End_Year { Loop, Parse, 31_Day_Months, CSV { FormatTime, Day, %Year%%A_LoopField%01, dddd IfEqual, Day, Friday { All_Months_With_5_Weekends .= A_LoopField . "/" . Year ", " 5_Weekend_Count++ Year_Has_5_Weekend_Month := 1 } } IfEqual, Year_Has_5_Weekend_Month, 0 { All_Years_Without_5_Weekend .= Year ", " No_5_Weekend_Count ++ } Year ++ Year_Has_5_Weekend_Month := 0 } ; Trim the spaces and comma off the last item. StringTrimRight, All_Months_With_5_Weekends, All_Months_With_5_Weekends, 5 StringTrimRight, All_Years_Without_5_Weekend, All_Years_Without_5_Weekend, 4 MsgBox, ( Months with 5 day weekends between 1900 and 2100 : %5_Weekend_Count% %All_Months_With_5_Weekends% ) MsgBox, ( Years with no 5 day weekends between 1900 and 2100 : %No_5_Weekend_Count% %All_Years_Without_5_Weekend% )
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
#D
D
import std.algorithm; import std.exception; import std.math; import std.stdio; import std.string;   string toBaseN(const long num, const int base) in (base > 1, "base cannot be less than 2") body { immutable ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; enforce(base < ALPHABET.length, "base cannot be represented");   char[] result; long cnum = abs(num); while (cnum > 0) { auto rem = cast(uint) (cnum % base); result ~= ALPHABET[rem]; cnum = (cnum - rem) / base; }   if (num < 0) { result ~= '-'; } return result.reverse.idup; }   int countUnique(string buf) { bool[char] m; foreach (c; buf) { m[c] = true; } return m.keys.length; }   void find(int base) { long nmin = cast(long) pow(cast(real) base, 0.5 * (base - 1));   for (long n = nmin; /*blank*/; n++) { auto sq = n * n; enforce(n * n > 0, "Overflowed the square"); string sqstr = toBaseN(sq, base); if (sqstr.length >= base && countUnique(sqstr) == base) { string nstr = toBaseN(n, base); writefln("Base %2d : Num %8s Square %16s", base, nstr, sqstr); return; } } }   void main() { foreach (i; 2..17) { find(i); } }
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
#Bori
Bori
double acos (double d) { return Math.acos(d); } double asin (double d) { return Math.asin(d); } double cos (double d) { return Math.cos(d); } double sin (double d) { return Math.sin(d); } double croot (double d) { return Math.pow(d, 1/3); } double cube (double x) { return x * x * x; }   Var compose (Var f, Var g, double x) { Func ff = f; Func fg = g; return ff(fg(x)); }   void button1_onClick (Widget widget) { Array arr1 = [ sin, cos, cube ]; Array arr2 = [ asin, acos, croot ];   str s; for (int i = 1; i <= 3; i++) { s << compose(arr1.get(i), arr2.get(i), 0.5) << str.newline; } label1.setText(s); }
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
#BQN
BQN
funsA ← ⟨⋆⟜2,-,•math.Sin,{𝕩×3}⟩ funsB ← ⟨√,-,•math.Asin,{𝕩÷3}⟩   comp ← funsA {𝕎∘𝕏}¨ funsB   •Show comp {𝕎𝕩}¨<0.5
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.
#Factor
Factor
USING: combinators grouping kernel literals math math.matrices math.vectors prettyprint random raylib.ffi sequences ; IN: rosetta-code.forest-fire   ! The following private vocab builds up to a useful combinator, ! matrix-map-neighbors, which takes a matrix, a quotation, and ! inside the quotation makes available each element of the ! matrix as well as its neighbors, mapping the result of the ! quotation to a new matrix.   <PRIVATE   CONSTANT: neighbors { { -1 -1 } { -1 0 } { -1 1 } { 0 -1 } { 0 1 } { 1 -1 } { 1 0 } { 1 1 } }   : ?i,j ( i j matrix -- elt/f ) swapd ?nth ?nth ;   : ?i,jths ( seq matrix -- newseq ) [ [ first2 ] dip ?i,j ] curry map ;   : neighbor-coords ( loc -- seq ) [ neighbors ] dip [ v+ ] curry map ;   : get-neighbors ( loc matrix -- seq ) [ neighbor-coords ] dip ?i,jths ;   : matrix>neighbors ( matrix -- seq ) dup dim matrix-coordinates concat [ swap get-neighbors sift ] with map ;   : matrix-map-neighbors ( ... matrix quot: ( ... neighbors elt -- ... newelt ) -- ... newmatrix ) [ [ dim first ] [ matrix>neighbors ] [ concat ] tri ] dip 2map swap group ; inline   PRIVATE>     ! ##### Simulation code #####   ! In our forest, ! 0 = empty ! 1 = tree ! 2 = fire   CONSTANT: ignite-probability 1/12000 CONSTANT: grow-probability 1/100   : make-forest ( m n probability -- matrix ) [ random-unit > 1 0 ? ] curry make-matrix ;   : ?ignite ( -- 1/2 ) ignite-probability random-unit > 2 1 ? ; : ?grow ( -- 0/1 ) grow-probability random-unit > 1 0 ? ;   : next-plot ( neighbors elt -- n ) { { [ dup 2 = ] [ 2drop 0 ] } { [ 2dup [ [ 2 = ] any? ] [ 1 = ] bi* and ] [ 2drop 2 ] } { [ 1 = ] [ drop ?ignite ] } [ drop ?grow ] } cond ;   : next-forest ( forest -- newforest ) [ next-plot ] matrix-map-neighbors ;     ! ##### Display code #####   CONSTANT: colors ${ GRAY GREEN RED }   : draw-forest ( matrix -- ) dup dim matrix-coordinates [ concat ] bi@ swap [ [ first2 [ 5 * ] bi@ 5 5 ] dip colors nth draw-rectangle ] 2each ;   500 500 "Forest Fire" init-window 100 100 1/2 make-forest 60 set-target-fps [ window-should-close ] [ begin-drawing BLACK clear-background dup draw-forest end-drawing next-forest ] until drop close-window
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.
#Kotlin
Kotlin
// version 1.1.3   class Environment(var seq: Int, var count: Int)   const val JOBS = 12 val envs = List(JOBS) { Environment(it + 1, 0) } var seq = 0 // 'seq' for current environment var count = 0 // 'count' for current environment var currId = 0 // index of current environment   fun switchTo(id: Int) { if (id != currId) { envs[currId].seq = seq envs[currId].count = count currId = id } seq = envs[id].seq count = envs[id].count }   fun hailstone() { print("%4d".format(seq)) if (seq == 1) return count++ seq = if (seq % 2 == 1) 3 * seq + 1 else seq / 2 }   val allDone get(): Boolean { for (a in 0 until JOBS) { switchTo(a) if (seq != 1) return false } return true }   fun code() { do { for (a in 0 until JOBS) { switchTo(a) hailstone() } println() } while (!allDone)   println("\nCOUNTS:") for (a in 0 until JOBS) { switchTo(a) print("%4d".format(count)) } println() }   fun main(args: Array<String>) { code() }
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
#CoffeeScript
CoffeeScript
  flatten = (arr) -> arr.reduce ((xs, el) -> if Array.isArray el xs.concat flatten el else xs.concat [el]), []   # test list = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []] console.log flatten list  
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.
#MATLAB
MATLAB
function FlippingBitsGame(n) % Play the flipping bits game on an n x n array   % Generate random target array fprintf('Welcome to the Flipping Bits Game!\n') if nargin < 1 n = input('What dimension array should we use? '); end Tar = logical(randi([0 1], n));   % Generate starting array by randomly flipping rows or columns Cur = Tar; while all(Cur(:) == Tar(:)) nFlips = randi([3*n max(10*n, 100)]); randDim = randi([0 1], nFlips, 1); randIdx = randi([1 n], nFlips, 1); for k = 1:nFlips if randDim(k) Cur(randIdx(k), :) = ~Cur(randIdx(k), :); else Cur(:, randIdx(k)) = ~Cur(:, randIdx(k)); end end end   % Print rules fprintf('Given a %d x %d logical array,\n', n, n) fprintf('and a target array configuration,\n') fprintf('attempt to transform the array to the target\n') fprintf('by inverting the bits in a whole row or column\n') fprintf('at once in as few moves as possible.\n') fprintf('Enter the corresponding letter to invert a column,\n') fprintf('or the corresponding number to invert a row.\n') fprintf('0 will reprint the target array, and no entry quits.\n\n') fprintf('Target:\n') PrintArray(Tar)   % Play until player wins or quits move = true; nMoves = 0; while ~isempty(move) && any(Cur(:) ~= Tar(:)) fprintf('Move %d:\n', nMoves) PrintArray(Cur) move = lower(input('Enter move: ', 's')); if length(move) > 1 fprintf('Invalid move, try again\n') elseif move r = str2double(move); if isnan(r) c = move-96; if c > n || c < 1 fprintf('Invalid move, try again\n') else Cur(:, c) = ~Cur(:, c); nMoves = nMoves+1; end else if r > n || r < 0 fprintf('Invalid move, try again\n') elseif r == 0 fprintf('Target:\n') PrintArray(Tar) else Cur(r, :) = ~Cur(r, :); nMoves = nMoves+1; end end end end   if all(Cur(:) == Tar(:)) fprintf('You win in %d moves! Try not to flip out!\n', nMoves) else fprintf('Quitting? The challenge a bit much for you?\n') end end   function PrintArray(A) [nRows, nCols] = size(A); fprintf(' ') fprintf(' %c', (1:nCols)+96) fprintf('\n') for r = 1:nRows fprintf('%8d%s\n', r, sprintf(' %d', A(r, :))) end fprintf('\n') end
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.
#Kotlin
Kotlin
import kotlin.math.ln import kotlin.math.pow   fun main() { runTest(12, 1) runTest(12, 2) runTest(123, 45) runTest(123, 12345) runTest(123, 678910) }   private fun runTest(l: Int, n: Int) { // System.out.printf("p(%d, %d) = %,d%n", l, n, p(l, n)) println("p($l, $n) = %,d".format(p(l, n))) }   fun p(l: Int, n: Int): Int { var m = n var test = 0 val log = ln(2.0) / ln(10.0) var factor = 1 var loop = l while (loop > 10) { factor *= 10 loop /= 10 } while (m > 0) { test++ val value = (factor * 10.0.pow(test * log % 1)).toInt() if (value == l) { m-- } } return test }
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
#Lua
Lua
  -- This function returns another function that -- keeps n1 and n2 in scope, ie. a closure. function multiplier (n1, n2) return function (m) return n1 * n2 * m end end   -- Multiple assignment a-go-go local x, xi, y, yi = 2.0, 0.5, 4.0, 0.25 local z, zi = x + y, 1.0 / ( x + y ) local nums, invs = {x, y, z}, {xi, yi, zi}   -- 'new_function' stores the closure and then has the 0.5 applied to it -- (this 0.5 isn't in the task description but everyone else used it) for k, v in pairs(nums) do new_function = multiplier(v, invs[k]) print(v .. " * " .. invs[k] .. " * 0.5 = " .. new_function(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
#M2000_Interpreter
M2000 Interpreter
  Module CheckIt { \\ by default numbers are double x = 2 xi = 0.5 y = 4 yi = 0.25 z = x + y zi = 1 / ( x + y ) Composed=lambda (a, b)-> { =lambda a,b (n)->{ =a*b*n } } numbers=(x,y,z) inverses=(xi,yi,zi) Dim Base 0, combo(3) combo(0)=Composed(x,xi), Composed(y,yi), Composed(z,zi) num=each(numbers) inv=each(inverses) fun=each(combo()) While num, inv, fun { Print $("0.00"), Array(num);" * ";Array(inv);" * 0.50 = "; combo(fun^)(0.5),$("") Print } } Checkit \\ for functions we have this definition Composed=lambda (f1, f2) -> { =lambda f1, f2 (x)->{ =f1(f2(x)) } }    
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
#Oforth
Oforth
break
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
#Oz
Oz
case {OS.rand} mod 3 of 0 then {Foo} [] 1 then {Bar} [] 2 then {Buzz} end
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.
#Cowgol
Cowgol
include "cowgol.coh";   sub width(n: uint16): (w: uint8) is w := 1; while n >= 10 loop n := n / 10; w := w + 1; end loop; end sub;   sub print_fixed(n: uint16, w: uint8) is w := w - width(n); while w > 0 loop print_char(' '); w := w - 1; end loop; print_i16(n); end sub;   sub floyd(rows: uint16) is var maxno := rows * (rows+1)/2; var num: uint16 := 1; var row: uint16 := 1; while row <= rows loop var col: uint16 := 1; while col <= row loop print_fixed(num, 1 + width(maxno - rows + col)); num := num + 1; col := col + 1; end loop; print_nl(); row := row + 1; end loop; end sub;   floyd(5); print_nl(); floyd(14);
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)
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
g = Graph[{1 \[DirectedEdge] 3, 3 \[DirectedEdge] 4, 4 \[DirectedEdge] 2, 2 \[DirectedEdge] 1, 2 \[DirectedEdge] 3}, EdgeWeight -> {(1 \[DirectedEdge] 3) -> -2, (3 \[DirectedEdge] 4) -> 2, (4 \[DirectedEdge] 2) -> -1, (2 \[DirectedEdge] 1) -> 4, (2 \[DirectedEdge] 3) -> 3}] vl = VertexList[g]; dm = GraphDistanceMatrix[g]; Grid[LexicographicSort[ DeleteCases[ Catenate[ Table[{vl[[i]], vl[[j]], dm[[i, j]]}, {i, Length[vl]}, {j, Length[vl]}]], {x_, x_, _}]]]
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
#SETL
SETL
proc multiply( a, b ); return a * b; end proc;
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
#Sidef
Sidef
func multiply(a, b) { a * b; }
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.)
#Pascal
Pascal
Program ForwardDifferenceDemo(output);   procedure fowardDifference(list: array of integer); var b: array of integer; i, newlength: integer; begin newlength := length(list) - 1; if newlength > 0 then begin setlength(b, newlength); for i := low(b) to high(b) do begin b[i] := list[i+1] - list[i]; write (b[i]:6); end; writeln; fowardDifference(b); end; end;   var a: array [1..10] of integer = (90, 47, 58, 29, 22, 32, 55, 5, 55, 73); begin fowardDifference(a); end.
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.
#Sather
Sather
class MAIN is main is #OUT + #FMT("<F0 #####.###>", 7.1257) + "\n"; #OUT + #FMT("<F0 #####.###>", 7.1254) + "\n"; end; end;
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.
#Scala
Scala
object FormattedNumeric { val r = 7.125 //> r  : Double = 7.125 println(f" ${-r}%9.3f"); //> -7,125 println(f" $r%9.3f"); //> 7,125 println(f" $r%-9.3f"); //> 7,125 println(f" ${-r}%09.3f"); //> -0007,125 println(f" $r%09.3f"); //> 00007,125 println(f" $r%-9.3f"); //> 7,125 println(f" $r%+09.3f"); //> +0007,125 }
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).
#PicoLisp
PicoLisp
(de halfAdder (A B) #> (Carry . Sum) (cons (and A B) (xor A B) ) )   (de fullAdder (A B C) #> (Carry . Sum) (let (Ha1 (halfAdder C A) Ha2 (halfAdder (cdr Ha1) B)) (cons (or (car Ha1) (car Ha2)) (cdr Ha2) ) ) )   (de 4bitsAdder (A4 A3 A2 A1 B4 B3 B2 B1) #> (V S4 S3 S2 S1) (let (Fa1 (fullAdder A1 B1) Fa2 (fullAdder A2 B2 (car Fa1)) Fa3 (fullAdder A3 B3 (car Fa2)) Fa4 (fullAdder A4 B4 (car Fa3)) ) (list (car Fa4) (cdr Fa4) (cdr Fa3) (cdr Fa2) (cdr Fa1) ) ) )
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.
#Groovy
Groovy
class Fivenum { static double median(double[] x, int start, int endInclusive) { int size = endInclusive - start + 1 if (size <= 0) { throw new IllegalArgumentException("Array slice cannot be empty") } int m = start + (int) (size / 2) return (size % 2 == 1) ? x[m] : (x[m - 1] + x[m]) / 2.0 }   static double[] fivenum(double[] x) { for (Double d : x) { if (d.isNaN()) { throw new IllegalArgumentException("Unable to deal with arrays containing NaN") } } double[] result = new double[5] Arrays.sort(x) result[0] = x[0] result[2] = median(x, 0, x.length - 1) result[4] = x[x.length - 1] int m = (int) (x.length / 2) int lowerEnd = (x.length % 2 == 1) ? m : m - 1 result[1] = median(x, 0, lowerEnd) result[3] = median(x, m, x.length - 1) return result }   static void main(String[] args) { double[][] xl = [ [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 (double[] x : xl) { println("${fivenum(x)}") } } }
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)
#8086_Assembly
8086 Assembly
cpu 8086 org 100h mov si,perms ; Start of permutations xor bx,bx ; First word of permutation xor dx,dx ; Second word of permutation mov cx,23 ; There are 23 permutations given perm: lodsw ; Load first word of permutation xor bx,ax ; XOR with first word of missing lodsw ; Load second word of permutation xor dx,ax ; XOR with second word of missing loop perm ; Get next permutation mov [mperm],bx ; Store in placeholder mov [mperm+2],dx mov ah,9 ; Write output mov dx,msg int 21h ret msg: db 'Missing permutation: ' mperm: db 0,0,0,0,'$' ; Placeholder perms: db 'ABCD','CABD','ACDB','DACB','BCDA','ACBD','ADCB','CDAB' db 'DABC','BCAD','CADB','CDBA','CBAD','ABDC','ADBC','BDCA' db 'DCBA','BACD','BADC','BDAC','CBDA','DBCA','DCAB'
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
#ALGOL-M
ALGOL-M
  BEGIN   % CALCULATE P MOD Q % INTEGER FUNCTION MOD(P, Q); INTEGER P, Q; BEGIN MOD := P - Q * (P / Q); END;   COMMENT RETURN DAY OF WEEK (SUN=0, MON=1, ETC.) FOR A GIVEN GREGORIAN CALENDAR DATE USING ZELLER'S CONGRUENCE; INTEGER FUNCTION DAYOFWEEK(MO, DA, YR); INTEGER MO, DA, YR; BEGIN INTEGER Y, C, Z; IF MO < 3 THEN BEGIN MO := MO + 10; YR := YR - 1; END ELSE MO := MO - 2; Y := MOD(YR, 100); C := YR / 100; Z := (26 * MO - 2) / 10; Z := Z + DA + Y + (Y / 4) + (C / 4) - 2 * C + 777; DAYOFWEEK := MOD(Z, 7); END;   % RETURN 1 IF Y IS A LEAP YEAR, OTHERWISE 0 % INTEGER FUNCTION ISLEAPYR(Y); INTEGER Y; BEGIN IF MOD(Y,4) <> 0 THEN  % QUICK EXIT IN MOST COMMON CASE % ISLEAPYR := 0 ELSE IF MOD(Y,400) = 0 THEN ISLEAPYR := 1 ELSE IF MOD(Y,100) = 0 THEN ISLEAPYR := 0 ELSE  % NON-CENTURY AND DIVISIBLE BY 4 % ISLEAPYR := 1; END;   % RETURN THE NUMBER OF DAYS IN THE SPECIFIED MONTH % INTEGER FUNCTION MONTHDAYS(MO, YR); INTEGER MO, YR; BEGIN IF MO = 2 THEN BEGIN IF ISLEAPYR(YR) = 1 THEN MONTHDAYS := 29 ELSE MONTHDAYS := 28; END ELSE IF (MO = 4) OR (MO = 6) OR (MO = 9) OR (MO = 11) THEN MONTHDAYS := 30 ELSE MONTHDAYS := 31; END;   COMMENT RETURN THE DAY OF THE MONTH CORRESPONDING TO LAST OCCURRENCE OF WEEKDAY K (SUN=0, MON=1, ETC.) FOR A GIVEN MONTH AND YEAR; INTEGER FUNCTION LASTKDAY(K, M, Y); INTEGER K, M, Y; BEGIN INTEGER D, W;  % DETERMINE WEEKDAY FOR THE LAST DAY OF THE MONTH % D := MONTHDAYS(M, Y); W := DAYOFWEEK(M, D, Y);  % BACK UP AS NEEDED TO DESIRED WEEKDAY % IF W >= K THEN D := D - (W - K) ELSE D := D - (7 - K - W); LASTKDAY := D; END;   STRING FUNCTION MONTHNAME(N); INTEGER N; BEGIN CASE (N - 1) OF BEGIN MONTHNAME := "JAN"; MONTHNAME := "FEB"; MONTHNAME := "MAR"; MONTHNAME := "APR"; MONTHNAME := "MAY"; MONTHNAME := "JUN"; MONTHNAME := "JUL"; MONTHNAME := "AUG"; MONTHNAME := "SEP"; MONTHNAME := "OCT"; MONTHNAME := "NOV"; MONTHNAME := "DEC"; END; END;   % EXERCISE THE ROUTINE % INTEGER M, Y, SUNDAY; SUNDAY := 0; WRITE("DISPLAY LAST SUNDAYS FOR WHAT YEAR?"); READ(Y); FOR M:=1 STEP 1 UNTIL 12 DO WRITE(MONTHNAME(M), LASTKDAY(SUNDAY,M,Y));   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
#ALGOL_W
ALGOL W
begin % find the last Sunday in each month of a year  %  % returns true if year is a leap year, false otherwise  %  % assumes year is in the Gregorian Calendar  % logical procedure isLeapYear ( integer value year ) ; year rem 400 = 0 or ( year rem 4 = 0 and year rem 100 not = 0 );  % returns the day of the week of the specified date (d/m/y)  %  % Sunday = 1  % integer procedure Day_of_week ( integer value d, m, y ); begin integer j, k, mm, yy; mm := m; yy := y; if mm <= 2 then begin mm := mm + 12; yy := yy - 1; end if_m_le_2; j := yy div 100; k := yy rem 100; (d + ( ( mm + 1 ) * 26 ) div 10 + k + k div 4 + j div 4 + 5 * j ) rem 7 end Day_of_week;  % sets the elements of last to the day of the last Sunday  %  % of each month in year  % procedure lastSundays ( integer value year  ; integer array last ( * ) ) ; begin integer array lastDays ( 1 :: 12 ); integer m;  % set ld to the day number od the last day of each  %  % month in year  % m := 1; for ld := 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 do begin lastDays( m ) := ld; m  := m + 1 end for_ld ; if isLeapYear( year ) then lastDays( 2 ) := 29;  % for each month, determine the day number of the  %  % last Sunday  % for mPos := 1 until 12 do begin integer dow; dow := Day_of_week( lastDays( mPos ), mPos, year ); if dow = 0 % Saturday % then dow := 7;  % calculate the offset for the previous Sunday  % last( mPos ) := ( lastDays( mPos ) + 1 ) - dow end for_mPos end lastSundays ; begin  % test the lastSundays procedure  % integer array last ( 1 :: 12 ); integer year; year := 2020; lastSundays( year, last ); i_w := 1; s_w := 0; % output formatting  % for mPos := 1 until 12 do write( year, if mPos < 10 then "-0" else "-1", mPos rem 10, "-", last( mPos ) ) end 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) .
#ALGOL_68
ALGOL 68
BEGIN # mode to hold a point # MODE POINT = STRUCT( REAL x, y ); # mode to hold a line expressed as y = mx + c # MODE LINE = STRUCT( REAL m, c ); # returns the line that passes through p1 and p2 # PROC find line = ( POINT p1, p2 )LINE: IF x OF p1 = x OF p2 THEN # the line is vertical # LINE( 0, x OF p1 ) ELSE # the line is not vertical # REAL m = ( y OF p1 - y OF p2 ) / ( x OF p1 - x OF p2 ); LINE( m, y OF p1 - ( m * x OF p1 ) ) FI # find line # ;   # returns the intersection of two lines - the lines must be distinct and not parallel # PRIO INTERSECTION = 5; OP INTERSECTION = ( LINE l1, l2 )POINT: BEGIN REAL x = ( c OF l2 - c OF l1 ) / ( m OF l1 - m OF l2 ); POINT( x, ( m OF l1 * x ) + c OF l1 ) END # INTERSECTION # ;   # find the intersection of the lines as per the task # POINT i = find line( POINT( 4.0, 0.0 ), POINT( 6.0, 10.0 ) ) INTERSECTION find line( ( 0.0, 3.0 ), ( 10.0, 7.0 ) ); print( ( fixed( x OF i, -8, 4 ), fixed( y OF i, -8, 4 ), newline ) )   END
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].
#11l
11l
F intersection_point(ray_direction, ray_point, plane_normal, plane_point) R ray_point - ray_direction * dot(ray_point - plane_point, plane_normal) / dot(ray_direction, plane_normal)   print(‘The ray intersects the plane at ’intersection_point((0.0, -1.0, -1.0), (0.0, 0.0, 10.0), (0.0, 0.0, 1.0), (0.0, 0.0, 5.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
#8086_Assembly
8086 Assembly
  with: n   : num? \ n f -- ) if drop else . then ;   \ is m mod n 0? leave the result twice on the stack : div? \ m n -- f f mod 0 = dup ;   : fizz? \ n -- n f dup 3 div? if "Fizz" . then ;   : buzz? \ n f -- n f over 5 div? if "Buzz" . then or ;   \ print a message as appropriate for the given number: : fizzbuzz \ n -- fizz? buzz? num? space ;   \ iterate from 1 to 100: ' fizzbuzz 1 100 loop cr bye  
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
#AutoIt
AutoIt
  #include <Date.au3> #include <Array.au3> $array = Five_weekends(1) _ArrayDisplay($array) $array = Five_weekends(2) _ArrayDisplay($array) $array = Five_weekends(3) _ArrayDisplay($array)   Func Five_weekends($ret = 1) If $ret < 1 Or $ret > 3 Then Return SetError(1, 0, 0) Local $avDateArray[1] Local $avYearArray[1] Local $avMonthArray[1] For $iYear = 1900 To 2100 Local $checkyear = False For $iMonth = 1 To 12 If _DateDaysInMonth($iYear, $iMonth) <> 31 Then ContinueLoop ; Month has less then 31 Days If _DateToDayOfWeek($iYear, $iMonth, "01") <> 6 Then ContinueLoop ;First Day is not a Friday _ArrayAdd($avMonthArray, $iYear & "-" & _DateToMonth($iMonth)) $checkyear = True For $s = 1 To 31 Local $Date = _DateToDayOfWeek($iYear, $iMonth, $s) If $Date = 6 Or $Date = 7 Or $Date = 1 Then ; if Date is Friday, Saturday or Sunday _ArrayAdd($avDateArray, $iYear & "\" & StringFormat("%02d", $iMonth) & "\" & StringFormat("%02d", $s)) EndIf Next Next If Not $checkyear Then _ArrayAdd($avYearArray, $iYear) Next $avDateArray[0] = UBound($avDateArray) - 1 $avYearArray[0] = UBound($avYearArray) - 1 $avMonthArray[0] = UBound($avMonthArray) - 1 If $ret = 1 Then Return $avDateArray ElseIf $ret = 2 Then Return $avYearArray ElseIf $ret = 3 Then Return $avMonthArray EndIf EndFunc ;==>Five_weekends  
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
#F.23
F#
  // Nigel Galloway: May 21st., 2019 let fN g=let g=int64(sqrt(float(pown g (int(g-1L)))))+1L in (Seq.unfold(fun(n,g)->Some(n,(n+g,g+2L))))(g*g,g*2L+1L) let fG n g=Array.unfold(fun n->if n=0L then None else let n,g=System.Math.DivRem(n,g) in Some(g,n)) n let fL g=let n=set[0L..g-1L] in Seq.find(fun x->set(fG x g)=n) (fN g) let toS n g=let a=Array.concat [[|'0'..'9'|];[|'a'..'f'|]] in System.String(Array.rev(fG n g)|>Array.map(fun n->a.[(int n)])) [2L..16L]|>List.iter(fun n->let g=fL n in printfn "Base %d: %s² -> %s" n (toS (int64(sqrt(float g))) n) (toS g n))  
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
#Bracmat
Bracmat
( (sqrt=.!arg^1/2) & (log=.e\L!arg) & (A=x2d (=.!arg^2) log (=.!arg*pi)) & ( B = d2x sqrt (=.e^!arg) (=.!arg*pi^-1) ) & ( compose = f g .  !arg:(?f.?g) & '(.($f)$(($g)$!arg)) ) & whl ' ( !A:%?F ?A & !B:%?G ?B & out$((compose$(!F.!G))$3210) ) )
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
#C
C
#include <stdlib.h> #include <stdio.h> #include <math.h>   /* declare a typedef for a function pointer */ typedef double (*Class2Func)(double);   /*A couple of functions with the above prototype */ double functionA( double v) { return v*v*v; } double functionB(double v) { return exp(log(v)/3); }   /* A function taking a function as an argument */ double Function1( Class2Func f2, double val ) { return f2(val); }   /*A function returning a function */ Class2Func WhichFunc( int idx) { return (idx < 4) ? &functionA : &functionB; }   /* A list of functions */ Class2Func funcListA[] = {&functionA, &sin, &cos, &tan }; Class2Func funcListB[] = {&functionB, &asin, &acos, &atan };   /* Composing Functions */ double InvokeComposed( Class2Func f1, Class2Func f2, double val ) { return f1(f2(val)); }   typedef struct sComposition { Class2Func f1; Class2Func f2; } *Composition;   Composition Compose( Class2Func f1, Class2Func f2) { Composition comp = malloc(sizeof(struct sComposition)); comp->f1 = f1; comp->f2 = f2; return comp; }   double CallComposed( Composition comp, double val ) { return comp->f1( comp->f2(val) ); } /** * * * * * * * * * * * * * * * * * * * * * * * * * * */   int main(int argc, char *argv[]) { int ix; Composition c;   printf("Function1(functionA, 3.0) = %f\n", Function1(WhichFunc(0), 3.0));   for (ix=0; ix<4; ix++) { c = Compose(funcListA[ix], funcListB[ix]); printf("Compostion %d(0.9) = %f\n", ix, CallComposed(c, 0.9)); }   return 0; }
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.
#Forth
Forth
30 CONSTANT WIDTH 30 CONSTANT HEIGHT WIDTH HEIGHT * CONSTANT SIZE   1 VALUE SEED : (RAND) ( -- u) \ xorshift generator SEED DUP 13 LSHIFT XOR DUP 17 RSHIFT XOR DUP 5 LSHIFT XOR DUP TO SEED ; 10000 CONSTANT RANGE 100 CONSTANT GROW 1 CONSTANT BURN : RAND ( -- u) (RAND) RANGE MOD ;   \ Create buffers for world state CREATE A SIZE ALLOT A SIZE ERASE CREATE B SIZE ALLOT B SIZE ERASE   0 CONSTANT NONE 1 CONSTANT TREE 2 CONSTANT FIRE : NEARBY-FIRE? ( addr u -- t|f) 2 -1 DO 2 -1 DO J WIDTH * I + OVER + \ calculate an offset DUP 0> OVER SIZE < AND IF >R OVER R> + C@ \ fetch state of the offset cell FIRE = IF UNLOOP UNLOOP DROP DROP TRUE EXIT THEN ELSE DROP THEN LOOP LOOP DROP DROP FALSE ; : GROW? RAND GROW <= ; \ spontaneously sprout? : BURN? RAND BURN <= ; \ spontaneously combust? : STEP ( prev next --) \ Given state in PREV, put next in NEXT >R 0 BEGIN DUP SIZE < WHILE 2DUP + C@ CASE FIRE OF NONE ENDOF TREE OF 2DUP NEARBY-FIRE? BURN? OR IF FIRE ELSE TREE THEN ENDOF NONE OF GROW? IF TREE ELSE NONE THEN ENDOF ENDCASE ( i next-cell-state) OVER R@ + C! \ commit to next 1+ REPEAT R> DROP DROP DROP ;   : (ESCAPE) 27 EMIT [CHAR] [ EMIT ; : ESCAPE" POSTPONE (ESCAPE) POSTPONE S" POSTPONE TYPE ; IMMEDIATE : CLEAR ESCAPE" H" ; : RETURN ESCAPE" E" ; : RESET ESCAPE" m" ; : .FOREST ( addr --) CLEAR HEIGHT 0 DO WIDTH 0 DO DUP C@ CASE NONE OF SPACE ENDOF TREE OF ESCAPE" 32m" [CHAR] T EMIT RESET ENDOF FIRE OF ESCAPE" 31m" [CHAR] # EMIT RESET ENDOF ENDCASE 1+ LOOP RETURN LOOP RESET DROP ;   : (GO) ( buffer buffer' -- buffer' buffer) 2DUP STEP \ step the simulation DUP .FOREST \ print the current state SWAP ; \ prepare for next iteration : GO A B BEGIN (GO) AGAIN ;
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.
#Lua
Lua
  local envs = { } for i = 1, 12 do -- fallback to the global environment for io and math envs[i] = setmetatable({ count = 0, n = i }, { __index = _G }) end   local code = [[ io.write(("% 4d"):format(n)) if n ~= 1 then count = count + 1 n = (n % 2 == 1) and 3 * n + 1 or math.floor(n / 2) end ]]   while true do local finished = 0 for _, env in ipairs(envs) do if env.n == 1 then finished = finished + 1 end end   if finished == #envs then break end   for _, env in ipairs(envs) do -- 5.1; in 5.2, use load(code, nil, nil, env)() instead setfenv(loadstring(code), env)() end io.write "\n" end   print "counts:" for _, env in ipairs(envs) do io.write(("% 4d"):format(env.count)) 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.
#Nim
Nim
import strformat   const Jobs = 12   type Environment = object sequence: int count: int   var env: array[Jobs, Environment] sequence, count: ptr int   #---------------------------------------------------------------------------------------------------   proc hail() = stdout.write fmt"{sequence[]: 4d}" if sequence[] == 1: return inc count[] sequence[] = if (sequence[] and 1) != 0: 3 * sequence[] + 1 else: sequence[] div 2   #---------------------------------------------------------------------------------------------------   proc switchTo(id: int) = sequence = addr(env[id].sequence) count = addr(env[id].count)   #---------------------------------------------------------------------------------------------------   template forAllJobs(statements: untyped): untyped = for i in 0..<Jobs: switchTo(i) statements   #———————————————————————————————————————————————————————————————————————————————————————————————————   for i in 0..<Jobs: switchTo(i) env[i].sequence = i + 1   var terminated = false while not terminated:   forAllJobs: hail() echo ""   terminated = true forAllJobs: if sequence[] != 1: terminated = false break   echo "" echo "Counts:" forAllJobs: stdout.write fmt"{count[]: 4d}" echo ""
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
#Common_Lisp
Common Lisp
(defun flatten (structure) (cond ((null structure) nil) ((atom structure) (list structure)) (t (mapcan #'flatten structure))))
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.
#MiniScript
MiniScript
// Flipping Bits game. // Transform a start grid to an end grid by flipping rows or columns.   size = 3   board = [] goal = [] for i in range(1,size) row = [] for j in range(1,size) row.push (rnd > 0.5) end for board.push row goal.push row[0:] end for   flipRow = function(n) for j in range(0, size-1) board[n-1][j] = not board[n-1][j] end for end function   flipCol = function(n) for i in range(0, size-1) board[i][n-1] = not board[i][n-1] end for end function   flipAny = function(s) s = s[0].upper if s >= "A" then flipCol s.code - 64 else flipRow val(s) end function   for scramble in range(20) if rnd < 0.5 then flipRow ceil(rnd*size) else flipCol ceil(rnd*size) end for   solved = function() for i in range(0, size-1) for j in range(0, size-1) if board[i][j] != goal[i][j] then return false end for end for return true end function   moveCount = 0 while true print " CURRENT:" + " "*(4+size*3) + "GOAL:" for i in range(1,size) s = i + " " + str(board[i-1]) s = s + " "*(3+size*3) + str(goal[i-1]) print s end for s = " " for i in range(1,size) s = s + char(64+i) + " " end for print s if solved then break moveCount = moveCount + 1 inp = input("Move " + moveCount + "? ") flipAny(inp) end while print "You did it!"
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.
#Nim
Nim
import random, strformat, strutils   type Bit = range[0..1] Board = array[3, array[3, Bit]]     #---------------------------------------------------------------------------------------------------   func flipRow(board: var Board; row: int) = for cell in board[row].mitems: cell = 1 - cell   #---------------------------------------------------------------------------------------------------   func flipCol(board: var Board; col: int) = for row in board.mitems: row[col] = 1 - row[col]   #---------------------------------------------------------------------------------------------------   proc initBoard(target: Board): Board =   # Starting from the target we make 9 random row or column flips. result = target for _ in 1..9: if rand(1) == 0: result.flipRow(rand(2)) else: result.flipCol(rand(2))   #---------------------------------------------------------------------------------------------------   proc print(board: Board; label: string) =   echo &"{label}:" echo " | a b c" echo "---------" for r, row in board: stdout.write &"{r + 1} |" for cell in row: stdout.write &" {cell}" echo "" echo ""     #———————————————————————————————————————————————————————————————————————————————————————————————————   var target, board: Board   randomize()   # Initialize target. for row in target.mitems: for cell in row.mitems: cell = rand(1)   # Initialize board and ensure it differs from the target i.e. game not already over! while true: board = initBoard(target) if board != target: break   target.print("TARGET") board.print("OPENING BOARD")   var flips = 0 while board != target:   # Get input from player. var isRow = true var n = -1 while n < 0: stdout.write "Enter row number or column letter to be flipped: " stdout.flushFile() let input = stdin.readLine() let ch = if input.len > 0: input[0].toLowerAscii else: '0' if ch notin "123abc": echo "Must be 1, 2, 3, a, b or c" continue if ch in '1'..'3': n = ord(ch) - ord('1') else: isRow = false n = ord(ch) - ord('a')   # Update board. inc flips if isRow: board.flipRow(n) else: board.flipCol(n) target.print("\nTARGET") let plural = if flips == 1: "" else: "S" board.print(&"BOARD AFTER {flips} FLIP{plural}")   let plural = if flips == 1: "" else: "s" echo &"You’ve succeeded in {flips} flip{plural}"
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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
f = Compile[{{ll, _Integer}, {n, _Integer}}, Module[{l, digitcount, log10power, raised, found, firstdigits, pwr = 2}, l = Abs[ll]; digitcount = Floor[Log[10, l]]; log10power = Log[10, pwr]; raised = -1; found = 0; While[found < n, raised++; firstdigits = Floor[10^(FractionalPart[log10power raised] + digitcount)]; If[firstdigits == l, found += 1; ] ]; Return[raised] ] ]; f[12, 1] f[12, 2] f[123, 45] f[123, 12345] f[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.
#Nim
Nim
import math, strformat   const Lfloat64 = pow(2.0, 64) Log10_2_64 = int(Lfloat64 * log10(2.0))   #---------------------------------------------------------------------------------------------------   func ordinal(n: int): string = case n of 1: "1st" of 2: "2nd" of 3: "3rd" else: $n & "th"   #---------------------------------------------------------------------------------------------------   proc findExp(number, countLimit: int) =   var i = number var digits = 1 while i >= 10: digits *= 10 i = i div 10   var lmtLower, lmtUpper: uint64 var log10num = log10((number + 1) / digits) if log10num >= 0.5: lmtUpper = if (number + 1) / digits < 10: uint(log10Num * (Lfloat64 * 0.5)) * 2 + uint(log10Num * 2) else: 0 log10Num = log10(number / digits) lmtLower = uint(log10Num * (Lfloat64 * 0.5)) * 2 + uint(log10Num * 2) else: lmtUpper = uint(log10Num * Lfloat64) lmtLower = uint(log10(number / digits) * Lfloat64)   var count = 0 var frac64 = 0u64 var p = 0 if lmtUpper != 0: while true: inc p inc frac64, Log10_2_64 if frac64 in lmtLower..lmtUpper: inc count if count >= countLimit: break else: # Searching for "999...". while true: inc p inc frac64, Log10_2_64 if frac64 >= lmtLower: inc count if count >= countLimit: break   echo fmt"""The {ordinal(count)} occurrence of 2 raised to a power""" & fmt""" whose product starts with "{number}" is {p}"""   #———————————————————————————————————————————————————————————————————————————————————————————————————   findExp(12, 1) findExp(12, 2)   findExp(123, 45) findExp(123, 12345) findExp(123, 678910)
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
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
multiplier[n1_,n2_]:=n1 n2 #& num={2,4,2+4}; numi=1/num; multiplierfuncs = multiplier @@@ Transpose[{num, numi}];  
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
#Nemerle
Nemerle
using System; using System.Console; using Nemerle.Collections.NCollectionsExtensions;   module FirstClassNums { Main() : void { def x = 2.0; def xi = 0.5; def y = 4.0; def yi = 0.25; def z = x + y; def zi = 1.0 / (x + y); def multiplier = fun (a, b) {fun (c) {a * b * c}}; def nums = [x, y, z]; def inums = [xi, yi, zi]; WriteLine($[multiplier(n, m) (0.5)|(n, m) in ZipLazy(nums, inums)]); } }
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
#PARI.2FGP
PARI/GP
label jumpto; begin ... jumpto: some statement; ... goto jumpto; ... end;
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
#Pascal
Pascal
label jumpto; begin ... jumpto: some statement; ... goto jumpto; ... end;
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.
#D
D
import std.stdio, std.conv;   void floydTriangle(in uint n) { immutable lowerLeftCorner = n * (n - 1) / 2 + 1; foreach (r; 0 .. n) foreach (c; 0 .. r + 1) writef("%*d%c", text(lowerLeftCorner + c).length, r * (r + 1) / 2 + c + 1, c == r ? '\n' : ' '); }   void main() { floydTriangle(5); floydTriangle(14); }
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)
#Mercury
Mercury
:- module floyd_warshall_task.   :- interface. :- import_module io. :- pred main(io, io). :- mode main(di, uo) is det.   :- implementation. :- import_module float. :- import_module int. :- import_module list. :- import_module string. :- import_module version_array2d.   %%%-------------------------------------------------------------------   %% Square arrays with 1-based indexing.   :- func arr_init(int, T) = version_array2d(T). arr_init(N, Fill) = version_array2d.init(N, N, Fill).   :- func arr_get(version_array2d(T), int, int) = T. arr_get(Arr, I, J) = Elem :- I1 = I - 1, J1 = J - 1, Elem = Arr^elem(I1, J1).   :- func arr_set(version_array2d(T), int, int, T) = version_array2d(T). arr_set(Arr0, I, J, Elem) = Arr :- I1 = I - 1, J1 = J - 1, Arr = (Arr0^elem(I1, J1) := Elem).   %%%-------------------------------------------------------------------   :- func find_max_vertex(list({int, float, int})) = int. find_max_vertex(Edges) = find_max_vertex_(Edges, 0).   :- func find_max_vertex_(list({int, float, int}), int) = int. find_max_vertex_([], MaxVertex0) = MaxVertex0. find_max_vertex_([{U, _, V} | Tail], MaxVertex0) = MaxVertex :- MaxVertex = find_max_vertex_(Tail, max(max(MaxVertex0, U), V)).   %%%-------------------------------------------------------------------   :- func arbitrary_float = float. arbitrary_float = (12345.0).   :- func nil_vertex = int. nil_vertex = 0.   :- func floyd_warshall(list({int, float, int})) = {int, version_array2d(float), version_array2d(int)}. floyd_warshall(Edges) = {N, Dist, Next} :- N = find_max_vertex(Edges), Dist0 = arr_init(N, arbitrary_float), Next0 = arr_init(N, nil_vertex), (if (N = 0) then (Dist = Dist0, Next = Next0) else ({Dist1, Next1} = floyd_warshall_initialize(Edges, N, Dist0, Next0), {Dist, Next} = floyd_warshall_loop_k(N, 1, Dist1, Next1))).   :- func floyd_warshall_initialize(list({int, float, int}), int, version_array2d(float), version_array2d(int)) = {version_array2d(float), version_array2d(int)}. floyd_warshall_initialize(Edges, N, Dist0, Next0) = {Dist1, Next1} :- floyd_warshall_read_edges(Edges, Dist0, Next0) = {D1, X1}, floyd_warshall_diagonals(N, 1, D1, X1) = {Dist1, Next1}.   :- func floyd_warshall_read_edges(list({int, float, int}), version_array2d(float), version_array2d(int)) = {version_array2d(float), version_array2d(int)}. floyd_warshall_read_edges([], Dist0, Next0) = {Dist0, Next0}. floyd_warshall_read_edges([{U, Weight, V} | Tail], Dist0, Next0) = {Dist1, Next1} :- D1 = arr_set(Dist0, U, V, Weight), X1 = arr_set(Next0, U, V, V), floyd_warshall_read_edges(Tail, D1, X1) = {Dist1, Next1}.   :- func floyd_warshall_diagonals(int, int, version_array2d(float), version_array2d(int)) = {version_array2d(float), version_array2d(int)}. floyd_warshall_diagonals(N, I, Dist0, Next0) = {Dist1, Next1} :- N1 = N + 1, (if (I = N1) then (Dist1 = Dist0, Next1 = Next0) else (  %% The distance from a vertex to itself = 0.0. D1 = arr_set(Dist0, I, I, 0.0), X1 = arr_set(Next0, I, I, I), I1 = I + 1, floyd_warshall_diagonals(N, I1, D1, X1) = {Dist1, Next1})).   :- func floyd_warshall_loop_k(int, int, version_array2d(float), version_array2d(int)) = {version_array2d(float), version_array2d(int)}. floyd_warshall_loop_k(N, K, Dist0, Next0) = {Dist1, Next1} :- N1 = N + 1, (if (K = N1) then (Dist1 = Dist0, Next1 = Next0) else ({D1, X1} = floyd_warshall_loop_i(N, K, 1, Dist0, Next0), K1 = K + 1, {Dist1, Next1} = floyd_warshall_loop_k(N, K1, D1, X1))).   :- func floyd_warshall_loop_i(int, int, int, version_array2d(float), version_array2d(int)) = {version_array2d(float), version_array2d(int)}. floyd_warshall_loop_i(N, K, I, Dist0, Next0) = {Dist1, Next1} :- N1 = N + 1, (if (I = N1) then (Dist1 = Dist0, Next1 = Next0) else ({D1, X1} = floyd_warshall_loop_j(N, K, I, 1, Dist0, Next0), I1 = I + 1, {Dist1, Next1} = floyd_warshall_loop_i(N, K, I1, D1, X1))).   :- func floyd_warshall_loop_j(int, int, int, int, version_array2d(float), version_array2d(int)) = {version_array2d(float), version_array2d(int)}. floyd_warshall_loop_j(N, K, I, J, Dist0, Next0) = {Dist1, Next1} :- J1 = J + 1, N1 = N + 1, (if (J = N1) then (Dist1 = Dist0, Next1 = Next0) else (if ((arr_get(Next0, I, K) = nil_vertex); (arr_get(Next0, K, J) = nil_vertex)) then ({Dist1, Next1} = floyd_warshall_loop_j(N, K, I, J1, Dist0, Next0)) else (Dist_ikj = arr_get(Dist0, I, K) + arr_get(Dist0, K, J), (if (arr_get(Next0, I, J) = nil_vertex; Dist_ikj < arr_get(Dist0, I, J)) then (D1 = arr_set(Dist0, I, J, Dist_ikj), X1 = arr_set(Next0, I, J, arr_get(Next0, I, K)), {Dist1, Next1} = floyd_warshall_loop_j(N, K, I, J1, D1, X1)) else ({Dist1, Next1} = floyd_warshall_loop_j(N, K, I, J1, Dist0, Next0)))))).   %%%-------------------------------------------------------------------   :- func path_string(version_array2d(int), int, int) = string. path_string(Next, U, V) = S :- if (arr_get(Next, U, V) = nil_vertex) then S = "" else S = path_string_(Next, U, V, int_to_string(U)).   :- func path_string_(version_array2d(int), int, int, string) = string. path_string_(Next, U, V, S0) = S :- (if (U = V) then (S = S0) else (U1 = arr_get(Next, U, V), S1 = append(append(S0, " -> "), int_to_string(U1)), path_string_(Next, U1, V, S1) = S)).   %%%-------------------------------------------------------------------   main(!IO) :- Example_graph = [{1, -2.0, 3}, {3, 2.0, 4}, {4, -1.0, 2}, {2, 4.0, 1}, {2, 3.0, 3}], {N, Dist, Next} = floyd_warshall(Example_graph), format(" pair distance path\n", [], !IO), format("-------------------------------------\n", [], !IO), main_loop_u(N, 1, Dist, Next, !IO).   :- pred main_loop_u(int, int, version_array2d(float), version_array2d(int), io, io). :- mode main_loop_u(in, in, in, in, di, uo) is det. main_loop_u(N, U, Dist, Next, !IO) :- N1 = N + 1, (if (U = N1) then true else (main_loop_v(N, U, 1, Dist, Next, !IO), U1 = U + 1, main_loop_u(N, U1, Dist, Next, !IO))).   :- pred main_loop_v(int, int, int, version_array2d(float), version_array2d(int), io, io). :- mode main_loop_v(in, in, in, in, in, di, uo) is det. main_loop_v(N, U, V, Dist, Next, !IO) :- V1 = V + 1, N1 = N + 1, (if (V = N1) then true else if (U = V) then main_loop_v(N, U, V1, Dist, Next, !IO) else (format(" %d -> %d  %4.1f  %s\n", [i(U), i(V), f(arr_get(Dist, U, V)), s(path_string(Next, U, V))],  !IO), main_loop_v(N, U, V1, Dist, Next, !IO))).   %%%------------------------------------------------------------------- %%% local variables: %%% mode: mercury %%% prolog-indent-width: 2 %%% 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
#Simula
Simula
BEGIN INTEGER PROCEDURE multiply(x, y); INTEGER x, y; BEGIN multiply := x * y END; Outint(multiply(7,8), 2); Outimage 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
#Slate
Slate
define: #multiply -> [| :a :b | a * b].
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.)
#Perl
Perl
sub dif { my @s = @_; map { $s[$_+1] - $s[$_] } 0 .. $#s-1 }   @a = qw<90 47 58 29 22 32 55 5 55 73>; while (@a) { printf('%6d', $_) for @a = dif @a; print "\n" }
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.
#Scheme
Scheme
(load "srfi-54.scm") (load "srfi-54.scm") ;; Don't ask.   (define x 295643087.65432)   (dotimes (i 4) (print (cat x 25 3.0 #\0 (list #\, (- 4 i)))))  
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.
#Seed7
Seed7
$ include "seed7_05.s7i"; include "float.s7i";   const proc: main is func local const float: r is 7.125; begin writeln( r digits 3 lpad 9); writeln(-r digits 3 lpad 9); writeln( r digits 3 lpad0 9); writeln(-r digits 3 lpad0 9); writeln( r digits 3); writeln(-r digits 3); end func;
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).
#PL.2FI
PL/I
  /* 4-BIT ADDER */   TEST: PROCEDURE OPTIONS (MAIN); DECLARE CARRY_IN BIT (1) STATIC INITIAL ('0'B) ALIGNED; declare (m, n, sum)(4) bit(1) aligned; declare i fixed binary;   get edit (m, n) (b(1)); put edit (m, ' + ', n, ' = ') (4 b, a);   do i = 4 to 1 by -1; call full_adder ((carry_in), m(i), n(i), sum(i), carry_in); end; put edit (sum) (b);   HALF_ADDER: PROCEDURE (IN1, IN2, SUM, CARRY); DECLARE (IN1, IN2, SUM, CARRY) BIT (1) ALIGNED;   SUM = ( ^IN1 & IN2) | ( IN1 & ^IN2); /* Exclusive OR using only AND, NOT, OR. */ CARRY = IN1 & IN2;   END HALF_ADDER;   FULL_ADDER: PROCEDURE (CARRY_IN, IN1, IN2, SUM, CARRY); DECLARE (CARRY_IN, IN1, IN2, SUM, CARRY) BIT (1) ALIGNED; DECLARE (SUM2, CARRY2) BIT (1) ALIGNED;   CALL HALF_ADDER (CARRY_IN, IN1, SUM, CARRY); CALL HALF_ADDER (SUM, IN2, SUM2, CARRY2); SUM = SUM2; CARRY = CARRY | CARRY2; END FULL_ADDER;   END TEST;  
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.
#Haskell
Haskell
import Data.List (sort)   fivenum :: [Double] -> [Double] fivenum [] = [] fivenum xs | l >= 5 = fmap ( (/ 2) . ( (+) . (!!) s . floor <*> (!!) s . ceiling ) . pred ) [1, q, succ l / 2, succ l - q, l] | otherwise = s where l = realToFrac $ length xs q = realToFrac (floor $ (l + 3) / 2) / 2 s = sort xs   main :: IO () main = print $ fivenum [ 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 ]
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)
#Action.21
Action!
PROC Main() DEFINE PTR="CARD" DEFINE COUNT="23" PTR ARRAY perm(COUNT) CHAR ARRAY s,missing=[4 0 0 0 0] BYTE i,j   perm(0)="ABCD" perm(1)="CABD" perm(2)="ACDB" perm(3)="DACB" perm(4)="BCDA" perm(5)="ACBD" perm(6)="ADCB" perm(7)="CDAB" perm(8)="DABC" perm(9)="BCAD" perm(10)="CADB" perm(11)="CDBA" perm(12)="CBAD" perm(13)="ABDC" perm(14)="ADBC" perm(15)="BDCA" perm(16)="DCBA" perm(17)="BACD" perm(18)="BADC" perm(19)="BDAC" perm(20)="CBDA" perm(21)="DBCA" perm(22)="DCAB"   FOR i=0 TO COUNT-1 DO s=perm(i) FOR j=1 TO 4 DO missing(j)==XOR s(j) OD OD   Print(missing) RETURN
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
#AppleScript
AppleScript
-- LAST SUNDAYS OF YEAR ------------------------------------------------------   -- lastSundaysOfYear :: Int -> [Date] on lastSundaysOfYear(y)   -- lastWeekDaysOfYear :: Int -> Int -> [Date] script lastWeekDaysOfYear on |λ|(intYear, iWeekday)   -- lastWeekDay :: Int -> Int -> Date script lastWeekDay on |λ|(iLastDay, iMonth) set iYear to intYear   calendarDate(iYear, iMonth, iLastDay - ¬ (((weekday of calendarDate(iYear, iMonth, iLastDay)) as integer) + ¬ (7 - (iWeekday))) mod 7) end |λ| end script   map(lastWeekDay, lastDaysOfMonths(intYear)) end |λ|   -- isLeapYear :: Int -> Bool on isLeapYear(y) (0 = y mod 4) and (0 ≠ y mod 100) or (0 = y mod 400) end isLeapYear   -- lastDaysOfMonths :: Int -> [Int] on lastDaysOfMonths(y) {31, cond(isLeapYear(y), 29, 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31} end lastDaysOfMonths end script   lastWeekDaysOfYear's |λ|(y, Sunday as integer) end lastSundaysOfYear     -- TEST ---------------------------------------------------------------------- on run argv   intercalate(linefeed, ¬ map(isoRow, ¬ transpose(map(lastSundaysOfYear, ¬ apply(cond(class of argv is list and argv ≠ {}, ¬ singleYearOrRange, fiveCurrentYears), argIntegers(argv))))))   end run   -- ARGUMENT HANDLING ---------------------------------------------------------   -- Up to two optional command line arguments: [yearFrom], [yearTo] -- (Default range in absence of arguments: from two years ago, to two years ahead)   -- ~ $ osascript ~/Desktop/lastSundays.scpt -- ~ $ osascript ~/Desktop/lastSundays.scpt 2013 -- ~ $ osascript ~/Desktop/lastSundays.scpt 2013 2016   -- singleYearOrRange :: [Int] -> [Int] on singleYearOrRange(argv) apply(cond(length of argv > 0, my range, my fiveCurrentYears), argv) end singleYearOrRange   -- fiveCurrentYears :: () -> [Int] on fiveCurrentYears(_) set intThisYear to year of (current date) enumFromTo(intThisYear - 2, intThisYear + 2) end fiveCurrentYears   -- argIntegers :: maybe [String] -> [Int] on argIntegers(argv) if class of argv is list and argv ≠ {} then {map(my parseInt, argv)} else {} end if end argIntegers     -- GENERIC FUNCTIONS ---------------------------------------------------------   -- apply (a -> b) -> a -> b on apply(f, a) mReturn(f)'s |λ|(a) end apply   -- calendarDate :: Int -> Int -> Int -> Date on calendarDate(intYear, intMonth, intDay) tell (current date) set {its year, its month, its day, its time} to ¬ {intYear, intMonth, intDay, 0} return it end tell end calendarDate   -- cond :: Bool -> (a -> b) -> (a -> b) -> (a -> b) on cond(bool, f, g) if bool then f else g end if end cond   -- enumFromTo :: Int -> Int -> [Int] on enumFromTo(m, n) if m > n then set d to -1 else set d to 1 end if set lst to {} repeat with i from m to n by d set end of lst to i end repeat return lst end enumFromTo   -- intercalate :: Text -> [Text] -> Text on intercalate(strText, lstText) set {dlm, my text item delimiters} to ¬ {my text item delimiters, strText} set strJoined to lstText as text set my text item delimiters to dlm return strJoined end intercalate   -- isoDateString :: Date -> String on isoDateString(dte) (((year of dte) as string) & ¬ "-" & text items -2 thru -1 of ¬ ("0" & ((month of dte) as integer) as string)) & ¬ "-" & text items -2 thru -1 of ¬ ("0" & day of dte) end isoDateString   -- isoRow :: [Date] -> String on isoRow(lstDate) intercalate(tab, map(my isoDateString, lstDate)) end isoRow   -- map :: (a -> b) -> [a] -> [b] on map(f, xs) tell mReturn(f) set lng to length of xs set lst to {} repeat with i from 1 to lng set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell end map   -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: Handler -> Script on mReturn(f) if class of f is script then f else script property |λ| : f end script end if end mReturn   -- parseInt :: String -> Int on parseInt(s) s as integer end parseInt   -- transpose :: [[a]] -> [[a]] on transpose(xss) script column on |λ|(_, iCol) script row on |λ|(xs) item iCol of xs end |λ| end script   map(row, xss) end |λ| end script   map(column, item 1 of xss) end transpose
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) .
#APL
APL
  ⍝ APL has a powerful operator the « dyadic domino » to solve a system of N linear equations with N unknowns ⍝ We use it first to solve the a and b, defining the 2 lines as y = ax + b, with the x and y of the given points ⍝ The system of equations for first line will be: ⍝ 0 = 4a + b ⍝ 10 = 6a + b ⍝ The two arguments to be passed to the dyadic domino are: ⍝ The (0, 10) vector as the left argument ⍝ The ( 4 1 ) matrix as the right argument. ⍝ ( 6 1 ) ⍝ We will define a solver that will take the matrix of coordinates, one point per row, then massage the argument to extract x,y ⍝ and inject 1, where needed, and return a pair (a, b) of resolved unknowns. ⍝ Applied twice, we will have a, b and a', b' defining the two lines, we need to resolve it in x and y, in order to determine ⍝ their intersection ⍝ y = ax + b ⍝ y = a'x + b' ⍝ In order to reuse the same solver, we need to format a little bit the arguments, and change the sign of a and a', therefore ⍝ multiply (a,b) and (a', b') by (-1, 1): ⍝ b = -ax + y ⍝ b' = -a'x + y A ← 4 0 B ← 6 10 C ← 0 3 D ← 10 7 solver ← {(,2 ¯1↑⍵)⌹(2 1↑⍵),1} I ← solver 2 2⍴((¯1 1)×solver 2 2⍴A,B),(¯1 1)×solver 2 2⍴C,D  
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) .
#Arturo
Arturo
define :point [x,y][] define :line [a, b][ init: [ this\slope: div this\b\y-this\a\y this\b\x-this\a\x this\yInt: this\a\y - this\slope*this\a\x ] ]   evalX: function [line, x][ line\yInt + line\slope * x ]   intersect: function [line1, line2][ x: div line2\yInt-line1\yInt line1\slope-line2\slope y: evalX line1 x   to :point @[x y] ]   l1: to :line @[to :point [4.0 0.0] to :point [6.0 10.0]] l2: to :line @[to :point [0.0 3.0] to :point [10.0 7.0]]   print intersect l1 l2
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].
#Action.21
Action!
INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit   DEFINE REALPTR="CARD" TYPE VectorR=[REALPTR x,y,z]   PROC PrintVector(VectorR POINTER v) Print("(") PrintR(v.x) Print(",") PrintR(v.y) Print(",") PrintR(v.z) Print(")") RETURN   PROC Vector(REAL POINTER vx,vy,vz VectorR POINTER v) v.x=vx v.y=vy v.z=vz RETURN   PROC VectorSub(VectorR POINTER a,b,res) RealSub(a.x,b.x,res.x) RealSub(a.y,b.y,res.y) RealSub(a.z,b.z,res.z) RETURN   PROC VectorDot(VectorR POINTER a,b REAL POINTER res) REAL tmp1,tmp2   RealMult(a.x,b.x,res) RealMult(a.y,b.y,tmp1) RealAdd(res,tmp1,tmp2) RealMult(a.z,b.z,tmp1) RealAdd(tmp1,tmp2,res) RETURN   PROC VectorMul(VectorR POINTER a REAL POINTER b VectorR POINTER res) RealMult(a.x,b,res.x) RealMult(a.y,b,res.y) RealMult(a.z,b,res.z) RETURN   BYTE FUNC IsZero(REAL POINTER a) CHAR ARRAY s(10)   StrR(a,s) IF s(0)=1 AND s(1)='0 THEN RETURN (1) FI RETURN (0)   BYTE FUNC Intersection(VectorR POINTER rayVector,rayPoint,planeNormal,planePoint,result)   REAL tmpx,tmpy,tmpz,prod1,prod2,prod3 VectorR tmp   Vector(tmpx,tmpy,tmpz,tmp)   VectorSub(rayPoint,planePoint,tmp) VectorDot(tmp,planeNormal,prod1) VectorDot(rayVector,planeNormal,prod2)   IF IsZero(prod2) THEN RETURN (1) FI   RealDiv(prod1,prod2,prod3) VectorMul(rayVector,prod3,tmp) VectorSub(rayPoint,tmp,result) RETURN (0)   PROC Test(VectorR POINTER rayVector,rayPoint,planeNormal,planePoint) BYTE res REAL px,py,pz VectorR p   Vector(px,py,pz,p) res=Intersection(rayVector,rayPoint,planeNormal,planePoint,p)   Print("Ray vector: ") PrintVector(rayVector) PutE() Print("Ray point: ") PrintVector(rayPoint) PutE() Print("Plane normal: ") PrintVector(planeNormal) PutE() Print("Plane point: ") PrintVector(planePoint) PutE()   IF res=0 THEN Print("Intersection point: ") PrintVector(p) PutE() ELSEIF res=1 THEN PrintE("There is no intersection") FI PutE() RETURN   PROC Main() REAL r0,r1,r5,r10,rm1 VectorR rayVector,rayPoint,planeNormal,planePoint   Put(125) PutE() ;clear screen   ValR("0",r0) ValR("1",r1) ValR("5",r5) ValR("10",r10) ValR("-1",rm1)   Vector(r0,rm1,rm1,rayVector) Vector(r0,r0,r10,rayPoint) Vector(r0,r0,r1,planeNormal) Vector(r0,r0,r5,planePoint) Test(rayVector,rayPoint,planeNormal,planePoint)   Vector(r1,r1,r0,rayVector) Vector(r1,r1,r0,rayPoint) Vector(r0,r0,r1,planeNormal) Vector(r5,r1,r0,planePoint) Test(rayVector,rayPoint,planeNormal,planePoint) 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].
#Ada
Ada
with Ada.Numerics.Generic_Real_Arrays; with Ada.Text_IO;   procedure Intersection is   type Real is new Long_Float;   package Real_Arrays is new Ada.Numerics.Generic_Real_Arrays (Real => Real); use Real_Arrays;   package Real_IO is new Ada.Text_IO.Float_IO (Num => Real);   subtype Vector_3D is Real_Vector (1 .. 3);   function Line_Plane_Intersection (Line_Vector  : in Vector_3D; Line_Point  : in Vector_3D; Plane_Normal : in Vector_3D; Plane_Point  : in Vector_3D) return Vector_3D is Diff  : constant Vector_3D := Line_Point - Plane_Point; Denom : constant Real  := Line_Vector * Plane_Normal; begin if Denom = 0.0 then raise Constraint_Error with "Line does not intersect plane"; end if; declare Scale : constant Real := -Real'(Diff * Plane_Normal) / Denom; Point : constant Vector_3D := Diff + Plane_Point + Scale * Line_Vector; begin return Point; end; end Line_Plane_Intersection;   procedure Put (V : in Vector_3D) is use Ada.Text_IO, Real_IO; begin Put ("("); Put (V (1)); Put (","); Put (V (2)); Put (","); Put (V (3)); Put (")"); end Put;   begin Real_IO.Default_Exp := 0; Real_IO.Default_Aft := 3;   Put (Line_Plane_Intersection (Line_Vector => (0.0, -1.0, -1.0), Line_Point => (0.0, 0.0, 10.0), Plane_Normal => (0.0, 0.0, 1.0), Plane_Point => (0.0, 0.0, 5.0))); end Intersection;
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
#8th
8th
  with: n   : num? \ n f -- ) if drop else . then ;   \ is m mod n 0? leave the result twice on the stack : div? \ m n -- f f mod 0 = dup ;   : fizz? \ n -- n f dup 3 div? if "Fizz" . then ;   : buzz? \ n f -- n f over 5 div? if "Buzz" . then or ;   \ print a message as appropriate for the given number: : fizzbuzz \ n -- fizz? buzz? num? space ;   \ iterate from 1 to 100: ' fizzbuzz 1 100 loop cr bye  
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
#AWK
AWK
  # usage: awk -f 5weekends.awk cal.txt   # Filter a file of month-calendars, such as # ... ## January 1901 ## Mo Tu We Th Fr Sa Su ## 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 # ... ## March 1901 ## Mo Tu We Th Fr Sa Su ## 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 # ... # This file is generated by a script for the unix-shell, # see http://rosettacode.org/wiki/Five_weekends#UNIX_Shell   BEGIN { print("# Month with 5 weekends:") badYears = numW5 = 0; lastW5 = -1 }   0+$2>33 { if( $2>currYear ) { # calendar-header: month, year if( lastW5==numW5 ) { badYears++; sep="\n" if( badYears % 10 ) { sep=" " } bY=bY currYear sep; # collect years in string ##print badYears,":", currYear } lastW5=numW5 } WE=0; currYear=$2; currMY = $1 " " $2; ##print currMY; next }   /^Mo/ { next } # skip lines with weekday-names   { $0 = substr($0,13) } # cut inputline, leave Fr,Sa,Su only   NF>2 { WE++; # 3 fields left => complete weekend found if( WE>4 ) { numW5++; printf("%4d : %s\n", numW5, currMY) } }   END { print("# Found", numW5, "month with 5 weekends.") print("# Found", badYears, "years with no month having 5 weekends:") print(bY) }  
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
#Factor
Factor
USING: assocs formatting fry kernel math math.functions math.parser math.ranges math.statistics sequences ; IN: rosetta-code.A260182   : pandigital? ( n base -- ? ) [ >base histogram assoc-size ] keep >= ;   ! Return the smallest decimal integer square root whose squared ! digit length in base n is at least n. : search-start ( base -- n ) dup 1 - ^ sqrt ceiling >integer ;   : find-root ( base -- n ) [ search-start ] [ ] bi '[ dup sq _ pandigital? ] [ 1 + ] until ;   : show-base ( base -- ) dup find-root dup sq pick [ >base ] curry bi@ "Base %2d: %8s squared = %s\n" printf ;   : main ( -- ) 2 16 [a,b] [ show-base ] each ;   MAIN: main
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
#Forth
Forth
  #! /usr/bin/gforth-fast   : 2^ 1 swap lshift ;   : sq s" dup *" evaluate ; immediate   : min-root ( -- n ) \ minimum root that can be pandigitial base @ s>f fdup 1e f- 0.5e f* f** f>s ;   : pandigital? ( n -- f ) 0 swap \ bitmask begin base @ /mod >r 2^ or r> dup 0= until drop base @ 2^ 1- = ;   : panroot ( -- n ) \ get the minimum square root using the variable BASE. min-root 1- begin 1+ dup sq pandigital? until ;   : .squares ( -- ) base @ 17 2 do i base ! i 2 dec.r 3 spaces panroot dup 8 .r ." ² = " sq . cr loop base ! ;   .squares bye  
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
#C.23
C#
using System;   class Program { static void Main(string[] args) { var cube = new Func<double, double>(x => Math.Pow(x, 3.0)); var croot = new Func<double, double>(x => Math.Pow(x, 1 / 3.0));   var functionTuples = new[] { (forward: Math.Sin, backward: Math.Asin), (forward: Math.Cos, backward: Math.Acos), (forward: cube, backward: croot) };   foreach (var ft in functionTuples) { Console.WriteLine(ft.backward(ft.forward(0.5))); } } }  
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.
#Fortran
Fortran
module ForestFireModel implicit none   type :: forestfire integer, dimension(:,:,:), allocatable :: field integer :: width, height integer :: swapu real :: prob_tree, prob_f, prob_p end type forestfire   integer, parameter :: & empty = 0, & tree = 1, & burning = 2   private :: bcheck, set, oget, burning_neighbor ! cset, get   contains   ! create and initialize the field(s) function forestfire_new(w, h, pt, pf, pp) result(res) type(forestfire) :: res integer, intent(in) :: w, h real, intent(in), optional :: pt, pf, pp   integer :: i, j real :: r   allocate(res%field(2,w,h)) ! no error check res%prob_tree = 0.5 res%prob_f = 0.00001 res%prob_p = 0.001 if ( present(pt) ) res%prob_tree = pt if ( present(pf) ) res%prob_f = pf if ( present(pp) ) res%prob_p = pp   res%width = w res%height = h res%swapu = 0   res%field = empty   do i = 1,w do j = 1,h call random_number(r) if ( r <= res%prob_tree ) call cset(res, i, j, tree) end do end do   end function forestfire_new   ! destroy the field(s) subroutine forestfire_destroy(f) type(forestfire), intent(inout) :: f   if ( allocated(f%field) ) deallocate(f%field)   end subroutine forestfire_destroy   ! evolution subroutine forestfire_evolve(f) type(forestfire), intent(inout) :: f   integer :: i, j real :: r   do i = 1, f%width do j = 1, f%height select case ( get(f, i, j) ) case (burning) call set(f, i, j, empty) case (empty) call random_number(r) if ( r > f%prob_p ) then call set(f, i, j, empty) else call set(f, i, j, tree) end if case (tree) if ( burning_neighbor(f, i, j) ) then call set(f, i, j, burning) else call random_number(r) if ( r > f%prob_f ) then call set(f, i, j, tree) else call set(f, i, j, burning) end if end if end select end do end do f%swapu = ieor(f%swapu, 1) end subroutine forestfire_evolve   ! helper funcs/subs subroutine set(f, i, j, t) type(forestfire), intent(inout) :: f integer, intent(in) :: i, j, t   if ( bcheck(f, i, j) ) then f%field(ieor(f%swapu,1), i, j) = t end if end subroutine set   subroutine cset(f, i, j, t) type(forestfire), intent(inout) :: f integer, intent(in) :: i, j, t   if ( bcheck(f, i, j) ) then f%field(f%swapu, i, j) = t end if end subroutine cset   function bcheck(f, i, j) logical :: bcheck type(forestfire), intent(in) :: f integer, intent(in) :: i, j   bcheck = .false. if ( (i >= 1) .and. (i <= f%width) .and. & (j >= 1) .and. (j <= f%height) ) bcheck = .true.   end function bcheck     function get(f, i, j) result(r) integer :: r type(forestfire), intent(in) :: f integer, intent(in) :: i, j   if ( .not. bcheck(f, i, j) ) then r = empty else r = f%field(f%swapu, i, j) end if end function get   function oget(f, i, j) result(r) integer :: r type(forestfire), intent(in) :: f integer, intent(in) :: i, j   if ( .not. bcheck(f, i, j) ) then r = empty else r = f%field(ieor(f%swapu,1), i, j) end if end function oget   function burning_neighbor(f, i, j) result(r) logical :: r type(forestfire), intent(in) :: f integer, intent(in) :: i, j   integer, dimension(3,3) :: s   s = f%field(f%swapu, i-1:i+1, j-1:j+1) s(2,2) = empty r = any(s == burning) end function burning_neighbor   subroutine forestfire_print(f) type(forestfire), intent(in) :: f   integer :: i, j   do j = 1, f%height do i = 1, f%width select case(get(f, i, j)) case (empty) write(*,'(A)', advance='no') '.' case (tree) write(*,'(A)', advance='no') 'Y' case (burning) write(*,'(A)', advance='no') '*' end select end do write(*,*) end do end subroutine forestfire_print   end module ForestFireModel
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.
#Order
Order
#include <order/interpreter.h>   #define ORDER_PP_DEF_8hail ORDER_PP_FN( \ 8fn(8N, 8cond((8equal(8N, 1), 1) \ (8is_0(8remainder(8N, 2)), 8quotient(8N, 2)) \ (8else, 8inc(8times(8N, 3))))) )   #define ORDER_PP_DEF_8h_loop ORDER_PP_FN( \ 8fn(8S, \ 8let((8F, 8fn(8E, 8env_ref(8(8H), 8E))), \ 8do( \ 8print(8seq_to_tuple(8seq_map(8F, 8S)) 8space), \ 8let((8S, 8h_once(8S)), \ 8if(8equal(1, \ 8seq_fold(8times, 1, 8seq_map(8F, 8S))), \ 8print_counts(8S), \ 8h_loop(8S)))))) )   #define ORDER_PP_DEF_8h_once ORDER_PP_FN( \ 8fn(8S, \ 8seq_map( \ 8fn(8E, \ 8eval(8E, \ 8quote( \ 8env_bind(8(8C), \ 8env_bind(8(8H), \ 8env_bind(8(8E), 8E, 8E), \ 8hail(8H)), \ 8if(8equal(8H, 1), 8C, 8inc(8C))) ))), \ 8S)) )   #define ORDER_PP_DEF_8print_counts ORDER_PP_FN( \ 8fn(8S, \ 8print(8space 8(Counts:) \ 8seq_to_tuple(8seq_map(8fn(8E, 8env_ref(8(8C), 8E)), 8S)))) )   ORDER_PP( 8let((8S, // Build a list of environments 8seq_map(8fn(8N, 8seq_of_pairs_to_env( 8seq(8pair(8(8H), 8N), 8pair(8(8C), 0), 8pair(8(8E), 8env_nil)))), 8seq_iota(1, 13))), 8h_loop(8S)) )
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.
#Perl
Perl
  use strict; use warnings;   use Safe;   sub hail_next { my $n = shift; return 1 if $n == 1; return $n * 3 + 1 if $n % 2; $n / 2; };   my @enviornments; for my $initial ( 1..12 ) { my $env = Safe->new; ${ $env->varglob('value') } = $initial; ${ $env->varglob('count') } = 0; $env->share('&hail_next'); $env->reval(q{ sub task { return if $value == 1; $value = hail_next( $value ); ++$count; } }); push @enviornments, $env; }   my @value_refs = map $_->varglob('value'), @enviornments; my @tasks = map $_->varglob('task'), @enviornments; while( grep { $$_ != 1 } @value_refs ) { printf "%4s", $$_ for @value_refs; print "\n"; $_->() for @tasks; }   print "Counts\n";   printf "%4s", ${$_->varglob('count')} for @enviornments; print "\n";  
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
#Crystal
Crystal
  [[1], 2, [[3, 4], 5], [[[] of Int32]], [[[6]]], 7, 8, [] of Int32].flatten()  
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.
#OCaml
OCaml
module FlipGame = struct type t = bool array array   let make side = Array.make_matrix side side false   let flipcol b n = for i = 0 to (Array.length b - 1) do b.(n).(i) <- not b.(n).(i) done   let fliprow b n = for i = 0 to (Array.length b - 1) do b.(i).(n) <- not b.(i).(n) done   let randflip b = let n = Random.int (Array.length b - 1) in match Random.bool () with | true -> fliprow b n | false -> flipcol b n   let rec game side steps = let start, target = make side, make side in for i = 1 to steps do randflip start; randflip target done; if start = target then game side steps (* try again *) else (start, target)   let print b = for i = 0 to Array.length b - 1 do for j = 0 to Array.length b - 1 do Printf.printf " %d " (if b.(j).(i) then 1 else 0) done; print_newline () done; print_newline ()   let draw_game board target = print_endline "TARGET"; print target; print_endline "BOARD"; print board end   let play () = let module G = FlipGame in let board, target = G.game 3 10 in let steps = ref 0 in while board <> target do G.draw_game board target; print_string "> "; flush stdout; incr steps; match String.split_on_char ' ' (read_line ()) with | ["row"; row] -> (match int_of_string_opt row with | Some n -> G.fliprow board n | None -> print_endline "(nothing happens)") | ["col"; col] -> (match int_of_string_opt col with | Some n -> G.flipcol board n | None -> print_endline "(nothing happens)") | _ -> () done; G.draw_game board target; Printf.printf "\n\nGame solved in %d steps\n" !steps   let () = if not !Sys.interactive then (Random.self_init (); play ())
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.
#Pascal
Pascal
program Power2FirstDigits;   uses sysutils, strUtils;   const {$IFDEF FPC} {$MODE DELPHI}   ld10 :double = ln(2)/ln(10);// thats 1/log2(10) {$ELSE} ld10 = 0.30102999566398119521373889472449;   function Numb2USA(const S: string): string; var i, NA: Integer; begin i := Length(S); Result := S; NA := 0; while (i > 0) do begin if ((Length(Result) - i + 1 - NA) mod 3 = 0) and (i <> 1) then begin insert(',', Result, i); inc(NA); end; Dec(i); end; end;   {$ENDIF}   function FindExp(CntLmt, Number: NativeUint): NativeUint; var i, cnt, DgtShift: NativeUInt; begin //calc how many Digits needed i := Number; DgtShift := 1; while i >= 10 do begin DgtShift := DgtShift * 10; i := i div 10; end;   cnt := 0; i := 0; repeat inc(i); // x= i*ld10 -> 2^I = 10^x // 10^frac(x) -> [0..10[ = exp(ln(10)*frac(i*lD10)) if Trunc(DgtShift * exp(ln(10) * frac(i * lD10))) = Number then begin inc(cnt); if cnt >= CntLmt then BREAK; end; until false; write('The ', Numb2USA(IntToStr(cnt)), 'th occurrence of 2 raised to a power'); write(' whose product starts with "', Numb2USA(IntToStr(Number))); writeln('" is ', Numb2USA(IntToStr(i))); FindExp := i; end;   begin FindExp(1, 12); FindExp(2, 12);   FindExp(45, 123); FindExp(12345, 123); FindExp(678910, 123); 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
#Never
Never
  func multiplier(a : float, b : float) -> (float) -> float { let func(m : float) -> float { a * b * m } }   func main() -> int { var x = 2.0; var xi = 0.5; var y = 4.0; var yi = 0.25; var z = x + y; var zi = 1.0 / z;   var f = [ x, y, z ] : float; var i = [ xi, yi, zi ] : float; var c = 0; var mult = let func(m : float) -> float { 0.0 };   for (c = 0; c < 3; c = c + 1) { mult = multiplier(f[c], i[c]); prints(f[c] + " * " + i[c] + " * " + 1.0 + " = " + mult(1) + "\n") };   0 }  
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
#Nim
Nim
  func multiplier(a, b: float): auto = let ab = a * b result = func(c: float): float = ab * c   let x = 2.0 xi = 0.5 y = 4.0 yi = 0.25 z = x + y zi = 1.0 / ( x + y )   let list = [x, y, z] let invlist = [xi, yi, zi]   for i in 0..list.high: # Create a multiplier function... let f = multiplier(list[i], invlist[i]) # ... and apply it. echo f(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
#Perl
Perl
FORK: # some code goto FORK;
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
#Phix
Phix
without js -- (no goto in JavaScript) procedure p() goto :but_print puts(1,"This will not be printed...\n") ::but_print puts(1,"...but this will\n") end procedure p()
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.
#Elixir
Elixir
defmodule Floyd do def triangle(n) do max = trunc(n * (n + 1) / 2) widths = for m <- (max - n + 1)..max, do: (m |> Integer.to_string |> String.length) + 1 format = Enum.map(widths, fn wide -> "~#{wide}w" end) |> List.to_tuple line(n, 0, 1, format) end   def line(n, n, _, _), do: :ok def line(n, i, count, format) do Enum.each(0..i, fn j -> :io.fwrite(elem(format,j), [count+j]) end) IO.puts "" line(n, i+1, count+i+1, format) end end   Floyd.triangle(5) Floyd.triangle(14)
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.
#Erlang
Erlang
  -module( floyds_triangle ).   -export( [integers/1, print/1, strings/1, task/0] ).   integers( N ) -> lists:reverse( integers_reversed(N) ).   print( N ) -> [io:fwrite("~s~n", [lists:flatten(X)]) || X <- strings(N)].   strings( N ) -> Strings_reversed = [strings_from_integers(X) || X <- integers_reversed(N)], Paddings = paddings( [lengths(X) || X <- Strings_reversed] ), [formats(X, Y) || {X, Y} <- lists:zip(Paddings, lists:reverse(Strings_reversed))].   task() -> print( 5 ), print( 14 ).       formats( Paddings, Strings ) -> [lists:flatten(io_lib:format(" ~*s", [X, Y])) || {X, Y} <- lists:zip(Paddings, Strings)].   integers_reversed( N ) -> {_End, Integers_reversed} = lists:foldl( fun integers_reversed/2, {1, []}, lists:seq(0, N - 1) ), Integers_reversed.   integers_reversed( N, {Start, Acc} ) -> End = Start + N, {End + 1, [lists:seq(Start, End) | Acc]}.   lengths( Strings ) -> [string:len(X) || X <- Strings].   paddings( [Last_line | T] ) -> {[], Paddings} = lists:foldl( fun paddings/2, {paddings_lose_last(Last_line), [Last_line]}, lists:seq(1, erlang:length(T)) ), Paddings.   paddings( _N, {Current, Acc} ) -> {paddings_lose_last(Current), [Current | Acc]}.   paddings_lose_last( List ) -> [_H | T] = lists:reverse( List ), lists:reverse( T ).   strings_from_integers( Integers ) -> [erlang:integer_to_list(X) || X <- Integers].  
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)
#Modula-2
Modula-2
MODULE FloydWarshall; FROM FormatString IMPORT FormatString; FROM SpecialReals IMPORT Infinity; FROM Terminal IMPORT ReadChar,WriteString,WriteLn;   CONST NUM_VERTICIES = 4; TYPE IntArray = ARRAY[0..NUM_VERTICIES-1],[0..NUM_VERTICIES-1] OF INTEGER; RealArray = ARRAY[0..NUM_VERTICIES-1],[0..NUM_VERTICIES-1] OF REAL;   PROCEDURE FloydWarshall(weights : ARRAY OF ARRAY OF INTEGER); VAR dist : RealArray; next : IntArray; i,j,k : INTEGER; BEGIN FOR i:=0 TO NUM_VERTICIES-1 DO FOR j:=0 TO NUM_VERTICIES-1 DO dist[i,j] := Infinity; END END; k := HIGH(weights); FOR i:=0 TO k DO dist[weights[i,0]-1,weights[i,1]-1] := FLOAT(weights[i,2]); END; FOR i:=0 TO NUM_VERTICIES-1 DO FOR j:=0 TO NUM_VERTICIES-1 DO IF i#j THEN next[i,j] := j+1; END END END; FOR k:=0 TO NUM_VERTICIES-1 DO FOR i:=0 TO NUM_VERTICIES-1 DO FOR j:=0 TO NUM_VERTICIES-1 DO IF dist[i,j] > dist[i,k] + dist[k,j] THEN dist[i,j] := dist[i,k] + dist[k,j]; next[i,j] := next[i,k]; END END END END; PrintResult(dist, next); END FloydWarshall;   PROCEDURE PrintResult(dist : RealArray; next : IntArray); VAR i,j,u,v : INTEGER; buf : ARRAY[0..63] OF CHAR; BEGIN WriteString("pair dist path"); WriteLn; FOR i:=0 TO NUM_VERTICIES-1 DO FOR j:=0 TO NUM_VERTICIES-1 DO IF i#j THEN u := i + 1; v := j + 1; FormatString("%i -> %i  %2i  %i", buf, u, v, TRUNC(dist[i,j]), u); WriteString(buf); REPEAT u := next[u-1,v-1]; FormatString(" -> %i", buf, u); WriteString(buf); UNTIL u=v; WriteLn END END END END PrintResult;   TYPE WeightArray = ARRAY[0..4],[0..2] OF INTEGER; VAR weights : WeightArray; BEGIN weights := WeightArray{ {1, 3, -2}, {2, 1, 4}, {2, 3, 3}, {3, 4, 2}, {4, 2, -1} };   FloydWarshall(weights);   ReadChar END FloydWarshall.
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
#Smalltalk
Smalltalk
|mul| mul := [ :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
#SNOBOL4
SNOBOL4
define('multiply(a,b)') :(mul_end) multiply multiply = a * b  :(return) mul_end * Test output = multiply(10.1,12.2) output = multiply(10,12) end
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.)
#Phix
Phix
with javascript_semantics function fwd_diff_n(sequence s, integer order) assert(order<length(s)) s = deep_copy(s) for i=1 to order do for j=1 to length(s)-1 do s[j] = s[j+1]-s[j] end for s = s[1..-2] end for return s end function constant s = {90, 47, 58, 29, 22, 32, 55, 5, 55, 73} for i=1 to 9 do ?fwd_diff_n(s,i) end for
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.
#Sidef
Sidef
printf("%09.3f\n", 7.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.
#Smalltalk
Smalltalk
Transcript show: (7.125 printPaddedWith: $0 to: 3.6); cr. "output: 007.125000"
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).
#PowerShell
PowerShell
function bxor2 ( [byte] $a, [byte] $b ) { $out1 = $a -band ( -bnot $b ) $out2 = ( -bnot $a ) -band $b $out1 -bor $out2 }   function hadder ( [byte] $a, [byte] $b ) { @{ "S"=bxor2 $a $b "C"=$a -band $b } }   function fadder ( [byte] $a, [byte] $b, [byte] $cd ) { $out1 = hadder $cd $a $out2 = hadder $out1["S"] $b @{ "S"=$out2["S"] "C"=$out1["C"] -bor $out2["C"] } }   function FourBitAdder ( [byte] $a, [byte] $b ) { $a0 = $a -band 1 $a1 = ($a -band 2)/2 $a2 = ($a -band 4)/4 $a3 = ($a -band 8)/8 $b0 = $b -band 1 $b1 = ($b -band 2)/2 $b2 = ($b -band 4)/4 $b3 = ($b -band 8)/8 $out1 = fadder $a0 $b0 0 $out2 = fadder $a1 $b1 $out1["C"] $out3 = fadder $a2 $b2 $out2["C"] $out4 = fadder $a3 $b3 $out3["C"] @{ "S"="{3}{2}{1}{0}" -f $out1["S"], $out2["S"], $out3["S"], $out4["S"] "V"=$out4["C"] } }   FourBitAdder 3 5   FourBitAdder 0xA 5   FourBitAdder 0xC 0xB   [Convert]::ToByte((FourBitAdder 0xC 0xB)["S"],2)
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.
#J
J
midpts=: (1 + #) <:@(] , -:@[ , -) -:@<.@-:@(3 + #) NB. mid points of y quartiles=: -:@(+/)@((<. ,: >.)@midpts { /:~@]) NB. quartiles of y fivenum=: <./ , quartiles , >./ NB. fivenum summary of y
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.
#Java
Java
import java.util.Arrays;   public class Fivenum {   static double median(double[] x, int start, int endInclusive) { int size = endInclusive - start + 1; if (size <= 0) throw new IllegalArgumentException("Array slice cannot be empty"); int m = start + size / 2; return (size % 2 == 1) ? x[m] : (x[m - 1] + x[m]) / 2.0; }   static double[] fivenum(double[] x) { for (Double d : x) { if (d.isNaN()) throw new IllegalArgumentException("Unable to deal with arrays containing NaN"); } double[] result = new double[5]; Arrays.sort(x); result[0] = x[0]; result[2] = median(x, 0, x.length - 1); result[4] = x[x.length - 1]; int m = x.length / 2; int lowerEnd = (x.length % 2 == 1) ? m : m - 1; result[1] = median(x, 0, lowerEnd); result[3] = median(x, m, x.length - 1); return result; }   public static void main(String[] args) { double xl[][] = { {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 (double[] x : xl) System.out.printf("%s\n\n", Arrays.toString(fivenum(x))); } }
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)
#Ada
Ada
with Ada.Text_IO; procedure Missing_Permutations is subtype Permutation_Character is Character range 'A' .. 'D';   Character_Count : constant := 1 + Permutation_Character'Pos (Permutation_Character'Last) - Permutation_Character'Pos (Permutation_Character'First);   type Permutation_String is array (1 .. Character_Count) of Permutation_Character;   procedure Put (Item : Permutation_String) is begin for I in Item'Range loop Ada.Text_IO.Put (Item (I)); end loop; end Put;   Given_Permutations : array (Positive range <>) of Permutation_String := ("ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", "ADCB", "CDAB", "DABC", "BCAD", "CADB", "CDBA", "CBAD", "ABDC", "ADBC", "BDCA", "DCBA", "BACD", "BADC", "BDAC", "CBDA", "DBCA", "DCAB");   Count  : array (Permutation_Character, 1 .. Character_Count) of Natural  := (others => (others => 0)); Max_Count : Positive := 1;   Missing_Permutation : Permutation_String; begin for I in Given_Permutations'Range loop for Pos in 1 .. Character_Count loop Count (Given_Permutations (I) (Pos), Pos)  := Count (Given_Permutations (I) (Pos), Pos) + 1; if Count (Given_Permutations (I) (Pos), Pos) > Max_Count then Max_Count := Count (Given_Permutations (I) (Pos), Pos); end if; end loop; end loop;   for Char in Permutation_Character loop for Pos in 1 .. Character_Count loop if Count (Char, Pos) < Max_Count then Missing_Permutation (Pos) := Char; end if; end loop; end loop;   Ada.Text_IO.Put_Line ("Missing Permutation:"); Put (Missing_Permutation); end Missing_Permutations;
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
#Arturo
Arturo
lastSundayForMonth: function [m,y][ ensure -> in? m 1..12   daysOfMonth: @[0 31 (leap? y)? -> 28 -> 27 31 30 31 30 31 31 30 31 30 31] loop range get daysOfMonth m 1 [d][ dt: to :date.format:"yyyy-M-dd" ~"|y|-|m|-|d|" if dt\Day = "Sunday" -> return dt ] ]   getLastSundays: function [year][ loop 1..12 'month [ print to :string.format:"yyyy-MM-dd" lastSundayForMonth month year ] ]   getLastSundays 2013
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) .
#AutoHotkey
AutoHotkey
LineIntersectionByPoints(L1, L2){ x1 := L1[1,1], y1 := L1[1,2] x2 := L1[2,1], y2 := L1[2,2] x3 := L2[1,1], y3 := L2[1,2] x4 := L2[2,1], y4 := L2[2,2] return ((x1*y2-y1*x2)*(x3-x4) - (x1-x2)*(x3*y4-y3*x4)) / ((x1-x2)*(y3-y4) - (y1-y2)*(x3-x4)) ", " . ((x1*y2-y1*x2)*(y3-y4) - (y1-y2)*(x3*y4-y3*x4)) / ((x1-x2)*(y3-y4) - (y1-y2)*(x3-x4)) }
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].
#APL
APL
⍝ Find the intersection of a line with a plane ⍝ The intersection I belongs to a line defined by point L and vector V, translates to: ⍝ A real parameter t exists, that satisfies I = L + tV ⍝ I belongs to the plan defined by point P and normal vector N. This means that any two points of the plane make a vector ⍝ normal to vector N. As I and P belong to the plane, the vector IP is normal to N. ⍝ This translates to: The scalar product IP.N = 0. ⍝ (P - I).N = 0 <=> (P - L - tV).N = 0 ⍝ Using distributivity, then associativity, the following equations are established: ⍝ (P - L - tV).N = (P - L).N - (tV).N = (P - L).N - t(V.N) = 0 ⍝ Which allows to resolve t: t = ((P - L).N) ÷ (V.N) ⍝ In APL, A.B is coded +/A x B V ← 0 ¯1 ¯1 L ← 0 0 10 N ← 0 0 1 P ← 0 0 5 dot ← { +/ ⍺ × ⍵ } t ← ((P - L) dot N) ÷ V dot N I ← L + t × V  
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
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program FizzBuzz64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesARM64.inc"   /*******************************************/ /* Initialized data */ /*******************************************/ .data szMessFizz: .asciz "Fizz\n" szMessBuzz: .asciz "Buzz\n" szMessFizzBuzz: .asciz "FizzBuzz\n" szMessNumber: .asciz "Number : @ " szCarriageReturn: .asciz "\n"   /*******************************************/ /* UnInitialized data */ /*******************************************/ .bss sZoneConv: .skip 24 /*******************************************/ /* code section */ /*******************************************/ .text .global main main: // entry of program mov x10,3 // divisor 3 mov x11,5 // divisor 5 mov x12,15 // divisor 15 mov x13,1 // indice 1: // loop begin udiv x14,x13,x12 // multiple 15 msub x15,x14,x12,x13 // remainder cbnz x15,2f // zero ? mov x0,x13 ldr x1,qAdrszMessFizzBuzz bl displayResult b 4f 2: // multiple 3 udiv x14,x13,x10 msub x15,x14,x10,x13 // remainder cbnz x15,3f // zero ? mov x0,x13 ldr x1,qAdrszMessFizz bl displayResult b 4f 3: // multiple 5 udiv x14,x13,x11 msub x15,x14,x11,x13 // remainder cbnz x15,4f // zero ? mov x0,x13 ldr x1,qAdrszMessBuzz bl displayResult 4: add x13,x13,1 // increment indice cmp x13,100 // maxi ? ble 1b   100: // standard end of the program mov x8,EXIT // request to exit program svc 0 // perform the system call qAdrszMessFizzBuzz: .quad szMessFizzBuzz qAdrszMessFizz: .quad szMessFizz qAdrszMessBuzz: .quad szMessBuzz /******************************************************************/ /* Display résult */ /******************************************************************/ /* x0 contains the number*/ /* x1 contains display string address */ displayResult: stp x2,lr,[sp,-16]! // save registers mov x2,x1 ldr x1,qAdrsZoneConv // conversion number bl conversion10S // decimal conversion ldr x0,qAdrszMessNumber ldr x1,qAdrsZoneConv bl strInsertAtCharInc // insert result at @ character bl affichageMess // display message final mov x0,x2 bl affichageMess   ldp x2,lr,[sp],16 // restaur 2 registers ret // return to address lr x30 qAdrsZoneConv: .quad sZoneConv qAdrszMessNumber: .quad szMessNumber /********************************************************/ /* File Include fonctions */ /********************************************************/ /* for this file see task include a file in language AArch64 assembly */ .include "../includeARM64.inc"  
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
#BBC_BASIC
BBC BASIC
INSTALL @lib$+"DATELIB" DIM Month$(12) Month$() = "","January","February","March","April","May","June", \ \ "July","August","September","October","November","December"   num% = 0 FOR year% = 1900 TO 2100 PRINT ; year% ": " ; oldnum% = num% FOR month% = 1 TO 12 IF FN_dim(month%,year%) = 31 IF FN_dow(FN_mjd(1,month%,year%)) = 5 THEN num% += 1 PRINT Month$(month%), ; ENDIF NEXT IF num% = oldnum% PRINT "(none)" ELSE PRINT NEXT year% PRINT "Total = " ; num%
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
#Go
Go
package main   import ( "fmt" "math/big" "strconv" "time" )   const maxBase = 27 const minSq36 = "1023456789abcdefghijklmnopqrstuvwxyz" const minSq36x = "10123456789abcdefghijklmnopqrstuvwxyz"   var bigZero = new(big.Int) var bigOne = new(big.Int).SetUint64(1)   func containsAll(sq string, base int) bool { var found [maxBase]byte le := len(sq) reps := 0 for _, r := range sq { d := r - 48 if d > 38 { d -= 39 } found[d]++ if found[d] > 1 { reps++ if le-reps < base { return false } } } return true }   func sumDigits(n, base *big.Int) *big.Int { q := new(big.Int).Set(n) r := new(big.Int) sum := new(big.Int).Set(bigZero) for q.Cmp(bigZero) == 1 { q.QuoRem(q, base, r) sum.Add(sum, r) } return sum }   func digitalRoot(n *big.Int, base int) int { root := new(big.Int) b := big.NewInt(int64(base)) for i := new(big.Int).Set(n); i.Cmp(b) >= 0; i.Set(root) { root.Set(sumDigits(i, b)) } return int(root.Int64()) }   func minStart(base int) (string, uint64, int) { nn := new(big.Int) ms := minSq36[:base] nn.SetString(ms, base) bdr := digitalRoot(nn, base) var drs []int var ixs []uint64 for n := uint64(1); n < uint64(2*base); n++ { nn.SetUint64(n * n) dr := digitalRoot(nn, base) if dr == 0 { dr = int(n * n) } if dr == bdr { ixs = append(ixs, n) } if n < uint64(base) && dr >= bdr { drs = append(drs, dr) } } inc := uint64(1) if len(ixs) >= 2 && base != 3 { inc = ixs[1] - ixs[0] } if len(drs) == 0 { return ms, inc, bdr } min := drs[0] for _, dr := range drs[1:] { if dr < min { min = dr } } rd := min - bdr if rd == 0 { return ms, inc, bdr } if rd == 1 { return minSq36x[:base+1], 1, bdr } ins := string(minSq36[rd]) return (minSq36[:rd] + ins + minSq36[rd:])[:base+1], inc, bdr }   func main() { start := time.Now() var nb, nn big.Int for n, k, base := uint64(2), uint64(1), 2; ; n += k { if base > 2 && n%uint64(base) == 0 { continue } nb.SetUint64(n) sq := nb.Mul(&nb, &nb).Text(base) if !containsAll(sq, base) { continue } ns := strconv.FormatUint(n, base) tt := time.Since(start).Seconds() fmt.Printf("Base %2d:%15s² = %-27s in %8.3fs\n", base, ns, sq, tt) if base == maxBase { break } base++ ms, inc, bdr := minStart(base) k = inc nn.SetString(ms, base) nb.Sqrt(&nn) if nb.Uint64() < n+1 { nb.SetUint64(n + 1) } if k != 1 { for { nn.Mul(&nb, &nb) dr := digitalRoot(&nn, base) if dr == bdr { n = nb.Uint64() - k break } nb.Add(&nb, bigOne) } } else { n = nb.Uint64() - k } } }
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
#C.2B.2B
C++
  #include <functional> #include <algorithm> #include <iostream> #include <vector> #include <cmath>   using std::cout; using std::endl; using std::vector; using std::function; using std::transform; using std::back_inserter;   typedef function<double(double)> FunType;   vector<FunType> A = {sin, cos, tan, [](double x) { return x*x*x; } }; vector<FunType> B = {asin, acos, atan, [](double x) { return exp(log(x)/3); } };   template <typename A, typename B, typename C> function<C(A)> compose(function<C(B)> f, function<B(A)> g) { return [f,g](A x) { return f(g(x)); }; }   int main() { vector<FunType> composedFuns; auto exNums = {0.0, 0.2, 0.4, 0.6, 0.8, 1.0};   transform(B.begin(), B.end(), A.begin(), back_inserter(composedFuns), compose<double, double, double>);   for (auto num: exNums) for (auto fun: composedFuns) cout << u8"f\u207B\u00B9.f(" << num << ") = " << fun(num) << endl;   return 0; }  
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.
#Go
Go
package main   import ( "fmt" "math/rand" "strings" )   const ( rows = 20 cols = 30 p = .01 f = .001 )   const rx = rows + 2 const cx = cols + 2   func main() { odd := make([]byte, rx*cx) even := make([]byte, rx*cx) for r := 1; r <= rows; r++ { for c := 1; c <= cols; c++ { if rand.Intn(2) == 1 { odd[r*cx+c] = 'T' } } } for { print(odd) step(even, odd) fmt.Scanln()   print(even) step(odd, even) fmt.Scanln() } }   func print(model []byte) { fmt.Println(strings.Repeat("__", cols)) fmt.Println() for r := 1; r <= rows; r++ { for c := 1; c <= cols; c++ { if model[r*cx+c] == 0 { fmt.Print(" ") } else { fmt.Printf(" %c", model[r*cx+c]) } } fmt.Println() } }   func step(dst, src []byte) { for r := 1; r <= rows; r++ { for c := 1; c <= cols; c++ { x := r*cx + c dst[x] = src[x] switch dst[x] { case '#': // rule 1. A burning cell turns into an empty cell dst[x] = 0 case 'T': // rule 2. A tree will burn if at least one neighbor is burning if src[x-cx-1]=='#' || src[x-cx]=='#' || src[x-cx+1]=='#' || src[x-1] == '#' || src[x+1] == '#' || src[x+cx-1]=='#' || src[x+cx]=='#' || src[x+cx+1] == '#' { dst[x] = '#'   // rule 3. A tree ignites with probability f // even if no neighbor is burning } else if rand.Float64() < f { dst[x] = '#' } default: // rule 4. An empty space fills with a tree with probability p if rand.Float64() < p { dst[x] = 'T' } } } } }
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.
#Phix
Phix
with javascript_semantics function hail(integer n) if remainder(n,2)=0 then n /= 2 else n = 3*n+1 end if return n end function sequence hails = tagset(12), counts = repeat(0,12), results = columnize({hails}) function step(integer edx) integer n = hails[edx] if n=1 then return 0 end if n = hail(n) hails[edx] = n counts[edx] += 1 results[edx] = deep_copy(results[edx]) & n return 1 end function procedure main() bool done = false while not done do done = true for i=1 to 12 do if step(i) then done = false end if end for end while for i=1 to max(counts)+1 do for j=1 to 12 do puts(1,iff(i<=length(results[j])?sprintf("%4d",{results[j][i]}):" ")) end for puts(1,"\n") end for printf(1," %s\n",{join(repeat("===",12))}) for j=1 to 12 do printf(1,"%4d",{counts[j]}) end for puts(1,"\n") end procedure main()
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
D
import std.stdio, std.algorithm, std.conv, std.range;   struct TreeList(T) { union { // A tagged union TreeList[] arr; // it's a node T data; // It's a leaf. } bool isArray = true; // = Contains an arr on default.   static TreeList opCall(A...)(A items) pure nothrow { TreeList result;   foreach (i, el; items) static if (is(A[i] == T)) { TreeList item; item.isArray = false; item.data = el; result.arr ~= item; } else result.arr ~= el;   return result; }   string toString() const pure { return isArray ? arr.text : data.text; } }   T[] flatten(T)(in TreeList!T t) pure nothrow { if (t.isArray) return t.arr.map!flatten.join; else return [t.data]; }   void main() { alias TreeList!int L; static assert(L.sizeof == 12); auto l = L(L(1), 2, L(L(3,4), 5), L(L(L())), L(L(L(6))),7,8,L()); l.writeln; l.flatten.writeln; }