task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Function_definition
Function definition
A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract from showing how functions are created and values returned). Related task   Function prototype
#Tcl
Tcl
proc multiply { arg1 arg2 } { return [expr {$arg1 * $arg2}] }
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.)
#Pop11
Pop11
define forward_difference(l); lvars res = [], prev, el; if l = [] then return([]); endif; front(l) -> prev; for el in back(l) do cons(el - prev, res) -> res; el -> prev; endfor; rev(res); enddefine;   define nth_difference(l, n); lvars res = l, i; for i from 1 to n do forward_difference(res) -> res; endfor; res; enddefine;
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.)
#PowerShell
PowerShell
function Forward-Difference( [UInt64] $n, [Array] $f ) { $flen = $f.length if( $flen -gt [Math]::Max( 1, $n ) ) { 0..( $flen - $n - 1 ) | ForEach-Object { $l=0; for( $k = 0; $k -le $n; $k++ ) { $j = 1 for( $i = 1; $i -le $k; $i++ ) { $j *= ( ( $n - $k + $i ) / $i ) } $l += $j * ( 1 - 2 * ( ( $n - $k ) % 2 ) ) * $f[ $_ + $k ] } $l } } }   Forward-Difference 2 1,2,4,5
http://rosettacode.org/wiki/Formatted_numeric_output
Formatted numeric output
Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
#Toka
Toka
needs values value n 123 to n   2 import printf " %08d" n printf
http://rosettacode.org/wiki/Formatted_numeric_output
Formatted numeric output
Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
#Ursala
Ursala
#import flo   x = 7.125   #show+   t = <printf/'%09.3f' x>
http://rosettacode.org/wiki/Four_bit_adder
Four bit adder
Task "Simulate" a four-bit adder. This design can be realized using four 1-bit full adders. Each of these 1-bit full adders can be built with two half adders and an   or   gate. ; Finally a half adder can be made using an   xor   gate and an   and   gate. The   xor   gate can be made using two   nots,   two   ands   and one   or. Not,   or   and   and,   the only allowed "gates" for the task, can be "imitated" by using the bitwise operators of your language. If there is not a bit type in your language, to be sure that the   not   does not "invert" all the other bits of the basic type   (e.g. a byte)   we are not interested in,   you can use an extra   nand   (and   then   not)   with the constant   1   on one input. Instead of optimizing and reducing the number of gates used for the final 4-bit adder,   build it in the most straightforward way,   connecting the other "constructive blocks",   in turn made of "simpler" and "smaller" ones. Schematics of the "constructive blocks" (Xor gate with ANDs, ORs and NOTs)            (A half adder)                   (A full adder)                             (A 4-bit adder)         Solutions should try to be as descriptive as possible, making it as easy as possible to identify "connections" between higher-order "blocks". It is not mandatory to replicate the syntax of higher-order blocks in the atomic "gate" blocks, i.e. basic "gate" operations can be performed as usual bitwise operations, or they can be "wrapped" in a block in order to expose the same syntax of higher-order blocks, at implementers' choice. To test the implementation, show the sum of two four-bit numbers (in binary).
#Racket
Racket
#lang racket   (define (adder-and a b) (if (= 2 (+ a b)) 1 0))  ; Defining the basic and function   (define (adder-not a) (if (zero? a) 1 0))  ; Defining the basic not function   (define (adder-or a b) (if (> (+ a b) 0) 1 0))  ; Defining the basic or function   (define (adder-xor a b) (adder-or (adder-and (adder-not a) b) (adder-and a (adder-not b))))  ; Defines the xor function based on the basic functions   (define (half-adder a b) (list (adder-xor a b) (adder-and a b))) ; Creates the half adder, returning '(sum carry)   (define (adder a b c0) (define half-a (half-adder c0 a)) (define half-b (half-adder (car half-a) b)) (list (car half-b) (adder-or (cadr half-a) (cadr half-b))))  ; Creates the full adder, returns '(sum carry)   (define (n-bit-adder 4a 4b)  ; Creates the n-bit adder, it receives 2 lists of same length (let-values  ; Lists of the form '([01]+) (((4s v)  ; for/fold form will return 2 values, receiving this here (for/fold ((S null) (c 0)) ;initializes the full sum and carry ((a (in-list (reverse 4a))) (b (in-list (reverse 4b))))  ;here it prepares variables for summing each element, starting from the least important bits (define added (adder a b c)) (values (cons (car added) S) ; changes S and c to it's new values in the next iteration (cadr added))))) (if (zero? v) 4s (cons v 4s))))   (n-bit-adder '(1 0 1 0) '(0 1 1 1)) ;-> '(1 0 0 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.
#MATLAB_.2F_Octave
MATLAB / Octave
  function r = fivenum(x) r = quantile(x,[0:4]/4); end;  
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.
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
ClearAll[FiveNum] FiveNum[x_List] := Quantile[x, Range[0, 1, 1/4]] FiveNum[RandomVariate[NormalDistribution[], 10000]]
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)
#AppleScript
AppleScript
use framework "Foundation" -- ( sort )   --------------- RAREST LETTER IN EACH COLUMN ------------- on run concat(map(composeList({¬ head, ¬ minimumBy(comparing(|length|)), ¬ group, ¬ sort}), ¬ transpose(map(chars, ¬ |words|("ABCD CABD ACDB DACB BCDA ACBD " & ¬ "ADCB CDAB DABC BCAD CADB CDBA " & ¬ "CBAD ABDC ADBC BDCA DCBA BACD " & ¬ "BADC BDAC CBDA DBCA DCAB")))))   --> "DBAC" end run     -------------------- GENERIC FUNCTIONS -------------------   -- chars :: String -> [String] on chars(s) characters of s end chars     -- Ordering  :: (-1 | 0 | 1) -- compare :: a -> a -> Ordering on compare(a, b) if a < b then -1 else if a > b then 1 else 0 end if end compare     -- comparing :: (a -> b) -> (a -> a -> Ordering) on comparing(f) script on |λ|(a, b) tell mReturn(f) to compare(|λ|(a), |λ|(b)) end |λ| end script end comparing     -- composeList :: [(a -> a)] -> (a -> a) on composeList(fs) script on |λ|(x) script go on |λ|(f, a) mReturn(f)'s |λ|(a) end |λ| end script foldr(go, x, fs) end |λ| end script end composeList     -- concat :: [[a]] -> [a] -- concat :: [String] -> String on concat(xs) set lng to length of xs if 0 < lng and string is class of (item 1 of xs) then set acc to "" else set acc to {} end if repeat with i from 1 to lng set acc to acc & item i of xs end repeat acc end concat     -- foldl :: (a -> b -> a) -> a -> [b] -> a on foldl(f, startValue, xs) tell mReturn(f) set v to startValue set lng to length of xs repeat with i from 1 to lng set v to |λ|(v, item i of xs, i, xs) end repeat return v end tell end foldl     -- foldr :: (b -> a -> a) -> a -> [b] -> a on foldr(f, startValue, xs) tell mReturn(f) set v to startValue set lng to length of xs repeat with i from lng to 1 by -1 set v to |λ|(item i of xs, v, i, xs) end repeat return v end tell end foldr     -- group :: Eq a => [a] -> [[a]] on group(xs) script eq on |λ|(a, b) a = b end |λ| end script   groupBy(eq, xs) end group     -- groupBy :: (a -> a -> Bool) -> [a] -> [[a]] on groupBy(f, xs) set mf to mReturn(f)   script enGroup on |λ|(a, x) if length of (active of a) > 0 then set h to item 1 of active of a else set h to missing value end if   if h is not missing value and mf's |λ|(h, x) then {active:(active of a) & x, sofar:sofar of a} else {active:{x}, sofar:(sofar of a) & {active of a}} end if end |λ| end script   if length of xs > 0 then set dct to foldl(enGroup, {active:{item 1 of xs}, sofar:{}}, tail(xs)) if length of (active of dct) > 0 then sofar of dct & {active of dct} else sofar of dct end if else {} end if end groupBy     -- head :: [a] -> a on head(xs) if length of xs > 0 then item 1 of xs else missing value end if end head     -- intercalate :: Text -> [Text] -> Text on intercalate(strText, lstText) set {dlm, my text item delimiters} to {my text item delimiters, strText} set strJoined to lstText as text set my text item delimiters to dlm return strJoined end intercalate     -- length :: [a] -> Int on |length|(xs) length of xs end |length|     -- map :: (a -> b) -> [a] -> [b] on map(f, xs) tell mReturn(f) set lng to length of xs set lst to {} repeat with i from 1 to lng set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell end map     -- minimumBy :: (a -> a -> Ordering) -> [a] -> a on minimumBy(f) script on |λ|(xs) if length of xs < 1 then return missing value tell mReturn(f) set v to item 1 of xs repeat with x in xs if |λ|(x, v) < 0 then set v to x end repeat return v end tell end |λ| end script end minimumBy     -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: Handler -> Script on mReturn(f) if class of f is script then f else script property |λ| : f end script end if end mReturn     -- sort :: [a] -> [a] on sort(xs) ((current application's NSArray's arrayWithArray:xs)'s ¬ sortedArrayUsingSelector:"compare:") as list end sort     -- tail :: [a] -> [a] on tail(xs) if length of xs > 1 then items 2 thru -1 of xs else {} end if end tail     -- transpose :: [[a]] -> [[a]] on transpose(xss) script column on |λ|(_, iCol) script row on |λ|(xs) item iCol of xs end |λ| end script   map(row, xss) end |λ| end script   map(column, item 1 of xss) end transpose     -- words :: String -> [String] on |words|(s) words of s end |words|
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
#Befunge
Befunge
":raeY",,,,,&>55+,:::45*:*%\"d"%!*\4%+!3v v2++6**"I"5\+/*:*54\-/"d"\/4::-1::p53+g5< >:00p5g4-+7%\:0\v>,"-",5g+:55+/68*+,55+%v ^<<_$$vv*86%+55:<^+*86%+55,+*86/+55:-1:<6 >$$^@$<>+\55+/:#^_$>:#,_$"-",\:04-\-00g^8 ^<# #"#"##"#"##!` +76:+1g00,+55,+*<
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) .
#C.23
C#
using System; using System.Drawing; public class Program { static PointF FindIntersection(PointF s1, PointF e1, PointF s2, PointF e2) { float a1 = e1.Y - s1.Y; float b1 = s1.X - e1.X; float c1 = a1 * s1.X + b1 * s1.Y;   float a2 = e2.Y - s2.Y; float b2 = s2.X - e2.X; float c2 = a2 * s2.X + b2 * s2.Y;   float delta = a1 * b2 - a2 * b1; //If lines are parallel, the result will be (NaN, NaN). return delta == 0 ? new PointF(float.NaN, float.NaN) : new PointF((b2 * c1 - b1 * c2) / delta, (a1 * c2 - a2 * c1) / delta); }   static void Main() { Func<float, float, PointF> p = (x, y) => new PointF(x, y); Console.WriteLine(FindIntersection(p(4f, 0f), p(6f, 10f), p(0f, 3f), p(10f, 7f))); Console.WriteLine(FindIntersection(p(0f, 0f), p(1f, 1f), p(1f, 2f), p(4f, 5f))); } }
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].
#C.23
C#
using System;   namespace FindIntersection { class Vector3D { private double x, y, z;   public Vector3D(double x, double y, double z) { this.x = x; this.y = y; this.z = z; }   public static Vector3D operator +(Vector3D lhs, Vector3D rhs) { return new Vector3D(lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z); }   public static Vector3D operator -(Vector3D lhs, Vector3D rhs) { return new Vector3D(lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z); }   public static Vector3D operator *(Vector3D lhs, double rhs) { return new Vector3D(lhs.x * rhs, lhs.y * rhs, lhs.z * rhs); }   public double Dot(Vector3D rhs) { return x * rhs.x + y * rhs.y + z * rhs.z; }   public override string ToString() { return string.Format("({0:F}, {1:F}, {2:F})", x, y, z); } }   class Program { static Vector3D IntersectPoint(Vector3D rayVector, Vector3D rayPoint, Vector3D planeNormal, Vector3D planePoint) { var diff = rayPoint - planePoint; var prod1 = diff.Dot(planeNormal); var prod2 = rayVector.Dot(planeNormal); var prod3 = prod1 / prod2; return rayPoint - rayVector * prod3; }   static void Main(string[] args) { var rv = new Vector3D(0.0, -1.0, -1.0); var rp = new Vector3D(0.0, 0.0, 10.0); var pn = new Vector3D(0.0, 0.0, 1.0); var pp = new Vector3D(0.0, 0.0, 5.0); var ip = IntersectPoint(rv, rp, pn, pp); Console.WriteLine("The ray intersects the plane at {0}", 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
#ActionScript
ActionScript
for (var i:int = 1; i <= 100; i++) { if (i % 15 == 0) trace('FizzBuzz'); else if (i % 5 == 0) trace('Buzz'); else if (i % 3 == 0) trace('Fizz'); else trace(i); }
http://rosettacode.org/wiki/Five_weekends
Five weekends
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays. Task Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar). Show the number of months with this property (there should be 201). Show at least the first and last five dates, in order. Algorithm suggestions Count the number of Fridays, Saturdays, and Sundays in every month. Find all of the 31-day months that begin on Friday. Extra credit Count and/or show all of the years which do not have at least one five-weekend month (there should be 29). Related tasks Day of the week Last Friday of each month Find last sunday of each month
#Ceylon
Ceylon
  module rosetta.fiveweekends "1.0.0" { import ceylon.time "1.2.2"; }  
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
#Clojure
Clojure
(import java.util.GregorianCalendar java.text.DateFormatSymbols)   (->> (for [year (range 1900 2101) month [0 2 4 6 7 9 11] ;; 31 day months  :let [cal (GregorianCalendar. year month 1) day (.get cal GregorianCalendar/DAY_OF_WEEK)]  :when (= day GregorianCalendar/FRIDAY)] (println month "-" year)) count (println "Total Months: " ,))
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
#Julia
Julia
const num = "0123456789abcdef" hasallin(n, nums, b) = (s = string(n, base=b); all(x -> occursin(x, s), nums))   function squaresearch(base) basenumerals = [c for c in num[1:base]] highest = parse(Int, "10" * num[3:base], base=base) for n in Int(trunc(sqrt(highest))):highest if hasallin(n * n, basenumerals, base) return n end end end   println("Base Root N") for b in 2:16 n = squaresearch(b) println(lpad(b, 3), lpad(string(n, base=b), 10), " ", string(n * n, base=b)) end  
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
#Kotlin
Kotlin
import java.math.BigInteger import java.time.Duration import java.util.ArrayList import java.util.HashSet import kotlin.math.sqrt   const val ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz|" var base: Byte = 0 var bmo: Byte = 0 var blim: Byte = 0 var ic: Byte = 0 var st0: Long = 0 var bllim: BigInteger? = null var threshold: BigInteger? = null var hs: MutableSet<Byte> = HashSet() var o: MutableSet<Byte> = HashSet() val chars = ALPHABET.toCharArray() var limits: MutableList<BigInteger?>? = null var ms: String? = null   fun indexOf(c: Char): Int { for (i in chars.indices) { if (chars[i] == c) { return i } } return -1 }   // convert BigInteger to string using current base fun toStr(b: BigInteger): String { var b2 = b val bigBase = BigInteger.valueOf(base.toLong()) val res = StringBuilder() while (b2 > BigInteger.ZERO) { val divRem = b2.divideAndRemainder(bigBase) res.append(chars[divRem[1].toInt()]) b2 = divRem[0] } return res.toString() }   // check for a portion of digits, bailing if uneven fun allInQS(b: BigInteger): Boolean { var b2 = b val bigBase = BigInteger.valueOf(base.toLong()) var c = ic.toInt() hs.clear() hs.addAll(o) while (b2 > bllim) { val divRem = b2.divideAndRemainder(bigBase) hs.add(divRem[1].toByte()) c++ if (c > hs.size) { return false } b2 = divRem[0] } return true }   // check for a portion of digits, all the way to the end fun allInS(b: BigInteger): Boolean { var b2 = b val bigBase = BigInteger.valueOf(base.toLong()) hs.clear() hs.addAll(o) while (b2 > bllim) { val divRem = b2.divideAndRemainder(bigBase) hs.add(divRem[1].toByte()) b2 = divRem[0] } return hs.size == base.toInt() }   // check for all digits, bailing if uneven fun allInQ(b: BigInteger): Boolean { var b2 = b val bigBase = BigInteger.valueOf(base.toLong()) var c = 0 hs.clear() while (b2 > BigInteger.ZERO) { val divRem = b2.divideAndRemainder(bigBase) hs.add(divRem[1].toByte()) c++ if (c > hs.size) { return false } b2 = divRem[0] } return true }   // check for all digits, all the way to the end fun allIn(b: BigInteger): Boolean { var b2 = b val bigBase = BigInteger.valueOf(base.toLong()) hs.clear() while (b2 > BigInteger.ZERO) { val divRem = b2.divideAndRemainder(bigBase) hs.add(divRem[1].toByte()) b2 = divRem[0] } return hs.size == base.toInt() }   // parse a string into a BigInteger, using current base fun to10(s: String?): BigInteger { val bigBase = BigInteger.valueOf(base.toLong()) var res = BigInteger.ZERO for (element in s!!) { val idx = indexOf(element) val bigIdx = BigInteger.valueOf(idx.toLong()) res = res.multiply(bigBase).add(bigIdx) } return res }   // returns the minimum value string, optionally inserting extra digit fun fixup(n: Int): String { var res = ALPHABET.substring(0, base.toInt()) if (n > 0) { val sb = StringBuilder(res) sb.insert(n, n) res = sb.toString() } return "10" + res.substring(2) }   // checks the square against the threshold, advances various limits when needed fun check(sq: BigInteger) { if (sq > threshold) { o.remove(indexOf(ms!![blim.toInt()]).toByte()) blim-- ic-- threshold = limits!![bmo - blim - 1] bllim = to10(ms!!.substring(0, blim + 1)) } }   // performs all the calculations for the current base fun doOne() { limits = ArrayList() bmo = (base - 1).toByte() var dr: Byte = 0 if ((base.toInt() and 1) == 1) { dr = (base.toInt() shr 1).toByte() } o.clear() blim = 0 var id: Byte = 0 var inc = 1 val st = System.nanoTime() val sdr = ByteArray(bmo.toInt()) var rc: Byte = 0 for (i in 0 until bmo) { sdr[i] = (i * i % bmo).toByte() if (sdr[i] == dr) { rc = (rc + 1).toByte() } if (sdr[i] == 0.toByte()) { sdr[i] = (sdr[i] + bmo).toByte() } } var i: Long = 0 if (dr > 0) { id = base i = 1 while (i <= dr) { if (sdr[i.toInt()] >= dr) { if (id > sdr[i.toInt()]) { id = sdr[i.toInt()] } } i++ } id = (id - dr).toByte() i = 0 } ms = fixup(id.toInt()) var sq = to10(ms) var rt = BigInteger.valueOf((sqrt(sq.toDouble()) + 1).toLong()) sq = rt.multiply(rt) if (base > 9) { for (j in 1 until base) { limits!!.add(to10(ms!!.substring(0, j) + chars[bmo.toInt()].toString().repeat(base - j + if (rc > 0) 0 else 1))) } limits!!.reverse() while (sq < limits!![0]) { rt = rt.add(BigInteger.ONE) sq = rt.multiply(rt) } } var dn = rt.shiftLeft(1).add(BigInteger.ONE) var d = BigInteger.ONE if (base > 3 && rc > 0) { while (sq.remainder(BigInteger.valueOf(bmo.toLong())).compareTo(BigInteger.valueOf(dr.toLong())) != 0) { rt = rt.add(BigInteger.ONE) sq = sq.add(dn) dn = dn.add(BigInteger.TWO) } // aligns sq to dr inc = bmo / rc if (inc > 1) { dn = dn.add(rt.multiply(BigInteger.valueOf(inc - 2.toLong())).subtract(BigInteger.ONE)) d = BigInteger.valueOf(inc * inc.toLong()) } dn = dn.add(dn).add(d) } d = d.shiftLeft(1) if (base > 9) { blim = 0 while (sq < limits!![bmo - blim - 1]) { blim++ } ic = (blim + 1).toByte() threshold = limits!![bmo - blim - 1] if (blim > 0) { for (j in 0..blim) { o.add(indexOf(ms!![j]).toByte()) } } bllim = if (blim > 0) { to10(ms!!.substring(0, blim + 1)) } else { BigInteger.ZERO } if (base > 5 && rc > 0) while (!allInQS(sq)) { sq = sq.add(dn) dn = dn.add(d) i += 1 check(sq) } else { while (!allInS(sq)) { sq = sq.add(dn) dn = dn.add(d) i += 1 check(sq) } } } else { if (base > 5 && rc > 0) { while (!allInQ(sq)) { sq = sq.add(dn) dn = dn.add(d) i += 1 } } else { while (!allIn(sq)) { sq = sq.add(dn) dn = dn.add(d) i += 1 } } } rt = rt.add(BigInteger.valueOf(i * inc)) val delta1 = System.nanoTime() - st val dur1 = Duration.ofNanos(delta1) val delta2 = System.nanoTime() - st0 val dur2 = Duration.ofNanos(delta2) System.out.printf( "%3d  %2d  %2s %20s -> %-40s %10d %9s  %9s\n", base, inc, if (id > 0) ALPHABET.substring(id.toInt(), id + 1) else " ", toStr(rt), toStr(sq), i, format(dur1), format(dur2) ) }   private fun format(d: Duration): String { val minP = d.toMinutesPart() val secP = d.toSecondsPart() val milP = d.toMillisPart() return String.format("%02d:%02d.%03d", minP, secP, milP) }   fun main() { println("base inc id root square test count time total") st0 = System.nanoTime() base = 2 while (base < 28) { doOne() ++base } }
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
#D
D
void main() { import std.stdio, std.math, std.typetuple, std.functional;   alias dir = TypeTuple!(sin, cos, x => x ^^ 3); alias inv = TypeTuple!(asin, acos, cbrt); // foreach (f, g; staticZip!(dir, inv)) foreach (immutable i, f; dir) writefln("%6.3f", compose!(f, inv[i])(0.5)); }
http://rosettacode.org/wiki/First-class_functions
First-class functions
A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming: Create new functions from preexisting functions at run-time Store functions in collections Use functions as arguments to other functions Use functions as return values of other functions Task Write a program to create an ordered collection A of functions of a real number. At least one function should be built-in and at least one should be user-defined; try using the sine, cosine, and cubing functions. Fill another collection B with the inverse of each function in A. Implement function composition as in Functional Composition. Finally, demonstrate that the result of applying the composition of each function in A and its inverse in B to a value, is the original value. (Within the limits of computational accuracy). (A solution need not actually call the collections "A" and "B". These names are only used in the preceding paragraph for clarity.) Related task First-class Numbers
#Dart
Dart
import 'dart:math' as Math; cube(x) => x*x*x; cuberoot(x) => Math.pow(x, 1/3); compose(f,g) => ((x)=>f(g(x))); main(){ var functions = [Math.sin, Math.exp, cube]; var inverses = [Math.asin, Math.log, cuberoot]; for (int i = 0; i < 3; i++){ print(compose(functions[i], inverses[i])(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.
#JAMES_II.2FRule-based_Cellular_Automata
JAMES II/Rule-based Cellular Automata
@caversion 1;   dimensions 2;   state EMPTY, TREE, BURNING;   // an empty cell grows a tree with a chance of p = 5 % rule{EMPTY} [0.05] : -> TREE;   // a burning cell turns to a burned cell rule{BURNING}: -> EMPTY;   // a tree starts burning if there is at least one neighbor burning rule{TREE} : BURNING{1,} -> BURNING;   // a tree is hit by lightning with a change of f = 0.006 % rule{TREE} [0.00006] : -> BURNING;
http://rosettacode.org/wiki/First_class_environments
First class environments
According to Wikipedia, "In computing, a first-class object ... is an entity that can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable". Often this term is used in the context of "first class functions". In an analogous way, a programming language may support "first class environments". The environment is minimally, the set of variables accessible to a statement being executed. Change the environments and the same statement could produce different results when executed. Often an environment is captured in a closure, which encapsulates a function together with an environment. That environment, however, is not first-class, as it cannot be created, passed etc. independently from the function's code. Therefore, a first class environment is a set of variable bindings which can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable. It is like a closure without code. A statement must be able to be executed within a stored first class environment and act according to the environment variable values stored within. Task Build a dozen environments, and a single piece of code to be run repeatedly in each of these environments. Each environment contains the bindings for two variables:   a value in the Hailstone sequence, and   a count which is incremented until the value drops to 1. The initial hailstone values are 1 through 12, and the count in each environment is zero. When the code runs, it calculates the next hailstone step in the current environment (unless the value is already 1) and counts the steps. Then it prints the current value in a tabular form. When all hailstone values dropped to 1, processing stops, and the total number of hailstone steps for each environment is printed.
#Ruby
Ruby
# Build environments envs = (1..12).map do |n| Object.new.instance_eval {@n = n; @cnt = 0; self} end   # Until all values are 1: until envs.all? {|e| e.instance_eval{@n} == 1} envs.each do |e| e.instance_eval do # Use environment _e_ printf "%4s", @n if @n > 1 @cnt += 1 # Increment step count @n = if @n.odd? # Calculate next hailstone value @n * 3 + 1 else @n / 2 end end end end puts end puts '=' * 48 envs.each do |e| # For each environment _e_ e.instance_eval do printf "%4s", @cnt # print the step count end end puts
http://rosettacode.org/wiki/First_class_environments
First class environments
According to Wikipedia, "In computing, a first-class object ... is an entity that can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable". Often this term is used in the context of "first class functions". In an analogous way, a programming language may support "first class environments". The environment is minimally, the set of variables accessible to a statement being executed. Change the environments and the same statement could produce different results when executed. Often an environment is captured in a closure, which encapsulates a function together with an environment. That environment, however, is not first-class, as it cannot be created, passed etc. independently from the function's code. Therefore, a first class environment is a set of variable bindings which can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable. It is like a closure without code. A statement must be able to be executed within a stored first class environment and act according to the environment variable values stored within. Task Build a dozen environments, and a single piece of code to be run repeatedly in each of these environments. Each environment contains the bindings for two variables:   a value in the Hailstone sequence, and   a count which is incremented until the value drops to 1. The initial hailstone values are 1 through 12, and the count in each environment is zero. When the code runs, it calculates the next hailstone step in the current environment (unless the value is already 1) and counts the steps. Then it prints the current value in a tabular form. When all hailstone values dropped to 1, processing stops, and the total number of hailstone steps for each environment is printed.
#Sidef
Sidef
func calculator({.is_one} ) { 1 } func calculator(n {.is_even}) { n / 2 } func calculator(n ) { 3*n + 1 }   func succ(this {_{:value}.is_one}, _) { return this }   func succ(this, get_next) { this{:value} = get_next(this{:value}) this{:count}++ return this }   var enviornments = (1..12 -> map {|i| Hash(value => i, count => 0) });   while (!enviornments.map{ _{:value} }.all { .is_one }) { say enviornments.map {|h| "%4s" % h{:value} }.join; enviornments.range.each { |i| enviornments[i] = succ(enviornments[i], calculator); } }   say 'Counts'; say enviornments.map{ |h| "%4s" % h{:count} }.join;
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
#Ela
Ela
xs = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]   flat = flat' [] where flat' n [] = n flat' n (x::xs) | x is List = flat' (flat' n xs) x | else = x :: flat' n xs   flat xs
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.
#Raku
Raku
sub MAIN ($square = 4) { say "{$square}? Seriously?" and exit if $square < 1 or $square > 26; my %bits = map { $_ => %( map { $_ => 0 }, ('A' .. *)[^ $square] ) }, (1 .. *)[^ $square]; scramble %bits; my $target = build %bits; scramble %bits until build(%bits) ne $target; display($target, %bits); my $turns = 0; while my $flip = prompt "Turn {++$turns}: Flip which row / column? " { flip $flip.match(/\w/).uc, %bits; if display($target, %bits) { say "Hurray! You solved it in $turns turns."; last; } } }   sub display($goal, %hash) { shell('clear'); say "Goal\n$goal\nYou"; my $this = build %hash; say $this; return ($goal eq $this); }   sub flip ($a, %hash) { given $a { when any(keys %hash) { %hash{$a}{$_} = %hash{$a}{$_} +^ 1 for %hash{$a}.keys }; when any(keys %hash{'1'}) { %hash{$_}{$a} = %hash{$_}{$a} +^ 1 for %hash.keys }; } }   sub build (%hash) { my $string = ' '; $string ~= sprintf "%2s ", $_ for sort keys %hash{'1'}; $string ~= "\n"; for %hash.keys.sort: +* -> $key { $string ~= sprintf "%2s ", $key; $string ~= sprintf "%2s ", %hash{$key}{$_} for sort keys %hash{$key}; $string ~= "\n"; }; $string }   sub scramble(%hash) { my @keys = keys %hash; @keys.push: | keys %hash{'1'}; flip $_, %hash for @keys.pick( @keys/2 ); }
http://rosettacode.org/wiki/First_power_of_2_that_has_leading_decimal_digits_of_12
First power of 2 that has leading decimal digits of 12
(This task is taken from a   Project Euler   problem.) (All numbers herein are expressed in base ten.) 27   =   128   and   7   is the first power of   2   whose leading decimal digits are   12. The next power of   2   whose leading decimal digits are   12   is   80, 280   =   1208925819614629174706176. Define     p(L,n)     to be the nth-smallest value of   j   such that the base ten representation of   2j   begins with the digits of   L . So p(12, 1) = 7 and p(12, 2) = 80 You are also given that: p(123, 45)   =   12710 Task   find:   p(12, 1)   p(12, 2)   p(123, 45)   p(123, 12345)   p(123, 678910)   display the results here, on this page.
#REXX
REXX
/*REXX program computes powers of two whose leading decimal digits are "12" (in base 10)*/ parse arg L n b . /*obtain optional arguments from the CL*/ if L=='' | L=="," then L= 12 /*Not specified? Then use the default.*/ if n=='' | n=="," then n= 1 /* " " " " " " */ if b=='' | b=="," then b= 2 /* " " " " " " */ LL= length(L) /*obtain the length of L for compares*/ fd= left(L, 1) /*obtain the first dec. digit of L.*/ fr= substr(L, 2) /* " " rest of dec. digits " " */ numeric digits max(20, LL+2) /*use an appropriate value of dec. digs*/ rest= LL - 1 /*the length of the rest of the digits.*/ #= 0 /*the number of occurrences of a result*/ x= 1 /*start with a product of unity (B**0).*/ do j=1 until #==n; x= x * b /*raise B to a whole bunch of powers.*/ parse var x _ 2 /*obtain the first decimal digit of X.*/ if _ \== fd then iterate /*check only the 1st digit at this time*/ if LL>1 then do /*check the rest of the digits, maybe. */ $= format(x, , , , 0) /*express X in exponential format. */ parse var $ '.' +1 f +(rest) /*obtain the rest of the digits. */ if f \== fr then iterate /*verify that X has the rest of digs.*/ end /* [↓] found an occurrence of an answer*/ #= # + 1 /*bump the number of occurrences so far*/ end /*j*/   say 'The ' th(n) ' occurrence of ' b ' raised to a power whose product starts with' , ' "'L"'" ' is ' commas(j). exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ commas: arg _; do c=length(_)-3 to 1 by -3; _= insert(',', _, c); end; return _ th: arg _; return _ || word('th st nd rd', 1 +_//10 * (_//100 % 10\==1) * (_//10 <4))
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
#PicoLisp
PicoLisp
(load "@lib/math.l")   (de multiplier (N1 N2) (curry (N1 N2) (X) (*/ N1 N2 X `(* 1.0 1.0)) ) )   (let (X 2.0 Xi 0.5 Y 4.0 Yi 0.25 Z (+ X Y) Zi (*/ 1.0 1.0 Z)) (mapc '((Num Inv) (prinl (format ((multiplier Inv Num) 0.5) *Scl)) ) (list X Y Z) (list Xi Yi Zi) ) )
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
#Python
Python
IDLE 2.6.1 >>> # Number literals >>> x,xi, y,yi = 2.0,0.5, 4.0,0.25 >>> # Numbers from calculation >>> z = x + y >>> zi = 1.0 / (x + y) >>> # The multiplier function is similar to 'compose' but with numbers >>> multiplier = lambda n1, n2: (lambda m: n1 * n2 * m) >>> # Numbers as members of collections >>> numlist = [x, y, z] >>> numlisti = [xi, yi, zi] >>> # Apply numbers from list >>> [multiplier(inversen, n)(.5) for n, inversen in zip(numlist, numlisti)] [0.5, 0.5, 0.5] >>>
http://rosettacode.org/wiki/Flow-control_structures
Flow-control structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task Document common flow-control structures. One common example of a flow-control structure is the   goto   construct. Note that   Conditional Structures   and   Loop Structures   have their own articles/categories. Related tasks   Conditional Structures   Loop Structures
#REBOL
REBOL
rebol [ Title: "Flow Control" URL: http://rosettacode.org/wiki/Flow_Control_Structures ]   ; return -- Return early from function (normally, functions return ; result of last evaluation).   hatefive: func [ "Prints value unless it's the number 5." value "Value to print." ][ if value = 5 [return "I hate five!"] print value ]   print "Function hatefive, with various values:" hatefive 99 hatefive 13 hatefive 5 hatefive 3   ; break -- Break out of current loop.   print [crlf "Loop to 10, but break out at five:"] repeat i 10 [ if i = 5 [break] print i ]   ; catch/throw -- throw breaks out of a code block to enclosing catch.   print [crlf "Start to print two lines, but throw out after the first:"] catch [ print "First" throw "I'm done!" print "Second" ]   ; Using named catch blocks, you can select which catcher you want when throwing.   print [crlf "Throw from inner code block, caught by outer:"] catch/name [ print "Outer catch block." catch/name [ print "Inner catch block." throw/name "I'm done!" 'Johnson print "We never get here." ] 'Clemens print "We never get here, either." ] 'Johnson   ; try   div: func [ "Divide first number by second." a b /local r "Result" ][ if error? try [r: a / b] [r: "Error!"] r ; Functions return last value evaluated. ]   print [crlf "Report error on bad division:"] print div 10 4 print div 10 2 print div 10 1 print div 10 0
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
#Relation
Relation
call routineName /*no arguments passed to routine.*/ call routineName 50 /*one argument (fifty) passed. */ call routineName 50,60 /*two arguments passed. */ call routineName 50, 60 /*(same as above) */ call routineName 50 ,60 /*(same as above) */ call routineName 10*5 , 8**4 - 4 /*(same as above) */ call routineName 50 , , , 70 /*4 args passed, 2nd&3rd omitted.*/ /*omitted args are NOT null. */ call routineName ,,,,,,,,,,,,,,,,800 /*17 args passed, 16 omitted. */ call date /*looks for DATE internally first*/ call 'DATE' /* " " " BIF | externally*/
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.
#FreeBASIC
FreeBASIC
' version 19-09-2015 ' compile with: fbc -s console   Sub pascal_triangle(n As UInteger)   Dim As UInteger a = 1, b, i, j, switch = n + 1 Dim As String frmt, frmt_1, frmt_2   ' last number of the last line i = (n * (n + 1)) \ 2 frmt_2 = String(Len(Str(i)) + 1, "#") ' first number of the last line i = ((n - 1) * n) \ 2 + 1 frmt_1 = String(Len(Str(i)) + 1, "#")   ' we have 2 different formats strings ' find the point where we have to make the switch If frmt_1 <> frmt_2 Then j = i + 1 While Len(Str(i)) = Len(Str(J)) j = j + 1 Wend switch = j - i End If   Print "output for "; Str(n) : Print For i = 1 To n frmt = frmt_1 b = (i * (i + 1)) \ 2 For j = a To b ' if we have the switching point change format string If j - a = switch Then frmt = frmt_2 Print Using frmt; j; Next j Print a = b + 1 Next i Print   End Sub   ' ------=< MAIN >=------   pascal_triangle(5)   pascal_triangle(14)     ' empty keyboard buffer While Inkey <> "" : Wend Print : Print "hit any key to end program" Sleep End
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)
#Phix
Phix
constant inf = 1e300*1e300 function Path(integer u, integer v, sequence next) if next[u,v]=null then return "" end if sequence path = {sprintf("%d",u)} while u!=v do u = next[u,v] path = append(path,sprintf("%d",u)) end while return join(path,"->") end function procedure FloydWarshall(integer V, sequence weights) sequence dist = repeat(repeat(inf,V),V) sequence next = repeat(repeat(null,V),V) for k=1 to length(weights) do integer {u,v,w} = weights[k] dist[u,v] := w -- the weight of the edge (u,v) next[u,v] := v end for -- standard Floyd-Warshall implementation for k=1 to V do for i=1 to V do for j=1 to V do atom d = dist[i,k] + dist[k,j] if dist[i,j] > d then dist[i,j] := d next[i,j] := next[i,k] end if end for end for end for printf(1,"pair dist path\n") for u=1 to V do for v=1 to V do if u!=v then printf(1,"%d->%d  %2d  %s\n",{u,v,dist[u,v],Path(u,v,next)}) end if end for end for end procedure constant V = 4 constant weights = {{1, 3, -2}, {2, 1, 4}, {2, 3, 3}, {3, 4, 2}, {4, 2, -1}} FloydWarshall(V,weights)
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
#TI-89_BASIC
TI-89 BASIC
multiply(a, b) Func Return a * b EndFunc
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.)
#PureBasic
PureBasic
Procedure forward_difference(List a()) If ListSize(a()) <= 1 ClearList(a()): ProcedureReturn EndIf Protected NewList b() CopyList(a(), b()) LastElement(a()): DeleteElement(a()) SelectElement(b(), 1) ForEach a() a() - b(): NextElement(b()) Next EndProcedure   Procedure nth_difference(List a(), List b(), n) Protected i CopyList(a(), b()) For i = 1 To n forward_difference(b()) Next EndProcedure   Procedure.s display(List a()) Protected output.s ForEach a() output + Str(a()) + "," Next ProcedureReturn RTrim(output,",") EndProcedure   DataSection ;list data Data.i 10 ;element count Data.i 90, 47, 58, 29, 22, 32, 55, 5, 55, 73 EndDataSection   ;create and fill list Define i NewList a() Read.i i While i > 0 AddElement(a()): Read.i a(): i - 1 Wend   If OpenConsole() NewList b() For i = 1 To 10 nth_difference(a(), b(), i) PrintN(Str(i) + " [" + display(b()) + "]") Next   Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input() CloseConsole() EndIf    
http://rosettacode.org/wiki/Formatted_numeric_output
Formatted numeric output
Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
#Vala
Vala
void main() { double r = 7.125; print(" %9.3f\n", -r); print(" %9.3f\n",r); print(" %-9.3f\n",r); print(" %09.3f\n",-r); print(" %09.3f\n",r); print(" %-09.3f\n",r); }
http://rosettacode.org/wiki/Formatted_numeric_output
Formatted numeric output
Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
#VBA
VBA
Option Explicit   Sub Main() Debug.Print fFormat(13, 2, 1230.3333) Debug.Print fFormat(2, 13, 1230.3333) Debug.Print fFormat(10, 5, 0.3333) Debug.Print fFormat(13, 2, 1230) End Sub   Private Function fFormat(NbInt As Integer, NbDec As Integer, Nb As Double) As String 'NbInt : Lenght of integral part 'NbDec : Lenght of decimal part 'Nb : decimal on integer number Dim u As String, v As String, i As Integer u = CStr(Nb) i = InStr(u, Application.DecimalSeparator) If i > 0 Then v = Mid(u, i + 1) u = Left(u, i - 1) fFormat = Right(String(NbInt, "0") & u, NbInt) & Application.DecimalSeparator & Left(v & String(NbDec, "0"), NbDec) Else fFormat = Right(String(NbInt, "0") & u, NbInt) & Application.DecimalSeparator & String(NbDec, "0") End If End Function  
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).
#Raku
Raku
sub xor ($a, $b) { (($a and not $b) or (not $a and $b)) ?? 1 !! 0 }   sub half-adder ($a, $b) { return xor($a, $b), ($a and $b); }   sub full-adder ($a, $b, $c0) { my ($ha0_s, $ha0_c) = half-adder($c0, $a); my ($ha1_s, $ha1_c) = half-adder($ha0_s, $b); return $ha1_s, ($ha0_c or $ha1_c); }   sub four-bit-adder ($a0, $a1, $a2, $a3, $b0, $b1, $b2, $b3) { my ($fa0_s, $fa0_c) = full-adder($a0, $b0, 0); my ($fa1_s, $fa1_c) = full-adder($a1, $b1, $fa0_c); my ($fa2_s, $fa2_c) = full-adder($a2, $b2, $fa1_c); my ($fa3_s, $fa3_c) = full-adder($a3, $b3, $fa2_c);   return $fa0_s, $fa1_s, $fa2_s, $fa3_s, $fa3_c; }   { use Test;   is four-bit-adder(1, 0, 0, 0, 1, 0, 0, 0), (0, 1, 0, 0, 0), '1 + 1 == 2'; is four-bit-adder(1, 0, 1, 0, 1, 0, 1, 0), (0, 1, 0, 1, 0), '5 + 5 == 10'; is four-bit-adder(1, 0, 0, 1, 1, 1, 1, 0)[4], 1, '7 + 9 == overflow'; }
http://rosettacode.org/wiki/Fivenum
Fivenum
Many big data or scientific programs use boxplots to show distributions of data.   In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM.   It can be useful to save large arrays as arrays with five numbers to save memory. For example, the   R   programming language implements Tukey's five-number summary as the fivenum function. Task Given an array of numbers, compute the five-number summary. Note While these five numbers can be used to draw a boxplot,   statistical packages will typically need extra data. Moreover, while there is a consensus about the "box" of the boxplot,   there are variations among statistical packages for the whiskers.
#Modula-2
Modula-2
MODULE Fivenum; FROM FormatString IMPORT FormatString; FROM LongStr IMPORT RealToStr; FROM Terminal IMPORT WriteString,WriteLn,ReadChar;   PROCEDURE WriteLongReal(v : LONGREAL); VAR buf : ARRAY[0..63] OF CHAR; BEGIN RealToStr(v, buf); WriteString(buf) END WriteLongReal;   PROCEDURE WriteArray(arr : ARRAY OF LONGREAL); VAR i : CARDINAL; BEGIN WriteString("["); FOR i:=0 TO HIGH(arr) DO WriteLongReal(arr[i]); WriteString(", ") END; WriteString("]") END WriteArray;   (* Assumes that the input is sorted *) PROCEDURE Median(x : ARRAY OF LONGREAL; beg,end : CARDINAL) : LONGREAL; VAR m,cnt : CARDINAL; BEGIN cnt := end - beg + 1; m := cnt / 2; IF cnt MOD 2 = 1 THEN RETURN x[beg + m] END; RETURN (x[beg + m - 1] + x[beg + m]) / 2.0 END Median;   TYPE Summary = ARRAY[0..4] OF LONGREAL; PROCEDURE Fivenum(input : ARRAY OF LONGREAL) : Summary; PROCEDURE Sort(); VAR i,j : CARDINAL; t : LONGREAL; BEGIN FOR i:=0 TO HIGH(input) DO FOR j:=0 TO HIGH(input) DO IF (i#j) AND (input[i] < input[j]) THEN t := input[i]; input[i] := input[j]; input[j] := t END END END END Sort; VAR result : Summary; size,m,low : CARDINAL; BEGIN size := HIGH(input); Sort();   result[0] := input[0]; result[2] := Median(input,0,size); result[4] := input[size];   m := size / 2; IF (size MOD 2 = 1) THEN low := m ELSE low := m - 1 END; result[1] := Median(input, 0, m); result[3] := Median(input, m+1, size);   RETURN result; END Fivenum;   TYPE A6 = ARRAY[0..5] OF LONGREAL; A11 = ARRAY[0..10] OF LONGREAL; A20 = ARRAY[0..19] OF LONGREAL; VAR a6 : A6; a11 : A11; a20 : A20; BEGIN a11 := A11{15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0}; WriteArray(Fivenum(a11)); WriteLn; WriteLn;   a6 := A6{36.0, 40.0, 7.0, 39.0, 41.0, 15.0}; WriteArray(Fivenum(a6)); WriteLn; WriteLn;   a20 := A20{ 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 }; WriteArray(Fivenum(a20)); WriteLn;   ReadChar END Fivenum.
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)
#Arturo
Arturo
perms: [ "ABCD" "CABD" "ACDB" "DACB" "BCDA" "ACBD" "ADCB" "CDAB" "DABC" "BCAD" "CADB" "CDBA" "CBAD" "ABDC" "ADBC" "BDCA" "DCBA" "BACD" "BADC" "BDAC" "CBDA" "DBCA" "DCAB" ]   allPerms: map permutate split "ABCD" => join   print first difference allPerms perms
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
#C
C
  #include <stdio.h> #include <stdlib.h>   int main(int argc, char *argv[]) { int days[] = {31,29,31,30,31,30,31,31,30,31,30,31}; int m, y, w;   if (argc < 2 || (y = atoi(argv[1])) <= 1752) return 1; days[1] -= (y % 4) || (!(y % 100) && (y % 400)); w = y * 365 + 97 * (y - 1) / 400 + 4;   for(m = 0; m < 12; m++) { w = (w + days[m]) % 7; printf("%d-%02d-%d\n", y, m + 1,days[m] - w); }   return 0; }  
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) .
#C.2B.2B
C++
#include <iostream> #include <cmath> #include <cassert> using namespace std;   /** Calculate determinant of matrix: [a b] [c d] */ inline double Det(double a, double b, double c, double d) { return a*d - b*c; }   /// Calculate intersection of two lines. ///\return true if found, false if not found or error bool LineLineIntersect(double x1, double y1, // Line 1 start double x2, double y2, // Line 1 end double x3, double y3, // Line 2 start double x4, double y4, // Line 2 end double &ixOut, double &iyOut) // Output { double detL1 = Det(x1, y1, x2, y2); double detL2 = Det(x3, y3, x4, y4); double x1mx2 = x1 - x2; double x3mx4 = x3 - x4; double y1my2 = y1 - y2; double y3my4 = y3 - y4;   double denom = Det(x1mx2, y1my2, x3mx4, y3my4); if(denom == 0.0) // Lines don't seem to cross { ixOut = NAN; iyOut = NAN; return false; }   double xnom = Det(detL1, x1mx2, detL2, x3mx4); double ynom = Det(detL1, y1my2, detL2, y3my4); ixOut = xnom / denom; iyOut = ynom / denom; if(!isfinite(ixOut) || !isfinite(iyOut)) // Probably a numerical issue return false;   return true; //All OK }   int main() { // **Simple crossing diagonal lines**   // Line 1 double x1=4.0, y1=0.0; double x2=6.0, y2=10.0;   // Line 2 double x3=0.0, y3=3.0; double x4=10.0, y4=7.0;   double ix = -1.0, iy = -1.0; bool result = LineLineIntersect(x1, y1, x2, y2, x3, y3, x4, y4, ix, iy); cout << "result " << result << "," << ix << "," << iy << endl;   double eps = 1e-6; assert(result == true); assert(fabs(ix - 5.0) < eps); assert(fabs(iy - 5.0) < eps); return 0; }
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].
#C.2B.2B
C++
#include <iostream> #include <sstream>   class Vector3D { public: Vector3D(double x, double y, double z) { this->x = x; this->y = y; this->z = z; }   double dot(const Vector3D& rhs) const { return x * rhs.x + y * rhs.y + z * rhs.z; }   Vector3D operator-(const Vector3D& rhs) const { return Vector3D(x - rhs.x, y - rhs.y, z - rhs.z); }   Vector3D operator*(double rhs) const { return Vector3D(rhs*x, rhs*y, rhs*z); }   friend std::ostream& operator<<(std::ostream&, const Vector3D&);   private: double x, y, z; };   std::ostream & operator<<(std::ostream & os, const Vector3D &f) { std::stringstream ss; ss << "(" << f.x << ", " << f.y << ", " << f.z << ")"; return os << ss.str(); }   Vector3D intersectPoint(Vector3D rayVector, Vector3D rayPoint, Vector3D planeNormal, Vector3D planePoint) { Vector3D diff = rayPoint - planePoint; double prod1 = diff.dot(planeNormal); double prod2 = rayVector.dot(planeNormal); double prod3 = prod1 / prod2; return rayPoint - rayVector * prod3; }   int main() { Vector3D rv = Vector3D(0.0, -1.0, -1.0); Vector3D rp = Vector3D(0.0, 0.0, 10.0); Vector3D pn = Vector3D(0.0, 0.0, 1.0); Vector3D pp = Vector3D(0.0, 0.0, 5.0); Vector3D ip = intersectPoint(rv, rp, pn, pp);   std::cout << "The ray intersects the plane at " << ip << std::endl;   return 0; }
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) The   FizzBuzz   problem was presented as the lowest level of comprehension required to illustrate adequacy. Also see   (a blog)   dont-overthink-fizzbuzz   (a blog)   fizzbuzz-the-programmers-stairway-to-heaven
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO;   procedure Fizzbuzz is begin for I in 1..100 loop if I mod 15 = 0 then Put_Line("FizzBuzz"); elsif I mod 5 = 0 then Put_Line("Buzz"); elsif I mod 3 = 0 then Put_Line("Fizz"); else Put_Line(Integer'Image(I)); end if; end loop; end Fizzbuzz;
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
#COBOL
COBOL
  program-id. five-we. data division. working-storage section. 1 wk binary. 2 int-date pic 9(8). 2 dow pic 9(4). 2 friday pic 9(4) value 5. 2 mo-sub pic 9(4). 2 months-with-5 pic 9(4) value 0. 2 years-no-5 pic 9(4) value 0. 2 5-we-flag pic 9(4) value 0. 88 5-we-true value 1 when false 0. 1 31-day-mos pic 9(14) value 01030507081012. 1 31-day-table redefines 31-day-mos. 2 mo-no occurs 7 pic 99. 1 cal-date. 2 yr pic 9(4). 2 mo pic 9(2). 2 da pic 9(2) value 1. procedure division. perform varying yr from 1900 by 1 until yr > 2100 set 5-we-true to false perform varying mo-sub from 1 by 1 until mo-sub > 7 move mo-no (mo-sub) to mo compute int-date = function integer-of-date (function numval (cal-date)) compute dow = function mod ((int-date - 1) 7) + 1 if dow = friday perform output-date add 1 to months-with-5 set 5-we-true to true end-if end-perform if not 5-we-true add 1 to years-no-5 end-if end-perform perform output-counts stop run .   output-counts. display "Months with 5 weekends: " months-with-5 display "Years without 5 weekends: " years-no-5 .   output-date. display yr "-" mo . end program five-we.  
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
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
ClearAll[FirstSquare] FirstSquare[b_Integer] := Module[{n, alldigits, digs, start}, digs = Range[0, b - 1]; digs[[{2, 1}]] //= Reverse; start = Floor[Sqrt[FromDigits[digs, b]]]; n = start; alldigits = Range[0, b - 1]; While[! ContainsAll[IntegerDigits[n^2, b], alldigits], n++]; {b, n, start, BaseForm[n, b]} ] Scan[Print@*FirstSquare, Range[2, 16]]
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
#Nim
Nim
import algorithm, math, strformat   const Alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"     func toBaseN(num, base: Natural): string = doAssert(base in 2..Alphabet.len, &"base must be in 2..{Alphabet.len}") var num = num while true: result.add(Alphabet[num mod base]) num = num div base if num == 0: break result.reverse()     func countUnique(str: string): int = var charset: set['0'..'Z'] for ch in str: charset.incl(ch) result = charset.card     proc find(base: Natural) = var n = pow(base.toFloat, (base - 1) / 2).int while true: let sq = n * n let sqstr = sq.toBaseN(base) if sqstr.len >= base and countUnique(sqstr) == base: let nstr = n.toBaseN(base) echo &"Base {base:2d}: {nstr:>8s}² = {sqstr:<16s}" break inc n     when isMainModule: for base in 2..16: base.find()
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
#Delphi
Delphi
  program First_class_functions;   {$APPTYPE CONSOLE}   uses System.SysUtils, System.Math;   type TFunctionTuple = record forward, backward: TFunc<Double, Double>; procedure Assign(forward, backward: TFunc<Double, Double>); end;   TFunctionTuples = array of TFunctionTuple;   var cube, croot, fsin, fcos, faSin, faCos: TFunc<Double, Double>; FunctionTuples: TFunctionTuples; ft: TFunctionTuple;   { TFunctionTuple }   procedure TFunctionTuple.Assign(forward, backward: TFunc<Double, Double>); begin self.forward := forward; self.backward := backward; end;   begin cube := function(x: Double): Double begin result := x * x * x; end;   croot := function(x: Double): Double begin result := Power(x, 1 / 3.0); end;   fsin := function(x: Double): Double begin result := Sin(x); end;   fcos := function(x: Double): Double begin result := Cos(x); end;   faSin := function(x: Double): Double begin result := ArcSin(x); end;   faCos := function(x: Double): Double begin result := ArcCos(x); end;   SetLength(FunctionTuples, 3); FunctionTuples[0].Assign(fsin, faSin); FunctionTuples[1].Assign(fcos, faCos); FunctionTuples[2].Assign(cube, croot);   for ft in FunctionTuples do Writeln(ft.backward(ft.forward(0.5)):2:2);   readln; end.
http://rosettacode.org/wiki/Forest_fire
Forest fire
This page uses content from Wikipedia. The original article was at Forest-fire model. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Implement the Drossel and Schwabl definition of the forest-fire model. It is basically a 2D   cellular automaton   where each cell can be in three distinct states (empty, tree and burning) and evolves according to the following rules (as given by Wikipedia) A burning cell turns into an empty cell A tree will burn if at least one neighbor is burning A tree ignites with probability   f   even if no neighbor is burning An empty space fills with a tree with probability   p Neighborhood is the   Moore neighborhood;   boundary conditions are so that on the boundary the cells are always empty ("fixed" boundary condition). At the beginning, populate the lattice with empty and tree cells according to a specific probability (e.g. a cell has the probability 0.5 to be a tree). Then, let the system evolve. Task's requirements do not include graphical display or the ability to change parameters (probabilities   p   and   f )   through a graphical or command line interface. Related tasks   See   Conway's Game of Life   See   Wireworld.
#Java
Java
import java.util.Arrays; import java.util.LinkedList; import java.util.List;   public class Fire { private static final char BURNING = 'w'; //w looks like fire, right? private static final char TREE = 'T'; private static final char EMPTY = '.'; private static final double F = 0.2; private static final double P = 0.4; private static final double TREE_PROB = 0.5;   private static List<String> process(List<String> land){ List<String> newLand = new LinkedList<String>(); for(int i = 0; i < land.size(); i++){ String rowAbove, thisRow = land.get(i), rowBelow; if(i == 0){//first row rowAbove = null; rowBelow = land.get(i + 1); }else if(i == land.size() - 1){//last row rowBelow = null; rowAbove = land.get(i - 1); }else{//middle rowBelow = land.get(i + 1); rowAbove = land.get(i - 1); } newLand.add(processRows(rowAbove, thisRow, rowBelow)); } return newLand; }   private static String processRows(String rowAbove, String thisRow, String rowBelow){ String newRow = ""; for(int i = 0; i < thisRow.length();i++){ switch(thisRow.charAt(i)){ case BURNING: newRow+= EMPTY; break; case EMPTY: newRow+= Math.random() < P ? TREE : EMPTY; break; case TREE: String neighbors = ""; if(i == 0){//first char neighbors+= rowAbove == null ? "" : rowAbove.substring(i, i + 2); neighbors+= thisRow.charAt(i + 1); neighbors+= rowBelow == null ? "" : rowBelow.substring(i, i + 2); if(neighbors.contains(Character.toString(BURNING))){ newRow+= BURNING; break; } }else if(i == thisRow.length() - 1){//last char neighbors+= rowAbove == null ? "" : rowAbove.substring(i - 1, i + 1); neighbors+= thisRow.charAt(i - 1); neighbors+= rowBelow == null ? "" : rowBelow.substring(i - 1, i + 1); if(neighbors.contains(Character.toString(BURNING))){ newRow+= BURNING; break; } }else{//middle neighbors+= rowAbove == null ? "" : rowAbove.substring(i - 1, i + 2); neighbors+= thisRow.charAt(i + 1); neighbors+= thisRow.charAt(i - 1); neighbors+= rowBelow == null ? "" : rowBelow.substring(i - 1, i + 2); if(neighbors.contains(Character.toString(BURNING))){ newRow+= BURNING; break; } } newRow+= Math.random() < F ? BURNING : TREE; } } return newRow; }   public static List<String> populate(int width, int height){ List<String> land = new LinkedList<String>(); for(;height > 0; height--){//height is just a copy anyway StringBuilder line = new StringBuilder(width); for(int i = width; i > 0; i--){ line.append((Math.random() < TREE_PROB) ? TREE : EMPTY); } land.add(line.toString()); } return land; }   //process the land n times public static void processN(List<String> land, int n){ for(int i = 0;i < n; i++){ land = process(land); } }   //process the land n times and print each step along the way public static void processNPrint(List<String> land, int n){ for(int i = 0;i < n; i++){ land = process(land); print(land); } }   //print the land public static void print(List<String> land){ for(String row: land){ System.out.println(row); } System.out.println(); }   public static void main(String[] args){ List<String> land = Arrays.asList(".TTT.T.T.TTTT.T", "T.T.T.TT..T.T..", "TT.TTTT...T.TT.", "TTT..TTTTT.T..T", ".T.TTT....TT.TT", "...T..TTT.TT.T.", ".TT.TT...TT..TT", ".TT.T.T..T.T.T.", "..TTT.TT.T..T..", ".T....T.....TTT", "T..TTT..T..T...", "TTT....TTTTTT.T", "......TwTTT...T", "..T....TTTTTTTT", ".T.T.T....TT..."); print(land); processNPrint(land, 10);   System.out.println("Random land test:");   land = populate(10, 10); print(land); processNPrint(land, 10); } }
http://rosettacode.org/wiki/First_class_environments
First class environments
According to Wikipedia, "In computing, a first-class object ... is an entity that can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable". Often this term is used in the context of "first class functions". In an analogous way, a programming language may support "first class environments". The environment is minimally, the set of variables accessible to a statement being executed. Change the environments and the same statement could produce different results when executed. Often an environment is captured in a closure, which encapsulates a function together with an environment. That environment, however, is not first-class, as it cannot be created, passed etc. independently from the function's code. Therefore, a first class environment is a set of variable bindings which can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable. It is like a closure without code. A statement must be able to be executed within a stored first class environment and act according to the environment variable values stored within. Task Build a dozen environments, and a single piece of code to be run repeatedly in each of these environments. Each environment contains the bindings for two variables:   a value in the Hailstone sequence, and   a count which is incremented until the value drops to 1. The initial hailstone values are 1 through 12, and the count in each environment is zero. When the code runs, it calculates the next hailstone step in the current environment (unless the value is already 1) and counts the steps. Then it prints the current value in a tabular form. When all hailstone values dropped to 1, processing stops, and the total number of hailstone steps for each environment is printed.
#Tcl
Tcl
package require Tcl 8.5   for {set i 1} {$i <= 12} {incr i} { dict set hailenv hail$i [dict create num $i steps 0] } while 1 { set loopagain false foreach k [dict keys $hailenv] { dict with hailenv $k { puts -nonewline [format %4d $num] if {$num == 1} { continue } elseif {$num & 1} { set num [expr {3*$num + 1}] } else { set num [expr {$num / 2}] } set loopagain true incr steps } } puts "" if {!$loopagain} break } puts "Counts..." foreach k [dict keys $hailenv] { dict with hailenv $k { puts -nonewline [format %4d $steps] } } puts ""
http://rosettacode.org/wiki/First_class_environments
First class environments
According to Wikipedia, "In computing, a first-class object ... is an entity that can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable". Often this term is used in the context of "first class functions". In an analogous way, a programming language may support "first class environments". The environment is minimally, the set of variables accessible to a statement being executed. Change the environments and the same statement could produce different results when executed. Often an environment is captured in a closure, which encapsulates a function together with an environment. That environment, however, is not first-class, as it cannot be created, passed etc. independently from the function's code. Therefore, a first class environment is a set of variable bindings which can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable. It is like a closure without code. A statement must be able to be executed within a stored first class environment and act according to the environment variable values stored within. Task Build a dozen environments, and a single piece of code to be run repeatedly in each of these environments. Each environment contains the bindings for two variables:   a value in the Hailstone sequence, and   a count which is incremented until the value drops to 1. The initial hailstone values are 1 through 12, and the count in each environment is zero. When the code runs, it calculates the next hailstone step in the current environment (unless the value is already 1) and counts the steps. Then it prints the current value in a tabular form. When all hailstone values dropped to 1, processing stops, and the total number of hailstone steps for each environment is printed.
#Wren
Wren
import "/fmt" for Fmt   var environment = Fn.new { class E { construct new(value, count) { _value = value _count = count }   value { _value } count { _count }   hailstone() { Fmt.write("$4d", _value) if (_value == 1) return _count = _count + 1 _value = (_value%2 == 0) ? _value/2 : 3*_value + 1 } } return E }   // create and initialize the environments var jobs = 12 var envs = List.filled(jobs, null) for (i in 0...jobs) envs[i] = environment.call().new(i+1, 0) System.print("Sequences:") var done = false while (!done) { for (env in envs) env.hailstone() System.print() done = true for (env in envs) { if (env.value != 1) { done = false break } } } System.print("Counts:") for (env in envs) Fmt.write("$4d", env.count) System.print()
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
#Elixir
Elixir
  defmodule RC do def flatten([]), do: [] def flatten([h|t]), do: flatten(h) ++ flatten(t) def flatten(h), do: [h] end   list = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]   # Our own implementation IO.inspect RC.flatten(list) # Library function IO.inspect List.flatten(list)  
http://rosettacode.org/wiki/Flipping_bits_game
Flipping bits game
The game Given an   N×N   square array of zeroes or ones in an initial configuration,   and a target configuration of zeroes and ones. The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered columns at once   (as one move). In an inversion.   any  1  becomes  0,   and any  0  becomes  1  for that whole row or column. Task Create a program to score for the Flipping bits game. The game should create an original random target configuration and a starting configuration. Ensure that the starting position is never the target position. The target position must be guaranteed as reachable from the starting position.   (One possible way to do this is to generate the start position by legal flips from a random target position.   The flips will always be reversible back to the target from the given start position). The number of moves taken so far should be shown. Show an example of a short game here, on this page, for a   3×3   array of bits.
#Red
Red
  Red [] random/seed now/time/precise ;; start random generator kRows: kCols: 3 ;; define board size, 3x3 upto 9x9 possible ;; create series of 3 empty blocks: loop kRows [ append/only board: [] copy [] ] ;; ( this is actually a bit tricky, normally you'd have to use "copy" [] inside a loop )   kValid: "1A" ;; generate string for input validation "321ABC" loop (kRows - 1 ) [insert kValid (first kValid) + 1 ] loop (kCols - 1 ) [append kValid (last kValid) + 1 ]   repeat row kRows [ loop kCols [ append board/:row -1 + random 2 ] ] ;; fill board with random 0 / 1 ;;-------------------------------------- xorme: func ['val][ set val 1 xor get val ] ;; function: flip the given board position ;;-------------------------------------- flip: func [ what [string!] ] [ ;; flip complete row or column of board row: -48 + to-integer first what ;; convert string to integer row/column index if row <= kRows [ repeat col kCols [ xorme board/:row/:col] return 0 ] repeat row2 kRows [ xorme board/:row2/(row - 16)] ] ;;-------------------------------------- showboard: func [title [string!] b] [ ;; function: show board name + board or target prin [title newline newline" " letter: #"A" ] ;; ( prin doesn't print newline at end ) loop ( kCols - 1) [ prin ["" letter: letter + 1] ] print "" ;; print column letters repeat row kRows [ ;; print one row prin row ;; first print row number repeat col kCols [ prin ["" b/:row/:col ]] print "" ] ]   showboard "Target" target: copy/deep board ;; create target as copy from board and show random kvalid repeat pos 3 [flip copy/part skip kvalid pos 1] ;; now flip board 3 times at random row/column   run: -1 forever [ showboard "Board" board if board = target [ Print ["You solved it in" run + 1 "move(s) !" ] halt ] ;; count last move print [newline "moves:" run: run + 1 ] ;; show moves taken so far until [ find kvalid inp: uppercase ask "Enter Row No or Column Letter to flip ?" ] ;; read valid input character flip inp ] ;; 42 lines :- )  
http://rosettacode.org/wiki/First_power_of_2_that_has_leading_decimal_digits_of_12
First power of 2 that has leading decimal digits of 12
(This task is taken from a   Project Euler   problem.) (All numbers herein are expressed in base ten.) 27   =   128   and   7   is the first power of   2   whose leading decimal digits are   12. The next power of   2   whose leading decimal digits are   12   is   80, 280   =   1208925819614629174706176. Define     p(L,n)     to be the nth-smallest value of   j   such that the base ten representation of   2j   begins with the digits of   L . So p(12, 1) = 7 and p(12, 2) = 80 You are also given that: p(123, 45)   =   12710 Task   find:   p(12, 1)   p(12, 2)   p(123, 45)   p(123, 12345)   p(123, 678910)   display the results here, on this page.
#Ruby
Ruby
def p(l, n) test = 0 logv = Math.log(2.0) / Math.log(10.0) factor = 1 loopv = l while loopv > 10 do factor = factor * 10 loopv = loopv / 10 end while n > 0 do test = test + 1 val = (factor * (10.0 ** ((test * logv).modulo(1.0)))).floor if val == l then n = n - 1 end end return test end   def runTest(l, n) print "P(%d, %d) = %d\n" % [l, n, p(l, n)] end   runTest(12, 1) runTest(12, 2) runTest(123, 45) runTest(123, 12345) runTest(123, 678910)
http://rosettacode.org/wiki/First-class_functions/Use_numbers_analogously
First-class functions/Use numbers analogously
In First-class functions, a language is showing how its manipulation of functions is similar to its manipulation of other types. This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers. Write a program to create an ordered collection of a mixture of literally typed and expressions producing a real number, together with another ordered collection of their multiplicative inverses. Try and use the following pseudo-code to generate the numbers for the ordered collections: x = 2.0 xi = 0.5 y = 4.0 yi = 0.25 z = x + y zi = 1.0 / ( x + y ) Create a function multiplier, that given two numbers as arguments returns a function that when called with one argument, returns the result of multiplying the two arguments to the call to multiplier that created it and the argument in the call: new_function = multiplier(n1,n2) # where new_function(m) returns the result of n1 * n2 * m Applying the multiplier of a number and its inverse from the two ordered collections of numbers in pairs, show that the result in each case is one. Compare and contrast the resultant program with the corresponding entry in First-class functions. They should be close. To paraphrase the task description: Do what was done before, but with numbers rather than functions
#R
R
multiplier <- function(n1,n2) { (function(m){n1*n2*m}) } x = 2.0 xi = 0.5 y = 4.0 yi = 0.25 z = x + y zi = 1.0 / ( x + y ) num = c(x,y,z) inv = c(xi,yi,zi)   multiplier(num,inv)(0.5)   Output [1] 0.5 0.5 0.5  
http://rosettacode.org/wiki/First-class_functions/Use_numbers_analogously
First-class functions/Use numbers analogously
In First-class functions, a language is showing how its manipulation of functions is similar to its manipulation of other types. This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers. Write a program to create an ordered collection of a mixture of literally typed and expressions producing a real number, together with another ordered collection of their multiplicative inverses. Try and use the following pseudo-code to generate the numbers for the ordered collections: x = 2.0 xi = 0.5 y = 4.0 yi = 0.25 z = x + y zi = 1.0 / ( x + y ) Create a function multiplier, that given two numbers as arguments returns a function that when called with one argument, returns the result of multiplying the two arguments to the call to multiplier that created it and the argument in the call: new_function = multiplier(n1,n2) # where new_function(m) returns the result of n1 * n2 * m Applying the multiplier of a number and its inverse from the two ordered collections of numbers in pairs, show that the result in each case is one. Compare and contrast the resultant program with the corresponding entry in First-class functions. They should be close. To paraphrase the task description: Do what was done before, but with numbers rather than functions
#Racket
Racket
  #lang racket   (define x 2.0) (define xi 0.5) (define y 4.0) (define yi 0.25) (define z (+ x y)) (define zi (/ 1.0 (+ x y)))   (define ((multiplier x y) z) (* x y z))   (define numbers (list x y z)) (define inverses (list xi yi zi))   (for/list ([n numbers] [i inverses]) ((multiplier n i) 0.5)) ;; -> '(0.5 0.5 0.5)  
http://rosettacode.org/wiki/Flow-control_structures
Flow-control structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task Document common flow-control structures. One common example of a flow-control structure is the   goto   construct. Note that   Conditional Structures   and   Loop Structures   have their own articles/categories. Related tasks   Conditional Structures   Loop Structures
#REXX
REXX
call routineName /*no arguments passed to routine.*/ call routineName 50 /*one argument (fifty) passed. */ call routineName 50,60 /*two arguments passed. */ call routineName 50, 60 /*(same as above) */ call routineName 50 ,60 /*(same as above) */ call routineName 10*5 , 8**4 - 4 /*(same as above) */ call routineName 50 , , , 70 /*4 args passed, 2nd&3rd omitted.*/ /*omitted args are NOT null. */ call routineName ,,,,,,,,,,,,,,,,800 /*17 args passed, 16 omitted. */ call date /*looks for DATE internally first*/ call 'DATE' /* " " " BIF | externally*/
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
#Ring
Ring
  i = 1 while true see i + nl if i = 10 see "Break!" exit ok i = i + 1 end  
http://rosettacode.org/wiki/Floyd%27s_triangle
Floyd's triangle
Floyd's triangle   lists the natural numbers in a right triangle aligned to the left where the first row is   1     (unity) successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above. The first few lines of a Floyd triangle looks like this: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Task Write a program to generate and display here the first   n   lines of a Floyd triangle. (Use   n=5   and   n=14   rows). Ensure that when displayed in a mono-space font, the numbers line up in vertical columns as shown and that only one space separates numbers of the last row.
#Gambas
Gambas
Public Sub Main() Dim siCount, siNo, siCounter As Short Dim siLine As Short = 1 Dim siInput As Short[] = [5, 14]   For siCount = 0 To siInput.Max Print "Floyd's triangle to " & siInput[siCount] & " lines" Do Inc siNo Inc siCounter Print Format(siNo, "####"); If siLine = siCounter Then Print Inc siLine siCounter = 0 End If If siLine - 1 = siInput[siCount] Then Break Loop siLine = 1 siCounter = 0 siNo = 0 Print Next   End
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)
#PHP
PHP
<?php $graph = array(); for ($i = 0; $i < 10; ++$i) { $graph[] = array(); for ($j = 0; $j < 10; ++$j) $graph[$i][] = $i == $j ? 0 : 9999999; }   for ($i = 1; $i < 10; ++$i) { $graph[0][$i] = $graph[$i][0] = rand(1, 9); }   for ($k = 0; $k < 10; ++$k) { for ($i = 0; $i < 10; ++$i) { for ($j = 0; $j < 10; ++$j) { if ($graph[$i][$j] > $graph[$i][$k] + $graph[$k][$j]) $graph[$i][$j] = $graph[$i][$k] + $graph[$k][$j]; } } }   print_r($graph); ?>
http://rosettacode.org/wiki/Function_definition
Function definition
A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract from showing how functions are created and values returned). Related task   Function prototype
#Toka
Toka
[ ( ab-c ) * ] is multiply
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
#Transd
Transd
multiply: (lambda a Double() b Double() (* 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.)
#Python
Python
>>> dif = lambda s: [x-s[i] for i,x in enumerate(s[1:])] >>> # or, dif = lambda s: [x-y for x,y in zip(s[1:],s)] >>> difn = lambda s, n: difn(dif(s), n-1) if n else s   >>> s = [90, 47, 58, 29, 22, 32, 55, 5, 55, 73] >>> difn(s, 0) [90, 47, 58, 29, 22, 32, 55, 5, 55, 73] >>> difn(s, 1) [-43, 11, -29, -7, 10, 23, -50, 50, 18] >>> difn(s, 2) [54, -40, 22, 17, 13, -73, 100, -32]   >>> from pprint import pprint >>> pprint( [difn(s, i) for i in xrange(10)] ) [[90, 47, 58, 29, 22, 32, 55, 5, 55, 73], [-43, 11, -29, -7, 10, 23, -50, 50, 18], [54, -40, 22, 17, 13, -73, 100, -32], [-94, 62, -5, -4, -86, 173, -132], [156, -67, 1, -82, 259, -305], [-223, 68, -83, 341, -564], [291, -151, 424, -905], [-442, 575, -1329], [1017, -1904], [-2921]]
http://rosettacode.org/wiki/Formatted_numeric_output
Formatted numeric output
Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
#VBScript
VBScript
  a = 1234.5678   ' Round to three decimal places. Groups by default. Output = "1,234.568". WScript.Echo FormatNumber(a, 3)   ' Truncate to three decimal places. Output = "1234.567". WScript.Echo Left(a, InStr(a, ".") + 3)   ' Round to a whole number. Grouping disabled. Output = "1235". WScript.Echo FormatNumber(a, 0, , , False)   ' Use integer portion only and pad with zeroes to fill 8 chars. Output = "00001234". WScript.Echo Right("00000000" & Int(a), 8)  
http://rosettacode.org/wiki/Formatted_numeric_output
Formatted numeric output
Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
#Vedit_macro_language
Vedit macro language
#1 = 7125 Num_Ins(#1, FILL+COUNT, 9) Char(-3) Ins_Char('.')
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).
#REXX
REXX
/*REXX program displays (all) the sums of a full 4─bit adder (with carry). */ call hdr1; call hdr2 /*note the order of headers & trailers.*/ /* [↓] traipse thru all possibilities.*/ do j=0 for 16 do m=0 for 4; a.m= bit(j, m) end /*m*/ do k=0 for 16 do m=0 for 4; b.m= bit(k, m) end /*m*/ sc= 4bitAdder(a., b.) z= a.3 a.2 a.1 a.0 '~+~' b.3 b.2 b.1 b.0 "~=~" sc ',' s.3 s.2 s.1 s.0 say translate( space(z, 0), , '~') /*translate tildes (~) to blanks in Z. */ end /*k*/ end /*j*/   call hdr2; call hdr1 /*display two trailers (note the order)*/ exit 0 /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ bit: procedure; parse arg x,y; return substr( reverse( x2b( d2x(x) ) ), y+1, 1) halfAdder: procedure expose c; parse arg x,y; c= x & y; return x && y hdr1: say 'aaaa + bbbb = c, sum [c=carry]'; return hdr2: say '════ ════ ══════'  ; return /*──────────────────────────────────────────────────────────────────────────────────────*/ fullAdder: procedure expose c; parse arg x,y,fc #1= halfAdder(fc, x); c1= c #2= halfAdder(#1, y); c= c | c1; return #2 /*──────────────────────────────────────────────────────────────────────────────────────*/ 4bitAdder: procedure expose s. a. b.; carry.= 0 do j=0 for 4; n= j - 1 s.j= fullAdder(a.j, b.j, carry.n); carry.j= c end /*j*/; return c
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.
#Nim
Nim
import algorithm   type FiveNum = array[5, float]   template isOdd(n: SomeInteger): bool = (n and 1) != 0   func median(x: openArray[float]; startIndex, endIndex: Natural): float = let size = endIndex - startIndex + 1 assert(size > 0, "array slice cannot be empty") let m = startIndex + size div 2 result = if size.isOdd: x[m] else: (x[m-1] + x[m]) / 2   func fivenum(x: openArray[float]): FiveNum = let x = sorted(x) let m = x.len div 2 let lowerEnd = if x.len.isOdd: m else: m - 1 result[0] = x[0] result[1] = median(x, 0, lowerEnd) result[2] = median(x, 0, x.high) result[3] = median(x, m, x.high) result[4] = x[^1]   const Lists = [@[15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0], @[36.0, 40.0, 7.0, 39.0, 41.0, 15.0], @[0.14082834, 0.09748790, 1.73131507, 0.87636009, -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 list in Lists: echo "" echo list echo " → ", list.fivenum
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.
#Perl
Perl
use POSIX qw(ceil floor);   sub fivenum { my(@array) = @_; my $n = scalar @array; die "No values were entered into fivenum!" if $n == 0; my @x = sort {$a <=> $b} @array; my $n4 = floor(($n+3)/2)/2; my @d = (1, $n4, ($n +1)/2, $n+1-$n4, $n); my @sum_array; for my $e (0..4) { my $floor = floor($d[$e]-1); my $ceil = ceil($d[$e]-1); push @sum_array, (0.5 * ($x[$floor] + $x[$ceil])); } return @sum_array; }   my @x = (15, 6, 42, 41, 7, 36, 49, 40, 39, 47, 43); my @tukey = fivenum(\@x); say join (',', @tukey); #---------- @x = (36, 40, 7, 39, 41, 15), @tukey = fivenum(\@x); say join (',', @tukey); #---------- @x = (0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578); @tukey = fivenum(\@x); say join (',', @tukey);
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)
#AutoHotkey
AutoHotkey
IncompleteList := "ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB"   CompleteList := Perm( "ABCD" ) Missing := ""   Loop, Parse, CompleteList, `n, `r If !InStr( IncompleteList , A_LoopField ) Missing .= "`n" A_LoopField   MsgBox Missing Permutation(s):%Missing%   ;-------------------------------------------------   ; Shortened version of [VxE]'s permutation function ; http://www.autohotkey.com/forum/post-322251.html#322251 Perm( s , dL="" , t="" , p="") { StringSplit, m, s, % d := SubStr(dL,1,1) , %t% IfEqual, m0, 1, return m1 d p Loop %m0% { r := m1 Loop % m0-2 x := A_Index + 1, r .= d m%x% L .= Perm(r, d, t, m%m0% d p)"`n" , mx := m1 Loop % m0-1 x := A_Index + 1, m%A_Index% := m%x% m%m0% := mx } return substr(L, 1, -1) }
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
#C.23
C#
using System;   namespace LastSundayOfEachMonth { class Program { static void Main() { Console.Write("Year to calculate: ");   string strYear = Console.ReadLine(); int year = Convert.ToInt32(strYear);   DateTime date; for (int i = 1; i <= 12; i++) { date = new DateTime(year, i, DateTime.DaysInMonth(year, i), System.Globalization.CultureInfo.CurrentCulture.Calendar); /* Modification by Albert Zakhia on 2021-16-02 The below code is very slow due to the loop, we will go twice as fast while (date.DayOfWeek != DayOfWeek.Sunday) { date = date.AddDays(-1); } */ // The updated code int daysOffset = date.DayOfWeek - dayOfWeek; // take the offset to subtract directly instead of looping if (daysOffset < 0) daysOffset += 7; // if the code is negative, we need to normalize them date = date.AddDays(-daysOffset ); // now just add the days offset Console.WriteLine(date.ToString("yyyy-MM-dd")); } } } }  
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) .
#Clojure
Clojure
;; Point is [x y] tuple (defn compute-line [pt1 pt2] (let [[x1 y1] pt1 [x2 y2] pt2 m (/ (- y2 y1) (- x2 x1))] {:slope m  :offset (- y1 (* m x1))}))   (defn intercept [line1 line2] (let [x (/ (- (:offset line1) (:offset line2)) (- (:slope line2) (:slope line1)))] {:x x  :y (+ (* (:slope line1) x) (:offset line1))}))
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) .
#Common_Lisp
Common Lisp
  ;; Point is [x y] tuple (defun point-of-intersection (x1 y1 x2 y2 x3 y3 x4 y4) "Find the point of intersection of the lines defined by the points (x1 y1) (x2 y2) and (x3 y3) (x4 y4)" (let* ((dx1 (- x2 x1)) (dx2 (- x4 x3)) (dy1 (- y2 y1)) (dy2 (- y4 y3)) (den (- (* dy1 dx2) (* dy2 dx1))) ) (unless (zerop den) (list (/ (+ (* (- y3 y1) dx1 dx2) (* x1 dy1 dx2) (* -1 x3 dy2 dx1)) den) (/ (+ (* (+ x3 x1) dy1 dy2) (* -1 y1 dx1 dy2) (* y3 dx2 dy1)) den) ))))  
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].
#D
D
import std.stdio;   struct Vector3D { private real x; private real y; private real z;   this(real x, real y, real z) { this.x = x; this.y = y; this.z = z; }   auto opBinary(string op)(Vector3D rhs) const { static if (op == "+" || op == "-") { mixin("return Vector3D(x" ~ op ~ "rhs.x, y" ~ op ~ "rhs.y, z" ~ op ~ "rhs.z);"); } }   auto opBinary(string op : "*")(real s) const { return Vector3D(s*x, s*y, s*z); }   auto dot(Vector3D rhs) const { return x*rhs.x + y*rhs.y + z*rhs.z; }   void toString(scope void delegate(const(char)[]) sink) const { import std.format;   sink("("); formattedWrite!"%f"(sink, x); sink(","); formattedWrite!"%f"(sink, y); sink(","); formattedWrite!"%f"(sink, z); sink(")"); } }   auto intersectPoint(Vector3D rayVector, Vector3D rayPoint, Vector3D planeNormal, Vector3D planePoint) { auto diff = rayPoint - planePoint; auto prod1 = diff.dot(planeNormal); auto prod2 = rayVector.dot(planeNormal); auto prod3 = prod1 / prod2; return rayPoint - rayVector * prod3; }   void main() { auto rv = Vector3D(0.0, -1.0, -1.0); auto rp = Vector3D(0.0, 0.0, 10.0); auto pn = Vector3D(0.0, 0.0, 1.0); auto pp = Vector3D(0.0, 0.0, 5.0); auto ip = intersectPoint(rv, rp, pn, pp); writeln("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
#ALGOL_68
ALGOL 68
main:( FOR i TO 100 DO printf(($gl$, IF i %* 15 = 0 THEN "FizzBuzz" ELIF i %* 3 = 0 THEN "Fizz" ELIF i %* 5 = 0 THEN "Buzz" ELSE i FI )) OD )
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
#CoffeeScript
CoffeeScript
  startsOnFriday = (month, year) -> # 0 is Sunday, 1 is Monday, ... 5 is Friday, 6 is Saturday new Date(year, month, 1).getDay() == 5   has31Days = (month, year) -> new Date(year, month, 31).getDate() == 31   checkMonths = (year) -> month = undefined count = 0 month = 0 while month < 12 if startsOnFriday(month, year) and has31Days(month, year) count += 1 console.log year + ' ' + month + '' month += 1 count   fiveWeekends = -> startYear = 1900 endYear = 2100 year = undefined monthTotal = 0 yearsWithoutFiveWeekends = [] total = 0 year = startYear while year <= endYear monthTotal = checkMonths(year) total += monthTotal # extra credit if monthTotal == 0 yearsWithoutFiveWeekends.push year year += 1 console.log 'Total number of months: ' + total + '' console.log '' console.log yearsWithoutFiveWeekends + '' console.log 'Years with no five-weekend months: ' + yearsWithoutFiveWeekends.length + '' return   fiveWeekends()    
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
#Pascal
Pascal
program project1; //Find the smallest number n to base b, so that n*n includes all //digits of base b {$IFDEF FPC}{$MODE DELPHI}{$ENDIF} uses sysutils; const charSet : array[0..36] of char ='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'; type tNumtoBase = record ntb_dgt : array[0..31-4] of byte; ntb_cnt, ntb_bas : Word; end; var Num, sqr2B, deltaNum : tNumtoBase;   function Minimal_n(base:NativeUint):Uint64; //' 1023456789ABCDEFGHIJ...' var i : NativeUint; Begin result := base; // aka '10' IF base > 2 then For i := 2 to base-1 do result := result*base+i; result := trunc(sqrt(result)+0.99999); end;   procedure Conv2num(var num:tNumtoBase;n:Uint64;base:NativeUint); var quot :UInt64; i :NativeUint; Begin i := 0; repeat quot := n div base; Num.ntb_dgt[i] := n-quot*base; n := quot; inc(i); until n = 0; Num.ntb_cnt := i; Num.ntb_bas := base; //clear upper digits For i := i to high(tNumtoBase.ntb_dgt) do Num.ntb_dgt[i] := 0; end;   procedure OutNum(const num:tNumtoBase); var i : NativeInt; Begin with num do Begin For i := 17-ntb_cnt-1 downto 0 do write(' '); For i := ntb_cnt-1 downto 0 do write(charSet[ntb_dgt[i]]); end; end;   procedure IncNumBig(var add1:tNumtoBase;n:NativeUInt); //prerequisites //bases are the same,delta : NativeUint var i,s,b,carry : NativeInt; Begin b := add1.ntb_bas; i := 0; carry := 0; while n > 0 do Begin s := add1.ntb_dgt[i]+carry+ n MOD b; carry := Ord(s>=b); s := s- (-carry AND b); add1.ntb_dgt[i] := s; n := n div b; inc(i); end;   while carry <> 0 do Begin s := add1.ntb_dgt[i]+carry; carry := Ord(s>=b); s := s- (-carry AND b); add1.ntb_dgt[i] := s; inc(i); end;   IF add1.ntb_cnt < i then add1.ntb_cnt := i; end;   procedure IncNum(var add1:tNumtoBase;carry:NativeInt); //prerequisites: bases are the same, carry==delta < base var i,s,b : NativeInt; Begin b := add1.ntb_bas; i := 0; while carry <> 0 do Begin s := add1.ntb_dgt[i]+carry; carry := Ord(s>=b); s := s- (-carry AND b); add1.ntb_dgt[i] := s; inc(i); end; IF add1.ntb_cnt < i then add1.ntb_cnt := i; end;   procedure AddNum(var add1,add2:tNumtoBase); //prerequisites //bases are the same,add1>add2, add1 <= add1+add2; var i,carry,s,b : NativeInt; Begin b := add1.ntb_bas; carry := 0; For i := 0 to add2.ntb_cnt-1 do begin s := add1.ntb_dgt[i]+add2.ntb_dgt[i]+carry; carry := Ord(s>=b); s := s- (-carry AND b); add1.ntb_dgt[i] := s; end;   i := add2.ntb_cnt; while carry = 1 do Begin s := add1.ntb_dgt[i]+carry; carry := Ord(s>=b); // remove of if s>b then by bit-twiddling s := s- (-carry AND b); add1.ntb_dgt[i] := s; inc(i); end;   IF add1.ntb_cnt < i then add1.ntb_cnt := i; end;   procedure Test(base:NativeInt); var n : Uint64; i,j,TestSet : NativeInt; Begin write(base:5); n := Minimal_n(base); Conv2num(sqr2B,n*n,base); Conv2num(Num,n,base); deltaNum := num; AddNum(deltaNum,deltaNum); IncNum(deltaNum,1);   i := 0; repeat //count used digits TestSet := 0; For j := sqr2B.ntb_cnt-1 downto 0 do TestSet := TestSet OR (1 shl sqr2B.ntb_dgt[j]); inc(TestSet); IF (1 shl base)=TestSet then BREAK; //next square number AddNum(sqr2B,deltaNum); IncNum(deltaNum,2); inc(i); until false; IncNumBig(num,i); OutNum(Num); OutNum(sqr2B); Writeln(i:14); end;   var T0: TDateTime; base :nativeInt; begin T0 := now; writeln('base n square(n) Testcnt'); For base := 2 to 16 do Test(base); writeln((now-T0)*86400:10:3); {$IFDEF WINDOWS}readln;{$ENDIF} 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
#Dyalect
Dyalect
func apply(fun, x) { y => fun(x, y) }   func sum(x, y) { x + y }   let sum2 = apply(sum, 2)
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
#D.C3.A9j.C3.A0_Vu
Déjà Vu
negate: - 0   set :A [ @++ $ @negate @-- ]   set :B [ @-- $ @++ @negate ]   test n: for i range 0 -- len A: if /= n call compose @B! i @A! i n: return false true   test to-num !prompt "Enter a number: " if: !print "f^-1(f(x)) = x" else: !print "Something went wrong."  
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.
#JavaScript
JavaScript
"use strict"   const _ = require('lodash');   const WIDTH_ARGUMENT_POSITION = 2; const HEIGHT_ARGUMENT_POSITION = 3; const TREE_PROBABILITY = 0.5; const NEW_TREE_PROBABILITY = 0.01; const BURN_PROBABILITY = 0.0001; const CONSOLE_RED = '\x1b[31m'; const CONSOLE_GREEN = '\x1b[32m'; const CONSOLE_COLOR_CLOSE = '\x1b[91m'; const CONSOLE_CLEAR = '\u001B[2J\u001B[0;0f'; const NEIGHBOURS = [ [-1, -1], [-1, 0], [-1, 1], [ 0, -1], [ 0, 1], [ 1, -1], [ 1, 0], [ 1, 1] ]; const PRINT_DECODE = { ' ': ' ', 'T': `${CONSOLE_GREEN}T${CONSOLE_COLOR_CLOSE}`, 'B': `${CONSOLE_RED}T${CONSOLE_COLOR_CLOSE}`, }; const CONDITIONS = { 'T': (forest, y, x) => Math.random() < BURN_PROBABILITY || burningNeighbour(forest, y, x) ? 'B' : 'T', ' ': () => Math.random() < NEW_TREE_PROBABILITY ? 'T' : ' ', 'B': () => ' ' };   const WIDTH = process.argv[WIDTH_ARGUMENT_POSITION] || 20; const HEIGHT = process.argv[HEIGHT_ARGUMENT_POSITION] || 10;   const update = forest => { return _.map(forest, (c, ci) => { return _.map(c, (r, ri) => { return CONDITIONS[r](forest, ci, ri); }); }); }   const printForest = forest => { process.stdout.write(CONSOLE_CLEAR); _.each(forest, c => { _.each(c, r => { process.stdout.write(PRINT_DECODE[r]); }); process.stdout.write('\n'); }) }   const burningNeighbour = (forest, y, x) => { return _(NEIGHBOURS) .map(n => _.isUndefined(forest[y + n[0]]) ? null : forest[y + n[0]][x + n[1]]) .any(_.partial(_.isEqual, 'B')); };   let forest = _.times(HEIGHT, () => _.times(WIDTH, () => Math.random() < TREE_PROBABILITY ? 'T' : ' '));   setInterval(() => { forest = update(forest); printForest(forest) }, 20);    
http://rosettacode.org/wiki/First_class_environments
First class environments
According to Wikipedia, "In computing, a first-class object ... is an entity that can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable". Often this term is used in the context of "first class functions". In an analogous way, a programming language may support "first class environments". The environment is minimally, the set of variables accessible to a statement being executed. Change the environments and the same statement could produce different results when executed. Often an environment is captured in a closure, which encapsulates a function together with an environment. That environment, however, is not first-class, as it cannot be created, passed etc. independently from the function's code. Therefore, a first class environment is a set of variable bindings which can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable. It is like a closure without code. A statement must be able to be executed within a stored first class environment and act according to the environment variable values stored within. Task Build a dozen environments, and a single piece of code to be run repeatedly in each of these environments. Each environment contains the bindings for two variables:   a value in the Hailstone sequence, and   a count which is incremented until the value drops to 1. The initial hailstone values are 1 through 12, and the count in each environment is zero. When the code runs, it calculates the next hailstone step in the current environment (unless the value is already 1) and counts the steps. Then it prints the current value in a tabular form. When all hailstone values dropped to 1, processing stops, and the total number of hailstone steps for each environment is printed.
#zkl
zkl
class Env{ var n,cnt=0; fcn init(_n){n=_n; returnClass(self.f)} fcn f{ if(n!=1){ cnt += 1; if(n.isEven) n=n/2; else n=n*3+1; } n } }
http://rosettacode.org/wiki/Flatten_a_list
Flatten a list
Task Write a function to flatten the nesting in an arbitrary list of values. Your program should work on the equivalent of this list: [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []] Where the correct result would be the list: [1, 2, 3, 4, 5, 6, 7, 8] Related task   Tree traversal
#Elm
Elm
  import Graphics.Element exposing (show)   type Tree a = Leaf a | Node (List (Tree a))   flatten : Tree a -> List a flatten tree = case tree of Leaf a -> [a] Node list -> List.concatMap flatten list   -- [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []] tree : Tree Int tree = Node [ Node [Leaf 1] , Leaf 2 , Node [Node [Leaf 3, Leaf 4], Leaf 5] , Node [Node [Node []]] , Node [Node [Node [Leaf 6]]] , Leaf 7 , Leaf 8 , Node [] ]   main = show (flatten tree)  
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.
#REXX
REXX
/*REXX program presents a "flipping bit" puzzle. The user can solve via it via C.L. */ parse arg N u seed . /*get optional arguments from the C.L. */ if N=='' | N=="," then N=3 /*Size given? Then use default of 3.*/ if u=='' | u=="," then u=N /*the number of bits initialized to ON.*/ if datatype(seed, 'W') then call random ,,seed /*is there a seed (for repeatability?) */ col@= 'a b c d e f g h i j k l m n o p q r s t u v w x y z' /*literal for column id.*/ cols=space(col@, 0); upper cols /*letters to be used for the columns. */ @.=0;  !.=0 /*set both arrays to "off" characters.*/ tries=0 /*number of player's attempts (so far).*/ do while show(0) < u /* [↓] turn "on" U number of bits.*/ r=random(1, N); c=random(1, N) /*get a random row and column. */ @.r.c=1  ;  !.r.c=1 /*set (both) row and column to ON. */ end /*while*/ /* [↑] keep going 'til U bits set.*/ oz=z /*save the original array string. */ call show 1, ' ◄═══target═══╣', , 1 /*display the target for user to attain*/ do random(1,2); call flip 'R',random(1,N) /*flip a row of bits. */ call flip 'C',random(1,N) /* " " column " " */ end /*random*/ /* [↑] just perform 1 or 2 times. */ if z==oz then call flip 'R', random(1, N) /*ensure it's not target we're flipping*/ do until z==oz; call prompt /*prompt until they get it right. */ call flip left(?, 1), substr(?, 2) /*flip a user selected row or column. */ call show 0 /*get image (Z) of the updated array. */ end /*until*/ call show 1, ' ◄───your array' /*display the array to the terminal. */ say '─────────Congrats! You did it in' tries "tries." exit tries /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ halt: say 'program was halted by user.'; exit /*the REXX program was halted by user. */ hdr: aaa=arg(1); if oo==1 then aaa=translate(aaa, "╔═║", '┌─│'); say aaa; return isInt: return datatype( arg(1), 'W') /*returns 1 if arg is an integer.*/ isLet: return datatype( arg(1), 'M') /*returns 1 if arg is a letter. */ terr: if ok then say '───────── ***error***: illegal' arg(1); ok=0; return /*──────────────────────────────────────────────────────────────────────────────────────*/ flip: arg x,#; do c=1 for N while x=='R'; @.#.c = \@.#.c; end /*c*/ do r=1 for N while x=='C'; @.r.# = \@.r.#; end /*r*/; return /*──────────────────────────────────────────────────────────────────────────────────────*/ prompt: if tries\==0 then say '─────────bit array after play: ' tries signal on halt /*another method for the player to quit*/  !='─────────Please enter a row number or a column letter, or Quit:' call show 1, ' ◄───your array' /*display the array to the terminal. */ do forever until ok; ok=1; say; say !; pull ? _ . 1 aa if abbrev('QUIT', ?, 1) then do; say '─────────quitting···'; exit 0; end if ?=='' then do; call show 1," ◄═══target═══╣",.,1; ok=0 call show 1," ◄───your array" end /* [↑] reshow targ*/ if _ \== '' then call terr 'too many args entered:' aa if \isInt(?) & \isLet(?) then call terr 'row/column: '  ? if isLet(?) then a=pos(?, cols) if isLet(?) & (a<1 | a>N | length(?)>1) then call terr 'column: '  ? if isLet(?) then ?='C'pos(?, cols) if isInt(?) & (?<1 | ?>N) then call terr 'row: '  ? if isInt(?) then ?='R' || (?/1) /*normalize number*/ end /*forever*/ /*end of da checks*/ tries= tries + 1 /*bump da counter.*/ return ? /*return response.*/ /*──────────────────────────────────────────────────────────────────────────────────────*/ show: $=0; _=; parse arg tell,tx,o,oo /*$≡num of ON bits*/ if tell then do; say; say ' ' subword(col@, 1, N) " column letter" call hdr 'row ┌'copies('─', N+N+1) /*prepend col hdrs*/ end /* [↑] grid hdrs.*/ z= /* [↓] build grid.*/ do r=1 for N /*show grid rows.*/ do c=1 for N; if o==. then do; z=z || !.r.c; _=_ !.r.c; $=$ + !.r.c; end else do; z=z || @.r.c; _=_ @.r.c; $=$ + @.r.c; end end /*c*/ /*··· and sum ONs.*/ if tx\=='' then tar.r=_ tx /*build da target?*/ if tell then call hdr right(r, 2) ' │'_ tx; _= /*show the grid? */ end /*r*/ /*show a grid row.*/ if tell then say; return $ /*show blank line?*/
http://rosettacode.org/wiki/First_power_of_2_that_has_leading_decimal_digits_of_12
First power of 2 that has leading decimal digits of 12
(This task is taken from a   Project Euler   problem.) (All numbers herein are expressed in base ten.) 27   =   128   and   7   is the first power of   2   whose leading decimal digits are   12. The next power of   2   whose leading decimal digits are   12   is   80, 280   =   1208925819614629174706176. Define     p(L,n)     to be the nth-smallest value of   j   such that the base ten representation of   2j   begins with the digits of   L . So p(12, 1) = 7 and p(12, 2) = 80 You are also given that: p(123, 45)   =   12710 Task   find:   p(12, 1)   p(12, 2)   p(123, 45)   p(123, 12345)   p(123, 678910)   display the results here, on this page.
#Rust
Rust
fn power_of_two(l: isize, n: isize) -> isize { let mut test: isize = 0; let log: f64 = 2.0_f64.ln() / 10.0_f64.ln(); let mut factor: isize = 1; let mut looop = l; let mut nn = n; while looop > 10 { factor *= 10; looop /= 10; }   while nn > 0 { test = test + 1; let val: isize = (factor as f64 * 10.0_f64.powf(test as f64 * log % 1.0)) as isize;   if val == l { nn = nn - 1; } }   test }   fn run_test(l: isize, n: isize) { println!("p({}, {}) = {}", l, n, power_of_two(l, n)); }   fn main() { run_test(12, 1); run_test(12, 2); run_test(123, 45); run_test(123, 12345); run_test(123, 678910); }  
http://rosettacode.org/wiki/First_power_of_2_that_has_leading_decimal_digits_of_12
First power of 2 that has leading decimal digits of 12
(This task is taken from a   Project Euler   problem.) (All numbers herein are expressed in base ten.) 27   =   128   and   7   is the first power of   2   whose leading decimal digits are   12. The next power of   2   whose leading decimal digits are   12   is   80, 280   =   1208925819614629174706176. Define     p(L,n)     to be the nth-smallest value of   j   such that the base ten representation of   2j   begins with the digits of   L . So p(12, 1) = 7 and p(12, 2) = 80 You are also given that: p(123, 45)   =   12710 Task   find:   p(12, 1)   p(12, 2)   p(123, 45)   p(123, 12345)   p(123, 678910)   display the results here, on this page.
#Scala
Scala
object FirstPowerOfTwo { def p(l: Int, n: Int): Int = { var n2 = n var test = 0 val log = math.log(2) / math.log(10) var factor = 1 var loop = l while (loop > 10) { factor *= 10 loop /= 10 } while (n2 > 0) { test += 1 val value = (factor * math.pow(10, test * log % 1)).asInstanceOf[Int] if (value == l) { n2 -= 1 } } test }   def runTest(l: Int, n: Int): Unit = { printf("p(%d, %d) = %,d%n", l, n, p(l, n)) }   def main(args: Array[String]): Unit = { runTest(12, 1) runTest(12, 2) runTest(123, 45) runTest(123, 12345) runTest(123, 678910) } }
http://rosettacode.org/wiki/First-class_functions/Use_numbers_analogously
First-class functions/Use numbers analogously
In First-class functions, a language is showing how its manipulation of functions is similar to its manipulation of other types. This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers. Write a program to create an ordered collection of a mixture of literally typed and expressions producing a real number, together with another ordered collection of their multiplicative inverses. Try and use the following pseudo-code to generate the numbers for the ordered collections: x = 2.0 xi = 0.5 y = 4.0 yi = 0.25 z = x + y zi = 1.0 / ( x + y ) Create a function multiplier, that given two numbers as arguments returns a function that when called with one argument, returns the result of multiplying the two arguments to the call to multiplier that created it and the argument in the call: new_function = multiplier(n1,n2) # where new_function(m) returns the result of n1 * n2 * m Applying the multiplier of a number and its inverse from the two ordered collections of numbers in pairs, show that the result in each case is one. Compare and contrast the resultant program with the corresponding entry in First-class functions. They should be close. To paraphrase the task description: Do what was done before, but with numbers rather than functions
#Raku
Raku
sub multiplied ($g, $f) { return { $g * $f * $^x } }   my $x = 2.0; my $xi = 0.5; my $y = 4.0; my $yi = 0.25; my $z = $x + $y; my $zi = 1.0 / ( $x + $y );   my @numbers = $x, $y, $z; my @inverses = $xi, $yi, $zi;   for flat @numbers Z @inverses { say multiplied($^g, $^f)(.5) }
http://rosettacode.org/wiki/First-class_functions/Use_numbers_analogously
First-class functions/Use numbers analogously
In First-class functions, a language is showing how its manipulation of functions is similar to its manipulation of other types. This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers. Write a program to create an ordered collection of a mixture of literally typed and expressions producing a real number, together with another ordered collection of their multiplicative inverses. Try and use the following pseudo-code to generate the numbers for the ordered collections: x = 2.0 xi = 0.5 y = 4.0 yi = 0.25 z = x + y zi = 1.0 / ( x + y ) Create a function multiplier, that given two numbers as arguments returns a function that when called with one argument, returns the result of multiplying the two arguments to the call to multiplier that created it and the argument in the call: new_function = multiplier(n1,n2) # where new_function(m) returns the result of n1 * n2 * m Applying the multiplier of a number and its inverse from the two ordered collections of numbers in pairs, show that the result in each case is one. Compare and contrast the resultant program with the corresponding entry in First-class functions. They should be close. To paraphrase the task description: Do what was done before, but with numbers rather than functions
#REXX
REXX
/*REXX program to use a first-class function to use numbers analogously. */ nums= 2.0 4.0 6.0 /*various numbers, can have fractions.*/ invs= 1/2.0 1/4.0 1/6.0 /*inverses of the above (real) numbers.*/ m= 0.5 /*multiplier when invoking new function*/ do j=1 for words(nums); num= word(nums, j); inv= word(invs, j) nf= multiplier(num, inv); interpret call nf m /*sets the var RESULT.*/ say 'number=' @(num) 'inverse=' @(inv) 'm=' @(m) 'result=' @(result) end /*j*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ @: return left( arg(1) / 1, 15) /*format the number, left justified. */ multiplier: procedure expose n1n2; parse arg n1,n2; n1n2= n1 * n2; return 'a_new_func' a_new_func: return n1n2 * arg(1)
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
#Ruby
Ruby
begin # some code that may raise an exception rescue ExceptionClassA => a # handle code rescue ExceptionClassB, ExceptionClassC => b_or_c # handle ... rescue # handle all other exceptions else # when no exception occurred, execute this code ensure # execute this code always 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
#SAS
SAS
/* GOTO: as in other languages STOP: to stop current data step */ data _null_; n=1; p=1; L1: put n p; n=n+1; if n<=p then goto L1; p=p+1; n=1; if p>10 then stop; goto L1;   run;   /* LINK: equivalent of GOSUB in BASIC RETURN: after a LINK, or to return to the beginning of data step */ data _null_; input a b; link gcd; put a b gcd; return;   gcd: _a=a; _b=b; do while(_b>0); _r=mod(_a,_b); _a=_b; _b=_r; end; gcd=_a; return;   cards; 2 15 533 221 8 44 ; run;
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.
#Go
Go
package main   import "fmt"   func main() { floyd(5) floyd(14) }   func floyd(n int) { fmt.Printf("Floyd %d:\n", n) lowerLeftCorner := n*(n-1)/2 + 1 lastInColumn := lowerLeftCorner lastInRow := 1 for i, row := 1, 1; row <= n; i++ { w := len(fmt.Sprint(lastInColumn)) if i < lastInRow { fmt.Printf("%*d ", w, i) lastInColumn++ } else { fmt.Printf("%*d\n", w, i) row++ lastInRow += row lastInColumn = lowerLeftCorner } } }
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)
#Prolog
Prolog
:- use_module(library(clpfd)).   path(List, To, From, [From], W) :- select([To,From,W],List,_). path(List, To, From, [Link|R], W) :- select([To,Link,W1],List,Rest), W #= W1 + W2, path(Rest, Link, From, R, W2).   find_path(Din, From, To, [From|Pout], Wout) :- between(1, 4, From), between(1, 4, To), dif(From, To), findall([W,P], ( path(Din, From, To, P, W), all_distinct(P) ), Paths), sort(Paths, [[Wout,Pout]|_]).     print_all_paths :- D = [[1, 3, -2], [2, 3, 3], [2, 1, 4], [3, 4, 2], [4, 2, -1]], format('Pair\t Dist\tPath~n'), forall( find_path(D, From, To, Path, Weight),( atomic_list_concat(Path, ' -> ', PPath), format('~p -> ~p\t ~p\t~w~n', [From, To, Weight, PPath]))).
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
#TXR
TXR
@(define multiply (a b out)) @(bind out @(* a b)) @(end) @(multiply 3 4 result)
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
#uBasic.2F4tH_2
uBasic/4tH
PRINT FUNC (_Multiply (2,3)) END   _Multiply PARAM (2) RETURN (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.)
#Quackery
Quackery
[ times [ [] swap behead swap witheach [ tuck dip [ - join ] ] drop ] ] is f-diff ( [ n --> [ )   ' [ 90 47 58 29 22 32 55 5 55 73 ]   dup size times [ dup i^ dup echo say ": " f-diff echo cr ] drop
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.)
#R
R
forwarddif <- function(a, n) { if ( n == 1 ) a[2:length(a)] - a[1:length(a)-1] else { r <- forwarddif(a, 1) forwarddif(r, n-1) } }   fdiff <- function(a, n) { r <- a for(i in 1:n) { r <- r[2:length(r)] - r[1:length(r)-1] } r }   v <- c(90, 47, 58, 29, 22, 32, 55, 5, 55, 73)   print(forwarddif(v, 9)) print(fdiff(v, 9))
http://rosettacode.org/wiki/Formatted_numeric_output
Formatted numeric output
Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
#Visual_Basic
Visual Basic
  Debug.Print Format$(7.125, "00000.000")  
http://rosettacode.org/wiki/Formatted_numeric_output
Formatted numeric output
Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
#Wren
Wren
import "/fmt" for Fmt   var n = 7.125 System.print(Fmt.rjust(9, n, "0"))
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).
#Ring
Ring
    ###--------------------------- # Program: 4 Bit Adder - Ring # Author: Bert Mariani # Date: 2018-02-28 # # Bit Adder: Input A B Cin # Output S Cout # # A ^ B => axb XOR gate # axb ^ C => Sout XOR gate # axb & C => d AND gate # # A & B => anb AND gate # anb | d => Cout OR gate # # Call Adder for number of bit in input fields ###------------------------------------------- ### 4 Bits   Cout = "0" OutputS = "0000" InputA = "0101" InputB = "1101"   See "InputA:.. "+ InputA +nl See "InputB:.. "+ InputB +nl BitsAdd(InputA, InputB) See "Sum...: "+ Cout +" "+ OutputS +nl+nl   ###------------------------------------------- ### 32 Bits   Cout = "0" OutputS = "00000000000000000000000000000000" InputA = "01010101010101010101010101010101" InputB = "11011101110111011101110111011101"   See "InputA:.. "+ InputA +nl See "InputB:.. "+ InputB +nl BitsAdd(InputA, InputB) See "Sum...: "+ Cout +" "+ OutputS +nl+nl   ###-------------------------------   Func BitsAdd(InputA, InputB) nbrBits = len(InputA)   for i = nbrBits to 1 step -1 A = InputA[i] B = InputB[i] C = Cout   S = Adder(A,B,C) OutputS[i] = "" + S next return   ###------------------------ Func Adder(A,B,C)   axb = A ^ B Sout = axb ^ C d = axb & C   anb = A & B Cout = anb | d ### Cout is global   return(Sout) ###------------------------    
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.
#Phix
Phix
with javascript_semantics function median(sequence tbl, integer lo, hi) integer l = hi-lo+1 integer m = lo+floor(l/2) if remainder(l,2)=1 then return tbl[m] end if return (tbl[m-1]+tbl[m])/2 end function function fivenum(sequence tbl) tbl = sort(deep_copy(tbl)) integer l = length(tbl), m = floor(l/2)+remainder(l,2) atom r1 = tbl[1], r2 = median(tbl,1,m), r3 = median(tbl,1,l), r4 = median(tbl,m+1,l), r5 = tbl[l] return {r1, r2, r3, r4, r5} end function constant x1 = {15, 6, 42, 41, 7, 36, 49, 40, 39, 47, 43}, x2 = {36, 40, 7, 39, 41, 15}, x3 = {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} pp(fivenum(x1)) pp(fivenum(x2)) pp(fivenum(x3))
http://rosettacode.org/wiki/Find_the_missing_permutation
Find the missing permutation
ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB Listed above are   all-but-one   of the permutations of the symbols   A,   B,   C,   and   D,   except   for one permutation that's   not   listed. Task Find that missing permutation. Methods Obvious method: enumerate all permutations of A, B, C, and D, and then look for the missing permutation. alternate method: Hint: if all permutations were shown above, how many times would A appear in each position? What is the parity of this number? another alternate method: Hint: if you add up the letter values of each column, does a missing letter A, B, C, and D from each column cause the total value for each column to be unique? Related task   Permutations)
#AWK
AWK
{ split($1,a,""); for (i=1;i<=4;++i) { t[i,a[i]]++; } } END { for (k in t) { split(k,a,SUBSEP) for (l in t) { split(l, b, SUBSEP) if (a[1] == b[1] && t[k] < t[l]) { s[a[1]] = a[2] break } } } print s[1]s[2]s[3]s[4] }
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
#C.2B.2B
C++
  #include <windows.h> #include <iostream> #include <string>   //-------------------------------------------------------------------------------------------------- using namespace std;   //-------------------------------------------------------------------------------------------------- class lastSunday { public: lastSunday() { m[0] = "JANUARY: "; m[1] = "FEBRUARY: "; m[2] = "MARCH: "; m[3] = "APRIL: "; m[4] = "MAY: "; m[5] = "JUNE: "; m[6] = "JULY: "; m[7] = "AUGUST: "; m[8] = "SEPTEMBER: "; m[9] = "OCTOBER: "; m[10] = "NOVEMBER: "; m[11] = "DECEMBER: "; }   void findLastSunday( int y ) { year = y; isleapyear();   int days[] = { 31, isleap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }, d; for( int i = 0; i < 12; i++ ) { d = days[i]; while( true ) { if( !getWeekDay( i, d ) ) break; d--; } lastDay[i] = d; }   display(); }   private: void isleapyear() { isleap = false; if( !( year % 4 ) ) { if( year % 100 ) isleap = true; else if( !( year % 400 ) ) isleap = true; } }   void display() { system( "cls" ); cout << " YEAR " << year << endl << "=============" << endl; for( int x = 0; x < 12; x++ ) cout << m[x] << lastDay[x] << endl;   cout << endl << endl; }   int getWeekDay( int m, int d ) { int y = year;   int f = y + d + 3 * m - 1; m++; if( m < 3 ) y--; else f -= int( .4 * m + 2.3 );   f += int( y / 4 ) - int( ( y / 100 + 1 ) * 0.75 ); f %= 7;   return f; }   int lastDay[12], year; string m[12]; bool isleap; }; //-------------------------------------------------------------------------------------------------- int main( int argc, char* argv[] ) { int y; lastSunday ls;   while( true ) { system( "cls" ); cout << "Enter the year( yyyy ) --- ( 0 to quit ): "; cin >> y; if( !y ) return 0;   ls.findLastSunday( y );   system( "pause" ); } return 0; } //--------------------------------------------------------------------------------------------------  
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) .
#D
D
import std.stdio;   struct Point { real x, y;   void toString(scope void delegate(const(char)[]) sink) const { import std.format; sink("{"); sink.formattedWrite!"%f"(x); sink(", "); sink.formattedWrite!"%f"(y); sink("}"); } }   struct Line { Point s, e; }   Point findIntersection(Line l1, Line l2) { auto a1 = l1.e.y - l1.s.y; auto b1 = l1.s.x - l1.e.x; auto c1 = a1 * l1.s.x + b1 * l1.s.y;   auto a2 = l2.e.y - l2.s.y; auto b2 = l2.s.x - l2.e.x; auto c2 = a2 * l2.s.x + b2 * l2.s.y;   auto delta = a1 * b2 - a2 * b1; // If lines are parallel, intersection point will contain infinite values return Point((b2 * c1 - b1 * c2) / delta, (a1 * c2 - a2 * c1) / delta); }   void main() { auto l1 = Line(Point(4.0, 0.0), Point(6.0, 10.0)); auto l2 = Line(Point(0f, 3f), Point(10f, 7f)); writeln(findIntersection(l1, l2)); l1 = Line(Point(0.0, 0.0), Point(1.0, 1.0)); l2 = Line(Point(1.0, 2.0), Point(4.0, 5.0)); writeln(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].
#F.23
F#
open System   type Vector(x : double, y : double, z : double) = member this.x = x member this.y = y member this.z = z static member (-) (lhs : Vector, rhs : Vector) = Vector(lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z) static member (*) (lhs : Vector, rhs : double) = Vector(lhs.x * rhs, lhs.y * rhs, lhs.z * rhs) override this.ToString() = String.Format("({0:F}, {1:F}, {2:F})", x, y, z)   let Dot (lhs:Vector) (rhs:Vector) = lhs.x * rhs.x + lhs.y * rhs.y + lhs.z * rhs.z   let IntersectPoint rayVector rayPoint planeNormal planePoint = let diff = rayPoint - planePoint let prod1 = Dot diff planeNormal let prod2 = Dot rayVector planeNormal let prod3 = prod1 / prod2 rayPoint - rayVector * prod3   [<EntryPoint>] let main _ = let rv = Vector(0.0, -1.0, -1.0) let rp = Vector(0.0, 0.0, 10.0) let pn = Vector(0.0, 0.0, 1.0) let pp = Vector(0.0, 0.0, 5.0) let ip = IntersectPoint rv rp pn pp Console.WriteLine("The ray intersects the plane at {0}", ip)   0 // return an integer exit code