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/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)
#RATFOR
RATFOR
# # Floyd-Warshall algorithm. # # See https://en.wikipedia.org/w/index.php?title=Floyd%E2%80%93Warshall_algorithm&oldid=1082310013 #   # # A C programmer might take note that the most rapid stride in an # array is on the *leftmost* index, rather than the *rightmost* as in # C. # # (In other words, Fortran has "column-major order", whereas C has # "row-major order". I prefer to think of it in terms of strides. For # one thing, in my opinion, which index is for a "column" and which # for a "row" should be considered arbitrary unless dictated by # context.) #   # VLIMIT = the maximum number of vertices the program can handle. define(VLIMIT, 100)   # NILVTX = the nil vertex. define(NILVTX, 0)   # STRSZ = a buffer size used in some character-handling routines. define(STRSZ, 300)   # BUFSZ = a buffer size used in some character-handling routines. define(BUFSZ, 20)   function maxvtx (numedg, edges)   # Find the maximum vertex number.   implicit none   integer numedg real edges(1:3, 1:numedg) # Notice Fortran's column-major order! integer maxvtx   integer n, i   n = 1 for (i = 1; i <= numedg; i = i + 1) { n = max (n, int (edges(1, i))) n = max (n, int (edges(3, i))) } maxvtx = n end   subroutine floyd (numedg, edges, n, dist, nxtvtx)   # Floyd-Warshall.   implicit none   integer numedg real edges(1:3, 1:numedg) # Notice Fortran's column-major order! integer n real dist(1:VLIMIT, 1:VLIMIT) integer nxtvtx(1:VLIMIT, 1:VLIMIT)   # # This implementation does NOT initialize elements of "dist" that # would be set "infinite" in the original Fortran 90. Such elements # are left uninitialized. Instead you should use the "nxtvtx" array # to determine whether there exists a finite path from one vertex to # another. # # See also the Icon and Object Icon implementations that use "&null" # as a stand-in for "infinity". This implementation is similar to # those. In this Ratfor, the nil entry in "nxtvtx" is used instead # of one in "dist". #   integer i, j, k integer u, v real dstikj   # Initialization.   for (i = 1; i <= n; i = i + 1) for (j = 1; j <= n; j = j + 1) nxtvtx(i, j) = NILVTX for (i = 1; i <= numedg; i = i + 1) { u = int (edges(1, i)) v = int (edges(3, i)) dist(u, v) = edges(2, i) nxtvtx(u, v) = v } for (i = 1; i <= n; i = i + 1) { dist(i, i) = 0.0 # Distance from a vertex to itself. nxtvtx(i, i) = i }   # Perform the algorithm.   for (k = 1; k <= n; k = k + 1) for (i = 1; i <= n; i = i + 1) for (j = 1; j <= n; j = j + 1) if (nxtvtx(i, k) != NILVTX && nxtvtx(k, j) != NILVTX) { dstikj = dist(i, k) + dist(k, j) if (nxtvtx(i, j) == NILVTX) { dist(i, j) = dstikj nxtvtx(i, j) = nxtvtx(i, k) } else if (dstikj < dist(i, j)) { dist(i, j) = dstikj nxtvtx(i, j) = nxtvtx(i, k) } } end   subroutine cpy (chr, str, j)   # A helper subroutine for pthstr.   implicit none   character*BUFSZ chr character str*STRSZ integer j   integer i   i = 1 while (chr(i:i) == ' ') { if (i == BUFSZ) { write (*, *) "character* boundary exceeded in cpy" stop } i = i + 1 } while (i <= BUFSZ) { if (STRSZ < j) { write (*, *) "character* boundary exceeded in cpy" stop } str(j:j) = chr(i:i) j = j + 1 i = i + 1 } end   subroutine pthstr (nxtvtx, u, v, str, k)   # Construct a string for a path from u to v. Start at str(k).   implicit none   integer nxtvtx(1:VLIMIT, 1:VLIMIT) integer u, v character str*STRSZ integer k   integer i, j character*BUFSZ chr character*25 fmt10 character*25 fmt20   write (fmt10, '(''(I'', I15, '')'')') BUFSZ - 1 write (fmt20, '(''(A'', I15, '')'')') BUFSZ   if (nxtvtx(u, v) != NILVTX) { j = k i = u chr = ' ' write (chr, fmt10) i call cpy (chr, str, j) while (i != v) { write (chr, fmt20) "-> " call cpy (chr, str, j) i = nxtvtx(i, v) write (chr, fmt10) i call cpy (chr, str, j) } } end   function trimr (str)   # Find the length of a character*, if one ignores trailing spaces.   implicit none   character str*STRSZ integer trimr   logical done   trimr = STRSZ done = .false. while (!done) { if (trimr == 0) done = .true. else if (str(trimr:trimr) != ' ') done = .true. else trimr = trimr - 1 } end   program demo implicit none   integer maxvtx integer trimr   integer exmpsz real exampl(1:3, 1:5) integer n real dist(1:VLIMIT, 1:VLIMIT) integer nxtvtx(1:VLIMIT, 1:VLIMIT) character str*STRSZ integer u, v integer j   exmpsz = 5 data exampl / 1, -2.0, 3, _ 3, +2.0, 4, _ 4, -1.0, 2, _ 2, +4.0, 1, _ 2, +3.0, 3 /   n = maxvtx (exmpsz, exampl) call floyd (exmpsz, exampl, n, dist, nxtvtx)   1000 format (I2, ' ->', I2, 5X, F4.1, 6X)   write (*, '('' pair distance path'')') write (*, '(''---------------------------------------'')') for (u = 1; u <= n; u = u + 1) for (v = 1; v <= n; v = v + 1) if (u != v) { str = ' ' write (str, 1000) u, v, dist(u, v) call pthstr (nxtvtx, u, v, str, 23) write (* , '(1000A1)') (str(j:j), j = 1, trimr (str)) } 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
#VBScript
VBScript
function multiply( multiplicand, multiplier ) multiply = multiplicand * multiplier end function
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
#Visual_Basic
Visual Basic
  Function multiply(a As Integer, b As Integer) As Integer multiply = 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.)
#Scala
Scala
def fdiff(xs: List[Int]) = (xs.tail, xs).zipped.map(_ - _)   def fdiffn(i: Int, xs: List[Int]): List[Int] = if (i == 1) fdiff(xs) else fdiffn(i - 1, fdiff(xs))
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.)
#Scheme
Scheme
(define (forward-diff lst) (if (or (null? lst) (null? (cdr lst))) '() (cons (- (cadr lst) (car lst)) (forward-diff (cdr lst)))))   (define (nth-forward-diff n xs) (if (= n 0) xs (nth-forward-diff (- n 1) (forward-diff xs))))
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).
#Scala
Scala
object FourBitAdder { type Nibble=(Boolean, Boolean, Boolean, Boolean)   def xor(a:Boolean, b:Boolean)=(!a)&&b || a&&(!b)   def halfAdder(a:Boolean, b:Boolean)={ val s=xor(a,b) val c=a && b (s, c) }   def fullAdder(a:Boolean, b:Boolean, cIn:Boolean)={ val (s1, c1)=halfAdder(a, cIn) val (s, c2)=halfAdder(s1, b) val cOut=c1 || c2 (s, cOut) }   def fourBitAdder(a:Nibble, b:Nibble)={ val (s0, c0)=fullAdder(a._4, b._4, false) val (s1, c1)=fullAdder(a._3, b._3, c0) val (s2, c2)=fullAdder(a._2, b._2, c1) val (s3, cOut)=fullAdder(a._1, b._1, c2) ((s3, s2, s1, s0), cOut) } }
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.
#Relation
Relation
  program fivenum(X) rename X^ x order x 1 dup project x min, x median, x max, x count set q1 = x_count / 4 set q1min = floor(q1) set q1weight = q1 - q1min set q3 = x_count * 3 / 4 set q3min = floor(q3) set q3weight = q3 - q3min swap dup select rownumber = q1min + 1 or rownumber = q1min + 2 extend w = q1weight * (rownumber - 1) - (rownumber-1-1) * (1-q1weight) extend xw = x * w project xw sum rename xw_sum x_quarter1 swap select rownumber = q3min + 1 or rownumber = q3min + 2 extend w = q3weight * (rownumber - 1) - (rownumber-1-1) * (1-q3weight) extend xw = x * w project xw sum rename xw_sum x_quarter3 join cross join cross project x_min, x_quarter1, x_median, x_quarter3, x_max print end program   relation a insert 3 insert 4 insert 18 insert 12 insert 17 insert 5 insert 6 insert 11 insert 8 run fivenum("a")  
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.
#REXX
REXX
/*REXX program computes the five─number summary (LO─value, p25, medium, p75, HI─value).*/ parse arg x if x='' then x= 15 6 42 41 7 36 49 40 39 47 43 /*Not specified? Then use the defaults*/ say 'input numbers: ' space(x) /*display the original list of numbers.*/ call 5num /*invoke the five─number function. */ say ' five─numbers: ' result /*display " " " results. */ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ bSort: procedure expose @.; parse arg n; m=n-1 /*N: the number of @ array elements.*/ do m=m for m by -1 until ok; ok= 1 /*keep sorting the @ array 'til done.*/ do j=1 for m; k= j + 1; /*set K to the next item in @ array.*/ if @.j<[email protected] then iterate /*Is @.J in numerical order? Good. */ parse value @.j @.k 0 with @.k @.j ok /*swap two elements and flag as ¬done.*/ end /*j*/ end /*m*/; return /*──────────────────────────────────────────────────────────────────────────────────────*/ med: arg s,e; $=e-s+1; m=s+$%2; if $//2 then return @.m; _=m-1; return (@[email protected])/2 /*──────────────────────────────────────────────────────────────────────────────────────*/ 5num: #= words(x); if #==0 then return '***error*** array is empty.' parse var x . 1 LO . 1 HI . /*assume values for LO and HI (for now)*/ q2= # % 2; er= '***error*** element' do j=1 for #; @.j= word(x, j) if \datatype(@.j, 'N') then return er j "isn't numeric: " @.j LO= min(LO, @.j); HI= max(HI, @.j) end /*j*/ /* [↑] traipse thru array, find min,max*/ call bSort # /*use a bubble sort (easiest to code). */ if #//2 then p25= q2 /*calculate the second quartile number.*/ else p25= q2 - 1 /* " " " " " */ return LO med(1, p25) med(1, #) med(q2, #) HI /*return list of 5 numbers.*/
http://rosettacode.org/wiki/Find_the_missing_permutation
Find the missing permutation
ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB Listed above are   all-but-one   of the permutations of the symbols   A,   B,   C,   and   D,   except   for one permutation that's   not   listed. Task Find that missing permutation. Methods Obvious method: enumerate all permutations of A, B, C, and D, and then look for the missing permutation. alternate method: Hint: if all permutations were shown above, how many times would A appear in each position? What is the parity of this number? another alternate method: Hint: if you add up the letter values of each column, does a missing letter A, B, C, and D from each column cause the total value for each column to be unique? Related task   Permutations)
#C.23
C#
using System; using System.Collections.Generic;   namespace MissingPermutation { class Program { static void Main() { string[] given = new string[] { "ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", "ADCB", "CDAB", "DABC", "BCAD", "CADB", "CDBA", "CBAD", "ABDC", "ADBC", "BDCA", "DCBA", "BACD", "BADC", "BDAC", "CBDA", "DBCA", "DCAB" };   List<string> result = new List<string>(); permuteString(ref result, "", "ABCD");   foreach (string a in result) if (Array.IndexOf(given, a) == -1) Console.WriteLine(a + " is a missing Permutation"); }   public static void permuteString(ref List<string> result, string beginningString, string endingString) { if (endingString.Length <= 1) { result.Add(beginningString + endingString); } else { for (int i = 0; i < endingString.Length; i++) { string newString = endingString.Substring(0, i) + endingString.Substring(i + 1); permuteString(ref result, beginningString + (endingString.ToCharArray())[i], newString); } } } } }
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month
Find the last Sunday of each month
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 2013-05-26 2013-06-30 2013-07-28 2013-08-25 2013-09-29 2013-10-27 2013-11-24 2013-12-29 Related tasks Day of the week Five weekends Last Friday of each month
#D
D
void lastSundays(in uint year) { import std.stdio, std.datetime;   foreach (immutable month; 1 .. 13) { auto date = Date(year, month, 1); date.day(date.daysInMonth); date.roll!"days"(-(date.dayOfWeek + 7) % 7); date.writeln; } }   void main() { lastSundays(2013); }
http://rosettacode.org/wiki/Find_the_intersection_of_two_lines
Find the intersection of two lines
[1] Task Find the point of intersection of two lines in 2D. The 1st line passes though   (4,0)   and   (6,10) . The 2nd line passes though   (0,3)   and   (10,7) .
#Frink
Frink
lineIntersection[x1, y1, x2, y2, x3, y3, x4, y4] := { det = (x1 - x2)(y3 - y4) - (y1 - y2)(x3 - x4) if det == 0 return undef   t1 = (x1 y2 - y1 x2) t2 = (x3 y4 - y3 x4) px = (t1 (x3 - x4) - t2 (x1 - x2)) / det py = (t1 (y3 - y4) - t2 (y1 - y2)) / det return [px, py] }   println[lineIntersection[4, 0, 6, 10, 0, 3, 10, 7]]
http://rosettacode.org/wiki/Find_the_intersection_of_two_lines
Find the intersection of two lines
[1] Task Find the point of intersection of two lines in 2D. The 1st line passes though   (4,0)   and   (6,10) . The 2nd line passes though   (0,3)   and   (10,7) .
#Go
Go
  package main   import ( "fmt" "errors" )   type Point struct { x float64 y float64 }   type Line struct { slope float64 yint float64 }   func CreateLine (a, b Point) Line { slope := (b.y-a.y) / (b.x-a.x) yint := a.y - slope*a.x return Line{slope, yint} }   func EvalX (l Line, x float64) float64 { return l.slope*x + l.yint }   func Intersection (l1, l2 Line) (Point, error) { if l1.slope == l2.slope { return Point{}, errors.New("The lines do not intersect") } x := (l2.yint-l1.yint) / (l1.slope-l2.slope) y := EvalX(l1, x) return Point{x, y}, nil }   func main() { l1 := CreateLine(Point{4, 0}, Point{6, 10}) l2 := CreateLine(Point{0, 3}, Point{10, 7}) if result, err := Intersection(l1, l2); err == nil { fmt.Println(result) } else { fmt.Println("The lines do not intersect") } }  
http://rosettacode.org/wiki/Find_the_intersection_of_a_line_with_a_plane
Find the intersection of a line with a plane
Finding the intersection of an infinite ray with a plane in 3D is an important topic in collision detection. Task Find the point of intersection for the infinite ray with direction   (0, -1, -1)   passing through position   (0, 0, 10)   with the infinite plane with a normal vector of   (0, 0, 1)   and which passes through [0, 0, 5].
#Haskell
Haskell
import Control.Applicative (liftA2) import Text.Printf (printf)   data V3 a = V3 a a a deriving Show   instance Functor V3 where fmap f (V3 a b c) = V3 (f a) (f b) (f c)   instance Applicative V3 where pure a = V3 a a a V3 a b c <*> V3 d e f = V3 (a d) (b e) (c f)   instance Num a => Num (V3 a) where (+) = liftA2 (+) (-) = liftA2 (-) (*) = liftA2 (*) negate = fmap negate abs = fmap abs signum = fmap signum fromInteger = pure . fromInteger   dot ::Num a => V3 a -> V3 a -> a dot a b = x + y + z where V3 x y z = a * b   intersect :: Fractional a => V3 a -> V3 a -> V3 a -> V3 a -> V3 a intersect rayVector rayPoint planeNormal planePoint = rayPoint - rayVector * pure prod3 where diff = rayPoint - planePoint prod1 = diff `dot` planeNormal prod2 = rayVector `dot` planeNormal prod3 = prod1 / prod2   main = printf "The ray intersects the plane at (%f, %f, %f)\n" x y z where V3 x y z = intersect rv rp pn pp :: V3 Double rv = V3 0 (-1) (-1) rp = V3 0 0 10 pn = V3 0 0 1 pp = V3 0 0 5
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
#APL
APL
⎕IO←0 (L,'Fizz' 'Buzz' 'FizzBuzz')[¯1+(L×W=0)+W←(100×~0=W)+W←⊃+/1 2×0=3 5|⊂L←1+⍳100]  
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
#ERRE
ERRE
  PROGRAM FIVE_WEEKENDS   DIM M$[12]   PROCEDURE MODULO(X,Y->MD) IF Y=0 THEN MD=X ELSE MD=X-Y*INT(X/Y) END IF END PROCEDURE   PROCEDURE WD(M,D,Y->RES%) IF M=1 OR M=2 THEN M+=12 Y-=1 END IF MODULO(365*Y+INT(Y/4)-INT(Y/100)+INT(Y/400)+D+INT((153*M+8)/5),7->RES) RES%=RES+1.0 END PROCEDURE   BEGIN M$[]=("","JANUARY","FEBRUARY","MARCH","APRIL","MAY","JUNE","JULY","AUGUST","SEPTEMBER","OCTOBER","NOVEMBER","DECEMBER") PRINT(CHR$(12);) ! CLS FOR YEAR=1900 TO 2100 DO FOREACH MONTH IN (1,3,5,7,8,10,12) DO  ! months with 31 days WD(MONTH,1,YEAR->RES%) IF RES%=6 THEN  ! day #6 is Friday PRINT(YEAR;": ";M$[MONTH]) CNT%=CNT%+1 ! IF CNT% MOD 20=0 THEN GET(K$) END IF  ! press a key for next page END IF END FOR END FOR PRINT("Total =";CNT%) END PROGRAM  
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
#Euphoria
Euphoria
  --Five Weekend task from Rosetta Code wiki --User:Lnettnay   include std/datetime.e   atom numbermonths = 0 sequence longmonths = {1, 3, 5, 7, 8, 10, 12} sequence yearsmonths = {} atom none = 0 datetime dt   for year = 1900 to 2100 do atom flag = 0 for month = 1 to length(longmonths) do dt = new(year, longmonths[month], 1) if weeks_day(dt) = 6 then --Friday is day 6 flag = 1 numbermonths += 1 yearsmonths = append(yearsmonths, {year, longmonths[month]}) end if end for   if flag = 0 then none += 1 end if end for   puts(1, "Number of months with five full weekends from 1900 to 2100 = ") ? numbermonths   puts(1, "First five and last five years, months\n")   for count = 1 to 5 do ? yearsmonths[count] end for   for count = length(yearsmonths) - 4 to length(yearsmonths) do ? yearsmonths[count] end for   puts(1, "Number of years that have no months with five full weekends = ") ? none  
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
#REXX
REXX
/*REXX program finds/displays the first perfect square with N unique digits in base N.*/ numeric digits 40 /*ensure enough decimal digits for a #.*/ parse arg LO HI . /*obtain optional argument from the CL.*/ if LO=='' then do; LO=2; HI=16; end /*not specified? Then use the default.*/ if LO==',' then LO=2 /*not specified? Then use the default.*/ if HI=='' | HI=="," then HI=LO /*not specified? Then use the default.*/ @start= 1023456789abcdefghijklmnopqrstuvwxyz /*contains the start # (up to base 36).*/ /* [↓] find the smallest square with */ do j=LO to HI; beg= left(@start, j) /* N unique digits in base N. */ do k=iSqrt( base(beg,10,j) ) until #==0 /*start each search from smallest sqrt.*/ $= base(k*k, j, 10) /*calculate square, convert to base J. */ $u= $; upper $u /*get an uppercase version fast count. */ #= verify(beg, $u) /*count differences between 2 numbers. */ end /*k*/ say 'base' right(j, length(HI) ) " root=" , lower( right( base(k, j, 10), max(5, HI) ) ) ' square=' lower($) end /*j*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ base: procedure; arg x 1 #,toB,inB /*obtain: three arguments. */ @l= '0123456789abcdefghijklmnopqrstuvwxyz' /*lowercase (Latin or English) alphabet*/ @u= @l; upper @u /*uppercase " " " " */ if inb\==10 then /*only convert if not base 10. */ do 1; #= 0 /*result of converted X (in base 10).*/ if inb==2 then do; #= b2d(x); leave; end /*convert binary to decimal. */ if inb==16 then do; #= x2d(x); leave; end /* " hexadecimal " " */ do j=1 for length(x) /*convert X: base inB ──► base 10. */ #= # * inB + pos(substr(x,j,1), @u)-1 /*build a new number, digit by digit. */ end /*j*/ /* [↑] this also verifies digits. */ end y= /*the value of X in base B (so far).*/ if tob==10 then return # /*if TOB is ten, then simply return #.*/ if tob==2 then return d2b(#) /*convert base 10 number to binary. */ if tob==16 then return lower( d2x(#) ) /* " " " " " hexadecimal*/ do while # >= toB /*convert #: decimal ──► base toB.*/ y= substr(@l, (# // toB) + 1, 1)y /*construct the output number. */ #= # % toB /* ··· and whittle # down also. */ end /*while*/ /* [↑] algorithm may leave a residual.*/ return substr(@l, # + 1, 1)y /*prepend the residual, if any. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ iSqrt: procedure; parse arg x; r=0; q=1; do while q<=x; q=q*4; end do while q>1; q=q%4; _=x-r-q; r=r%2; if _>=0 then do;x=_;r=r+q; end; end; return r /*──────────────────────────────────────────────────────────────────────────────────────*/ b2d: return x2d( b2x( arg(1) ) ) /*convert binary number to decimal*/ d2b: return x2b( d2x( arg(1) ) ) + 0 /* " hexadecimal " " " */ lower: @abc= 'abcdefghijklmnopqrstuvwxyz'; return translate(arg(1), @abc, translate(@abc))
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
#F.23
F#
open System   let cube x = x ** 3.0 let croot x = x ** (1.0/3.0)   let funclist = [Math.Sin; Math.Cos; cube] let funclisti = [Math.Asin; Math.Acos; croot] let composed = List.map2 (<<) funclist funclisti   let main() = for f in composed do printfn "%f" (f 0.5)   main()
http://rosettacode.org/wiki/First-class_functions
First-class functions
A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming: Create new functions from preexisting functions at run-time Store functions in collections Use functions as arguments to other functions Use functions as return values of other functions Task Write a program to create an ordered collection A of functions of a real number. At least one function should be built-in and at least one should be user-defined; try using the sine, cosine, and cubing functions. Fill another collection B with the inverse of each function in A. Implement function composition as in Functional Composition. Finally, demonstrate that the result of applying the composition of each function in A and its inverse in B to a value, is the original value. (Within the limits of computational accuracy). (A solution need not actually call the collections "A" and "B". These names are only used in the preceding paragraph for clarity.) Related task First-class Numbers
#Factor
Factor
USING: assocs combinators kernel math.functions prettyprint sequences ; IN: rosettacode.first-class-functions   CONSTANT: A { [ sin ] [ cos ] [ 3 ^ ] } CONSTANT: B { [ asin ] [ acos ] [ 1/3 ^ ] }   : compose-all ( seq1 seq2 -- seq ) [ compose ] 2map ;   : test-fcf ( -- ) 0.5 A B compose-all [ call( x -- y ) ] with map . ;
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.
#Nim
Nim
import random, os, sequtils, strutils   randomize()   type State {.pure.} = enum Empty, Tree, Fire   const Disp: array[State, string] = [" ", "\e[32m/\\\e[m", "\e[07;31m/\\\e[m"] TreeProb = 0.01 BurnProb = 0.001   proc chance(prob: float): bool {.inline.} = rand(1.0) < prob   # Set the size var w, h: int if paramCount() >= 2: w = paramStr(1).parseInt h = paramStr(2).parseInt if w <= 0: w = 30 if h <= 0: h = 30   iterator fields(a = (0, 0), b = (h-1, w-1)): tuple[y, x: int] = ## Iterate over fields in the universe for y in max(a[0], 0) .. min(b[0], h-1): for x in max(a[1], 0) .. min(b[1], w-1): yield (y, x)   # Initialize var univ, univNew = newSeqWith(h, newSeq[State](w))   while true:   # Show. stdout.write "\e[H" for y, x in fields(): stdout.write Disp[univ[y][x]] if x == 0: stdout.write "\e[E" stdout.flushFile   # Evolve. for y, x in fields(): case univ[y][x] of Fire: univNew[y][x] = Empty of Empty: if chance(TreeProb): univNew[y][x] = Tree of Tree: for y1, x1 in fields((y-1, x-1), (y+1, x+1)): if univ[y1][x1] == Fire: univNew[y][x] = Fire break if chance(BurnProb): univNew[y][x] = Fire univ = univNew sleep 200
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
#Factor
Factor
USE: sequences.deep ( scratchpad ) { { 1 } 2 { { 3 4 } 5 } { { { } } } { { { 6 } } } 7 8 { } } flatten . { 1 2 3 4 5 6 7 8 }
http://rosettacode.org/wiki/Flipping_bits_game
Flipping bits game
The game Given an   N×N   square array of zeroes or ones in an initial configuration,   and a target configuration of zeroes and ones. The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered columns at once   (as one move). In an inversion.   any  1  becomes  0,   and any  0  becomes  1  for that whole row or column. Task Create a program to score for the Flipping bits game. The game should create an original random target configuration and a starting configuration. Ensure that the starting position is never the target position. The target position must be guaranteed as reachable from the starting position.   (One possible way to do this is to generate the start position by legal flips from a random target position.   The flips will always be reversible back to the target from the given start position). The number of moves taken so far should be shown. Show an example of a short game here, on this page, for a   3×3   array of bits.
#Wren
Wren
import "random" for Random import "/ioutil" for Input import "/str" for Str   var rand = Random.new() var target = List.filled(3, null) var board = List.filled(3, null) for (i in 0..2) { target[i] = List.filled(3, 0) board[i] = List.filled(3, 0) for (j in 0..2) target[i][j] = rand.int(2) }   var flipRow = Fn.new { |r| for (c in 0..2) board[r][c] = (board[r][c] == 0) ? 1 : 0 }   var flipCol = Fn.new { |c| for (r in 0..2) board[r][c] = (board[r][c] == 0) ? 1 : 0 }   /* starting from the target we make 9 random row or column flips */ var initBoard = Fn.new { for (i in 0..2) { for (j in 0..2) board[i][j] = target[i][j] } for (i in 1..9) { var rc = rand.int(2) if (rc == 0) { flipRow.call(rand.int(3)) } else { flipCol.call(rand.int(3)) } } }   var printBoard = Fn.new { |label, isTarget| var a = (isTarget) ? target : board System.print("%(label):") System.print(" | a b c") System.print("---------") for (r in 0..2) { System.write("%(r + 1) |") for (c in 0..2) System.write(" %(a[r][c])") System.print() } System.print() }   var gameOver = Fn.new { for (r in 0..2) { for (c in 0..2) if (board[r][c] != target[r][c]) return false } return true }   // initialize board and ensure it differs from the target i.e. game not already over! while (true) { initBoard.call() if (!gameOver.call()) break }   printBoard.call("TARGET", true) printBoard.call("OPENING BOARD", false) var flips = 0   while (true) { var isRow = true var n = -1 var prompt = "Enter row number or column letter to be flipped: " var ch = Str.lower(Input.option(prompt, "123abcABC")) if (ch == "1" || ch == "2" || ch == "3") { n = ch.bytes[0] - 49 } else { isRow = false n = ch.bytes[0] - 97 } flips = flips + 1 if (isRow) flipRow.call(n) else flipCol.call(n) var plural = (flips == 1) ? "" : "S" printBoard.call("\nBOARD AFTER %(flips) FLIP%(plural)", false) if (gameOver.call()) break }   var plural = (flips == 1) ? "" : "s" System.print("You've succeeded in %(flips) flip%(plural)")
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
#Wren
Wren
import "/fmt" for Fmt   var multiplier = Fn.new { |n1, n2| Fn.new { |m| n1 * n2 * m } }   var orderedCollection = Fn.new { var x = 2.0 var xi = 0.5 var y = 4.0 var yi = 0.25 var z = x + y var zi = 1.0 / ( x + y ) return [[x, y, z], [xi, yi, zi]] }   var oc = orderedCollection.call() for (i in 0..2) { var x = oc[0][i] var y = oc[1][i] var m = 0.5 // rather than 1 to compare with first-class functions task Fmt.print("$0.1g * $g * $0.1g = $0.1g", x, y, m, multiplier.call(x, y).call(m)) }
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
#zkl
zkl
var x=2.0, y=4.0, z=(x+y), c=T(x,y,z).apply(fcn(n){ T(n,1.0/n) }); //-->L(L(2,0.5),L(4,0.25),L(6,0.166667))
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
#Yabasic
Yabasic
  gosub subrutina   label bucle print "Bucle infinito" goto bucle end   label subrutina print "En subrutina" wait 10 return 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
#Z80_Assembly
Z80 Assembly
PrintString: ld a,(hl) ;HL is our pointer to the string we want to print cp 0 ;it's better to use OR A to compare A to zero, but for demonstration purposes this is easier to read. ret z ;return if accumulator = zero call PrintChar ;prints accumulator's ascii code to screen - on Amstrad CPC for example this label points to memory address &BB5A inc hl ;next char jr PrintString ;jump back to the start of the loop. RET Z is our only exit.
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.
#JavaScript
JavaScript
(function () { 'use strict';   // FLOYD's TRIANGLE -------------------------------------------------------   // floyd :: Int -> [[Int]] function floyd(n) { return snd(mapAccumL(function (start, row) { return [start + row + 1, enumFromTo(start, start + row)]; }, 1, enumFromTo(0, n - 1))); };   // showFloyd :: [[Int]] -> String function showFloyd(xss) { var ws = map(compose([succ, length, show]), last(xss)); return unlines(map(function (xs) { return concat(zipWith(function (w, x) { return justifyRight(w, ' ', show(x)); }, ws, xs)); }, xss)); };     // GENERIC FUNCTIONS ------------------------------------------------------   // compose :: [(a -> a)] -> (a -> a) function compose(fs) { return function (x) { return fs.reduceRight(function (a, f) { return f(a); }, x); }; };   // concat :: [[a]] -> [a] | [String] -> String function concat(xs) { if (xs.length > 0) { var unit = typeof xs[0] === 'string' ? '' : []; return unit.concat.apply(unit, xs); } else return []; };   // enumFromTo :: Int -> Int -> [Int] function enumFromTo(m, n) { return Array.from({ length: Math.floor(n - m) + 1 }, function (_, i) { return m + i; }); };   // justifyRight :: Int -> Char -> Text -> Text function justifyRight(n, cFiller, strText) { return n > strText.length ? (cFiller.repeat(n) + strText) .slice(-n) : strText; };   // last :: [a] -> a function last(xs) { return xs.length ? xs.slice(-1)[0] : undefined; };   // length :: [a] -> Int function length(xs) { return xs.length; };   // map :: (a -> b) -> [a] -> [b] function map(f, xs) { return xs.map(f); };   // 'The mapAccumL function behaves like a combination of map and foldl; // it applies a function to each element of a list, passing an accumulating // parameter from left to right, and returning a final value of this // accumulator together with the new list.' (See hoogle )   // mapAccumL :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y]) function mapAccumL(f, acc, xs) { return xs.reduce(function (a, x) { var pair = f(a[0], x);   return [pair[0], a[1].concat([pair[1]])]; }, [acc, []]); };   // show :: // (a -> String) f, Num n => // a -> maybe f -> maybe n -> String var show = JSON.stringify;   // snd :: (a, b) -> b function snd(tpl) { return Array.isArray(tpl) ? tpl[1] : undefined; };   // succ :: Int -> Int function succ(x) { return x + 1; };   // unlines :: [String] -> String function unlines(xs) { return xs.join('\n'); };   // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] function zipWith(f, xs, ys) { var ny = ys.length; return (xs.length <= ny ? xs : xs.slice(0, ny)) .map(function (x, i) { return f(x, ys[i]); }); };   // TEST ( n=5 and n=14 rows ) ---------------------------------------------   return unlines(map(function (n) { return showFloyd(floyd(n)) + '\n'; }, [5, 14])); })();
http://rosettacode.org/wiki/Floyd-Warshall_algorithm
Floyd-Warshall algorithm
The Floyd–Warshall algorithm is an algorithm for finding shortest paths in a weighted graph with positive or negative edge weights. Task Find the lengths of the shortest paths between all pairs of vertices of the given directed graph. Your code may assume that the input has already been checked for loops, parallel edges and negative cycles. Print the pair, the distance and (optionally) the path. Example pair dist path 1 -> 2 -1 1 -> 3 -> 4 -> 2 1 -> 3 -2 1 -> 3 1 -> 4 0 1 -> 3 -> 4 2 -> 1 4 2 -> 1 2 -> 3 2 2 -> 1 -> 3 2 -> 4 4 2 -> 1 -> 3 -> 4 3 -> 1 5 3 -> 4 -> 2 -> 1 3 -> 2 1 3 -> 4 -> 2 3 -> 4 2 3 -> 4 4 -> 1 3 4 -> 2 -> 1 4 -> 2 -1 4 -> 2 4 -> 3 1 4 -> 2 -> 1 -> 3 See also Floyd-Warshall Algorithm - step by step guide (youtube)
#REXX
REXX
/*REXX program uses Floyd─Warshall algorithm to find shortest distance between vertices.*/ v= 4 /*███ {1} ███*/ /*number of vertices in weighted graph.*/ @.= 99999999 /*███ 4 / \ -2 ███*/ /*the default distance (edge weight). */ @.1.3= -2 /*███ / 3 \ ███*/ /*the distance (weight) for an edge. */ @.2.1= 4 /*███ {2} ────► {3} ███*/ /* " " " " " " */ @.2.3= 3 /*███ \ / ███*/ /* " " " " " " */ @.3.4= 2 /*███ -1 \ / 2 ███*/ /* " " " " " " */ @.4.2= -1 /*███ {4} ███*/ /* " " " " " " */   do k=1 for v do i=1 for v do j=1 for v; _= @.i.k + @.k.j /*add two nodes together. */ if @.i.j>_ then @.i.j= _ /*use a new distance (weight) for edge.*/ end /*j*/ end /*i*/ end /*k*/ w= 12; $= left('', 20) /*width of the columns for the output. */ say $ center('vertices',w) center('distance', w) /*display the 1st line of the title. */ say $ center('pair' ,w) center('(weight)', w) /* " " 2nd " " " " */ say $ copies('═' ,w) copies('═' , w) /* " " 3rd " " " " */ /* [↓] display edge distances (weight)*/ do f=1 for v /*process each of the "from" vertices. */ do t=1 for v; if f==t then iterate /* " " " " "to" " */ say $ center(f '───►' t, w) right(@.f.t, w % 2) end /*t*/ /* [↑] the distance between 2 vertices*/ end /*f*/ /*stick a fork in it, we're all done. */
http://rosettacode.org/wiki/Function_definition
Function definition
A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract from showing how functions are created and values returned). Related task   Function prototype
#Visual_Basic_.NET
Visual Basic .NET
Function Multiply(ByVal a As Integer, ByVal b As Integer) As Integer Return a * b End Function
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
#Wart
Wart
def (multiply a b) a*b
http://rosettacode.org/wiki/Forward_difference
Forward difference
Task Provide code that produces a list of numbers which is the   nth  order forward difference, given a non-negative integer (specifying the order) and a list of numbers. The first-order forward difference of a list of numbers   A   is a new list   B,   where   Bn = An+1 - An. List   B   should have one fewer element as a result. The second-order forward difference of   A   will be: tdefmodule Diff do def forward(arr,i\\1) do forward(arr,[],i) end def forward([_|[]],diffs,i) do if i == 1 do IO.inspect diffs else forward(diffs,[],i-1) end end def forward([val1|[val2|vals]],diffs,i) do forward([val2|vals],diffs++[val2-val1],i) end end The same as the first-order forward difference of   B. That new list will have two fewer elements than   A   and one less than   B. The goal of this task is to repeat this process up to the desired order. For a more formal description, see the related   Mathworld article. Algorithmic options Iterate through all previous forward differences and re-calculate a new array each time. Use this formula (from Wikipedia): Δ n [ f ] ( x ) = ∑ k = 0 n ( n k ) ( − 1 ) n − k f ( x + k ) {\displaystyle \Delta ^{n}[f](x)=\sum _{k=0}^{n}{n \choose k}(-1)^{n-k}f(x+k)} (Pascal's Triangle   may be useful for this option.)
#Seed7
Seed7
$ include "seed7_05.s7i";   const func array integer: forwardDifference (in array integer: data) is func result var array integer: diffResult is 0 times 0; local var integer: index is 0; begin for index range 1 to pred(length(data)) do diffResult &:= -data[index] + data[succ(index)]; end for; end func;   const proc: main is func local var array integer: data is [] (90, 47, 58, 29, 22, 32, 55, 5, 55, 73); var integer: level is 0; var integer: number is 0; var boolean: firstElement is TRUE; begin for level range 0 to length(data) do firstElement := TRUE; for number range data do if not firstElement then write(", "); end if; firstElement := FALSE; write(number); end for; writeln; data := forwardDifference(data); end for; end func;
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.)
#SequenceL
SequenceL
  forwardDifference(x(1), n) := forwardDifferenceHelper(x, n, [x]);   forwardDifferenceHelper(x(1), n, result(2)) := let difference := tail(x) - x[1 ... size(x) - 1]; in result when n = 0 or size(x) = 1 else forwardDifferenceHelper(difference, n - 1, result ++ [difference]);  
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).
#Scheme
Scheme
  (import (scheme base) (scheme write) (srfi 60)) ;; for logical bits   ;; Returns a list of bits: '(sum carry) (define (half-adder a b) (list (bitwise-xor a b) (bitwise-and a b)))   ;; Returns a list of bits: '(sum carry) (define (full-adder a b c-in) (let* ((h1 (half-adder c-in a)) (h2 (half-adder (car h1) b))) (list (car h2) (bitwise-ior (cadr h1) (cadr h2)))))   ;; a and b are lists of 4 bits each (define (four-bit-adder a b) (let* ((add-1 (full-adder (list-ref a 3) (list-ref b 3) 0)) (add-2 (full-adder (list-ref a 2) (list-ref b 2) (list-ref add-1 1))) (add-3 (full-adder (list-ref a 1) (list-ref b 1) (list-ref add-2 1))) (add-4 (full-adder (list-ref a 0) (list-ref b 0) (list-ref add-3 1)))) (list (list (car add-4) (car add-3) (car add-2) (car add-1)) (cadr add-4))))   (define (show-eg a b) (display a) (display " + ") (display b) (display " = ") (display (four-bit-adder a b)) (newline))   (show-eg (list 0 0 0 0) (list 0 0 0 0)) (show-eg (list 0 0 0 0) (list 1 1 1 1)) (show-eg (list 1 1 1 1) (list 0 0 0 0)) (show-eg (list 0 1 0 1) (list 1 1 0 0)) (show-eg (list 1 1 1 1) (list 1 1 1 1)) (show-eg (list 1 0 1 0) (list 0 1 0 1))  
http://rosettacode.org/wiki/Fivenum
Fivenum
Many big data or scientific programs use boxplots to show distributions of data.   In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM.   It can be useful to save large arrays as arrays with five numbers to save memory. For example, the   R   programming language implements Tukey's five-number summary as the fivenum function. Task Given an array of numbers, compute the five-number summary. Note While these five numbers can be used to draw a boxplot,   statistical packages will typically need extra data. Moreover, while there is a consensus about the "box" of the boxplot,   there are variations among statistical packages for the whiskers.
#Ring
Ring
  rem1 = 0 rem2 = 0 rem3 = 0 rem4 = 0 rem5 = 0 fn1 = [15, 6, 42, 41, 7, 36, 49, 40, 39, 47, 43] fn2 = [36, 40, 7, 39, 41, 15] fn3 = [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] decimals(1) fivenum(fn1) showarray([rem1,rem2,rem3,rem4,rem5]) fivenum(fn2) showarray([rem1,rem2,rem3,rem4,rem5]) decimals(8) fivenum(fn3) showarray([rem1,rem2,rem3,rem4,rem5])   func median(table,low,high) l = high-low+1 m = low + floor(l/2) if l%2 = 1 return table[m] ok return (table[m-1]+table[m])/2   func fivenum(table) table = sort(table) low = len(table) m = floor(low/2)+low%2 rem1 = table[1] rem2 = median(table,1,m) rem3 = median(table,1,low) rem4 = median(table,m+1,low) rem5 = table[low] return [rem1, rem2, rem3, rem4, rem5]   func showarray vect svect = "" for n in vect svect += " " + n + "," next  ? "[" + left(svect, len(svect) - 1) + "]"  
http://rosettacode.org/wiki/Fivenum
Fivenum
Many big data or scientific programs use boxplots to show distributions of data.   In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM.   It can be useful to save large arrays as arrays with five numbers to save memory. For example, the   R   programming language implements Tukey's five-number summary as the fivenum function. Task Given an array of numbers, compute the five-number summary. Note While these five numbers can be used to draw a boxplot,   statistical packages will typically need extra data. Moreover, while there is a consensus about the "box" of the boxplot,   there are variations among statistical packages for the whiskers.
#Ruby
Ruby
def fivenum(array) sorted_arr = array.sort n = array.size n4 = (((n + 3).to_f / 2.to_f) / 2.to_f).floor d = Array.[](1, n4, ((n.to_f + 1) / 2).to_i, n + 1 - n4, n) sum_array = [] (0..4).each do |e| # each loops have local scope, for loops don't index_floor = (d[e] - 1).floor index_ceil = (d[e] - 1).ceil sum_array.push(0.5 * (sorted_arr[index_floor] + sorted_arr[index_ceil])) end sum_array end   test_array = [15, 6, 42, 41, 7, 36, 49, 40, 39, 47, 43] tukey_array = fivenum(test_array) p tukey_array test_array = [36, 40, 7, 39, 41, 15] tukey_array = fivenum(test_array) p tukey_array test_array = [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] tukey_array = fivenum(test_array) p tukey_array  
http://rosettacode.org/wiki/Find_the_missing_permutation
Find the missing permutation
ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB Listed above are   all-but-one   of the permutations of the symbols   A,   B,   C,   and   D,   except   for one permutation that's   not   listed. Task Find that missing permutation. Methods Obvious method: enumerate all permutations of A, B, C, and D, and then look for the missing permutation. alternate method: Hint: if all permutations were shown above, how many times would A appear in each position? What is the parity of this number? another alternate method: Hint: if you add up the letter values of each column, does a missing letter A, B, C, and D from each column cause the total value for each column to be unique? Related task   Permutations)
#C.2B.2B
C++
#include <algorithm> #include <vector> #include <set> #include <iterator> #include <iostream> #include <string>   static const std::string GivenPermutations[] = { "ABCD","CABD","ACDB","DACB", "BCDA","ACBD","ADCB","CDAB", "DABC","BCAD","CADB","CDBA", "CBAD","ABDC","ADBC","BDCA", "DCBA","BACD","BADC","BDAC", "CBDA","DBCA","DCAB" }; static const size_t NumGivenPermutations = sizeof(GivenPermutations) / sizeof(*GivenPermutations);   int main() { std::vector<std::string> permutations; std::string initial = "ABCD"; permutations.push_back(initial);   while(true) { std::string p = permutations.back(); std::next_permutation(p.begin(), p.end()); if(p == permutations.front()) break; permutations.push_back(p); }   std::vector<std::string> missing; std::set<std::string> given_permutations(GivenPermutations, GivenPermutations + NumGivenPermutations); std::set_difference(permutations.begin(), permutations.end(), given_permutations.begin(), given_permutations.end(), std::back_inserter(missing)); std::copy(missing.begin(), missing.end(), std::ostream_iterator<std::string>(std::cout, "\n")); return 0; }
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month
Find the last Sunday of each month
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 2013-05-26 2013-06-30 2013-07-28 2013-08-25 2013-09-29 2013-10-27 2013-11-24 2013-12-29 Related tasks Day of the week Five weekends Last Friday of each month
#Delphi
Delphi
  program Find_the_last_Sunday_of_each_month;   {$APPTYPE CONSOLE}   uses System.SysUtils, System.DateUtils;   // ADayOfWeek -> sunday is the first day and is 1 function LastDayOfWeekOfEachMonth(AYear, ADayOfWeek: Word): TArray<TDateTime>; var month: word; daysOffset: Integer; date: TDatetime; begin if (ADayOfWeek > 7) or (ADayOfWeek < 1) then raise Exception.CreateFmt('Error on FindAllDaysOfWeek: "%d" must be in [1..7] (sun..sat)', [ADayOfWeek]);   SetLength(Result, 12);   for month := 1 to 12 do begin date := EncodeDate(AYear, month, DaysInAMonth(AYear, month));   daysOffset := DayOfWeek(date) - ADayOfWeek; if daysOffset < 0 then inc(daysOffset, 7);   Result[month - 1] := date - daysOffset; end; end;   var strYear: string; Year: Integer; date: TDateTime;   begin write('Year to calculate: '); Readln(strYear); if not TryStrToInt(strYear, Year) or (Year < 1900) then raise Exception.CreateFmt('Error: "%s" is not a valid year', [strYear]);   for date in LastDayOfWeekOfEachMonth(Year, 1) do writeln(FormatDateTime('yyyy-mmm-dd', date));   readln; end.
http://rosettacode.org/wiki/Find_the_intersection_of_two_lines
Find the intersection of two lines
[1] Task Find the point of intersection of two lines in 2D. The 1st line passes though   (4,0)   and   (6,10) . The 2nd line passes though   (0,3)   and   (10,7) .
#Groovy
Groovy
class Intersection { private static class Point { double x, y   Point(double x, double y) { this.x = x this.y = y }   @Override String toString() { return "($x, $y)" } }   private static class Line { Point s, e   Line(Point s, Point e) { this.s = s this.e = e } }   private static Point findIntersection(Line l1, Line l2) { double a1 = l1.e.y - l1.s.y double b1 = l1.s.x - l1.e.x double c1 = a1 * l1.s.x + b1 * l1.s.y   double a2 = l2.e.y - l2.s.y double b2 = l2.s.x - l2.e.x double c2 = a2 * l2.s.x + b2 * l2.s.y   double delta = a1 * b2 - a2 * b1 return new Point((b2 * c1 - b1 * c2) / delta, (a1 * c2 - a2 * c1) / delta) }   static void main(String[] args) { Line l1 = new Line(new Point(4, 0), new Point(6, 10)) Line l2 = new Line(new Point(0, 3), new Point(10, 7)) println(findIntersection(l1, l2))   l1 = new Line(new Point(0, 0), new Point(1, 1)) l2 = new Line(new Point(1, 2), new Point(4, 5)) println(findIntersection(l1, l2)) } }
http://rosettacode.org/wiki/Find_the_intersection_of_a_line_with_a_plane
Find the intersection of a line with a plane
Finding the intersection of an infinite ray with a plane in 3D is an important topic in collision detection. Task Find the point of intersection for the infinite ray with direction   (0, -1, -1)   passing through position   (0, 0, 10)   with the infinite plane with a normal vector of   (0, 0, 1)   and which passes through [0, 0, 5].
#J
J
mp=: +/ .* NB. matrix product p=: mp&{: %~ -~&{. mp {:@] NB. solve intersectLinePlane=: [ +/@:* 1 , p NB. substitute
http://rosettacode.org/wiki/Find_the_intersection_of_a_line_with_a_plane
Find the intersection of a line with a plane
Finding the intersection of an infinite ray with a plane in 3D is an important topic in collision detection. Task Find the point of intersection for the infinite ray with direction   (0, -1, -1)   passing through position   (0, 0, 10)   with the infinite plane with a normal vector of   (0, 0, 1)   and which passes through [0, 0, 5].
#Java
Java
public class LinePlaneIntersection { private static class Vector3D { private double x, y, z;   Vector3D(double x, double y, double z) { this.x = x; this.y = y; this.z = z; }   Vector3D plus(Vector3D v) { return new Vector3D(x + v.x, y + v.y, z + v.z); }   Vector3D minus(Vector3D v) { return new Vector3D(x - v.x, y - v.y, z - v.z); }   Vector3D times(double s) { return new Vector3D(s * x, s * y, s * z); }   double dot(Vector3D v) { return x * v.x + y * v.y + z * v.z; }   @Override public String toString() { return String.format("(%f, %f, %f)", x, y, z); } }   private static Vector3D intersectPoint(Vector3D rayVector, Vector3D rayPoint, Vector3D planeNormal, Vector3D planePoint) { Vector3D diff = rayPoint.minus(planePoint); double prod1 = diff.dot(planeNormal); double prod2 = rayVector.dot(planeNormal); double prod3 = prod1 / prod2; return rayPoint.minus(rayVector.times(prod3)); }   public static void main(String[] args) { Vector3D rv = new Vector3D(0.0, -1.0, -1.0); Vector3D rp = new Vector3D(0.0, 0.0, 10.0); Vector3D pn = new Vector3D(0.0, 0.0, 1.0); Vector3D pp = new Vector3D(0.0, 0.0, 5.0); Vector3D ip = intersectPoint(rv, rp, pn, pp); System.out.println("The ray intersects the plane at " + ip); } }
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
#AppleScript
AppleScript
property outputText: "" repeat with i from 1 to 100 if i mod 15 = 0 then set outputText to outputText & "FizzBuzz" else if i mod 3 = 0 then set outputText to outputText & "Fizz" else if i mod 5 = 0 then set outputText to outputText & "Buzz" else set outputText to outputText & i end if set outputText to outputText & linefeed end repeat outputText
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
#F.23
F#
open System   [<EntryPoint>] let main argv = let (yearFrom, yearTo) = (1900, 2100)   let monthsWith5We year = [1; 3; 5; 7; 8; 10; 12] |> List.filter (fun month -> DateTime(year, month, 1).DayOfWeek = DayOfWeek.Friday)   let ym5we = [yearFrom .. yearTo] |> List.map (fun year -> year, (monthsWith5We year))   let countMonthsWith5We = ym5we |> List.sumBy (snd >> List.length)   let countYearsWithout5WeMonths = ym5we |> List.sumBy (snd >> List.isEmpty >> (function|true->1|_->0))   let allMonthsWith5we = ym5we |> List.filter (snd >> List.isEmpty >> not)   printfn "%d months in the range of years from %d to %d have 5 weekends." countMonthsWith5We yearFrom yearTo printfn "%d years in the range of years from %d to %d have no month with 5 weekends." countYearsWithout5WeMonths yearFrom yearTo printfn "Months with 5 weekends: %A ... %A" (List.take 5 allMonthsWith5we) (List.take 5 (List.skip ((List.length allMonthsWith5we) - 5) allMonthsWith5we)) 0
http://rosettacode.org/wiki/First_perfect_square_in_base_n_with_n_unique_digits
First perfect square in base n with n unique digits
Find the first perfect square in a given base N that has at least N digits and exactly N significant unique digits when expressed in base N. E.G. In base 10, the first perfect square with at least 10 unique digits is 1026753849 (32043²). You may use analytical methods to reduce the search space, but the code must do a search. Do not use magic numbers or just feed the code the answer to verify it is correct. Task Find and display here, on this page, the first perfect square in base N, with N significant unique digits when expressed in base N, for each of base 2 through 12. Display each number in the base N for which it was calculated. (optional) Do the same for bases 13 through 16. (stretch goal) Continue on for bases 17 - ?? (Big Integer math) See also OEIS A260182: smallest square that is pandigital in base n. Related task Casting out nines
#Ring
Ring
  basePlus = [] decList = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] baseList = ["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"]   see "working..." + nl   for base = 2 to 10 for n = 1 to 40000 basePlus = [] nrPow = pow(n,2) str = decimaltobase(nrPow,base) ln = len(str) for m = 1 to ln nr = str[m] ind = find(baseList,nr) num = decList[ind] add(basePlus,num) next flag = 1 basePlus = sort(basePlus) if len(basePlus) = base for p = 1 to base if basePlus[p] = p-1 flag = 1 else flag = 0 exit ok next if flag = 1 see "in base: " + base + " root: " + n + " square: " + nrPow + " perfect square: " + str + nl exit ok ok next next see "done..." + nl   func decimaltobase(nr,base) binList = [] binary = 0 remainder = 1 while(nr != 0) remainder = nr % base ind = find(decList,remainder) rem = baseList[ind] add(binList,rem) nr = floor(nr/base) end binlist = reverse(binList) binList = list2str(binList) binList = substr(binList,nl,"") return binList  
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
#Ruby
Ruby
DIGITS = "1023456789abcdefghijklmnopqrstuvwxyz"   2.upto(16) do |n| start = Integer.sqrt( DIGITS[0,n].to_i(n) ) res = start.step.detect{|i| (i*i).digits(n).uniq.size == n } puts "Base %2d:%10s² = %-14s" % [n, res.to_s(n), (res*res).to_s(n)] end  
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
#Fantom
Fantom
  class FirstClassFns { static |Obj -> Obj| compose (|Obj -> Obj| fn1, |Obj -> Obj| fn2) { return |Obj x -> Obj| { fn2 (fn1 (x)) } }   public static Void main () { cube := |Float a -> Float| { a * a * a } cbrt := |Float a -> Float| { a.pow(1/3f) }   |Float->Float|[] fns := [Float#sin.func, Float#cos.func, cube] |Float->Float|[] inv := [Float#asin.func, Float#acos.func, cbrt] |Float->Float|[] composed := fns.map |fn, i| { compose(fn, inv[i]) }   composed.each |fn| { echo (fn(0.5f)) } } }  
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
#Forth
Forth
: compose ( xt1 xt2 -- xt3 ) >r >r :noname r> compile, r> compile, postpone ; ;   : cube fdup fdup f* f* ; : cuberoot 1e 3e f/ f** ;   : table create does> swap cells + @ ;   table fn ' fsin , ' fcos , ' cube , table inverse ' fasin , ' facos , ' cuberoot ,   : main 3 0 do i fn i inverse compose ( xt ) 0.5e execute f. loop ;   main \ 0.5 0.5 0.5
http://rosettacode.org/wiki/Forest_fire
Forest fire
This page uses content from Wikipedia. The original article was at Forest-fire model. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Implement the Drossel and Schwabl definition of the forest-fire model. It is basically a 2D   cellular automaton   where each cell can be in three distinct states (empty, tree and burning) and evolves according to the following rules (as given by Wikipedia) A burning cell turns into an empty cell A tree will burn if at least one neighbor is burning A tree ignites with probability   f   even if no neighbor is burning An empty space fills with a tree with probability   p Neighborhood is the   Moore neighborhood;   boundary conditions are so that on the boundary the cells are always empty ("fixed" boundary condition). At the beginning, populate the lattice with empty and tree cells according to a specific probability (e.g. a cell has the probability 0.5 to be a tree). Then, let the system evolve. Task's requirements do not include graphical display or the ability to change parameters (probabilities   p   and   f )   through a graphical or command line interface. Related tasks   See   Conway's Game of Life   See   Wireworld.
#OCaml
OCaml
open Curses   let ignite_prob = 0.02 let sprout_prob = 0.01   type cell = Empty | Burning | Tree   let get w x y = try w.(x).(y) with Invalid_argument _ -> Empty   let neighborhood_burning w x y = try for _x = pred x to succ x do for _y = pred y to succ y do if get w _x _y = Burning then raise Exit done done ; false with Exit -> true   let evolves w x y = match w.(x).(y) with | Burning -> Empty | Tree -> if neighborhood_burning w x y then Burning else begin if (Random.float 1.0) < ignite_prob then Burning else Tree end | Empty -> if (Random.float 1.0) < sprout_prob then Tree else Empty   let step width height w = for x = 0 to pred width do for y = 0 to pred height do w.(x).(y) <- evolves w x y done done   let i = int_of_char let repr = function | Empty -> i ' ' | Burning -> i '#' | Tree -> i 't'   let draw width height w = for x = 0 to pred width do for y = 0 to pred height do ignore(move y x); ignore(delch ()); ignore(insch (repr w.(x).(y))); done; done; ignore(refresh ())   let () = Random.self_init (); let wnd = initscr () in ignore(cbreak ()); ignore(noecho ()); let height, width = getmaxyx wnd in let w = Array.make_matrix width height Empty in clear (); ignore(refresh ()); while true do draw width height w; step width height w; Unix.sleep 1; done; endwin()
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
#Fantom
Fantom
  class Main { // uses recursion to flatten a list static List myflatten (List items) { List result := [,] items.each |item| { if (item is List) result.addAll (myflatten(item)) else result.add (item) } return result }   public static Void main () { List sample := [[1], 2, [[3,4], 5], [[[,]]], [[[6]]], 7, 8, [,]] // there is a built-in flatten method for lists echo ("Flattened list 1: " + sample.flatten) // or use the function 'myflatten' echo ("Flattened list 2: " + myflatten (sample)) } }  
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
#zkl
zkl
continue; continue(n); // continue nth nested loop break; break(n); // break out of nth nested loop try{ ... }catch(exception){ ... } [else{ ... }] onExit(fcn); // run fcn when enclosing function exits
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.
#jq
jq
# floyd(n) creates an n-row floyd's triangle def floyd(n): def lpad(len): tostring | (((len - length) * " ") + .);   # Construct an array of widths. # Assuming N is the last integer on the last row (i.e. (n+1)*n/2), # the last row has n entries from (1+N-n) through N: def widths: ((n+1)*n/2) as $N | [range(1 + $N - n; $N + 1) | tostring | length];   # emit line k assuming it starts with the integer "start" def line(start; k; widths): reduce range(start; start+k) as $i (""; . + ($i|lpad(widths[$i - start])) + " ");   widths as $widths | (reduce range(0;n) as $row ( [0, ""]; # state: i, string (.[0] + 1) as $i | .[1] as $string | [ ($i + $row), ($string + "\n" + line($i; $row + 1; $widths )) ] ) | .[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.
#Julia
Julia
function floydtriangle(rows) r = collect(1:div(rows *(rows + 1), 2)) for i in 1:rows for j in 1:i print(rpad(lpad(popfirst!(r), j > 8 ? 3 : 2), j > 8 ? 4 : 3)) end println() end end   floydtriangle(5); println(); floydtriangle(14)    
http://rosettacode.org/wiki/Floyd-Warshall_algorithm
Floyd-Warshall algorithm
The Floyd–Warshall algorithm is an algorithm for finding shortest paths in a weighted graph with positive or negative edge weights. Task Find the lengths of the shortest paths between all pairs of vertices of the given directed graph. Your code may assume that the input has already been checked for loops, parallel edges and negative cycles. Print the pair, the distance and (optionally) the path. Example pair dist path 1 -> 2 -1 1 -> 3 -> 4 -> 2 1 -> 3 -2 1 -> 3 1 -> 4 0 1 -> 3 -> 4 2 -> 1 4 2 -> 1 2 -> 3 2 2 -> 1 -> 3 2 -> 4 4 2 -> 1 -> 3 -> 4 3 -> 1 5 3 -> 4 -> 2 -> 1 3 -> 2 1 3 -> 4 -> 2 3 -> 4 2 3 -> 4 4 -> 1 3 4 -> 2 -> 1 4 -> 2 -1 4 -> 2 4 -> 3 1 4 -> 2 -> 1 -> 3 See also Floyd-Warshall Algorithm - step by step guide (youtube)
#Ruby
Ruby
def floyd_warshall(n, edge) dist = Array.new(n){|i| Array.new(n){|j| i==j ? 0 : Float::INFINITY}} nxt = Array.new(n){Array.new(n)} edge.each do |u,v,w| dist[u-1][v-1] = w nxt[u-1][v-1] = v-1 end   n.times do |k| n.times do |i| n.times do |j| if dist[i][j] > dist[i][k] + dist[k][j] dist[i][j] = dist[i][k] + dist[k][j] nxt[i][j] = nxt[i][k] end end end end   puts "pair dist path" n.times do |i| n.times do |j| next if i==j u = i path = [u] path << (u = nxt[u][j]) while u != j path = path.map{|u| u+1}.join(" -> ") puts "%d -> %d  %4d  %s" % [i+1, j+1, dist[i][j], path] end end end   n = 4 edge = [[1, 3, -2], [2, 1, 4], [2, 3, 3], [3, 4, 2], [4, 2, -1]] floyd_warshall(n, edge)
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
#WebAssembly
WebAssembly
(func $multipy (param $a i32) (param $b i32) (result i32) local.get $a local.get $b i32.mul )
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
#Wren
Wren
var multiply = Fn.new { |a, b| a * b }   System.print(multiply.call(3, 7)) System.print(multiply.call("abc", 3)) System.print(multiply.call([1], 5)) System.print(multiply.call(true, false))
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.)
#Sidef
Sidef
func dif(arr) { gather { for i (0 ..^ arr.end) { take(arr[i+1] - arr[i]) } } }   func difn(n, arr) { { arr = dif(arr) } * n arr }   say dif([1, 23, 45, 678]) # => [22, 22, 633] say difn(2, [1, 23, 45, 678]) # => [0, 611]
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).
#Sed
Sed
  #!/bin/sed -f # (C) 2005,2014 by Mariusz Woloszyn :) # https://en.wikipedia.org/wiki/Adder_(electronics)   ############################## # PURE SED BINARY FULL ADDER # ##############################     # Input two lines, sanitize input N s/ //g /^[01 ]\+\n[01 ]\+$/! { i\ ERROR: WRONG INPUT DATA d q } s/[ ]//g   # Add place for Sum and Cary bit s/$/\n\n0/   :LOOP # Pick A,B and C bits and put that to hold s/^\(.*\)\(.\)\n\(.*\)\(.\)\n\(.*\)\n\(.\)$/0\1\n0\3\n\5\n\6\2\4/ h   # Grab just A,B,C s/^.*\n.*\n.*\n\(...\)$/\1/   # binary full adder module # INPUT: 3bits (A,B,Carry in), for example 101 # OUTPUT: 2bits (Carry, Sum), for wxample 10 s/$/;000=00001=01010=01011=10100=01101=10110=10111=11/ s/^\(...\)[^;]*;[^;]*\1=\(..\).*/\2/   # Append the sum to hold H   # Rewrite the output, append the sum bit to final sum g s/^\(.*\)\n\(.*\)\n\(.*\)\n...\n\(.\)\(.\)$/\1\n\2\n\5\3\n\4/   # Output result and exit if no more bits to process.. /^\([0]*\)\n\([0]*\)\n/ { s/^.*\n.*\n\(.*\)\n\(.\)/\2\1/ s/^0\(.*\)/\1/ q }   b LOOP
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.
#Rust
Rust
  #[derive(Debug)] struct FiveNum { minimum: f64, lower_quartile: f64, median: f64, upper_quartile: f64, maximum: f64, }   fn median(samples: &[f64]) -> f64 { // input is already sorted let n = samples.len(); let m = n / 2; if n % 2 == 0 { (samples[m] + samples[m - 1]) / 2.0 } else { samples[m] } }   fn fivenum(samples: &[f64]) -> FiveNum { let mut xs = samples.to_vec(); xs.sort_by(|x, y| x.partial_cmp(y).unwrap());   let m = xs.len() / 2;   FiveNum { minimum: xs[0], lower_quartile: median(&xs[0..(m + (xs.len() % 2))]), median: median(&xs), upper_quartile: median(&xs[m..]), maximum: xs[xs.len() - 1], } } fn main() { let inputs = vec![ vec![15., 6., 42., 41., 7., 36., 49., 40., 39., 47., 43.], vec![36., 40., 7., 39., 41., 15.], vec![ 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 input in inputs { let result = fivenum(&input); println!("Fivenum",); println!(" Minumum: {}", result.minimum); println!(" Lower quartile: {}", result.lower_quartile); println!(" Median: {}", result.median); println!(" Upper quartile: {}", result.upper_quartile); println!(" Maximum: {}", result.maximum); } }  
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.
#SAS
SAS
/* build a dataset */ data test; do i=1 to 10000; x=rannor(12345); output; end; keep x; run;   /* compute the five numbers */ proc means data=test min p25 median p75 max; var x; run;
http://rosettacode.org/wiki/Find_the_missing_permutation
Find the missing permutation
ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB Listed above are   all-but-one   of the permutations of the symbols   A,   B,   C,   and   D,   except   for one permutation that's   not   listed. Task Find that missing permutation. Methods Obvious method: enumerate all permutations of A, B, C, and D, and then look for the missing permutation. alternate method: Hint: if all permutations were shown above, how many times would A appear in each position? What is the parity of this number? another alternate method: Hint: if you add up the letter values of each column, does a missing letter A, B, C, and D from each column cause the total value for each column to be unique? Related task   Permutations)
#Clojure
Clojure
  (use 'clojure.math.combinatorics) (use 'clojure.set)   (def given (apply hash-set (partition 4 5 "ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB" ))) (def s1 (apply hash-set (permutations "ABCD"))) (def missing (difference s1 given))  
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month
Find the last Sunday of each month
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 2013-05-26 2013-06-30 2013-07-28 2013-08-25 2013-09-29 2013-10-27 2013-11-24 2013-12-29 Related tasks Day of the week Five weekends Last Friday of each month
#Elixir
Elixir
defmodule RC do def lastSunday(year) do Enum.map(1..12, fn month -> lastday = :calendar.last_day_of_the_month(year, month) daynum = :calendar.day_of_the_week(year, month, lastday) sunday = lastday - rem(daynum, 7) {year, month, sunday} end) end end   y = String.to_integer(hd(System.argv)) Enum.each(RC.lastSunday(y), fn {year, month, day} ->  :io.format "~4b-~2..0w-~2..0w~n", [year, month, day] end)
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month
Find the last Sunday of each month
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 2013-05-26 2013-06-30 2013-07-28 2013-08-25 2013-09-29 2013-10-27 2013-11-24 2013-12-29 Related tasks Day of the week Five weekends Last Friday of each month
#Emacs_Lisp
Emacs Lisp
(require 'calendar)   (defun last-sunday (year) "Print the last Sunday in each month of year" (mapcar (lambda (month) (let* ((days (number-sequence 1 (calendar-last-day-of-month month year))) (mdy (mapcar (lambda (x) (list month x year)) days)) (weekdays (mapcar #'calendar-day-of-week mdy)) (lastsunday (1+ (cl-position 0 weekdays :from-end t)))) (insert (format "%i-%02i-%02i \n" year month lastsunday)))) (number-sequence 1 12)))   (last-sunday 2013)
http://rosettacode.org/wiki/Find_the_intersection_of_two_lines
Find the intersection of two lines
[1] Task Find the point of intersection of two lines in 2D. The 1st line passes though   (4,0)   and   (6,10) . The 2nd line passes though   (0,3)   and   (10,7) .
#Haskell
Haskell
type Line = (Point, Point)   type Point = (Float, Float)   intersection :: Line -> Line -> Either String Point intersection ab pq = case determinant of 0 -> Left "(Parallel lines – no intersection)" _ -> let [abD, pqD] = (\(a, b) -> diff ([fst, snd] <*> [a, b])) <$> [ab, pq] [ix, iy] = [\(ab, pq) -> diff [abD, ab, pqD, pq] / determinant] <*> [(abDX, pqDX), (abDY, pqDY)] in Right (ix, iy) where delta f x = f (fst x) - f (snd x) diff [a, b, c, d] = a * d - b * c [abDX, pqDX, abDY, pqDY] = [delta fst, delta snd] <*> [ab, pq] determinant = diff [abDX, abDY, pqDX, pqDY]   -- TEST ---------------------------------------------------------------- ab :: Line ab = ((4.0, 0.0), (6.0, 10.0))   pq :: Line pq = ((0.0, 3.0), (10.0, 7.0))   interSection :: Either String Point interSection = intersection ab pq   main :: IO () main = putStrLn $ case interSection of Left x -> x Right x -> show x
http://rosettacode.org/wiki/Find_the_intersection_of_a_line_with_a_plane
Find the intersection of a line with a plane
Finding the intersection of an infinite ray with a plane in 3D is an important topic in collision detection. Task Find the point of intersection for the infinite ray with direction   (0, -1, -1)   passing through position   (0, 0, 10)   with the infinite plane with a normal vector of   (0, 0, 1)   and which passes through [0, 0, 5].
#jq
jq
# add as many as you please def addVector: transpose | add;   # . - y def minusVector(y): [.[0] - y[0], .[1] - y[1], .[2] - y[2]];   # scalar multiplication: . * s def multVector(s): map(. * s);   def dot(y): .[0] * y[0] + .[1] * y[1] + .[2] * y[2];   def intersectPoint($rayVector; $rayPoint; $planeNormal; $planePoint): ($rayPoint | minusVector($planePoint)) as $diff | ($diff|dot($planeNormal)) as $prod1 | ($rayVector|dot($planeNormal)) as $prod2 | $rayPoint | minusVector($rayVector | multVector(($prod1 / $prod2) )) ;     def rv : [0, -1, -1]; def rp : [0, 0, 10]; def pn : [0, 0, 1]; def pp : [0, 0, 5];   "The ray intersects the plane at:", intersectPoint(rv; rp; pn; pp)
http://rosettacode.org/wiki/Find_the_intersection_of_a_line_with_a_plane
Find the intersection of a line with a plane
Finding the intersection of an infinite ray with a plane in 3D is an important topic in collision detection. Task Find the point of intersection for the infinite ray with direction   (0, -1, -1)   passing through position   (0, 0, 10)   with the infinite plane with a normal vector of   (0, 0, 1)   and which passes through [0, 0, 5].
#Julia
Julia
function lineplanecollision(planenorm::Vector, planepnt::Vector, raydir::Vector, raypnt::Vector) ndotu = dot(planenorm, raydir) if ndotu ≈ 0 error("no intersection or line is within plane") end   w = raypnt - planepnt si = -dot(planenorm, w) / ndotu ψ = w .+ si .* raydir .+ planepnt return ψ end   # Define plane planenorm = Float64[0, 0, 1] planepnt = Float64[0, 0, 5]   # Define ray raydir = Float64[0, -1, -1] raypnt = Float64[0, 0, 10]   ψ = lineplanecollision(planenorm, planepnt, raydir, raypnt) println("Intersection at $ψ")
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
#Applesoft_BASIC
Applesoft BASIC
fizzbuzz(): for x in [1..100] if x%5==0 and x%3==0 return "FizzBuzz" else if x%3==0 return "Fizz" else if x%5==0 return "Buzz" else return x   main(): fizzbuzz() -> io
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
#Factor
Factor
USING: calendar calendar.format formatting io kernel math sequences ;   : timestamps>my ( months -- ) [ { MONTH bl YYYY nl } formatted 2drop ] each ;   : month-range ( start-year #months -- seq ) [ <year> ] [ <iota> ] bi* [ months time+ ] with map ;   : find-five-weekend-months ( months -- months' ) [ [ friday? ] [ days-in-month ] bi 31 = and ] filter ;   1900 12 201 * month-range find-five-weekend-months [ length "%d five-weekend months found.\n" printf ] [ 5 head timestamps>my "..." print ] [ 5 tail* timestamps>my ] tri
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
#Sidef
Sidef
func first_square(b) {   var start = [1, 0, (2..^b)...].flip.map_kv{|k,v| v * b**k }.sum.isqrt   start..Inf -> first_by {|k| k.sqr.digits(b).freq.len == b }.sqr }   for b in (2..16) { var s = first_square(b) printf("Base %2d: %10s² == %s\n", b, s.isqrt.base(b), s.base(b)) }
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
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   #Include "crt/math.bi" '' include math functions in C runtime library   ' Declare function pointer type ' This implicitly assumes default StdCall calling convention on Windows Type Class2Func As Function(As Double) As Double   ' A couple of functions with the above prototype Function functionA(v As Double) As Double Return v*v*v '' cube of v End Function   Function functionB(v As Double) As Double Return Exp(Log(v)/3) '' same as cube root of v which would normally be v ^ (1.0/3.0) in FB End Function   ' A function taking a function as an argument Function function1(f2 As Class2Func, val_ As Double) As Double Return f2(val_) End Function   ' A function returning a function Function whichFunc(idx As Long) As Class2Func Return IIf(idx < 4, @functionA, @functionB) End Function   ' Additional function needed to treat CDecl function pointer as StdCall ' Get compiler warning otherwise Function cl2(f As Function CDecl(As Double) As Double) As Class2Func Return CPtr(Class2Func, f) End Function   ' A list of functions ' Using C Runtime library versions of trig functions as it doesn't appear ' to be possible to apply address operator (@) to FB's built-in versions Dim funcListA(0 To 3) As Class2Func = {@functionA, cl2(@sin_), cl2(@cos_), cl2(@tan_)} Dim funcListB(0 To 3) As Class2Func = {@functionB, cl2(@asin_), cl2(@acos_), cl2(@atan_)}   ' Composing Functions Function invokeComposed(f1 As Class2Func, f2 As Class2Func, val_ As double) As Double Return f1(f2(val_)) End Function   Type Composition As Class2Func f1, f2 End Type   Function compose(f1 As Class2Func, f2 As Class2Func) As Composition Ptr Dim comp As Composition Ptr = Allocate(SizeOf(Composition)) comp->f1 = f1 comp->f2 = f2 Return comp End Function   Function callComposed(comp As Composition Ptr, val_ As Double ) As Double Return comp->f1(comp->f2(val_)) End Function   Dim ix As Integer Dim c As Composition Ptr   Print "function1(functionA, 3.0) = "; CSng(function1(whichFunc(0), 3.0)) Print For ix = 0 To 3 c = compose(funcListA(ix), funcListB(ix)) Print "Composition"; ix; "(0.9) = "; CSng(callComposed(c, 0.9)) Next   Deallocate(c) Print Print "Press any key to quit" Sleep
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.
#Ol
Ol
  (import (lib gl)) (import (otus random!))   (define WIDTH 170) (define HEIGHT 96)   ; probabilities (define p 20) (define f 1000)   (gl:set-window-title "Drossel and Schwabl 'forest-fire'") (import (OpenGL version-1-0))   (glShadeModel GL_SMOOTH) (glClearColor 0.11 0.11 0.11 1) (glOrtho 0 WIDTH 0 HEIGHT 0 1)   (gl:set-userdata (make-vector (map (lambda (-) (make-vector (map (lambda (-) (rand! 2)) (iota WIDTH)))) (iota HEIGHT))))   (gl:set-renderer (lambda (mouse) (let ((forest (gl:get-userdata)) (step (make-vector (map (lambda (-) (make-vector (repeat 0 WIDTH))) (iota HEIGHT))))) (glClear GL_COLOR_BUFFER_BIT)   (glPointSize (/ 854 WIDTH)) (glBegin GL_POINTS) (for-each (lambda (y) (for-each (lambda (x) (case (ref (ref forest y) x) (0 ; An empty space fills with a tree with probability "p" (if (zero? (rand! p)) (set-ref! (ref step y) x 1))) (1 (glColor3f 0.2 0.7 0.2) (glVertex2f x y) ; A tree will burn if at least one neighbor is burning ; A tree ignites with probability "f" even if no neighbor is burning (if (or (eq? (ref (ref forest (- y 1)) (- x 1)) 2) (eq? (ref (ref forest (- y 1)) x) 2) (eq? (ref (ref forest (- y 1)) (+ x 1)) 2) (eq? (ref (ref forest y ) (- x 1)) 2) (eq? (ref (ref forest y ) (+ x 1)) 2) (eq? (ref (ref forest (+ y 1)) (- x 1)) 2) (eq? (ref (ref forest (+ y 1)) x) 2) (eq? (ref (ref forest (+ y 1)) (+ x 1)) 2) (zero? (rand! f))) (set-ref! (ref step y) x 2) (set-ref! (ref step y) x 1))) (2 (glColor3f 0.7 0.7 0.1) (glVertex2f x y)) ; A burning cell turns into an empty cell (set-ref! (ref step y) x 0))) (iota WIDTH))) (iota HEIGHT)) (glEnd) (gl:set-userdata step))))  
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
#Forth
Forth
include FMS-SI.f include FMS-SILib.f   : flatten {: list1 list2 --  :} list1 size: 0 ?do i list1 at: dup is-a object-list2 if list2 recurse else list2 add: then loop ;   object-list2 list o{ o{ 1 } 2 o{ o{ 3 4 } 5 } o{ o{ o{ } } } o{ o{ o{ 6 } } } 7 8 o{ } } list flatten list p: \ o{ 1 2 3 4 5 6 7 8 } ok
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.
#Kotlin
Kotlin
fun main(args: Array<String>) = args.forEach { Triangle(it.toInt()) }   internal class Triangle(n: Int) { init { println("$n rows:") var printMe = 1 var printed = 0 var row = 1 while (row <= n) { val cols = Math.ceil(Math.log10(n * (n - 1) / 2 + printed + 2.0)).toInt() print("%${cols}d ".format(printMe)) if (++printed == row) { println(); row++; printed = 0 } printMe++ } } }
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)
#Rust
Rust
pub type Edge = (usize, usize);   #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct Graph<T> { size: usize, edges: Vec<Option<T>>, }   impl<T> Graph<T> { pub fn new(size: usize) -> Self { Self { size, edges: std::iter::repeat_with(|| None).take(size * size).collect(), } }   pub fn new_with(size: usize, f: impl FnMut(Edge) -> Option<T>) -> Self { let edges = (0..size) .flat_map(|i| (0..size).map(move |j| (i, j))) .map(f) .collect();   Self { size, edges } }   pub fn with_diagonal(mut self, mut f: impl FnMut(usize) -> Option<T>) -> Self { self.edges .iter_mut() .step_by(self.size + 1) .enumerate() .for_each(move |(vertex, edge)| *edge = f(vertex));   self }   pub fn size(&self) -> usize { self.size }   pub fn edge(&self, edge: Edge) -> &Option<T> { let index = self.edge_index(edge); &self.edges[index] }   pub fn edge_mut(&mut self, edge: Edge) -> &mut Option<T> { let index = self.edge_index(edge); &mut self.edges[index] }   fn edge_index(&self, (row, col): Edge) -> usize { assert!(row < self.size && col < self.size); row * self.size() + col } }   impl<T> std::ops::Index<Edge> for Graph<T> { type Output = Option<T>;   fn index(&self, index: Edge) -> &Self::Output { self.edge(index) } }   impl<T> std::ops::IndexMut<Edge> for Graph<T> { fn index_mut(&mut self, index: Edge) -> &mut Self::Output { self.edge_mut(index) } }   #[derive(Clone, Debug, PartialEq, Eq)] pub struct Paths(Graph<usize>);   impl Paths { pub fn new<T>(graph: &Graph<T>) -> Self { Self(Graph::new_with(graph.size(), |(i, j)| { graph[(i, j)].as_ref().map(|_| j) })) }   pub fn vertices(&self, from: usize, to: usize) -> Path<'_> { assert!(from < self.0.size() && to < self.0.size());   Path { graph: &self.0, from: Some(from), to, } }   fn update(&mut self, from: usize, to: usize, via: usize) { self.0[(from, to)] = self.0[(from, via)]; } }   #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Path<'a> { graph: &'a Graph<usize>, from: Option<usize>, to: usize, }   impl<'a> Iterator for Path<'a> { type Item = usize;   fn next(&mut self) -> Option<Self::Item> { self.from.map(|from| { let result = from;   self.from = if result != self.to { self.graph[(result, self.to)] } else { None };   result }) } }   pub fn floyd_warshall<W>(mut result: Graph<W>) -> (Graph<W>, Option<Paths>) where W: Copy + std::ops::Add<W, Output = W> + std::cmp::Ord + Default, { let mut without_negative_cycles = true; let mut paths = Paths::new(&result); let n = result.size();   for k in 0..n { for i in 0..n { for j in 0..n { // Negative cycle detection with T::default as the negative boundary if i == j && result[(i, j)].filter(|&it| it < W::default()).is_some() { without_negative_cycles = false; continue; }   if let (Some(ik_weight), Some(kj_weight)) = (result[(i, k)], result[(k, j)]) { let ij_edge = result.edge_mut((i, j)); let ij_weight = ik_weight + kj_weight;   if ij_edge.is_none() { *ij_edge = Some(ij_weight); paths.update(i, j, k); } else { ij_edge .as_mut() .filter(|it| ij_weight < **it) .map_or((), |it| { *it = ij_weight; paths.update(i, j, k); }); } } } } }   (result, Some(paths).filter(|_| without_negative_cycles)) // No paths for negative cycles }   fn format_path<T: ToString>(path: impl Iterator<Item = T>) -> String { path.fold(String::new(), |mut acc, x| { if !acc.is_empty() { acc.push_str(" -> "); }   acc.push_str(&x.to_string()); acc }) }   fn print_results<W, V>(weights: &Graph<W>, paths: Option<&Paths>, vertex: impl Fn(usize) -> V) where W: std::fmt::Display + Default + Eq, V: std::fmt::Display, { let n = weights.size();   for from in 0..n { for to in 0..n { if let Some(weight) = &weights[(from, to)] { // Skip trivial information (i.e., default weight on the diagonal) if from == to && *weight == W::default() { continue; }   println!( "{} -> {}: {} \t{}", vertex(from), vertex(to), weight, format_path(paths.iter().flat_map(|p| p.vertices(from, to)).map(&vertex)) ); } } } }   fn main() { let graph = { let mut g = Graph::new(4).with_diagonal(|_| Some(0)); g[(0, 2)] = Some(-2); g[(1, 0)] = Some(4); g[(1, 2)] = Some(3); g[(2, 3)] = Some(2); g[(3, 1)] = Some(-1); g };   let (weights, paths) = floyd_warshall(graph); // Fixup the vertex name (as we use zero-based indices) print_results(&weights, paths.as_ref(), |index| index + 1); }  
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
#X86_Assembly
X86 Assembly
.text .globl multiply .type multiply,@function multiply: movl 4(%esp), %eax mull 8(%esp) ret
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
#XBS
XBS
func multiply(a,b){ send a*b; }
http://rosettacode.org/wiki/Forward_difference
Forward difference
Task Provide code that produces a list of numbers which is the   nth  order forward difference, given a non-negative integer (specifying the order) and a list of numbers. The first-order forward difference of a list of numbers   A   is a new list   B,   where   Bn = An+1 - An. List   B   should have one fewer element as a result. The second-order forward difference of   A   will be: tdefmodule Diff do def forward(arr,i\\1) do forward(arr,[],i) end def forward([_|[]],diffs,i) do if i == 1 do IO.inspect diffs else forward(diffs,[],i-1) end end def forward([val1|[val2|vals]],diffs,i) do forward([val2|vals],diffs++[val2-val1],i) end end The same as the first-order forward difference of   B. That new list will have two fewer elements than   A   and one less than   B. The goal of this task is to repeat this process up to the desired order. For a more formal description, see the related   Mathworld article. Algorithmic options Iterate through all previous forward differences and re-calculate a new array each time. Use this formula (from Wikipedia): Δ n [ f ] ( x ) = ∑ k = 0 n ( n k ) ( − 1 ) n − k f ( x + k ) {\displaystyle \Delta ^{n}[f](x)=\sum _{k=0}^{n}{n \choose k}(-1)^{n-k}f(x+k)} (Pascal's Triangle   may be useful for this option.)
#Slate
Slate
s@(Sequence traits) forwardDifference [ s allButFirst with: s allButLast collect: #- `er ].   s@(Sequence traits) forwardDifference "Without creating two intermediate throwaway Sequences." [ result ::= s allButFirst. result doWithIndex: [| :nextValue :index | result at: index infect: [| :oldValue | oldValue - (s at: index)]. result ].   s@(Sequence traits) forwardDifference: n [ (0 below: n) inject: s into: [| :seq :_ | seq forwardDifference] ].
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.)
#Smalltalk
Smalltalk
Array extend [ difference [ ^self allButFirst with: self allButLast collect: [ :a :b | a - b ] ]   nthOrderDifference: n [ ^(1 to: n) inject: self into: [ :old :unused | old difference ] ] ]   s := #(90 47 58 29 22 32 55 5 55 73) 1 to: s size - 1 do: [ :i | (s nthOrderDifference: i) printNl ]
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).
#Sidef
Sidef
func bxor(a, b) { (~a & b) | (a & ~b) }   func half_adder(a, b) { return (bxor(a, b), a & b) }   func full_adder(a, b, c) { var (s1, c1) = half_adder(a, c) var (s2, c2) = half_adder(s1, b) return (s2, c1 | c2) }   func four_bit_adder(a, b) { var (s0, c0) = full_adder(a[0], b[0], 0) var (s1, c1) = full_adder(a[1], b[1], c0) var (s2, c2) = full_adder(a[2], b[2], c1) var (s3, c3) = full_adder(a[3], b[3], c2) return ([s3,s2,s1,s0].join, c3.to_s) }   say " A B A B C S sum" for a in ^16 { for b in ^16 { var(abin, bbin) = [a,b].map{|n| "%04b"%n->chars.reverse.map{.to_i} }... var(s, c) = four_bit_adder(abin, bbin) printf("%2d + %2d = %s + %s = %s %s = %2d\n", a, b, abin.join, bbin.join, c, s, "#{c}#{s}".bin) } }
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.
#Scala
Scala
import java.util   object Fivenum extends App {   val xl = Array( Array(15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0), Array(36.0, 40.0, 7.0, 39.0, 41.0, 15.0), Array(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 (x <- xl) println(f"${util.Arrays.toString(fivenum(x))}%s\n\n")   def fivenum(x: Array[Double]): Array[Double] = { require(x.forall(!_.isNaN), "Unable to deal with arrays containing NaN")   def median(x: Array[Double], start: Int, endInclusive: Int): Double = { val size = endInclusive - start + 1 require(size > 0, "Array slice cannot be empty") val m = start + size / 2 if (size % 2 == 1) x(m) else (x(m - 1) + x(m)) / 2.0 }   val result = new Array[Double](5) util.Arrays.sort(x) result(0) = x(0) result(2) = median(x, 0, x.length - 1) result(4) = x(x.length - 1) val m = x.length / 2 val lowerEnd = if (x.length % 2 == 1) m else m - 1 result(1) = median(x, 0, lowerEnd) result(3) = median(x, m, x.length - 1) result }   }
http://rosettacode.org/wiki/Find_the_missing_permutation
Find the missing permutation
ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB Listed above are   all-but-one   of the permutations of the symbols   A,   B,   C,   and   D,   except   for one permutation that's   not   listed. Task Find that missing permutation. Methods Obvious method: enumerate all permutations of A, B, C, and D, and then look for the missing permutation. alternate method: Hint: if all permutations were shown above, how many times would A appear in each position? What is the parity of this number? another alternate method: Hint: if you add up the letter values of each column, does a missing letter A, B, C, and D from each column cause the total value for each column to be unique? Related task   Permutations)
#CoffeeScript
CoffeeScript
  missing_permutation = (arr) -> # Find the missing permutation in an array of N! - 1 permutations.   # We won't validate every precondition, but we do have some basic # guards. if arr.length == 0 throw Error "Need more data" if arr.length == 1 return [arr[0][1] + arr[0][0]]   # Now we know that for each position in the string, elements should appear # an even number of times (N-1 >= 2). We can use a set to detect the element appearing # an odd number of times. Detect odd occurrences by toggling admission/expulsion # to and from the set for each value encountered. At the end of each pass one element # will remain in the set. result = '' for pos in [0...arr[0].length] set = {} for permutation in arr c = permutation[pos] if set[c] delete set[c] else set[c] = true for c of set result += c break result   given = '''ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB'''   arr = (s for s in given.replace('\n', ' ').split ' ' when s != '')   console.log missing_permutation(arr)  
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month
Find the last Sunday of each month
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 2013-05-26 2013-06-30 2013-07-28 2013-08-25 2013-09-29 2013-10-27 2013-11-24 2013-12-29 Related tasks Day of the week Five weekends Last Friday of each month
#Erlang
Erlang
  -module(last_sundays).   -export([in_year/1]).   % calculate all the last sundays in a particular year in_year(Year) -> [lastday(Year, Month, 7) || Month <- lists:seq(1, 12)].   % calculate the date of the last occurrence of a particular weekday lastday(Year, Month, WeekDay) -> Ldm = calendar:last_day_of_the_month(Year, Month), Diff = calendar:day_of_the_week(Year, Month, Ldm) rem WeekDay, {Year, Month, Ldm - Diff}.    
http://rosettacode.org/wiki/Find_the_intersection_of_two_lines
Find the intersection of two lines
[1] Task Find the point of intersection of two lines in 2D. The 1st line passes though   (4,0)   and   (6,10) . The 2nd line passes though   (0,3)   and   (10,7) .
#J
J
det=: -/ .* NB. calculate determinant findIntersection=: (det ,."1 [: |: -/"2) %&det -/"2
http://rosettacode.org/wiki/Find_the_intersection_of_two_lines
Find the intersection of two lines
[1] Task Find the point of intersection of two lines in 2D. The 1st line passes though   (4,0)   and   (6,10) . The 2nd line passes though   (0,3)   and   (10,7) .
#Java
Java
public class Intersection { private static class Point { double x, y;   Point(double x, double y) { this.x = x; this.y = y; }   @Override public String toString() { return String.format("{%f, %f}", x, y); } }   private static class Line { Point s, e;   Line(Point s, Point e) { this.s = s; this.e = e; } }   private static Point findIntersection(Line l1, Line l2) { double a1 = l1.e.y - l1.s.y; double b1 = l1.s.x - l1.e.x; double c1 = a1 * l1.s.x + b1 * l1.s.y;   double a2 = l2.e.y - l2.s.y; double b2 = l2.s.x - l2.e.x; double c2 = a2 * l2.s.x + b2 * l2.s.y;   double delta = a1 * b2 - a2 * b1; return new Point((b2 * c1 - b1 * c2) / delta, (a1 * c2 - a2 * c1) / delta); }   public static void main(String[] args) { Line l1 = new Line(new Point(4, 0), new Point(6, 10)); Line l2 = new Line(new Point(0, 3), new Point(10, 7)); System.out.println(findIntersection(l1, l2));   l1 = new Line(new Point(0, 0), new Point(1, 1)); l2 = new Line(new Point(1, 2), new Point(4, 5)); System.out.println(findIntersection(l1, l2)); } }
http://rosettacode.org/wiki/Find_the_intersection_of_a_line_with_a_plane
Find the intersection of a line with a plane
Finding the intersection of an infinite ray with a plane in 3D is an important topic in collision detection. Task Find the point of intersection for the infinite ray with direction   (0, -1, -1)   passing through position   (0, 0, 10)   with the infinite plane with a normal vector of   (0, 0, 1)   and which passes through [0, 0, 5].
#Kotlin
Kotlin
// version 1.1.51   class Vector3D(val x: Double, val y: Double, val z: Double) {   operator fun plus(v: Vector3D) = Vector3D(x + v.x, y + v.y, z + v.z)   operator fun minus(v: Vector3D) = Vector3D(x - v.x, y - v.y, z - v.z)   operator fun times(s: Double) = Vector3D(s * x, s * y, s * z)   infix fun dot(v: Vector3D) = x * v.x + y * v.y + z * v.z   override fun toString() = "($x, $y, $z)" }   fun intersectPoint( rayVector: Vector3D, rayPoint: Vector3D, planeNormal: Vector3D, planePoint: Vector3D ): Vector3D { val diff = rayPoint - planePoint val prod1 = diff dot planeNormal val prod2 = rayVector dot planeNormal val prod3 = prod1 / prod2 return rayPoint - rayVector * prod3 }   fun main(args: Array<String>) { val rv = Vector3D(0.0, -1.0, -1.0) val rp = Vector3D(0.0, 0.0, 10.0) val pn = Vector3D(0.0, 0.0, 1.0) val pp = Vector3D(0.0, 0.0, 5.0) val ip = intersectPoint(rv, rp, pn, pp) println("The ray intersects the plane at $ip") }
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
#Arbre
Arbre
fizzbuzz(): for x in [1..100] if x%5==0 and x%3==0 return "FizzBuzz" else if x%3==0 return "Fizz" else if x%5==0 return "Buzz" else return x   main(): fizzbuzz() -> io
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
#Fortran
Fortran
program Five_weekends implicit none   integer :: m, year, nfives = 0, not5 = 0 logical :: no5weekend   type month integer :: n character(3) :: name end type month   type(month) :: month31(7)   month31(1) = month(13, "Jan") month31(2) = month(3, "Mar") month31(3) = month(5, "May") month31(4) = month(7, "Jul") month31(5) = month(8, "Aug") month31(6) = month(10, "Oct") month31(7) = month(12, "Dec")   do year = 1900, 2100 no5weekend = .true. do m = 1, size(month31) if(month31(m)%n == 13) then if(Day_of_week(1, month31(m)%n, year-1) == 6) then write(*, "(a3, i5)") month31(m)%name, year nfives = nfives + 1 no5weekend = .false. end if else if(Day_of_week(1, month31(m)%n, year) == 6) then write(*,"(a3, i5)") month31(m)%name, year nfives = nfives + 1 no5weekend = .false. end if end if end do if(no5weekend) not5 = not5 + 1 end do   write(*, "(a, i0)") "Number of months with five weekends between 1900 and 2100 = ", nfives write(*, "(a, i0)") "Number of years between 1900 and 2100 with no five weekend months = ", not5   contains   function Day_of_week(d, m, y) integer :: Day_of_week integer, intent(in) :: d, m, y integer :: j, k   j = y / 100 k = mod(y, 100) Day_of_week = mod(d + (m+1)*26/10 + k + k/4 + j/4 + 5*j, 7)   end function Day_of_week end program Five_weekends
http://rosettacode.org/wiki/First_perfect_square_in_base_n_with_n_unique_digits
First perfect square in base n with n unique digits
Find the first perfect square in a given base N that has at least N digits and exactly N significant unique digits when expressed in base N. E.G. In base 10, the first perfect square with at least 10 unique digits is 1026753849 (32043²). You may use analytical methods to reduce the search space, but the code must do a search. Do not use magic numbers or just feed the code the answer to verify it is correct. Task Find and display here, on this page, the first perfect square in base N, with N significant unique digits when expressed in base N, for each of base 2 through 12. Display each number in the base N for which it was calculated. (optional) Do the same for bases 13 through 16. (stretch goal) Continue on for bases 17 - ?? (Big Integer math) See also OEIS A260182: smallest square that is pandigital in base n. Related task Casting out nines
#Visual_Basic_.NET
Visual Basic .NET
Imports System.Numerics   Module Program Dim base, bm1 As Byte, hs As New HashSet(Of Byte), st0 As DateTime Const chars As String = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz|"   ' converts base10 to string, using current base Function toStr(ByVal b As BigInteger) As String toStr = "" : Dim re As BigInteger : While b > 0 b = BigInteger.DivRem(b, base, re) : toStr = chars(CByte(re)) & toStr : End While End Function   ' checks for all digits present, checks every one (use when extra digit is present) Function allIn(ByVal b As BigInteger) As Boolean Dim re As BigInteger : hs.Clear() : While b > 0 : b = BigInteger.DivRem(b, base, re) hs.Add(CByte(re)) : End While : Return hs.Count = base End Function   ' checks for all digits present, bailing when duplicates occur (can't use when extra digit is present) Function allInQ(ByVal b As BigInteger) As Boolean Dim re As BigInteger, c As Integer = 0 : hs.Clear() : While b > 0 : b = BigInteger.DivRem(b, base, re) hs.Add(CByte(re)) : c += 1 : If c <> hs.Count Then Return False End While : Return True End Function   ' converts string to base 10, using current base Function to10(s As String) As BigInteger to10 = 0 : For Each i As Char In s : to10 = to10 * base + chars.IndexOf(i) : Next End Function   ' returns minimum string representation, optionally inserting a digit Function fixup(n As Integer) As String fixup = chars.Substring(0, base) If n > 0 Then fixup = fixup.Insert(n, n.ToString) fixup = "10" & fixup.Substring(2) End Function   ' returns close approx. Function IntSqRoot(v As BigInteger) As BigInteger IntSqRoot = New BigInteger(Math.Sqrt(CDbl(v))) : Dim term As BigInteger Do : term = v / IntSqRoot : If BigInteger.Abs(term - IntSqRoot) < 2 Then Exit Do IntSqRoot = (IntSqRoot + term) / 2 : Loop Until False End Function   ' tabulates one base Sub doOne() bm1 = base - 1 : Dim dr As Byte = 0 : If (base And 1) = 1 Then dr = base >> 1 Dim id As Integer = 0, inc As Integer = 1, i As Long = 0, st As DateTime = DateTime.Now Dim sdr(bm1 - 1) As Byte, rc As Byte = 0 : For i = 0 To bm1 - 1 : sdr(i) = (i * i) Mod bm1 rc += If(sdr(i) = dr, 1, 0) : sdr(i) += If(sdr(i) = 0, bm1, 0) : Next : i = 0 If dr > 0 Then id = base : For i = 1 To dr : If sdr(i) >= dr Then If id > sdr(i) Then id = sdr(i) Next : id -= dr : i = 0 : End If Dim sq As BigInteger = to10(fixup(id)), rt As BigInteger = IntSqRoot(sq) + 0, dn As BigInteger = (rt << 1) + 1, d As BigInteger = 1 sq = rt * rt : If base > 3 AndAlso rc > 0 Then While sq Mod bm1 <> dr : rt += 1 : sq += dn : dn += 2 : End While ' alligns sq to dr inc = bm1 \ rc : If inc > 1 Then dn += rt * (inc - 2) - 1 : d = inc * inc dn += dn + d End If : d <<= 1 : If base > 5 AndAlso rc > 0 Then : Do : If allInQ(sq) Then Exit Do sq += dn : dn += d : i += 1 : Loop Until False : Else : Do : If allIn(sq) Then Exit Do sq += dn : dn += d : i += 1 : Loop Until False : End If : rt += i * inc Console.WriteLine("{0,3} {1,3} {2,2} {3,20} -> {4,-38} {5,10} {6,8:0.000}s {7,8:0.000}s", base, inc, If(id = 0, " ", id.ToString), toStr(rt), toStr(sq), i, (DateTime.Now - st).TotalSeconds, (DateTime.Now - st0).TotalSeconds) End Sub   Sub Main(args As String()) st0 = DateTime.Now Console.WriteLine("base inc id root square" & _ " test count time total") For base = 2 To 28 : doOne() : Next Console.WriteLine("Elasped time was {0,8:0.00} minutes", (DateTime.Now - st0).TotalMinutes) End Sub End Module
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
#GAP
GAP
# Function composition Composition := function(f, g) local h; h := function(x) return f(g(x)); end; return h; end;   # Apply each function in list u, to argument x ApplyList := function(u, x) local i, n, v; n := Size(u); v := [ ]; for i in [1 .. n] do v[i] := u[i](x); od; return v; end;   # Inverse and Sqrt are in the built-in library. Note that Sqrt yields values in cyclotomic fields. # For example, # gap> Sqrt(7); # E(28)^3-E(28)^11-E(28)^15+E(28)^19-E(28)^23+E(28)^27 # where E(n) is a primitive n-th root of unity a := [ i -> i + 1, Inverse, Sqrt ]; # [ function( i ) ... end, <Operation "InverseImmutable">, <Operation "Sqrt"> ] b := [ i -> i - 1, Inverse, x -> x*x ]; # [ function( i ) ... end, <Operation "InverseImmutable">, function( x ) ... end ]   # Compose each couple z := ListN(a, b, Composition);   # Now a test ApplyList(z, 3); [ 3, 3, 3 ]
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
#Go
Go
package main   import "math" import "fmt"   // user-defined function, per task. Other math functions used are built-in. func cube(x float64) float64 { return math.Pow(x, 3) }   // ffType and compose function taken from Function composition task type ffType func(float64) float64   func compose(f, g ffType) ffType { return func(x float64) float64 { return f(g(x)) } }   func main() { // collection A funclist := []ffType{math.Sin, math.Cos, cube} // collection B funclisti := []ffType{math.Asin, math.Acos, math.Cbrt} for i := 0; i < 3; i++ { // apply composition and show result fmt.Println(compose(funclisti[i], funclist[i])(.5)) } }
http://rosettacode.org/wiki/Forest_fire
Forest fire
This page uses content from Wikipedia. The original article was at Forest-fire model. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Implement the Drossel and Schwabl definition of the forest-fire model. It is basically a 2D   cellular automaton   where each cell can be in three distinct states (empty, tree and burning) and evolves according to the following rules (as given by Wikipedia) A burning cell turns into an empty cell A tree will burn if at least one neighbor is burning A tree ignites with probability   f   even if no neighbor is burning An empty space fills with a tree with probability   p Neighborhood is the   Moore neighborhood;   boundary conditions are so that on the boundary the cells are always empty ("fixed" boundary condition). At the beginning, populate the lattice with empty and tree cells according to a specific probability (e.g. a cell has the probability 0.5 to be a tree). Then, let the system evolve. Task's requirements do not include graphical display or the ability to change parameters (probabilities   p   and   f )   through a graphical or command line interface. Related tasks   See   Conway's Game of Life   See   Wireworld.
#PARI.2FGP
PARI/GP
step(M,p,f)={ my(m=matsize(M)[1],n=matsize(M)[2]); matrix(m,n,i,j, if(M[i,j]=="*", " " , if(M[i,j]=="t", my(nbr="t"); for(x=max(1,i-1),min(m,i+1), for(y=max(1,j-1),min(n,j+1), if(M[x,y]=="*",nbr="*";break(2)) ) ); if(random(1.)<f,"*",nbr) , if(random(1.)<p,"t"," ") ) ) ) }; burn(n,p,f)={ my(M=matrix(n,n,i,j,if(random(2)," ","t")),N); while(1,print(M=step(M,p,f))) }; burn(5,.1,.03)
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
#Fortran
Fortran
  ! input  : [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []] ! flatten : [1, 2, 3, 4, 5, 6, 7, 8 ]   module flat implicit none   type n integer :: a type(n), dimension(:), pointer :: p => null() logical :: empty = .false. end type   contains   recursive subroutine del(this) type(n), intent(inout) :: this integer :: i if (associated(this%p)) then do i = 1, size(this%p) call del(this%p(i)) end do end if end subroutine   function join(xs) result (r) type(n), dimension(:), target :: xs type(n) :: r integer :: i if (size(xs)>0) then allocate(r%p(size(xs)), source=xs) do i = 1, size(xs) r%p(i) = xs(i) end do else r%empty = .true. end if end function   recursive subroutine flatten1(x,r) integer, dimension (:), allocatable, intent(inout) :: r type(n), intent(in) :: x integer, dimension (:), allocatable :: tmp integer :: i if (associated(x%p)) then do i = 1, size(x%p) call flatten1(x%p(i), r) end do elseif (.not. x%empty) then allocate(tmp(size(r)+1)) tmp(1:size(r)) = r tmp(size(r)+1) = x%a call move_alloc(tmp, r) end if end subroutine   function flatten(x) result (r) type(n), intent(in) :: x integer, dimension(:), allocatable :: r allocate(r(0)) call flatten1(x,r) end function   recursive subroutine show(x) type(n) :: x integer :: i if (x%empty) then write (*, "(a)", advance="no") "[]" elseif (associated(x%p)) then write (*, "(a)", advance="no") "[" do i = 1, size(x%p) call show(x%p(i)) if (i<size(x%p)) then write (*, "(a)", advance="no") ", " end if end do write (*, "(a)", advance="no") "]" else write (*, "(g0)", advance="no") x%a end if end subroutine   function fromString(line) result (r) character(len=*) :: line type (n) :: r type (n), dimension(:), allocatable :: buffer, buffer1 integer, dimension(:), allocatable :: stack, stack1 integer :: sp,i0,i,j, a, cur, start character :: c   if (.not. allocated(buffer)) then allocate (buffer(5)) ! will be re-allocated if more is needed end if if (.not. allocated(stack)) then allocate (stack(5)) end if   sp = 1; cur = 1; i = 1 do if ( i > len_trim(line) ) exit c = line(i:i) if (c=="[") then if (sp>size(stack)) then allocate(stack1(2*size(stack))) stack1(1:size(stack)) = stack call move_alloc(stack1, stack) end if stack(sp) = cur; sp = sp + 1; i = i+1 elseif (c=="]") then sp = sp - 1; start = stack(sp) r = join(buffer(start:cur-1)) do j = start, cur-1 call del(buffer(j)) end do buffer(start) = r; cur = start+1; i = i+1 elseif (index(" ,",c)>0) then i = i + 1; continue elseif (index("-123456789",c)>0) then i0 = i do if ((i>len_trim(line)).or. & index("1234567890",line(i:i))==0) then read(line(i0:i-1),*) a if (cur>size(buffer)) then allocate(buffer1(2*size(buffer))) buffer1(1:size(buffer)) = buffer call move_alloc(buffer1, buffer) end if buffer(cur) = n(a); cur = cur + 1; exit else i = i+1 end if end do else stop "input corrupted" end if end do end function end module   program main use flat type (n) :: x x = fromString("[[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]") write(*, "(a)", advance="no") "input  : " call show(x) print * write (*,"(a)", advance="no") "flatten : [" write (*, "(*(i0,:,:', '))", advance="no") flatten(x) print *, "]" end program  
http://rosettacode.org/wiki/Floyd%27s_triangle
Floyd's triangle
Floyd's triangle   lists the natural numbers in a right triangle aligned to the left where the first row is   1     (unity) successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above. The first few lines of a Floyd triangle looks like this: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Task Write a program to generate and display here the first   n   lines of a Floyd triangle. (Use   n=5   and   n=14   rows). Ensure that when displayed in a mono-space font, the numbers line up in vertical columns as shown and that only one space separates numbers of the last row.
#Lasso
Lasso
define floyds_triangle(n::integer) => { local(out = array(array(1)),comp = array, num = 1) while(#out->size < #n) => { local(new = array) loop(#out->last->size + 1) => { #num++ #new->insert(#num) } #out->insert(#new) } local(pad = #out->last->last->asString->size) with line in #out do => { local(lineout = string) with i in #line do => { #i != #line->first ? #lineout->append(' ') #lineout->append((' '*(#pad - #i->asString->size))+#i) } #comp->insert(#lineout) } return #comp->join('\r') } floyds_triangle(5) '\r\r' floyds_triangle(14)
http://rosettacode.org/wiki/Floyd%27s_triangle
Floyd's triangle
Floyd's triangle   lists the natural numbers in a right triangle aligned to the left where the first row is   1     (unity) successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above. The first few lines of a Floyd triangle looks like this: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Task Write a program to generate and display here the first   n   lines of a Floyd triangle. (Use   n=5   and   n=14   rows). Ensure that when displayed in a mono-space font, the numbers line up in vertical columns as shown and that only one space separates numbers of the last row.
#Liberty_BASIC
Liberty BASIC
input "Number of rows needed:- "; rowsNeeded   dim colWidth(rowsNeeded) ' 5 rows implies 5 columns   for col=1 to rowsNeeded colWidth(col) = len(str$(col + rowsNeeded*(rowsNeeded-1)/2)) next   currentNumber =1   for row=1 to rowsNeeded for col=1 to row print right$( " "+str$( currentNumber), colWidth(col)); " "; currentNumber = currentNumber + 1 next print next
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)
#Scheme
Scheme
;;; Floyd-Warshall algorithm. ;;; ;;; See https://en.wikipedia.org/w/index.php?title=Floyd%E2%80%93Warshall_algorithm&oldid=1082310013 ;;;   (import (scheme base)) (import (scheme cxr)) (import (scheme write))   ;;; ;;; A square array will be represented by a cons-pair: ;;; ;;; (vector-of-length n-squared . n) ;;; ;;; Arrays are indexed *starting at one*. ;;;   (define (make-arr n fill) (cons (make-vector (* n n) fill) n))   (define (arr-set! arr i j x) (let ((vec (car arr)) (n (cdr arr))) (vector-set! vec (+ (- i 1) (* n (- j 1))) x)))   (define (arr-ref arr i j) (let ((vec (car arr)) (n (cdr arr))) (vector-ref vec (+ (- i 1) (* n (- j 1))))))   ;;; ;;; Floyd-Warshall. ;;; ;;; Input is a list of length-3 lists representing edges; each entry ;;; is: ;;; ;;; (start-vertex edge-weight end-vertex) ;;; ;;; where vertex identifiers are (to help keep this example brief) ;;; integers from 1 .. n. ;;;   (define (floyd-warshall edges)   (define n ;; Set n to the maximum vertex number. By design, n also equals ;; the number of vertices. (max (apply max (map car edges)) (apply max (map caddr edges))))   (define distance (make-arr n +inf.0)) (define next-vertex (make-arr n #f))   ;; Initialize "distance" and "next-vertex". (for-each (lambda (edge) (let ((u (car edge)) (weight (cadr edge)) (v (caddr edge))) (arr-set! distance u v weight) (arr-set! next-vertex u v v))) edges) (do ((v 1 (+ v 1))) ((< n v)) (arr-set! distance v v 0) (arr-set! next-vertex v v v))   ;; Perform the algorithm. (do ((k 1 (+ k 1))) ((< n k)) (do ((i 1 (+ i 1))) ((< n i)) (do ((j 1 (+ j 1))) ((< n j)) (let ((dist-ij (arr-ref distance i j)) (dist-ik (arr-ref distance i k)) (dist-kj (arr-ref distance k j))) (let ((dist-ik+dist-kj (+ dist-ik dist-kj))) (when (< dist-ik+dist-kj dist-ij) (arr-set! distance i j dist-ik+dist-kj) (arr-set! next-vertex i j (arr-ref next-vertex i k))))))))   ;; Return the results. (values n distance next-vertex))   ;;; ;;; Path reconstruction from the "next-vertex" array. ;;; ;;; The return value is a list of vertices. ;;;   (define (find-path next-vertex u v) (if (not (arr-ref next-vertex u v)) (list) (let loop ((u u) (path (list u))) (if (= u v) (reverse path) (let ((u^ (arr-ref next-vertex u v))) (loop u^ (cons u^ path)))))))   (define (display-path path) (let loop ((p path)) (cond ((null? p)) ((null? (cdr p)) (display (car p))) (else (display (car p)) (display " -> ") (loop (cdr p))))))   (define example-graph '((1 -2 3) (3 2 4) (4 -1 2) (2 4 1) (2 3 3)))   (let-values (((n distance next-vertex) (floyd-warshall example-graph))) (display " pair distance path") (newline) (display "------------------------------------") (newline) (do ((u 1 (+ u 1))) ((< n u)) (do ((v 1 (+ v 1))) ((< n v)) (unless (= u v) (display u) (display " -> ") (display v) (let* ((s (number->string (arr-ref distance u v))) (slen (string-length s)) (padding (- 7 slen))) (display (make-string padding #\space)) (display s)) (display " ") (display-path (find-path next-vertex u v)) (newline)))))
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
#XLISP
XLISP
(defun multiply (x y) (* 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
#Xojo
Xojo
Function Multiply(ByVal a As Integer, ByVal 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.)
#SQL
SQL
WITH RECURSIVE T0 (N, ITEM, LIST, NEW_LIST) AS ( SELECT 1, NULL, '90,47,58,29,22,32,55,5,55,73' || ',', NULL UNION ALL SELECT CASE WHEN SUBSTR(LIST, INSTR(LIST, ',') + 1, LENGTH(LIST)) = '' THEN N + 1 ELSE N END, CASE WHEN SUBSTR(LIST, INSTR(LIST, ',') + 1, LENGTH(LIST)) <> '' THEN SUBSTR(LIST, 1, INSTR(LIST, ',') - 1) ELSE NULL END, CASE WHEN SUBSTR(LIST, INSTR(LIST, ',') + 1, LENGTH(LIST)) = '' THEN IFNULL(NEW_LIST || (SUBSTR(LIST, 1, INSTR(LIST, ',') - 1) - ITEM) || ',', '') ELSE SUBSTR(LIST, INSTR(LIST, ',') + 1, LENGTH(LIST)) END, CASE WHEN SUBSTR(LIST, INSTR(LIST, ',') + 1, LENGTH(LIST)) <> '' THEN IFNULL(NEW_LIST, '') || IFNULL((SUBSTR(LIST, 1, INSTR(LIST, ',') - 1) - ITEM) || ',', '') ELSE NULL END FROM T0 WHERE INSTR(LIST, ',') > 0 ) SELECT N, TRIM(LIST, ',') LIST FROM T0 WHERE NEW_LIST IS NULL AND LIST <> '' ORDER BY N;
http://rosettacode.org/wiki/Four_bit_adder
Four bit adder
Task "Simulate" a four-bit adder. This design can be realized using four 1-bit full adders. Each of these 1-bit full adders can be built with two half adders and an   or   gate. ; Finally a half adder can be made using an   xor   gate and an   and   gate. The   xor   gate can be made using two   nots,   two   ands   and one   or. Not,   or   and   and,   the only allowed "gates" for the task, can be "imitated" by using the bitwise operators of your language. If there is not a bit type in your language, to be sure that the   not   does not "invert" all the other bits of the basic type   (e.g. a byte)   we are not interested in,   you can use an extra   nand   (and   then   not)   with the constant   1   on one input. Instead of optimizing and reducing the number of gates used for the final 4-bit adder,   build it in the most straightforward way,   connecting the other "constructive blocks",   in turn made of "simpler" and "smaller" ones. Schematics of the "constructive blocks" (Xor gate with ANDs, ORs and NOTs)            (A half adder)                   (A full adder)                             (A 4-bit adder)         Solutions should try to be as descriptive as possible, making it as easy as possible to identify "connections" between higher-order "blocks". It is not mandatory to replicate the syntax of higher-order blocks in the atomic "gate" blocks, i.e. basic "gate" operations can be performed as usual bitwise operations, or they can be "wrapped" in a block in order to expose the same syntax of higher-order blocks, at implementers' choice. To test the implementation, show the sum of two four-bit numbers (in binary).
#Swift
Swift
typealias FourBit = (Int, Int, Int, Int)   func halfAdder(_ a: Int, _ b: Int) -> (Int, Int) { return (a ^ b, a & b) }   func fullAdder(_ a: Int, _ b: Int, carry: Int) -> (Int, Int) { let (s0, c0) = halfAdder(a, b) let (s1, c1) = halfAdder(s0, carry)   return (s1, c0 | c1) }   func fourBitAdder(_ a: FourBit, _ b: FourBit) -> (FourBit, carry: Int) { let (sum1, carry1) = halfAdder(a.3, b.3) let (sum2, carry2) = fullAdder(a.2, b.2, carry: carry1) let (sum3, carry3) = fullAdder(a.1, b.1, carry: carry2) let (sum4, carryOut) = fullAdder(a.0, b.0, carry: carry3)   return ((sum4, sum3, sum2, sum1), carryOut) }   let a = (0, 1, 1, 0) let b = (0, 1, 1, 0)   print("\(a) + \(b) = \(fourBitAdder(a, 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.
#Sidef
Sidef
func fourths(e) { var t = ((e>>1) / 2) [0, t, e/2, e - t, e] }   func fivenum(nums) { var x = nums.sort var d = fourths(x.end)   ([x[d.map{.floor}]] ~Z+ [x[d.map{.ceil}]]) »/» 2 }   var nums = [ [15, 6, 42, 41, 7, 36, 49, 40, 39, 47, 43], [36, 40, 7, 39, 41, 15], [ 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578, ]]   nums.each { say fivenum(_).join(', ') }
http://rosettacode.org/wiki/Find_the_missing_permutation
Find the missing permutation
ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB Listed above are   all-but-one   of the permutations of the symbols   A,   B,   C,   and   D,   except   for one permutation that's   not   listed. Task Find that missing permutation. Methods Obvious method: enumerate all permutations of A, B, C, and D, and then look for the missing permutation. alternate method: Hint: if all permutations were shown above, how many times would A appear in each position? What is the parity of this number? another alternate method: Hint: if you add up the letter values of each column, does a missing letter A, B, C, and D from each column cause the total value for each column to be unique? Related task   Permutations)
#Common_Lisp
Common Lisp
(defparameter *permutations* '("ABCD" "CABD" "ACDB" "DACB" "BCDA" "ACBD" "ADCB" "CDAB" "DABC" "BCAD" "CADB" "CDBA" "CBAD" "ABDC" "ADBC" "BDCA" "DCBA" "BACD" "BADC" "BDAC" "CBDA" "DBCA" "DCAB"))   (defun missing-perm (perms) (let* ((letters (loop for i across (car perms) collecting i)) (l (/ (1+ (length perms)) (length letters)))) (labels ((enum (n) (loop for i below n collecting i)) (least-occurs (pos) (let ((occurs (loop for i in perms collecting (aref i pos)))) (cdr (assoc (1- l) (mapcar #'(lambda (letter) (cons (count letter occurs) letter)) letters)))))) (concatenate 'string (mapcar #'least-occurs (enum (length letters)))))))
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month
Find the last Sunday of each month
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 2013-05-26 2013-06-30 2013-07-28 2013-08-25 2013-09-29 2013-10-27 2013-11-24 2013-12-29 Related tasks Day of the week Five weekends Last Friday of each month
#Excel
Excel
lastSundayOfEachMonth =LAMBDA(y, LAMBDA(monthEnd, 1 + monthEnd - WEEKDAY(monthEnd) )( EDATE( DATEVALUE(y & "-01-31"), SEQUENCE(12, 1, 0, 1) ) ) )