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/Fixed_length_records
Fixed length records
Fixed length read/write Before terminals, computers commonly used punch card readers or paper tape input. A common format before these devices were superseded by terminal technology was based on the Hollerith code, Hollerith code. These input devices handled 80 columns per card and had a limited character set, encoded by punching holes in one or more rows of the card for each column. These devices assumed/demanded a fixed line width of 80 characters, newlines were not required (and could not even be encoded in some systems). Task Write a program to read 80 column fixed length records (no newline terminators (but newline characters allowed in the data)) and then write out the reverse of each line as fixed length 80 column records. Samples here use printable characters, but that is not a given with fixed length data. Filenames used are sample.txt, infile.dat, outfile.dat. Note: There are no newlines, inputs and outputs are fixed at 80 columns, no more, no less, space padded. Fixed length data is 8 bit complete. NUL bytes of zero are allowed. These fixed length formats are still in wide use on mainframes, with JCL and with COBOL (which commonly use EBCDIC encoding and not ASCII). Most of the large players in day to day financial transactions know all about fixed length records and the expression logical record length. Sample data To create the sample input file, use an editor that supports fixed length records or use a conversion utility. For instance, most GNU/Linux versions of dd support blocking and unblocking records with a conversion byte size. Line 1...1.........2.........3.........4.........5.........6.........7.........8 Line 2 Line 3 Line 4 Line 6 Line 7 Indented line 8............................................................ Line 9 RT MARGIN prompt$ dd if=sample.txt of=infile.dat cbs=80 conv=block prompt$ dd if=infile.dat cbs=80 conv=unblock Bonus round Forth systems often include BLOCK words. A block is 1024 bytes. Source code is stored as 16 lines of 64 characters each (again, no newline character or sequence to mark the end of a line). Write a program to convert a block file to text (using newlines). Trailing spaces should be excluded from the output. Also demonstrate how to convert from a normal text file to block form. All lines either truncated or padded to 64 characters with no newline terminators. The last block filled to be exactly 1024 characters by adding blanks if needed. Assume a full range of 8 bit byte values for each character. The COBOL example uses forth.txt and forth.blk filenames.
#Ruby
Ruby
open("outfile.dat", "w") do |out_f| open("infile.dat") do |in_f| while record = in_f.read(80) out_f << record.reverse end end end # both files automatically closed  
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)
#Fortran
Fortran
module floyd_warshall_algorithm   use, intrinsic :: ieee_arithmetic   implicit none   integer, parameter :: floating_point_kind = & & ieee_selected_real_kind (6, 37) integer, parameter :: fpk = floating_point_kind   integer, parameter :: nil_vertex = 0   type :: edge integer :: u real(kind = fpk) :: weight integer :: v end type edge   type :: edge_list type(edge), allocatable :: element(:) end type edge_list   contains   subroutine make_example_graph (edges) type(edge_list), intent(out) :: edges   allocate (edges%element(1:5)) edges%element(1) = edge (1, -2.0, 3) edges%element(2) = edge (3, +2.0, 4) edges%element(3) = edge (4, -1.0, 2) edges%element(4) = edge (2, +4.0, 1) edges%element(5) = edge (2, +3.0, 3) end subroutine make_example_graph   function find_max_vertex (edges) result (n) type(edge_list), intent(in) :: edges integer n   integer i   n = 1 do i = lbound (edges%element, 1), ubound (edges%element, 1) n = max (n, edges%element(i)%u) n = max (n, edges%element(i)%v) end do end function find_max_vertex   subroutine floyd_warshall (edges, max_vertex, distance, next_vertex)   type(edge_list), intent(in) :: edges integer, intent(out) :: max_vertex real(kind = fpk), allocatable, intent(out) :: distance(:,:) integer, allocatable, intent(out) :: next_vertex(:,:)   integer :: n integer :: i, j, k integer :: u, v real(kind = fpk) :: dist_ikj real(kind = fpk) :: infinity   n = find_max_vertex (edges) max_vertex = n   allocate (distance(1:n, 1:n)) allocate (next_vertex(1:n, 1:n))   infinity = ieee_value (1.0_fpk, ieee_positive_inf)   ! Initialize.   do i = 1, n do j = 1, n distance(i, j) = infinity next_vertex (i, j) = nil_vertex end do end do do i = lbound (edges%element, 1), ubound (edges%element, 1) u = edges%element(i)%u v = edges%element(i)%v distance(u, v) = edges%element(i)%weight next_vertex(u, v) = v end do do i = 1, n distance(i, i) = 0.0_fpk ! Distance from a vertex to itself. next_vertex(i, i) = i end do   ! Perform the algorithm.   do k = 1, n do i = 1, n do j = 1, n dist_ikj = distance(i, k) + distance(k, j) if (dist_ikj < distance(i, j)) then distance(i, j) = dist_ikj next_vertex(i, j) = next_vertex(i, k) end if end do end do end do   end subroutine floyd_warshall   subroutine print_path (next_vertex, u, v) integer, intent(in) :: next_vertex(:,:) integer, intent(in) :: u, v   integer i   if (next_vertex(u, v) /= nil_vertex) then i = u write (*, '(I0)', advance = 'no') i do while (i /= v) i = next_vertex(i, v) write (*, '('' -> '', I0)', advance = 'no') i end do end if end subroutine print_path   end module floyd_warshall_algorithm   program floyd_warshall_task   use, non_intrinsic :: floyd_warshall_algorithm   implicit none   type(edge_list) :: example_graph integer :: max_vertex real(kind = fpk), allocatable :: distance(:,:) integer, allocatable :: next_vertex(:,:) integer :: u, v   call make_example_graph (example_graph) call floyd_warshall (example_graph, max_vertex, distance, & & next_vertex)   1000 format (1X, I0, ' -> ', I0, 5X, F4.1, 6X)   write (*, '('' pair distance path'')') write (*, '(''---------------------------------------'')') do u = 1, max_vertex do v = 1, max_vertex if (u /= v) then write (*, 1000, advance = 'no') u, v, distance(u, v) call print_path (next_vertex, u, v) write (*, '()', advance = 'yes') end if end do end do   end program floyd_warshall_task
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
#PureBasic
PureBasic
Procedure multiply(a,b) ProcedureReturn a*b EndProcedure
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.)
#JavaScript
JavaScript
(() => { 'use strict';   // forwardDifference :: Num a => [a] -> [a] const forwardDifference = xs => zipWith(subtract)(xs)(tail(xs));     // nthForwardDifference :: Num a => [a] -> Int -> [a] const nthForwardDifference = xs => index(iterate(forwardDifference)(xs)).Just;     //----------------------- TEST ------------------------ // main :: IO () const main = () => unlines( take(10)( iterate(forwardDifference)( [90, 47, 58, 29, 22, 32, 55, 5, 55, 73] ) ).map((x, i) => justifyRight(2)('x')(i) + ( ' -> ' ) + JSON.stringify(x)) );     //----------------- GENERIC FUNCTIONS -----------------   // Just :: a -> Maybe a const Just = x => ({ type: 'Maybe', Nothing: false, Just: x });     // Nothing :: Maybe a const Nothing = () => ({ type: 'Maybe', Nothing: true, });     // Tuple (,) :: a -> b -> (a, b) const Tuple = a => b => ({ type: 'Tuple', '0': a, '1': b, length: 2 });     // index (!!) :: [a] -> Int -> Maybe a // index (!!) :: Generator (Int, a) -> Int -> Maybe a // index (!!) :: String -> Int -> Maybe Char const index = xs => i => { const s = xs.constructor.constructor.name; return 'GeneratorFunction' !== s ? (() => { const v = xs[i]; return undefined !== v ? Just(v) : Nothing(); })() : Just(take(i)(xs), xs.next().value); };     // iterate :: (a -> a) -> a -> Gen [a] const iterate = f => function*(x) { let v = x; while (true) { yield(v); v = f(v); } };   // justifyRight :: Int -> Char -> String -> String const justifyRight = n => // The string s, preceded by enough padding (with // the character c) to reach the string length n. c => s => n > s.length ? ( s.padStart(n, c) ) : s;   // length :: [a] -> Int const length = xs => // Returns Infinity over objects without finite // length. This enables zip and zipWith to choose // the shorter argument when one is non-finite, // like cycle, repeat etc (Array.isArray(xs) || 'string' === typeof xs) ? ( xs.length ) : Infinity;     // map :: (a -> b) -> [a] -> [b] const map = f => // The list obtained by applying f // to each element of xs. // (The image of xs under f). xs => ( Array.isArray(xs) ? ( xs ) : xs.split('') ).map(f);     // subtract :: Num -> Num -> Num const subtract = x => y => y - x;     // tail :: [a] -> [a] const tail = xs => // A new list consisting of all // items of xs except the first. 0 < xs.length ? xs.slice(1) : [];     // take :: Int -> [a] -> [a] // take :: Int -> String -> String const take = n => // The first n elements of a list, // string of characters, or stream. xs => 'GeneratorFunction' !== xs .constructor.constructor.name ? ( xs.slice(0, n) ) : [].concat.apply([], Array.from({ length: n }, () => { const x = xs.next(); return x.done ? [] : [x.value]; }));     // unlines :: [String] -> String const unlines = xs => // A single string formed by the intercalation // of a list of strings with the newline character. xs.join('\n');     // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] const zipWith = f => xs => ys => { const lng = Math.min(length(xs), length(ys)), [as, bs] = [xs, ys].map(take(lng)); return Array.from({ length: lng }, (_, i) => f(as[i])( bs[i] )); };   // MAIN --- return main(); })();
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
#X86-64_Assembly
X86-64 Assembly
  option casemap:none if @Platform eq 1 option dllimport:<kernel32> ExitProcess proto :dword option dllimport:none exit equ ExitProcess endif printf proto :qword, :vararg exit proto :dword   .code main proc invoke printf, CSTR("Goodbye, World!",10) invoke exit, 0 ret main endp end  
http://rosettacode.org/wiki/Formatted_numeric_output
Formatted numeric output
Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
#OCaml
OCaml
Printf.printf "%09.3f\n" 7.125
http://rosettacode.org/wiki/Formatted_numeric_output
Formatted numeric output
Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
#OpenEdge.2FProgress
OpenEdge/Progress
MESSAGE STRING( 7.125, "99999.999" ) VIEW-AS ALERT-BOX.
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).
#LabVIEW
LabVIEW
  {def xor {lambda {:a :b} {or {and :a {not :b}} {and :b {not :a}}}}} -> xor   {def halfAdder {lambda {:a :b} {cons {and :a :b} {xor :a :b}}}} -> halfAdder   {def fullAdder {lambda {:a :b :c} {let { {:b :b} {:ha1 {halfAdder :c :a}} } {let { {:ha1 :ha1} {:ha2 {halfAdder {cdr :ha1} :b}} } {cons {or {car :ha1} {car :ha2}} {cdr :ha2}} }}}} -> fullAdder   {def 4bitsAdder {lambda {:a4 :a3 :a2 :a1 :b4 :b3 :b2 :b1} {let { {:a4 :a4} {:a3 :a3} {:a2 :a2} {:b4 :b4} {:b3 :b3} {:b2 :b2} {:fa1 {fullAdder :a1 :b1 false}} } {let { {:a4 :a4} {:a3 :a3} {:b4 :b4} {:b3 :b3} {:fa1 :fa1} {:fa2 {fullAdder :a2 :b2 {car :fa1}}} } {let { {:a4 :a4} {:b4 :b4} {:fa1 :fa1} {:fa2 :fa2} {:fa3 {fullAdder :a3 :b3 {car :fa2}}} } {let { {:fa1 :fa1} {:fa2 :fa2} {:fa3 :fa3} {:fa4 {fullAdder :a4 :b4 {car :fa3}}} } {car :fa4} {cdr :fa4} {cdr :fa3} {cdr :fa2} {cdr :fa1}}}}}}} -> 4bitsAdder   {def bin2bool {lambda {:b} {if {W.empty? {W.rest :b}} then {= {W.first :b} 1} else {= {W.first :b} 1} {bin2bool {W.rest :b}}}}} -> bin2bool   {def bool2bin {lambda {:b} {if {S.empty? {S.rest :b}} then {if {S.first :b} then 1 else 0} else {if {S.first :b} then 1 else 0}{bool2bin {S.rest :b}}}}} -> bool2bin   {def bin2dec {def bin2dec.r {lambda {:p :r} {if {A.empty? :p} then :r else {bin2dec.r {A.rest :p} {+ {A.first :p} {* 2 :r}}}}}} {lambda {:p} {bin2dec.r {A.split :p} 0}}} -> bin2dec   {def add {def numbers 0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 1011 1100 1101 1110 1111} {lambda {:a :b} {bin2dec {bool2bin {4bitsAdder {bin2bool {S.get :a {numbers}}} {bin2bool {S.get :b {numbers}}}}}}}} -> add   {table {S.map {lambda {:i} {tr {S.map {{lambda {:i :j} {td {add :i :j}}} :i} {S.serie 0 15}}}} {S.serie 0 15}} } -> 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30  
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.
#C.23
C#
using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Threading; using System.Windows.Forms;   namespace ForestFire { class Program : Form { private static readonly Random rand = new Random(); private Bitmap img;   public Program(int w, int h, int f, int p) { Size = new Size(w, h); StartPosition = FormStartPosition.CenterScreen;   Thread t = new Thread(() => fire(f, p)); t.Start();   FormClosing += (object sender, FormClosingEventArgs e) => { t.Abort(); t = null; }; }   private void fire(int f, int p) { int clientWidth = ClientRectangle.Width; int clientHeight = ClientRectangle.Height; int cellSize = 10;   img = new Bitmap(clientWidth, clientHeight); Graphics g = Graphics.FromImage(img);   CellState[,] state = InitializeForestFire(clientWidth, clientHeight);   uint generation = 0;   do { g.FillRectangle(Brushes.White, 0, 0, img.Width, img.Height); state = StepForestFire(state, f, p);   for (int y = 0; y < clientHeight - cellSize; y += cellSize) { for (int x = 0; x < clientWidth - cellSize; x += cellSize) { switch (state[y, x]) { case CellState.Empty: break; case CellState.Tree: g.FillRectangle(Brushes.DarkGreen, x, y, cellSize, cellSize); break; case CellState.Burning: g.FillRectangle(Brushes.DarkRed, x, y, cellSize, cellSize); break; } } }   Thread.Sleep(500);   Invoke((MethodInvoker)Refresh);   } while (generation < uint.MaxValue);   g.Dispose(); }   private CellState[,] InitializeForestFire(int width, int height) { // Create our state array, initialize all indices as Empty, and return it. var state = new CellState[height, width]; state.Initialize(); return state; }   private enum CellState : byte { Empty = 0, Tree = 1, Burning = 2 }   private CellState[,] StepForestFire(CellState[,] state, int f, int p) { /* Clone our old state, so we can write to our new state * without changing any values in the old state. */ var newState = (CellState[,])state.Clone();   int numRows = state.GetLength(0); int numCols = state.GetLength(1);   for (int r = 1; r < numRows - 1; r++) { for (int c = 1; c < numCols - 1; c++) { /* * Check the current cell. * * If it's empty, give it a 1/p chance of becoming a tree. * * If it's a tree, check to see if any neighbors are burning. * If so, set the cell's state to burning, otherwise give it * a 1/f chance of combusting. * * If it's burning, set it to empty. */ switch (state[r, c]) { case CellState.Empty: if (rand.Next(0, p) == 0) newState[r, c] = CellState.Tree; break;   case CellState.Tree: if (NeighborHasState(state, r, c, CellState.Burning) || rand.Next(0, f) == 0) newState[r, c] = CellState.Burning; break;   case CellState.Burning: newState[r, c] = CellState.Empty; break; } } }   return newState; }   private bool NeighborHasState(CellState[,] state, int x, int y, CellState value) { // Check each cell within a 1 cell radius for the specified value. for (int r = -1; r <= 1; r++) { for (int c = -1; c <= 1; c++) { if (r == 0 && c == 0) continue;   if (state[x + r, y + c] == value) return true; } }   return false; }   protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); e.Graphics.DrawImage(img, 0, 0); }   [STAThread] static void Main(string[] args) { Application.Run(new Program(w: 500, h: 500, f: 2, p: 5)); } } }
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
#AutoHotkey
AutoHotkey
list := object(1, object(1, 1), 2, 2, 3, object(1, object(1, 3, 2, 4) , 2, 5), 4, object(1, object(1, object(1, object()))), 5 , object(1, object(1, 6)), 6, 7, 7, 8, 9, object()) msgbox % objPrint(list) ; (( 1 ) 2 (( 3 4 ) 5 )(((())))(( 6 )) 7 8 ()) msgbox % objPrint(objFlatten(list)) ; ( 1 2 3 4 5 6 7 8 ) return   !r::reload !q::exitapp   objPrint(ast, reserved=0) { if !isobject(ast) return " " ast " "   if !reserved reserved := object("seen" . &ast, 1) ; to keep track of unique objects within top object   enum := ast._newenum() while enum[key, value] { if reserved["seen" . &value] continue ; don't copy repeat objects (circular references) ; string .= key . ": " . objPrint(value, reserved) string .= objPrint(value, reserved) } return "(" string ")" }     objFlatten(ast) { if !isobject(ast) return ast   flat := object() ; flat object   enum := ast._newenum() while enum[key, value] { if !isobject(value) flat._Insert(value) else { next := objFlatten(value) loop % next._MaxIndex() flat._Insert(next[A_Index])   } } return flat }
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.
#D
D
import std.stdio, std.random, std.ascii, std.string, std.range, std.algorithm, std.conv;   enum N = 3; // Board side. static assert(N <= lowercase.length); enum columnIDs = lowercase[0 .. N]; alias Board = ubyte[N][N];   void flipBits(ref Board board, in size_t count=1) { foreach (immutable _; 0 .. count) board[uniform(0, $)][uniform(0, $)] ^= 1; }   void notRow(ref Board board, in size_t i) pure nothrow { board[i][] ^= 1; }   void notColumn(ref Board board, in size_t i) pure nothrow { foreach (ref row; board) row[i] ^= 1; }   Board generateGameBoard(in ref Board target) { // board is generated with many flips, to keep parity unchanged. Board board = target; while (board == target) foreach (immutable _; 0 .. 2 * N) [&notRow, &notColumn][uniform(0, 2)](board, uniform(0, N)); return board; }   void show(in ref Board board, in string comment) { comment.writeln; writefln("  %-(%c %)", columnIDs); foreach (immutable j, const row; board) writefln("  %2d %-(%d %)", j + 1, row); }   void main() { "T prints the target, and Q exits.\n".writeln; // Create target and flip some of its bits randomly. Board target; flipBits(target, uniform(0, N) + 1); show(target, "Target configuration is:");   auto board = generateGameBoard(target); immutable prompt = format(" 1-%d / %s-%s to flip, or T, Q: ", N, columnIDs[0], columnIDs.back); uint move = 1; while (board != target) { show(board, format("\nMove %d:", move)); prompt.write; immutable ans = readln.strip;   if (ans.length == 1 && columnIDs.canFind(ans)) { board.notColumn(columnIDs.countUntil(ans)); move++; } else if (iota(1, N + 1).map!text.canFind(ans)) { board.notRow(ans.to!uint - 1); move++; } else if (ans == "T") { show(target, "Target configuration is:"); } else if (ans == "Q") { return "Game stopped.".writeln; } else writefln(" Wrong input '%s'. Try again.\n", ans.take(9)); }   "\nWell done!".writeln; }
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.
#ALGOL_68
ALGOL 68
# find values of p( L, n ) where p( L, n ) is the nth-smallest j such that # # the decimal representation of 2^j starts with the digits of L # BEGIN # returns a string representation of n with commas # PROC commatise = ( LONG INT n )STRING: BEGIN STRING result := ""; STRING unformatted = whole( n, 0 ); INT ch count := 0; FOR c FROM UPB unformatted BY -1 TO LWB unformatted DO IF ch count <= 2 THEN ch count +:= 1 ELSE ch count := 1; "," +=: result FI; unformatted[ c ] +=: result OD; result END # commatise # ; # returns p( prefix, occurance ) # PROC p = ( INT prefix, INT occurance )LONG INT: BEGIN LONG INT quarter long max int = long max int OVER 4; LONG INT p2 := 1; INT count := 0; INT power := 0; WHILE count < occurance DO power +:= 1; p2 +:= p2; LONG INT pre := p2; WHILE pre > prefix DO pre OVERAB 10 OD; IF pre = prefix THEN count +:= 1 FI; IF p2 > quarter long max int THEN p2 OVERAB 10 000 FI OD; power END # p # ; # prints p( prefix, occurance ) # PROC print p = ( INT prefix, INT occurance )VOID: print( ( "p(", whole( prefix, 0 ), ", ", whole( occurance, 0 ), ") = ", commatise( p( prefix, occurance ) ), newline ) ); # task test cases # print p( 12, 1 ); print p( 12, 2 ); print p( 123, 45 ); print p( 123, 12345 ); print p( 123, 678910 ) 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
#Axiom
Axiom
(x,xi,y,yi) := (2.0,0.5,4.0,0.25) (z,zi) := (x+y,1/(x+y)) (numbers,invers) := ([x,y,z],[xi,yi,zi]) multiplier(a:Float,b:Float):(Float->Float) == (m +-> a*b*m) [multiplier(number,inver) 0.5 for number in numbers for inver in invers]  
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
#BBC_BASIC
BBC BASIC
REM Create some numeric variables: x = 2 : xi = 1/2 y = 4 : yi = 0.25 z = x + y : zi = 1 / (x + y)   REM Create the collections (here structures are used): DIM c{x, y, z} DIM ci{x, y, z} c.x = x : c.y = y : c.z = z ci.x = xi : ci.y = yi : ci.z = zi   REM Create some multiplier functions: multx = FNmultiplier(c.x, ci.x) multy = FNmultiplier(c.y, ci.y) multz = FNmultiplier(c.z, ci.z)   REM Test applying the compositions: x = 1.234567 : PRINT x " ", FN(multx)(x) x = 2.345678 : PRINT x " ", FN(multy)(x) x = 3.456789 : PRINT x " ", FN(multz)(x) END   DEF FNmultiplier(n1,n2) LOCAL f$, p% f$ = "(m)=" + STR$n1 + "*" + STR$n2 + "*m" DIM p% LEN(f$) + 4 $(p%+4) = f$ : !p% = p%+4 = p%
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
#Fortran
Fortran
... ASSIGN 1101 to WHENCE !Remember my return point. GO TO 1000 !Dive into a "subroutine" 1101 CONTINUE !Resume. ... ASSIGN 1102 to WHENCE !Prepare for another invocation. GO TO 1000 !Like GOSUB in BASIC. 1102 CONTINUE !Carry on. ... Common code, far away. 1000 do something !This has all the context available. GO TO WHENCE !Return whence I came.
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
#FreeBASIC
FreeBASIC
  '$lang: "qb"   Gosub subrutina   bucle: Print "Bucle infinito" Goto bucle End   subrutina: Print "En subrutina" Sleep 100 Return Sleep  
http://rosettacode.org/wiki/Four_is_magic
Four is magic
Task Write a subroutine, function, whatever it may be called in your language, that takes an integer number and returns an English text sequence starting with the English cardinal representation of that integer, the word 'is' and then the English cardinal representation of the count of characters that made up the first word, followed by a comma. Continue the sequence by using the previous count word as the first word of the next phrase, append 'is' and the cardinal count of the letters in that word. Continue until you reach four. Since four has four characters, finish by adding the words 'four is magic' and a period. All integers will eventually wind up at four. For instance, suppose your are given the integer 3. Convert 3 to Three, add is , then the cardinal character count of three, or five, with a comma to separate if from the next phrase. Continue the sequence five is four, (five has four letters), and finally, four is magic. Three is five, five is four, four is magic. For reference, here are outputs for 0 through 9. Zero is four, four is magic. One is three, three is five, five is four, four is magic. Two is three, three is five, five is four, four is magic. Three is five, five is four, four is magic. Four is magic. Five is four, four is magic. Six is three, three is five, five is four, four is magic. Seven is five, five is four, four is magic. Eight is five, five is four, four is magic. Nine is four, four is magic. Some task guidelines You may assume the input will only contain integer numbers. Cardinal numbers between 20 and 100 may use either hyphens or spaces as word separators but they must use a word separator. (23 is twenty three or twenty-three not twentythree.) Cardinal number conversions should follow the English short scale. (billion is 1e9, trillion is 1e12, etc.) Cardinal numbers should not include commas. (20140 is twenty thousand one hundred forty not twenty thousand, one hundred forty.) When converted to a string, 100 should be one hundred, not a hundred or hundred, 1000 should be one thousand, not a thousand or thousand. When converted to a string, there should be no and in the cardinal string. 130 should be one hundred thirty not one hundred and thirty. When counting characters, count all of the characters in the cardinal number including spaces and hyphens. One hundred fifty-one should be 21 not 18. The output should follow the format "N is K, K is M, M is ... four is magic." (unless the input is 4, in which case the output should simply be "four is magic.") The output can either be the return value from the function, or be displayed from within the function. You are encouraged, though not mandated to use proper sentence capitalization. You may optionally support negative numbers. -7 is negative seven. Show the output here for a small representative sample of values, at least 5 but no more than 25. You are free to choose which which numbers to use for output demonstration. You can choose to use a library, (module, external routine, whatever) to do the cardinal conversions as long as the code is easily and freely available to the public. If you roll your own, make the routine accept at minimum any integer from 0 up to 999999. If you use a pre-made library, support at least up to unsigned 64 bit integers. (or the largest integer supported in your language if it is less.) Four is magic is a popular code-golf task. This is not code golf. Write legible, idiomatic and well formatted code. Related tasks   Four is the number of_letters in the ...   Look-and-say sequence   Number names   Self-describing numbers   Summarize and say sequence   Spelling of ordinal numbers   De Bruijn sequences
#Raku
Raku
use Lingua::EN::Numbers; # Version 2.4.0 or higher   sub card ($n) { cardinal($n).subst(/','/, '', :g) }   sub magic (Int $int is copy) { my $string; loop { $string ~= "{ card($int) } is "; if $int = ($int == 4) ?? 0 !! card($int).chars { $string ~= "{ card($int) }, " } else { $string ~= "magic.\n"; last } } $string.tc }   .&magic.say for 0, 4, 6, 11, 13, 75, 337, -164, 9876543209, 2**256;
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.
#AutoHotkey
AutoHotkey
Floyds_triangle(row){ i = 0 loop %row% { n := A_Index loop, %n% { m := n, j := i, i++ while (m<row) j += m , m++ res .= spaces(StrLen(j+1)-StrLen(i) +(A_Index=1?0:1)) i } if (A_Index < row) res .= "`r`n" } return res } Spaces(no){ loop, % no res.=" " return % res }
http://rosettacode.org/wiki/Fixed_length_records
Fixed length records
Fixed length read/write Before terminals, computers commonly used punch card readers or paper tape input. A common format before these devices were superseded by terminal technology was based on the Hollerith code, Hollerith code. These input devices handled 80 columns per card and had a limited character set, encoded by punching holes in one or more rows of the card for each column. These devices assumed/demanded a fixed line width of 80 characters, newlines were not required (and could not even be encoded in some systems). Task Write a program to read 80 column fixed length records (no newline terminators (but newline characters allowed in the data)) and then write out the reverse of each line as fixed length 80 column records. Samples here use printable characters, but that is not a given with fixed length data. Filenames used are sample.txt, infile.dat, outfile.dat. Note: There are no newlines, inputs and outputs are fixed at 80 columns, no more, no less, space padded. Fixed length data is 8 bit complete. NUL bytes of zero are allowed. These fixed length formats are still in wide use on mainframes, with JCL and with COBOL (which commonly use EBCDIC encoding and not ASCII). Most of the large players in day to day financial transactions know all about fixed length records and the expression logical record length. Sample data To create the sample input file, use an editor that supports fixed length records or use a conversion utility. For instance, most GNU/Linux versions of dd support blocking and unblocking records with a conversion byte size. Line 1...1.........2.........3.........4.........5.........6.........7.........8 Line 2 Line 3 Line 4 Line 6 Line 7 Indented line 8............................................................ Line 9 RT MARGIN prompt$ dd if=sample.txt of=infile.dat cbs=80 conv=block prompt$ dd if=infile.dat cbs=80 conv=unblock Bonus round Forth systems often include BLOCK words. A block is 1024 bytes. Source code is stored as 16 lines of 64 characters each (again, no newline character or sequence to mark the end of a line). Write a program to convert a block file to text (using newlines). Trailing spaces should be excluded from the output. Also demonstrate how to convert from a normal text file to block form. All lines either truncated or padded to 64 characters with no newline terminators. The last block filled to be exactly 1024 characters by adding blanks if needed. Assume a full range of 8 bit byte values for each character. The COBOL example uses forth.txt and forth.blk filenames.
#Rust
Rust
use std::fs::File; use std::io::prelude::*; use std::io::{BufReader, BufWriter};   fn reverse_file( input_filename: &str, output_filename: &str, record_len: usize, ) -> std::io::Result<()> { let mut input = BufReader::new(File::open(input_filename)?); let mut output = BufWriter::new(File::create(output_filename)?); let mut buffer = vec![0; record_len]; while input.read(&mut buffer)? == record_len { buffer.reverse(); output.write_all(&buffer)?; } output.flush()?; Ok(()) }   fn main() { match reverse_file("infile.dat", "outfile.dat", 80) { Ok(()) => {} Err(error) => eprintln!("I/O error: {}", error), } }
http://rosettacode.org/wiki/Fixed_length_records
Fixed length records
Fixed length read/write Before terminals, computers commonly used punch card readers or paper tape input. A common format before these devices were superseded by terminal technology was based on the Hollerith code, Hollerith code. These input devices handled 80 columns per card and had a limited character set, encoded by punching holes in one or more rows of the card for each column. These devices assumed/demanded a fixed line width of 80 characters, newlines were not required (and could not even be encoded in some systems). Task Write a program to read 80 column fixed length records (no newline terminators (but newline characters allowed in the data)) and then write out the reverse of each line as fixed length 80 column records. Samples here use printable characters, but that is not a given with fixed length data. Filenames used are sample.txt, infile.dat, outfile.dat. Note: There are no newlines, inputs and outputs are fixed at 80 columns, no more, no less, space padded. Fixed length data is 8 bit complete. NUL bytes of zero are allowed. These fixed length formats are still in wide use on mainframes, with JCL and with COBOL (which commonly use EBCDIC encoding and not ASCII). Most of the large players in day to day financial transactions know all about fixed length records and the expression logical record length. Sample data To create the sample input file, use an editor that supports fixed length records or use a conversion utility. For instance, most GNU/Linux versions of dd support blocking and unblocking records with a conversion byte size. Line 1...1.........2.........3.........4.........5.........6.........7.........8 Line 2 Line 3 Line 4 Line 6 Line 7 Indented line 8............................................................ Line 9 RT MARGIN prompt$ dd if=sample.txt of=infile.dat cbs=80 conv=block prompt$ dd if=infile.dat cbs=80 conv=unblock Bonus round Forth systems often include BLOCK words. A block is 1024 bytes. Source code is stored as 16 lines of 64 characters each (again, no newline character or sequence to mark the end of a line). Write a program to convert a block file to text (using newlines). Trailing spaces should be excluded from the output. Also demonstrate how to convert from a normal text file to block form. All lines either truncated or padded to 64 characters with no newline terminators. The last block filled to be exactly 1024 characters by adding blanks if needed. Assume a full range of 8 bit byte values for each character. The COBOL example uses forth.txt and forth.blk filenames.
#Tcl
Tcl
chan configure stdin -translation binary chan configure stdout -translation binary   set lines [regexp -inline -all {.{80}} [read stdin]] puts -nonewline [join [lmap line $lines {string reverse $line}] ""]   # More "traditional" way   # while {[set line [read stdin 80]] ne ""} { # puts -nonewline [string reverse $line] # }
http://rosettacode.org/wiki/Fixed_length_records
Fixed length records
Fixed length read/write Before terminals, computers commonly used punch card readers or paper tape input. A common format before these devices were superseded by terminal technology was based on the Hollerith code, Hollerith code. These input devices handled 80 columns per card and had a limited character set, encoded by punching holes in one or more rows of the card for each column. These devices assumed/demanded a fixed line width of 80 characters, newlines were not required (and could not even be encoded in some systems). Task Write a program to read 80 column fixed length records (no newline terminators (but newline characters allowed in the data)) and then write out the reverse of each line as fixed length 80 column records. Samples here use printable characters, but that is not a given with fixed length data. Filenames used are sample.txt, infile.dat, outfile.dat. Note: There are no newlines, inputs and outputs are fixed at 80 columns, no more, no less, space padded. Fixed length data is 8 bit complete. NUL bytes of zero are allowed. These fixed length formats are still in wide use on mainframes, with JCL and with COBOL (which commonly use EBCDIC encoding and not ASCII). Most of the large players in day to day financial transactions know all about fixed length records and the expression logical record length. Sample data To create the sample input file, use an editor that supports fixed length records or use a conversion utility. For instance, most GNU/Linux versions of dd support blocking and unblocking records with a conversion byte size. Line 1...1.........2.........3.........4.........5.........6.........7.........8 Line 2 Line 3 Line 4 Line 6 Line 7 Indented line 8............................................................ Line 9 RT MARGIN prompt$ dd if=sample.txt of=infile.dat cbs=80 conv=block prompt$ dd if=infile.dat cbs=80 conv=unblock Bonus round Forth systems often include BLOCK words. A block is 1024 bytes. Source code is stored as 16 lines of 64 characters each (again, no newline character or sequence to mark the end of a line). Write a program to convert a block file to text (using newlines). Trailing spaces should be excluded from the output. Also demonstrate how to convert from a normal text file to block form. All lines either truncated or padded to 64 characters with no newline terminators. The last block filled to be exactly 1024 characters by adding blanks if needed. Assume a full range of 8 bit byte values for each character. The COBOL example uses forth.txt and forth.blk filenames.
#Wren
Wren
import "io" for File import "/str" for Str   var records = File.read("infile.dat") File.create("outfile.dat") { |f| for (record in Str.chunks(records, 80)) { record = record[-1..0] f.writeBytes(record) } } records = File.read("outfile.dat") for (record in Str.chunks(records, 80)) System.print(record)
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)
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Const POSITIVE_INFINITY As Double = 1.0/0.0   Sub printResult(dist(any, any) As Double, nxt(any, any) As Integer) Dim As Integer u, v Print("pair dist path") For i As Integer = 0 To UBound(nxt, 1) For j As Integer = 0 To UBound(nxt, 1) If i <> j Then u = i + 1 v = j + 1 Print Str(u); " -> "; Str(v); " "; dist(i, j); " "; Str(u); Do u = nxt(u - 1, v - 1) Print " -> "; Str(u); Loop While u <> v Print End If Next j Next i End Sub   Sub floydWarshall(weights(Any, Any) As Integer, numVertices As Integer) Dim dist(0 To numVertices - 1, 0 To numVertices - 1) As Double For i As Integer = 0 To numVertices - 1 For j As Integer = 0 To numVertices - 1 dist(i, j) = POSITIVE_INFINITY Next j Next i   For x As Integer = 0 To UBound(weights, 1) dist(weights(x, 0) - 1, weights(x, 1) - 1) = weights(x, 2) Next x   Dim nxt(0 To numVertices - 1, 0 To numVertices - 1) As Integer For i As Integer = 0 To numVertices - 1 For j As Integer = 0 To numVertices - 1 If i <> j Then nxt(i, j) = j + 1 Next j Next i   For k As Integer = 0 To numVertices - 1 For i As Integer = 0 To numVertices - 1 For j As Integer = 0 To numVertices - 1 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 If Next j Next i Next k   printResult(dist(), nxt()) End Sub   Dim weights(4, 2) As Integer = {{1, 3, -2}, {2, 1, 4}, {2, 3, 3}, {3, 4, 2}, {4, 2, -1}} Dim numVertices As Integer = 4 floydWarshall(weights(), numVertices) Print Print "Press any key to quit" Sleep
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
#Python
Python
def multiply(a, b): 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
#Q
Q
multiply:{[a;b] a*b}
http://rosettacode.org/wiki/Forward_difference
Forward difference
Task Provide code that produces a list of numbers which is the   nth  order forward difference, given a non-negative integer (specifying the order) and a list of numbers. The first-order forward difference of a list of numbers   A   is a new list   B,   where   Bn = An+1 - An. List   B   should have one fewer element as a result. The second-order forward difference of   A   will be: tdefmodule Diff do def forward(arr,i\\1) do forward(arr,[],i) end def forward([_|[]],diffs,i) do if i == 1 do IO.inspect diffs else forward(diffs,[],i-1) end end def forward([val1|[val2|vals]],diffs,i) do forward([val2|vals],diffs++[val2-val1],i) end end The same as the first-order forward difference of   B. That new list will have two fewer elements than   A   and one less than   B. The goal of this task is to repeat this process up to the desired order. For a more formal description, see the related   Mathworld article. Algorithmic options Iterate through all previous forward differences and re-calculate a new array each time. Use this formula (from Wikipedia): Δ n [ f ] ( x ) = ∑ k = 0 n ( n k ) ( − 1 ) n − k f ( x + k ) {\displaystyle \Delta ^{n}[f](x)=\sum _{k=0}^{n}{n \choose k}(-1)^{n-k}f(x+k)} (Pascal's Triangle   may be useful for this option.)
#jq
jq
# If n is a non-negative number and if input is # a (possibly empty) array of numbers, # emit an array, even if the input list is too short: def ndiff(n): if n==0 then . elif n == 1 then . as $in | [range(1;length) | $in[.] - $in[.-1]] else ndiff(1) | ndiff(n-1) 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.)
#Julia
Julia
ndiff(A::Array, n::Integer) = n < 1 ? A : diff(ndiff(A, n-1))   s = [90, 47, 58, 29, 22, 32, 55, 5, 55, 73] println.(collect(ndiff(s, i) for i in 0:9))
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
#XBasic
XBasic
  PROGRAM "hello" VERSION "0.0003"   DECLARE FUNCTION Entry()   FUNCTION Entry() PRINT "Hello World" END FUNCTION END PROGRAM  
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.
#Oz
Oz
declare fun {PrintFloat X Prec} {Property.put 'print.floatPrecision' Prec} S = {Float.toString X} in {Append for I in 1..Prec-{Length S}+1 collect:C do {C &0} end S} end in {System.showInfo {PrintFloat 7.125 8}}
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.
#PARI.2FGP
PARI/GP
printf("%09.4f\n", Pi)
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).
#Lambdatalk
Lambdatalk
  {def xor {lambda {:a :b} {or {and :a {not :b}} {and :b {not :a}}}}} -> xor   {def halfAdder {lambda {:a :b} {cons {and :a :b} {xor :a :b}}}} -> halfAdder   {def fullAdder {lambda {:a :b :c} {let { {:b :b} {:ha1 {halfAdder :c :a}} } {let { {:ha1 :ha1} {:ha2 {halfAdder {cdr :ha1} :b}} } {cons {or {car :ha1} {car :ha2}} {cdr :ha2}} }}}} -> fullAdder   {def 4bitsAdder {lambda {:a4 :a3 :a2 :a1 :b4 :b3 :b2 :b1} {let { {:a4 :a4} {:a3 :a3} {:a2 :a2} {:b4 :b4} {:b3 :b3} {:b2 :b2} {:fa1 {fullAdder :a1 :b1 false}} } {let { {:a4 :a4} {:a3 :a3} {:b4 :b4} {:b3 :b3} {:fa1 :fa1} {:fa2 {fullAdder :a2 :b2 {car :fa1}}} } {let { {:a4 :a4} {:b4 :b4} {:fa1 :fa1} {:fa2 :fa2} {:fa3 {fullAdder :a3 :b3 {car :fa2}}} } {let { {:fa1 :fa1} {:fa2 :fa2} {:fa3 :fa3} {:fa4 {fullAdder :a4 :b4 {car :fa3}}} } {car :fa4} {cdr :fa4} {cdr :fa3} {cdr :fa2} {cdr :fa1}}}}}}} -> 4bitsAdder   {def bin2bool {lambda {:b} {if {W.empty? {W.rest :b}} then {= {W.first :b} 1} else {= {W.first :b} 1} {bin2bool {W.rest :b}}}}} -> bin2bool   {def bool2bin {lambda {:b} {if {S.empty? {S.rest :b}} then {if {S.first :b} then 1 else 0} else {if {S.first :b} then 1 else 0}{bool2bin {S.rest :b}}}}} -> bool2bin   {def bin2dec {def bin2dec.r {lambda {:p :r} {if {A.empty? :p} then :r else {bin2dec.r {A.rest :p} {+ {A.first :p} {* 2 :r}}}}}} {lambda {:p} {bin2dec.r {A.split :p} 0}}} -> bin2dec   {def add {def numbers 0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 1011 1100 1101 1110 1111} {lambda {:a :b} {bin2dec {bool2bin {4bitsAdder {bin2bool {S.get :a {numbers}}} {bin2bool {S.get :b {numbers}}}}}}}} -> add   {table {S.map {lambda {:i} {tr {S.map {{lambda {:i :j} {td {add :i :j}}} :i} {S.serie 0 15}}}} {S.serie 0 15}} } -> 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30  
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.
#11l
11l
F fivenum(array) V n = array.len V x = sorted(array) V n4 = floor((n + 3.0) / 2.0) / 2.0 V d = [1.0, n4, (n + 1) / 2, n + 1 - n4, Float(n)] [Float] sum_array L(e) 5 V fl = Int(floor(d[e] - 1)) V ce = Int(ceil(d[e] - 1)) sum_array.append(0.5 * (x[fl] + x[ce])) R sum_array   V x = [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]   print(fivenum(x))
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.
#C.2B.2B
C++
  #include <windows.h> #include <string>   //-------------------------------------------------------------------------------------------------- using namespace std;   //-------------------------------------------------------------------------------------------------- enum states { NONE, TREE, FIRE }; const int MAX_SIDE = 500;   //-------------------------------------------------------------------------------------------------- class myBitmap { public: myBitmap() : pen( NULL ) {} ~myBitmap() { DeleteObject( pen ); DeleteDC( hdc ); DeleteObject( bmp ); }   bool create( int w, int h ) { BITMAPINFO bi; ZeroMemory( &bi, sizeof( bi ) );   bi.bmiHeader.biSize = sizeof( bi.bmiHeader ); bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8; bi.bmiHeader.biCompression = BI_RGB; bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biWidth = w; bi.bmiHeader.biHeight = -h;   HDC dc = GetDC( GetConsoleWindow() ); bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 ); if( !bmp ) return false;   hdc = CreateCompatibleDC( dc ); SelectObject( hdc, bmp ); ReleaseDC( GetConsoleWindow(), dc );   width = w; height = h;   return true; }   void clear() { ZeroMemory( pBits, width * height * sizeof( DWORD ) ); }   void setPenColor( DWORD clr ) { if( pen ) DeleteObject( pen ); pen = CreatePen( PS_SOLID, 1, clr ); SelectObject( hdc, pen ); }   void saveBitmap( string path ) { BITMAPFILEHEADER fileheader; BITMAPINFO infoheader; BITMAP bitmap; DWORD wb;   GetObject( bmp, sizeof( bitmap ), &bitmap );   DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight]; ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) ); ZeroMemory( &infoheader, sizeof( BITMAPINFO ) ); ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );   infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8; infoheader.bmiHeader.biCompression = BI_RGB; infoheader.bmiHeader.biPlanes = 1; infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader ); infoheader.bmiHeader.biHeight = bitmap.bmHeight; infoheader.bmiHeader.biWidth = bitmap.bmWidth; infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );   fileheader.bfType = 0x4D42; fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER ); fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;   GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );   HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL ); WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL ); WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL ); CloseHandle( file );   delete [] dwpBits; }   HDC getDC() const { return hdc; } int getWidth() const { return width; } int getHeight() const { return height; }   private: HBITMAP bmp; HDC hdc; HPEN pen; void *pBits; int width, height; }; //-------------------------------------------------------------------------------------------------- class forest { public: forest() { _bmp.create( MAX_SIDE, MAX_SIDE ); initForest( 0.05f, 0.005f ); }   void initForest( float p, float f ) { _p = p; _f = f; seedForest(); }   void mainLoop() { display(); simulate(); }   void setHWND( HWND hwnd ) { _hwnd = hwnd; }   private: float probRand() { return ( float )rand() / 32768.0f; }   void display() { HDC bdc = _bmp.getDC(); DWORD clr;   for( int y = 0; y < MAX_SIDE; y++ ) { for( int x = 0; x < MAX_SIDE; x++ ) { switch( _forest[x][y] ) { case FIRE: clr = 255; break; case TREE: clr = RGB( 0, 255, 0 ); break; default: clr = 0; }   SetPixel( bdc, x, y, clr ); } }   HDC dc = GetDC( _hwnd ); BitBlt( dc, 0, 0, MAX_SIDE, MAX_SIDE, _bmp.getDC(), 0, 0, SRCCOPY ); ReleaseDC( _hwnd, dc ); }   void seedForest() { ZeroMemory( _forestT, sizeof( _forestT ) ); ZeroMemory( _forest, sizeof( _forest ) ); for( int y = 0; y < MAX_SIDE; y++ ) for( int x = 0; x < MAX_SIDE; x++ ) if( probRand() < _p ) _forest[x][y] = TREE; }   bool getNeighbors( int x, int y ) { int a, b; for( int yy = -1; yy < 2; yy++ ) for( int xx = -1; xx < 2; xx++ ) { if( !xx && !yy ) continue; a = x + xx; b = y + yy; if( a < MAX_SIDE && b < MAX_SIDE && a > -1 && b > -1 ) if( _forest[a][b] == FIRE ) return true; }   return false; }   void simulate() { for( int y = 0; y < MAX_SIDE; y++ ) { for( int x = 0; x < MAX_SIDE; x++ ) { switch( _forest[x][y] ) { case FIRE: _forestT[x][y] = NONE; break; case NONE: if( probRand() < _p ) _forestT[x][y] = TREE; break; case TREE: if( getNeighbors( x, y ) || probRand() < _f ) _forestT[x][y] = FIRE; } } }   for( int y = 0; y < MAX_SIDE; y++ ) for( int x = 0; x < MAX_SIDE; x++ ) _forest[x][y] = _forestT[x][y]; }   myBitmap _bmp; HWND _hwnd; BYTE _forest[MAX_SIDE][MAX_SIDE], _forestT[MAX_SIDE][MAX_SIDE]; float _p, _f; }; //-------------------------------------------------------------------------------------------------- class wnd { public: int wnd::Run( HINSTANCE hInst ) { _hInst = hInst; _hwnd = InitAll();   _ff.setHWND( _hwnd ); _ff.initForest( 0.02f, 0.001f );   ShowWindow( _hwnd, SW_SHOW ); UpdateWindow( _hwnd );   MSG msg; ZeroMemory( &msg, sizeof( msg ) ); while( msg.message != WM_QUIT ) { if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 ) { TranslateMessage( &msg ); DispatchMessage( &msg ); } else { _ff.mainLoop(); } } return UnregisterClass( "_FOREST_FIRE_", _hInst ); } private: static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) { switch( msg ) { case WM_DESTROY: PostQuitMessage( 0 ); break; default: return DefWindowProc( hWnd, msg, wParam, lParam ); } return 0; }   HWND InitAll() { WNDCLASSEX wcex; ZeroMemory( &wcex, sizeof( wcex ) ); wcex.cbSize = sizeof( WNDCLASSEX ); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = ( WNDPROC )WndProc; wcex.hInstance = _hInst; wcex.hCursor = LoadCursor( NULL, IDC_ARROW ); wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 ); wcex.lpszClassName = "_FOREST_FIRE_";   RegisterClassEx( &wcex );   return CreateWindow( "_FOREST_FIRE_", ".: Forest Fire -- PJorente :.", WS_SYSMENU, CW_USEDEFAULT, 0, MAX_SIDE, MAX_SIDE, NULL, NULL, _hInst, NULL ); }   HINSTANCE _hInst; HWND _hwnd; forest _ff; }; //-------------------------------------------------------------------------------------------------- int APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) { srand( GetTickCount() ); wnd myWnd; return myWnd.Run( hInstance ); } //--------------------------------------------------------------------------------------------------  
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
#BaCon
BaCon
OPTION COLLAPSE TRUE   lst$ = "\"1\",2,\"\\\"3,4\\\",5\",\"\\\"\\\\\"\\\\\"\\\"\",\"\\\"\\\\\"6\\\\\"\\\"\",7,8,\"\""   PRINT lst$   REPEAT lst$ = FLATTEN$(lst$) UNTIL AMOUNT(lst$, ",") = AMOUNT(FLATTEN$(lst$), ",")   PRINT SORT$(lst$, ",")
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.
#Elixir
Elixir
defmodule Flip_game do @az Enum.map(?a..?z, &List.to_string([&1])) @in2i Enum.concat(Enum.map(1..26, fn i -> {to_string(i), i} end), Enum.with_index(@az) |> Enum.map(fn {c,i} -> {c,-i-1} end)) |> Enum.into(Map.new)   def play(n) when n>2 do target = generate_target(n) display(n, "Target: ", target) board = starting_config(n, target) play(n, target, board, 1) end   def play(n, target, board, moves) do display(n, "Board: ", board) ans = IO.gets("row/column to flip: ") |> String.strip |> String.downcase new_board = case @in2i[ans] do i when i in 1..n -> flip_row(n, board, i) i when i in -1..-n -> flip_column(n, board, -i) _ -> IO.puts "invalid input: #{ans}" board end if target == new_board do display(n, "Board: ", new_board) IO.puts "You solved the game in #{moves} moves" else IO.puts "" play(n, target, new_board, moves+1) end end   defp generate_target(n) do for i <- 1..n, j <- 1..n, into: Map.new, do: {{i, j}, :rand.uniform(2)-1} end   defp starting_config(n, target) do Enum.concat(1..n, -1..-n) |> Enum.take_random(n) |> Enum.reduce(target, fn x,acc -> if x>0, do: flip_row(n, acc, x), else: flip_column(n, acc, -x) end) end   defp flip_row(n, board, row) do Enum.reduce(1..n, board, fn col,acc -> Map.update!(acc, {row,col}, fn bit -> 1 - bit end) end) end   defp flip_column(n, board, col) do Enum.reduce(1..n, board, fn row,acc -> Map.update!(acc, {row,col}, fn bit -> 1 - bit end) end) end   defp display(n, title, board) do IO.puts title IO.puts " #{Enum.join(Enum.take(@az,n), " ")}" Enum.each(1..n, fn row ->  :io.fwrite "~2w ", [row] IO.puts Enum.map_join(1..n, " ", fn col -> board[{row, col}] end) end) end end   Flip_game.play(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.
#FOCAL
FOCAL
01.10 T "FLIP THE BITS"!"-------------"!!;S M=0 01.20 A "SIZE",N;I (N-2)1.2;I (8-N)1.2 01.30 F I=0,N*N-1;D 3.2;S G(I)=A;S B(I)=A 01.35 D 3.3;S L=FITR(A*5)*2+6;F K=0,L;D 3.1;S Z=A;D 3.2;D 4.4 01.40 S A=0;F I=0,N*N-1;S A=A+FABS(G(I)-B(I)) 01.42 T "MOVES",%3,M,!;S M=M+1 01.45 I (0-A)1.5;T !"YOU WIN!"!;Q 01.50 D 2 01.55 A "FLIP ROW (A) OR COLUMN (B)",A;S A=A-1;I (1-A)1.5 01.60 A "WHICH",Z;S Z=Z-1;I (N-A)1.6 01.65 D 4.4;G 1.4   02.10 T "--BOARD--";F A=1,N*2-5;T " " 02.14 T "--GOAL--"!" ";F A=0,N-1;T " ";D 5 02.15 T " ";F A=0,N-1;T " ";D 5 02.20 F R=0,N-1;S A=R;T !;D 2.4;T " ";D 2.5 02.30 T !!;R 02.40 D 5;F C=0,N-1;D 2.6 02.50 D 5;F C=0,N-1;D 2.7 02.60 I (B(R*N+C)-1)2.8;T " 1" 02.70 I (G(R*N+C)-1)2.8;T " 1" 02.80 T " 0"   03.10 D 3.3;S A=FITR(A*N) 03.20 D 3.3;S A=FITR(A+0.5) 03.30 S A=FABS(FRAN())*10;S A=A-FITR(A)   04.40 I (A-1)4.5,4.6 04.50 F I=0,N-1;S B(Z*N+I)=1-B(Z*N+I) 04.60 F I=0,N-1;S B(I*N+Z)=1-B(I*N+Z)   05.10 I (A-7)5.2;T "H";R 05.20 I (A-6)5.3;T "G";R 05.30 I (A-5)5.4;T "F";R 05.40 I (A-4)5.5;T "E";R 05.50 I (A-3)5.6;T "D";R 05.60 I (A-2)5.7;T "C";R 05.70 I (A-1)5.8;T "B";R 05.80 T "A"
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.
#BASIC256
BASIC256
global FAC FAC = 0.30102999566398119521373889472449302677   print p(12, 1) print p(12, 2) print p(123, 45) print p(123, 12345) print p(123, 678910) end   function p(L, n) cont = 0 : j = 0 LS = string(L) while cont < n j += 1 x = FAC * j if x < length(LS) then continue while y = 10^(x-int(x)) y *= 10^length(LS) digits = string(y) if left(digits,length(LS)) = LS then cont += 1 end while return j end function
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.
#C
C
#include <math.h> #include <stdio.h>   int p(int l, int n) { int test = 0; double logv = log(2.0) / log(10.0); int factor = 1; int loop = l; while (loop > 10) { factor *= 10; loop /= 10; } while (n > 0) { int val;   test++; val = (int)(factor * pow(10.0, fmod(test * logv, 1))); if (val == l) { n--; } } return test; }   void runTest(int l, int n) { printf("p(%d, %d) = %d\n", l, n, p(l, n)); }   int main() { runTest(12, 1); runTest(12, 2); runTest(123, 45); runTest(123, 12345); runTest(123, 678910);   return 0; }
http://rosettacode.org/wiki/First-class_functions/Use_numbers_analogously
First-class functions/Use numbers analogously
In First-class functions, a language is showing how its manipulation of functions is similar to its manipulation of other types. This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers. Write a program to create an ordered collection of a mixture of literally typed and expressions producing a real number, together with another ordered collection of their multiplicative inverses. Try and use the following pseudo-code to generate the numbers for the ordered collections: x = 2.0 xi = 0.5 y = 4.0 yi = 0.25 z = x + y zi = 1.0 / ( x + y ) Create a function multiplier, that given two numbers as arguments returns a function that when called with one argument, returns the result of multiplying the two arguments to the call to multiplier that created it and the argument in the call: new_function = multiplier(n1,n2) # where new_function(m) returns the result of n1 * n2 * m Applying the multiplier of a number and its inverse from the two ordered collections of numbers in pairs, show that the result in each case is one. Compare and contrast the resultant program with the corresponding entry in First-class functions. They should be close. To paraphrase the task description: Do what was done before, but with numbers rather than functions
#C.23
C#
using System; using System.Linq;   class Program { static void Main(string[] args) { double x, xi, y, yi, z, zi; x = 2.0; xi = 0.5; y = 4.0; yi = 0.25; z = x + y; zi = 1.0 / (x + y);   var numlist = new[] { x, y, z }; var numlisti = new[] { xi, yi, zi }; var multiplied = numlist.Zip(numlisti, (n1, n2) => { Func<double, double> multiplier = m => n1 * n2 * m; return multiplier; });   foreach (var multiplier in multiplied) Console.WriteLine(multiplier(0.5)); } }  
http://rosettacode.org/wiki/Flow-control_structures
Flow-control structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task Document common flow-control structures. One common example of a flow-control structure is the   goto   construct. Note that   Conditional Structures   and   Loop Structures   have their own articles/categories. Related tasks   Conditional Structures   Loop Structures
#Gambas
Gambas
Public Sub Main() Dim siCount As Short   LOOPIT:   Print siCount;; Inc siCount If siCount > 100 Then Quit Goto LoopIt   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
#Go
Go
func main() { inf: goto inf }
http://rosettacode.org/wiki/Four_is_magic
Four is magic
Task Write a subroutine, function, whatever it may be called in your language, that takes an integer number and returns an English text sequence starting with the English cardinal representation of that integer, the word 'is' and then the English cardinal representation of the count of characters that made up the first word, followed by a comma. Continue the sequence by using the previous count word as the first word of the next phrase, append 'is' and the cardinal count of the letters in that word. Continue until you reach four. Since four has four characters, finish by adding the words 'four is magic' and a period. All integers will eventually wind up at four. For instance, suppose your are given the integer 3. Convert 3 to Three, add is , then the cardinal character count of three, or five, with a comma to separate if from the next phrase. Continue the sequence five is four, (five has four letters), and finally, four is magic. Three is five, five is four, four is magic. For reference, here are outputs for 0 through 9. Zero is four, four is magic. One is three, three is five, five is four, four is magic. Two is three, three is five, five is four, four is magic. Three is five, five is four, four is magic. Four is magic. Five is four, four is magic. Six is three, three is five, five is four, four is magic. Seven is five, five is four, four is magic. Eight is five, five is four, four is magic. Nine is four, four is magic. Some task guidelines You may assume the input will only contain integer numbers. Cardinal numbers between 20 and 100 may use either hyphens or spaces as word separators but they must use a word separator. (23 is twenty three or twenty-three not twentythree.) Cardinal number conversions should follow the English short scale. (billion is 1e9, trillion is 1e12, etc.) Cardinal numbers should not include commas. (20140 is twenty thousand one hundred forty not twenty thousand, one hundred forty.) When converted to a string, 100 should be one hundred, not a hundred or hundred, 1000 should be one thousand, not a thousand or thousand. When converted to a string, there should be no and in the cardinal string. 130 should be one hundred thirty not one hundred and thirty. When counting characters, count all of the characters in the cardinal number including spaces and hyphens. One hundred fifty-one should be 21 not 18. The output should follow the format "N is K, K is M, M is ... four is magic." (unless the input is 4, in which case the output should simply be "four is magic.") The output can either be the return value from the function, or be displayed from within the function. You are encouraged, though not mandated to use proper sentence capitalization. You may optionally support negative numbers. -7 is negative seven. Show the output here for a small representative sample of values, at least 5 but no more than 25. You are free to choose which which numbers to use for output demonstration. You can choose to use a library, (module, external routine, whatever) to do the cardinal conversions as long as the code is easily and freely available to the public. If you roll your own, make the routine accept at minimum any integer from 0 up to 999999. If you use a pre-made library, support at least up to unsigned 64 bit integers. (or the largest integer supported in your language if it is less.) Four is magic is a popular code-golf task. This is not code golf. Write legible, idiomatic and well formatted code. Related tasks   Four is the number of_letters in the ...   Look-and-say sequence   Number names   Self-describing numbers   Summarize and say sequence   Spelling of ordinal numbers   De Bruijn sequences
#REXX
REXX
/*REXX pgm converts a # to English into the phrase: a is b, b is c, ... four is magic. */ numeric digits 3003 /*be able to handle gihugic numbers. */ parse arg x /*obtain optional numbers from the C.L.*/ if x='' then x= -164 0 4 6 11 13 75 100 337 9223372036854775807 /*use these defaults?*/ @.= . /*stemmed array used for memoization. */ do j=1 for words(x) /*process each of the numbers in list. */ say 4_is( word(x, j) ) /*display phrase that'll be returned. */ say /*display a blank line between outputs.*/ end /*j*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ 4_is: procedure expose @.; parse arg #,,$ /*obtain the start number.*/ if #\==4 then do until L==4 /*Not 4? Process number.*/ @.#= $spell#(# 'quiet minus negative') /*spell number in English.*/ #= @.#; L= length(#) /*get the length of spelt#*/ if @.L==. then @.L= $spell#(L 'quiet') /*¬spelt before? Spell it.*/ $= $ # "is" @.L',' /*add phrase to the answer*/ #= L /*use the new number, ··· */ end /*until*/ /* ··· which will be spelt*/ $= strip($ 'four is magic.') /*finish the sentence with the finale. */ parse var $ first 2 other; upper first /*capitalize the first letter of output*/ return first || other /*return the sentence to the invoker. */
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.
#AWK
AWK
#!/bin/awk -f   BEGIN { if (rows !~ /^[0-9]+$/ || rows < 0) { print "invalid rows or missing from command line" print "syntax: awk -v rows=14 -f floyds_triangle.awk" exit 1 }   for (row=cols=1; row<=rows; row++ cols++) { width[row] = length(row + (rows * (rows-1))/2) for (col=1; col<=cols; col++) printf("%*d%c", width[col], ++n, row == col ? "\n" : " ") } }  
http://rosettacode.org/wiki/Fixed_length_records
Fixed length records
Fixed length read/write Before terminals, computers commonly used punch card readers or paper tape input. A common format before these devices were superseded by terminal technology was based on the Hollerith code, Hollerith code. These input devices handled 80 columns per card and had a limited character set, encoded by punching holes in one or more rows of the card for each column. These devices assumed/demanded a fixed line width of 80 characters, newlines were not required (and could not even be encoded in some systems). Task Write a program to read 80 column fixed length records (no newline terminators (but newline characters allowed in the data)) and then write out the reverse of each line as fixed length 80 column records. Samples here use printable characters, but that is not a given with fixed length data. Filenames used are sample.txt, infile.dat, outfile.dat. Note: There are no newlines, inputs and outputs are fixed at 80 columns, no more, no less, space padded. Fixed length data is 8 bit complete. NUL bytes of zero are allowed. These fixed length formats are still in wide use on mainframes, with JCL and with COBOL (which commonly use EBCDIC encoding and not ASCII). Most of the large players in day to day financial transactions know all about fixed length records and the expression logical record length. Sample data To create the sample input file, use an editor that supports fixed length records or use a conversion utility. For instance, most GNU/Linux versions of dd support blocking and unblocking records with a conversion byte size. Line 1...1.........2.........3.........4.........5.........6.........7.........8 Line 2 Line 3 Line 4 Line 6 Line 7 Indented line 8............................................................ Line 9 RT MARGIN prompt$ dd if=sample.txt of=infile.dat cbs=80 conv=block prompt$ dd if=infile.dat cbs=80 conv=unblock Bonus round Forth systems often include BLOCK words. A block is 1024 bytes. Source code is stored as 16 lines of 64 characters each (again, no newline character or sequence to mark the end of a line). Write a program to convert a block file to text (using newlines). Trailing spaces should be excluded from the output. Also demonstrate how to convert from a normal text file to block form. All lines either truncated or padded to 64 characters with no newline terminators. The last block filled to be exactly 1024 characters by adding blanks if needed. Assume a full range of 8 bit byte values for each character. The COBOL example uses forth.txt and forth.blk filenames.
#zkl
zkl
Line 1...1.........2.........3.........4.........5.........6.........7.........8Line 2 Line 3 Line 4 Line 6 Line 7 Indented line 8............................................................Line 9 RT MARGIN
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)
#Go
Go
package main   import ( "fmt" "strconv" )   // A Graph is the interface implemented by graphs that // this algorithm can run on. type Graph interface { Vertices() []Vertex Neighbors(v Vertex) []Vertex Weight(u, v Vertex) int }   // Nonnegative integer ID of vertex type Vertex int   // ig is a graph of integers that satisfies the Graph interface. type ig struct { vert []Vertex edges map[Vertex]map[Vertex]int }   func (g ig) edge(u, v Vertex, w int) { if _, ok := g.edges[u]; !ok { g.edges[u] = make(map[Vertex]int) } g.edges[u][v] = w } func (g ig) Vertices() []Vertex { return g.vert } func (g ig) Neighbors(v Vertex) (vs []Vertex) { for k := range g.edges[v] { vs = append(vs, k) } return vs } func (g ig) Weight(u, v Vertex) int { return g.edges[u][v] } func (g ig) path(vv []Vertex) (s string) { if len(vv) == 0 { return "" } s = strconv.Itoa(int(vv[0])) for _, v := range vv[1:] { s += " -> " + strconv.Itoa(int(v)) } return s }   const Infinity = int(^uint(0) >> 1)   func FloydWarshall(g Graph) (dist map[Vertex]map[Vertex]int, next map[Vertex]map[Vertex]*Vertex) { vert := g.Vertices() dist = make(map[Vertex]map[Vertex]int) next = make(map[Vertex]map[Vertex]*Vertex) for _, u := range vert { dist[u] = make(map[Vertex]int) next[u] = make(map[Vertex]*Vertex) for _, v := range vert { dist[u][v] = Infinity } dist[u][u] = 0 for _, v := range g.Neighbors(u) { v := v dist[u][v] = g.Weight(u, v) next[u][v] = &v } } for _, k := range vert { for _, i := range vert { for _, j := range vert { if dist[i][k] < Infinity && dist[k][j] < Infinity { if dist[i][j] > dist[i][k]+dist[k][j] { dist[i][j] = dist[i][k] + dist[k][j] next[i][j] = next[i][k] } } } } } return dist, next }   func Path(u, v Vertex, next map[Vertex]map[Vertex]*Vertex) (path []Vertex) { if next[u][v] == nil { return } path = []Vertex{u} for u != v { u = *next[u][v] path = append(path, u) } return path }   func main() { g := ig{[]Vertex{1, 2, 3, 4}, make(map[Vertex]map[Vertex]int)} g.edge(1, 3, -2) g.edge(3, 4, 2) g.edge(4, 2, -1) g.edge(2, 1, 4) g.edge(2, 3, 3)   dist, next := FloydWarshall(g) fmt.Println("pair\tdist\tpath") for u, m := range dist { for v, d := range m { if u != v { fmt.Printf("%d -> %d\t%3d\t%s\n", u, v, d, g.path(Path(u, v, next))) } } } }
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
#Quack
Quack
fn 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
#Quackery
Quackery
[ * ] is multiply ( n n --> 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.)
#K4
K4
fd:1_-':
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.)
#Kotlin
Kotlin
// version 1.1.2   fun forwardDifference(ia: IntArray, order: Int): IntArray { if (order < 0) throw IllegalArgumentException("Order must be non-negative") if (order == 0) return ia val size = ia.size if (size == 0) return ia // same empty array if (order >= size) return intArrayOf() // new empty array var old = ia var new = old var count = order while (count-- >= 1) { new = IntArray(old.size - 1) for (i in 0 until new.size) new[i] = old[i + 1] - old[i] old = new } return new }   fun printArray(ia: IntArray) { print("[") for (i in 0 until ia.size) { print("%5d".format(ia[i])) if (i < ia .size - 1) print(", ") } println("]") }   fun main(args: Array<String>) { val ia = intArrayOf(90, 47, 58, 29, 22, 32, 55, 5, 55, 73) for (order in 0..ia.size) { val fd = forwardDifference(ia, order) print("%2d".format(order) + ": ") printArray(fd) } }
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
#xEec
xEec
  h#10 h$! h$d h$l h$r h$o h$w h#32 h$o h$l h$l h$e h$H >o o$ p jno  
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
#XL
XL
use XL.UI.CONSOLE WriteLn "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.
#Pascal
Pascal
procedure writeInFixedFormat(n: real); const wholeNumberPlaces = 5; fractionalPlaces = 3; zeroDigit = '0'; negative = '-'; var signPresent: boolean; i: integer; begin // NOTE: This does not catch “negative” zero. signPresent := n < 0.0; if signPresent then begin write(negative); n := abs(n); end;   // determine number of leading zeros i := wholeNumberPlaces; if n > 0 then begin i := i - trunc(ln(n) / ln(10)); end;   for i := i - 1 downto succ(ord(signPresent)) do begin write(zeroDigit); end;   // writes n with // - at least 0 characters in total // - exactly fractionalPlaces post-radix digits // rounded write(n:0:fractionalPlaces); end;
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).
#Lua
Lua
-- Build XOR from AND, OR and NOT function xor (a, b) return (a and not b) or (b and not a) end   -- Can make half adder now XOR exists function halfAdder (a, b) return xor(a, b), a and b end   -- Full adder is two half adders with carry outputs OR'd function fullAdder (a, b, cIn) local ha0s, ha0c = halfAdder(cIn, a) local ha1s, ha1c = halfAdder(ha0s, b) local cOut, s = ha0c or ha1c, ha1s return cOut, s end   -- Carry bits 'ripple' through adders, first returned value is overflow function fourBitAdder (a3, a2, a1, a0, b3, b2, b1, b0) -- LSB-first local fa0c, fa0s = fullAdder(a0, b0, false) local fa1c, fa1s = fullAdder(a1, b1, fa0c) local fa2c, fa2s = fullAdder(a2, b2, fa1c) local fa3c, fa3s = fullAdder(a3, b3, fa2c) return fa3c, fa3s, fa2s, fa1s, fa0s -- Return as MSB-first end   -- Take string of noughts and ones, convert to native boolean type function toBool (bitString) local boolList, bit = {} for digit = 1, 4 do bit = string.sub(string.format("%04d", bitString), digit, digit) if bit == "0" then table.insert(boolList, false) end if bit == "1" then table.insert(boolList, true) end end return boolList end   -- Take list of booleans, convert to string of binary digits (variadic) function toBits (...) local bStr = "" for i, bool in pairs{...} do if bool then bStr = bStr .. "1" else bStr = bStr .. "0" end end return bStr end   -- Little driver function to neaten use of the adder function add (n1, n2) local A, B = toBool(n1), toBool(n2) local v, s0, s1, s2, s3 = fourBitAdder( A[1], A[2], A[3], A[4], B[1], B[2], B[3], B[4] ) return toBits(s0, s1, s2, s3), v end   -- Main procedure (usage examples) print("SUM", "OVERFLOW\n") print(add(0001, 0001)) -- 1 + 1 = 2 print(add(0101, 1010)) -- 5 + 10 = 15 print(add(0000, 1111)) -- 0 + 15 = 15 print(add(0001, 1111)) -- 1 + 15 = 16 (causes overflow)
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.
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO; with Ada.Containers.Generic_Array_Sort;   procedure Main is package Real_Io is new Float_IO (Long_Float); use Real_Io;   type Data_Array is array (Natural range <>) of Long_Float; subtype Five_Num_Type is Data_Array (0 .. 4);   procedure Sort is new Ada.Containers.Generic_Array_Sort (Index_Type => Natural, Element_Type => Long_Float, Array_Type => Data_Array);   function Median (X : Data_Array) return Long_Float with Pre => X'Length > 0;   function Median (X : Data_Array) return Long_Float is M : constant Natural := X'First + X'Last / 2; begin if X'Length rem 2 = 1 then return X (M); else return (X (M - 1) + X (M)) / 2.0; end if; end Median;   procedure fivenum (X : Data_Array; Result : out Five_Num_Type) is Temp  : Data_Array := X; m  : Natural  := X'Length / 2; Lower_end : Natural  := (if X'Length rem 2 = 0 then m - 1 else m); begin Sort (Temp); Result (0) := Temp (Temp'First); Result (2) := Median (Temp); Result (4) := Temp (Temp'Last); Result (1) := Median (Temp (1 .. Lower_end)); Result (3) := Median (Temp (m .. Temp'Last)); end fivenum;   procedure print (Result : Five_Num_Type; Aft : Natural) is begin Put ("["); for I in Result'Range loop Put (Item => Result (I), Fore => 1, Aft => Aft, Exp => 0); if I < Result'Last then Put (", "); else Put_Line ("]"); end if; end loop; New_Line; end print;   X1 : Data_Array := (15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0); X2 : Data_Array := (36.0, 40.0, 7.0, 39.0, 41.0, 15.0); X3 : Data_Array := (0.140_828_34, 0.097_487_90, 1.731_315_07, 0.876_360_09, -1.950_595_94, 0.734_385_55, -0.030_357_26, 1.466_759_70, -0.746_213_49, -0.725_887_72, 0.639_051_60, 0.615_015_27, -0.989_837_80, -1.004_478_74, -0.627_594_69, 0.662_061_63, 1.043_120_09, -0.103_053_85, 0.757_756_34, 0.325_665_78); Result : Five_Num_Type; begin fivenum (X1, Result); print (Result, 1); fivenum (X2, Result); print (Result, 1); fivenum (X3, Result); print (Result, 9); end Main;  
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.
#Ceylon
Ceylon
import ceylon.random { DefaultRandom }   abstract class Cell() of tree | dirt | burning {} object tree extends Cell() { string => "A"; } object dirt extends Cell() { string => " "; } object burning extends Cell() { string => "#"; }   class Forest(Integer width, Integer height, Float f, Float p) {   value random = DefaultRandom(); function chance(Float probability) => random.nextFloat() < probability; value sparked => chance(f); value sprouted => chance(p);   alias Point => Integer[2]; interface Row => {Cell*};   object doubleBufferedGrid satisfies Correspondence<Point, Cell> & KeyedCorrespondenceMutator<Point, Cell> {   value grids = [ Array { for (j in 0:height) Array { for (i in 0:width) chance(0.5) then tree else dirt } }, Array { for (j in 0:height) Array.ofSize(width, dirt) } ];   variable value showFirst = true; value currentState => showFirst then grids.first else grids.last; value nextState => showFirst then grids.last else grids.first;   shared void swapStates() => showFirst = !showFirst;   shared {Row*} rows => currentState;   shared actual Boolean defines(Point key) => let (x = key[0], y = key[1]) 0 <= x < width && 0 <= y < height; shared actual Cell? get(Point key) => let (x = key[0], y = key[1]) currentState.get(y)?.get(x);   shared actual void put(Point key, Cell cell) { value [x, y] = key; nextState.get(y)?.set(x, cell); } }   variable value evolutions = 0; shared Integer generation => evolutions + 1;   shared void evolve() {   evolutions++;   function firesNearby(Integer x, Integer y) => { for (j in y - 1 : 3) for (i in x - 1 : 3) doubleBufferedGrid[[i, j]] }.coalesced.any(burning.equals);   for(j->row in doubleBufferedGrid.rows.indexed) { for(i->cell in row.indexed) { switch (cell) case (burning) { doubleBufferedGrid[[i, j]] = dirt; } case (dirt) { doubleBufferedGrid[[i, j]] = sprouted then tree else dirt; } case (tree) { doubleBufferedGrid[[i, j]] = firesNearby(i, j) || sparked then burning else tree; } } }   doubleBufferedGrid.swapStates(); }   shared void display() {   void drawLine() => print("-".repeat(width + 2));   drawLine(); for (row in doubleBufferedGrid.rows) { process.write("|"); for (cell in row) { process.write(cell.string); } print("|"); } drawLine(); } }   shared void run() {   value forest = Forest(78, 38, 0.02, 0.03);   while (true) {   forest.display();   print("Generation ``forest.generation``"); print("Press enter for next generation or q and then enter to quit");   value input = process.readLine(); if (exists input, input.trimmed.lowercased == "q") { return; }   forest.evolve(); } }
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
#BASIC256
BASIC256
sComma = "": sFlatter = "" sString = "[[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8 []]"   For siCount = 1 To Length(sString) If Instr("[] ,", Mid(sString, siCount, 1)) = 0 Then sFlatter = sFlatter & sComma & Mid(sString, siCount, 1) sComma = ", " End If Next siCount   Print "["; sFlatter; "]" End
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.
#Fortran
Fortran
  !Implemented by Anant Dixit (October 2014) program flipping_bits implicit none character(len=*), parameter :: cfmt = "(A3)", ifmt = "(I3)" integer :: N, i, j, io, seed(8), moves, input logical, allocatable :: Brd(:,:), Trgt(:,:) logical :: solved double precision :: r   do write(*,*) 'Enter the number of squares (between 1 and 10) you would like: ' read(*,*,iostat=io) N if(N.gt.0 .and. N.le.10 .and. io.eq.0) exit write(*,*) 'Please, an integer between 1 and 10' end do   allocate(Brd(N,N),Trgt(N,N)) call date_and_time(values=seed) call srand(1000*seed(7)+seed(8)+60000*seed(6)) do i = 1,N do j = 1,N r = rand() if(r.gt.0.5D0) then Brd(i,j) = .TRUE. Trgt(i,j) = .TRUE. else Brd(i,j) = .FALSE. Trgt(i,j) = .FALSE. end if end do end do ! Random moves taken by the program to `create' a target moves = N do i = 1,moves r = 1+2.0D0*dble(N)*rand() - 1.0D-17 !Only to make sure that the number is between 1 and 2N (less than 2N-1) if(floor(r).le.N) then do j = 1,N Trgt(floor(r),j) = .NOT.Trgt(floor(r),j) end do else r = r-N do j = 1,N Trgt(j,floor(r)) = .NOT.Trgt(j,floor(r)) end do end if end do   !This part checks if the target and the starting configurations are same or not. do input = N call next_move(Brd,Trgt,N,input,solved) call next_move(Brd,Trgt,N,input,solved) if(solved) then r = 1+2.0D0*dble(N)*rand() - 1.0D-17 if(floor(r).le.N) then do j = 1,N Trgt(floor(r),j) = .NOT.Trgt(floor(r),j) end do else r = r-N do j = 1,N Trgt(j,floor(r)) = .NOT.Trgt(j,floor(r)) end do end if else exit end if end do   write(*,*) 'Welcome to the Flipping Bits game!' write(*,*) 'You have the current position'   moves = 0 call display(Brd,Trgt,N) input = N do write(*,*) 'Number of moves so far:', moves write(*,*) 'Select the column or row you wish to flip: ' read(*,*,iostat=io) input if(io.eq.0 .and. input.gt.0 .and. input.le.(2*N)) then moves = moves+1 write(*,*) 'Flipping ', input call next_move(Brd,Trgt,N,input,solved) call display(Brd,Trgt,N) if(solved) exit else write(*,*) 'Please enter a valid column or row number. To quit, press Ctrl+C!' end if end do   write(*,*) 'Congratulations! You finished the game!' write(*,ifmt,advance='no') moves write(*,*) ' moves were taken by you!!' deallocate(Brd,Trgt) end program   subroutine display(Brd,Trgt,N) implicit none !arguments integer :: N logical :: Brd(N,N), Trgt(N,N) !local character(len=*), parameter :: cfmt = "(A3)", ifmt = "(I3)" integer :: i, j write(*,*) 'Current Configuration: ' do i = 0,N if(i.eq.0) then write(*,cfmt,advance='no') 'R/C' write(*,cfmt,advance='no') ' | ' else write(*,ifmt,advance='no') i end if end do write(*,*) do i = 0,N if(i.eq.0) then do j = 0,N+2 write(*,cfmt,advance='no') '---' end do else write(*,ifmt,advance='no') i+N write(*,cfmt,advance='no') ' | ' do j = 1,N if(Brd(i,j)) then write(*,ifmt,advance='no') 1 else write(*,ifmt,advance='no') 0 end if end do end if write(*,*) end do   write(*,*) write(*,*)   write(*,*) 'Target Configuration' do i = 0,N if(i.eq.0) then write(*,cfmt,advance='no') 'R/C' write(*,cfmt,advance='no') ' | ' else write(*,ifmt,advance='no') i end if end do write(*,*) do i = 0,N if(i.eq.0) then do j = 0,N+2 write(*,cfmt,advance='no') '---' end do else write(*,ifmt,advance='no') i+N write(*,cfmt,advance='no') ' | ' do j = 1,N if(Trgt(i,j)) then write(*,ifmt,advance='no') 1 else write(*,ifmt,advance='no') 0 end if end do end if write(*,*) end do write(*,*) write(*,*) end subroutine   subroutine next_move(Brd,Trgt,N,input,solved) implicit none !arguments integer :: N, input logical :: Brd(N,N), Trgt(N,N), solved !others integer :: i,j   if(input.gt.N) then input = input-N do i = 1,N Brd(input,i) = .not.Brd(input,i) end do else do i = 1,N Brd(i,input) = .not.Brd(i,input) end do end if solved = .TRUE. do i = 1,N do j = 1,N if( (.not.Brd(i,j).and.Trgt(i,j)) .or. (Brd(i,j).and..not.Trgt(i,j)) ) then solved = .FALSE. exit end if end do if(.not.solved) exit end do end subroutine  
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.
#C.2B.2B
C++
// a mini chrestomathy solution   #include <string> #include <chrono> #include <cmath> #include <locale>   using namespace std; using namespace chrono;   // translated from java example unsigned int js(int l, int n) { unsigned int res = 0, f = 1; double lf = log(2) / log(10), ip; for (int i = l; i > 10; i /= 10) f *= 10; while (n > 0) if ((int)(f * pow(10, modf(++res * lf, &ip))) == l) n--; return res; }   // translated from go integer example (a.k.a. go translation of pascal alternative example) unsigned int gi(int ld, int n) { string Ls = to_string(ld); unsigned int res = 0, count = 0; unsigned long long f = 1; for (int i = 1; i <= 18 - Ls.length(); i++) f *= 10; const unsigned long long ten18 = 1e18; unsigned long long probe = 1; do { probe <<= 1; res++; if (probe >= ten18) { do { if (probe >= ten18) probe /= 10; if (probe / f == ld) if (++count >= n) { count--; break; } probe <<= 1; res++; } while (1); } string ps = to_string(probe); if (ps.substr(0, min(Ls.length(), ps.length())) == Ls) if (++count >= n) break; } while (1); return res; }   // translated from pascal alternative example unsigned int pa(int ld, int n) { const double L_float64 = pow(2, 64); const unsigned long long Log10_2_64 = (unsigned long long)(L_float64 * log(2) / log(10)); double Log10Num; unsigned long long LmtUpper, LmtLower, Frac64; int res = 0, dgts = 1, cnt; for (int i = ld; i >= 10; i /= 10) dgts *= 10; Log10Num = log((ld + 1.0) / dgts) / log(10); // '316' was a limit if (Log10Num >= 0.5) { LmtUpper = (ld + 1.0) / dgts < 10.0 ? (unsigned long long)(Log10Num * (L_float64 * 0.5)) * 2 + (unsigned long long)(Log10Num * 2) : 0; Log10Num = log((double)ld / dgts) / log(10); LmtLower = (unsigned long long)(Log10Num * (L_float64 * 0.5)) * 2 + (unsigned long long)(Log10Num * 2); } else { LmtUpper = (unsigned long long)(Log10Num * L_float64); LmtLower = (unsigned long long)(log((double)ld / dgts) / log(10) * L_float64); } cnt = 0; Frac64 = 0; if (LmtUpper != 0) { do { res++; Frac64 += Log10_2_64; if ((Frac64 >= LmtLower) & (Frac64 < LmtUpper)) if (++cnt >= n) break; } while (1); } else { // '999..' do { res++; Frac64 += Log10_2_64; if (Frac64 >= LmtLower) if (++cnt >= n) break; } while (1); }; return res; }   int params[] = { 12, 1, 12, 2, 123, 45, 123, 12345, 123, 678910, 99, 1 };   void doOne(string name, unsigned int (*func)(int a, int b)) { printf("%s version:\n", name.c_str()); auto start = steady_clock::now(); for (int i = 0; i < size(params); i += 2) printf("p(%3d, %6d) = %'11u\n", params[i], params[i + 1], func(params[i], params[i + 1])); printf("Took %f seconds\n\n", duration<double>(steady_clock::now() - start).count()); }   int main() { setlocale(LC_ALL, ""); doOne("java simple", js); doOne("go integer", gi); doOne("pascal alternative", pa); }
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
#C.2B.2B
C++
#include <array> #include <iostream>   int main() { double x = 2.0; double xi = 0.5; double y = 4.0; double yi = 0.25; double z = x + y; double zi = 1.0 / ( x + y );   const std::array values{x, y, z}; const std::array inverses{xi, yi, zi};   auto multiplier = [](double a, double b) { return [=](double m){return a * b * m;}; };   for(size_t i = 0; i < values.size(); ++i) { auto new_function = multiplier(values[i], inverses[i]); double value = new_function(i + 1.0); std::cout << value << "\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
#GW-BASIC
GW-BASIC
10 LET a=1 20 IF a=2 THEN PRINT "This is a conditional statement" 30 IF a=1 THEN GOTO 50: REM a conditional jump 40 PRINT "This statement will be skipped" 50 PRINT ("Hello" AND (1=2)): REM This does NOT PRINT 100 PRINT "Endless loop" 110 GOTO 100:REM an unconditional jump
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
#Haskell
Haskell
import Control.Monad import Control.Monad.Trans import Control.Monad.Exit   main = do runExitTMaybe $ do forM_ [1..5] $ \x -> do forM_ [1..5] $ \y -> do lift $ print (x, y) when (x == 3 && y == 2) $ exitWith () putStrLn "Done."
http://rosettacode.org/wiki/Four_is_magic
Four is magic
Task Write a subroutine, function, whatever it may be called in your language, that takes an integer number and returns an English text sequence starting with the English cardinal representation of that integer, the word 'is' and then the English cardinal representation of the count of characters that made up the first word, followed by a comma. Continue the sequence by using the previous count word as the first word of the next phrase, append 'is' and the cardinal count of the letters in that word. Continue until you reach four. Since four has four characters, finish by adding the words 'four is magic' and a period. All integers will eventually wind up at four. For instance, suppose your are given the integer 3. Convert 3 to Three, add is , then the cardinal character count of three, or five, with a comma to separate if from the next phrase. Continue the sequence five is four, (five has four letters), and finally, four is magic. Three is five, five is four, four is magic. For reference, here are outputs for 0 through 9. Zero is four, four is magic. One is three, three is five, five is four, four is magic. Two is three, three is five, five is four, four is magic. Three is five, five is four, four is magic. Four is magic. Five is four, four is magic. Six is three, three is five, five is four, four is magic. Seven is five, five is four, four is magic. Eight is five, five is four, four is magic. Nine is four, four is magic. Some task guidelines You may assume the input will only contain integer numbers. Cardinal numbers between 20 and 100 may use either hyphens or spaces as word separators but they must use a word separator. (23 is twenty three or twenty-three not twentythree.) Cardinal number conversions should follow the English short scale. (billion is 1e9, trillion is 1e12, etc.) Cardinal numbers should not include commas. (20140 is twenty thousand one hundred forty not twenty thousand, one hundred forty.) When converted to a string, 100 should be one hundred, not a hundred or hundred, 1000 should be one thousand, not a thousand or thousand. When converted to a string, there should be no and in the cardinal string. 130 should be one hundred thirty not one hundred and thirty. When counting characters, count all of the characters in the cardinal number including spaces and hyphens. One hundred fifty-one should be 21 not 18. The output should follow the format "N is K, K is M, M is ... four is magic." (unless the input is 4, in which case the output should simply be "four is magic.") The output can either be the return value from the function, or be displayed from within the function. You are encouraged, though not mandated to use proper sentence capitalization. You may optionally support negative numbers. -7 is negative seven. Show the output here for a small representative sample of values, at least 5 but no more than 25. You are free to choose which which numbers to use for output demonstration. You can choose to use a library, (module, external routine, whatever) to do the cardinal conversions as long as the code is easily and freely available to the public. If you roll your own, make the routine accept at minimum any integer from 0 up to 999999. If you use a pre-made library, support at least up to unsigned 64 bit integers. (or the largest integer supported in your language if it is less.) Four is magic is a popular code-golf task. This is not code golf. Write legible, idiomatic and well formatted code. Related tasks   Four is the number of_letters in the ...   Look-and-say sequence   Number names   Self-describing numbers   Summarize and say sequence   Spelling of ordinal numbers   De Bruijn sequences
#Ring
Ring
  /* Checking numbers from 0 to 10 */ for c = 0 to 10 See checkmagic(c) + NL next     /* The functions */   Func CheckMagic numb CardinalN = "" Result = "" if isnumber(numb) = false or numb < 0 or numb > 999_999_999_999_999 Return "ERROR: Number entered is incorrect" ok if numb = 4 Result = "Four is magic." else While True if CardinalN = "four" Result += "four is magic" exit ok strnumb = StringNumber(numb) CardinalN = StringNumber(len(strnumb)) Result += strnumb + " is " + CardinalN + ", " numb = len(strnumb) End Result += "." Result = upper(Result[1]) + Right(Result, len(Result) -1) ok   Return Result   Func StringNumber cnumb   NumStr = [:n0 = "zero", :n1 = "one", :n2 = "two", :n3 = "three", :n4 = "four", :n5 = "five", :n6 = "six", :n7 = "seven", :n8 = "eight", :n9 = "nine", :n10 = "ten", :n11 = "eleven", :n12 = "twelve", :n13 = "thirteen", :n14 = "fourteen", :n15 = "fifteen", :n16 = "sixteen", :n17 = "seventeen", :n18 = "eighteen", :n19 = "nineteen", :n20 = "twenty", :n30 = "thirty", :n40 = "fourty", :n50 = "fifty", :n60 = "sixty", :n70 = "seventy", :n80 = "eighty", :n90 = "ninety"]   numLev = [:l1 = "", :l2 = "thousand", :l3 = "million", :l4 = "billion", :l5 = "trillion"]   Result = ""   if cnumb > 0 decimals(0) snumb = string((cnumb)) lnumb = [""] fl = floor(len(snumb) / 3) if fl > 0 for i = 1 to fl lnumb[i] = right(snumb, 3) snumb = left(snumb, len(snumb) -3) lnumb + "" next if (len(snumb) % 3) > 0 lnumb[len(lnumb)] = snumb else del(lnumb, len(lnumb)) ok else lnumb[1] = snumb ok for l = len(lnumb) to 1 step -1 bnumb = lnumb[l] bResult = "" if number(bnumb) != 0 for n = len(bnumb) to 1 step -1 if (len(bnumb) = 3 and n = 2) or (len(bnumb) = 2 and n = 1) if number(bnumb[n]) > 1 eval("bResult = NumStr[:n" + bnumb[n] + "0] + ' ' + bResult") elseif number(bnumb[n]) = 1 eval("bResult = NumStr[:n" + bnumb[n] + bnumb[n+1] + "] + ' ' + bResult") ok else if len(bnumb) = 3 and n = 1 and number(bnumb[1]) > 0 if trim(bResult) != "" bResult = " " + bResult ok if number(bnumb[1]) > 1 bResult = "hundreds" + bResult else bResult = "hundred" + bResult ok if left(trim(bResult), 7) = "hundred" bResult = bResult + " " ok ok if (len(bnumb) = 3 and n = 1 and number(bnumb[1]) = 0) OR (len(bnumb) = n and number(bnumb[n]) = 0) OR (len(bnumb) = 3 and number(bnumb[2]) = 1) OR (len(bnumb) = 2 and number(bnumb[1]) = 1) loop ok eval("bResult = NumStr[:n" + bnumb[n] + "] + ' ' + bResult") ok next Result = Result + bResult if l > 1 if number(bnumb) > 1 eval("Result = Result + numLev[:l" + l + "] + 's ' ") else eval("Result = Result + numLev[:l" + l + "] + ' ' ") ok ok ok next else Result = Result + NumStr[:n0] ok   Return trim(Result)  
http://rosettacode.org/wiki/Four_is_magic
Four is magic
Task Write a subroutine, function, whatever it may be called in your language, that takes an integer number and returns an English text sequence starting with the English cardinal representation of that integer, the word 'is' and then the English cardinal representation of the count of characters that made up the first word, followed by a comma. Continue the sequence by using the previous count word as the first word of the next phrase, append 'is' and the cardinal count of the letters in that word. Continue until you reach four. Since four has four characters, finish by adding the words 'four is magic' and a period. All integers will eventually wind up at four. For instance, suppose your are given the integer 3. Convert 3 to Three, add is , then the cardinal character count of three, or five, with a comma to separate if from the next phrase. Continue the sequence five is four, (five has four letters), and finally, four is magic. Three is five, five is four, four is magic. For reference, here are outputs for 0 through 9. Zero is four, four is magic. One is three, three is five, five is four, four is magic. Two is three, three is five, five is four, four is magic. Three is five, five is four, four is magic. Four is magic. Five is four, four is magic. Six is three, three is five, five is four, four is magic. Seven is five, five is four, four is magic. Eight is five, five is four, four is magic. Nine is four, four is magic. Some task guidelines You may assume the input will only contain integer numbers. Cardinal numbers between 20 and 100 may use either hyphens or spaces as word separators but they must use a word separator. (23 is twenty three or twenty-three not twentythree.) Cardinal number conversions should follow the English short scale. (billion is 1e9, trillion is 1e12, etc.) Cardinal numbers should not include commas. (20140 is twenty thousand one hundred forty not twenty thousand, one hundred forty.) When converted to a string, 100 should be one hundred, not a hundred or hundred, 1000 should be one thousand, not a thousand or thousand. When converted to a string, there should be no and in the cardinal string. 130 should be one hundred thirty not one hundred and thirty. When counting characters, count all of the characters in the cardinal number including spaces and hyphens. One hundred fifty-one should be 21 not 18. The output should follow the format "N is K, K is M, M is ... four is magic." (unless the input is 4, in which case the output should simply be "four is magic.") The output can either be the return value from the function, or be displayed from within the function. You are encouraged, though not mandated to use proper sentence capitalization. You may optionally support negative numbers. -7 is negative seven. Show the output here for a small representative sample of values, at least 5 but no more than 25. You are free to choose which which numbers to use for output demonstration. You can choose to use a library, (module, external routine, whatever) to do the cardinal conversions as long as the code is easily and freely available to the public. If you roll your own, make the routine accept at minimum any integer from 0 up to 999999. If you use a pre-made library, support at least up to unsigned 64 bit integers. (or the largest integer supported in your language if it is less.) Four is magic is a popular code-golf task. This is not code golf. Write legible, idiomatic and well formatted code. Related tasks   Four is the number of_letters in the ...   Look-and-say sequence   Number names   Self-describing numbers   Summarize and say sequence   Spelling of ordinal numbers   De Bruijn sequences
#Ruby
Ruby
module NumberToWord   NUMBERS = { # taken from https://en.wikipedia.org/wiki/Names_of_large_numbers#cite_ref-a_14-3 1 => 'one', 2 => 'two', 3 => 'three', 4 => 'four', 5 => 'five', 6 => 'six', 7 => 'seven', 8 => 'eight', 9 => 'nine', 10 => 'ten', 11 => 'eleven', 12 => 'twelve', 13 => 'thirteen', 14 => 'fourteen', 15 => 'fifteen', 16 => 'sixteen', 17 => 'seventeen', 18 => 'eighteen', 19 => 'nineteen', 20 => 'twenty', 30 => 'thirty', 40 => 'forty', 50 => 'fifty', 60 => 'sixty', 70 => 'seventy', 80 => 'eighty', 90 => 'ninety', 100 => 'hundred', 1000 => 'thousand', 10 ** 6 => 'million', 10 ** 9 => 'billion', 10 ** 12 => 'trillion', 10 ** 15 => 'quadrillion', 10 ** 18 => 'quintillion', 10 ** 21 => 'sextillion', 10 ** 24 => 'septillion', 10 ** 27 => 'octillion', 10 ** 30 => 'nonillion', 10 ** 33 => 'decillion'}.reverse_each.to_h   refine Integer do def to_english return 'zero' if i.zero? words = self < 0 ? ['negative'] : [] i = self.abs NUMBERS.each do |k, v| if k <= i then times = i/k words << times.to_english if k >= 100 words << v i -= times * k end return words.join(" ") if i.zero? end end end   end   using NumberToWord   def magic4(n) words = [] until n == 4 s = n.to_english n = s.size words << "#{s} is #{n.to_english}" end words << "four is magic." words.join(", ").capitalize end   [0, 4, 6, 11, 13, 75, 337, -164, 9_876_543_209].each{|n| puts magic4(n) }  
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.
#BASIC
BASIC
  100 : 110 REM FLOYD'S TRIANGLE 120 : 130 DEF FN Q(A) = INT ( LOG (A) / LOG (10)) + 1 140 N = 14 150 DIM P(N): P(0) = - 1: FOR J = 1 TO N: I = (N * N - N) / 2 + J 160 P(J) = P(J - 1) + FN Q(I) + 1: NEXT J 200 FOR R = 1 TO N: FOR C = 1 TO R 210 NR = NR + 1:COL = P(C) - ( FN Q(NR) - 1) 220 HTAB COL: PRINT NR;: NEXT C 230 PRINT : NEXT R  
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)
#Groovy
Groovy
class FloydWarshall { static void main(String[] args) { int[][] weights = [[1, 3, -2], [2, 1, 4], [2, 3, 3], [3, 4, 2], [4, 2, -1]] int numVertices = 4   floydWarshall(weights, numVertices) }   static void floydWarshall(int[][] weights, int numVertices) { double[][] dist = new double[numVertices][numVertices] for (double[] row : dist) { Arrays.fill(row, Double.POSITIVE_INFINITY) }   for (int[] w : weights) { dist[w[0] - 1][w[1] - 1] = w[2] }   int[][] next = new int[numVertices][numVertices] for (int i = 0; i < next.length; i++) { for (int j = 0; j < next.length; j++) { if (i != j) { next[i][j] = j + 1 } } }   for (int k = 0; k < numVertices; k++) { for (int i = 0; i < numVertices; i++) { for (int j = 0; j < numVertices; j++) { 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) }   static void printResult(double[][] dist, int[][] next) { println("pair dist path") for (int i = 0; i < next.length; i++) { for (int j = 0; j < next.length; j++) { if (i != j) { int u = i + 1 int v = j + 1 String path = String.format("%d -> %d  %2d  %s", u, v, (int) dist[i][j], u) boolean loop = true while (loop) { u = next[u - 1][v - 1] path += " -> " + u loop = u != v } println(path) } } } } }
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
#R
R
mult <- function(a,b) a*b
http://rosettacode.org/wiki/Forward_difference
Forward difference
Task Provide code that produces a list of numbers which is the   nth  order forward difference, given a non-negative integer (specifying the order) and a list of numbers. The first-order forward difference of a list of numbers   A   is a new list   B,   where   Bn = An+1 - An. List   B   should have one fewer element as a result. The second-order forward difference of   A   will be: tdefmodule Diff do def forward(arr,i\\1) do forward(arr,[],i) end def forward([_|[]],diffs,i) do if i == 1 do IO.inspect diffs else forward(diffs,[],i-1) end end def forward([val1|[val2|vals]],diffs,i) do forward([val2|vals],diffs++[val2-val1],i) end end The same as the first-order forward difference of   B. That new list will have two fewer elements than   A   and one less than   B. The goal of this task is to repeat this process up to the desired order. For a more formal description, see the related   Mathworld article. Algorithmic options Iterate through all previous forward differences and re-calculate a new array each time. Use this formula (from Wikipedia): Δ n [ f ] ( x ) = ∑ k = 0 n ( n k ) ( − 1 ) n − k f ( x + k ) {\displaystyle \Delta ^{n}[f](x)=\sum _{k=0}^{n}{n \choose k}(-1)^{n-k}f(x+k)} (Pascal's Triangle   may be useful for this option.)
#Lambdatalk
Lambdatalk
  {def fdiff {lambda {:l} {A.new {S.map {{lambda {:l :i} {- {A.get {+ :i 1} :l} {A.get :i :l}} } :l} {S.serie 0 {- {A.length :l} 2}}}}}} -> fdiff   {def disp {lambda {:l} {if {A.empty? {A.rest :l}} then else {let { {:l {fdiff :l}} } {br}:l {disp :l}}}}} -> disp   {def L {A.new 90 47 58 29 22 32 55 5 55 73}} -> L   {disp {L}} -> [-43,11,-29,-7,10,23,-50,50,18] [54,-40,22,17,13,-73,100,-32] [-94,62,-5,-4,-86,173,-132] [156,-67,1,-82,259,-305] [-223,68,-83,341,-564] [291,-151,424,-905] [-442,575,-1329] [1017,-1904] [-2921]  
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
#XLISP
XLISP
(DISPLAY "Hello world!") (NEWLINE)
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.
#Perl
Perl
printf "%09.3f\n", 7.125;
http://rosettacode.org/wiki/Formatted_numeric_output
Formatted numeric output
Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
#Phix
Phix
printf(1,"%09.3f\n",7.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).
#M2000_Interpreter
M2000 Interpreter
  Module FourBitAdder { Flush dim not(0 to 1),and(0 to 1, 0 to 1),or(0 to 1, 0 to 1) not(0)=1,0 and(0,0)=0,0,0,1 or(0,0)=0,1,1,1 xor=lambda not(),and(),or() (a,b)-> or(and(a, not(b)), and(b, not(a))) ha=lambda xor, and() (a,b, &s, &c)->{ s=xor(a,b) c=and(a,b) } fa=lambda ha, or() (a, b, c0, &s, &c1)->{ def sa,ca,cb call ha(a, c0, &sa, &ca) call ha(sa, b, &s,&cb) c1=or(ca,cb) } add4=lambda fa (inpA(), inpB(), &v, &out()) ->{ dim carry(0 to 4)=0 carry(0)=v \\ 0 or 1 borrow for i=0 to 3 \\ mm=fa(InpA(i), inpB(i), carry(i), &out(i), &carry(i+1)) ' same as this Call fa(InpA(i), inpB(i), carry(i), &out(i), &carry(i+1)) next v=carry(4) } dim res(0 to 3)=-1, low() source=lambda->{ shift 1, -stack.size ' reverse stack items =array([]) ' convert current stack to array, empty current stack } def v, k, k_low Print "First Example 4-bit" Print "A", "", 1, 0, 1, 0 Print "B", "", 1, 0, 0, 1 call add4(source(1,0,1,0), source(1,0,0,1), &v, &res()) k=each(res() end to start) ' k is an iterator, now configure to read items in reverse Print "A+B",v, k ' print 1 0 0 1 1 Print "Second Example 4-bit" v-=v Print "A", "", 0, 1, 1, 0 Print "B", "", 0, 1, 1, 1 call add4(source(0,1,1,0), source(0,1,1,1), &v, &res()) k=each(res() end to start) ' k is an iterator, now configure to read items in reverse Print "A+B",v, k ' print 0 1 1 0 1 Print "Third Example 8-bit" v-=v Print "A ", "", 1, 0, 0, 0, 0, 1, 1, 0 Print "B ", "", 1, 1, 1, 1, 1, 1, 1, 1 call add4(source(0,1,1,0), source(1,1,1,1), &v, &res()) low()=res() ' a copy of res() ' v passed to second adder dim res(0 to 3)=-1 call add4(source(1,0,0,0), source(1,1,1,1), &v, &res()) k_low=each(low() end to start) ' k_low is an iterator, now configure to read items in reverse k=each(res() end to start) ' k is an iterator, now configure to read items in reverse Print "A+B",v, k, k_low ' print 1 1 0 0 0 0 1 0 1 } FourBitAdder  
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.
#ALGOL_68
ALGOL 68
BEGIN # construct an R-style fivenum function # PR read "rows.incl.a68" PR   PROC fivenum = ( []REAL array )[]REAL: BEGIN INT n = ( UPB array + 1 ) - LWB array; [ 1 : n ]REAL x := array[ AT 1 ]; QUICKSORT x FROMELEMENT LWB x TOELEMENT UPB x; REAL n4 = ( ( ( n + IF ODD n THEN 3 ELSE 2 FI ) / 2 ) / 2 ) ; []REAL d = ( 1, n4, ( n + 1 ) / 2, n + 1 - n4, n ); [ 1 : 5 ]REAL sum_array; FOR e TO 5 DO INT fl = ENTIER d[ e ]; INT ce = IF fl < d[ e ] THEN 1 + fl ELSE fl FI; sum_array[ e ] := 0.5 * ( x[ fl ] + x[ ce ] ) OD; sum_array END # five num # ;   SHOW fivenum( ( 36, 40, 7, 39, 41, 15 ) ); print( ( newline ) ); SHOW fivenum( ( 15, 6, 42, 41, 7, 36, 49, 40, 39, 47, 43 ) ); print( ( newline ) ); SHOW fivenum( ( 0.14082834, 0.09748790, 1.73131507, 0.87636009 , -1.95059594, 0.73438555, -0.03035726, 1.46675970 , -0.74621349, -0.72588772, 0.63905160, 0.61501527 , -0.98983780, -1.00447874, -0.62759469, 0.66206163 , 1.04312009, -0.10305385, 0.75775634, 0.32566578 ) ) END
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.
#Clojure
Clojure
  (def burn-prob 0.1) (def new-tree-prob 0.5)   (defn grow-new-tree? [] (> new-tree-prob (rand))) (defn burn-tree? [] (> burn-prob (rand))) (defn tree-maker [] (if (grow-new-tree?) :tree :grass))   (defn make-forest ([] (make-forest 5)) ([size] (take size (repeatedly #(take size (repeatedly tree-maker))))))   (defn tree-at [forest row col] (try (-> forest (nth row) (nth col)) (catch Exception _ false)))   (defn neighbores-burning? [forest row col] (letfn [(burnt? [row col] (= :burnt (tree-at forest row col)))] (or (burnt? (inc row) col) (burnt? (dec row) col) (burnt? row (inc col)) (burnt? row (dec col)))))   (defn lightning-strike [forest] (map (fn [forest-row] (map #(if (and (= % :tree) (burn-tree?))  :fire! %) forest-row) ) forest))   (defn burn-out-trees [forest] (map (fn [forest-row] (map #(case %  :burnt :grass  :fire! :burnt %) forest-row)) forest))   (defn burn-neighbores [forest] (let [forest-size (count forest) indicies (partition forest-size (for [row (range forest-size) col (range forest-size)] (cons row (list col))))] (map (fn [forest-row indicies-row] (map #(if (and (= :tree %) (neighbores-burning? forest (first %2) (second %2)))  :fire! %) forest-row indicies-row)) forest indicies)))   (defn grow-new-trees [forest] (map (fn [forest-row] (map #(if (= % :grass) (tree-maker) %) forest-row)) forest))   (defn forest-fire ([] (forest-fire 5)) ([forest-size] (loop [forest (make-forest forest-size)] (pprint forest) (Thread/sleep 300) (-> forest (burn-out-trees) (lightning-strike) (burn-neighbores) (grow-new-trees) (recur)))))   (forest-fire)    
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
#BQN
BQN
Enlist ← {(∾𝕊¨)⍟(1<≡)⥊𝕩}
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.
#Go
Go
package main   import ( "fmt" "math/rand" "time" )   func main() {   rand.Seed(time.Now().UnixNano())   var n int = 3 // Change to define board size var moves int = 0   a := make([][]int, n) for i := range a { a[i] = make([]int, n) for j := range a { a[i][j] = rand.Intn(2) } }   b := make([][]int, len(a)) for i := range a { b[i] = make([]int, len(a[i])) copy(b[i], a[i]) }   for i := rand.Intn(100); i > 0 || compareSlices(a, b) == true; i-- { b = flipCol(b, rand.Intn(n) + 1) b = flipRow(b, rand.Intn(n) + 1) }   fmt.Println("Target:") drawBoard(a) fmt.Println("\nBoard:") drawBoard(b)   var rc rune var num int   for { for{ fmt.Printf("\nFlip row (r) or column (c) 1 .. %d (c1, ...): ", n) _, err := fmt.Scanf("%c%d", &rc, &num) if err != nil { fmt.Println(err) continue } if num < 1 || num > n { fmt.Println("Wrong command!") continue } break }   switch rc { case 'c': fmt.Printf("Column %v will be flipped\n", num) flipCol(b, num) case 'r': fmt.Printf("Row %v will be flipped\n", num) flipRow(b, num) default: fmt.Println("Wrong command!") continue }   moves++ fmt.Println("\nMoves taken: ", moves)   fmt.Println("Target:") drawBoard(a) fmt.Println("\nBoard:") drawBoard(b)   if compareSlices(a, b) { fmt.Printf("Finished. You win with %d moves!\n", moves) break } } }   func drawBoard (m [][]int) { fmt.Print(" ") for i := range m { fmt.Printf("%d ", i+1) } for i := range m { fmt.Println() fmt.Printf("%d ", i+1) for _, val := range m[i] { fmt.Printf(" %d", val) } } fmt.Print("\n") }   func flipRow(m [][]int, row int) ([][]int) { for j := range m { m[row-1][j] ^= 1 } return m }   func flipCol(m [][]int, col int) ([][]int) { for j := range m { m[j][col-1] ^= 1 } return m }   func compareSlices(m [][]int, n[][]int) bool { o := true for i := range m { for j := range m { if m[i][j] != n[i][j] { o = false } } } return o }
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.
#C.23
C#
// a mini chrestomathy solution   using System;   class Program {   // translated from java example static long js(int l, int n) { long res = 0, f = 1; double lf = Math.Log10(2); for (int i = l; i > 10; i /= 10) f *= 10; while (n > 0) if ((int)(f * Math.Pow(10, ++res * lf % 1)) == l) n--; return res; }   // translated from go integer example (a.k.a. go translation of pascal alternative example) static long gi(int ld, int n) { string Ls = ld.ToString(); long res = 0, count = 0, f = 1; for (int i = 1; i <= 18 - Ls.Length; i++) f *= 10; const long ten18 = (long)1e18; long probe = 1; do { probe <<= 1; res++; if (probe >= ten18) do { if (probe >= ten18) probe /= 10; if (probe / f == ld) if (++count >= n) { count--; break; } probe <<= 1; res++; } while (true); string ps = probe.ToString(); if (ps.Substring(0, Math.Min(Ls.Length, ps.Length)) == Ls) if (++count >= n) break; } while (true); return res; }   // translated from pascal alternative example static long pa(int ld, int n) { double L_float64 = Math.Pow(2, 64); ulong Log10_2_64 = (ulong)(L_float64 * Math.Log10(2)); double Log10Num; ulong LmtUpper, LmtLower, Frac64; long res = 0, dgts = 1, cnt; for (int i = ld; i >= 10; i /= 10) dgts *= 10; Log10Num = Math.Log10((ld + 1.0) / dgts); // '316' was a limit if (Log10Num >= 0.5) { LmtUpper = (ld + 1.0) / dgts < 10.0 ? (ulong)(Log10Num * (L_float64 * 0.5)) * 2 + (ulong)(Log10Num * 2) : 0; Log10Num = Math.Log10((double)ld / dgts); LmtLower = (ulong)(Log10Num * (L_float64 * 0.5)) * 2 + (ulong)(Log10Num * 2); } else { LmtUpper = (ulong)(Log10Num * L_float64); LmtLower = (ulong)(Math.Log10((double)ld / dgts) * L_float64); } cnt = 0; Frac64 = 0; if (LmtUpper != 0) do { res++; Frac64 += Log10_2_64; if ((Frac64 >= LmtLower) & (Frac64 < LmtUpper)) if (++cnt >= n) break; } while (true); else // '999..' do { res++; Frac64 += Log10_2_64; if (Frac64 >= LmtLower) if (++cnt >= n) break; } while (true); return res; }   static int[] values = new int[] { 12, 1, 12, 2, 123, 45, 123, 12345, 123, 678910, 99, 1 };   static void doOne(string name, Func<int, int, long> fun) { Console.WriteLine("{0} version:", name); var start = DateTime.Now; for (int i = 0; i < values.Length; i += 2) Console.WriteLine("p({0,3}, {1,6}) = {2,11:n0}", values[i], values[i + 1], fun(values[i], values[i + 1])); Console.WriteLine("Took {0} seconds\n", DateTime.Now - start); }   static void Main() { doOne("java simple", js); doOne("go integer", gi); doOne("pascal alternative", pa); } }
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
#Clojure
Clojure
(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 numbers [x y z]) (def invers [xi yi zi])   (defn multiplier [a b] (fn [m] (* a b m)))   > (for [[n i] (zipmap numbers invers)] ((multiplier n i) 0.5)) (0.5 0.5 0.5)
http://rosettacode.org/wiki/First-class_functions/Use_numbers_analogously
First-class functions/Use numbers analogously
In First-class functions, a language is showing how its manipulation of functions is similar to its manipulation of other types. This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers. Write a program to create an ordered collection of a mixture of literally typed and expressions producing a real number, together with another ordered collection of their multiplicative inverses. Try and use the following pseudo-code to generate the numbers for the ordered collections: x = 2.0 xi = 0.5 y = 4.0 yi = 0.25 z = x + y zi = 1.0 / ( x + y ) Create a function multiplier, that given two numbers as arguments returns a function that when called with one argument, returns the result of multiplying the two arguments to the call to multiplier that created it and the argument in the call: new_function = multiplier(n1,n2) # where new_function(m) returns the result of n1 * n2 * m Applying the multiplier of a number and its inverse from the two ordered collections of numbers in pairs, show that the result in each case is one. Compare and contrast the resultant program with the corresponding entry in First-class functions. They should be close. To paraphrase the task description: Do what was done before, but with numbers rather than functions
#Common_Lisp
Common Lisp
(defun multiplier (f g) #'(lambda (x) (* f g x)))   (let* ((x 2.0) (xi 0.5) (y 4.0) (yi 0.25) (z (+ x y)) (zi (/ 1.0 (+ x y))) (numbers (list x y z)) (inverses (list xi yi zi))) (loop with value = 0.5 for number in numbers for inverse in inverses for multiplier = (multiplier number inverse) do (format t "~&(~A * ~A)(~A) = ~A~%" number inverse value (funcall multiplier value))))
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
#HicEst
HicEst
1 GOTO 2 ! branch to label   2 READ(FIle=name, IOStat=ios, ERror=3) something ! on error branch to label 3   3 ALARM(delay, n) ! n=2...9 simulate F2 to F9 keys: call asynchronously "Alarm"-SUBROUTINES F2...F9 with a delay   4 ALARM( 1 ) ! lets HicEst wait at this statement for any keyboard or mouse event   5 SYSTEM(WAIT=1000) ! msec   6 XEQ('CALL my_subroutine', *7) ! executes command string, on error branch to label 7   7 y = EXP(1E100, *8) ! on error branch to label 8   8 y = LOG( 0 , *9) ! on error branch to label 9   9 ALARM( 999 ) ! quit HicEst immediately
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
#Icon_and_Unicon
Icon and Unicon
  if x := every i := 1 to *container do { # * is the 'length' operator if container[i] ~== y then write("item ", i, " is not interesting") else break a } then write("found item ", x) else write("did not find an item")  
http://rosettacode.org/wiki/Four_is_magic
Four is magic
Task Write a subroutine, function, whatever it may be called in your language, that takes an integer number and returns an English text sequence starting with the English cardinal representation of that integer, the word 'is' and then the English cardinal representation of the count of characters that made up the first word, followed by a comma. Continue the sequence by using the previous count word as the first word of the next phrase, append 'is' and the cardinal count of the letters in that word. Continue until you reach four. Since four has four characters, finish by adding the words 'four is magic' and a period. All integers will eventually wind up at four. For instance, suppose your are given the integer 3. Convert 3 to Three, add is , then the cardinal character count of three, or five, with a comma to separate if from the next phrase. Continue the sequence five is four, (five has four letters), and finally, four is magic. Three is five, five is four, four is magic. For reference, here are outputs for 0 through 9. Zero is four, four is magic. One is three, three is five, five is four, four is magic. Two is three, three is five, five is four, four is magic. Three is five, five is four, four is magic. Four is magic. Five is four, four is magic. Six is three, three is five, five is four, four is magic. Seven is five, five is four, four is magic. Eight is five, five is four, four is magic. Nine is four, four is magic. Some task guidelines You may assume the input will only contain integer numbers. Cardinal numbers between 20 and 100 may use either hyphens or spaces as word separators but they must use a word separator. (23 is twenty three or twenty-three not twentythree.) Cardinal number conversions should follow the English short scale. (billion is 1e9, trillion is 1e12, etc.) Cardinal numbers should not include commas. (20140 is twenty thousand one hundred forty not twenty thousand, one hundred forty.) When converted to a string, 100 should be one hundred, not a hundred or hundred, 1000 should be one thousand, not a thousand or thousand. When converted to a string, there should be no and in the cardinal string. 130 should be one hundred thirty not one hundred and thirty. When counting characters, count all of the characters in the cardinal number including spaces and hyphens. One hundred fifty-one should be 21 not 18. The output should follow the format "N is K, K is M, M is ... four is magic." (unless the input is 4, in which case the output should simply be "four is magic.") The output can either be the return value from the function, or be displayed from within the function. You are encouraged, though not mandated to use proper sentence capitalization. You may optionally support negative numbers. -7 is negative seven. Show the output here for a small representative sample of values, at least 5 but no more than 25. You are free to choose which which numbers to use for output demonstration. You can choose to use a library, (module, external routine, whatever) to do the cardinal conversions as long as the code is easily and freely available to the public. If you roll your own, make the routine accept at minimum any integer from 0 up to 999999. If you use a pre-made library, support at least up to unsigned 64 bit integers. (or the largest integer supported in your language if it is less.) Four is magic is a popular code-golf task. This is not code golf. Write legible, idiomatic and well formatted code. Related tasks   Four is the number of_letters in the ...   Look-and-say sequence   Number names   Self-describing numbers   Summarize and say sequence   Spelling of ordinal numbers   De Bruijn sequences
#Rust
Rust
fn main() { magic(4); magic(2_340); magic(765_000); magic(27_000_001); magic(999_123_090); magic(239_579_832_723_441); magic(std::u64::MAX); }   fn magic(num: u64) { if num == 4 { println!("four is magic!"); println!(); return; } let name = number_name(num); let len = name.len() as u64; print!("{} is {}, ", name, number_name(len)); magic(len); }     const LOW: &'static [&'static str] = &[ "zero", "one", "two", "three", "four", "five", "six", "seven", "eight","nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" ]; const MED: &'static [&'static str] = &[ "twenty", "thirty", "forty", "fifty", "sixy", "seventy", "eighty", "ninety" ]; const HIGH: &'static [&'static str] = &[ "thousand", "million", "billion", "trillion", "quadrillion", "quintillion" ];   fn number_name(num: u64) -> String { if num < 20 { return LOW[num as usize].to_string(); } if num < 100 { let index = ((num / 10) - 2) as usize; let tens = MED[index].to_string(); let remainder = num % 10; if remainder > 0 { return format!("{}-{}", tens, number_name(remainder)); } return tens; } if num < 1000 { let hundreds = LOW[(num / 100) as usize]; let remainder = num % 100; if remainder > 0 { return format!("{} hundred {}", hundreds, number_name(remainder)); } return format!("{} hundred", hundreds); }   let mut remainder = num % 1000; let mut cur = if remainder > 0 { number_name(remainder) } else { "".to_string() }; let mut n = num / 1000;   for noun in HIGH.iter() { if n > 0 { remainder = n % 1000; if remainder > 0 { // this condition resolves double space issues cur = if cur.len() > 0 { format!("{} {} {}", number_name(remainder), noun, cur ) } else { format!("{} {}", number_name(remainder), noun) } } n /= 1000; } } return cur; }
http://rosettacode.org/wiki/Four_is_magic
Four is magic
Task Write a subroutine, function, whatever it may be called in your language, that takes an integer number and returns an English text sequence starting with the English cardinal representation of that integer, the word 'is' and then the English cardinal representation of the count of characters that made up the first word, followed by a comma. Continue the sequence by using the previous count word as the first word of the next phrase, append 'is' and the cardinal count of the letters in that word. Continue until you reach four. Since four has four characters, finish by adding the words 'four is magic' and a period. All integers will eventually wind up at four. For instance, suppose your are given the integer 3. Convert 3 to Three, add is , then the cardinal character count of three, or five, with a comma to separate if from the next phrase. Continue the sequence five is four, (five has four letters), and finally, four is magic. Three is five, five is four, four is magic. For reference, here are outputs for 0 through 9. Zero is four, four is magic. One is three, three is five, five is four, four is magic. Two is three, three is five, five is four, four is magic. Three is five, five is four, four is magic. Four is magic. Five is four, four is magic. Six is three, three is five, five is four, four is magic. Seven is five, five is four, four is magic. Eight is five, five is four, four is magic. Nine is four, four is magic. Some task guidelines You may assume the input will only contain integer numbers. Cardinal numbers between 20 and 100 may use either hyphens or spaces as word separators but they must use a word separator. (23 is twenty three or twenty-three not twentythree.) Cardinal number conversions should follow the English short scale. (billion is 1e9, trillion is 1e12, etc.) Cardinal numbers should not include commas. (20140 is twenty thousand one hundred forty not twenty thousand, one hundred forty.) When converted to a string, 100 should be one hundred, not a hundred or hundred, 1000 should be one thousand, not a thousand or thousand. When converted to a string, there should be no and in the cardinal string. 130 should be one hundred thirty not one hundred and thirty. When counting characters, count all of the characters in the cardinal number including spaces and hyphens. One hundred fifty-one should be 21 not 18. The output should follow the format "N is K, K is M, M is ... four is magic." (unless the input is 4, in which case the output should simply be "four is magic.") The output can either be the return value from the function, or be displayed from within the function. You are encouraged, though not mandated to use proper sentence capitalization. You may optionally support negative numbers. -7 is negative seven. Show the output here for a small representative sample of values, at least 5 but no more than 25. You are free to choose which which numbers to use for output demonstration. You can choose to use a library, (module, external routine, whatever) to do the cardinal conversions as long as the code is easily and freely available to the public. If you roll your own, make the routine accept at minimum any integer from 0 up to 999999. If you use a pre-made library, support at least up to unsigned 64 bit integers. (or the largest integer supported in your language if it is less.) Four is magic is a popular code-golf task. This is not code golf. Write legible, idiomatic and well formatted code. Related tasks   Four is the number of_letters in the ...   Look-and-say sequence   Number names   Self-describing numbers   Summarize and say sequence   Spelling of ordinal numbers   De Bruijn sequences
#Sidef
Sidef
func cardinal(n) { static lingua_en = frequire("Lingua::EN::Numbers") lingua_en.num2en(n) - / and|,/g }   func four_is_magic(n) { var str = "" loop { str += (cardinal(n) + " is ") if (n == 4) { str += "magic." break } else { n = cardinal(n).len str += (cardinal(n) + ", ") } } str.tc }   [0, 4, 6, 11, 13, 75, 337, -164, 9_876_543_209].each { |n| say four_is_magic(n) }
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.
#Batch_File
Batch File
:: Floyd's triangle Task from Rosetta Code :: Batch File Implementation   @echo off rem main thing setlocal enabledelayedexpansion call :floydtriangle 5 echo( call :floydtriangle 14 exit /b 0   :floydtriangle set "fila=%1" for /l %%c in (1,1,%fila%) do ( set /a "lastRowNum=%%c+fila*(fila-1)/2" rem count number of digits of whole number trick rem source: https://stackoverflow.com/a/45472269 set /a "Log=1!lastRowNum:~1!-!lastRowNum:~1!-0" set /a "numColum[%%c]=!Log:0=+1!" ) echo(Output for %fila% set "thisNum=1" for /l %%r in (1,1,%fila%) do ( set "printLine=" for /l %%c in (1,1,%%r) do ( rem count number of digits of whole number trick set /a "Log=1!thisNum:~1!-!thisNum:~1!-0" set /a "thisNumColum=!Log:0=+1!" rem handle spacing set "space= " set /a "extra=!numColum[%%c]!-!thisNumColum!" for /l %%s in (1,1,!extra!) do set "space=!space! " rem append current number to printLine set "printLine=!printLine!!space!!thisNum!" set /a "thisNum=!thisNum!+1" ) echo(!printLine! ) goto :EOF
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)
#Haskell
Haskell
import Control.Monad (join) import Data.List (union) import Data.Map hiding (foldr, union) import Data.Maybe (fromJust, isJust) import Data.Semigroup import Prelude hiding (lookup, filter)
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
#Racket
Racket
(define (multiply a b) (* a b))
http://rosettacode.org/wiki/Function_definition
Function definition
A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract from showing how functions are created and values returned). Related task   Function prototype
#Raku
Raku
sub multiply { return @_[0] * @_[1]; }
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.)
#Lasso
Lasso
#!/usr/bin/lasso9   define forwardDiff(values, order::integer=1) => {  !#order ? return #values->asArray local(result = array) iterate(#values) => { loop_count < #values->size ? #result->insert(#values->get(loop_count+1) - #values->get(loop_count)) } #order > 1 ? #result = forwardDiff(#result, #order-1) return #result }   local(data = (:90, 47, 58, 29, 22, 32, 55, 5, 55, 73)) with x in generateSeries(0, #data->size-1) do stdoutnl(#x + ': ' + forwardDiff(#data, #x))
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.)
#Logo
Logo
to fwd.diff :l if empty? :l [output []] if empty? bf :l [output []] output fput (first bf :l)-(first :l) fwd.diff bf :l end to nth.fwd.diff :n :l if :n = 0 [output :l] output nth.fwd.diff :n-1 fwd.diff :l end   show nth.fwd.diff 9 [90 47 58 29 22 32 55 5 55 73] [-2921]
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
#XPL0
XPL0
code Text=12; Text(0, "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
#XPath
XPath
'Hello world&#xA;'
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.
#PHP
PHP
echo str_pad(7.125, 9, '0', STR_PAD_LEFT);
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).
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
and[a_, b_] := Max[a, b]; or[a_, b_] := Min[a, b]; not[a_] := 1 - a; xor[a_, b_] := or[and[a, not[b]], and[b, not[a]]]; halfadder[a_, b_] := {xor[a, b], and[a, b]}; fulladder[a_, b_, c0_] := Module[{s, c, c1}, {s, c} = halfadder[c0, a]; {s, c1} = halfadder[s, b]; {s, or[c, c1]}]; fourbitadder[{a3_, a2_, a1_, a0_}, {b3_, b2_, b1_, b0_}] := Module[{s0, s1, s2, s3, c0, c1, c2, c3}, {s0, c0} = fulladder[a0, b0, 0]; {s1, c1} = fulladder[a1, b1, c0]; {s2, c2} = fulladder[a2, b2, c1]; {s3, c3} = fulladder[a3, b3, c2]; {{s3, s2, s1, s0}, c3}];
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.
#AppleScript
AppleScript
use AppleScript version "2.4" -- Mac OS X 10.10. (Yosemite) or later. use framework "Foundation"   on fivenum(listOfNumbers, l, r) script o property lst : missing value   on medianFromRange(l, r) set m1 to (l + r) div 2 set m2 to m1 + (l + r) mod 2 set median to my lst's item m1 if (m2 > m1) then set median to (median + (my lst's item m2)) / 2   return {median, m1, m2} end medianFromRange end script   if ((listOfNumbers is {}) or (r - l < 0)) then return missing value set o's lst to current application's class "NSMutableArray"'s arrayWithArray:(listOfNumbers) tell o's lst to sortUsingSelector:("compare:") set o's lst to o's lst as list   set {median, m1, m2} to o's medianFromRange(l, r) set {lowerQuartile} to o's medianFromRange(l, m1) set {upperQuartile} to o's medianFromRange(m2, r)   return {o's lst's beginning, lowerQuartile, median, upperQuartile, o's lst's end} end fivenum   -- Test code: set x to {15, 6, 42, 41, 7, 36, 49, 40, 39, 47, 43} set y to {36, 40, 7, 39, 41, 15} set z to {0.14082834, 0.0974879, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.4667597, -0.74621349, -0.72588772, ¬ 0.6390516, 0.61501527, -0.9898378, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578} return {fivenum(x, 1, count x), fivenum(y, 1, count y), fivenum(z, 1, count z)}
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.
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. forest-fire.   DATA DIVISION. WORKING-STORAGE SECTION. *> Probability represents a fraction of 10000. *> For instance, IGNITE-PROB means a tree has a 1 in 10000 chance *> of igniting. 78 IGNITE-PROB VALUE 1. 78 NEW-TREE-PROB VALUE 100.   78 EMPTY-PROB VALUE 3333.   78 AREA-SIZE VALUE 40.   01 sim-table. 03 sim-row OCCURS AREA-SIZE TIMES INDEXED BY row-index. 05 sim-area OCCURS AREA-SIZE TIMES INDEXED BY col-index. 07 current-status PIC 9. *> The flags correspond to the colours they will *> be displayed as. 88 empty VALUE 0. *> Black 88 tree VALUE 2. *> Green 88 burning VALUE 4. *> Red   07 next-status PIC 9. 88 empty VALUE 0. 88 tree VALUE 2. 88 burning VALUE 4.   01 rand-num PIC 9999.   01 next-row PIC 9(4). 01 next-col PIC 9(4).   01 neighbours-row PIC 9(4). 01 neighbours-col PIC 9(4).   PROCEDURE DIVISION. main-line. *> Seed RANDOM with current time. MOVE FUNCTION RANDOM(FUNCTION CURRENT-DATE (9:8)) TO rand-num   PERFORM initialise-table PERFORM FOREVER PERFORM show-simulation PERFORM step-simulation END-PERFORM   GOBACK .   initialise-table. PERFORM VARYING row-index FROM 1 BY 1 UNTIL AREA-SIZE < row-index AFTER col-index FROM 1 BY 1 UNTIL AREA-SIZE < col-index PERFORM get-rand-num IF rand-num <= EMPTY-PROB SET empty OF current-status (row-index, col-index) TO TRUE SET empty OF next-status (row-index, col-index) TO TRUE ELSE SET tree OF current-status (row-index, col-index) TO TRUE SET tree OF next-status (row-index, col-index) TO TRUE END-IF END-PERFORM .   show-simulation. PERFORM VARYING row-index FROM 1 BY 1 UNTIL AREA-SIZE < row-index AFTER col-index FROM 1 BY 1 UNTIL AREA-SIZE < col-index DISPLAY SPACE AT LINE row-index COLUMN col-index WITH BACKGROUND-COLOR current-status (row-index, col-index) END-PERFORM .   *> Updates the simulation. step-simulation. PERFORM VARYING row-index FROM 1 BY 1 UNTIL AREA-SIZE < row-index AFTER col-index FROM 1 BY 1 UNTIL AREA-SIZE < col-index EVALUATE TRUE WHEN empty OF current-status (row-index, col-index) PERFORM get-rand-num IF rand-num <= NEW-TREE-PROB SET tree OF next-status (row-index, col-index) TO TRUE END-IF   WHEN tree OF current-status (row-index, col-index) PERFORM simulate-tree   WHEN burning OF current-status (row-index, col-index) SET empty OF next-status (row-index, col-index) TO TRUE END-EVALUATE END-PERFORM   PERFORM update-statuses. .   *> Updates a tree tile, assuming row-index and col-index are at *> a tree area. simulate-tree. *> Find the row and column of the bottom-right neighbour. COMPUTE next-row = FUNCTION MIN(row-index + 1, AREA-SIZE) COMPUTE next-col = FUNCTION MIN(col-index + 1, AREA-SIZE)   COMPUTE neighbours-row = FUNCTION MAX(row-index - 1, 1) COMPUTE neighbours-col = FUNCTION MAX(col-index - 1, 1)   *> If a neighbour is burning, catch fire. PERFORM VARYING neighbours-row FROM neighbours-row BY 1 UNTIL next-row < neighbours-row *> Check if neighbours in a row are on fire. PERFORM VARYING neighbours-col FROM neighbours-col BY 1 UNTIL next-col < neighbours-col IF neighbours-row = row-index AND neighbours-col = col-index EXIT PERFORM CYCLE END-IF   IF burning OF current-status (neighbours-row, neighbours-col) SET burning OF next-status (row-index, col-index) TO TRUE EXIT PARAGRAPH END-IF END-PERFORM   *> Move neighbours-col back to starting position COMPUTE neighbours-col = FUNCTION MAX(neighbours-col - 3, 1) END-PERFORM   *> Otherwise, there is a random chance of *> catching fire. PERFORM get-rand-num IF rand-num <= IGNITE-PROB SET burning OF next-status (row-index, col-index) TO TRUE END-IF .   update-statuses. PERFORM VARYING row-index FROM 1 BY 1 UNTIL AREA-SIZE < row-index AFTER col-index FROM 1 BY 1 UNTIL AREA-SIZE < col-index MOVE next-status (row-index, col-index) TO current-status (row-index, col-index) END-PERFORM .   *> Puts a random value between 0 and 9999 in rand-num. get-rand-num. COMPUTE rand-num = FUNCTION MOD(FUNCTION RANDOM * 100000, 10000) .
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
#Bracmat
Bracmat
  ( (myList = ((1), 2, ((3,4), 5), ((())), (((6))), 7, 8, ())) & put$("Unevaluated:") & lst$myList & !myList:?myList { the expression !myList evaluates myList } & put$("Flattened:") & lst$myList )  
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.
#Haskell
Haskell
import Data.List (intersperse)   import System.Random (randomRIO)   import Data.Array (Array, (!), (//), array, bounds)   import Control.Monad (zipWithM_, replicateM, foldM, when)   type Board = Array (Char, Char) Int   flp :: Int -> Int flp 0 = 1 flp 1 = 0   numRows, numCols :: Board -> String numRows t = let ((a, _), (b, _)) = bounds t in [a .. b]   numCols t = let ((_, a), (_, b)) = bounds t in [a .. b]   flipRow, flipCol :: Board -> Char -> Board flipRow t r = let e = [ (ix, flp (t ! ix)) | ix <- zip (repeat r) (numCols t) ] in t // e   flipCol t c = let e = [ (ix, flp (t ! ix)) | ix <- zip (numRows t) (repeat c) ] in t // e   printBoard :: Board -> IO () printBoard t = do let rows = numRows t cols = numCols t f 0 = '0' f 1 = '1' p r xs = putStrLn $ [r, ' '] ++ intersperse ' ' (map f xs) putStrLn $ " " ++ intersperse ' ' cols zipWithM_ p rows [ [ t ! (y, x) | x <- cols ] | y <- rows ]   -- create a random goal board, and flip rows and columns randomly -- to get a starting board setupGame :: Char -> Char -> IO (Board, Board) setupGame sizey sizex -- random cell value at (row, col) = do let mk rc = (\v -> (rc, v)) <$> randomRIO (0, 1) rows = ['a' .. sizey] cols = ['1' .. sizex] goal <- array (('a', '1'), (sizey, sizex)) <$> mapM mk [ (r, c) | r <- rows , c <- cols ] start <- do let change :: Board -> Int -> IO Board -- flip random row change t 0 = flipRow t <$> randomRIO ('a', sizey) -- flip random col change t 1 = flipCol t <$> randomRIO ('1', sizex) numMoves <- randomRIO (3, 15) -- how many flips (3 - 15) -- determine if rows or cols are flipped moves <- replicateM numMoves $ randomRIO (0, 1) -- make changes and get a starting board foldM change goal moves if goal /= start -- check if boards are different then return (goal, start) -- all ok, return both boards else setupGame sizey sizex -- try again   main :: IO () main = do putStrLn "Select a board size (1 - 9).\nPress any other key to exit." sizec <- getChar when (sizec `elem` ['1' .. '9']) $ do let size = read [sizec] - 1 (g, s) <- setupGame (['a' ..] !! size) (['1' ..] !! size) turns g s 0 where turns goal current moves = do putStrLn "\nGoal:" printBoard goal putStrLn "\nBoard:" printBoard current when (moves > 0) $ putStrLn $ "\nYou've made " ++ show moves ++ " moves so far." putStrLn $ "\nFlip a row (" ++ numRows current ++ ") or a column (" ++ numCols current ++ ")" v <- getChar if v `elem` numRows current then check $ flipRow current v else if v `elem` numCols current then check $ flipCol current v else tryAgain where check t = if t == goal then putStrLn $ "\nYou've won in " ++ show (moves + 1) ++ " moves!" else turns goal t (moves + 1) tryAgain = do putStrLn ": Invalid row or column." turns goal current moves
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.
#D
D
import std.math; import std.stdio;   int p(int l, int n) { int test = 0; double logv = log(2.0) / log(10.0); int factor = 1; int loop = l; while (loop > 10) { factor *= 10; loop /= 10; } while (n > 0) { int val;   test++; val = cast(int)(factor * pow(10.0, fmod(test * logv, 1))); if (val == l) { n--; } } return test; }   void runTest(int l, int n) { writefln("p(%d, %d) = %d", l, n, p(l, n)); }   void main() { runTest(12, 1); runTest(12, 2); runTest(123, 45); runTest(123, 12345); runTest(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
#D
D
import std.stdio;   auto multiplier(double a, double b) { return (double c) => a * b * c; }   void main() { double x = 2.0; double xi = 0.5; double y = 4.0; double yi = 0.25; double z = x + y; double zi = 1.0 / (z);   double[3] f = [x, y, z]; double[3] r = [xi, yi, zi];   foreach (i; 0..3) { auto mult = multiplier(f[i], r[i]); writefln("%f * %f * %f == %f", f[i], r[i], 1.0, mult(1)); } }
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
#E
E
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 forward := [x, y, z ] def reverse := [xi, yi, zi]   def multiplier(a, b) { return fn x { a * b * x } }   def s := 0.5 for i => a in forward { def b := reverse[i] println(`s = $s, a = $a, b = $b, multiplier($a, $b)($s) = ${multiplier(a, b)(s)}`) }
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
#IDL
IDL
test: ..some code here goto, test
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
#J
J
2 * 1 2 3 2 4 6