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/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
#Ruby
Ruby
def multiply(a, b) a * b 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
#Rust
Rust
fn multiply(a: i32, b: i32) -> i32 { 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.)
#Nial
Nial
fd is - [rest, front]
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.)
#Nim
Nim
proc dif(s: seq[int]): seq[int] = result = newSeq[int](s.len-1) for i in 0..<s.high: result[i] = s[i+1] - s[i]   proc difn(s: seq[int]; n: int): seq[int] = if n > 0: difn(dif(s), n-1) else: s   const s = @[90, 47, 58, 29, 22, 32, 55, 5, 55, 73] echo difn(s, 0) echo difn(s, 1) echo difn(s, 2)
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#Zoea
Zoea
program: hello_world output: "Hello world!"
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#Zoea_Visual
Zoea Visual
print "Hello world!"
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.
#Raku
Raku
say 7.125.fmt('%09.3f');
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.
#Raven
Raven
7.125 "%09.3f" print   00007.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).
#OCaml
OCaml
  (* File blocks.ml   A block is just a black box with nin input lines and nout output lines, numbered from 0 to nin-1 and 0 to nout-1 respectively. It will be stored in a caml record, with the operation stored as a function. A value on a line is represented by a boolean value. *)   type block = { nin:int; nout:int; apply:bool array -> bool array };;   (* First we need function for boolean conversion to and from integer values, mainly for pretty printing of results *)   let int_of_bits nbits v = if (Array.length v) <> nbits then failwith "bad args" else (let r = ref 0L in for i=nbits-1 downto 0 do r := Int64.add (Int64.shift_left !r 1) (if v.(i) then 1L else 0L) done; !r);;   let bits_of_int nbits n = let v = Array.make nbits false and r = ref n in for i=0 to nbits-1 do v.(i) <- (Int64.logand !r 1L) <> Int64.zero; r := Int64.shift_right_logical !r 1 done; v;;   let input nbits v = let n = Array.length v in let w = Array.make (n*nbits) false in Array.iteri (fun i x -> Array.blit (bits_of_int nbits x) 0 w (i*nbits) nbits ) v; w;;   let output nbits v = let nv = Array.length v in let r = nv mod nbits and n = nv/nbits in if r <> 0 then failwith "bad output size" else Array.init n (fun i -> int_of_bits nbits (Array.sub v (i*nbits) nbits) );;   (* We have a type for blocks, so we need operations on blocks.   assoc: make one block from two blocks, side by side (they are not connected) serial: connect input from one block to output of another block parallel: make two outputs from one input passing through two blocks block_array: an array of blocks linked by the same connector (assoc, serial, parallel) *)   let assoc a b = { nin=a.nin+b.nin; nout=a.nout+b.nout; apply=function bits -> Array.append (a.apply (Array.sub bits 0 a.nin)) (b.apply (Array.sub bits a.nin b.nin)) };;   let serial a b = if a.nout <> b.nin then failwith "[serial] bad block" else { nin=a.nin; nout=b.nout; apply=function bits -> b.apply (a.apply bits) };;   let parallel a b = if a.nin <> b.nin then failwith "[parallel] bad blocks" else { nin=a.nin; nout=a.nout+b.nout; apply=function bits -> Array.append (a.apply bits) (b.apply bits) };;   let block_array comb v = let n = Array.length v and r = ref v.(0) in for i=1 to n-1 do r := comb !r v.(i) done; !r;;   (* wires   map: map n input lines on length(v) output lines, using the links out(k)=v(in(k)) pass: n wires not connected (out(k) = in(k)) fork: a wire is developed into n wires having the same value perm: permutation of wires forget: n wires going nowhere sub: subset of wires, other ones going nowhere *)   let map n v = { nin=n; nout=Array.length v; apply=function bits -> Array.map (function k -> bits.(k)) v };;   let pass n = { nin=n; nout=n; apply=function bits -> bits };;   let fork n = { nin=1; nout=n; apply=function bits -> Array.make n bits.(0) };;   let perm v = let n = Array.length v in { nin=n; nout=n; apply=function bits -> Array.init n (function k -> bits.(v.(k))) };;   let forget n = { nin=n; nout=0; apply=function bits -> [| |] };;   let sub nin nout where = { nin=nin; nout=nout; apply=function bits -> Array.sub bits where nout };;   let transpose n p v = if n*p <> Array.length v then failwith "bad dim" else let w = Array.copy v in for i=0 to n-1 do for j=0 to p-1 do let r = i*p+j and s = j*n+i in w.(r) <- v.(s) done done; w;;   (* line mixing (a special permutation) mix 4 2 : 0,1,2,3, 4,5,6,7 -> 0,4, 1,5, 2,6, 3,7 unmix: inverse operation *)   let mix n p = perm (transpose n p (Array.init (n*p) (function x -> x)));;   let unmix n p = perm (transpose p n (Array.init (n*p) (function x -> x)));;   (* basic blocks   dummy: no input, no output, usually not useful const: n wires with constant value (true or false) encode: translates an Int64 into boolean values, keeping only n lower bits bnand: NAND gate, the basic building block for all the other basic gates (or, and, not...) *)   let dummy = { nin=0; nout=0; apply=function bits -> bits };;   let const b n = { nin=0; nout=n; apply=function bits -> Array.make n b };;   let encode nbits x = { nin=0; nout=nbits; apply=function bits -> bits_of_int nbits x };;   let bnand = { nin=2; nout=1; apply=function [| a; b |] -> [| not (a && b) |] | _ -> failwith "bad args" };;   (* block evaluation : returns the value of the output, given an input and a block. *)   let eval block nbits_in nbits_out v = output nbits_out (block.apply (input nbits_in v));;   (* building a 4-bit adder *)   (* first we build the usual gates *)   let bnot = serial (fork 2) bnand;;   let band = serial bnand bnot;;   (* a or b = !a nand !b *) let bor = serial (assoc bnot bnot) bnand;;   (* line "a" -> two lines, "a" and "not a" *) let a_not_a = parallel (pass 1) bnot;;   let bxor = block_array serial [| assoc a_not_a a_not_a; perm [| 0; 3; 1; 2 |]; assoc band band; bor |];;   let half_adder = parallel bxor band;;   (* bits C0,A,B -> S,C1 *) let full_adder = block_array serial [| assoc half_adder (pass 1); perm [| 1; 0; 2 |]; assoc (pass 1) half_adder; perm [| 1; 0; 2 |]; assoc (pass 1) bor |];;   (* 4-bit adder *) let add4 = block_array serial [| mix 4 2; assoc half_adder (pass 6); assoc (assoc (pass 1) full_adder) (pass 4); assoc (assoc (pass 2) full_adder) (pass 2); assoc (pass 3) full_adder |];;   (* 4-bit adder and three supplementary lines to make a multiple of 4 (to translate back to 4-bit integers) *) let add4_io = assoc add4 (const false 3);;   (* wrapping the 4-bit to input and output integers instead of booleans plus a b -> (sum,carry) *) let plus a b = let v = Array.map Int64.to_int (eval add4_io 4 4 (Array.map Int64.of_int [| a; b |])) in v.(0), v.(1);;  
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.
#D
D
import std.algorithm; import std.exception; import std.math; import std.stdio;   double median(double[] x) { enforce(x.length >= 0, "Array slice cannot be empty"); int m = x.length / 2; if (x.length % 2 == 1) { return x[m]; } return (x[m-1] + x[m]) / 2.0; }   double[] fivenum(double[] x) { foreach (d; x) { enforce(!d.isNaN, "Unable to deal with arrays containing NaN"); }   double[] result; result.length = 5;   x.sort; result[0] = x[0]; result[2] = median(x); result[4] = x[$-1];   int m = x.length / 2; int lower = (x.length % 2 == 1) ? m : m - 1; result[1] = median(x[0..lower+1]); result[3] = median(x[lower+1..$]);   return result; }   void main() { double[][] x1 = [ [15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0], [36.0, 40.0, 7.0, 39.0, 41.0, 15.0], [ 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 ] ]; foreach(x; x1) { writeln(fivenum(x)); } }
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
#360_Assembly
360 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
#Action.21
Action!
;https://en.wikipedia.org/wiki/Determination_of_the_day_of_the_week#Sakamoto.27s_methods BYTE FUNC DayOfWeek(INT y BYTE m,d) ;1<=m<=12, y>1752 BYTE ARRAY t=[0 3 2 5 0 3 5 1 4 6 2 4] BYTE res   IF m<3 THEN y==-1 FI res=(y+y/4-y/100+y/400+t(m-1)+d) MOD 7 RETURN (res)   PROC Main() BYTE ARRAY m31=[1 3 5 7 8 10 12] INT ARRAY years(250) BYTE ARRAY months(250) INT y BYTE i,m,mCount,yCount,found,c   mCount=0 yCount=0 c=0 FOR y=1900 TO 2100 DO found=0 FOR i=0 TO 6 DO m=m31(i) IF DayOfWeek(y,m,1)=5 THEN years(mCount)=y months(mCount)=m found=1 mCount==+1 FI OD IF found=0 THEN yCount==+1 FI OD Print("5-weekend months in 1900-2100: ") PrintBE(mCount) Print("non 5-weekend years in 1900-2100: ") PrintBE(yCount) PutE()   FOR i=0 TO 4 DO PrintI(years(i)) Put('/) PrintBE(months(i)) OD PrintE("...") FOR i=mCount-5 TO mCount-1 DO PrintI(years(i)) Put('/) PrintBE(months(i)) OD RETURN
http://rosettacode.org/wiki/Five_weekends
Five weekends
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays. Task Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar). Show the number of months with this property (there should be 201). Show at least the first and last five dates, in order. Algorithm suggestions Count the number of Fridays, Saturdays, and Sundays in every month. Find all of the 31-day months that begin on Friday. Extra credit Count and/or show all of the years which do not have at least one five-weekend month (there should be 29). Related tasks Day of the week Last Friday of each month Find last sunday of each month
#Ada
Ada
  with Ada.Text_IO; use Ada.Text_IO; with Ada.Calendar.Formatting; use Ada.Calendar;   use Ada.Calendar.Formatting;   procedure Five_Weekends is Months : Natural := 0; begin for Year in Year_Number range 1901..2100 loop for Month in Month_Number range 1..12 loop begin if Day_Of_Week (Formatting.Time_Of (Year, Month, 31)) = Sunday then Put_Line (Year_Number'Image (Year) & Month_Number'Image (Month)); Months := Months + 1; end if; exception when Time_Error => null; end; end loop; end loop; Put_Line ("Number of months:" & Integer'Image (Months)); end 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
#C
C
#include <stdio.h> #include <string.h>   #define BUFF_SIZE 32   void toBaseN(char buffer[], long long num, int base) { char *ptr = buffer; char *tmp;   // write it backwards while (num >= 1) { int rem = num % base; num /= base;   *ptr++ = "0123456789ABCDEF"[rem]; } *ptr-- = 0;   // now reverse it to be written forwards for (tmp = buffer; tmp < ptr; tmp++, ptr--) { char c = *tmp; *tmp = *ptr; *ptr = c; } }   int countUnique(char inBuf[]) { char buffer[BUFF_SIZE]; int count = 0; int pos, nxt;   strcpy_s(buffer, BUFF_SIZE, inBuf);   for (pos = 0; buffer[pos] != 0; pos++) { if (buffer[pos] != 1) { count++; for (nxt = pos + 1; buffer[nxt] != 0; nxt++) { if (buffer[nxt] == buffer[pos]) { buffer[nxt] = 1; } } } }   return count; }   void find(int base) { char nBuf[BUFF_SIZE]; char sqBuf[BUFF_SIZE]; long long n, s;   for (n = 2; /*blank*/; n++) { s = n * n; toBaseN(sqBuf, s, base); if (strlen(sqBuf) >= base && countUnique(sqBuf) == base) { toBaseN(nBuf, n, base); toBaseN(sqBuf, s, base); //printf("Base %d : Num %lld Square %lld\n", base, n, s); printf("Base %d : Num %8s Square %16s\n", base, nBuf, sqBuf); break; } } }   int main() { int i;   for (i = 2; i <= 15; i++) { find(i); }   return 0; }
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
#AppleScript
AppleScript
-- Compose two functions, where each function is -- a script object with a call(x) handler. on compose(f, g) script on call(x) f's call(g's call(x)) end call end script end compose   script increment on call(n) n + 1 end call end script   script decrement on call(n) n - 1 end call end script   script twice on call(x) x * 2 end call end script   script half on call(x) x / 2 end call end script   script cube on call(x) x ^ 3 end call end script   script cuberoot on call(x) x ^ (1 / 3) end call end script   set functions to {increment, twice, cube} set inverses to {decrement, half, cuberoot} set answers to {} repeat with i from 1 to 3 set end of answers to ¬ compose(item i of inverses, ¬ item i of functions)'s ¬ call(0.5) end repeat answers -- Result: {0.5, 0.5, 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.
#Emacs_Lisp
Emacs Lisp
#!/usr/bin/env emacs -script ;; -*- lexical-binding: t -*- ;; run: ./forest-fire forest-fire.config (require 'cl-lib) ;; (setq debug-on-error t)   (defmacro swap (a b) `(setq ,b (prog1 ,a (setq ,a ,b))))   (defconst burning ?B) (defconst tree ?t)   (cl-defstruct world rows cols data)   (defun new-world (rows cols) ;; When allocating the vector add padding so the border will always be empty. (make-world :rows rows :cols cols :data (make-vector (* (1+ rows) (1+ cols)) nil)))   (defmacro world--rows (w) `(1+ (world-rows ,w)))   (defmacro world--cols (w) `(1+ (world-cols ,w)))   (defmacro world-pt (w r c) `(+ (* (mod ,r (world--rows ,w)) (world--cols ,w)) (mod ,c (world--cols ,w))))   (defmacro world-ref (w r c) `(aref (world-data ,w) (world-pt ,w ,r ,c)))   (defun print-world (world) (dotimes (r (world-rows world)) (dotimes (c (world-cols world)) (let ((cell (world-ref world r c))) (princ (format "%c" (if (not (null cell)) cell  ?.))))) (terpri)))   (defun random-probability () (/ (float (random 1000000)) 1000000))   (defun initialize-world (world p) (dotimes (r (world-rows world)) (dotimes (c (world-cols world)) (setf (world-ref world r c) (if (<= (random-probability) p) tree nil)))))   (defun neighbors-burning (world row col) (let ((n 0)) (dolist (offset '((1 . 1) (1 . 0) (1 . -1) (0 . 1) (0 . -1) (-1 . 1) (-1 . 0) (-1 . -1))) (when (eq (world-ref world (+ row (car offset)) (+ col (cdr offset))) burning) (setq n (1+ n)))) (> n 0)))   (defun advance (old new p f) (dotimes (r (world-rows old)) (dotimes (c (world-cols old)) (cond ((eq (world-ref old r c) burning) (setf (world-ref new r c) nil)) ((null (world-ref old r c)) (setf (world-ref new r c) (if (<= (random-probability) p) tree nil))) ((eq (world-ref old r c) tree) (setf (world-ref new r c) (if (or (neighbors-burning old r c) (<= (random-probability) f)) burning tree)))))))   (defun read-config (file-name) (with-temp-buffer (insert-file-contents-literally file-name) (read (current-buffer))))   (defun get-config (key config) (let ((val (assoc key config))) (if (null val) (error (format "missing value for %s" key)) (cdr val))))   (defun simulate-forest (file-name) (let* ((config (read-config file-name)) (rows (get-config 'rows config)) (cols (get-config 'cols config)) (skip (get-config 'skip config)) (a (new-world rows cols)) (b (new-world rows cols))) (initialize-world a (get-config 'tree config)) (dotimes (time (get-config 'time config)) (when (or (and (> skip 0) (= (mod time skip) 0)) (<= skip 0)) (princ (format "* time %d\n" time)) (print-world a)) (advance a b (get-config 'p config) (get-config 'f config)) (swap a b))))   (simulate-forest (elt command-line-args-left 0))  
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.
#Factor
Factor
USING: assocs continuations formatting io kernel math math.ranges sequences ;   : (next-hailstone) ( count value -- count' value' ) [ 1 + ] [ dup even? [ 2/ ] [ 3 * 1 + ] if ] bi* ;   : next-hailstone ( count value -- count' value' ) dup 1 = [ (next-hailstone) ] unless ;   : make-environments ( -- seq ) 12 [ 0 ] replicate 12 [1,b] zip ;   : step ( seq -- new-seq ) [ [ dup "%4d " printf next-hailstone ] with-datastack ] map nl ;   : done? ( seq -- ? ) [ second 1 = ] all? ;   make-environments [ dup done? ] [ step ] until nl "Counts:" print [ [ drop "%4d " printf ] with-datastack drop ] each nl
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.
#Go
Go
package main   import "fmt"   const jobs = 12   type environment struct{ seq, cnt int }   var ( env [jobs]environment seq, cnt *int )   func hail() { fmt.Printf("% 4d", *seq) if *seq == 1 { return } (*cnt)++ if *seq&1 != 0 { *seq = 3*(*seq) + 1 } else { *seq /= 2 } }   func switchTo(id int) { seq = &env[id].seq cnt = &env[id].cnt }   func main() { for i := 0; i < jobs; i++ { switchTo(i) env[i].seq = i + 1 }   again: for i := 0; i < jobs; i++ { switchTo(i) hail() } fmt.Println()   for j := 0; j < jobs; j++ { switchTo(j) if *seq != 1 { goto again } } fmt.Println()   fmt.Println("COUNTS:") for i := 0; i < jobs; i++ { switchTo(i) fmt.Printf("% 4d", *cnt) } fmt.Println() }
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
#C.2B.2B
C++
#include <list> #include <boost/any.hpp>   typedef std::list<boost::any> anylist;   void flatten(std::list<boost::any>& list) { typedef anylist::iterator iterator;   iterator current = list.begin(); while (current != list.end()) { if (current->type() == typeid(anylist)) { iterator next = current; ++next; list.splice(next, boost::any_cast<anylist&>(*current)); current = list.erase(current); } else ++current; } }
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.
#Kotlin
Kotlin
// version 1.1.3   import java.util.Random   val rand = Random() val target = Array(3) { IntArray(3) { rand.nextInt(2) } } val board = Array(3) { IntArray(3) }   fun flipRow(r: Int) { for (c in 0..2) board[r][c] = if (board[r][c] == 0) 1 else 0 }   fun flipCol(c: Int) { for (r in 0..2) board[r][c] = if (board[r][c] == 0) 1 else 0 }   /** starting from the target we make 9 random row or column flips */ fun initBoard() { for (i in 0..2) { for (j in 0..2) board[i][j] = target[i][j] } repeat(9) { val rc = rand.nextInt(2) if (rc == 0) flipRow(rand.nextInt(3)) else flipCol(rand.nextInt(3)) } }   fun printBoard(label: String, isTarget: Boolean = false) { val a = if (isTarget) target else board println("$label:") println(" | a b c") println("---------") for (r in 0..2) { print("${r + 1} |") for (c in 0..2) print(" ${a[r][c]}") println() } println() }   fun gameOver(): Boolean { for (r in 0..2) { for (c in 0..2) if (board[r][c] != target[r][c]) return false } return true }   fun main(args: Array<String>) { // initialize board and ensure it differs from the target i.e. game not already over! do { initBoard() } while(gameOver())   printBoard("TARGET", true) printBoard("OPENING BOARD") var flips = 0   do { var isRow = true var n = -1 do { print("Enter row number or column letter to be flipped: ") val input = readLine()!! val ch = if (input.isNotEmpty()) input[0].toLowerCase() else '0' if (ch !in "123abc") { println("Must be 1, 2, 3, a, b or c") continue } if (ch in '1'..'3') { n = ch.toInt() - 49 } else { isRow = false n = ch.toInt() - 97 } } while (n == -1)   flips++ if (isRow) flipRow(n) else flipCol(n) val plural = if (flips == 1) "" else "S" printBoard("\nBOARD AFTER $flips FLIP$plural") } while (!gameOver())   val plural = if (flips == 1) "" else "s" println("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.
#Haskell
Haskell
import Control.Monad (guard) import Text.Printf (printf)   p :: Int -> Int -> Int p l n = calc !! pred n where digitCount = floor $ logBase 10 (fromIntegral l :: Float) log10pwr = logBase 10 2 calc = do raised <- [-1 ..] let firstDigits = floor $ 10 ** (snd (properFraction $ log10pwr * realToFrac raised) + realToFrac digitCount) guard (firstDigits == l) [raised]   main :: IO () main = mapM_ (\(l, n) -> printf "p(%d, %d) = %d\n" l n (p l n)) [(12, 1), (12, 2), (123, 45), (123, 12345), (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
#Icon_and_Unicon
Icon and Unicon
import Utils   procedure main(A) mult := multiplier(get(A),get(A)) # first 2 args define function every write(mult(!A)) # remaining are passed to new function end   procedure multiplier(n1,n2) return makeProc { repeat inVal := n1 * n2 * (inVal@&source)[1] } 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
#J
J
x =: 2.0 xi =: 0.5 y =: 4.0 yi =: 0.25 z =: x + y zi =: 1.0 % (x + y) NB. / is spelled % in J   fwd =: x ,y ,z rev =: xi,yi,zi   multiplier =: 2 : 'm * n * ]'
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
#Maxima
Maxima
/* goto */ block(..., label, ..., go(label), ...);   /* throw, which is like trapping errors, and can do non-local jumps to return a value */ catch(..., throw(value), ...);   /* error trapping */ errcatch(..., error("Bad luck!"), ...);
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
#MUMPS
MUMPS
GOTO LABEL^ROUTINE
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.
#CLU
CLU
floyd = cluster is triangle rep = null   width = proc (n: int) returns (int) w: int := 1 while n >= 10 do w := w + 1 n := n / 10 end return (w) end width   triangle = proc (rows: int) returns (string) ss: stream := stream$create_output() maxno: int := rows * (rows+1)/2 num: int := 1 for row: int in int$from_to(1, rows) do for col: int in int$from_to(1, row) do stream$putright(ss, int$unparse(num), 1 + width(maxno-rows+col)) num := num + 1 end stream$putl(ss, "") end return (stream$get_contents(ss)) end triangle end floyd   start_up = proc () po: stream := stream$primary_output() stream$putl(po, floyd$triangle(5)) stream$putl(po, floyd$triangle(14)) end start_up
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.
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. FLOYD-TRIANGLE.   DATA DIVISION. WORKING-STORAGE SECTION. 01 VARIABLES COMP. 02 NUM-LINES PIC 99. 02 CUR-LINE PIC 99. 02 CUR-COL PIC 99. 02 CUR-NUM PIC 999. 02 ZERO-SKIP PIC 9. 02 LINE-PTR PIC 99. 02 MAX-NUM PIC 999.   01 OUTPUT-FORMAT. 02 OUT-LINE PIC X(72). 02 ONE-DIGIT PIC B9. 02 TWO-DIGITS PIC BZ9. 02 THREE-DIGITS PIC BZZ9. 02 MAX-COL-NUM PIC 999.   PROCEDURE DIVISION. BEGIN. MOVE 5 TO NUM-LINES. PERFORM FLOYD. DISPLAY ' '. MOVE 14 TO NUM-LINES. PERFORM FLOYD. STOP RUN.   FLOYD. MOVE 1 TO CUR-NUM. COMPUTE MAX-NUM = NUM-LINES * (NUM-LINES + 1) / 2. PERFORM FLOYD-LINE VARYING CUR-LINE FROM 1 BY 1 UNTIL CUR-LINE IS GREATER THAN NUM-LINES.   FLOYD-LINE. MOVE ' ' TO OUT-LINE. MOVE 1 TO LINE-PTR. PERFORM FLOYD-NUM VARYING CUR-COL FROM 1 BY 1 UNTIL CUR-COL IS GREATER THAN CUR-LINE. DISPLAY OUT-LINE.   FLOYD-NUM. COMPUTE MAX-COL-NUM = MAX-NUM - NUM-LINES + CUR-COL. MOVE 0 TO ZERO-SKIP. INSPECT MAX-COL-NUM TALLYING ZERO-SKIP FOR LEADING '0'. IF ZERO-SKIP IS EQUAL TO ZERO PERFORM FLOYD-THREE-DIGITS ELSE IF ZERO-SKIP IS EQUAL TO 1 PERFORM FLOYD-TWO-DIGITS ELSE IF ZERO-SKIP IS EQUAL TO 2 PERFORM FLOYD-ONE-DIGIT. ADD 1 TO CUR-NUM.   FLOYD-ONE-DIGIT. MOVE CUR-NUM TO ONE-DIGIT. STRING ONE-DIGIT DELIMITED BY SIZE INTO OUT-LINE WITH POINTER LINE-PTR.   FLOYD-TWO-DIGITS. MOVE CUR-NUM TO TWO-DIGITS. STRING TWO-DIGITS DELIMITED BY SIZE INTO OUT-LINE WITH POINTER LINE-PTR.   FLOYD-THREE-DIGITS. MOVE CUR-NUM TO THREE-DIGITS. STRING THREE-DIGITS DELIMITED BY SIZE INTO OUT-LINE WITH POINTER LINE-PTR.
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)
#Julia
Julia
# Floyd-Warshall algorithm: https://rosettacode.org/wiki/Floyd-Warshall_algorithm # v0.6   function floydwarshall(weights::Matrix, nvert::Int) dist = fill(Inf, nvert, nvert) for i in 1:size(weights, 1) dist[weights[i, 1], weights[i, 2]] = weights[i, 3] end # return dist next = collect(j != i ? j : 0 for i in 1:nvert, j in 1:nvert)   for k in 1:nvert, i in 1:nvert, j in 1:nvert if dist[i, k] + dist[k, j] < dist[i, j] dist[i, j] = dist[i, k] + dist[k, j] next[i, j] = next[i, k] end end   # return next function printresult(dist, next) println("pair dist path") for i in 1:size(next, 1), j in 1:size(next, 2) if i != j u = i path = @sprintf "%d -> %d  %2d  %s" i j dist[i, j] i while true u = next[u, j] path *= " -> $u" if u == j break end end println(path) end end end printresult(dist, next) end   floydwarshall([1 3 -2; 2 1 4; 2 3 3; 3 4 2; 4 2 -1], 4)
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
#S-BASIC
S-BASIC
  function multiply(a, b = real) = real end = 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
#Sather
Sather
class MAIN is -- we cannot have "functions" (methods) outside classes mult(a, b:FLT):FLT is return a*b; end;   main is #OUT + mult(5.2, 3.4) + "\n"; end; 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.)
#Objeck
Objeck
  bundle Default { class Test { function : Main(args : String[]) ~ Nil { a := [90.0, 47.0, 58.0, 29.0, 22.0, 32.0, 55.0, 5.0, 55.0, 73.0]; Print(Diff(a, 1)); Print(Diff(a, 2)); Print(Diff(a, 9)); }   function : Print(a : Float[]) ~ Nil { if(a <> Nil) { '['->Print(); each(i : a) { a[i]->Print(); ','->Print(); }; ']'->PrintLine(); }; }   function : Diff(a : Float[], n : Int) ~ Float[] { if (n < 0) { return Nil; };   for(i := 0; i < n & a->Size() > 0; i += 1;) { b := Float->New[a->Size() - 1]; for(j := 0; j < b->Size(); j += 1;){ b[j] := a[j+1] - a[j]; }; a := b; };   return a; } } }  
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#Zoomscript
Zoomscript
print "Hello world!"
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 PRINT "Hello world!"
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.
#REBOL
REBOL
rebol [ Title: "Formatted Numeric Output" URL: http://rosettacode.org/wiki/Formatted_Numeric_Output ]   ; REBOL has no built-in facilities for printing pictured output. ; However, it's not too hard to cook something up using the ; string manipulation facilities.   zeropad: func [ "Pad number with zeros or spaces. Works on entire number." pad "Number of characters to pad to." n "Number to pad." /space "Pad with spaces instead." /local nn c s ][ n: to-string n c: " " s: ""   if not space [ c: "0" if #"-" = n/1 [pad: pad - 1 n: copy skip n 1 s: "-"] ]   insert/dup n c (pad - length? n) insert n s n ]   ; These tests replicate the C example output.   print [zeropad/space 9 negate 7.125] print [zeropad/space 9 7.125] print 7.125 print [zeropad 9 negate 7.125] print [zeropad 9 7.125] print 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.
#REXX
REXX
/*REXX program shows various ways to add leading zeroes to numbers. */ a=7.125 b=translate(format(a,10),0,' ') say 'a=' a say 'b=' b say   c=8.37 d=right(c,20,0) say 'c=' c say 'd=' d say   e=19.46 f='000000'e say 'e=' e say 'f=' f say   g=18.25e+1 h=000000||g say 'g=' g say 'h=' h say   i=45.2 j=translate(' 'i,0," ") say 'i=' i say 'j=' j say   k=36.007 l=insert(00000000,k,0) say 'k=' k say 'l=' l say   m=.10055 n=copies(0,20)m say 'm=' m say 'n=' n say   p=4.060 q=0000000000000||p say 'p=' p say 'q=' q say   r=876 s=substr(r+10000000,2) say 'r=' r say 's=' s say   t=13.02 u=reverse(reverse(t)000000000) say 't=' t say 'u=' u /*stick a fork in it, we're done.*/
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).
#PARI.2FGP
PARI/GP
xor(a,b)=(!a&b)||(a&!b); halfadd(a,b)=[a&&b,xor(a,b)]; fulladd(a,b,c)=my(t=halfadd(a,c),s=halfadd(t[2],b));[t[1]||s[1],s[2]]; add4(a3,a2,a1,a0,b3,b2,b1,b0)={ my(s0,s1,s2,s3); s0=fulladd(a0,b0,0); s1=fulladd(a1,b1,s0[1]); s2=fulladd(a2,b2,s1[1]); s3=fulladd(a3,b3,s2[1]); [s3[1],s3[2],s2[2],s1[2],s0[2]] }; add4(0,0,0,0,0,0,0,0)
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.
#Delphi
Delphi
  program Fivenum;   {$APPTYPE CONSOLE}   uses System.SysUtils, System.Generics.Collections;   function Median(x: TArray<Double>; start, endInclusive: Integer): Double; var size, m: Integer; begin size := endInclusive - start + 1; if (size <= 0) then raise EArgumentException.Create('Array slice cannot be empty'); m := start + size div 2; if (odd(size)) then Result := x[m] else Result := (x[m - 1] + x[m]) / 2; end;   function FiveNumber(x: TArray<Double>): TArray<Double>; var m, lowerEnd: Integer; begin SetLength(result, 5); TArray.Sort<double>(x); result[0] := x[0]; result[2] := median(x, 0, length(x) - 1); result[4] := x[length(x) - 1]; m := length(x) div 2; if odd(length(x)) then lowerEnd := m else lowerEnd := m - 1; result[1] := median(x, 0, lowerEnd); result[3] := median(x, m, length(x) - 1); end;   function ArrayToString(x: TArray<double>): string; var i: Integer; begin Result := '['; for i := 0 to High(x) do begin if i > 0 then Result := Result + ','; Result := Result + format('%.4f', [x[i]]); end; Result := Result + ']'; end;   var xl: array of TArray<double> = [[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]]; x: TArray<double>;   begin for x in xl do writeln(ArrayToString(FiveNumber(x)), #10);   readln; end.
http://rosettacode.org/wiki/Find_the_missing_permutation
Find the missing permutation
ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB Listed above are   all-but-one   of the permutations of the symbols   A,   B,   C,   and   D,   except   for one permutation that's   not   listed. Task Find that missing permutation. Methods Obvious method: enumerate all permutations of A, B, C, and D, and then look for the missing permutation. alternate method: Hint: if all permutations were shown above, how many times would A appear in each position? What is the parity of this number? another alternate method: Hint: if you add up the letter values of each column, does a missing letter A, B, C, and D from each column cause the total value for each column to be unique? Related task   Permutations)
#11l
11l
V perms = [‘ABCD’, ‘CABD’, ‘ACDB’, ‘DACB’, ‘BCDA’, ‘ACBD’, ‘ADCB’, ‘CDAB’, ‘DABC’, ‘BCAD’, ‘CADB’, ‘CDBA’, ‘CBAD’, ‘ABDC’, ‘ADBC’, ‘BDCA’, ‘DCBA’, ‘BACD’, ‘BADC’, ‘BDAC’, ‘CBDA’, ‘DBCA’, ‘DCAB’]   V missing = ‘’ L(i) 4 V cnt = [0] * 4 L(j) 0 .< perms.len cnt[perms[j][i].code - ‘A’.code]++ L(j) 4 I cnt[j] != factorial(4-1) missing ‘’= Char(code' ‘A’.code + j) L.break   print(missing)
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month
Find the last Sunday of each month
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 2013-05-26 2013-06-30 2013-07-28 2013-08-25 2013-09-29 2013-10-27 2013-11-24 2013-12-29 Related tasks Day of the week Five weekends Last Friday of each month
#11l
11l
F last_sundays(year) [String] sundays L(month) 1..12 V last_day_of_month = I month < 12 {Time(year, month + 1)} E Time(year + 1) L last_day_of_month -= TimeDelta(days' 1) I last_day_of_month.strftime(‘%w’) == ‘0’ sundays [+]= year‘-’(‘#02’.format(month))‘-’last_day_of_month.strftime(‘%d’) L.break R sundays   print(last_sundays(2013).join("\n"))
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) .
#11l
11l
F line_intersect(Ax1, Ay1, Ax2, Ay2, Bx1, By1, Bx2, By2) V d = (By2 - By1) * (Ax2 - Ax1) - (Bx2 - Bx1) * (Ay2 - Ay1) I d == 0 R (Float.infinity, Float.infinity)   V uA = ((Bx2 - Bx1) * (Ay1 - By1) - (By2 - By1) * (Ax1 - Bx1)) / d V uB = ((Ax2 - Ax1) * (Ay1 - By1) - (Ay2 - Ay1) * (Ax1 - Bx1)) / d   I !(uA C 0.0..1.0 & uB C 0.0..1.0) R (Float.infinity, Float.infinity) V x = Ax1 + uA * (Ax2 - Ax1) V y = Ay1 + uA * (Ay2 - Ay1)   R (x, y)   V (a, b, c, d) = (4.0, 0.0, 6.0, 10.0) V (e, f, g, h) = (0.0, 3.0, 10.0, 7.0) V pt = line_intersect(a, b, c, d, e, f, g, h) print(pt)
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
#6502_Assembly
6502 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
#ALGOL_68
ALGOL 68
five_weekends: BEGIN INT m, year, nfives := 0, not5 := 0; BOOL no5weekend;   MODE MONTH = STRUCT( INT n, [3]CHAR name ) # MODE MONTH #;   []MONTH month = ( MONTH(13, "Jan"), MONTH(3, "Mar"), MONTH(5, "May"), MONTH(7, "Jul"), MONTH(8, "Aug"), MONTH(10, "Oct"), MONTH(12, "Dec") );   FOR year FROM 1900 TO 2100 DO IF year = 1905 THEN printf($"..."l$) FI; no5weekend := TRUE; FOR m TO UPB month DO IF n OF month(m) = 13 THEN IF day_of_week(1, n OF month(m), year-1) = 6 THEN IF year<1905 OR year > 2096 THEN printf(($g, 5zl$, name OF month(m), year)) FI; nfives +:= 1; no5weekend := FALSE FI ELSE IF day_of_week(1, n OF month(m), year) = 6 THEN IF year<1905 OR year > 2096 THEN printf(($g, 5zl$, name OF month(m), year)) FI; nfives +:= 1; no5weekend := FALSE FI FI OD; IF no5weekend THEN not5 +:= 1 FI OD;   printf(($g, g(0)l$, "Number of months with five weekends between 1900 and 2100 = ", nfives)); printf(($g, g(0)l$, "Number of years between 1900 and 2100 with no five weekend months = ", not5));   # contains #   PROC day_of_week = (INT d, m, y)INT: BEGIN INT j, k; j := y OVER 100; k := y MOD 100; (d + (m+1)*26 OVER 10 + k + k OVER 4 + j OVER 4 + 5*j) MOD 7 END # function day_of_week #; SKIP END # program 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
#C.23
C#
using System; using System.Collections.Generic; using System.Numerics;   static class Program { static byte Base, bmo, blim, ic; static DateTime st0; static BigInteger bllim, threshold; static HashSet<byte> hs = new HashSet<byte>(), o = new HashSet<byte>(); static string chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz|"; static List<BigInteger> limits; static string ms;   // convert BigInteger to string using current base static string toStr(BigInteger b) { string res = ""; BigInteger re; while (b > 0) { b = BigInteger.DivRem(b, Base, out re); res = chars[(byte)re] + res; } return res; }   // check for a portion of digits, bailing if uneven static bool allInQS(BigInteger b) { BigInteger re; int c = ic; hs.Clear(); hs.UnionWith(o); while (b > bllim) { b = BigInteger.DivRem(b, Base, out re); hs.Add((byte)re); c += 1; if (c > hs.Count) return false; } return true; }   // check for a portion of digits, all the way to the end static bool allInS(BigInteger b) { BigInteger re; hs.Clear(); hs.UnionWith(o); while (b > bllim) { b = BigInteger.DivRem(b, Base, out re); hs.Add((byte)re); } return hs.Count == Base; }   // check for all digits, bailing if uneven static bool allInQ(BigInteger b) { BigInteger re; int c = 0; hs.Clear(); while (b > 0) { b = BigInteger.DivRem(b, Base, out re); hs.Add((byte)re); c += 1; if (c > hs.Count) return false; } return true; }   // check for all digits, all the way to the end static bool allIn(BigInteger b) { BigInteger re; hs.Clear(); while (b > 0) { b = BigInteger.DivRem(b, Base, out re); hs.Add((byte)re); } return hs.Count == Base; }   // parse a string into a BigInteger, using current base static BigInteger to10(string s) { BigInteger res = 0; foreach (char i in s) res = res * Base + chars.IndexOf(i); return res; }   // returns the minimum value string, optionally inserting extra digit static string fixup(int n) { string res = chars.Substring(0, Base); if (n > 0) res = res.Insert(n, n.ToString()); return "10" + res.Substring(2); }   // checks the square against the threshold, advances various limits when needed static void check(BigInteger sq) { if (sq > threshold) { o.Remove((byte)chars.IndexOf(ms[blim])); blim -= 1; ic -= 1; threshold = limits[bmo - blim - 1]; bllim = to10(ms.Substring(0, blim + 1)); } }   // performs all the caclulations for the current base static void doOne() { limits = new List<BigInteger>(); bmo = (byte)(Base - 1); byte dr = 0; if ((Base & 1) == 1) dr = (byte)(Base >> 1); o.Clear(); blim = 0; byte id = 0; int inc = 1; long i = 0; DateTime st = DateTime.Now; if (Base == 2) st0 = st; byte[] sdr = new byte[bmo]; byte rc = 0; for (i = 0; i < bmo; i++) { sdr[i] = (byte)((i * i) % bmo); rc += sdr[i] == dr ? (byte)1 : (byte)0; sdr[i] += sdr[i] == 0 ? bmo : (byte)0; } i = 0; if (dr > 0) { id = Base; for (i = 1; i <= dr; i++) if (sdr[i] >= dr) if (id > sdr[i]) id = sdr[i]; id -= dr; i = 0; } ms = fixup(id); BigInteger sq = to10(ms); BigInteger rt = new BigInteger(Math.Sqrt((double)sq) + 1); sq = rt * rt; if (Base > 9) { for (int j = 1; j < Base; j++) limits.Add(to10(ms.Substring(0, j) + new string(chars[bmo], Base - j + (rc > 0 ? 0 : 1)))); limits.Reverse(); while (sq < limits[0]) { rt++; sq = rt * rt; } } BigInteger dn = (rt << 1) + 1; BigInteger d = 1; if (Base > 3 && rc > 0) { while (sq % bmo != dr) { rt += 1; sq += dn; dn += 2; } // alligns sq to dr inc = bmo / rc; if (inc > 1) { dn += rt * (inc - 2) - 1; d = inc * inc; } dn += dn + d; } d <<= 1; if (Base > 9) { blim = 0; while (sq < limits[bmo - blim - 1]) blim++; ic = (byte)(blim + 1); threshold = limits[bmo - blim - 1]; if (blim > 0) for (byte j = 0; j <= blim; j++) o.Add((byte)chars.IndexOf(ms[j])); if (blim > 0) bllim = to10(ms.Substring(0, blim + 1)); else bllim = 0; if (Base > 5 && rc > 0) do { if (allInQS(sq)) break; sq += dn; dn += d; i += 1; check(sq); } while (true); else do { if (allInS(sq)) break; sq += dn; dn += d; i += 1; check(sq); } while (true); } else { if (Base > 5 && rc > 0) do { if (allInQ(sq)) break; sq += dn; dn += d; i += 1; } while (true); else do { if (allIn(sq)) break; sq += dn; dn += d; i += 1; } while (true); } rt += i * inc; Console.WriteLine("{0,3} {1,2} {2,2} {3,20} -> {4,-40} {5,10} {6,9:0.0000}s {7,9:0.0000}s", Base, inc, (id > 0 ? chars.Substring(id, 1) : " "), toStr(rt), toStr(sq), i, (DateTime.Now - st).TotalSeconds, (DateTime.Now - st0).TotalSeconds); }   static void Main(string[] args) { Console.WriteLine("base inc id root square" + " test count time total"); for (Base = 2; Base <= 28; Base++) doOne(); Console.WriteLine("Elasped time was {0,8:0.00} minutes", (DateTime.Now - st0).TotalMinutes); } }
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
#Arturo
Arturo
cube: function [x] -> x^3 croot: function [x] -> x^(1//3)   names: ["sin/asin", "cos/acos", "cube/croot"] funclist: @[var 'sin, var 'cos, var 'cube] invlist: @[var 'asin, var 'acos, var 'croot]   num: 0.5   loop 0..2 'f [ result: call funclist\[f] @[num] print [names\[f] "=>" call invlist\[f] @[result]] ]
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
#AutoHotkey
AutoHotkey
#NoEnv ; Set the floating-point precision SetFormat, Float, 0.15 ; Super-global variables for function objects Global F, G ; User-defined functions Cube(X) { Return X ** 3 } CubeRoot(X) { Return X ** (1/3) } ; Function arrays, Sin/ASin and Cos/ACos are built-in FuncArray1 := [Func("Sin"), Func("Cos"), Func("Cube")] FuncArray2 := [Func("ASin"), Func("ACos"), Func("CubeRoot")] ; Compose Compose(FN1, FN2) { Static FG := Func("ComposedFunction") F := FN1, G:= FN2 Return FG } ComposedFunction(X) { Return F.(G.(X)) } ; Run X := 0.5 + 0 Result := "Input:`n" . X . "`n`nOutput:" For Index In FuncArray1 Result .= "`n" . Compose(FuncArray1[Index], FuncArray2[Index]).(X) MsgBox, 0, First-Class Functions, % Result ExitApp
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.
#Erlang
Erlang
  -module( forest_fire ).   -export( [task/0] ).   -record( state, {neighbours=[], position, probability_burn, probability_grow, tree} ).   task() -> erlang:spawn( fun() -> Pid_positions = forest_create( 5, 5, 0.5, 0.3, 0.2 ), Pids = [X || {X, _} <- Pid_positions], [X ! {tree_pid_positions, Pid_positions} || X <- Pids], Start = forest_status( Pids ), Histories = [Start | [forest_step( Pids ) || _X <- lists:seq(1, 2)]], [io:fwrite("~p~n~n", [X]) || X <- Histories] end ).       forest_create( X_max, Y_max, Init, Grow, Burn ) -> [{tree_create(tree_init(Init, random:uniform()), X, Y, Grow, Burn), {X,Y}} || X <- lists:seq(1, X_max), Y<- lists:seq(1, Y_ma\ x)].   forest_status( Pids ) -> [X ! {status_request, erlang:self()} || X <- Pids], [receive {status, Tree, Position, X} -> {Tree, Position} end || X <- Pids].   forest_step( Pids ) -> [X ! {step} || X <- Pids], forest_status( Pids ).   is_neighbour({X, Y}, {X, Y} ) -> false; % Myself is_neighbour({Xn, Yn}, {X, Y} ) when abs(Xn - X) =< 1, abs(Yn - Y) =< 1 -> true; is_neighbour( _Position_neighbour, _Position ) -> false.   loop( State ) -> receive {tree_pid_positions, Pid_positions} -> loop( loop_neighbour(Pid_positions, State) ); {step} -> [X ! {tree, State#state.tree, erlang:self()} || X <- State#state.neighbours], loop( loop_step(State) ); {status_request, Pid} -> Pid ! {status, State#state.tree, State#state.position, erlang:self()}, loop( State ) end.   loop_neighbour( Pid_positions, State ) -> My_position = State#state.position, State#state{neighbours=[Pid || {Pid, Position} <- Pid_positions, is_neighbour( Position, My_position)]}.   loop_step( State ) -> Is_burning = lists:any( fun loop_step_burning/1, [loop_step_receive(X) || X <- State#state.neighbours] ), Tree = loop_step_next( Is_burning, random:uniform(), State ), State#state{tree=Tree}.   loop_step_burning( Tree ) -> Tree =:= burning.   loop_step_next( _Is_burning, Probablility, #state{tree=empty, probability_grow=Grow} ) when Grow > Probablility -> tree; loop_step_next( _Is_burning, _Probablility, #state{tree=empty} ) -> empty; loop_step_next( _Is_burning, _Probablility, #state{tree=burning} ) -> empty; loop_step_next( true, _Probablility, #state{tree=tree} ) -> burning; loop_step_next( false, Probablility, #state{tree=tree, probability_burn=Burn} ) when Burn > Probablility -> burning; loop_step_next( false, _Probablility, #state{tree=tree} ) -> tree.   loop_step_receive( Pid ) -> receive {tree, Tree, Pid} -> Tree end.   tree_create( Tree, X, Y, Grow, Burn ) -> State = #state{position={X, Y}, probability_burn=Burn, probability_grow=Grow, tree=Tree}, erlang:spawn_link( fun() -> random:seed( X, Y, 0 ), loop( State ) end ).   tree_init( Tree_probalility, Random ) when Tree_probalility > Random -> tree; tree_init( _Tree_probalility, _Random ) -> empty.  
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.
#Haskell
Haskell
hailstone n | n == 1 = 1 | even n = n `div` 2 | odd n = 3*n + 1
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.
#Icon_and_Unicon
Icon and Unicon
link printf   procedure main() every put(environment := [], hailenv(1 to 12,0)) # setup environments printf("Sequences:\n") while (e := !environment).sequence > 1 do { every hailstep(!environment) printf("\n") } printf("\nCounts:\n") every printf("%4d ",(!environment).count) printf("\n") end   record hailenv(sequence,count)   procedure hailstep(env) printf("%4d ",env.sequence) if env.sequence ~= 1 then { env.count +:= 1 if env.sequence % 2 = 0 then env.sequence /:= 2 else env.sequence := 3 * env.sequence + 1 } end
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
#Ceylon
Ceylon
shared void run() { "Lazily flatten nested streams" {Anything*} flatten({Anything*} stream) => stream.flatMap((element) => switch (element) case (is {Anything*}) flatten(element) else [element]);   value list = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []];   print(list); print(flatten(list).sequence()); }
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.
#Lua
Lua
  target, board, moves, W, H = {}, {}, 0, 3, 3   function getIndex( i, j ) return i + j * W - W end   function flip( d, r ) function invert( a ) if a == 1 then return 0 end return 1 end local idx if d == 1 then for i = 1, W do idx = getIndex( i, r ) board[idx] = invert( board[idx] ) end else for i = 1, H do idx = getIndex( r, i ) board[idx] = invert( board[idx] ) end end moves = moves + 1 end function createTarget() target, board = {}, {} local idx for j = 1, H do for i = 1, W do idx = getIndex( i, j ) if math.random() < .5 then target[idx] = 0 else target[idx] = 1 end board[idx] = target[idx] end end for i = 1, 103 do if math.random() < .5 then flip( 1, math.random( H ) ) else flip( 2, math.random( W ) ) end end moves = 0 end function getUserInput() io.write( "Input row and/or column: " ); local r = io.read() local a for i = 1, #r do a = string.byte( r:sub( i, i ):lower() ) if a >= 48 and a <= 57 then flip( 2, a - 48 ) end if a >= 97 and a <= string.byte( 'z' ) then flip( 1, a - 96 ) end end end function solved() local idx for j = 1, H do for i = 1, W do idx = getIndex( i, j ) if target[idx] ~= board[idx] then return false end end end return true end function display() local idx io.write( "\nTARGET\n " ) for i = 1, W do io.write( string.format( "%d ", i ) ) end; print() for j = 1, H do io.write( string.format( "%s ", string.char( 96 + j ) ) ) for i = 1, W do idx = getIndex( i, j ) io.write( string.format( "%d ", target[idx] ) ) end; io.write( "\n" ) end io.write( "\nBOARD\n " ) for i = 1, W do io.write( string.format( "%d ", i ) ) end; print() for j = 1, H do io.write( string.format( "%s ", string.char( 96 + j ) ) ) for i = 1, W do idx = getIndex( i, j ) io.write( string.format( "%d ", board[idx] ) ) end; io.write( "\n" ) end io.write( string.format( "Moves: %d\n", moves ) ) end function play() while true do createTarget() repeat display() getUserInput() until solved() display() io.write( "Very well!\nPlay again(Y/N)? " ); if io.read():lower() ~= "y" then return end end end --[[entry point]]-- math.randomseed( os.time() ) 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.
#J
J
  p=: adverb define : el =. x en =. y pwr =. m el =. <. | el digitcount =. <. 10 ^. el log10pwr =. 10 ^. pwr 'raised found' =. _1 0 while. found < en do. raised =. >: raised firstdigits =. (<.!.0) 10^digitcount + 1 | log10pwr * raised found =. found + firstdigits = el end. raised )  
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.
#Java
Java
  public class FirstPowerOfTwo {   public static void main(String[] args) { runTest(12, 1); runTest(12, 2); runTest(123, 45); runTest(123, 12345); runTest(123, 678910); }   private static void runTest(int l, int n) { System.out.printf("p(%d, %d) = %,d%n", l, n, p(l, n)); }   public static int p(int l, int n) { int test = 0; double log = Math.log(2) / Math.log(10); int factor = 1; int loop = l; while ( loop > 10 ) { factor *= 10; loop /= 10; } while ( n > 0) { test++; int val = (int) (factor * Math.pow(10, test * log % 1)); if ( val == l ) { n--; } } 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
#jq
jq
# Infrastructure: # zip this and that def zip(that): . as $this | reduce range(0;length) as $i ([]; . + [ [$this[$i], that[$i]] ]);   # The task: 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 numlist: [x,y,z];   def invlist: [xi, yi, zi];   # Input: [x,y] def multiplier(j): .[0] * .[1] * j;   numlist|zip(invlist) | map( multiplier(0.5) )
http://rosettacode.org/wiki/First-class_functions/Use_numbers_analogously
First-class functions/Use numbers analogously
In First-class functions, a language is showing how its manipulation of functions is similar to its manipulation of other types. This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers. Write a program to create an ordered collection of a mixture of literally typed and expressions producing a real number, together with another ordered collection of their multiplicative inverses. Try and use the following pseudo-code to generate the numbers for the ordered collections: x = 2.0 xi = 0.5 y = 4.0 yi = 0.25 z = x + y zi = 1.0 / ( x + y ) Create a function multiplier, that given two numbers as arguments returns a function that when called with one argument, returns the result of multiplying the two arguments to the call to multiplier that created it and the argument in the call: new_function = multiplier(n1,n2) # where new_function(m) returns the result of n1 * n2 * m Applying the multiplier of a number and its inverse from the two ordered collections of numbers in pairs, show that the result in each case is one. Compare and contrast the resultant program with the corresponding entry in First-class functions. They should be close. To paraphrase the task description: Do what was done before, but with numbers rather than functions
#JavaScript
JavaScript
const x = 2.0; const xi = 0.5; const y = 4.0; const yi = 0.25; const z = x + y; const zi = 1.0 / (x + y); const pairs = [[x, xi], [y, yi], [z, zi]]; const testVal = 0.5;   const multiplier = (a, b) => m => a * b * m;   const test = () => { return pairs.map(([a, b]) => { const f = multiplier(a, b); const result = f(testVal); return `${a} * ${b} * ${testVal} = ${result}`; }); }   test().join('\n');
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
#Nemerle
Nemerle
loop xx = 1 to 10 if xx = 1 then leave -- loop terminated by leave say 'unreachable' 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
#NetRexx
NetRexx
loop xx = 1 to 10 if xx = 1 then leave -- loop terminated by leave say 'unreachable' 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.
#CoffeeScript
CoffeeScript
triangle = (array) -> for n in array console.log "#{n} rows:" printMe = 1 printed = 0 row = 1 to_print = "" while row <= n cols = Math.ceil(Math.log10(n * (n - 1) / 2 + printed + 2.0)) p = ("" + printMe).length while p++ <= cols to_print += ' ' to_print += printMe + ' ' if ++printed == row console.log to_print to_print = "" row++ printed = 0 printMe++   triangle [5, 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)
#Kotlin
Kotlin
// version 1.1   object FloydWarshall { fun doCalcs(weights: Array<IntArray>, nVertices: Int) { val dist = Array(nVertices) { DoubleArray(nVertices) { Double.POSITIVE_INFINITY } } for (w in weights) dist[w[0] - 1][w[1] - 1] = w[2].toDouble() val next = Array(nVertices) { IntArray(nVertices) } for (i in 0 until next.size) { for (j in 0 until next.size) { if (i != j) next[i][j] = j + 1 } } for (k in 0 until nVertices) { for (i in 0 until nVertices) { for (j in 0 until nVertices) { if (dist[i][k] + dist[k][j] < dist[i][j]) { dist[i][j] = dist[i][k] + dist[k][j] next[i][j] = next[i][k] } } } } printResult(dist, next) }   private fun printResult(dist: Array<DoubleArray>, next: Array<IntArray>) { var u: Int var v: Int var path: String println("pair dist path") for (i in 0 until next.size) { for (j in 0 until next.size) { if (i != j) { u = i + 1 v = j + 1 path = ("%d -> %d  %2d  %s").format(u, v, dist[i][j].toInt(), u) do { u = next[u - 1][v - 1] path += " -> " + u } while (u != v) println(path) } } } } }   fun main(args: Array<String>) { val weights = arrayOf( intArrayOf(1, 3, -2), intArrayOf(2, 1, 4), intArrayOf(2, 3, 3), intArrayOf(3, 4, 2), intArrayOf(4, 2, -1) ) val nVertices = 4 FloydWarshall.doCalcs(weights, nVertices) }
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
#Scala
Scala
def multiply(a: Int, b: Int) = 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
#Scheme
Scheme
(define multiply *)
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.)
#OCaml
OCaml
let rec forward_difference = function a :: (b :: _ as xs) -> b - a :: forward_difference xs | _ -> []   let rec nth_forward_difference n xs = if n = 0 then xs else nth_forward_difference (pred n) (forward_difference xs)
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.
#Ring
Ring
  decimals(3) see fixedprint(7.125, 5) + nl   func fixedprint num, digs for i = 1 to digs - len(string(floor(num))) see "0" next see num + nl  
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.
#Ruby
Ruby
r = 7.125 printf " %9.3f\n", r #=> 7.125 printf " %09.3f\n", r #=> 00007.125 printf " %09.3f\n", -r #=> -0007.125 printf " %+09.3f\n", r #=> +0007.125 puts " %9.3f" % r #=> 7.125 puts " %09.3f" % r #=> 00007.125 puts " %09.3f" % -r #=> -0007.125 puts " %+09.3f" % r #=> +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).
#Perl
Perl
sub dec2bin { sprintf "%04b", shift } sub bin2dec { oct "0b".shift } sub bin2bits { reverse split(//, substr(shift,0,shift)); } sub bits2bin { join "", map { 0+$_ } reverse @_ }   sub bxor { my($a, $b) = @_; (!$a & $b) | ($a & !$b); }   sub half_adder { my($a, $b) = @_; ( bxor($a,$b), $a & $b ); }   sub full_adder { my($a, $b, $c) = @_; my($s1, $c1) = half_adder($a, $c); my($s2, $c2) = half_adder($s1, $b); ($s2, $c1 | $c2); }   sub four_bit_adder { my($a, $b) = @_; my @abits = bin2bits($a,4); my @bbits = bin2bits($b,4);   my($s0,$c0) = full_adder($abits[0], $bbits[0], 0); my($s1,$c1) = full_adder($abits[1], $bbits[1], $c0); my($s2,$c2) = full_adder($abits[2], $bbits[2], $c1); my($s3,$c3) = full_adder($abits[3], $bbits[3], $c2); (bits2bin($s0, $s1, $s2, $s3), $c3); }   print " A B A B C S sum\n"; for my $a (0 .. 15) { for my $b (0 .. 15) { my($abin, $bbin) = map { dec2bin($_) } $a,$b; my($s,$c) = four_bit_adder( $abin, $bbin ); printf "%2d + %2d = %s + %s = %s %s = %2d\n", $a, $b, $abin, $bbin, $c, $s, bin2dec($c.$s); } }
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.
#F.23
F#
open System   // Take from https://stackoverflow.com/a/1175123 let rec last = function | hd :: [] -> hd | _ :: tl -> last tl | _ -> failwith "Empty list."   let median x = for e in x do if Double.IsNaN(e) then failwith "unable to deal with lists containing NaN"   let size = List.length(x) if size <= 0 then failwith "Array slice cannot be empty" let m = size / 2 if size % 2 = 1 then x.[m] else (x.[m - 1] + x.[m]) / 2.0   let fivenum x = let x2 = List.sort(x) let m = List.length(x2) / 2 let lowerEnd = if List.length(x2) % 2 = 1 then m else m - 1 [List.head x2, median x2.[..lowerEnd], median x2, median x2.[m..], last x2]   [<EntryPoint>] let main _ = let x1 = [ [15.0; 6.0; 42.0; 41.0; 7.0; 36.0; 49.0; 40.0; 39.0; 47.0; 43.0]; [36.0; 40.0; 7.0; 39.0; 41.0; 15.0]; [ 0.14082834; 0.09748790; 1.73131507; 0.87636009; -1.95059594; 0.73438555; -0.03035726; 1.46675970; -0.74621349; -0.72588772; 0.63905160; 0.61501527; -0.98983780; -1.00447874; -0.62759469; 0.66206163; 1.04312009; -0.10305385; 0.75775634; 0.32566578 ] ]   for a in x1 do let y = fivenum a Console.WriteLine("{0}", y);   0 // return an integer exit code
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)
#360_Assembly
360 Assembly
* Find the missing permutation - 19/10/2015 PERMMISX CSECT USING PERMMISX,R15 set base register LA R4,0 i=0 LA R6,1 step LA R7,23 to LOOPI BXH R4,R6,ELOOPI do i=1 to hbound(perms) LA R5,0 j=0 LA R8,1 step LA R9,4 to LOOPJ BXH R5,R8,ELOOPJ do j=1 to hbound(miss) LR R1,R4 i SLA R1,2 *4 LA R3,PERMS-5(R1) @perms(i) AR R3,R5 j LA R2,MISS-1(R5) @miss(j) XC 0(1,R2),0(R3) miss(j)=miss(j) xor substr(perms(i),j,1) B LOOPJ ELOOPJ B LOOPI ELOOPI XPRNT MISS,15 print buffer XR R15,R15 set return code BR R14 return to caller PERMS DC C'ABCD',C'CABD',C'ACDB',C'DACB',C'BCDA',C'ACBD' DC C'ADCB',C'CDAB',C'DABC',C'BCAD',C'CADB',C'CDBA' DC C'CBAD',C'ABDC',C'ADBC',C'BDCA',C'DCBA',C'BACD' DC C'BADC',C'BDAC',C'CBDA',C'DBCA',C'DCAB' MISS DC 4XL1'00',C' is missing' buffer YREGS END PERMMISX
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
#360_Assembly
360 Assembly
* Last Sunday of each month 31/01/2017 LASTSUND CSECT USING LASTSUND,R13 base register B 72(R15) skip savearea DC 17F'0' savearea STM R14,R12,12(R13) prolog ST R13,4(R15) " <- ST R15,8(R13) " -> LR R13,R15 " addressability L R4,YEAR year SRDA R4,32 . D R4,=F'400' year/400 LTR R4,R4 if year//400=0 BZ LEAP L R4,YEAR year SRDA R4,32 . D R4,=F'4' year/4 LTR R4,R4 if year//4=0 BNZ NOTLEAP L R4,YEAR year SRDA R4,32 . D R4,=F'100' year/400 LTR R4,R4 if year//100=0 BZ NOTLEAP LEAP MVC DAYS+4(4),=F'29' days(2)=29 NOTLEAP L R8,YEAR year BCTR R8,0 y=year-1 LA R7,42 42 AR R7,R8 +y LR R3,R8 y SRA R3,2 y/4 AR R7,R3 +y/4 LR R4,R8 y SRDA R4,32 . D R4,=F'100' y/100 LA R4,0 . M R4,=F'6' *6 AR R7,R5 +6*(y/100) LR R4,R8 y SRDA R4,32 . D R4,=F'400' y/100 AR R7,R5 k=42+y+y/4+6*(y/100)+y/400 LA R6,1 m=1 LOOPM C R6,=F'12' do m=1 to 12 BH ELOOPM LR R1,R6 m SLA R1,2 . L R2,DAYS-4(R1) days(m) AR R7,R2 k=k+days(m) LR R4,R7 k SRDA R4,32 . D R4,=F'7' k/7 SR R2,R4 days(m)-k//7 LR R9,R2 d=days(m)-k//7 L R1,YEAR year CVD R1,DW year: binary to packed OI DW+7,X'0F' zap sign UNPK PG(4),DW unpack (ZL4) CVD R6,DW m : binary to packed OI DW+7,X'0F' zap sign UNPK PG+5(2),DW unpack (ZL2) CVD R9,DW d: binary to packed OI DW+7,X'0F' zap sign UNPK PG+8(2),DW unpack (ZL2) XPRNT PG,L'PG print buffer LA R6,1(R6) m=m+1 B LOOPM ELOOPM L R13,4(0,R13) epilog LM R14,R12,12(R13) " restore XR R15,R15 " rc=0 BR R14 exit YEAR DC F'2013' <== input year DAYS DC F'31',F'28',F'31',F'30',F'31',F'30' DC F'31',F'31',F'30',F'31',F'30',F'31' PG DC CL80'YYYY-MM-DD' buffer XDEC DS CL12 temp DW DS D packed (PL8) 15num YREGS END LASTSUND
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
#Action.21
Action!
;https://en.wikipedia.org/wiki/Determination_of_the_day_of_the_week#Sakamoto.27s_methods BYTE FUNC DayOfWeek(INT y BYTE m,d) ;1<=m<=12, y>1752 BYTE ARRAY t=[0 3 2 5 0 3 5 1 4 6 2 4] BYTE res   IF m<3 THEN y==-1 FI res=(y+y/4-y/100+y/400+t(m-1)+d) MOD 7 RETURN (res)   BYTE FUNC IsLeapYear(INT y) IF y MOD 100=0 THEN IF y MOD 400=0 THEN RETURN (1) ELSE RETURN (0) FI FI   IF y MOD 4=0 THEN RETURN (1) FI RETURN (0)   INT FUNC GetMaxDay(INT y BYTE m) BYTE ARRAY MaxDay=[31 28 31 30 31 30 31 31 30 31 30 31]   IF m=2 AND IsLeapYear(y)=1 THEN RETURN (29) FI RETURN (MaxDay(m-1))   PROC PrintB2(BYTE x) IF x<10 THEN Put('0) FI PrintB(x) RETURN   PROC Main() INT MinYear=[1753],MaxYear=[9999],y BYTE m,d,last,maxD   DO PrintF("Input year in range %I...%I: ",MinYear,MaxYear) y=InputI() UNTIL y>=MinYear AND y<=MaxYear OD   FOR m=1 TO 12 DO last=0 maxD=GetMaxDay(y,m) FOR d=1 TO maxD DO IF DayOfWeek(y,m,d)=0 THEN last=d FI OD PrintI(y) Put('-) PrintB2(m) Put('-) PrintB2(last) PutE() OD RETURN
http://rosettacode.org/wiki/Find_the_intersection_of_two_lines
Find the intersection of two lines
[1] Task Find the point of intersection of two lines in 2D. The 1st line passes though   (4,0)   and   (6,10) . The 2nd line passes though   (0,3)   and   (10,7) .
#360_Assembly
360 Assembly
* Intersection of two lines 01/03/2019 INTERSEC CSECT USING INTERSEC,R13 base register B 72(R15) skip savearea DC 17F'0' savearea SAVE (14,12) save previous context ST R13,4(R15) link backward ST R15,8(R13) link forward LR R13,R15 set addressability LE F0,XA xa IF CE,F0,EQ,XB THEN if xa=xb then STE F0,X1 x1=xa LE F0,YA IF CE,F0,EQ,YB THEN if ya=yb then MVI MSG,C'=' msg='=' ENDIF , endif ELSE , else MVI FK1,X'01' fk1=true LE F0,YB SE F0,YA yb-ya LE F2,XB SE F2,XA xb-xa DER F0,F2 / STE F0,K1 k1=(yb-ya)/(xb-xa) ME F0,XA k1*xa LE F2,YA ya SER F2,F0 - STE F2,D1 d1=ya-k1*xa ENDIF , endif LE F0,XC IF CE,F0,EQ,XD THEN if xc=xd then STE F0,X2 x2=xc LE F4,YC yc IF CE,F4,EQ,YD THEN if yc=yd then MVI MSG,C'=' msg='=' ENDIF , endif ELSE , else MVI FK2,X'01' fk2=true LE F0,YD SE F0,YC yd-yc LE F2,XD SE F2,XC xd-xc DER F0,F2 / STE F0,K2 k2=(yd-yc)/(xd-xc) ME F0,XC k2*xc LE F2,YC yc SER F2,F0 - STE F2,D2 d2=yc-k2*xc ENDIF , endif IF CLI,MSG,EQ,C' ' THEN if msg=' ' then IF CLI,FK1,EQ,X'00' THEN if not fk1 then IF CLI,FK2,EQ,X'00' THEN if not fk2 then LE F4,X1 IF CE,F4,EQ,X2 if x1=x2 then MVI MSG,C'=' msg='=' ELSE , else MVI MSG,C'/' msg='/' ENDIF , endif ELSE , else LE F0,X1 STE F0,X x=x1 LE F0,K2 k2 ME F0,X *x AE F0,D2 +d2 STE F0,Y y=k2*x+d2 ENDIF , endif ELSE , else IF CLI,FK2,EQ,X'00' THEN if not fk2 then LE F0,X2 STE F0,X x=x2 LE F0,K1 k1 ME F0,X *x AE F0,D1 +d1 STE F0,Y y=k1*x+d1 ELSE , else LE F4,K1 IF CE,F4,EQ,K2 THEN if k1=k2 then LE F4,D1 IF CE,F4,EQ,D2 THEN if d1=d2 then MVI MSG,C'=' msg='='; ELSE , else MVI MSG,C'/' msg='/'; ENDIF , endif ELSE , else LE F0,D2 d2 SE F0,D1 -d1 LE F2,K1 k1 SE F2,K2 -k2 DER F0,F2 / STE F0,X x=(d2-d1)/(k1-k2) LE F0,K1 k1 ME F0,X *x AE F0,D1 +d1 STE F0,Y y=k1*x+d1 ENDIF , endif ENDIF , endif ENDIF , endif ENDIF , endif IF CLI,MSG,EQ,C' ' THEN if msg=' ' then LE F0,X x LA R0,3 decimal=3 BAL R14,FORMATF format x MVC PG+0(13),0(R1) output x LE F0,Y y LA R0,3 decimal=3 BAL R14,FORMATF format y MVC PG+13(13),0(R1) output y ENDIF , endif MVC PG+28(1),MSG output msg XPRNT PG,L'PG print buffer L R13,4(0,R13) restore previous savearea pointer RETURN (14,12),RC=0 restore registers from calling sav COPY plig\$_FORMATF.MLC XA DC E'4.0' point A YA DC E'0.0' XB DC E'6.0' point B YB DC E'10.0' XC DC E'0.0' point C YC DC E'3.0' XD DC E'10.0' point D YD DC E'7.0' X DS E Y DS E X1 DS E X2 DS E K1 DS E K2 DS E D1 DS E D2 DS E FK1 DC X'00' FK2 DC X'00' MSG DC C' ' PG DC CL80' ' REGEQU END INTERSEC
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) .
#Action.21
Action!
INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit   DEFINE REALPTR="CARD" TYPE PointR=[REALPTR x,y]   PROC Det(REAL POINTER x1,y1,x2,y2,res) REAL tmp1,tmp2   RealMult(x1,y2,tmp1) RealMult(y1,x2,tmp2) RealSub(tmp1,tmp2,res) 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(PointR POINTER p1,p2,p3,p4,res) REAL det1,det2,dx1,dx2,dy1,dy2,nom,denom   Det(p1.x,p1.y,p2.x,p2.y,det1) Det(p3.x,p3.y,p4.x,p4.y,det2) RealSub(p1.x,p2.x,dx1) RealSub(p1.y,p2.y,dy1) RealSub(p3.x,p4.x,dx2) RealSub(p3.y,p4.y,dy2) Det(dx1,dy1,dx2,dy2,denom)   IF IsZero(denom) THEN RETURN (0) FI   Det(det1,dx1,det2,dx2,nom) RealDiv(nom,denom,res.x) Det(det1,dy1,det2,dy2,nom) RealDiv(nom,denom,res.y) RETURN (1)   PROC PrintPoint(PointR POINTER p) Print("(") PrintR(p.x) Print(",") PrintR(p.y) Print(")") RETURN   PROC PrintLine(PointR POINTER p1,p2) PrintPoint(p1) Print(" and ") PrintPoint(p2) RETURN   PROC Test(PointR POINTER p1,p2,p3,p4) BYTE res REAL px,py PointR p   p.x=px p.y=py Print("Line 1 points: ") PrintLine(p1,p2) PutE() Print("Line 2 points: ") PrintLine(p3,p4) PutE()   res=Intersection(p1,p2,p3,p4,p) IF res THEN Print("Intersection point: ") PrintPoint(p) PutE() ELSE PrintE("There is no intersection") FI PutE() RETURN   PROC Main() REAL x1,y1,x2,y2,x3,y3,x4,y4,px,py PointR p1,p2,p3,p4   Put(125) PutE() ;clear screen   p1.x=x1 p1.y=y1 p2.x=x2 p2.y=y2 p3.x=x3 p3.y=y3 p4.x=x4 p4.y=y4   IntToReal(4,x1) IntToReal(0,y1) IntToReal(6,x2) IntToReal(10,y2) IntToReal(0,x3) IntToReal(3,y3) IntToReal(10,x4) IntToReal(7,y4) Test(p1,p2,p3,p4)   IntToReal(0,x1) IntToReal(0,y1) IntToReal(1,x2) IntToReal(1,y2) IntToReal(1,x3) IntToReal(2,y3) IntToReal(4,x4) IntToReal(5,y4) Test(p1,p2,p3,p4) RETURN
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
#68000_Assembly
68000 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
#AppleScript
AppleScript
set fiveWeekendMonths to {} set noFiveWeekendYears to {}   set someDate to current date set day of someDate to 1   repeat with someYear from 1900 to 2100 set year of someDate to someYear set foundOne to false repeat with someMonth in {January, March, May, July, ¬ August, October, December} set month of someDate to someMonth if weekday of someDate is Friday then set foundOne to true set end of fiveWeekendMonths to ¬ (someYear as text) & "-" & (someMonth as text) end end repeat if not foundOne then set end of noFiveWeekendYears to someYear end end repeat   set text item delimiters to ", " set monthList to ¬ (items 1 thru 5 of fiveWeekendMonths as text) & ", ..." & linefeed & ¬ " ..., " & (items -5 thru end of fiveWeekendMonths as text)   set monthCount to count fiveWeekendMonths set yearCount to count noFiveWeekendYears   set resultText to ¬ "Months with five weekends (" & monthCount & "): " & linefeed & ¬ " " & monthList & linefeed & linefeed & ¬ "Years with no such months (" & yearCount & "): "   set y to 1 repeat while y < yearCount set final to y+11 if final > yearCount then set final to yearCount end set resultText to ¬ resultText & linefeed & ¬ " " & (items y through final of noFiveWeekendYears as text) set y to y + 12 end resultText
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
#C.2B.2B
C++
#include <string> #include <iostream> #include <cstdlib> #include <math.h> #include <chrono> #include <iomanip>   using namespace std;   const int maxBase = 16; // maximum base tabulated int base, bmo, tc; // globals: base, base minus one, test count const string chars = "0123456789ABCDEF"; // characters to use for the different bases unsigned long long full; // for allIn() testing   // converts base 10 to string representation of the current base string toStr(const unsigned long long ull) { unsigned long long u = ull; string res = ""; while (u > 0) { lldiv_t result1 = lldiv(u, base); res = chars[(int)result1.rem] + res; u = (unsigned long long)result1.quot; } return res; }   // converts string to base 10 unsigned long long to10(string s) { unsigned long long res = 0; for (char i : s) res = res * base + chars.find(i); return res; }   // determines whether all characters are present bool allIn(const unsigned long long ull) { unsigned long long u, found; u = ull; found = 0; while (u > 0) { lldiv_t result1 = lldiv(u, base); found |= (unsigned long long)1 << result1.rem; u = result1.quot; } return found == full; }   // returns the minimum value string, optionally inserting extra digit string fixup(int n) { string res = chars.substr(0, base); if (n > 0) res = res.insert(n, chars.substr(n, 1)); return "10" + res.substr(2); }   // perform the calculations for one base void doOne() { bmo = base - 1; tc = 0; unsigned long long sq, rt, dn, d; int id = 0, dr = (base & 1) == 1 ? base >> 1 : 0, inc = 1, sdr[maxBase] = { 0 }; full = ((unsigned long long)1 << base) - 1; int rc = 0; for (int i = 0; i < bmo; i++) { sdr[i] = (i * i) % bmo; if (sdr[i] == dr) rc++; if (sdr[i] == 0) sdr[i] += bmo; } if (dr > 0) { id = base; for (int i = 1; i <= dr; i++) if (sdr[i] >= dr) if (id > sdr[i]) id = sdr[i]; id -= dr; } sq = to10(fixup(id)); rt = (unsigned long long)sqrt(sq) + 1; sq = rt * rt; dn = (rt << 1) + 1; d = 1; if (base > 3 && rc > 0) { while (sq % bmo != dr) { rt += 1; sq += dn; dn += 2; } // alligns sq to dr inc = bmo / rc; if (inc > 1) { dn += rt * (inc - 2) - 1; d = inc * inc; } dn += dn + d; } d <<= 1; do { if (allIn(sq)) break; sq += dn; dn += d; tc++; } while (true); rt += tc * inc; cout << setw(4) << base << setw(3) << inc << " " << setw(2) << (id > 0 ? chars.substr(id, 1) : " ") << setw(10) << toStr(rt) << " " << setw(20) << left << toStr(sq) << right << setw(12) << tc << endl; }   int main() { cout << "base inc id root sqr test count" << endl; auto st = chrono::system_clock::now(); for (base = 2; base <= maxBase; base++) doOne(); chrono::duration<double> et = chrono::system_clock::now() - st; cout << "\nComputation time was " << et.count() * 1000 << " milliseconds" << endl; return 0; }
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
#Axiom
Axiom
fns := [sin$Float, cos$Float, (x:Float):Float +-> x^3] inv := [asin$Float, acos$Float, (x:Float):Float +-> x^(1/3)] [(f*g) 0.5 for f in fns for g in inv]
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
#BBC_BASIC
BBC BASIC
REM Create some functions and their inverses: DEF FNsin(a) = SIN(a) DEF FNasn(a) = ASN(a) DEF FNcos(a) = COS(a) DEF FNacs(a) = ACS(a) DEF FNcube(a) = a^3 DEF FNroot(a) = a^(1/3)   dummy = FNsin(1)   REM Create the collections (here structures are used): DIM cA{Sin%, Cos%, Cube%} DIM cB{Asn%, Acs%, Root%} cA.Sin% = ^FNsin() : cA.Cos% = ^FNcos() : cA.Cube% = ^FNcube() cB.Asn% = ^FNasn() : cB.Acs% = ^FNacs() : cB.Root% = ^FNroot()   REM Create some function compositions: AsnSin% = FNcompose(cB.Asn%, cA.Sin%) AcsCos% = FNcompose(cB.Acs%, cA.Cos%) RootCube% = FNcompose(cB.Root%, cA.Cube%)   REM Test applying the compositions: x = 1.234567 : PRINT x, FN(AsnSin%)(x) x = 2.345678 : PRINT x, FN(AcsCos%)(x) x = 3.456789 : PRINT x, FN(RootCube%)(x) END   DEF FNcompose(f%,g%) LOCAL f$, p% f$ = "(x)=" + CHR$&A4 + "(&" + STR$~f% + ")(" + \ \ CHR$&A4 + "(&" + STR$~g% + ")(x))" DIM p% LEN(f$) + 4 $(p%+4) = f$ : !p% = p%+4 = p%
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.
#F.23
F#
open System open System.Diagnostics open System.Drawing open System.Drawing.Imaging open System.Runtime.InteropServices open System.Windows.Forms   module ForestFire =   type Cell = Empty | Tree | Fire   let rnd = new System.Random() let initial_factor = 0.35 let ignition_factor = 1e-5 // rate of lightning strikes (f) let growth_factor = 2e-3 // rate of regrowth (p) let width = 640 // width of the forest region let height = 480 // height of the forest region   let make_forest = Array2D.init height width (fun _ _ -> if rnd.NextDouble() < initial_factor then Tree else Empty)   let count (forest:Cell[,]) row col = let mutable n = 0 let h,w = forest.GetLength 0, forest.GetLength 1 for r in row-1 .. row+1 do for c in col-1 .. col+1 do if r >= 0 && r < h && c >= 0 && c < w && forest.[r,c] = Fire then n <- n + 1 if forest.[row,col] = Fire then n-1 else n   let burn (forest:Cell[,]) r c = match forest.[r,c] with | Fire -> Empty | Tree -> if rnd.NextDouble() < ignition_factor then Fire else if (count forest r c) > 0 then Fire else Tree | Empty -> if rnd.NextDouble() < growth_factor then Tree else Empty   // All the functions below this point are drawing the generated images to screen. let make_image (pixels:int[]) = let bmp = new Bitmap(width, height) let bits = bmp.LockBits(Rectangle(0,0,width,height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb) Marshal.Copy(pixels, 0, bits.Scan0, bits.Height*bits.Width) |> ignore bmp.UnlockBits(bits) bmp   // This function is run asynchronously to avoid blocking the main GUI thread. let run (box:PictureBox) (label:Label) = async { let timer = new Stopwatch() let forest = make_forest |> ref let pixel = Array.create (height*width) (Color.Black.ToArgb()) let rec update gen = timer.Start() forest := burn !forest |> Array2D.init height width for y in 0..height-1 do for x in 0..width-1 do pixel.[x+y*width] <- match (!forest).[y,x] with | Empty -> Color.Gray.ToArgb() | Tree -> Color.Green.ToArgb() | Fire -> Color.Red.ToArgb() let img = make_image pixel box.Invoke(MethodInvoker(fun () -> box.Image <- img)) |> ignore let msg = sprintf "generation %d @ %.1f fps" gen (1000./timer.Elapsed.TotalMilliseconds) label.Invoke(MethodInvoker(fun () -> label.Text <- msg )) |> ignore timer.Reset() update (gen + 1) update 0 }   let main args = let form = new Form(AutoSize=true, Size=new Size(800,600), Text="Forest fire cellular automata") let box = new PictureBox(Dock=DockStyle.Fill,Location=new Point(0,0),SizeMode=PictureBoxSizeMode.StretchImage) let label = new Label(Dock=DockStyle.Bottom, Text="Ready") form.FormClosed.Add(fun eventArgs -> Async.CancelDefaultToken() Application.Exit()) form.Controls.Add(box) form.Controls.Add(label) run box label |> Async.Start form.Show() Application.Run() 0   #if INTERACTIVE ForestFire.main [|""|] #else [<System.STAThread>] [<EntryPoint>] let main args = ForestFire.main args #endif
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.
#J
J
coclass 'hailstone'   step=:3 :0 NB. and determine next element in hailstone sequence if.1=N do. N return.end. NB. count how many times this has run when N was not 1 STEP=:STEP+1 if.0=2|N do. N=: N%2 else. N=: 1 + 3*N end. )   create=:3 :0 STEP=: 0 N=: y )   current=:3 :0 N__y )   run1=:3 :0 step__y'' STEP__y )   run=:3 :0 old=: '' while. -. old -: state=: run1"0 y do. smoutput 4j0 ": current"0 y old=: state 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.
#jq
jq
{ "value": <HAILSTONE>, "count": <COUNT> }
http://rosettacode.org/wiki/First_class_environments
First class environments
According to Wikipedia, "In computing, a first-class object ... is an entity that can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable". Often this term is used in the context of "first class functions". In an analogous way, a programming language may support "first class environments". The environment is minimally, the set of variables accessible to a statement being executed. Change the environments and the same statement could produce different results when executed. Often an environment is captured in a closure, which encapsulates a function together with an environment. That environment, however, is not first-class, as it cannot be created, passed etc. independently from the function's code. Therefore, a first class environment is a set of variable bindings which can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable. It is like a closure without code. A statement must be able to be executed within a stored first class environment and act according to the environment variable values stored within. Task Build a dozen environments, and a single piece of code to be run repeatedly in each of these environments. Each environment contains the bindings for two variables:   a value in the Hailstone sequence, and   a count which is incremented until the value drops to 1. The initial hailstone values are 1 through 12, and the count in each environment is zero. When the code runs, it calculates the next hailstone step in the current environment (unless the value is already 1) and counts the steps. Then it prints the current value in a tabular form. When all hailstone values dropped to 1, processing stops, and the total number of hailstone steps for each environment is printed.
#Julia
Julia
const jobs = 12   mutable struct Environment seq::Int cnt::Int Environment() = new(0, 0) end   const env = [Environment() for i in 1:jobs] const currentjob = [1]   seq() = env[currentjob[1]].seq cnt() = env[currentjob[1]].cnt seq(n) = (env[currentjob[1]].seq = n) cnt(n) = (env[currentjob[1]].cnt = n)   function hail() print(lpad(seq(), 4)) if seq() == 1 return end cnt(cnt() + 1) seq(isodd(seq()) ? 3 * seq() + 1 : div(seq(), 2)) end   function runtest() for i in 1:jobs currentjob[1] = i env[i].seq = i end computing = true while computing for i in 1:jobs currentjob[1] = i hail() end println() for j in 1:jobs currentjob[1] = j if seq() != 1 break elseif j == jobs computing = false end end end println("\nCOUNTS:") for i in 1:jobs currentjob[1] = i print(lpad(cnt(), 4)) end println() end   runtest()  
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
#Clojure
Clojure
(defn flatten [coll] (lazy-seq (when-let [s (seq coll)] (if (coll? (first s)) (concat (flatten (first s)) (flatten (rest s))) (cons (first s) (flatten (rest s)))))))
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.
#Maple
Maple
FlippingBits := module() export ModuleApply; local gameSetup, flip, printGrid, checkInput; local board;   gameSetup := proc(n) local r, c, i, toFlip, target; randomize(): target := Array( 1..n, 1..n, rand(0..1) ); board := copy(target); for i to rand(3..9)() do toFlip := [0, 0]; toFlip[1] := StringTools[Random](1, "rc"); toFlip[2] := convert(rand(1..n)(), string); flip(toFlip); end do; return target; end proc;   flip := proc(line) local i, lineNum; lineNum := parse(op(line[2..-1])); for i to upperbound(board)[1] do if line[1] = "R" then board[lineNum, i] := `if`(board[lineNum, i] = 0, 1, 0); else board[i, lineNum] := `if`(board[i, lineNum] = 0, 1, 0); end if; end do; return NULL; end proc;   printGrid := proc(grid) local r, c; for r to upperbound(board)[1] do for c to upperbound(board)[1] do printf("%a ", grid[r, c]); end do; printf("\n"); end do; printf("\n"); return NULL; end proc;   checkInput := proc(input) try if input[1] = "" then return false, ""; elif not input[1] = "R" and not input[1] = "C" then return false, "Please start with 'r' or 'c'."; elif not type(parse(op(input[2..-1])), posint) then error; elif parse(op(input[2..-1])) < 1 or parse(op(input[2..-1])) > upperbound(board)[1] then return false, "Row or column number too large or too small."; end if; catch: return false, "Please indicate a row or column number." end try; return true, ""; end proc;   ModuleApply := proc(n) local gameOver, toFlip, target, answer, restart; restart := true; while restart do target := gameSetup(n); while ArrayTools[IsEqual](target, board) do target := gameSetup(n); end do; gameOver := false; while not gameOver do printf("The Target:\n"); printGrid(target); printf("The Board:\n"); printGrid(board); if ArrayTools[IsEqual](target, board) then printf("You win!! Press enter to play again or type END to quit.\n\n"); answer := StringTools[UpperCase](readline()); gameOver := true; if answer = "END" then restart := false end if; else toFlip := ["", ""]; while not checkInput(toFlip)[1] and not gameOver do ifelse (not op(checkInput(toFlip)[2..-1]) = "", printf("%s\n\n", op(checkInput(toFlip)[2..-1])), NULL); printf("Please enter a row or column to flip. (ex: r1 or c2) Press enter for a new game or type END to quit.\n\n"); answer := StringTools[UpperCase](readline()); if answer = "END" or answer = "" then gameOver := true; if answer = "END" then restart := false; end if; end if; toFlip := [substring(answer, 1), substring(answer, 2..-1)]; end do; if not gameOver then flip(toFlip); end if; end if; end do; end do; printf("Game Over!\n"); end proc; end module:   FlippingBits(3);
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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
ClearAll[PermuteState] PermuteState[state_, {rc_, n_Integer}] := Module[{s}, s = state; Switch[rc, "R", s[[n]] = 1 - s[[n]], "C", s[[All, n]] = 1 - s[[All, n]] ]; s ] SeedRandom[1337]; n = 3; goalstate = state = RandomChoice[{0, 1}, {n, n}]; While[goalstate == state, permutations = {RandomChoice[{"C", "R"}, 20], RandomInteger[{1, n}, 20]} // Transpose; state = Fold[PermuteState, state, permutations]; ]; i = 0; history = {state}; Grid[goalstate, ItemSize -> {5, 3}, Frame -> True] b1 = Button["", state = PermuteState[state, {"C", #}]; AppendTo[history, state]; i++; If[state === goalstate, MessageDialog["You Won!"]; Print[Grid[#, Frame -> True]] & /@ history]] & /@ Range[n]; b2 = Button["", state = PermuteState[state, {"R", #}]; AppendTo[history, state]; i++; If[state === goalstate, MessageDialog["You Won!"]; Print[Grid[#, Frame -> True]] & /@ history]] & /@ Range[n]; Dynamic[Grid[ Prepend[MapThread[Prepend, {state, b2}], Prepend[b1, Row[{"Flips: ", i}]]], Frame -> True ]]
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.
#jq
jq
def normalize_base($base): def n: if length == 1 and .[0] < $base then .[0] else .[0] % $base, ((.[0] / $base|floor) as $carry |.[1:] | .[0] += $carry | n ) end; n;   def integers_as_arrays_times($n; $base): map(. * $n) | [normalize_base($base)];     def p($L; $n): # @assert($L > 0 and $n > 0) ($L|tostring|explode|reverse|map(. - 48)) as $digits # "0" is 48 | ($digits|length) as $ndigits | (2*(2+($n|log|floor))) as $extra | { m: $n, i: 0, keep: ( 2*(2+$ndigits) + $extra), p: [1] # reverse-array representation of 1 } | until(.m == 0; .i += 1 | .p |= integers_as_arrays_times(2; 10) | .p = .p[ -(.keep) :] | if (.p[-$ndigits:]) == $digits then | .m += -1 | .keep -= ($extra/$n) else . end ) | .i;   ## The task [[12, 1], [12, 2], [123, 45], [123, 12345], [123, 678910]][] | "With L = \(.[0]) and n = \(.[1]), p(L, n) = \( p(.[0]; .[1]))"  
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.
#Julia
Julia
function p(L, n) @assert(L > 0 && n > 0) places, logof2, nfound = trunc(log(10, L)), log(10, 2), 0 for i in 1:typemax(Int) if L == trunc(10^(((i * logof2) % 1) + places)) && (nfound += 1) == n return i end end end   for (L, n) in [(12, 1), (12, 2), (123, 45), (123, 12345), (123, 678910)] println("With L = $L and n = $n, p(L, n) = ", p(L, n)) 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
#Julia
Julia
x, xi = 2.0, 0.5 y, yi = 4.0, 0.25 z, zi = x + y, 1.0 / ( x + y )   multiplier = (n1, n2) -> (m) -> n1 * n2 * m   numlist = [x , y, z] numlisti = [xi, yi, zi]   @show collect(multiplier(n, invn)(0.5) for (n, invn) in zip(numlist, numlisti))
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
#Kotlin
Kotlin
// version 1.1.2   fun multiplier(n1: Double, n2: Double) = { m: Double -> n1 * n2 * m}   fun main(args: Array<String>) { val x = 2.0 val xi = 0.5 val y = 4.0 val yi = 0.25 val z = x + y val zi = 1.0 / ( x + y) val a = doubleArrayOf(x, y, z) val ai = doubleArrayOf(xi, yi, zi) val m = 0.5 for (i in 0 until a.size) { println("${multiplier(a[i], ai[i])(m)} = multiplier(${a[i]}, ${ai[i]})($m)") } }
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
#Nim
Nim
block outer: for i in 0..1000: for j in 0..1000: if i + j == 3: break outer
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
#OCaml
OCaml
exception Found of int   let () = (* search the first number in a list greater than 50 *) try let nums = [36; 23; 44; 51; 28; 63; 17] in List.iter (fun v -> if v > 50 then raise(Found v)) nums; print_endline "nothing found" with Found res -> Printf.printf "found %d\n" res
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.
#Common_Lisp
Common Lisp
;;;using flet to define local functions and storing precalculated column widths in array ;;;verbose, but more readable and efficient than version 2   (defun floydtriangle (rows) (let (column-widths) (setf column-widths (make-array rows :initial-element nil)) (flet ( (lazycat (n) (/ (+ (expt n 2) n 2) 2)) (width (v) (+ 1 (floor (log v 10))))) (dotimes (i rows) (setf (aref column-widths i)(width (+ i (lazycat (- rows 1)))))) (dotimes (row rows) (dotimes (col (+ 1 row)) (format t "~vd " (aref column-widths col)(+ col (lazycat row)))) (format t "~%")))))
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)
#Lua
Lua
function printResult(dist, nxt) print("pair dist path") for i=0, #nxt do for j=0, #nxt do if i ~= j then u = i + 1 v = j + 1 path = string.format("%d -> %d  %2d  %s", u, v, dist[i][j], u) repeat u = nxt[u-1][v-1] path = path .. " -> " .. u until (u == v) print(path) end end end end   function floydWarshall(weights, numVertices) dist = {} for i=0, numVertices-1 do dist[i] = {} for j=0, numVertices-1 do dist[i][j] = math.huge end end   for _,w in pairs(weights) do -- the weights array is one based dist[w[1]-1][w[2]-1] = w[3] end   nxt = {} for i=0, numVertices-1 do nxt[i] = {} for j=0, numVertices-1 do if i ~= j then nxt[i][j] = j+1 end end end   for k=0, numVertices-1 do for i=0, numVertices-1 do for j=0, numVertices-1 do if dist[i][k] + dist[k][j] < dist[i][j] then dist[i][j] = dist[i][k] + dist[k][j] nxt[i][j] = nxt[i][k] end end end end   printResult(dist, nxt) end   weights = { {1, 3, -2}, {2, 1, 4}, {2, 3, 3}, {3, 4, 2}, {4, 2, -1} } numVertices = 4 floydWarshall(weights, numVertices)
http://rosettacode.org/wiki/Function_definition
Function definition
A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract from showing how functions are created and values returned). Related task   Function prototype
#Seed7
Seed7
const func float: multiply (in float: a, in float: b) is return 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
#SenseTalk
SenseTalk
put multiply(3,7) as words   to multiply num1, num2 return num1 * num2 end multiply  
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.)
#Oforth
Oforth
: forwardDiff(l) l right(l size 1 -) l zipWith(#-) ; : forwardDiffN(n, l) l #[ forwardDiff dup println ] times(n) ;
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.)
#PARI.2FGP
PARI/GP
fd(v)=vector(#v-1,i,v[i+1]-v[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.
#Run_BASIC
Run BASIC
print right$("00000";using("#####.##",7.125),8) ' => 00007.13
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.
#Rust
Rust
  fn main() { let x = 7.125;   println!("{:9}", x); println!("{:09}", x); println!("{:9}", -x); println!("{:09}", -x); }  
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).
#Phix
Phix
with javascript_semantics function xor_gate(bool a, bool b) return (a and not b) or (not a and b) end function function half_adder(bool a, bool b) bool s = xor_gate(a,b), c = a and b return {s,c} end function function full_adder(bool a, bool b, bool c) bool {s1,c1} = half_adder(c,a), {s2,c2} = half_adder(s1,b) c = c1 or c2 return {s2,c} end function function four_bit_adder(bool a0, a1, a2, a3, b0, b1, b2, b3) bool s0,s1,s2,s3,c {s0,c} = full_adder(a0,b0,0) {s1,c} = full_adder(a1,b1,c) {s2,c} = full_adder(a2,b2,c) {s3,c} = full_adder(a3,b3,c) return {s3,s2,s1,s0,c} end function procedure test(integer a, integer b) bool {a0,a1,a2,a3} = int_to_bits(a,4), {b0,b1,b2,b3} = int_to_bits(b,4), {r3,r2,r1,r0,c} = four_bit_adder(a0,a1,a2,a3,b0,b1,b2,b3) integer r = bits_to_int({r0,r1,r2,r3}) string s = iff(c?sprintf(" [=%d+16]",r):"") printf(1,"%04b + %04b = %04b %b (%d+%d=%d%s)\n",{a,b,r,c,a,b,c*16+r,s}) end procedure test(0,0) test(0,1) test(0b1111,0b1111) test(3,7) test(11,8) test(0b1100,0b1100) test(0b1100,0b1101) test(0b1100,0b1110) test(0b1100,0b1111) test(0b1101,0b0000) test(0b1101,0b0001) test(0b1101,0b0010) test(0b1101,0b0011)
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.
#Factor
Factor
USING: combinators combinators.smart kernel math math.statistics prettyprint sequences sorting ; IN: rosetta-code.five-number   <PRIVATE   : bisect ( seq -- lower upper ) dup length even? [ halves ] [ dup midpoint@ 1 + [ head ] [ tail* ] 2bi ] if ;   : (fivenum) ( seq -- summary ) natural-sort { [ infimum ] [ bisect drop median ] [ median ] [ bisect nip median ] [ supremum ] } cleave>array ;   PRIVATE>   ERROR: fivenum-empty data ; ERROR: fivenum-nan data ;   : fivenum ( seq -- summary ) { { [ dup empty? ] [ fivenum-empty ] } { [ dup [ fp-nan? ] any? ] [ fivenum-nan ] } [ (fivenum) ] } cond ;   : fivenum-demo ( -- ) { 15 6 42 41 7 36 49 40 39 47 43 } { 36 40 7 39 41 15 } { 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 } [ fivenum . ] tri@ ;   MAIN: fivenum-demo
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.
#Go
Go
package main   import ( "fmt" "math" "sort" )   func fivenum(a []float64) (n5 [5]float64) { sort.Float64s(a) n := float64(len(a)) n4 := float64((len(a)+3)/2) / 2 d := []float64{1, n4, (n + 1) / 2, n + 1 - n4, n} for e, de := range d { floor := int(de - 1) ceil := int(math.Ceil(de - 1)) n5[e] = .5 * (a[floor] + a[ceil]) } return }   var ( x1 = []float64{36, 40, 7, 39, 41, 15} x2 = []float64{15, 6, 42, 41, 7, 36, 49, 40, 39, 47, 43} x3 = []float64{ 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, } )   func main() { fmt.Println(fivenum(x1)) fmt.Println(fivenum(x2)) fmt.Println(fivenum(x3)) }
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)
#8080_Assembly
8080 Assembly
PRMLEN: equ 4 ; length of permutation string puts: equ 9 ; CP/M print string org 100h lxi d,perms ; Start with first permutation perm: lxi h,mperm ; Missing permutation mvi b,PRMLEN ; Length of permutation char: ldax d ; Load character ora a ; Done? jz done xra m ; If not, XOR into missing permutation mov m,a inx h ; Increment pointers inx d dcr b ; Next character of current permutation jnz char jmp perm ; Next permutation done: lxi d,msg ; Print the message and exit mvi c,puts jmp 5 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' db 0 ; end marker