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/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
#Swift
Swift
import Foundation   func fourIsMagic(_ number: NSNumber) -> String { let formatter = NumberFormatter() formatter.numberStyle = .spellOut formatter.locale = Locale(identifier: "en_EN")   var result: [String] = []   var numberString = formatter.string(from: number)! result.append(numberString.capitalized)   while numberString != "four" { numberString = formatter.string(from: NSNumber(value: numberString.count))! result.append(contentsOf: [" is ", numberString, ", ", numberString]) }   result.append(" is magic.") return result.joined() }   for testInput in [23, 1000000000, 20140, 100, 130, 151, -7] { print(fourIsMagic(testInput as NSNumber)) }
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
#UNIX_Shell
UNIX Shell
#!/usr/bin/env bash name_of() { # return the English name for a numeric value local -i n=$1   if (( n < 0 )); then printf 'negative %s\n' "$(name_of $(( -n )))" return 0 fi   # Names for numbers that fit in a bash integer local -A names=([0]=zero [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 [1000000]=million [1000000000]=billion [1000000000000]=trillion [1000000000000000]=quadrillion [1000000000000000000]=quintillion)   # The powers of 10 above 10, in descending order local powers_of_10=($(printf '%s\n' "${!names[@]}" | sort -nr | grep '00$'))   # find the largest power of 10 that is smaller than n local -i i=0 local -i p=${powers_of_10[i]} while (( p > n && i < ${#powers_of_10[@]}-1 )); do i=i+1 p=${powers_of_10[$i]} done   # if we found one, split on it and construct quotient 'name' remainder if (( n >= p )); then local -i quotient=n/p local -i remainder=n%p local remname= if (( remainder > 0 )); then remname=$(name_of $remainder) fi printf '%s %s\n' "$(name_of $quotient)" "${names[$p]}${remname:+ $remname}" elif (( n > 20 )); then # things are a little different under 100, since the multiples of # 10 have their own names local -i remainder=n%10 local -i tens=n-remainder local remname= if (( remainder > 0 )); then remname=-$(name_of $remainder) fi printf '%s\n' "${names[$tens]}${remname:+$remname}" else printf '%s\n' "${names[$n]}" fi   return 0 }   # Convert numbers into the length of their names # Display the series of values in name form until # the length turns into four; then terminate with "four is magic." # Again, takes a second argument, this time a prefix, to # facilitate tail recursion. four_is_magic() { local -i n=$1 local prefix=$2 local name=$(name_of $n)   # capitalize the first entry if [[ -z $prefix ]]; then name=${name^} fi   # Stop at 4, otherwise count the length of the name and recurse if (( $n == 4 )); then printf '%s%s is magic.\n' "${prefix:+$prefix, }" "$name" else local -i len=${#name} four_is_magic "$len" "${prefix:+$prefix, }$name is $(name_of $len)" fi }
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.
#BCPL
BCPL
get "libhdr"   let width(n) = n<10 -> 1, 1 + width(n/10)   let floyd(rows) be $( let maxno = rows * (rows+1)/2 let num = 1 for r = 1 to rows $( for c = 1 to r $( writed(num, 1 + width(maxno-rows+c)) num := num + 1 $) wrch('*N') $) $)   let start() be $( floyd(5) wrch('*N') floyd(14) $)
http://rosettacode.org/wiki/Floyd%27s_triangle
Floyd's triangle
Floyd's triangle   lists the natural numbers in a right triangle aligned to the left where the first row is   1     (unity) successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above. The first few lines of a Floyd triangle looks like this: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Task Write a program to generate and display here the first   n   lines of a Floyd triangle. (Use   n=5   and   n=14   rows). Ensure that when displayed in a mono-space font, the numbers line up in vertical columns as shown and that only one space separates numbers of the last row.
#Befunge
Befunge
0" :seniL">:#,_&>:!#@_55+,:00p::1+*2/1v vv+1:\-1p01g5-\g00<v`*9"o"\+`"c"\`9:::_ $>>\:::9`\"c"`+\9v:>>+00g1-:00p5p1-00g^ <v\*84-\g01+`*"o"<^<<p00:+1\+1/2*+1:::\ ^>:#\1#,-#:\_$$.\:#^_$$>>1+\1-55+,:!#@_
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)
#Icon
Icon
# # Floyd-Warshall algorithm. # # See https://en.wikipedia.org/w/index.php?title=Floyd%E2%80%93Warshall_algorithm&oldid=1082310013 #   record fw_results (n, distance, next_vertex)   link array link numbers link printf   procedure main () local example_graph local fw local u, v   example_graph := [[1, -2.0, 3], [3, +2.0, 4], [4, -1.0, 2], [2, +4.0, 1], [2, +3.0, 3]]   fw := floyd_warshall (example_graph)   printf (" pair distance path\n") printf ("-------------------------------------\n") every u := 1 to fw.n do { every v := 1 to fw.n do { if u ~= v then { printf (" %d -> %d  %4s  %s\n", u, v, string (ref_array (fw.distance, u, v)), path_to_string (find_path (fw.next_vertex, u, v))) } } } end   procedure floyd_warshall (edges) local n, distance, next_vertex local e local i, j, k local dist_ij, dist_ik, dist_kj, dist_ikj   n := max_vertex (edges) distance := create_array ([1, 1], [n, n], &null) next_vertex := create_array ([1, 1], [n, n], &null)   # Initialization. every e := !edges do { ref_array (distance, e[1], e[3]) := e[2] ref_array (next_vertex, e[1], e[3]) := e[3] } every i := 1 to n do { ref_array (distance, i, i) := 0.0 # Distance to self = 0. ref_array (next_vertex, i, i) := i }   # Perform the algorithm. Here &null will play the role of # "infinity": "\" means a value is finite, "/" that it is infinite. every k := 1 to n do { every i := 1 to n do { every j := 1 to n do { dist_ij := ref_array (distance, i, j) dist_ik := ref_array (distance, i, k) dist_kj := ref_array (distance, k, j) if \dist_ik & \dist_kj then { dist_ikj := dist_ik + dist_kj if /dist_ij | dist_ikj < dist_ij then { ref_array (distance, i, j) := dist_ikj ref_array (next_vertex, i, j) := ref_array (next_vertex, i, k) } } } } }   return fw_results (n, distance, next_vertex) end   procedure find_path (next_vertex, u, v) local path   if / (ref_array (next_vertex, u, v)) then { path := [] } else { path := [u] while u ~= v do { u := ref_array (next_vertex, u, v) put (path, u) } } return path end   procedure path_to_string (path) local s   if *path = 0 then { s := "" } else { s := string (path[1]) every s ||:= (" -> " || !path[2 : 0]) } return s end   procedure max_vertex (edges) local e local m   *edges = 0 & stop ("no edges") m := 1 every e := !edges do m := max (m, e[1], e[3]) return m end
http://rosettacode.org/wiki/Function_definition
Function definition
A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract from showing how functions are created and values returned). Related task   Function prototype
#Raven
Raven
define multiply use 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
#REALbasic
REALbasic
  Function Multiply(a As Integer, b As Integer) As Integer Return a * b End Function  
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.)
#Lua
Lua
function dif(a, b, ...) if(b) then return b-a, dif(b, ...) end end function dift(t) return {dif(unpack(t))} end print(unpack(dift{1,3,6,10,15}))
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
#XSLT
XSLT
<xsl:text>Hello world! </xsl:text>
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
#Yabasic
Yabasic
  print "Hello world!"  
http://rosettacode.org/wiki/Formatted_numeric_output
Formatted numeric output
Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
#PicoLisp
PicoLisp
(pad 9 (format 7125 3)) (pad 9 (format 7125 3 ",")) # European format
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.
#PL.2FI
PL/I
  put edit (X) (p'999999.V999'); /* Western format. */   put edit (X) (p'999999,V999'); /* In European format. */    
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).
#MATLAB_.2F_Octave
MATLAB / Octave
function [S,v] = fourBitAdder(input1,input2)   %Make sure that only 4-Bit numbers are being added. This assumes that %if input1 and input2 are a vector of multiple decimal numbers, then %the binary form of these vectors are an n by 4 matrix. assert((size(input1,2) == 4) && (size(input2,2) == 4),'This will only work on 4-Bit Numbers');   %Converts MATLAB binary strings to matricies of 1 and 0 function mat = binStr2Mat(binStr) mat = zeros(size(binStr)); for i = (1:numel(binStr)) mat(i) = str2double(binStr(i)); end end   %XOR decleration function AxorB = xor(A,B) AxorB = or(and(A,not(B)),and(B,not(A))); end   %Half-Adder decleration function [S,C] = halfAdder(A,B) S = xor(A,B); C = and(A,B); end   %Full-Adder decleration function [S,Co] = fullAdder(A,B,Ci) [SAdder1,CAdder1] = halfAdder(Ci,A); [S,CAdder2] = halfAdder(SAdder1,B); Co = or(CAdder1,CAdder2); end   %The rest of this code is the 4-bit adder   binStrFlag = false; %A flag to determine if the original input was a binary string   %If either of the inputs was a binary string, convert it to a matrix of %1's and 0's. if ischar(input1) input1 = binStr2Mat(input1); binStrFlag = true; end if ischar(input2) input2 = binStr2Mat(input2); binStrFlag = true; end   %This does the addition S = zeros(size(input1));   [S(:,4),Co] = fullAdder(input1(:,4),input2(:,4),0); [S(:,3),Co] = fullAdder(input1(:,3),input2(:,3),Co); [S(:,2),Co] = fullAdder(input1(:,2),input2(:,2),Co); [S(:,1),v] = fullAdder(input1(:,1),input2(:,1),Co);   %If the original inputs were binary strings, convert the output of the %4-bit adder to a binary string with the same formatting as the %original binary strings. if binStrFlag S = num2str(S); v = num2str(v); end end %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.
#Arturo
Arturo
fivenum: function [lst][ lst: sort lst m: (size lst)/2 lowerEnd: (odd? size lst)? -> m -> m-1   return @[ first lst median slice lst 0 lowerEnd median slice lst 0 dec size lst median slice lst m dec size lst last lst ] ]   lists: @[ @[15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0], @[36.0, 40.0, 7.0, 39.0, 41.0, 15.0], @[0.14082834, 0.09748790, 1.73131507, 0.87636009,0-1.95059594, 0.73438555,0-0.03035726, 1.46675970,0-0.74621349,0-0.72588772, 0.63905160, 0.61501527,0-0.98983780,0-1.00447874,0-0.62759469, 0.66206163, 1.04312009,0-0.10305385, 0.75775634, 0.32566578] ]   loop lists 'l [ print [l "->"] print [fivenum l] print "" ]
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.
#Common_Lisp
Common Lisp
(defvar *dims* '(10 10)) (defvar *prob-t* 0.5) (defvar *prob-f* 0.1) (defvar *prob-p* 0.01)   (defmacro with-gensyms (names &body body) `(let ,(mapcar (lambda (n) (list n '(gensym))) names) ,@body))   (defmacro traverse-grid (grid rowvar colvar (&rest after-cols) &body body) (with-gensyms (dims rows cols) `(let* ((,dims (array-dimensions ,grid)) (,rows (car ,dims)) (,cols (cadr ,dims))) (dotimes (,rowvar ,rows ,grid) (dotimes (,colvar ,cols ,after-cols) ,@body)))))   (defun make-new-forest (&optional (dims *dims*)) (let ((forest (make-array dims :element-type 'symbol :initial-element 'void))) (traverse-grid forest row col nil (if (<= (random 1.0) *prob-t*) (setf (aref forest row col) 'tree)))))   (defun print-forest (forest) (traverse-grid forest row col (terpri) (ecase (aref forest row col) ((void) (write-char #\space)) ((tree) (write-char #\T)) ((fire) (write-char #\#)))) (values))   (defvar *neighboring* '((-1 . -1) (-1 . 0) (-1 . 1) (0 . -1) (0 . 1) (1 . -1) (1 . 0) (1 . 1)))   (defun neighbors (forest row col) (loop for n in *neighboring* for nrow = (+ row (car n)) for ncol = (+ col (cdr n)) when (array-in-bounds-p forest nrow ncol) collect (aref forest nrow ncol)))   (defun evolve-tree (forest row col) (let ((tree (aref forest row col))) (cond ((eq tree 'fire) ;; if the tree was on fire, it's dead Jim 'void) ((and (eq tree 'tree) ;; if a neighbor is on fire, it's on fire too (find 'fire (neighbors forest row col) :test #'eq)) 'fire) ((and (eq tree 'tree) ;; random chance of fire happening (<= (random 1.0) *prob-f*)) 'fire) ((and (eq tree 'void) ;; random chance of empty space becoming a tree (<= (random 1.0) *prob-p*)) 'tree) (t tree))))   (defun evolve-forest (forest) (let* ((dims (array-dimensions forest)) (new (make-array dims :element-type 'symbol :initial-element 'void))) (traverse-grid forest row col nil (setf (aref new row col) (evolve-tree forest row col))) new))   (defun simulate (forest n &optional (print-all t)) (format t "------ Initial forest ------~%") (print-forest forest) (dotimes (i n) (setf forest (evolve-forest forest)) (when print-all (progn (format t "~%------ Generation ~d ------~%" (1+ i)) (print-forest forest)))))  
http://rosettacode.org/wiki/First_class_environments
First class environments
According to Wikipedia, "In computing, a first-class object ... is an entity that can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable". Often this term is used in the context of "first class functions". In an analogous way, a programming language may support "first class environments". The environment is minimally, the set of variables accessible to a statement being executed. Change the environments and the same statement could produce different results when executed. Often an environment is captured in a closure, which encapsulates a function together with an environment. That environment, however, is not first-class, as it cannot be created, passed etc. independently from the function's code. Therefore, a first class environment is a set of variable bindings which can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable. It is like a closure without code. A statement must be able to be executed within a stored first class environment and act according to the environment variable values stored within. Task Build a dozen environments, and a single piece of code to be run repeatedly in each of these environments. Each environment contains the bindings for two variables:   a value in the Hailstone sequence, and   a count which is incremented until the value drops to 1. The initial hailstone values are 1 through 12, and the count in each environment is zero. When the code runs, it calculates the next hailstone step in the current environment (unless the value is already 1) and counts the steps. Then it prints the current value in a tabular form. When all hailstone values dropped to 1, processing stops, and the total number of hailstone steps for each environment is printed.
#BBC_BASIC
BBC BASIC
DIM @environ$(12) @% = 4 : REM Column width   REM Initialise: FOR E% = 1 TO 12 PROCsetenvironment(@environ$(E%)) seq% = E% cnt% = 0 @environ$(E%) = FNgetenvironment NEXT   REM Run hailstone sequences: REPEAT T% = 0 FOR E% = 1 TO 12 PROCsetenvironment(@environ$(E%)) PRINT seq% ; IF seq% <> 1 THEN T% += 1 cnt% += 1 IF seq% AND 1 seq% = 3 * seq% + 1 ELSE seq% DIV= 2 ENDIF @environ$(E%) = FNgetenvironment NEXT PRINT UNTIL T% = 0   REM Print counts: PRINT "Counts:" FOR E% = 1 TO 12 PROCsetenvironment(@environ$(E%)) PRINT cnt% ; @environ$(E%) = FNgetenvironment NEXT PRINT END   DEF FNgetenvironment LOCAL e$ : e$ = STRING$(216, CHR$0) SYS "RtlMoveMemory", !^e$, ^@%+108, 216 = e$   DEF PROCsetenvironment(e$) IF LEN(e$) < 216 e$ = STRING$(216, CHR$0) SYS "RtlMoveMemory", ^@%+108, !^e$, 216 ENDPROC
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
#Brat
Brat
array.prototype.flatten = { true? my.empty? { [] } { true? my.first.array? { my.first.flatten + my.rest.flatten } { [my.first] + my.rest.flatten } } }   list = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []] p "List: #{list}" p "Flattened: #{list.flatten}"
http://rosettacode.org/wiki/Flipping_bits_game
Flipping bits game
The game Given an   N×N   square array of zeroes or ones in an initial configuration,   and a target configuration of zeroes and ones. The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered columns at once   (as one move). In an inversion.   any  1  becomes  0,   and any  0  becomes  1  for that whole row or column. Task Create a program to score for the Flipping bits game. The game should create an original random target configuration and a starting configuration. Ensure that the starting position is never the target position. The target position must be guaranteed as reachable from the starting position.   (One possible way to do this is to generate the start position by legal flips from a random target position.   The flips will always be reversible back to the target from the given start position). The number of moves taken so far should be shown. Show an example of a short game here, on this page, for a   3×3   array of bits.
#J
J
start=:3 :0 Moves=:0 N=:i.y Board=: ?2$~,~y 'fr fc'=. (2,y)$}.#:(+?&.<:@<:)2x^2*y End=: fr~:fc~:"1 Board Board;End )   abc=:'abcdefghij' move=:3 :0 fc=. N e.abc i. y ([-.-.)abc fr=. N e._-.~_ "."0 abc-.~":y Board=: fr~:fc~:"1 Board smoutput (":Moves=:Moves++/fr,fc),' moves' if. Board-:End do. 'yes' else. Board;End end. )
http://rosettacode.org/wiki/First_power_of_2_that_has_leading_decimal_digits_of_12
First power of 2 that has leading decimal digits of 12
(This task is taken from a   Project Euler   problem.) (All numbers herein are expressed in base ten.) 27   =   128   and   7   is the first power of   2   whose leading decimal digits are   12. The next power of   2   whose leading decimal digits are   12   is   80, 280   =   1208925819614629174706176. Define     p(L,n)     to be the nth-smallest value of   j   such that the base ten representation of   2j   begins with the digits of   L . So p(12, 1) = 7 and p(12, 2) = 80 You are also given that: p(123, 45)   =   12710 Task   find:   p(12, 1)   p(12, 2)   p(123, 45)   p(123, 12345)   p(123, 678910)   display the results here, on this page.
#Delphi
Delphi
  // First power of 2 that has specified leading decimal digits. Nigel Galloway: March 14th., 2021 let fG n g=let fN l=let l=10.0**(l-floor l) in l>=n && l<g in let f=log10 2.0 in seq{1..0x0FFFFFFF}|>Seq.filter(float>>(*)f>>fN) printfn "p(23,1)->%d" (int(Seq.item 0 (fG 2.3 2.4))) printfn "p(99,1)->%d" (int(Seq.item 0 (fG 9.9 10.0))) printfn "p(12,1)->%d" (int(Seq.item 0 (fG 1.2 1.3))) printfn "p(12,2)->%d" (int(Seq.item 1 (fG 1.2 1.3))) printfn "p(123,45)->%d" (int(Seq.item 44 (fG 1.23 1.24))) printfn "p(123,12345)->%d" (int(Seq.item 12344 (fG 1.23 1.24))) printfn "p(123,678910)->%d" (int(Seq.item 678909 (fG 1.23 1.24)))  
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
#Elena
Elena
import system'routines; import extensions;   public program() { real x := 2.0r; real xi := 0.5r; real y := 4.0r; real yi := 0.25r; real z := x + y; real zi := 1.0r / (x + y);   var numlist := new real[]{ x, y, z }; var numlisti := new real[]{ xi, yi, zi };   var multiplied := numlist.zipBy(numlisti, (n1,n2 => (m => n1 * n2 * m) )).toArray();   multiplied.forEach:(multiplier){ console.printLine(multiplier(0.5r)) } }
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
#Erlang
Erlang
  -module( first_class_functions_use_numbers ).   -export( [task/0] ).   task() -> X = 2.0, Xi = 0.5, Y = 4.0, Yi = 0.25, Z = X + Y, Zi = 1.0 / (X + Y), As = [X, Y, Z], Bs = [Xi, Yi, Zi], [io:fwrite( "Value: 2.5 Result: ~p~n", [(multiplier(A, B))(2.5)]) || {A, B} <- lists:zip(As, Bs)].       multiplier( N1, N2 ) -> fun(M) -> N1 * N2 * M 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
#Java
Java
switch (xx) { case 1: case 2: /* 1 & 2 both come here... */ ... break; case 4: /* 4 comes here... */ ... break; case 5: /* 5 comes here... */ ... break; default: /* everything else */ break; }   for (int i = 0; i < 10; ++i) { ... if (some_condition) { break; } ... }   _Time_: do { for (int i = 0; i < 10; ++i) { ... if (some_condition) { break _Time_; /* terminate the do-while loop */} ... } ... } while (thisCondition);
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
#JavaScript
JavaScript
$ jq -n '1, (2 | label $foo | debug | 3 | break $foo | debug), 4' 1 ["DEBUG:",2] 4
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
#Vlang
Vlang
import math fn main() { for n in [i64(0), 4, 6, 11, 13, 75, 100, 337, -164, math.max_i64, ] { println(four_is_magic(n)) } }   fn four_is_magic(nn i64) string { mut n := nn mut s := say(n) s = s[..1].to_upper() + s[1..] mut t := s for n != 4 { n = i64(s.len) s = say(n) t += " is " + s + ", " + s } t += " is magic." return t }   const small = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"] const tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"] const illions = ["", " thousand", " million", " billion", " trillion", " quadrillion", " quintillion"]   fn say(nn i64) string { mut t := '' mut n := nn if n < 0 { t = "negative " // Note, for math.MinInt64 this leaves n negative. n = -n } match true { n < 20 { t += small[n] } n < 100 { t += tens[n/10] s := n % 10 if s > 0 { t += "-" + small[s] } } n < 1000 { t += small[n/100] + " hundred" s := n % 100 if s > 0 { t += " " + say(s) } } else { // work right-to-left mut sx := "" for i := 0; n > 0; i++ { p := n % 1000 n /= 1000 if p > 0 { mut ix := say(p) + illions[i] if sx != "" { ix += " " + sx } sx = ix } } t += sx } } return t }
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
#Wren
Wren
import "/str" for Str   var small = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]   var tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]   var illions = ["", " thousand", " million", " billion"," trillion", " quadrillion", " quintillion"]   var say say = Fn.new { |n| var t = "" if (n < 0) { t = "negative " n = -n } if (n < 20) { t = t + small[n] } else if (n < 100) { t = t + tens[(n/10).floor] var s = n % 10 if (s > 0) t = t + "-" + small[s] } else if (n < 1000) { t = t + small[(n/100).floor] + " hundred" var s = n % 100 System.write("") // guards against VM recursion bug if (s > 0) t = t + " " + say.call(s) } else { var sx = "" var i = 0 while (n > 0) { var p = n % 1000 n = (n/1000).floor if (p > 0) { System.write("") // guards against VM recursion bug var ix = say.call(p) + illions[i] if (sx != "") ix = ix + " " + sx sx = ix } i = i + 1 } t = t + sx } return t }   var fourIsMagic = Fn.new { |n| var s = Str.capitalize(say.call(n)) var t = s while (n != 4) { n = s.count s = say.call(n) t = t + " is " + s + ", " + s } return t + " is magic." }   for (n in [0, 4, 6, 11, 13, 75, 100, 337, -164, 9007199254740991]) { System.print(fourIsMagic.call(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.
#Bracmat
Bracmat
( ( floyd = lowerLeftCorner lastInColumn lastInRow row i W w . put$(str$("Floyd " !arg ":\n")) &  !arg*(!arg+-1)*1/2+1  : ?lowerLeftCorner  : ?lastInColumn & 1:?lastInRow:?row:?i & whl ' ( !row:~>!arg & @(!lastInColumn:? [?W) & @(!i:? [?w) & whl'(!w+1:~>!W:?w&put$" ") & put$!i & (  !i:<!lastInRow & put$" " & 1+!lastInColumn:?lastInColumn | put$\n & (1+!row:?row)+!lastInRow:?lastInRow & !lowerLeftCorner:?lastInColumn ) & 1+!i:?i ) ) & floyd$5 & floyd$14 );
http://rosettacode.org/wiki/Floyd%27s_triangle
Floyd's triangle
Floyd's triangle   lists the natural numbers in a right triangle aligned to the left where the first row is   1     (unity) successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above. The first few lines of a Floyd triangle looks like this: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Task Write a program to generate and display here the first   n   lines of a Floyd triangle. (Use   n=5   and   n=14   rows). Ensure that when displayed in a mono-space font, the numbers line up in vertical columns as shown and that only one space separates numbers of the last row.
#C
C
#include <stdio.h>   void t(int n) { int i, j, c, len;   i = n * (n - 1) / 2; for (len = c = 1; c < i; c *= 10, len++); c -= i; // c is the col where width changes   #define SPEED_MATTERS 0 #if SPEED_MATTERS // in case we really, really wanted to print huge triangles often char tmp[32], s[4096], *p;   sprintf(tmp, "%*d", len, 0);   inline void inc_numstr(void) { int k = len;   redo: if (!k--) return;   if (tmp[k] == '9') { tmp[k] = '0'; goto redo; }   if (++tmp[k] == '!') tmp[k] = '1'; }   for (p = s, i = 1; i <= n; i++) { for (j = 1; j <= i; j++) { inc_numstr(); __builtin_memcpy(p, tmp + 1 - (j >= c), len - (j < c)); p += len - (j < c);   *(p++) = (i - j)? ' ' : '\n';   if (p - s + len >= 4096) { fwrite(s, 1, p - s, stdout); p = s; } } }   fwrite(s, 1, p - s, stdout); #else // NO_IT_DOESN'T int num; for (num = i = 1; i <= n; i++) for (j = 1; j <= i; j++) printf("%*d%c", len - (j < c), num++, i - j ? ' ':'\n'); #endif }   int main(void) { t(5), t(14);   // maybe not // t(10000); return 0; }
http://rosettacode.org/wiki/Floyd-Warshall_algorithm
Floyd-Warshall algorithm
The Floyd–Warshall algorithm is an algorithm for finding shortest paths in a weighted graph with positive or negative edge weights. Task Find the lengths of the shortest paths between all pairs of vertices of the given directed graph. Your code may assume that the input has already been checked for loops, parallel edges and negative cycles. Print the pair, the distance and (optionally) the path. Example pair dist path 1 -> 2 -1 1 -> 3 -> 4 -> 2 1 -> 3 -2 1 -> 3 1 -> 4 0 1 -> 3 -> 4 2 -> 1 4 2 -> 1 2 -> 3 2 2 -> 1 -> 3 2 -> 4 4 2 -> 1 -> 3 -> 4 3 -> 1 5 3 -> 4 -> 2 -> 1 3 -> 2 1 3 -> 4 -> 2 3 -> 4 2 3 -> 4 4 -> 1 3 4 -> 2 -> 1 4 -> 2 -1 4 -> 2 4 -> 3 1 4 -> 2 -> 1 -> 3 See also Floyd-Warshall Algorithm - step by step guide (youtube)
#J
J
floyd=: verb define for_j. i.#y do. y=. y <. j ({"1 +/ {) y 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
#REBOL
REBOL
multiply: func [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
#Relation
Relation
  function multiply(a,b) set result = a*b end function  
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.)
#M2000_Interpreter
M2000 Interpreter
  Form 80, 40 Module Forward_difference { Print $(0,6) ' 6 characters column Dim a(), b() a()=(90,47,58,29,22,32,55,5,55,73) Function Diff(a()) { for i=0 to len(a())-2: a(i)=a(i+1)-a(i):Next i Dim a(len(a())-1) ' redim one less =a() } Print "Original:","",a() b()=a() ' copy a() to b() k=1 While len(b())>1 { b()=Diff(b()) ' copy returned array to b() Print "Difference ";k;":",b() k++ } } Forward_difference    
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.)
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
i={3,5,12,1,6,19,6,2,4,9}; Differences[i]
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
#Yorick
Yorick
write, "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.
#Pop11
Pop11
;;; field of length 12, 3 digits after decimal place format_print('~12,3,0,`*,`0F', [1299.19]); ;;; prints "00001299.190" format_print('~12,3,0,`*,`0F', [100000000000000000]); ;;; Since the number does not fit into the field prints "************" ;;; that is stars instead of the number format_print('~12,3,0,`*,`0F', [-1299.19]); ;;; prints "000-1299.190" ;;; that is _leading zeros_ before sign   format_print('~3,1,12,`0:$', [1299.19]); ;;; prints "00001299.190" format_print('~3,1,12,`0:$', [-1299.19]); ;;; prints "-0001299.190" ;;; that is sign before leading zeros format_print('~3,1,12,`0:$', [100000000000000000]); ;;; prints "100000000000000000.000" ;;; that is uses more space if the number does not fit into ;;; fixed width
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.
#PowerShell
PowerShell
'{0:00000.000}' -f 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).
#MUMPS
MUMPS
XOR(Y,Z) ;Uses logicals - i.e., 0 is false, anything else is true (1 is used if setting a value) QUIT (Y&'Z)!('Y&Z) HALF(W,X) QUIT $$XOR(W,X)_"^"_(W&X) FULL(U,V,CF) NEW F1,F2 S F1=$$HALF(U,V) S F2=$$HALF($P(F1,"^",1),CF) QUIT $P(F2,"^",1)_"^"_($P(F1,"^",2)!($P(F2,"^",2))) FOUR(Y,Z,C4) NEW S,I,T FOR I=4:-1:1 SET T=$$FULL($E(Y,I),$E(Z,I),C4),$E(S,I)=$P(T,"^",1),C4=$P(T,"^",2) K I,T QUIT S_"^"_C4
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.
#C
C
#include <stdio.h> #include <stdlib.h>   double median(double *x, int start, int end_inclusive) { int size = end_inclusive - start + 1; if (size <= 0) { printf("Array slice cannot be empty\n"); exit(1); } int m = start + size / 2; if (size % 2) return x[m]; return (x[m - 1] + x[m]) / 2.0; }   int compare (const void *a, const void *b) { double aa = *(double*)a; double bb = *(double*)b; if (aa > bb) return 1; if (aa < bb) return -1; return 0; }   int fivenum(double *x, double *result, int x_len) { int i, m, lower_end; for (i = 0; i < x_len; i++) { if (x[i] != x[i]) { printf("Unable to deal with arrays containing NaN\n\n"); return 1; } } qsort(x, x_len, sizeof(double), compare); result[0] = x[0]; result[2] = median(x, 0, x_len - 1); result[4] = x[x_len - 1]; m = x_len / 2; lower_end = (x_len % 2) ? m : m - 1; result[1] = median(x, 0, lower_end); result[3] = median(x, m, x_len - 1); return 0; }   int show(double *result, int places) { int i; char f[7]; sprintf(f, "%%.%dlf", places); printf("["); for (i = 0; i < 5; i++) { printf(f, result[i]); if (i < 4) printf(", "); } printf("]\n\n"); }   int main() { double result[5];   double x1[11] = {15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0}; if (!fivenum(x1, result, 11)) show(result, 1);   double x2[6] = {36.0, 40.0, 7.0, 39.0, 41.0, 15.0}; if (!fivenum(x2, result, 6)) show(result, 1);   double x3[20] = { 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 }; if (!fivenum(x3, result, 20)) show(result, 9);   return 0; }
http://rosettacode.org/wiki/First-class_functions
First-class functions
A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming: Create new functions from preexisting functions at run-time Store functions in collections Use functions as arguments to other functions Use functions as return values of other functions Task Write a program to create an ordered collection A of functions of a real number. At least one function should be built-in and at least one should be user-defined; try using the sine, cosine, and cubing functions. Fill another collection B with the inverse of each function in A. Implement function composition as in Functional Composition. Finally, demonstrate that the result of applying the composition of each function in A and its inverse in B to a value, is the original value. (Within the limits of computational accuracy). (A solution need not actually call the collections "A" and "B". These names are only used in the preceding paragraph for clarity.) Related task First-class Numbers
#ActionScript
ActionScript
  var cube:Function = function(x) { return Math.pow(x, 3); }; var cuberoot:Function = function(x) { return Math.pow(x, 1/3); };   function compose(f:Function, g:Function):Function { return function(x:Number) {return f(g(x));}; } var functions:Array = [Math.cos, Math.tan, cube]; var inverse:Array = [Math.acos, Math.atan, cuberoot];   function test() { for (var i:uint = 0; i < functions.length; i++) { // Applying the composition to 0.5 trace(compose(functions[i], inverse[i])(0.5)); } }   test();
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.
#D
D
import std.stdio, std.random, std.string, std.algorithm;   enum treeProb = 0.55; // Original tree probability. enum fProb = 0.01; // Auto combustion probability. enum cProb = 0.01; // Tree creation probability.   enum Cell : char { empty=' ', tree='T', fire='#' } alias World = Cell[][];   bool hasBurningNeighbours(in World world, in ulong r, in ulong c) pure nothrow @safe @nogc { foreach (immutable rowShift; -1 .. 2) foreach (immutable colShift; -1 .. 2) if ((r + rowShift) >= 0 && (r + rowShift) < world.length && (c + colShift) >= 0 && (c + colShift) < world[0].length && world[r + rowShift][c + colShift] == Cell.fire) return true; return false; }   void nextState(in World world, World nextWorld) /*nothrow*/ @safe /*@nogc*/ { foreach (r, row; world) foreach (c, elem; row) final switch (elem) with (Cell) { case empty: nextWorld[r][c]= (uniform01 < cProb) ? tree : empty; break;   case tree: if (world.hasBurningNeighbours(r, c)) nextWorld[r][c] = fire; else nextWorld[r][c] = (uniform01 < fProb) ? fire : tree; break;   case fire: nextWorld[r][c] = empty; break; } }   void main() @safe { auto world = new World(8, 65); foreach (row; world) foreach (ref el; row) el = (uniform01 < treeProb) ? Cell.tree : Cell.empty; auto nextWorld = new World(world.length, world[0].length);   foreach (immutable i; 0 .. 4) { nextState(world, nextWorld); writefln("%(%(%c%)\n%)\n", nextWorld); world.swap(nextWorld); } }
http://rosettacode.org/wiki/First_class_environments
First class environments
According to Wikipedia, "In computing, a first-class object ... is an entity that can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable". Often this term is used in the context of "first class functions". In an analogous way, a programming language may support "first class environments". The environment is minimally, the set of variables accessible to a statement being executed. Change the environments and the same statement could produce different results when executed. Often an environment is captured in a closure, which encapsulates a function together with an environment. That environment, however, is not first-class, as it cannot be created, passed etc. independently from the function's code. Therefore, a first class environment is a set of variable bindings which can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable. It is like a closure without code. A statement must be able to be executed within a stored first class environment and act according to the environment variable values stored within. Task Build a dozen environments, and a single piece of code to be run repeatedly in each of these environments. Each environment contains the bindings for two variables:   a value in the Hailstone sequence, and   a count which is incremented until the value drops to 1. The initial hailstone values are 1 through 12, and the count in each environment is zero. When the code runs, it calculates the next hailstone step in the current environment (unless the value is already 1) and counts the steps. Then it prints the current value in a tabular form. When all hailstone values dropped to 1, processing stops, and the total number of hailstone steps for each environment is printed.
#Bracmat
Bracmat
( (environment=(cnt=0) (seq=)) & :?environments & 13:?seq & whl ' ( !seq+-1:>0:?seq & new$environment:?env & !seq:?(env..seq) & !env !environments:?environments ) & out$(Before !environments) & whl ' ( !environments:? (=? (seq=>1) ?) ? & !environments:?envs & whl ' ( !envs:(=?env) ?envs & ( ' ( $env ( = . put$(!(its.seq) \t) & !(its.seq):1 | 1+!(its.cnt):?(its.cnt) & 1/2*!(its.seq):~/?(its.seq) | 3*!(its.seq)+1:?(its.seq) ) ) . ) $ ) & out$ ) & out$(After !environments) )
http://rosettacode.org/wiki/First_class_environments
First class environments
According to Wikipedia, "In computing, a first-class object ... is an entity that can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable". Often this term is used in the context of "first class functions". In an analogous way, a programming language may support "first class environments". The environment is minimally, the set of variables accessible to a statement being executed. Change the environments and the same statement could produce different results when executed. Often an environment is captured in a closure, which encapsulates a function together with an environment. That environment, however, is not first-class, as it cannot be created, passed etc. independently from the function's code. Therefore, a first class environment is a set of variable bindings which can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable. It is like a closure without code. A statement must be able to be executed within a stored first class environment and act according to the environment variable values stored within. Task Build a dozen environments, and a single piece of code to be run repeatedly in each of these environments. Each environment contains the bindings for two variables:   a value in the Hailstone sequence, and   a count which is incremented until the value drops to 1. The initial hailstone values are 1 through 12, and the count in each environment is zero. When the code runs, it calculates the next hailstone step in the current environment (unless the value is already 1) and counts the steps. Then it prints the current value in a tabular form. When all hailstone values dropped to 1, processing stops, and the total number of hailstone steps for each environment is printed.
#C
C
#include <stdio.h>   #define JOBS 12 #define jobs(a) for (switch_to(a = 0); a < JOBS || !printf("\n"); switch_to(++a)) typedef struct { int seq, cnt; } env_t;   env_t env[JOBS] = {{0, 0}}; int *seq, *cnt;   void hail() { printf("% 4d", *seq); if (*seq == 1) return; ++*cnt; *seq = (*seq & 1) ? 3 * *seq + 1 : *seq / 2; }   void switch_to(int id) { seq = &env[id].seq; cnt = &env[id].cnt; }   int main() { int i; jobs(i) { env[i].seq = i + 1; }   again: jobs(i) { hail(); } jobs(i) { if (1 != *seq) goto again; }   printf("COUNTS:\n"); jobs(i) { printf("% 4d", *cnt); }   return 0; }
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
#Burlesque
Burlesque
  blsq ) {{1} 2 {{3 4} 5} {{{}}} {{{6}}} 7 8 {}}{\[}{)to{"Block"==}ay}w! {1 2 3 4 5 6 7 8}  
http://rosettacode.org/wiki/Flipping_bits_game
Flipping bits game
The game Given an   N×N   square array of zeroes or ones in an initial configuration,   and a target configuration of zeroes and ones. The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered columns at once   (as one move). In an inversion.   any  1  becomes  0,   and any  0  becomes  1  for that whole row or column. Task Create a program to score for the Flipping bits game. The game should create an original random target configuration and a starting configuration. Ensure that the starting position is never the target position. The target position must be guaranteed as reachable from the starting position.   (One possible way to do this is to generate the start position by legal flips from a random target position.   The flips will always be reversible back to the target from the given start position). The number of moves taken so far should be shown. Show an example of a short game here, on this page, for a   3×3   array of bits.
#Java
Java
import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*;   public class FlippingBitsGame extends JPanel { final int maxLevel = 7; final int minLevel = 3;   private Random rand = new Random(); private int[][] grid, target; private Rectangle box; private int n = maxLevel; private boolean solved = true;   FlippingBitsGame() { setPreferredSize(new Dimension(640, 640)); setBackground(Color.white); setFont(new Font("SansSerif", Font.PLAIN, 18));   box = new Rectangle(120, 90, 400, 400);   startNewGame();   addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { if (solved) { startNewGame(); } else { int x = e.getX(); int y = e.getY();   if (box.contains(x, y)) return;   if (x > box.x && x < box.x + box.width) { flipCol((x - box.x) / (box.width / n));   } else if (y > box.y && y < box.y + box.height) flipRow((y - box.y) / (box.height / n));   if (solved(grid, target)) solved = true;   printGrid(solved ? "Solved!" : "The board", grid); } repaint(); } }); }   void startNewGame() { if (solved) {   n = (n == maxLevel) ? minLevel : n + 1;   grid = new int[n][n]; target = new int[n][n];   do { shuffle();   for (int i = 0; i < n; i++) target[i] = Arrays.copyOf(grid[i], n);   shuffle();   } while (solved(grid, target));   solved = false; printGrid("The target", target); printGrid("The board", grid); } }   void printGrid(String msg, int[][] g) { System.out.println(msg); for (int[] row : g) System.out.println(Arrays.toString(row)); System.out.println(); }   boolean solved(int[][] a, int[][] b) { for (int i = 0; i < n; i++) if (!Arrays.equals(a[i], b[i])) return false; return true; }   void shuffle() { for (int i = 0; i < n * n; i++) { if (rand.nextBoolean()) flipRow(rand.nextInt(n)); else flipCol(rand.nextInt(n)); } }   void flipRow(int r) { for (int c = 0; c < n; c++) { grid[r][c] ^= 1; } }   void flipCol(int c) { for (int[] row : grid) { row[c] ^= 1; } }   void drawGrid(Graphics2D g) { g.setColor(getForeground());   if (solved) g.drawString("Solved! Click here to play again.", 180, 600); else g.drawString("Click next to a row or a column to flip.", 170, 600);   int size = box.width / n;   for (int r = 0; r < n; r++) for (int c = 0; c < n; c++) { g.setColor(grid[r][c] == 1 ? Color.blue : Color.orange); g.fillRect(box.x + c * size, box.y + r * size, size, size); g.setColor(getBackground()); g.drawRect(box.x + c * size, box.y + r * size, size, size); g.setColor(target[r][c] == 1 ? Color.blue : Color.orange); g.fillRect(7 + box.x + c * size, 7 + box.y + r * size, 10, 10); } }   @Override public void paintComponent(Graphics gg) { super.paintComponent(gg); Graphics2D g = (Graphics2D) gg; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);   drawGrid(g); }   public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setTitle("Flipping Bits Game"); f.setResizable(false); f.add(new FlippingBitsGame(), BorderLayout.CENTER); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); }); } }
http://rosettacode.org/wiki/First_power_of_2_that_has_leading_decimal_digits_of_12
First power of 2 that has leading decimal digits of 12
(This task is taken from a   Project Euler   problem.) (All numbers herein are expressed in base ten.) 27   =   128   and   7   is the first power of   2   whose leading decimal digits are   12. The next power of   2   whose leading decimal digits are   12   is   80, 280   =   1208925819614629174706176. Define     p(L,n)     to be the nth-smallest value of   j   such that the base ten representation of   2j   begins with the digits of   L . So p(12, 1) = 7 and p(12, 2) = 80 You are also given that: p(123, 45)   =   12710 Task   find:   p(12, 1)   p(12, 2)   p(123, 45)   p(123, 12345)   p(123, 678910)   display the results here, on this page.
#F.23
F#
  // First power of 2 that has specified leading decimal digits. Nigel Galloway: March 14th., 2021 let fG n g=let fN l=let l=10.0**(l-floor l) in l>=n && l<g in let f=log10 2.0 in seq{1..0x0FFFFFFF}|>Seq.filter(float>>(*)f>>fN) printfn "p(23,1)->%d" (int(Seq.item 0 (fG 2.3 2.4))) printfn "p(99,1)->%d" (int(Seq.item 0 (fG 9.9 10.0))) printfn "p(12,1)->%d" (int(Seq.item 0 (fG 1.2 1.3))) printfn "p(12,2)->%d" (int(Seq.item 1 (fG 1.2 1.3))) printfn "p(123,45)->%d" (int(Seq.item 44 (fG 1.23 1.24))) printfn "p(123,12345)->%d" (int(Seq.item 12344 (fG 1.23 1.24))) printfn "p(123,678910)->%d" (int(Seq.item 678909 (fG 1.23 1.24)))  
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
#F.23
F#
  let x = 2.0 let xi = 0.5 let y = 4.0 let yi = 0.25 let z = x + y let zi = 1.0 / ( x + y ) let multiplier (n1,n2) = fun (m:float) -> n1 * n2 * m   [x; y; z] |> List.zip [xi; yi; zi] |> List.map multiplier |> List.map ((|>) 0.5) |> printfn "%A"  
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
#Factor
Factor
USING: arrays kernel literals math prettyprint sequences ; IN: q   CONSTANT: x 2.0 CONSTANT: xi 0.5 CONSTANT: y 4.0 CONSTANT: yi .25 CONSTANT: z $[ $ x $ y + ] CONSTANT: zi $[ 1 $ x $ y + / ]   CONSTANT: A ${ x y z } CONSTANT: B ${ xi yi zi }   : multiplier ( n1 n2 -- q ) [ * * ] 2curry ; : create-all ( seq1 seq2 -- seq ) [ multiplier ] 2map ; : example ( -- ) 0.5 A B create-all [ call( x -- y ) ] with map . ;
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
#jq
jq
$ jq -n '1, (2 | label $foo | debug | 3 | break $foo | debug), 4' 1 ["DEBUG:",2] 4
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
#Julia
Julia
  function example() println("Hello ") @goto world println("Never printed") @label world println("world") end  
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
#zkl
zkl
fcn fourIsMagic(int){ if(int==0) return("Zero is four, four is magic."); string:=""; while(1){ c:=nth(int,False); string+="%s is ".fmt(c); if(int = ( if(int==4) 0 else c.len() )){ string+="%s, ".fmt(nth(int,False)); }else{ string+="magic."; break; } } string[0].toUpper() + string[1,*] }
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.
#C.23
C#
using System; using System.Text;   public class FloydsTriangle { internal static void Main(string[] args) { int count; if (args.Length >= 1 && int.TryParse(args[0], out count) && count > 0) { Console.WriteLine(MakeTriangle(count)); } else { Console.WriteLine(MakeTriangle(5)); Console.WriteLine(); Console.WriteLine(MakeTriangle(14)); } }   public static string MakeTriangle(int rows) { int maxValue = (rows * (rows + 1)) / 2; int digit = 0; StringBuilder output = new StringBuilder();   for (int row = 1; row <= rows; row++) { for (int column = 0; column < row; column++) { int colMaxDigit = (maxValue - rows) + column + 1; if (column > 0) { output.Append(' '); }   digit++; output.Append(digit.ToString().PadLeft(colMaxDigit.ToString().Length)); }   output.AppendLine(); }   return output.ToString(); } }
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)
#Java
Java
import static java.lang.String.format; import java.util.Arrays;   public class FloydWarshall {   public 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) { System.out.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 = format("%d -> %d  %2d  %s", u, v, (int) dist[i][j], u); do { u = next[u - 1][v - 1]; path += " -> " + u; } while (u != v); System.out.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
#Retro
Retro
: multiply ( nn-n ) * ;
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
#REXX
REXX
multiply: return arg(1) * arg(2) /*return the product of the two arguments.*/
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.)
#MATLAB_.2F_Octave
MATLAB / Octave
Y = diff(X,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.)
#Maxima
Maxima
ldiff(u, n) := block([m: length(u)], for j thru n do u: makelist(u[i + 1] - u[i], i, 1, m - j), u);
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
#Z80_Assembly
Z80 Assembly
org $4000   txt_output: equ $bb5a   push hl ld hl,world   print: ld a,(hl) cp 0 jr z,end call txt_output inc hl jr print   end: pop hl ret   world: defm "Hello world!\r\n\0"
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.
#PureBasic
PureBasic
RSet(StrF(7.125,3),8,"0") ; Will be 0007.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.
#Python
Python
from math import pi, exp r = exp(pi)-pi print r print "e=%e f=%f g=%g G=%G s=%s r=%r!"%(r,r,r,r,r,r) print "e=%9.4e f=%9.4f g=%9.4g!"%(-r,-r,-r) print "e=%9.4e f=%9.4f g=%9.4g!"%(r,r,r) print "e=%-9.4e f=%-9.4f g=%-9.4g!"%(r,r,r) print "e=%09.4e f=%09.4f g=%09.4g!"%(-r,-r,-r) print "e=%09.4e f=%09.4f g=%09.4g!"%(r,r,r) print "e=%-09.4e f=%-09.4f g=%-09.4g!"%(r,r,r)
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).
#MyHDL
MyHDL
""" To run: python3 Four_bit_adder_011.py """   from myhdl import *   # define set of primitives   @block def NOTgate( a, q ): # define component name & interface """ q <- not(a) """ @always_comb # define asynchronous logic def NOTgateLogic(): q.next = not a   return NOTgateLogic # return defined logic function, named 'NOTgate'     @block def ANDgate( a, b, q ): """ q <- a and b """ @always_comb def ANDgateLogic(): q.next = a and b   return ANDgateLogic     @block def ORgate( a, b, q ): """ q <- a or b """ @always_comb def ORgateLogic(): q.next = a or b   return ORgateLogic     # build components using defined primitive set   @block def XORgate( a, b, q ): """ q <- a xor b """ # define internal signals nota, notb, annotb, bnnota = [Signal(bool(0)) for i in range(4)] # name sub-components, and their interconnect inv0 = NOTgate( a, nota ) inv1 = NOTgate( b, notb ) and2a = ANDgate( a, notb, annotb ) and2b = ANDgate( b, nota, bnnota ) or2a = ORgate( annotb, bnnota, q )   return inv0, inv1, and2a, and2b, or2a     @block def HalfAdder( in_a, in_b, summ, carry ): """ carry,sum is the sum of in_a, in_b """ and2a = ANDgate(in_a, in_b, carry) xor2a = XORgate(in_a, in_b, summ)   return and2a, xor2a     @block def FullAdder( fa_c0, fa_a, fa_b, fa_s, fa_c1 ): """ fa_c1,fa_s is the sum of fa_c0, fa_a, fa_b """   ha1_s, ha1_c1, ha2_c1 = [Signal(bool(0)) for i in range(3)]   HalfAdder01 = HalfAdder( fa_c0, fa_a, ha1_s, ha1_c1 ) HalfAdder02 = HalfAdder( ha1_s, fa_b, fa_s, ha2_c1 ) or2a = ORgate(ha1_c1, ha2_c1, fa_c1)   return HalfAdder01, HalfAdder02, or2a     @block def Adder4b( ina, inb, cOut, sum4): ''' assemble 4 full adders '''   cl = [Signal(bool()) for i in range(0,4)] # carry signal list sl = [Signal(bool()) for i in range(4)] # sum signal list   HalfAdder0 = HalfAdder( ina(0), inb(0), sl[0], cl[1] ) FullAdder1 = FullAdder( cl[1], ina(1), inb(1), sl[1], cl[2] ) FullAdder2 = FullAdder( cl[2], ina(2), inb(2), sl[2], cl[3] ) FullAdder3 = FullAdder( cl[3], ina(3), inb(3), sl[3], cOut )   sc = ConcatSignal(*reversed(sl)) # create internal bus for output list   @always_comb def list2intbv(): sum4.next = sc # assign internal bus to actual output   return HalfAdder0, FullAdder1, FullAdder2, FullAdder3, list2intbv     """ define signals and code for testing ----------------------------------- """ t_co, t_s, t_a, t_b, dbug = [Signal(bool(0)) for i in range(5)] ina4, inb4, sum4 = [Signal(intbv(0)[4:]) for i in range(3)]   from random import randrange   @block def Test_Adder4b(): ''' Test Bench for Adder4b ''' dut = Adder4b( ina4, inb4, t_co, sum4 )   @instance def check(): print( "\n b a | c1 s \n -------------------" ) for i in range(15): ina4.next, inb4.next = randrange(2**4), randrange(2**4) yield delay(5) print( "  %2d  %2d |  %2d  %2d " \  % (ina4,inb4, t_co,sum4) ) assert t_co * 16 + sum4 == ina4 + inb4 # test result print()   return dut, check     """ instantiate components and run test ----------------------------------- """   def main(): simInst = Test_Adder4b() simInst.name = "mySimInst" simInst.config_sim(trace=True) # waveform trace turned on simInst.run_sim(duration=None)   inst = Adder4b( ina4, inb4, t_co, sum4 ) #Multibit_Adder( a, b, s) inst.convert(hdl='VHDL') # export VHDL inst.convert(hdl='Verilog') # export Verilog     if __name__ == '__main__': main()  
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.
#C.23
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text;   namespace Fivenum { public static class Helper { public static string AsString<T>(this ICollection<T> c, string format = "{0}") { StringBuilder sb = new StringBuilder("["); int count = 0; foreach (var t in c) { if (count++ > 0) { sb.Append(", "); } sb.AppendFormat(format, t); } return sb.Append("]").ToString(); } }   class Program { static double Median(double[] x, int start, int endInclusive) { int size = endInclusive - start + 1; if (size <= 0) throw new ArgumentException("Array slice cannot be empty"); int m = start + size / 2; return (size % 2 == 1) ? x[m] : (x[m - 1] + x[m]) / 2.0; }   static double[] Fivenum(double[] x) { foreach (var d in x) { if (Double.IsNaN(d)) { throw new ArgumentException("Unable to deal with arrays containing NaN"); } } double[] result = new double[5]; Array.Sort(x); result[0] = x.First(); result[2] = Median(x, 0, x.Length - 1); result[4] = x.Last(); int m = x.Length / 2; int lowerEnd = (x.Length % 2 == 1) ? m : m - 1; result[1] = Median(x, 0, lowerEnd); result[3] = Median(x, m, x.Length - 1); return result; }   static void Main(string[] args) { double[][] x1 = new double[][]{ new double[]{ 15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0}, new double[]{ 36.0, 40.0, 7.0, 39.0, 41.0, 15.0}, new double[]{ 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 }, }; foreach(var x in x1) { var result = Fivenum(x); Console.WriteLine(result.AsString("{0:F8}")); } } } }
http://rosettacode.org/wiki/First-class_functions
First-class functions
A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming: Create new functions from preexisting functions at run-time Store functions in collections Use functions as arguments to other functions Use functions as return values of other functions Task Write a program to create an ordered collection A of functions of a real number. At least one function should be built-in and at least one should be user-defined; try using the sine, cosine, and cubing functions. Fill another collection B with the inverse of each function in A. Implement function composition as in Functional Composition. Finally, demonstrate that the result of applying the composition of each function in A and its inverse in B to a value, is the original value. (Within the limits of computational accuracy). (A solution need not actually call the collections "A" and "B". These names are only used in the preceding paragraph for clarity.) Related task First-class Numbers
#Ada
Ada
with Ada.Float_Text_IO, Ada.Integer_Text_IO, Ada.Text_IO, Ada.Numerics.Elementary_Functions;   procedure First_Class_Functions is use Ada.Float_Text_IO, Ada.Integer_Text_IO, Ada.Text_IO, Ada.Numerics.Elementary_Functions;   function Sqr (X : Float) return Float is begin return X ** 2; end Sqr;   type A_Function is access function (X : Float) return Float;   generic F, G : A_Function; function Compose (X : Float) return Float;   function Compose (X : Float) return Float is begin return F (G (X)); end Compose;   Functions : array (Positive range <>) of A_Function := (Sin'Access, Cos'Access, Sqr'Access); Inverses  : array (Positive range <>) of A_Function := (Arcsin'Access, Arccos'Access, Sqrt'Access); begin for I in Functions'Range loop declare function Identity is new Compose (Functions (I), Inverses (I)); Test_Value : Float := 0.5; Result  : Float; begin Result := Identity (Test_Value);   if Result = Test_Value then Put ("Example "); Put (I, Width => 0); Put_Line (" is perfect for the given test value."); else Put ("Example "); Put (I, Width => 0); Put (" is off by"); Put (abs (Result - Test_Value)); Put_Line (" for the given test value."); end if; end; end loop; end First_Class_Functions;
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.
#D.C3.A9j.C3.A0_Vu
Déjà Vu
#chance of empty->tree set :p 0.004 #chance of spontaneous tree combustion set :f 0.001 #chance of tree in initial state set :s 0.5 #height of world set :H 10 #width of world set :W 20   has-burning-neigbour state pos: for i range -- swap ++ dup &< pos: for j range -- swap ++ dup &> pos: & i j try: state! catch value-error: :empty if = :burning: return true false   evolve state pos: state! pos if = :tree dup: if has-burning-neigbour state pos: :burning drop elseif chance f: :burning drop elseif = :burning: :empty else: if chance p: :tree else: :empty   step state: local :next {} for k in keys state: set-to next k evolve state k next   local :(c) { :tree "T" :burning "B" :empty "." } print-state state: for j range 0 H: for i range 0 W: !print\ (c)! state! & i j !print ""   init-state: local :first {} for j range 0 H: for i range 0 W: if chance s: :tree else: :empty set-to first & i j first   run: init-state while true: print-state dup !print "" step   run-slowly: init-state while true: print-state dup drop !prompt "Continue." step   run
http://rosettacode.org/wiki/First_class_environments
First class environments
According to Wikipedia, "In computing, a first-class object ... is an entity that can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable". Often this term is used in the context of "first class functions". In an analogous way, a programming language may support "first class environments". The environment is minimally, the set of variables accessible to a statement being executed. Change the environments and the same statement could produce different results when executed. Often an environment is captured in a closure, which encapsulates a function together with an environment. That environment, however, is not first-class, as it cannot be created, passed etc. independently from the function's code. Therefore, a first class environment is a set of variable bindings which can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable. It is like a closure without code. A statement must be able to be executed within a stored first class environment and act according to the environment variable values stored within. Task Build a dozen environments, and a single piece of code to be run repeatedly in each of these environments. Each environment contains the bindings for two variables:   a value in the Hailstone sequence, and   a count which is incremented until the value drops to 1. The initial hailstone values are 1 through 12, and the count in each environment is zero. When the code runs, it calculates the next hailstone step in the current environment (unless the value is already 1) and counts the steps. Then it prints the current value in a tabular form. When all hailstone values dropped to 1, processing stops, and the total number of hailstone steps for each environment is printed.
#Clojure
Clojure
  (def hailstone-src "(defn hailstone-step [env] (let [{:keys[n cnt]} env] (cond (= n 1) {:n 1 :cnt cnt} (even? n) {:n (/ n 2) :cnt (inc cnt)}  :else {:n (inc (* n 3)) :cnt (inc cnt)})))")   (defn create-hailstone-table [f-src] (let [done? (fn [e] (= (:n e) 1)) print-step (fn [envs] (println (map #(format "%4d" (:n %)) envs))) print-counts (fn [envs] (println "Counts:\n" (map #(format "%4d" (:cnt %)) envs)))] (loop [f (eval (read-string f-src)) envs (for [n (range 12)] {:n (inc n) :cnt 0})] (if (every? done? envs) (print-counts envs) (do (print-step envs) (recur f (map f envs)))))))  
http://rosettacode.org/wiki/First_class_environments
First class environments
According to Wikipedia, "In computing, a first-class object ... is an entity that can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable". Often this term is used in the context of "first class functions". In an analogous way, a programming language may support "first class environments". The environment is minimally, the set of variables accessible to a statement being executed. Change the environments and the same statement could produce different results when executed. Often an environment is captured in a closure, which encapsulates a function together with an environment. That environment, however, is not first-class, as it cannot be created, passed etc. independently from the function's code. Therefore, a first class environment is a set of variable bindings which can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable. It is like a closure without code. A statement must be able to be executed within a stored first class environment and act according to the environment variable values stored within. Task Build a dozen environments, and a single piece of code to be run repeatedly in each of these environments. Each environment contains the bindings for two variables:   a value in the Hailstone sequence, and   a count which is incremented until the value drops to 1. The initial hailstone values are 1 through 12, and the count in each environment is zero. When the code runs, it calculates the next hailstone step in the current environment (unless the value is already 1) and counts the steps. Then it prints the current value in a tabular form. When all hailstone values dropped to 1, processing stops, and the total number of hailstone steps for each environment is printed.
#D
D
import std.stdio, std.algorithm, std.range, std.array;   struct Prop { int[string] data; ref opDispatch(string s)() pure nothrow { return data[s]; } }   immutable code = ` writef("% 4d", e.seq); if (e.seq != 1) { e.cnt++; e.seq = (e.seq & 1) ? 3 * e.seq + 1 : e.seq / 2; }`;   void main() { auto envs = 12.iota.map!(i => Prop(["cnt": 0, "seq": i+1])).array;   while (envs.any!(env => env.seq > 1)) { foreach (e; envs) { mixin(code); } writeln; }   writefln("Counts:\n%(% 4d%)", envs.map!(env => env.cnt)); }
http://rosettacode.org/wiki/Flatten_a_list
Flatten a list
Task Write a function to flatten the nesting in an arbitrary list of values. Your program should work on the equivalent of this list: [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []] Where the correct result would be the list: [1, 2, 3, 4, 5, 6, 7, 8] Related task   Tree traversal
#C
C
#include <stdio.h> #include <stdlib.h> #include <string.h>   typedef struct list_t list_t, *list; struct list_t{ int is_list, ival; /* ival is either the integer value or list length */ list *lst; };   list new_list() { list x = malloc(sizeof(list_t)); x->ival = 0; x->is_list = 1; x->lst = 0; return x; }   void append(list parent, list child) { parent->lst = realloc(parent->lst, sizeof(list) * (parent->ival + 1)); parent->lst[parent->ival++] = child; }   list from_string(char *s, char **e, list parent) { list ret = 0; if (!parent) parent = new_list();   while (*s != '\0') { if (*s == ']') { if (e) *e = s + 1; return parent; } if (*s == '[') { ret = new_list(); ret->is_list = 1; ret->ival = 0; append(parent, ret); from_string(s + 1, &s, ret); continue; } if (*s >= '0' && *s <= '9') { ret = new_list(); ret->is_list = 0; ret->ival = strtol(s, &s, 10); append(parent, ret); continue; } s++; }   if (e) *e = s; return parent; }   void show_list(list l) { int i; if (!l) return; if (!l->is_list) { printf("%d", l->ival); return; }   printf("["); for (i = 0; i < l->ival; i++) { show_list(l->lst[i]); if (i < l->ival - 1) printf(", "); } printf("]"); }   list flatten(list from, list to) { int i; list t;   if (!to) to = new_list(); if (!from->is_list) { t = new_list(); *t = *from; append(to, t); } else for (i = 0; i < from->ival; i++) flatten(from->lst[i], to); return to; }   void delete_list(list l) { int i; if (!l) return; if (l->is_list && l->ival) { for (i = 0; i < l->ival; i++) delete_list(l->lst[i]); free(l->lst); }   free(l); }   int main() { list l = from_string("[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []", 0, 0);   printf("Nested: "); show_list(l); printf("\n");   list flat = flatten(l, 0); printf("Flattened: "); show_list(flat);   /* delete_list(l); delete_list(flat); */ return 0; }
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.
#JavaScript
JavaScript
function numOfRows(board) { return board.length; } function numOfCols(board) { return board[0].length; } function boardToString(board) { // First the top-header var header = ' '; for (var c = 0; c < numOfCols(board); c++) header += c + ' ';   // Then the side-header + board var sideboard = []; for (var r = 0; r < numOfRows(board); r++) { sideboard.push(r + ' [' + board[r].join(' ') + ']'); }   return header + '\n' + sideboard.join('\n'); } function flipRow(board, row) { for (var c = 0; c < numOfCols(board); c++) { board[row][c] = 1 - board[row][c]; } } function flipCol(board, col) { for (var r = 0; r < numOfRows(board); r++) { board[r][col] = 1 - board[r][col]; } }   function playFlippingBitsGame(rows, cols) { rows = rows | 3; cols = cols | 3; var targetBoard = []; var manipulatedBoard = []; // Randomly generate two identical boards. for (var r = 0; r < rows; r++) { targetBoard.push([]); manipulatedBoard.push([]); for (var c = 0; c < cols; c++) { targetBoard[r].push(Math.floor(Math.random() * 2)); manipulatedBoard[r].push(targetBoard[r][c]); } } // Naive-scramble one of the boards. while (boardToString(targetBoard) == boardToString(manipulatedBoard)) { var scrambles = rows * cols; while (scrambles-- > 0) { if (0 == Math.floor(Math.random() * 2)) { flipRow(manipulatedBoard, Math.floor(Math.random() * rows)); } else { flipCol(manipulatedBoard, Math.floor(Math.random() * cols)); } } } // Get the user to solve. alert( 'Try to match both boards.\n' + 'Enter `r<num>` or `c<num>` to manipulate a row or col or enter `q` to quit.' ); var input = '', letter, num, moves = 0; while (boardToString(targetBoard) != boardToString(manipulatedBoard) && input != 'q') { input = prompt( 'Target:\n' + boardToString(targetBoard) + '\n\n\n' + 'Board:\n' + boardToString(manipulatedBoard) ); try { letter = input.charAt(0); num = parseInt(input.slice(1)); if (letter == 'q') break; if (isNaN(num) || (letter != 'r' && letter != 'c') || (letter == 'r' && num >= rows) || (letter == 'c' && num >= cols) ) { throw new Error(''); } if (letter == 'r') { flipRow(manipulatedBoard, num); } else { flipCol(manipulatedBoard, num); } moves++; } catch(e) { alert('Uh-oh, there seems to have been an input error'); } } if (input == 'q') { alert('~~ Thanks for playing ~~'); } else { alert('Completed in ' + moves + ' 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.
#Factor
Factor
USING: formatting fry generalizations kernel literals math math.functions math.parser sequences tools.time ;   CONSTANT: ld10 $[ 2 log 10 log / ]   : p ( L n -- m ) swap [ 0 0 ] [ '[ over _ >= ] ] [ [ log10 >integer 10^ ] keep ] tri* '[ 1 + dup ld10 * dup >integer - 10 log * e^ _ * truncate _ number= [ [ 1 + ] dip ] when ] until nip ;   [ 12 1 12 2 123 45 123 12345 123 678910 [ 2dup p "%d %d p = %d\n" printf ] 2 5 mnapply ] time
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.
#FreeBASIC
FreeBASIC
#define FAC 0.30102999566398119521373889472449302677   function p( L as uinteger, n as uinteger ) as uinteger dim as uinteger count, j = 0 dim as double x, y dim as string digits, LS = str(L) while count < n j+=1 x = FAC * j if x < len(LS) then continue while y = 10^(x-int(x)) y *= 10^len(LS) digits = str(y) if left(digits,len(LS)) = LS then count += 1 wend return j end function   print p(12, 1) print p(12, 2) print p(123, 45) print p(123, 12345) print p(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
#Fantom
Fantom
  class Main { static |Float -> Float| combine (Float n1, Float n2) { return |Float m -> Float| { n1 * n2 * m } }   public static Void main () { Float x := 2f Float xi := 0.5f Float y := 4f Float yi := 0.25f Float z := x + y Float zi := 1 / (x + y) echo (combine(x, xi)(0.5f)) echo (combine(y, yi)(0.5f)) echo (combine(z, zi)(0.5f)) } }  
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
#Go
Go
package main   import "fmt"   func main() { x := 2. xi := .5 y := 4. yi := .25 z := x + y zi := 1 / (x + y) // point A   numbers := []float64{x, y, z} inverses := []float64{xi, yi, zi} // point B   mfs := make([]func(float64) float64, len(numbers)) for i := range mfs { mfs[i] = multiplier(numbers[i], inverses[i]) } // point C   for _, mf := range mfs { fmt.Println(mf(1)) } }   func multiplier(n1, n2 float64) func(float64) float64 { // compute product of n's, store in a new variable n1n2 := n1 * n2 // close on variable containing product return func(m float64) float64 { return n1n2 * m } }
http://rosettacode.org/wiki/Flow-control_structures
Flow-control structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task Document common flow-control structures. One common example of a flow-control structure is the   goto   construct. Note that   Conditional Structures   and   Loop Structures   have their own articles/categories. Related tasks   Conditional Structures   Loop Structures
#Kotlin
Kotlin
// version 1.0.6   fun main(args: Array<String>) { for (i in 0 .. 2) { for (j in 0 .. 2) { if (i + j == 2) continue if (i + j == 3) break println(i + j) } } println() if (args.isNotEmpty()) throw IllegalArgumentException("No command line arguments should be supplied") println("Goodbye!") // won't be executed }
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
#Lua
Lua
i = 0 while true do i = i + 1 if i > 10 then break end end
http://rosettacode.org/wiki/Floyd%27s_triangle
Floyd's triangle
Floyd's triangle   lists the natural numbers in a right triangle aligned to the left where the first row is   1     (unity) successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above. The first few lines of a Floyd triangle looks like this: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Task Write a program to generate and display here the first   n   lines of a Floyd triangle. (Use   n=5   and   n=14   rows). Ensure that when displayed in a mono-space font, the numbers line up in vertical columns as shown and that only one space separates numbers of the last row.
#C.2B.2B
C++
  #include <windows.h> #include <sstream> #include <iostream>   //-------------------------------------------------------------------------------------------------- using namespace std;   //-------------------------------------------------------------------------------------------------- class floyds_tri { public: floyds_tri() { lastLineLen = 0; } ~floyds_tri() { killArray(); }   void create( int rows ) { _rows = rows; calculateLastLineLen(); display(); }   private: void killArray() { if( lastLineLen ) delete [] lastLineLen; }   void calculateLastLineLen() { killArray(); lastLineLen = new BYTE[_rows];   int s = 1 + ( _rows * ( _rows - 1 ) ) / 2;   for( int x = s, ix = 0; x < s + _rows; x++, ix++ ) { ostringstream cvr; cvr << x; lastLineLen[ix] = static_cast<BYTE>( cvr.str().size() ); } }   void display() { cout << endl << "Floyd\'s Triangle - " << _rows << " rows" << endl << "===============================================" << endl; int number = 1; for( int r = 0; r < _rows; r++ ) { for( int c = 0; c <= r; c++ ) { ostringstream cvr; cvr << number++; string str = cvr.str(); while( str.length() < lastLineLen[c] ) str = " " + str; cout << str << " "; } cout << endl; } }   int _rows; BYTE* lastLineLen; }; //-------------------------------------------------------------------------------------------------- int main( int argc, char* argv[] ) { floyds_tri t; int s; while( true ) { cout << "Enter the size of the triangle ( 0 to QUIT ): "; cin >> s; if( !s ) return 0; if( s > 0 ) t.create( s );   cout << endl << endl; system( "pause" ); }   return 0; } //--------------------------------------------------------------------------------------------------
http://rosettacode.org/wiki/Floyd-Warshall_algorithm
Floyd-Warshall algorithm
The Floyd–Warshall algorithm is an algorithm for finding shortest paths in a weighted graph with positive or negative edge weights. Task Find the lengths of the shortest paths between all pairs of vertices of the given directed graph. Your code may assume that the input has already been checked for loops, parallel edges and negative cycles. Print the pair, the distance and (optionally) the path. Example pair dist path 1 -> 2 -1 1 -> 3 -> 4 -> 2 1 -> 3 -2 1 -> 3 1 -> 4 0 1 -> 3 -> 4 2 -> 1 4 2 -> 1 2 -> 3 2 2 -> 1 -> 3 2 -> 4 4 2 -> 1 -> 3 -> 4 3 -> 1 5 3 -> 4 -> 2 -> 1 3 -> 2 1 3 -> 4 -> 2 3 -> 4 2 3 -> 4 4 -> 1 3 4 -> 2 -> 1 4 -> 2 -1 4 -> 2 4 -> 3 1 4 -> 2 -> 1 -> 3 See also Floyd-Warshall Algorithm - step by step guide (youtube)
#JavaScript
JavaScript
var graph = []; for (i = 0; i < 10; ++i) { graph.push([]); for (j = 0; j < 10; ++j) graph[i].push(i == j ? 0 : 9999999); }   for (i = 1; i < 10; ++i) { graph[0][i] = graph[i][0] = parseInt(Math.random() * 9 + 1); }   for (k = 0; k < 10; ++k) { for (i = 0; i < 10; ++i) { for (j = 0; j < 10; ++j) { if (graph[i][j] > graph[i][k] + graph[k][j]) graph[i][j] = graph[i][k] + graph[k][j] } } }   console.log(graph);
http://rosettacode.org/wiki/Function_definition
Function definition
A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract from showing how functions are created and values returned). Related task   Function prototype
#Ring
Ring
  func multiply x,y return x*y  
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
#RLaB
RLaB
>> class(sin) function >> type(sin) builtin
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.)
#NetRexx
NetRexx
/* NetRexx************************************************************* * Forward differences * 18.08.2012 Walter Pachl derived from Rexx **********************************************************************/ Loop n=-1 To 11 differences('90 47 58 29 22 32 55 5 55 73',n) End   method differences(a,n) public static --arr=Rexx[11] -- array must be declared (zero based) arr='' -- alternative: indexed string m=a.words Select When n<0 Then Say 'n is negative:' n '<' 0 When n>m Then Say 'n is too large:' n '>' m Otherwise Do Loop i=1 To m arr[i]=a.word(i) End Loop i = 1 to n t = arr[i] Loop j = i+1 to m u = arr[j] arr[j] = arr[j]-t t = u end end ol='' Loop i=n+1 to m ol=ol arr[i] End Say n ol End End
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
#zkl
zkl
println("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
#Zig
Zig
const std = @import("std"); pub fn main() !void { try std.io.getStdOut().writer().writeAll("Hello world!\n"); }
http://rosettacode.org/wiki/Formatted_numeric_output
Formatted numeric output
Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
#R
R
> sprintf("%f", pi) [1] "3.141593" > sprintf("%.3f", pi) [1] "3.142" > sprintf("%1.0f", pi) [1] "3" > sprintf("%5.1f", pi) [1] " 3.1" > sprintf("%05.1f", pi) [1] "003.1" > sprintf("%+f", pi) [1] "+3.141593" > sprintf("% f", pi) [1] " 3.141593" > sprintf("%-10f", pi)# left justified [1] "3.141593 " > sprintf("%e", pi) [1] "3.141593e+00" > sprintf("%E", pi) [1] "3.141593E+00" > sprintf("%g", pi) [1] "3.14159" > sprintf("%g", 1e6 * pi) # -> exponential [1] "3.14159e+06" > sprintf("%.9g", 1e6 * pi) # -> "fixed" [1] "3141592.65" > sprintf("%G", 1e-6 * pi) [1] "3.14159E-06"
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.
#Racket
Racket
  -> (displayln (~a 7.125 #:width 9 #:align 'right #:pad-string "0")) 00007.125  
http://rosettacode.org/wiki/Four_bit_adder
Four bit adder
Task "Simulate" a four-bit adder. This design can be realized using four 1-bit full adders. Each of these 1-bit full adders can be built with two half adders and an   or   gate. ; Finally a half adder can be made using an   xor   gate and an   and   gate. The   xor   gate can be made using two   nots,   two   ands   and one   or. Not,   or   and   and,   the only allowed "gates" for the task, can be "imitated" by using the bitwise operators of your language. If there is not a bit type in your language, to be sure that the   not   does not "invert" all the other bits of the basic type   (e.g. a byte)   we are not interested in,   you can use an extra   nand   (and   then   not)   with the constant   1   on one input. Instead of optimizing and reducing the number of gates used for the final 4-bit adder,   build it in the most straightforward way,   connecting the other "constructive blocks",   in turn made of "simpler" and "smaller" ones. Schematics of the "constructive blocks" (Xor gate with ANDs, ORs and NOTs)            (A half adder)                   (A full adder)                             (A 4-bit adder)         Solutions should try to be as descriptive as possible, making it as easy as possible to identify "connections" between higher-order "blocks". It is not mandatory to replicate the syntax of higher-order blocks in the atomic "gate" blocks, i.e. basic "gate" operations can be performed as usual bitwise operations, or they can be "wrapped" in a block in order to expose the same syntax of higher-order blocks, at implementers' choice. To test the implementation, show the sum of two four-bit numbers (in binary).
#Nim
Nim
type   Bools[N: static int] = array[N, bool] SumCarry = tuple[sum, carry: bool]   proc ha(a, b: bool): SumCarry = (a xor b, a and b)   proc fa(a, b, ci: bool): SumCarry = let a = ha(ci, a) let b = ha(a[0], b) result = (b[0], a[1] or b[1])   proc fa4(a, b: Bools[4]): Bools[5] = var co, s: Bools[4] for i in 0..3: let r = fa(a[i], b[i], if i > 0: co[i-1] else: false) s[i] = r[0] co[i] = r[1] result[0..3] = s result[4] = co[3]   proc int2bus(n: int): Bools[4] = var n = n for i in 0..result.high: result[i] = (n and 1) == 1 n = n shr 1   proc bus2int(b: Bools): int = for i, x in b: result += (if x: 1 else: 0) shl i   for a in 0..7: for b in 0..7: assert a + b == bus2int fa4(int2bus(a), int2bus(b))
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.
#C.2B.2B
C++
#include <algorithm> #include <iostream> #include <ostream> #include <vector>   ///////////////////////////////////////////////////////////////////////////// // The following is taken from https://cpplove.blogspot.com/2012/07/printing-tuples.html   // Define a type which holds an unsigned integer value template<std::size_t> struct int_ {};   template <class Tuple, size_t Pos> std::ostream& print_tuple(std::ostream& out, const Tuple& t, int_<Pos>) { out << std::get< std::tuple_size<Tuple>::value - Pos >(t) << ", "; return print_tuple(out, t, int_<Pos - 1>()); }   template <class Tuple> std::ostream& print_tuple(std::ostream& out, const Tuple& t, int_<1>) { return out << std::get<std::tuple_size<Tuple>::value - 1>(t); }   template <class... Args> std::ostream& operator<<(std::ostream& out, const std::tuple<Args...>& t) { out << '('; print_tuple(out, t, int_<sizeof...(Args)>()); return out << ')'; }   /////////////////////////////////////////////////////////////////////////////   template <class RI> double median(RI beg, RI end) { if (beg == end) throw std::runtime_error("Range cannot be empty"); auto len = end - beg; auto m = len / 2; if (len % 2 == 1) { return *(beg + m); }   return (beg[m - 1] + beg[m]) / 2.0; }   template <class C> auto fivenum(C& c) { std::sort(c.begin(), c.end());   auto cbeg = c.cbegin(); auto cend = c.cend();   auto len = cend - cbeg; auto m = len / 2; auto lower = (len % 2 == 1) ? m : m - 1; double r2 = median(cbeg, cbeg + lower + 1); double r3 = median(cbeg, cend); double r4 = median(cbeg + lower + 1, cend);   return std::make_tuple(*cbeg, r2, r3, r4, *(cend - 1)); }   int main() { using namespace std; vector<vector<double>> cs = { { 15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0 }, { 36.0, 40.0, 7.0, 39.0, 41.0, 15.0 }, { 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 } };   for (auto & c : cs) { cout << fivenum(c) << endl; }   return 0; }
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) The   FizzBuzz   problem was presented as the lowest level of comprehension required to illustrate adequacy. Also see   (a blog)   dont-overthink-fizzbuzz   (a blog)   fizzbuzz-the-programmers-stairway-to-heaven
#11l
11l
L(i) 1..100 I i % 15 == 0 print(‘FizzBuzz’) E I i % 3 == 0 print(‘Fizz’) E I i % 5 == 0 print(‘Buzz’) E print(i)
http://rosettacode.org/wiki/Five_weekends
Five weekends
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays. Task Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar). Show the number of months with this property (there should be 201). Show at least the first and last five dates, in order. Algorithm suggestions Count the number of Fridays, Saturdays, and Sundays in every month. Find all of the 31-day months that begin on Friday. Extra credit Count and/or show all of the years which do not have at least one five-weekend month (there should be 29). Related tasks Day of the week Last Friday of each month Find last sunday of each month
#360_Assembly
360 Assembly
* Five weekends 31/05/2016 FIVEWEEK CSECT USING FIVEWEEK,R13 base register B 72(R15) skip savearea DC 17F'0' savearea STM R14,R12,12(R13) prolog ST R13,4(R15) " ST R15,8(R13) " LR R13,R15 " LM R10,R11,=AL8(0) nko=0; nok=0 LH R6,Y1 y=y1 LOOPY CH R6,Y2 do y=y1 to y2 BH ELOOPY MVI YF,X'00' yf=0 LA R7,1 im=1 LOOPIM C R7,=F'7' do im=1 to 7 BH ELOOPIM LR R1,R7 im SLA R1,1 *2 (H) LH R2,ML-2(R1) ml(im) ST R2,M m=ml(im) MVC D,=F'1' d=1 L R4,M m C R4,=F'2' if m<=2 BH MSUP2 L R8,M m LA R8,12(R8) mw=m+12 LR R9,R6 y BCTR R9,0 yw=y-1 B EMSUP2 MSUP2 L R8,M mw=m LR R9,R6 yw=y EMSUP2 LR R4,R9 ym SRDA R4,32 . D R4,=F'100' yw/100 ST R5,J j=yw/100 ST R4,K k=yw//100 LR R4,R8 mw LA R4,1(R4) mw+1 MH R4,=H'26' (mw+1)*26 SRDA R4,32 . D R4,=F'10' (mw+1)*26/10 LR R2,R5 " A R2,D d A R2,K d+k L R3,K k SRA R3,2 k/4 AR R2,R3 (mw+1)*26/10+k/4 L R3,J j SRA R3,2 j/4 AR R2,R3 (mw+1)*26/10+k/4+j/4 LA R5,5 5 M R4,J 5*j AR R2,R5 (mw+1)*26/10+k/4+j/4 SRDA R2,32 . D R2,=F'7' (d+(mw+1)*26/10+k+k/4+j/4+5*j)/7 C R2,=F'6' if dow=friday BNE NOFRIDAY XDECO R6,XDEC y MVC PG+0(4),XDEC+8 output y LR R1,R7 im MH R1,=H'3' *3 LA R14,MN-3(R1) @mn(im) MVC PG+5(3),0(R14) output mn(im) XPRNT PG,8 print buffer LA R11,1(R11) nok=nok+1 MVI YF,X'01' yf=1 NOFRIDAY LA R7,1(R7) im=im+1 B LOOPIM ELOOPIM L R4,YF yf CLI YF,X'00' if yf=0 BNE EYFNE0 LA R10,1(R10) nko=nko+1 EYFNE0 LA R6,1(R6) y=y+1 B LOOPY ELOOPY XDECO R11,XDEC nok MVC PG+0(4),XDEC+8 output nok MVC PG+4(12),=C' occurrences' XPRNT PG,80 print buffer XDECO R10,XDEC nko MVC PG+0(4),XDEC+8 output nko MVC PG+4(33),=C' years with no five weekend month' XPRNT PG,80 print buffer L R13,4(0,R13) epilog LM R14,R12,12(R13) " XR R15,R15 " BR R14 exit Y1 DC H'1900' year start Y2 DC H'2100' year stop ML DC H'1',H'3',H'5',H'7',H'8',H'10',H'12' MN DC C'jan',C'mar',C'may',C'jul',C'aug',C'oct',C'dec' YF DS X year flag M DS F month D DS F day J DS F j=yw/100 K DS F j=mod(yw,100) PG DC CL80'....-' buffer XDEC DS CL12 temp for XDECO YREGS END FIVEWEEK
http://rosettacode.org/wiki/First_perfect_square_in_base_n_with_n_unique_digits
First perfect square in base n with n unique digits
Find the first perfect square in a given base N that has at least N digits and exactly N significant unique digits when expressed in base N. E.G. In base 10, the first perfect square with at least 10 unique digits is 1026753849 (32043²). You may use analytical methods to reduce the search space, but the code must do a search. Do not use magic numbers or just feed the code the answer to verify it is correct. Task Find and display here, on this page, the first perfect square in base N, with N significant unique digits when expressed in base N, for each of base 2 through 12. Display each number in the base N for which it was calculated. (optional) Do the same for bases 13 through 16. (stretch goal) Continue on for bases 17 - ?? (Big Integer math) See also OEIS A260182: smallest square that is pandigital in base n. Related task Casting out nines
#11l
11l
L(base) 2..16 V n = Int64(Float(base) ^ ((base - 1) / 2)) L V sq = n * n V sqstr = String(sq, radix' base) I sqstr.len >= base & Set(Array(sqstr)).len == base V nstr = String(n, radix' base) print(‘Base #2: #8^2 = #.’.format(base, nstr, sqstr)) L.break n++
http://rosettacode.org/wiki/First-class_functions
First-class functions
A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming: Create new functions from preexisting functions at run-time Store functions in collections Use functions as arguments to other functions Use functions as return values of other functions Task Write a program to create an ordered collection A of functions of a real number. At least one function should be built-in and at least one should be user-defined; try using the sine, cosine, and cubing functions. Fill another collection B with the inverse of each function in A. Implement function composition as in Functional Composition. Finally, demonstrate that the result of applying the composition of each function in A and its inverse in B to a value, is the original value. (Within the limits of computational accuracy). (A solution need not actually call the collections "A" and "B". These names are only used in the preceding paragraph for clarity.) Related task First-class Numbers
#Aikido
Aikido
  import math   function compose (f, g) { return function (x) { return f(g(x)) } }   var fn = [Math.sin, Math.cos, function(x) { return x*x*x }] var inv = [Math.asin, Math.acos, function(x) { return Math.pow(x, 1.0/3) }]   for (var i=0; i<3; i++) { var f = compose(inv[i], fn[i]) println(f(0.5)) // 0.5 }    
http://rosettacode.org/wiki/First-class_functions
First-class functions
A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming: Create new functions from preexisting functions at run-time Store functions in collections Use functions as arguments to other functions Use functions as return values of other functions Task Write a program to create an ordered collection A of functions of a real number. At least one function should be built-in and at least one should be user-defined; try using the sine, cosine, and cubing functions. Fill another collection B with the inverse of each function in A. Implement function composition as in Functional Composition. Finally, demonstrate that the result of applying the composition of each function in A and its inverse in B to a value, is the original value. (Within the limits of computational accuracy). (A solution need not actually call the collections "A" and "B". These names are only used in the preceding paragraph for clarity.) Related task First-class Numbers
#ALGOL_68
ALGOL 68
MODE F = PROC (REAL)REAL; OP ** = (REAL x, power)REAL: exp(ln(x)*power);   # Add a user defined function and its inverse # PROC cube = (REAL x)REAL: x * x * x; PROC cube root = (REAL x)REAL: x ** (1/3);   # First class functions allow run-time creation of functions from functions # # return function compose(f,g)(x) == f(g(x)) # PROC non standard compose = (F f1, f2)F: (REAL x)REAL: f1(f2(x)); # eg ELLA ALGOL 68RS # PROC compose = (F f, g)F: ((F f2, g2, REAL x)REAL: f2(g2(x)))(f, g, );   # Or the classic "o" functional operator # PRIO O = 5; OP (F,F)F O = compose;   # first class functions should be able to be members of collection types # []F func list = (sin, cos, cube); []F arc func list = (arc sin, arc cos, cube root);   # Apply functions from lists as easily as integers # FOR index TO UPB func list DO STRUCT(F f, inverse f) this := (func list[index], arc func list[index]); print(((inverse f OF this O f OF this)(.5), new line)) OD
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.
#EasyLang
EasyLang
p_fire = 0.00002 p_tree = 0.002 # len f[] 102 * 102 len p[] len f[] background 100 clear for r range 100 for c range 100 i = r * 102 + c + 103 if randomf < 0.5 f[i] = 1 . . . timer 0 # subr show for r range 100 for c range 100 i = r * 102 + c + 103 h = f[i] if h <> p[i] move c + 0.5 r + 0.5 if h = 0 color 100 circle 0.6 elif h = 1 color 151 circle 0.5 else color 9 * 100 + (18 - 2 * h) * 10 circle 0.5 . . . . . subr update swap f[] p[] for r range 100 for c range 100 i = r * 102 + c + 103 if p[i] = 0 f[i] = 0 if randomf < p_tree f[i] = 1 . elif p[i] = 1 f[i] = 1 s = p[i - 103] + p[i - 102] + p[i - 101] s += p[i - 1] + p[i + 1] s += p[i + 101] + p[i + 102] + p[i + 103] if s >= 9 or randomf < p_fire f[i] = 9 . elif p[i] = 4 f[i] = 0 else f[i] = p[i] - 1 . . . . on timer call show call update timer 0.2 .
http://rosettacode.org/wiki/First_class_environments
First class environments
According to Wikipedia, "In computing, a first-class object ... is an entity that can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable". Often this term is used in the context of "first class functions". In an analogous way, a programming language may support "first class environments". The environment is minimally, the set of variables accessible to a statement being executed. Change the environments and the same statement could produce different results when executed. Often an environment is captured in a closure, which encapsulates a function together with an environment. That environment, however, is not first-class, as it cannot be created, passed etc. independently from the function's code. Therefore, a first class environment is a set of variable bindings which can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable. It is like a closure without code. A statement must be able to be executed within a stored first class environment and act according to the environment variable values stored within. Task Build a dozen environments, and a single piece of code to be run repeatedly in each of these environments. Each environment contains the bindings for two variables:   a value in the Hailstone sequence, and   a count which is incremented until the value drops to 1. The initial hailstone values are 1 through 12, and the count in each environment is zero. When the code runs, it calculates the next hailstone step in the current environment (unless the value is already 1) and counts the steps. Then it prints the current value in a tabular form. When all hailstone values dropped to 1, processing stops, and the total number of hailstone steps for each environment is printed.
#EchoLisp
EchoLisp
  (define (bump-value) (when (> value 1) (set! count (1+ count)) (set! value (if (even? value) (/ value 2) (1+ (* 3 value))))))   (define (env-show name envs ) (write name) (for ((env envs)) (write (format "%4a" (eval name env)))) (writeln))   (define (task (envnum 12)) (define envs (for/list ((i envnum)) (environment-new `((value ,(1+ i)) (count 0))))) (env-show 'value envs) (while (any (curry (lambda ( n env) (!= 1 (eval n env))) 'value) envs) (for/list ((env envs)) (eval '(bump-value) env)) (env-show 'value envs)) (env-show 'count envs))  
http://rosettacode.org/wiki/First_class_environments
First class environments
According to Wikipedia, "In computing, a first-class object ... is an entity that can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable". Often this term is used in the context of "first class functions". In an analogous way, a programming language may support "first class environments". The environment is minimally, the set of variables accessible to a statement being executed. Change the environments and the same statement could produce different results when executed. Often an environment is captured in a closure, which encapsulates a function together with an environment. That environment, however, is not first-class, as it cannot be created, passed etc. independently from the function's code. Therefore, a first class environment is a set of variable bindings which can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable. It is like a closure without code. A statement must be able to be executed within a stored first class environment and act according to the environment variable values stored within. Task Build a dozen environments, and a single piece of code to be run repeatedly in each of these environments. Each environment contains the bindings for two variables:   a value in the Hailstone sequence, and   a count which is incremented until the value drops to 1. The initial hailstone values are 1 through 12, and the count in each environment is zero. When the code runs, it calculates the next hailstone step in the current environment (unless the value is already 1) and counts the steps. Then it prints the current value in a tabular form. When all hailstone values dropped to 1, processing stops, and the total number of hailstone steps for each environment is printed.
#Erlang
Erlang
Note that using the Process Dictionary: Destroys referencial transparency Makes debugging difficult Survives Catch/Throw
http://rosettacode.org/wiki/Flatten_a_list
Flatten a list
Task Write a function to flatten the nesting in an arbitrary list of values. Your program should work on the equivalent of this list: [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []] Where the correct result would be the list: [1, 2, 3, 4, 5, 6, 7, 8] Related task   Tree traversal
#C.23
C#
  using System; using System.Collections; using System.Linq;   namespace RosettaCodeTasks { static class FlattenList { public static ArrayList Flatten(this ArrayList List) { ArrayList NewList = new ArrayList ( );   NewList.AddRange ( List );   while ( NewList.OfType<ArrayList> ( ).Count ( ) > 0 ) { int index = NewList.IndexOf ( NewList.OfType<ArrayList> ( ).ElementAt ( 0 ) ); ArrayList Temp = (ArrayList)NewList[index]; NewList.RemoveAt ( index ); NewList.InsertRange ( index, Temp ); }   return NewList; } } }  
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.
#Julia
Julia
module FlippingBitsGame   using Printf, Random import Base.size, Base.show, Base.==   struct Configuration M::BitMatrix end   Base.size(c::Configuration) = size(c.M) function Base.show(io::IO, conf::Configuration) M = conf.M nrow, ncol = size(M) print(io, " " ^ 3) for c in 1:ncol @printf(io, "%3i", c) end println(io, "\n", " " ^ 4, "-" ^ 3ncol) for r in 1:nrow @printf(io, "%2i |", r) for c in 1:ncol @printf(io, "%2c ", ifelse(M[r, c], 'T', 'F')) end println(io) end return nothing end Base.:(==)(a::Configuration, b::Configuration) = a.M == b.M   struct Index{D} i::Int end const ColIndex = Index{:C} const RowIndex = Index{:R}   function flipbits!(conf::Configuration, c::ColIndex) col = @view conf.M[:, c.i] @. col = !col return conf end function flipbits!(conf::Configuration, r::RowIndex) row = @view conf.M[r.i, :] @. row = !row return conf end   randomconfig(nrow::Integer, ncol::Integer) = Configuration(bitrand(nrow, ncol))   function randommoves!(conf::Configuration, nflips::Integer) nrow, ncol = size(conf) for _ in Base.OneTo(nflips) if rand() < 0.5 flipbits!(conf, ColIndex(rand(1:ncol))) else flipbits!(conf, RowIndex(rand(1:nrow))) end end return conf end   function play() nrow::Int, ncol::Int = 0, 0 while nrow < 2 || ncol < 2 print("Insert the size of the matrix (nrow [> 1] *space* ncol [> 1]):") nrow, ncol = parse.(Int, split(readline())) end mat = randomconfig(nrow, ncol) obj = deepcopy(mat) randommoves!(obj, 100) nflips = 0 while mat != obj println("\n", nflips, " flips until now.") println("Current configuration:") println(mat) println("Objective configuration:") println(obj) print("Insert R[ind] to flip row, C[ind] to flip a column, Q to quit: ") line = readline() input = match(r"([qrc])(\d+)"i, line) if input ≢ nothing && all(input.captures .≢ nothing) dim = Symbol(uppercase(input.captures[1])) ind = Index{dim}(parse(Int, input.captures[2])) flipbits!(mat, ind) nflips += 1 elseif occursin("q", line) println("\nSEE YOU SOON!") return else println("\nINPUT NOT VALID, RETRY!\n") end end println("\nSUCCED! In ", nflips, " flips.") println(mat) return end   end # module FlippingBitsGame   using .FlippingBitsGame   FlippingBitsGame.play()  
http://rosettacode.org/wiki/First_power_of_2_that_has_leading_decimal_digits_of_12
First power of 2 that has leading decimal digits of 12
(This task is taken from a   Project Euler   problem.) (All numbers herein are expressed in base ten.) 27   =   128   and   7   is the first power of   2   whose leading decimal digits are   12. The next power of   2   whose leading decimal digits are   12   is   80, 280   =   1208925819614629174706176. Define     p(L,n)     to be the nth-smallest value of   j   such that the base ten representation of   2j   begins with the digits of   L . So p(12, 1) = 7 and p(12, 2) = 80 You are also given that: p(123, 45)   =   12710 Task   find:   p(12, 1)   p(12, 2)   p(123, 45)   p(123, 12345)   p(123, 678910)   display the results here, on this page.
#Go
Go
package main   import ( "fmt" "math" "time" )   const ld10 = math.Ln2 / math.Ln10   func commatize(n uint64) string { s := fmt.Sprintf("%d", n) le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } return s }   func p(L, n uint64) uint64 { i := L digits := uint64(1) for i >= 10 { digits *= 10 i /= 10 } count := uint64(0) for i = 0; count < n; i++ { e := math.Exp(math.Ln10 * math.Mod(float64(i)*ld10, 1)) if uint64(math.Trunc(e*float64(digits))) == L { count++ } } return i - 1 }   func main() { start := time.Now() params := [][2]uint64{{12, 1}, {12, 2}, {123, 45}, {123, 12345}, {123, 678910}} for _, param := range params { fmt.Printf("p(%d, %d) = %s\n", param[0], param[1], commatize(p(param[0], param[1]))) } fmt.Printf("\nTook %s\n", time.Since(start)) }
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
#Groovy
Groovy
def multiplier = { n1, n2 -> { m -> n1 * n2 * m } }   def ε = 0.00000001 // tolerance(epsilon): acceptable level of "wrongness" to account for rounding error [(2.0):0.5, (4.0):0.25, (6.0):(1/6.0)].each { num, inv -> def new_function = multiplier(num, inv) (1.0..5.0).each { trial -> assert (new_function(trial) - trial).abs() < ε printf('%5.3f * %5.3f * %5.3f == %5.3f\n', num, inv, trial, trial) } println() }
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
#Haskell
Haskell
module Main where   import Text.Printf   -- Pseudo code happens to be valid Haskell x = 2.0 xi = 0.5 y = 4.0 yi = 0.25 z = x + y zi = 1.0 / ( x + y )   -- Multiplier function multiplier :: Double -> Double -> Double -> Double multiplier a b = \m -> a * b * m   main :: IO () main = do let numbers = [x, y, z] inverses = [xi, yi, zi] pairs = zip numbers inverses print_pair (number, inverse) = let new_function = multiplier number inverse in printf "%f * %f * 0.5 = %f\n" number inverse (new_function 0.5) mapM_ print_pair pairs  
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
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
  try % do some stuff catch % in case of error, continue here 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
#MATLAB_.2F_Octave
MATLAB / Octave
  try % do some stuff catch % in case of error, continue here end  
http://rosettacode.org/wiki/Floyd%27s_triangle
Floyd's triangle
Floyd's triangle   lists the natural numbers in a right triangle aligned to the left where the first row is   1     (unity) successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above. The first few lines of a Floyd triangle looks like this: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Task Write a program to generate and display here the first   n   lines of a Floyd triangle. (Use   n=5   and   n=14   rows). Ensure that when displayed in a mono-space font, the numbers line up in vertical columns as shown and that only one space separates numbers of the last row.
#Clojure
Clojure
  (defn TriangleList [n] (let [l (map inc (range))] (loop [l l x 1 nl []] (if (= n (count nl)) nl (recur (drop x l) (inc x) (conj nl (take x l)))))))   (defn TrianglePrint [n] (let [t (TriangleList n) m (count (str (last (last t)))) f (map #(map str %) t) l (map #(map (fn [x] (if (> m (count x)) (str (apply str (take (- m (count x)) (repeat " "))) x) x)) %) f) e (map #(map (fn [x] (str " " x)) %) l)] (map #(println (apply str %)) e)))  
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)
#jq
jq
  def weights: { "1": {"3": -2}, "2": {"1" : 4, "3": 3}, "3": {"4": 2}, "4": {"2": -1} };