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/Hailstone_sequence
Hailstone sequence
The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the sequence   = (3 * n) + 1 The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates. This sequence was named by Lothar Collatz in 1937   (or possibly in 1939),   and is also known as (the):   hailstone sequence,   hailstone numbers   3x + 2 mapping,   3n + 1 problem   Collatz sequence   Hasse's algorithm   Kakutani's problem   Syracuse algorithm,   Syracuse problem   Thwaites conjecture   Ulam's problem The hailstone sequence is also known as   hailstone numbers   (because the values are usually subject to multiple descents and ascents like hailstones in a cloud). Task Create a routine to generate the hailstone sequence for a number. Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1 Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.   (But don't show the actual sequence!) See also   xkcd (humourous).   The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).   The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
#Visual_Basic_.NET
Visual Basic .NET
Module HailstoneSequence Sub Main() ' Checking sequence of 27.   Dim l As List(Of Long) = HailstoneSequence(27) Console.WriteLine("27 has {0} elements in sequence:", l.Count())   For i As Integer = 0 To 3 : Console.Write("{0}, ", l(i)) : Next Console.Write("... ") For i As Integer = l.Count - 4 To l.Count - 1 : Console.Write(", {0}", l(i)) : Next   Console.WriteLine()   ' Finding longest sequence for numbers below 100000.   Dim max As Integer = 0 Dim maxCount As Integer = 0   For i = 1 To 99999 l = HailstoneSequence(i) If l.Count > maxCount Then max = i maxCount = l.Count End If Next Console.WriteLine("Max elements in sequence for number below 100k: {0} with {1} elements.", max, maxCount) Console.ReadLine() End Sub   Private Function HailstoneSequence(ByVal n As Long) As List(Of Long) Dim valList As New List(Of Long)() valList.Add(n)   Do Until n = 1 n = IIf(n Mod 2 = 0, n / 2, (3 * n) + 1) valList.Add(n) Loop   Return valList End Function   End Module
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
Generate lower case ASCII alphabet
Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code. During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code: set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z} Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#CLU
CLU
alph = proc () returns (string) a: int := char$c2i('a') letters: array[char] := array[char]$predict(1,26) for i: int in int$from_to(0, 25) do array[char]$addh(letters, char$i2c(a + i)) end return(string$ac2s(letters)) end alph   % test start_up = proc () stream$putl(stream$primary_output(), alph()) end start_up
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
Generate lower case ASCII alphabet
Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code. During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code: set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z} Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#COBOL
COBOL
identification division. program-id. lower-case-alphabet-program. data division. working-storage section. 01 ascii-lower-case. 05 lower-case-alphabet pic a(26). 05 character-code pic 999. 05 loop-counter pic 99. procedure division. control-paragraph. perform add-next-letter-paragraph varying loop-counter from 1 by 1 until loop-counter is greater than 26. display lower-case-alphabet upon console. stop run. add-next-letter-paragraph. add 97 to loop-counter giving character-code. move function char(character-code) to lower-case-alphabet(loop-counter:1).
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#Occam
Occam
#USE "course.lib" PROC main (CHAN BYTE screen!) out.string("Hello world!*c*n", 0, screen) :
http://rosettacode.org/wiki/Generic_swap
Generic swap
Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericity. If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation. That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange. Generic swap is a task which brings together a few separate issues in programming language semantics. Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places. Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities. Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism). Do your best!
#XBS
XBS
set x=1; set y=2; log("Before Swap"); log(x); log(y); swap x y; log("After Swap"); log(x); log(y);
http://rosettacode.org/wiki/Generic_swap
Generic swap
Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericity. If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation. That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange. Generic swap is a task which brings together a few separate issues in programming language semantics. Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places. Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities. Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism). Do your best!
#XPL0
XPL0
include c:\cxpl\codes;   proc Exch(A, B, S); char A, B, S; int I, T; for I:= 0 to S-1 do [T:= A(I); A(I):= B(I); B(I):= T];     real X, Y; [X:= 3.0; Y:= 4.0; Exch(addr X, addr Y, 8); RlOut(0, X); RlOut(0, Y); CrLf(0); ]
http://rosettacode.org/wiki/Generator/Exponential
Generator/Exponential
A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided. Generators are often built on top of coroutines or objects so that the internal state of the object is handled “naturally”. Generators are often used in situations where a sequence is potentially infinite, and where it is possible to construct the next value of the sequence with only minimal state. Task Create a function that returns a generation of the m'th powers of the positive integers starting from zero, in order, and without obvious or simple upper limit. (Any upper limit to the generator should not be stated in the source but should be down to factors such as the languages natural integer size limit or computational time/size). Use it to create a generator of:   Squares.   Cubes. Create a new generator that filters all cubes from the generator of squares. Drop the first 20 values from this last generator of filtered results, and then show the next 10 values. Note that this task requires the use of generators in the calculation of the result. Also see Generator
#Java
Java
import java.util.function.LongSupplier; import static java.util.stream.LongStream.generate;   public class GeneratorExponential implements LongSupplier { private LongSupplier source, filter; private long s, f;   public GeneratorExponential(LongSupplier source, LongSupplier filter) { this.source = source; this.filter = filter; f = filter.getAsLong(); }   @Override public long getAsLong() { s = source.getAsLong();   while (s == f) { s = source.getAsLong(); f = filter.getAsLong(); }   while (s > f) { f = filter.getAsLong(); }   return s; }   public static void main(String[] args) { generate(new GeneratorExponential(new SquaresGen(), new CubesGen())) .skip(20).limit(10) .forEach(n -> System.out.printf("%d ", n)); } }   class SquaresGen implements LongSupplier { private long n;   @Override public long getAsLong() { return n * n++; } }   class CubesGen implements LongSupplier { private long n;   @Override public long getAsLong() { return n * n * n++; } }
http://rosettacode.org/wiki/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related task   least common multiple. See also   MathWorld entry:   greatest common divisor.   Wikipedia entry:     greatest common divisor.
#VBScript
VBScript
Function GCD(a,b) Do If a Mod b > 0 Then c = a Mod b a = b b = c Else GCD = b Exit Do End If Loop End Function   WScript.Echo "The GCD of 48 and 18 is " & GCD(48,18) & "." WScript.Echo "The GCD of 1280 and 240 is " & GCD(1280,240) & "." WScript.Echo "The GCD of 1280 and 240 is " & GCD(3475689,23566319) & "." WScript.Echo "The GCD of 1280 and 240 is " & GCD(123456789,234736437) & "."
http://rosettacode.org/wiki/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related task   least common multiple. See also   MathWorld entry:   greatest common divisor.   Wikipedia entry:     greatest common divisor.
#Verilog
Verilog
module gcd ( input reset_l, input clk,   input [31:0] initial_u, input [31:0] initial_v, input load,   output reg [31:0] result, output reg busy );   reg [31:0] u, v;   always @(posedge clk or negedge reset_l) if (!reset_l) begin busy <= 0; u <= 0; v <= 0; end else begin   result <= u + v; // Result (one of them will be zero)   busy <= u && v; // We're still busy...   // Repeatedly subtract smaller number from larger one if (v <= u) u <= u - v; else if (u < v) v <= v - u;   if (load) // Load new problem when high begin u <= initial_u; v <= initial_v; busy <= 1; end   end   endmodule  
http://rosettacode.org/wiki/Generate_Chess960_starting_position
Generate Chess960 starting position
Chess960 is a variant of chess created by world champion Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints: as in the standard chess game, all eight white pawns must be placed on the second rank. White pieces must stand on the first rank as in the standard game, in random column order but with the two following constraints: the bishops must be placed on opposite color squares (i.e. they must be an odd number of spaces apart or there must be an even number of spaces between them) the King must be between two rooks (with any number of other pieces between them all) Black pawns and pieces must be placed respectively on the seventh and eighth ranks, mirroring the white pawns and pieces, just as in the standard game. (That is, their positions are not independently randomized.) With those constraints there are 960 possible starting positions, thus the name of the variant. Task The purpose of this task is to write a program that can randomly generate any one of the 960 Chess960 initial positions. You will show the result as the first rank displayed with Chess symbols in Unicode: ♔♕♖♗♘ or with the letters King Queen Rook Bishop kNight.
#Nim
Nim
import random, strutils   type   # Chess pieces on first row. Pieces {.pure.} = enum King = "♔", Queen = "♕", Rook1 = "♖", Rook2 = "♖", Bishop1 = "♗", Bishop2 = "♗", Knight1 = "♘", Knight2 = "♘"   # Position counted from 0. Position = range[0..7]   # Position of pieces. Positions = array[Pieces, Position]     func pop[T](s: var set[T]): T = ## Remove and return the first element of a set. for val in s: result = val break s.excl(result)     proc choose[T](s: var set[T]): T = ## Choose randomly a value from a set and remove it from the set. result = sample(s) s.excl(result)     proc positions(): Positions = ## Return a randomly chosen list of piece positions for the first row.   var pos = {Position.low..Position.high}   # Set bishops. result[Bishop1] = sample([0, 2, 4, 6]) # Black squares. result[Bishop2] = sample([1, 3, 5, 7]) # White squares. pos = pos - {result[Bishop1], result[Bishop2]}   # Set queen. result[Queen] = pos.choose()   # Set knights. result[Knight1] = pos.choose() result[Knight2] = pos.choose()   # In the remaining three pieces, the king must be between the two rooks. result[Rook1] = pos.pop() result[King] = pos.pop() result[Rook2] = pos.pop()     #———————————————————————————————————————————————————————————————————————————————————————————————————   randomize()   for _ in 1..10: var row: array[8, string] let pos = positions() for piece in Pieces: row[pos[piece]] = $piece echo row.join(" ")
http://rosettacode.org/wiki/Generate_Chess960_starting_position
Generate Chess960 starting position
Chess960 is a variant of chess created by world champion Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints: as in the standard chess game, all eight white pawns must be placed on the second rank. White pieces must stand on the first rank as in the standard game, in random column order but with the two following constraints: the bishops must be placed on opposite color squares (i.e. they must be an odd number of spaces apart or there must be an even number of spaces between them) the King must be between two rooks (with any number of other pieces between them all) Black pawns and pieces must be placed respectively on the seventh and eighth ranks, mirroring the white pawns and pieces, just as in the standard game. (That is, their positions are not independently randomized.) With those constraints there are 960 possible starting positions, thus the name of the variant. Task The purpose of this task is to write a program that can randomly generate any one of the 960 Chess960 initial positions. You will show the result as the first rank displayed with Chess symbols in Unicode: ♔♕♖♗♘ or with the letters King Queen Rook Bishop kNight.
#Objeck
Objeck
class Chess960 { function : Main(args : String[]) ~ Nil { Generate(10); }   function : Generate(c : Int) ~ Nil { for(x := 0; x < c; x += 1;) { StartPos()->PrintLine(); }; }   function : StartPos() ~ String { p := Char->New[8];   # bishops b1 : Int; b2 : Int; while(true) { b1 := GetPosition(); b2 := GetPosition();   b1c := b1 and 1; b2c := b2 and 1; c := b1c = 0 & b2c <> 0; if(c) { break; }; }; p[b1] := 0x2657; p[b2] := 0x2657;   # queen, knight, knight q := false; for(x := 0; x < 3; x += 1;) { do { b1 := GetPosition(); } while( p[b1] <> '\0');   if(<>q) { p[b1] := 0x2655; q := true; } else { p[b1] := 0x2658; }; };   # rook king rook q := false; for(x := 0; x < 3; x += 1;) { a := 0; while(a < 8) { if(p[a] = '\0') { break; }; a += 1; };   if(<>q) { p[a] := 0x2656; q := true; } else { p[a] := 0x2654; q := false; }; };   s := ""; for(x := 0; x < 8; x += 1;) { s->Append(p[x]); }; return s; }   function : GetPosition() ~ Int { return (Float->Random() * 1000)->As(Int) % 8; } }
http://rosettacode.org/wiki/Function_prototype
Function prototype
Some languages provide the facility to declare functions and subroutines through the use of function prototyping. Task Demonstrate the methods available for declaring prototypes within the language. The provided solutions should include: An explanation of any placement restrictions for prototype declarations A prototype declaration for a function that does not require arguments A prototype declaration for a function that requires two arguments A prototype declaration for a function that utilizes varargs A prototype declaration for a function that utilizes optional arguments A prototype declaration for a function that utilizes named parameters Example of prototype declarations for subroutines or procedures (if these differ from functions) An explanation and example of any special forms of prototyping not covered by the above Languages that do not provide function prototyping facilities should be omitted from this task.
#Delphi
Delphi
  program Function_prototype;   {$APPTYPE CONSOLE}   uses System.SysUtils;   type TIntArray = TArray<Integer>;   TIntArrayHelper = record helper for TIntArray const DEFAULT_VALUE = -1; // A prototype declaration for a function that does not require arguments function ToString(): string;   // A prototype declaration for a function that requires two arguments procedure Insert(Index: Integer; value: Integer);   // A prototype declaration for a function that utilizes varargs // varargs is not available, but a equivalent is array of const procedure From(Args: array of const);   //A prototype declaration for a function that utilizes optional arguments procedure Delete(Index: Integer; Count: Integer = 1);   //A prototype declaration for a function that utilizes named parameters // Named parameters is not supported in Delphi   //Example of prototype declarations for subroutines or procedures //(if these differ from functions) procedure Sqr; //Procedure return nothing function Averange: double; //Function return a value end;   { TIntHelper }   function TIntArrayHelper.Averange: double; begin Result := 0; for var e in self do Result := Result + e; Result := Result / Length(self); end;   procedure TIntArrayHelper.Delete(Index, Count: Integer); begin System.Delete(self, Index, Count); end;   procedure TIntArrayHelper.From(Args: array of const); var I, Count: Integer; begin Count := Length(Args); SetLength(self, Count);   if Count = 0 then exit; for I := 0 to High(Args) do with Args[I] do case VType of vtInteger: self[I] := VInteger; vtBoolean: self[I] := ord(VBoolean); vtChar, vtWideChar: self[I] := StrToIntDef(string(VChar), DEFAULT_VALUE); vtExtended: self[I] := Round(VExtended^); vtString: self[I] := StrToIntDef(VString^, DEFAULT_VALUE); vtPChar: self[I] := StrToIntDef(VPChar, DEFAULT_VALUE); vtObject: self[I] := cardinal(VObject); vtClass: self[I] := cardinal(VClass); vtAnsiString: self[I] := StrToIntDef(string(VAnsiString), DEFAULT_VALUE); vtCurrency: self[I] := Round(VCurrency^); vtVariant: self[I] := Integer(VVariant^); vtInt64: self[I] := Integer(VInt64^); vtUnicodeString: self[I] := StrToIntDef(string(VUnicodeString), DEFAULT_VALUE); end; end;   procedure TIntArrayHelper.Insert(Index, value: Integer); begin system.Insert([value], self, Index); end;   procedure TIntArrayHelper.Sqr; begin for var I := 0 to High(self) do Self[I] := Self[I] * Self[I]; end;   function TIntArrayHelper.ToString: string; begin Result := '['; for var e in self do Result := Result + e.ToString + ', '; Result := Result + ']'; end;   begin var val: TArray<Integer>; val.From([1, '2', PI]); val.Insert(0, -1); // insert -1 at position 0 writeln(' Array: ', val.ToString, ' '); writeln(' Averange: ', val.Averange: 3: 2); val.Sqr; writeln(' Sqr: ', val.ToString); Readln;   end.
http://rosettacode.org/wiki/Fusc_sequence
Fusc sequence
Definitions The   fusc   integer sequence is defined as:   fusc(0) = 0   fusc(1) = 1   for n>1,   the   nth   term is defined as:   if   n   is even;     fusc(n) = fusc(n/2)   if   n   is   odd;     fusc(n) = fusc((n-1)/2)   +   fusc((n+1)/2) Note that MathWorld's definition starts with unity, not zero.   This task will be using the OEIS' version   (above). An observation   fusc(A) = fusc(B) where   A   is some non-negative integer expressed in binary,   and where   B   is the binary value of   A   reversed. Fusc numbers are also known as:   fusc function   (named by Dijkstra, 1982)   Stern's Diatomic series   (although it starts with unity, not zero)   Stern-Brocot sequence   (although it starts with unity, not zero) Task   show the first   61   fusc numbers (starting at zero) in a horizontal format.   show the fusc number (and its index) whose length is greater than any previous fusc number length.   (the length is the number of decimal digits when the fusc number is expressed in base ten.)   show all numbers with commas   (if appropriate).   show all output here. Related task   RosettaCode Stern-Brocot sequence Also see   the MathWorld entry:   Stern's Diatomic Series.   the OEIS entry:   A2487.
#11l
11l
F fusc(n) V res = [0] * n res[1] = 1 L(i) 2 .< n res[i] = I i % 2 == 0 {res[i I/ 2]} E res[(i-1) I/ 2] + res[(i+1) I/ 2] R res   print(‘First 61 terms:’) print(fusc(61))   print() print(‘Points in the sequence where an item has more digits than any previous items:’) V f = fusc(20'000'000) V max_len = 0 L(i) 0 .< f.len I String(f[i]).len > max_len max_len = String(f[i]).len print((i, f[i]))
http://rosettacode.org/wiki/Functional_coverage_tree
Functional coverage tree
Functional coverage is a measure of how much a particular function of a system has been verified as correct. It is used heavily in tracking the completeness of the verification of complex System on Chip (SoC) integrated circuits, where it can also be used to track how well the functional requirements of the system have been verified. This task uses a sub-set of the calculations sometimes used in tracking functional coverage but uses a more familiar(?) scenario. Task Description The head of the clean-up crews for "The Men in a very dark shade of grey when viewed at night" has been tasked with managing the cleansing of two properties after an incident involving aliens. She arranges the task hierarchically with a manager for the crews working on each house who return with a breakdown of how they will report on progress in each house. The overall hierarchy of (sub)tasks is as follows, cleaning house1 bedrooms bathrooms bathroom1 bathroom2 outside lavatory attic kitchen living rooms lounge dining room conservatory playroom basement garage garden house2 upstairs bedrooms suite 1 suite 2 bedroom 3 bedroom 4 bathroom toilet attics groundfloor kitchen living rooms lounge dining room conservatory playroom wet room & toilet garage garden hot tub suite basement cellars wine cellar cinema The head of cleanup knows that her managers will report fractional completion of leaf tasks (tasks with no child tasks of their own), and she knows that she will want to modify the weight of values of completion as she sees fit. Some time into the cleaning, and some coverage reports have come in and she thinks see needs to weight the big house2 60-40 with respect to coverage from house1 She prefers a tabular view of her data where missing weights are assumed to be 1.0 and missing coverage 0.0. NAME_HIERARCHY |WEIGHT |COVERAGE | cleaning | | | house1 |40 | | bedrooms | |0.25 | bathrooms | | | bathroom1 | |0.5 | bathroom2 | | | outside_lavatory | |1 | attic | |0.75 | kitchen | |0.1 | living_rooms | | | lounge | | | dining_room | | | conservatory | | | playroom | |1 | basement | | | garage | | | garden | |0.8 | house2 |60 | | upstairs | | | bedrooms | | | suite_1 | | | suite_2 | | | bedroom_3 | | | bedroom_4 | | | bathroom | | | toilet | | | attics | |0.6 | groundfloor | | | kitchen | | | living_rooms | | | lounge | | | dining_room | | | conservatory | | | playroom | | | wet_room_&_toilet | | | garage | | | garden | |0.9 | hot_tub_suite | |1 | basement | | | cellars | |1 | wine_cellar | |1 | cinema | |0.75 | Calculation The coverage of a node in the tree is calculated as the weighted average of the coverage of its children evaluated bottom-upwards in the tree. The task is to calculate the overall coverage of the cleaning task and display the coverage at all levels of the hierarchy on this page, in a manner that visually shows the hierarchy, weights and coverage of all nodes. Extra Credit After calculating the coverage for all nodes, one can also calculate the additional/delta top level coverage that would occur if any (sub)task were to be fully covered from its current fractional coverage. This is done by multiplying the extra coverage that could be gained 1 − c o v e r a g e {\displaystyle 1-coverage} for any node, by the product of the `powers` of its parent nodes from the top down to the node. The power of a direct child of any parent is given by the power of the parent multiplied by the weight of the child divided by the sum of the weights of all the direct children. The pseudo code would be: method delta_calculation(this, power): sum_of_weights = sum(node.weight for node in children) this.delta = (1 - this.coverage) * power for node in self.children: node.delta_calculation(power * node.weight / sum_of_weights) return this.delta Followed by a call to: top.delta_calculation(power=1) Note: to aid in getting the data into your program you might want to use an alternative, more functional description of the starting data given on the discussion page.
#J
J
raw=: 0 :0 NAME_HIERARCHY |WEIGHT |COVERAGE | cleaning | | | house1 |40 | | bedrooms | |0.25 | bathrooms | | | bathroom1 | |0.5 | bathroom2 | | | outside_lavatory | |1 | attic | |0.75 | kitchen | |0.1 | living_rooms | | | lounge | | | dining_room | | | conservatory | | | playroom | |1 | basement | | | garage | | | garden | |0.8 | house2 |60 | | upstairs | | | bedrooms | | | suite_1 | | | suite_2 | | | bedroom_3 | | | bedroom_4 | | | bathroom | | | toilet | | | attics | |0.6 | groundfloor | | | kitchen | | | living_rooms | | | lounge | | | dining_room | | | conservatory | | | playroom | | | wet_room_&_toilet | | | garage | | | garden | |0.9 | hot_tub_suite | |1 | basement | | | cellars | |1 | wine_cellar | |1 | cinema | |0.75 | )
http://rosettacode.org/wiki/Functional_coverage_tree
Functional coverage tree
Functional coverage is a measure of how much a particular function of a system has been verified as correct. It is used heavily in tracking the completeness of the verification of complex System on Chip (SoC) integrated circuits, where it can also be used to track how well the functional requirements of the system have been verified. This task uses a sub-set of the calculations sometimes used in tracking functional coverage but uses a more familiar(?) scenario. Task Description The head of the clean-up crews for "The Men in a very dark shade of grey when viewed at night" has been tasked with managing the cleansing of two properties after an incident involving aliens. She arranges the task hierarchically with a manager for the crews working on each house who return with a breakdown of how they will report on progress in each house. The overall hierarchy of (sub)tasks is as follows, cleaning house1 bedrooms bathrooms bathroom1 bathroom2 outside lavatory attic kitchen living rooms lounge dining room conservatory playroom basement garage garden house2 upstairs bedrooms suite 1 suite 2 bedroom 3 bedroom 4 bathroom toilet attics groundfloor kitchen living rooms lounge dining room conservatory playroom wet room & toilet garage garden hot tub suite basement cellars wine cellar cinema The head of cleanup knows that her managers will report fractional completion of leaf tasks (tasks with no child tasks of their own), and she knows that she will want to modify the weight of values of completion as she sees fit. Some time into the cleaning, and some coverage reports have come in and she thinks see needs to weight the big house2 60-40 with respect to coverage from house1 She prefers a tabular view of her data where missing weights are assumed to be 1.0 and missing coverage 0.0. NAME_HIERARCHY |WEIGHT |COVERAGE | cleaning | | | house1 |40 | | bedrooms | |0.25 | bathrooms | | | bathroom1 | |0.5 | bathroom2 | | | outside_lavatory | |1 | attic | |0.75 | kitchen | |0.1 | living_rooms | | | lounge | | | dining_room | | | conservatory | | | playroom | |1 | basement | | | garage | | | garden | |0.8 | house2 |60 | | upstairs | | | bedrooms | | | suite_1 | | | suite_2 | | | bedroom_3 | | | bedroom_4 | | | bathroom | | | toilet | | | attics | |0.6 | groundfloor | | | kitchen | | | living_rooms | | | lounge | | | dining_room | | | conservatory | | | playroom | | | wet_room_&_toilet | | | garage | | | garden | |0.9 | hot_tub_suite | |1 | basement | | | cellars | |1 | wine_cellar | |1 | cinema | |0.75 | Calculation The coverage of a node in the tree is calculated as the weighted average of the coverage of its children evaluated bottom-upwards in the tree. The task is to calculate the overall coverage of the cleaning task and display the coverage at all levels of the hierarchy on this page, in a manner that visually shows the hierarchy, weights and coverage of all nodes. Extra Credit After calculating the coverage for all nodes, one can also calculate the additional/delta top level coverage that would occur if any (sub)task were to be fully covered from its current fractional coverage. This is done by multiplying the extra coverage that could be gained 1 − c o v e r a g e {\displaystyle 1-coverage} for any node, by the product of the `powers` of its parent nodes from the top down to the node. The power of a direct child of any parent is given by the power of the parent multiplied by the weight of the child divided by the sum of the weights of all the direct children. The pseudo code would be: method delta_calculation(this, power): sum_of_weights = sum(node.weight for node in children) this.delta = (1 - this.coverage) * power for node in self.children: node.delta_calculation(power * node.weight / sum_of_weights) return this.delta Followed by a call to: top.delta_calculation(power=1) Note: to aid in getting the data into your program you might want to use an alternative, more functional description of the starting data given on the discussion page.
#JavaScript
JavaScript
(() => { 'use strict';   // updatedCoverageOutline :: String -> String const updatedCoverageOutline = outlineText => { const delimiter = '|', indentedLines = indentLevelsFromLines(lines(outlineText)), columns = init(tokenizeWith(delimiter)(snd(indentedLines[0])));   // SERIALISATION OF UPDATED PARSE TREE (TO NEW OUTLINE TEXT) return tabulation(delimiter)( columns.concat('SHARE OF RESIDUE\n') ) + unlines( indentedLinesFromTree( showCoverage(delimiter))(' ')(   // TWO TRAVERSAL COMPUTATIONS   withResidueShares(1.0)( foldTree(weightedCoverage)(   // PARSE TREE (FROM OUTLINE TEXT) fmapTree(compose( partialRecord, tokenizeWith(delimiter) ))(fst( forestFromLineIndents(tail(indentedLines)) )) ) )) ); };   // TEST ----------------------------------------------- // main :: IO () const main = () => console.log( // strOutline is included as literal text // at the foot of this code listing. updatedCoverageOutline(strOutline) );   // COVERAGE AND SHARES OF RESIDUE ---------------------   // weightedCoverage :: Dict -> Forest Dict -> Tree Dict const weightedCoverage = x => xs => { const cws = map(compose( fanArrow(x => x.coverage)(x => x.weight), root ))(xs), totalWeight = cws.reduce((a, tpl) => a + snd(tpl), 0); return Node( insertDict('coverage')( cws.reduce((a, tpl) => { const [c, w] = Array.from(tpl); return a + (c * w); }, x.coverage) / ( 0 < totalWeight ? totalWeight : 1 ) )(x) )(xs); };     // withResidueShares :: Float -> Tree Dict -> Tree Dict const withResidueShares = shareOfTotal => tree => { const go = fraction => node => { const nodeRoot = node.root, forest = node.nest, weights = forest.map(x => x.root.weight), weightTotal = sum(weights); return Node( insertDict('share')( fraction * (1 - nodeRoot.coverage) )(nodeRoot) )( zipWith(go)( weights.map(w => fraction * (w / weightTotal)) )(forest) ); }; return go(shareOfTotal)(tree); };     // OUTLINE PARSED TO TREE -----------------------------   // forestFromLineIndents :: [(Int, String)] -> [Tree String] const forestFromLineIndents = tuples => { const go = xs => 0 < xs.length ? (() => { const [n, s] = Array.from(xs[0]); // Lines indented under this line, // tupled with all the rest. const [firstTreeLines, rest] = Array.from( span(x => n < x[0])(xs.slice(1)) ); // This first tree, and then the rest. return [Node(s)(go(firstTreeLines))] .concat(go(rest)); })() : []; return go(tuples); };   // indentLevelsFromLines :: [String] -> [(Int, String)] const indentLevelsFromLines = xs => { const indentTextPairs = xs.map(compose( firstArrow(length), span(isSpace) )), indentUnit = minimum(indentTextPairs.flatMap(pair => { const w = fst(pair); return 0 < w ? [w] : []; })); return indentTextPairs.map( firstArrow(flip(div)(indentUnit)) ); };   // partialRecord :: [String] -> Dict const partialRecord = xs => { const [name, weightText, coverageText] = take(3)( xs.concat(['', '', '']) ); return { name: name || '?', weight: parseFloat(weightText) || 1.0, coverage: parseFloat(coverageText) || 0.0, share: 0.0 }; };   // tokenizeWith :: String -> String -> [String] const tokenizeWith = delimiter => // A sequence of trimmed tokens obtained by // splitting s on the supplied delimiter. s => s.split(delimiter).map(x => x.trim());     // TREE SERIALIZED TO OUTLINE -------------------------   // indentedLinesFromTree :: (String -> a -> String) -> // String -> Tree a -> [String] const indentedLinesFromTree = showRoot => strTab => tree => { const go = indent => node => [showRoot(indent)(node.root)] .concat(node.nest.flatMap(go(strTab + indent))); return go('')(tree); };   // showN :: Int -> Float -> String const showN = p => n => justifyRight(7)(' ')(n.toFixed(p));   // showCoverage :: String -> String -> Dict -> String const showCoverage = delimiter => indent => x => tabulation(delimiter)( [indent + x.name, showN(0)(x.weight)] .concat([x.coverage, x.share].map(showN(4))) );   // tabulation :: String -> [String] -> String const tabulation = delimiter => // Up to 4 tokens drawn from the argument list, // as a single string with fixed left-justified // white-space widths, between delimiters. compose( intercalate(delimiter + ' '), zipWith(flip(justifyLeft)(' '))([31, 9, 9, 9]) );     // GENERIC AND REUSABLE FUNCTIONS ---------------------   // Node :: a -> [Tree a] -> Tree a const Node = v => xs => ({ type: 'Node', root: v, // any type of value (consistent across tree) nest: xs || [] });   // Tuple (,) :: a -> b -> (a, b) const Tuple = a => b => ({ type: 'Tuple', '0': a, '1': b, length: 2 });   // compose (<<<) :: (b -> c) -> (a -> b) -> a -> c const compose = (...fs) => x => fs.reduceRight((a, f) => f(a), x);   // concat :: [[a]] -> [a] // concat :: [String] -> String const concat = xs => 0 < xs.length ? (() => { const unit = 'string' !== typeof xs[0] ? ( [] ) : ''; return unit.concat.apply(unit, xs); })() : [];   // div :: Int -> Int -> Int const div = x => y => Math.floor(x / y);   // either :: (a -> c) -> (b -> c) -> Either a b -> c const either = fl => fr => e => 'Either' === e.type ? ( undefined !== e.Left ? ( fl(e.Left) ) : fr(e.Right) ) : undefined;   // Compose a function from a simple value to a tuple of // the separate outputs of two different functions   // fanArrow (&&&) :: (a -> b) -> (a -> c) -> (a -> (b, c)) const fanArrow = f => g => x => Tuple(f(x))( g(x) );   // Lift a simple function to one which applies to a tuple, // transforming only the first item of the tuple   // firstArrow :: (a -> b) -> ((a, c) -> (b, c)) const firstArrow = f => xy => Tuple(f(xy[0]))( xy[1] );   // flip :: (a -> b -> c) -> b -> a -> c const flip = f => 1 < f.length ? ( (a, b) => f(b, a) ) : (x => y => f(y)(x));   // fmapTree :: (a -> b) -> Tree a -> Tree b const fmapTree = f => tree => { const go = node => Node(f(node.root))( node.nest.map(go) ); return go(tree); };   // foldTree :: (a -> [b] -> b) -> Tree a -> b const foldTree = f => tree => { const go = node => f(node.root)( node.nest.map(go) ); return go(tree); };   // foldl1 :: (a -> a -> a) -> [a] -> a const foldl1 = f => xs => 1 < xs.length ? xs.slice(1) .reduce(uncurry(f), xs[0]) : xs[0];   // fst :: (a, b) -> a const fst = tpl => tpl[0];   // init :: [a] -> [a] const init = xs => 0 < xs.length ? ( xs.slice(0, -1) ) : undefined;   // insertDict :: String -> a -> Dict -> Dict const insertDict = k => v => dct => Object.assign({}, dct, { [k]: v });   // intercalate :: [a] -> [[a]] -> [a] // intercalate :: String -> [String] -> String const intercalate = sep => xs => xs.join(sep);   // isSpace :: Char -> Bool const isSpace = c => /\s/.test(c);   // justifyLeft :: Int -> Char -> String -> String const justifyLeft = n => cFiller => s => n > s.length ? ( s.padEnd(n, cFiller) ) : s;   // justifyRight :: Int -> Char -> String -> String const justifyRight = n => cFiller => s => n > s.length ? ( s.padStart(n, cFiller) ) : s;   // length :: [a] -> Int const length = xs => (Array.isArray(xs) || 'string' === typeof xs) ? ( xs.length ) : Infinity;   // lines :: String -> [String] const lines = s => s.split(/[\r\n]/);   // map :: (a -> b) -> [a] -> [b] const map = f => xs => (Array.isArray(xs) ? ( xs ) : xs.split('')).map(f);   // minimum :: Ord a => [a] -> a const minimum = xs => 0 < xs.length ? ( foldl1(a => x => x < a ? x : a)(xs) ) : undefined;   // root :: Tree a -> a const root = tree => tree.root;   // showLog :: a -> IO () const showLog = (...args) => console.log( args .map(JSON.stringify) .join(' -> ') );   // snd :: (a, b) -> b const snd = tpl => tpl[1];   // span :: (a -> Bool) -> [a] -> ([a], [a]) const span = p => xs => { const iLast = xs.length - 1; return splitAt( until(i => iLast < i || !p(xs[i]))( succ )(0) )(xs); };   // splitAt :: Int -> [a] -> ([a], [a]) const splitAt = n => xs => Tuple(xs.slice(0, n))( xs.slice(n) );   // succ :: Enum a => a -> a const succ = x => 1 + x;   // sum :: [Num] -> Num const sum = xs => xs.reduce((a, x) => a + x, 0);   // tail :: [a] -> [a] const tail = xs => 0 < xs.length ? xs.slice(1) : [];   // take :: Int -> [a] -> [a] // take :: Int -> String -> String const take = n => xs => 'GeneratorFunction' !== xs.constructor.constructor.name ? ( xs.slice(0, n) ) : [].concat.apply([], Array.from({ length: n }, () => { const x = xs.next(); return x.done ? [] : [x.value]; }));   // uncurry :: (a -> b -> c) -> ((a, b) -> c) const uncurry = f => (x, y) => f(x)(y);   // unlines :: [String] -> String const unlines = xs => xs.join('\n');   // until :: (a -> Bool) -> (a -> a) -> a -> a const until = p => f => x => { let v = x; while (!p(v)) v = f(v); return v; };   // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] const zipWith = f => xs => ys => xs.slice( 0, Math.min(xs.length, ys.length) ).map((x, i) => f(x)(ys[i]));   // SOURCE OUTLINE -----------------------------------------   const strOutline = `NAME_HIERARCHY |WEIGHT |COVERAGE | cleaning | | | house1 |40 | | bedrooms | |0.25 | bathrooms | | | bathroom1 | |0.5 | bathroom2 | | | outside_lavatory | |1 | attic | |0.75 | kitchen | |0.1 | living_rooms | | | lounge | | | dining_room | | | conservatory | | | playroom | |1 | basement | | | garage | | | garden | |0.8 | house2 |60 | | upstairs | | | bedrooms | | | suite_1 | | | suite_2 | | | bedroom_3 | | | bedroom_4 | | | bathroom | | | toilet | | | attics | |0.6 | groundfloor | | | kitchen | | | living_rooms | | | lounge | | | dining_room | | | conservatory | | | playroom | | | wet_room_&_toilet | | | garage | | | garden | |0.9 | hot_tub_suite | |1 | basement | | | cellars | |1 | wine_cellar | |1 | cinema | |0.75 |`;   // MAIN --- return main(); })();
http://rosettacode.org/wiki/Function_frequency
Function frequency
Display - for a program or runtime environment (whatever suits the style of your language) - the top ten most frequently occurring functions (or also identifiers or tokens, if preferred). This is a static analysis: The question is not how often each function is actually executed at runtime, but how often it is used by the programmer. Besides its practical usefulness, the intent of this task is to show how to do self-inspection within the language.
#Arturo
Arturo
source: to :block read arg\0 frequencies: #[]   inspectBlock: function [blk][ loop blk 'item [ case [] when? [word? item][ sItem: to :string item if set? sItem -> if function? var sItem [ if? key? frequencies sItem -> set frequencies sItem (get frequencies sItem)+1 else -> set frequencies sItem 1 ] ]   when? [or? block? item inline? item] -> inspectBlock item   else [] ] ]   inspectBlock source   inspect frequencies
http://rosettacode.org/wiki/Function_frequency
Function frequency
Display - for a program or runtime environment (whatever suits the style of your language) - the top ten most frequently occurring functions (or also identifiers or tokens, if preferred). This is a static analysis: The question is not how often each function is actually executed at runtime, but how often it is used by the programmer. Besides its practical usefulness, the intent of this task is to show how to do self-inspection within the language.
#AWK
AWK
  # syntax: GAWK -f FUNCTION_FREQUENCY.AWK filename(s).AWK # # sorting: # PROCINFO["sorted_in"] is used by GAWK # SORTTYPE is used by Thompson Automation's TAWK # BEGIN { # create array of keywords to be ignored by lexer asplit("BEGIN:END:atan2:break:close:continue:cos:delete:" \ "do:else:exit:exp:for:getline:gsub:if:in:index:int:" \ "length:log:match:next:print:printf:rand:return:sin:" \ "split:sprintf:sqrt:srand:strftime:sub:substr:system:tolower:toupper:while", keywords,":") # build the symbol-state table split("00:00:00:00:00:00:00:00:00:00:" \ "20:10:10:12:12:11:07:00:00:00:" \ "08:08:08:08:08:33:08:00:00:00:" \ "08:44:08:36:08:08:08:00:00:00:" \ "08:44:45:42:42:41:08",machine,":") # parse the input state = 1 for (;;) { symb = lex() # get next symbol nextstate = substr(machine[state symb],1,1) act = substr(machine[state symb],2,1) # perform required action if (act == "0") { # do nothing } else if (act == "1") { # found a function call if (!(inarray(tok,names))) { names[++nnames] = tok } ++xnames[tok] } else if (act == "2") { # found a variable or array if (tok in Local) { tok = tok "(" funcname ")" if (!(inarray(tok,names))) { names[++nnames] = tok } ++xnames[tok] } else { tok = tok "()" if (!(inarray(tok,names))) { names[++nnames] = tok } ++xnames[tok] } } else if (act == "3") { # found a function definition funcname = tok } else if (act == "4") { # found a left brace braces++ } else if (act == "5") { # found a right brace braces-- if (braces == 0) { delete Local funcname = "" nextstate = 1 } } else if (act == "6") { # found a local variable declaration Local[tok] = 1 } else if (act == "7") { # found end of file break } else if (act == "8") { # found an error printf("error: FILENAME=%s, FNR=%d\n",FILENAME,FNR) exit(1) } state = nextstate # finished with current token } # format function names for (i=1; i<=nnames; i++) { if (index(names[i],"(") == 0) { tmp_arr[xnames[names[i]]][names[i]] = "" } } # print function names PROCINFO["sorted_in"] = "@ind_num_desc" ; SORTTYPE = 9 for (i in tmp_arr) { PROCINFO["sorted_in"] = "@ind_str_asc" ; SORTTYPE = 1 for (j in tmp_arr[i]) { if (++shown <= 10) { printf("%d %s\n",i,j) } } } exit(0) } function asplit(str,arr,fs, i,n,temp_asplit) { n = split(str,temp_asplit,fs) for (i=1; i<=n; i++) { arr[temp_asplit[i]]++ } } function inarray(val,arr, j) { for (j in arr) { if (arr[j] == val) { return(j) } } return("") } function lex() { for (;;) { if (tok == "(eof)") { return(7) } while (length(line) == 0) { if (getline line == 0) { tok = "(eof)" return(7) } } sub(/^[ \t]+/,"",line) # remove white space, sub(/^"([^"]|\\")*"/,"",line) # quoted strings, sub(/^\/([^\/]|\\\/)+\//,"",line) # regular expressions, sub(/^#.*/,"",line) # and comments if (line ~ /^function /) { tok = "function" line = substr(line,10) return(1) } else if (line ~ /^{/) { tok = "{" line = substr(line,2) return(2) } else if (line ~ /^}/) { tok = "}" line = substr(line,2) return(3) } else if (match(line,/^[A-Za-z_][A-Za-z_0-9]*\[/)) { tok = substr(line,1,RLENGTH-1) line = substr(line,RLENGTH+1) return(5) } else if (match(line,/^[A-Za-z_][A-Za-z_0-9]*\(/)) { tok = substr(line,1,RLENGTH-1) line = substr(line,RLENGTH+1) if (!(tok in keywords)) { return(6) } } else if (match(line,/^[A-Za-z_][A-Za-z_0-9]*/)) { tok = substr(line,1,RLENGTH) line = substr(line,RLENGTH+1) if (!(tok in keywords)) { return(4) } } else { match(line,/^[^A-Za-z_{}]/) tok = substr(line,1,RLENGTH) line = substr(line,RLENGTH+1) } } }  
http://rosettacode.org/wiki/Gamma_function
Gamma function
Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function. The Gamma function can be defined as: Γ ( x ) = ∫ 0 ∞ t x − 1 e − t d t {\displaystyle \Gamma (x)=\displaystyle \int _{0}^{\infty }t^{x-1}e^{-t}dt} This suggests a straightforward (but inefficient) way of computing the Γ {\displaystyle \Gamma } through numerical integration. Better suggested methods: Lanczos approximation Stirling's approximation
#ANSI_Standard_BASIC
ANSI Standard BASIC
100 DECLARE EXTERNAL FUNCTION FNlngamma 110 120 DEF FNgamma(z) = EXP(FNlngamma(z)) 130 140 FOR x = 0.1 TO 2.05 STEP 0.1 150 PRINT USING$("#.#",x), USING$("##.############", FNgamma(x)) 160 NEXT x 170 END 180 190 EXTERNAL FUNCTION FNlngamma(z) 200 DIM lz(0 TO 6) 210 RESTORE 220 MAT READ lz 230 DATA 1.000000000190015, 76.18009172947146, -86.50532032941677, 24.01409824083091, -1.231739572450155, 0.0012086509738662, -0.000005395239385 240 IF z < 0.5 THEN 250 LET FNlngamma = LOG(PI / SIN(PI * z)) - FNlngamma(1.0 - z) 260 EXIT FUNCTION 270 END IF 280 LET z = z - 1.0 290 LET b = z + 5.5 300 LET a = lz(0) 310 FOR i = 1 TO 6 320 LET a = a + lz(i) / (z + i) 330 NEXT i 340 LET FNlngamma = (LOG(SQR(2*PI)) + LOG(a) - b) + LOG(b) * (z+0.5) 350 END FUNCTION
http://rosettacode.org/wiki/Galton_box_animation
Galton box animation
Example of a Galton Box at the end of animation. A   Galton device   Sir Francis Galton's device   is also known as a   bean machine,   a   Galton Board,   or a   quincunx. Description of operation In a Galton box, there are a set of pins arranged in a triangular pattern.   A number of balls are dropped so that they fall in line with the top pin, deflecting to the left or the right of the pin.   The ball continues to fall to the left or right of lower pins before arriving at one of the collection points between and to the sides of the bottom row of pins. Eventually the balls are collected into bins at the bottom   (as shown in the image),   the ball column heights in the bins approximate a   bell curve.   Overlaying   Pascal's triangle   onto the pins shows the number of different paths that can be taken to get to each bin. Task Generate an animated simulation of a Galton device. Task requirements   The box should have at least 5 pins on the bottom row.   A solution can use graphics or ASCII animation.   Provide a sample of the output/display such as a screenshot.   There can be one or more balls in flight at the same time.   If multiple balls are in flight, ensure they don't interfere with each other.   A solution should allow users to specify the number of balls, or it should run until full or a preset limit.   Optionally,   display the number of balls.
#C.2B.2B
C++
  #include "stdafx.h" #include <windows.h> #include <stdlib.h>   const int BMP_WID = 410, BMP_HEI = 230, MAX_BALLS = 120;   class myBitmap { public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() { DeleteObject( pen ); DeleteObject( brush ); DeleteDC( hdc ); DeleteObject( bmp ); } bool create( int w, int h ) { BITMAPINFO bi; ZeroMemory( &bi, sizeof( bi ) ); bi.bmiHeader.biSize = sizeof( bi.bmiHeader ); bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8; bi.bmiHeader.biCompression = BI_RGB; bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biWidth = w; bi.bmiHeader.biHeight = -h;   HDC dc = GetDC( GetConsoleWindow() ); bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 ); if( !bmp ) return false; hdc = CreateCompatibleDC( dc ); SelectObject( hdc, bmp ); ReleaseDC( GetConsoleWindow(), dc ); width = w; height = h; return true; } void clear( BYTE clr = 0 ) { memset( pBits, clr, width * height * sizeof( DWORD ) ); } void setBrushColor( DWORD bClr ) { if( brush ) DeleteObject( brush ); brush = CreateSolidBrush( bClr ); SelectObject( hdc, brush ); } void setPenColor( DWORD c ) { clr = c; createPen(); } void setPenWidth( int w ) { wid = w; createPen(); } HDC getDC() const { return hdc; } int getWidth() const { return width; } int getHeight() const { return height; } private: void createPen() { if( pen ) DeleteObject( pen ); pen = CreatePen( PS_SOLID, wid, clr ); SelectObject( hdc, pen ); } HBITMAP bmp; HDC hdc; HPEN pen; HBRUSH brush; void *pBits; int width, height, wid; DWORD clr; }; class point { public: int x; float y; void set( int a, float b ) { x = a; y = b; } }; typedef struct { point position, offset; bool alive, start; }ball; class galton { public : galton() { bmp.create( BMP_WID, BMP_HEI ); initialize(); } void setHWND( HWND hwnd ) { _hwnd = hwnd; } void simulate() { draw(); update(); Sleep( 1 ); } private: void draw() { bmp.clear(); bmp.setPenColor( RGB( 0, 255, 0 ) ); bmp.setBrushColor( RGB( 0, 255, 0 ) ); int xx, yy; for( int y = 3; y < 14; y++ ) { yy = 10 * y; for( int x = 0; x < 41; x++ ) { xx = 10 * x; if( pins[y][x] ) Rectangle( bmp.getDC(), xx - 3, yy - 3, xx + 3, yy + 3 ); } } bmp.setPenColor( RGB( 255, 0, 0 ) ); bmp.setBrushColor( RGB( 255, 0, 0 ) ); ball* b; for( int x = 0; x < MAX_BALLS; x++ ) { b = &balls[x]; if( b->alive ) Rectangle( bmp.getDC(), static_cast<int>( b->position.x - 3 ), static_cast<int>( b->position.y - 3 ), static_cast<int>( b->position.x + 3 ), static_cast<int>( b->position.y + 3 ) ); } for( int x = 0; x < 70; x++ ) { if( cols[x] > 0 ) { xx = 10 * x; Rectangle( bmp.getDC(), xx - 3, 160, xx + 3, 160 + cols[x] ); } } HDC dc = GetDC( _hwnd ); BitBlt( dc, 0, 0, BMP_WID, BMP_HEI, bmp.getDC(), 0, 0, SRCCOPY ); ReleaseDC( _hwnd, dc ); } void update() { ball* b; for( int x = 0; x < MAX_BALLS; x++ ) { b = &balls[x]; if( b->alive ) { b->position.x += b->offset.x; b->position.y += b->offset.y; if( x < MAX_BALLS - 1 && !b->start && b->position.y > 50.0f ) { b->start = true; balls[x + 1].alive = true; } int c = ( int )b->position.x, d = ( int )b->position.y + 6; if( d > 10 || d < 41 ) { if( pins[d / 10][c / 10] ) { if( rand() % 30 < 15 ) b->position.x -= 10; else b->position.x += 10; } } if( b->position.y > 160 ) { b->alive = false; cols[c / 10] += 1; } } } } void initialize() { for( int x = 0; x < MAX_BALLS; x++ ) { balls[x].position.set( 200, -10 ); balls[x].offset.set( 0, 0.5f ); balls[x].alive = balls[x].start = false; } balls[0].alive = true; for( int x = 0; x < 70; x++ ) cols[x] = 0; for( int y = 0; y < 70; y++ ) for( int x = 0; x < 41; x++ ) pins[x][y] = false; int p; for( int y = 0; y < 11; y++ ) { p = ( 41 / 2 ) - y; for( int z = 0; z < y + 1; z++ ) { pins[3 + y][p] = true; p += 2; } } } myBitmap bmp; HWND _hwnd; bool pins[70][40]; ball balls[MAX_BALLS]; int cols[70]; }; class wnd { public: int wnd::Run( HINSTANCE hInst ) { _hInst = hInst; _hwnd = InitAll(); _gtn.setHWND( _hwnd ); ShowWindow( _hwnd, SW_SHOW ); UpdateWindow( _hwnd ); MSG msg; ZeroMemory( &msg, sizeof( msg ) ); while( msg.message != WM_QUIT ) { if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 ) { TranslateMessage( &msg ); DispatchMessage( &msg ); } else _gtn.simulate(); } return UnregisterClass( "_GALTON_", _hInst ); } private: static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) { switch( msg ) { case WM_DESTROY: PostQuitMessage( 0 ); break; default: return static_cast<int>( DefWindowProc( hWnd, msg, wParam, lParam ) ); } return 0; } HWND InitAll() { WNDCLASSEX wcex; ZeroMemory( &wcex, sizeof( wcex ) ); wcex.cbSize = sizeof( WNDCLASSEX ); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = ( WNDPROC )WndProc; wcex.hInstance = _hInst; wcex.hCursor = LoadCursor( NULL, IDC_ARROW ); wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 ); wcex.lpszClassName = "_GALTON_"; RegisterClassEx( &wcex ); RECT rc; SetRect( &rc, 0, 0, BMP_WID, BMP_HEI ); AdjustWindowRect( &rc, WS_CAPTION, FALSE ); return CreateWindow( "_GALTON_", ".: Galton Box -- PJorente :.", WS_SYSMENU, CW_USEDEFAULT, 0, rc.right - rc.left, rc.bottom - rc.top, NULL, NULL, _hInst, NULL ); } HINSTANCE _hInst; HWND _hwnd; galton _gtn; }; int APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) { srand( GetTickCount() ); wnd myWnd; return myWnd.Run( hInstance ); }  
http://rosettacode.org/wiki/Gapful_numbers
Gapful numbers
Numbers   (positive integers expressed in base ten)   that are (evenly) divisible by the number formed by the first and last digit are known as   gapful numbers. Evenly divisible   means divisible with   no   remainder. All   one─   and two─digit   numbers have this property and are trivially excluded.   Only numbers   ≥ 100   will be considered for this Rosetta Code task. Example 187   is a   gapful   number because it is evenly divisible by the number   17   which is formed by the first and last decimal digits of   187. About   7.46%   of positive integers are   gapful. Task   Generate and show all sets of numbers (below) on one line (horizontally) with a title,   here on this page   Show the first   30   gapful numbers   Show the first   15   gapful numbers   ≥          1,000,000   Show the first   10   gapful numbers   ≥   1,000,000,000 Related tasks   Harshad or Niven series.   palindromic gapful numbers.   largest number divisible by its digits. Also see   The OEIS entry:   A108343 gapful numbers.   numbersaplenty gapful numbers
#D
D
import std.conv; import std.stdio;   string commatize(ulong n) { auto s = n.to!string; auto le = s.length; for (int i = le - 3; i >= 1; i -= 3) { s = s[0..i] ~ "," ~ s[i..$]; } return s; }   void main() { ulong[] starts = [cast(ulong)1e2, cast(ulong)1e6, cast(ulong)1e7, cast(ulong)1e9, 7123]; int[] counts = [30, 15, 15, 10, 25]; for (int i = 0; i < starts.length; i++) { int count = 0; auto j = starts[i]; ulong pow = 100; while (true) { if (j < pow * 10) { break; } pow *= 10; } writefln("First %d gapful numbers starting at %s:", counts[i], commatize(starts[i])); while (count < counts[i]) { auto fl = (j / pow) * 10 + (j % 10); if (j % fl == 0) { write(j, ' '); count++; } j++; if (j >= 10 * pow) { pow *= 10; } } writeln("\n"); } }
http://rosettacode.org/wiki/Gaussian_elimination
Gaussian elimination
Task Solve   Ax=b   using Gaussian elimination then backwards substitution. A   being an   n by n   matrix. Also,   x and b   are   n by 1   vectors. To improve accuracy, please use partial pivoting and scaling. See also   the Wikipedia entry:   Gaussian elimination
#Delphi
Delphi
program GuassianElimination;   // Modified from: // R. Sureshkumar (10 January 1997) // Gregory J. McRae (22 October 1997) // http://web.mit.edu/10.001/Web/Course_Notes/Gauss_Pivoting.c   {$APPTYPE CONSOLE}   {$R *.res}   uses System.SysUtils;   type TMatrix = class private _r, _c : integer; data : array of TDoubleArray; function getValue(rIndex, cIndex : integer): double; procedure setValue(rIndex, cIndex : integer; value: double); public constructor Create (r, c : integer); destructor Destroy; override;   property r : integer read _r; property c : integer read _c; property value[rIndex, cIndex: integer]: double read getValue write setValue; default; end;     constructor TMatrix.Create (r, c : integer); begin inherited Create; self.r := r; self.c := c; setLength (data, r, c); end;   destructor TMatrix.Destroy; begin data := nil; inherited; end;   function TMatrix.getValue(rIndex, cIndex: Integer): double; begin Result := data[rIndex-1, cIndex-1]; // 1-based array end;   procedure TMatrix.setValue(rIndex, cIndex : integer; value: double); begin data[rIndex-1, cIndex-1] := value; // 1-based array end;   // Solve A x = b procedure gauss (A, b, x : TMatrix); var rowx : integer; i, j, k, n, m : integer; amax, xfac, temp, temp1 : double; begin rowx := 0; // Keep count of the row interchanges n := A.r; for k := 1 to n - 1 do begin amax := abs (A[k,k]); m := k; // Find the row with largest pivot for i := k + 1 to n do begin xfac := abs (A[i,k]); if xfac > amax then begin amax := xfac; m := i; end; end;   if m <> k then begin // Row interchanges rowx := rowx+1; temp1 := b[k,1]; b[k,1] := b[m,1]; b[m,1] := temp1; for j := k to n do begin temp := a[k,j]; a[k,j] := a[m,j]; a[m,j] := temp; end; end;   for i := k+1 to n do begin xfac := a[i, k]/a[k, k]; for j := k+1 to n do a[i,j] := a[i,j]-xfac*a[k,j]; b[i,1] := b[i,1] - xfac*b[k,1] end; end;   // Back substitution for j := 1 to n do begin k := n-j + 1; x[k,1] := b[k,1]; for i := k+1 to n do begin x[k,1] := x[k,1] - a[k,i]*x[i,1]; end; x[k,1] := x[k,1]/a[k,k]; end; end;     var A, b, x : TMatrix;   begin try // Could have been done with simple arrays rather than a specific TMatrix class A := TMatrix.Create (4,4); // Note ideal but use TMatrix to define the vectors as well b := TMatrix.Create (4,1); x := TMatrix.Create (4,1);   A[1,1] := 2; A[1,2] := 1; A[1,3] := 0; A[1,4] := 0; A[2,1] := 1; A[2,2] := 1; A[2,3] := 1; A[2,4] := 0; A[3,1] := 0; A[3,2] := 1; A[3,3] := 2; A[3,4] := 1; A[4,1] := 0; A[3,2] := 0; A[4,3] := 1; A[4,4] := 2;   b[1,1] := 2; b[2,1] := 1; b[3,1] := 4; b[4,1] := 8;   gauss (A, b, x);   writeln (x[1,1]:5:2); writeln (x[2,1]:5:2); writeln (x[3,1]:5:2); writeln (x[4,1]:5:2);   readln; except on E: Exception do Writeln(E.ClassName, ': ', E.Message); end; end.    
http://rosettacode.org/wiki/Generate_random_chess_position
Generate random chess position
Task Generate a random chess position in FEN format. The position does not have to be realistic or even balanced,  but it must comply to the following rules: there is one and only one king of each color  (one black king and one white king); the kings must not be placed on adjacent squares; there can not be any pawn in the promotion square  (no white pawn in the eighth rank, and no black pawn in the first rank); including the kings, up to 32 pieces of either color can be placed. There is no requirement for material balance between sides. The picking of pieces does not have to comply to a regular chess set --- there can be five knights, twenty rooks, whatever ... as long as the total number of pieces do not exceed thirty-two. it is white's turn. It's assumed that both sides have lost castling rights and that there is no possibility for   en passant   (the FEN should thus end in w - - 0 1). No requirement is made regarding the probability distribution of your method, but your program should be able to span a reasonably representative sample of all possible positions. For instance, programs that would always generate positions with say five pieces on the board, or with kings on a corner, would not be considered truly random.
#Typescript
Typescript
  class Fen {   public createFen() { let grid: string[][];   grid = [];   for (let r = 0; r < 8; r++) { grid[r] = []; for (let c = 0; c < 8; c++) { grid[r][c] = "0"; } }   this.placeKings(grid); this.placePieces(grid, "PPPPPPPP", true); this.placePieces(grid, "pppppppp", true); this.placePieces(grid, "RNBQBNR", false); this.placePieces(grid, "rnbqbnr", false); return this.toFen(grid); }   private placeKings(grid: string[][]): void { let r1, c1, r2, c2: number; while (true) { r1 = Math.floor(Math.random() * 8); c1 = Math.floor(Math.random() * 8); r2 = Math.floor(Math.random() * 8); c2 = Math.floor(Math.random() * 8); if (r1 != r2 && Math.abs(r1 - r2) > 1 && Math.abs(c1 - c2) > 1) { break; } } grid[r1][c1] = "K"; grid[r2][c2] = "k"; }   private placePieces(grid: string[][], pieces: string, isPawn: boolean): void { let numToPlace: number = Math.floor(Math.random() * pieces.length); for (let n = 0; n < numToPlace; n++) { let r, c: number; do { r = Math.floor(Math.random() * 8); c = Math.floor(Math.random() * 8); } while (grid[r][c] != "0" || (isPawn && (r == 7 || r == 0)));   grid[r][c] = pieces.charAt(n); } }   private toFen(grid: string[][]): string { let result: string = ""; let countEmpty: number = 0; for (let r = 0; r < 8; r++) { for (let c = 0; c < 8; c++) { let char: string = grid[r][c]; if (char == "0") { countEmpty++; } else { if (countEmpty > 0) { result += countEmpty; countEmpty = 0; } result += char; } } if (countEmpty > 0) { result += countEmpty; countEmpty = 0; } result += "/"; } return result += " w - - 0 1"; }   }   let fen: Fen = new Fen(); console.log(fen.createFen());  
http://rosettacode.org/wiki/Generate_random_chess_position
Generate random chess position
Task Generate a random chess position in FEN format. The position does not have to be realistic or even balanced,  but it must comply to the following rules: there is one and only one king of each color  (one black king and one white king); the kings must not be placed on adjacent squares; there can not be any pawn in the promotion square  (no white pawn in the eighth rank, and no black pawn in the first rank); including the kings, up to 32 pieces of either color can be placed. There is no requirement for material balance between sides. The picking of pieces does not have to comply to a regular chess set --- there can be five knights, twenty rooks, whatever ... as long as the total number of pieces do not exceed thirty-two. it is white's turn. It's assumed that both sides have lost castling rights and that there is no possibility for   en passant   (the FEN should thus end in w - - 0 1). No requirement is made regarding the probability distribution of your method, but your program should be able to span a reasonably representative sample of all possible positions. For instance, programs that would always generate positions with say five pieces on the board, or with kings on a corner, would not be considered truly random.
#Wren
Wren
import "random" for Random import "/fmt" for Fmt   var rand = Random.new()   var grid = List.filled(8, null) for (i in 0..7) grid[i] = List.filled(9, ".")   var placeKings = Fn.new { while (true) { var r1 = rand.int(8) var c1 = rand.int(8) var r2 = rand.int(8) var c2 = rand.int(8) if (r1 != r2 && (r1 - r2).abs > 1 && (c1 - c2).abs > 1) { grid[r1][c1] = "K" grid[r2][c2] = "k" return } } }   var placePieces = Fn.new { |pieces, isPawn| var numToPlace = rand.int(pieces.count) for (n in 0...numToPlace) { var r var c while (true) { r = rand.int(8) c = rand.int(8) if (grid[r][c] == "." && !(isPawn && (r == 7 || r == 0))) break } grid[r][c] = pieces[n] } }   var toFen = Fn.new { var fen = "" var countEmpty = 0 for (r in 0..7) { for (c in 0..7) { var ch = grid[r][c] Fmt.write("$2s ", ch) if (ch == ".") { countEmpty = countEmpty + 1 } else { if (countEmpty > 0) { fen = fen + countEmpty.toString countEmpty = 0 } fen = fen + ch } } if (countEmpty > 0) { fen = fen + countEmpty.toString countEmpty = 0 } fen = fen + "/" System.print() } return fen + " w - - 0 1" }   var createFen = Fn.new { placeKings.call() placePieces.call("PPPPPPPP", true) placePieces.call("pppppppp", true) placePieces.call("RNBQBNR", false) placePieces.call("rnbqbnr", false) return toFen.call() }   System.print(createFen.call())
http://rosettacode.org/wiki/Gauss-Jordan_matrix_inversion
Gauss-Jordan matrix inversion
Task Invert matrix   A   using Gauss-Jordan method. A   being an   n × n   matrix.
#Java
Java
// GaussJordan.java   import java.util.Random;   public class GaussJordan { public static void main(String[] args) { int rows = 5; Matrix m = new Matrix(rows, rows); Random r = new Random(); for (int row = 0; row < rows; ++row) { for (int column = 0; column < rows; ++column) m.set(row, column, r.nextDouble()); } System.out.println("Matrix:"); m.print(); System.out.println("Inverse:"); Matrix inv = m.inverse(); inv.print(); System.out.println("Product of matrix and inverse:"); Matrix.product(m, inv).print(); } }
http://rosettacode.org/wiki/General_FizzBuzz
General FizzBuzz
Task Write a generalized version of FizzBuzz that works for any list of factors, along with their words. This is basically a "fizzbuzz" implementation where the user supplies the parameters. The user will enter the max number, then they will enter the factors to be calculated along with the corresponding word to be printed. For simplicity's sake, assume the user will input an integer as the max number and 3 factors, each with a word associated with them. For example, given: >20 #This is the maximum number, supplied by the user >3 Fizz #The user now enters the starting factor (3) and the word they want associated with it (Fizz) >5 Buzz #The user now enters the next factor (5) and the word they want associated with it (Buzz) >7 Baxx #The user now enters the next factor (7) and the word they want associated with it (Baxx) In other words: For this example, print the numbers 1 through 20, replacing every multiple of 3 with "Fizz", every multiple of 5 with "Buzz", and every multiple of 7 with "Baxx". In the case where a number is a multiple of at least two factors, print each of the words associated with those factors in the order of least to greatest factor. For instance, the number 15 is a multiple of both 3 and 5; print "FizzBuzz". If the max number was 105 instead of 20, you would print "FizzBuzzBaxx" because it's a multiple of 3, 5, and 7. Output: 1 2 Fizz 4 Buzz Fizz Baxx 8 Fizz Buzz 11 Fizz 13 Baxx FizzBuzz 16 17 Fizz 19 Buzz
#Go
Go
  package main   import ( "fmt" )   const numbers = 3   func main() {   //using the provided data max := 20 words := map[int]string{ 3: "Fizz", 5: "Buzz", 7: "Baxx", } keys := []int{3, 5, 7} divisible := false for i := 1; i <= max; i++ { for _, n := range keys { if i % n == 0 { fmt.Print(words[n]) divisible = true } } if !divisible { fmt.Print(i) } fmt.Println() divisible = false }   }
http://rosettacode.org/wiki/Hailstone_sequence
Hailstone sequence
The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the sequence   = (3 * n) + 1 The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates. This sequence was named by Lothar Collatz in 1937   (or possibly in 1939),   and is also known as (the):   hailstone sequence,   hailstone numbers   3x + 2 mapping,   3n + 1 problem   Collatz sequence   Hasse's algorithm   Kakutani's problem   Syracuse algorithm,   Syracuse problem   Thwaites conjecture   Ulam's problem The hailstone sequence is also known as   hailstone numbers   (because the values are usually subject to multiple descents and ascents like hailstones in a cloud). Task Create a routine to generate the hailstone sequence for a number. Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1 Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.   (But don't show the actual sequence!) See also   xkcd (humourous).   The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).   The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
#Vlang
Vlang
// 1st arg is the number to generate the sequence for. // 2nd arg is a slice to recycle, to reduce garbage. fn hs(nn int, recycle []int) []int { mut n := nn mut s := recycle[..0] s << n for n > 1 { if n&1 == 0 { n /= 2 } else { n = 3*n + 1 } s << n } return s }   fn main() { mut seq := hs(27, []) println("hs(27): $seq.len elements: [${seq[0]} ${seq[1]} ${seq[2]} ${seq[3]} ... ${seq[seq.len-4]} ${seq[seq.len-3]} ${seq[seq.len-2]} ${seq[seq.len-1]}]")   mut max_n, mut max_len := 0,0 for n in 1..100000 { seq = hs(n, seq) if seq.len > max_len { max_n = n max_len = seq.len } } println("hs($max_n): $max_len elements") }
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
Generate lower case ASCII alphabet
Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code. During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code: set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z} Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#CoffeeScript
CoffeeScript
  (String.fromCharCode(x) for x in [97..122])  
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
Generate lower case ASCII alphabet
Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code. During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code: set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z} Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Comal
Comal
dim alphabet$ of 26 for i := 1 to 26 alphabet$(i) := chr$(ord("a") - 1 + i) endfor i print alphabet$
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#Octave
Octave
disp("Hello world!");
http://rosettacode.org/wiki/Generic_swap
Generic swap
Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericity. If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation. That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange. Generic swap is a task which brings together a few separate issues in programming language semantics. Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places. Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities. Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism). Do your best!
#Yabasic
Yabasic
a = 1 b = 2   print a, b //----- swap ---- temp = a : a = b : b = temp print a, b
http://rosettacode.org/wiki/Generic_swap
Generic swap
Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericity. If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation. That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange. Generic swap is a task which brings together a few separate issues in programming language semantics. Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places. Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities. Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism). Do your best!
#Yorick
Yorick
> a = 1 > b = "foo" > swap, a, b > a "foo" > b 1
http://rosettacode.org/wiki/Generator/Exponential
Generator/Exponential
A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided. Generators are often built on top of coroutines or objects so that the internal state of the object is handled “naturally”. Generators are often used in situations where a sequence is potentially infinite, and where it is possible to construct the next value of the sequence with only minimal state. Task Create a function that returns a generation of the m'th powers of the positive integers starting from zero, in order, and without obvious or simple upper limit. (Any upper limit to the generator should not be stated in the source but should be down to factors such as the languages natural integer size limit or computational time/size). Use it to create a generator of:   Squares.   Cubes. Create a new generator that filters all cubes from the generator of squares. Drop the first 20 values from this last generator of filtered results, and then show the next 10 values. Note that this task requires the use of generators in the calculation of the result. Also see Generator
#JavaScript
JavaScript
  function PowersGenerator(m) { var n=0; while(1) { yield Math.pow(n, m); n += 1; } }   function FilteredGenerator(g, f){ var value = g.next(); var filter = f.next();   while(1) { if( value < filter ) { yield value; value = g.next(); } else if ( value > filter ) { filter = f.next(); } else { value = g.next(); filter = f.next(); } } }       var squares = PowersGenerator(2); var cubes = PowersGenerator(3);   var filtered = FilteredGenerator(squares, cubes);       for( var x = 0; x < 20; x++ ) filtered.next() for( var x = 20; x < 30; x++ ) console.logfiltered.next());    
http://rosettacode.org/wiki/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related task   least common multiple. See also   MathWorld entry:   greatest common divisor.   Wikipedia entry:     greatest common divisor.
#Visual_Basic
Visual Basic
Function GCD(ByVal a As Long, ByVal b As Long) As Long Dim h As Long   If a Then If b Then Do h = a Mod b a = b b = h Loop While b End If GCD = Abs(a) Else GCD = Abs(b) End If   End Function   Sub Main() ' testing the above function Debug.Assert GCD(12, 18) = 6 Debug.Assert GCD(1280, 240) = 80 Debug.Assert GCD(240, 1280) = 80 Debug.Assert GCD(-240, 1280) = 80 Debug.Assert GCD(240, -1280) = 80 Debug.Assert GCD(0, 0) = 0 Debug.Assert GCD(0, 1) = 1 Debug.Assert GCD(1, 0) = 1 Debug.Assert GCD(3475689, 23566319) = 7 Debug.Assert GCD(123456789, 234736437) = 3 Debug.Assert GCD(3780, 3528) = 252   End Sub
http://rosettacode.org/wiki/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related task   least common multiple. See also   MathWorld entry:   greatest common divisor.   Wikipedia entry:     greatest common divisor.
#Vlang
Vlang
fn gcd(xx int, yy int) int { mut x, mut y := xx, yy for y != 0 { x, y = y, x%y } return x }   fn main() { println(gcd(33, 77)) println(gcd(49865, 69811)) }  
http://rosettacode.org/wiki/Generate_Chess960_starting_position
Generate Chess960 starting position
Chess960 is a variant of chess created by world champion Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints: as in the standard chess game, all eight white pawns must be placed on the second rank. White pieces must stand on the first rank as in the standard game, in random column order but with the two following constraints: the bishops must be placed on opposite color squares (i.e. they must be an odd number of spaces apart or there must be an even number of spaces between them) the King must be between two rooks (with any number of other pieces between them all) Black pawns and pieces must be placed respectively on the seventh and eighth ranks, mirroring the white pawns and pieces, just as in the standard game. (That is, their positions are not independently randomized.) With those constraints there are 960 possible starting positions, thus the name of the variant. Task The purpose of this task is to write a program that can randomly generate any one of the 960 Chess960 initial positions. You will show the result as the first rank displayed with Chess symbols in Unicode: ♔♕♖♗♘ or with the letters King Queen Rook Bishop kNight.
#PARI.2FGP
PARI/GP
chess960() = { my (C = vector(8), i, j, r);   C[random(4) * 2 + 1] = C[random(4) * 2 + 2] = "B"; for (i = 1, 3, while (C[r = random(8) + 1],); C[r] = Vec("NNQ")[i]); for (i = 1, 8, if (!C[i], C[i] = Vec("RKR")[j++])); C }
http://rosettacode.org/wiki/Function_prototype
Function prototype
Some languages provide the facility to declare functions and subroutines through the use of function prototyping. Task Demonstrate the methods available for declaring prototypes within the language. The provided solutions should include: An explanation of any placement restrictions for prototype declarations A prototype declaration for a function that does not require arguments A prototype declaration for a function that requires two arguments A prototype declaration for a function that utilizes varargs A prototype declaration for a function that utilizes optional arguments A prototype declaration for a function that utilizes named parameters Example of prototype declarations for subroutines or procedures (if these differ from functions) An explanation and example of any special forms of prototyping not covered by the above Languages that do not provide function prototyping facilities should be omitted from this task.
#Diego
Diego
// A prototype declaration for a function that does not require arguments   begin_funct(foo); // function as a 'method' with no arguments, no return type end_funct(foo);   // or   with_funct(foo); // function as a 'method' with no arguments, no return type   // A prototype declaration for a function that requires two arguments   begin_funct(goo)_arg({string}, str1, str2); // two arguments, no return type end_funct[]; // derived name of function using [], like 'this'   with_funct(goo)_arg({str}, str1, str2); // two arguments, no return type with_funct(hoo)_param({integer}, i, j); // 'param' posit can be used instead of 'arg'   // A prototype declaration for a function that utilizes varargs   begin_funct(voo)_arg({int}, [vararg], v); // variable number of arguments, no return type, 'int' can be used instead of 'integer' end_funct[];   begin_funct({int}, voo)_arg({int}, ..., v); // variable number of arguments, with return type add_var({int}, sum)_v(0); forall_var(v)_calc([sum]+=[v]); [voo]_ret([sum]); end_funct[];   // A prototype declaration for a function that utilizes optional arguments   begin_funct({int}, ooo)_arg(o)_value(1); // optional argument with default value and return type integer with_funct(ooo)_return([o]); // Can be shortened to [ooo]_ret([0]); end_funct[];   begin_funct({int}, oxo)_arg(o,u,v)_opt(u)_value(1); // optional argument of second argument with default value and return type integer [ooo]_ret(1); // the execution has to name arguments or missing in comma-separated list of arguments end_funct[];   // A prototype declaration for a function that utilizes named parameters   begin_funct({int}, poo)_param({int}, a, b, c); // to enforce named parameters '_param' posit can be used. [poo]_ret([a]+[b]+[c]); end_funct[];   exec_funct(poo)_param(a)_value(1)_param(b, c)_value(2, 3) ? me_msg()_funct(poo); ;   begin_funct({int}, poo)_arg({int}, a, b, c); // named parameters can still be used with '_arg' posit. [poo]_ret([a]+[b]+[c]); end_funct[];   me_msg()_funct(poo)_arg(a)_value(1)_value(2, 3); // Callee has to figure out unnamed arguments by extraction // 'exec_' verb is implied before '_funct' action   // Example of prototype declarations for subroutines or procedures (if these differ from functions)   begin_instruct(foo); // instructions are 'methods', no arguments, no return type end_instruct[foo]; // explicit end of itself   // or   with_instruct(foo); // instructions are 'methods', no arguments, no return type   begin_funct(yoo)_arg(robotMoniker)_param(b); // A '_funct' can be used as a subroutine when missing the '{}' return datatype // a mix of '_arg' and '_param' posits can be used with_robot[robotMoniker]_var(sq)_calc([b]^2); // create a variable called 'sq' on robot 'robotMoniker' end_funct(yoo);   begin_instruct(woo)_arg(robotType)_param(b); // An '_instuct' is only used for subroutines and return datatypes are not accepted with_robot()_type[robotType]_var(sq)_calc([b]^2); // create a variable called 'sq' on all robots of type 'robotType' end_funct(woo);   // An explanation and example of any special forms of prototyping not covered by the above   begin_funct({double}, voo)_arg({int}, [numArgs], v); // variable-defined number of arguments, with return type add_var({int}, sum)_v(0); add_var({double}, average)_v(0); for_var(v)_until[numArgs]_calc([sum]+=[v]); // the number of arguments [numArgs] does not have to be number of arguments of v [voo]_ret([sum]/[numArgs]); end_funct[];   begin_funct({int}, [numArgsOut], voo)_arg({int}, [numArgsIn], v); // variable-defined number of arguments, with variable-defined number of return types add_var({int}, sum)_v(0); add_var({double}, average)_v(0); for_var(v)_until[numArgsOut]_calc([sum]+=[v]); [voo]_ret([sum]/[numArgsOut]); end_funct[];
http://rosettacode.org/wiki/Function_prototype
Function prototype
Some languages provide the facility to declare functions and subroutines through the use of function prototyping. Task Demonstrate the methods available for declaring prototypes within the language. The provided solutions should include: An explanation of any placement restrictions for prototype declarations A prototype declaration for a function that does not require arguments A prototype declaration for a function that requires two arguments A prototype declaration for a function that utilizes varargs A prototype declaration for a function that utilizes optional arguments A prototype declaration for a function that utilizes named parameters Example of prototype declarations for subroutines or procedures (if these differ from functions) An explanation and example of any special forms of prototyping not covered by the above Languages that do not provide function prototyping facilities should be omitted from this task.
#F.23
F#
// A function taking and returning nothing (unit). val noArgs : unit -> unit // A function taking two integers, and returning an integer. val twoArgs : int -> int -> int // A function taking a ParamPack array of ints, and returning an int. The ParamPack // attribute is not included in the signature. val varArgs : int [] -> int // A function taking an int and a ParamPack array of ints, and returning an // object of the same type. val atLeastOnArg : int -> int [] -> int // A function taking an int Option, and returning an int. val optionalArg : Option<int> -> int   // Named arguments and the other form of optional arguments are only available on // methods. type methodClass = class // A method taking an int named x, and returning an int. member NamedArg : x:int -> int // A method taking two optional ints in a tuple, and returning an int. The //optional arguments must be tupled. member OptionalArgs : ?x:int * ?y:int -> int end
http://rosettacode.org/wiki/Fusc_sequence
Fusc sequence
Definitions The   fusc   integer sequence is defined as:   fusc(0) = 0   fusc(1) = 1   for n>1,   the   nth   term is defined as:   if   n   is even;     fusc(n) = fusc(n/2)   if   n   is   odd;     fusc(n) = fusc((n-1)/2)   +   fusc((n+1)/2) Note that MathWorld's definition starts with unity, not zero.   This task will be using the OEIS' version   (above). An observation   fusc(A) = fusc(B) where   A   is some non-negative integer expressed in binary,   and where   B   is the binary value of   A   reversed. Fusc numbers are also known as:   fusc function   (named by Dijkstra, 1982)   Stern's Diatomic series   (although it starts with unity, not zero)   Stern-Brocot sequence   (although it starts with unity, not zero) Task   show the first   61   fusc numbers (starting at zero) in a horizontal format.   show the fusc number (and its index) whose length is greater than any previous fusc number length.   (the length is the number of decimal digits when the fusc number is expressed in base ten.)   show all numbers with commas   (if appropriate).   show all output here. Related task   RosettaCode Stern-Brocot sequence Also see   the MathWorld entry:   Stern's Diatomic Series.   the OEIS entry:   A2487.
#Ada
Ada
with Ada.Text_IO; with Ada.Integer_Text_IO;   procedure Show_Fusc is   generic Precalculate : Natural; package Fusc_Sequences is function Fusc (N : in Natural) return Natural; end Fusc_Sequences;   package body Fusc_Sequences is   Precalculated_Fusc : array (0 .. Precalculate) of Natural;   function Fusc_Slow (N : in Natural) return Natural is begin if N = 0 or N = 1 then return N; elsif N mod 2 = 0 then return Fusc_Slow (N / 2); else return Fusc_Slow ((N - 1) / 2) + Fusc_Slow ((N + 1) / 2); end if; end Fusc_Slow;   function Fusc (N : in Natural) return Natural is begin if N <= Precalculate then return Precalculated_Fusc (N); elsif N mod 2 = 0 then return Fusc (N / 2); else return Fusc ((N - 1) / 2) + Fusc ((N + 1) / 2); end if; end Fusc;   begin for N in Precalculated_Fusc'Range loop Precalculated_Fusc (N) := Fusc_Slow (N); end loop; end Fusc_Sequences;     package Fusc_Sequence is new Fusc_Sequences (Precalculate => 200_000);   function Fusc (N : in Natural) return Natural renames Fusc_Sequence.Fusc;     procedure Print_Small_Fuscs is use Ada.Text_IO; begin Put_Line ("First 61 numbers in the fusc sequence:"); for N in 0 .. 60 loop Put (Fusc (N)'Image); Put (" "); end loop; New_Line; end Print_Small_Fuscs;     procedure Print_Large_Fuscs (High : in Natural) is use Ada.Text_IO; use Ada.Integer_Text_IO; subtype N_Range is Natural range Natural'First .. High; F  : Natural; Len  : Natural; Max_Len : Natural := 0; Placeholder : String := " n fusc(n)"; Image_N  : String renames Placeholder (1 .. 8); Image_Fusc  : String renames Placeholder (10 .. Placeholder'Last); begin New_Line; Put_Line ("Printing all largest Fusc numbers upto " & High'Image); Put_Line (Placeholder);   for N in N_Range loop F  := Fusc (N); Len := F'Image'Length;   if Len > Max_Len then Max_Len := Len; Put (Image_N, N); Put (Image_Fusc, F); Put (Placeholder); New_Line; end if; end loop; end Print_Large_Fuscs;   begin Print_Small_Fuscs; Print_Large_Fuscs (High => 20_000_000); end Show_Fusc;
http://rosettacode.org/wiki/Functional_coverage_tree
Functional coverage tree
Functional coverage is a measure of how much a particular function of a system has been verified as correct. It is used heavily in tracking the completeness of the verification of complex System on Chip (SoC) integrated circuits, where it can also be used to track how well the functional requirements of the system have been verified. This task uses a sub-set of the calculations sometimes used in tracking functional coverage but uses a more familiar(?) scenario. Task Description The head of the clean-up crews for "The Men in a very dark shade of grey when viewed at night" has been tasked with managing the cleansing of two properties after an incident involving aliens. She arranges the task hierarchically with a manager for the crews working on each house who return with a breakdown of how they will report on progress in each house. The overall hierarchy of (sub)tasks is as follows, cleaning house1 bedrooms bathrooms bathroom1 bathroom2 outside lavatory attic kitchen living rooms lounge dining room conservatory playroom basement garage garden house2 upstairs bedrooms suite 1 suite 2 bedroom 3 bedroom 4 bathroom toilet attics groundfloor kitchen living rooms lounge dining room conservatory playroom wet room & toilet garage garden hot tub suite basement cellars wine cellar cinema The head of cleanup knows that her managers will report fractional completion of leaf tasks (tasks with no child tasks of their own), and she knows that she will want to modify the weight of values of completion as she sees fit. Some time into the cleaning, and some coverage reports have come in and she thinks see needs to weight the big house2 60-40 with respect to coverage from house1 She prefers a tabular view of her data where missing weights are assumed to be 1.0 and missing coverage 0.0. NAME_HIERARCHY |WEIGHT |COVERAGE | cleaning | | | house1 |40 | | bedrooms | |0.25 | bathrooms | | | bathroom1 | |0.5 | bathroom2 | | | outside_lavatory | |1 | attic | |0.75 | kitchen | |0.1 | living_rooms | | | lounge | | | dining_room | | | conservatory | | | playroom | |1 | basement | | | garage | | | garden | |0.8 | house2 |60 | | upstairs | | | bedrooms | | | suite_1 | | | suite_2 | | | bedroom_3 | | | bedroom_4 | | | bathroom | | | toilet | | | attics | |0.6 | groundfloor | | | kitchen | | | living_rooms | | | lounge | | | dining_room | | | conservatory | | | playroom | | | wet_room_&_toilet | | | garage | | | garden | |0.9 | hot_tub_suite | |1 | basement | | | cellars | |1 | wine_cellar | |1 | cinema | |0.75 | Calculation The coverage of a node in the tree is calculated as the weighted average of the coverage of its children evaluated bottom-upwards in the tree. The task is to calculate the overall coverage of the cleaning task and display the coverage at all levels of the hierarchy on this page, in a manner that visually shows the hierarchy, weights and coverage of all nodes. Extra Credit After calculating the coverage for all nodes, one can also calculate the additional/delta top level coverage that would occur if any (sub)task were to be fully covered from its current fractional coverage. This is done by multiplying the extra coverage that could be gained 1 − c o v e r a g e {\displaystyle 1-coverage} for any node, by the product of the `powers` of its parent nodes from the top down to the node. The power of a direct child of any parent is given by the power of the parent multiplied by the weight of the child divided by the sum of the weights of all the direct children. The pseudo code would be: method delta_calculation(this, power): sum_of_weights = sum(node.weight for node in children) this.delta = (1 - this.coverage) * power for node in self.children: node.delta_calculation(power * node.weight / sum_of_weights) return this.delta Followed by a call to: top.delta_calculation(power=1) Note: to aid in getting the data into your program you might want to use an alternative, more functional description of the starting data given on the discussion page.
#Julia
Julia
using CSV, DataFrames, Formatting   function updatecoverage(dfname, outputname) df = CSV.read(dfname) dchild = Dict{Int, Vector{Int}}([i => Int[] for i in 0:maximum(df[!, 1])])   for row in eachrow(df) push!(dchild[row[3]], row[1]) end   function coverage(t) return dchild[t] == [] ? df[t, :COVERAGE] * df[t, :WEIGHT] : sum(coverage, dchild[t]) / sum(x -> df[x, :WEIGHT], dchild[t]) * df[t, :WEIGHT] end   df[!, :COVERAGE] .= coverage.(df.NUMBER)   function possibleincrease(t) if !isempty(dchild[t]) return 0.0 else newcoverage = deepcopy(df.COVERAGE) newcoverage[t] = 1.0 oldcoverage = newcoverage[1] function potentialcoverage(t) return dchild[t] == [] ? newcoverage[t] * df[t, :WEIGHT] : sum(potentialcoverage, dchild[t]) / sum(x -> df[x, :WEIGHT], dchild[t]) * df[t, :WEIGHT] end   newcoverage .= potentialcoverage.(df[!, 1]) return newcoverage[1] - oldcoverage end end   df.POTENTIAL = possibleincrease.(df[!, 1])   CSV.write(outputname, df) end   function displaycoveragedb(dfname) df = CSV.read(dfname) indentlevel(t) = (i = 0; while (j = df[t, 3]) != 0 i += 1; t = j end; i) indent1 = [indentlevel(i) for i in df.NUMBER] maxindent = maximum(indent1) indent2 = maxindent .- indent1 showpot = size(df)[2] == 6 println("INDEX NAME_HIERARCHY WEIGHT COVERAGE (POTENTIAL INCREASE)") for (i, row) in enumerate(eachrow(df)) println(rpad(row[1], 7), " "^indent1[i], rpad(row[2], 20), " "^indent2[i], rpad(row[4], 8), rpad(format(row[5]), 12), showpot && row[6] != 0 ? format(row[6]) : "") end end   const dbname = "coverage.csv" const newdbname = "coverageupdated.csv"   println("Input data:") displaycoveragedb(dbname) updatecoverage(dbname, newdbname) println("\nUpdated data:") displaycoveragedb(newdbname)  
http://rosettacode.org/wiki/Functional_coverage_tree
Functional coverage tree
Functional coverage is a measure of how much a particular function of a system has been verified as correct. It is used heavily in tracking the completeness of the verification of complex System on Chip (SoC) integrated circuits, where it can also be used to track how well the functional requirements of the system have been verified. This task uses a sub-set of the calculations sometimes used in tracking functional coverage but uses a more familiar(?) scenario. Task Description The head of the clean-up crews for "The Men in a very dark shade of grey when viewed at night" has been tasked with managing the cleansing of two properties after an incident involving aliens. She arranges the task hierarchically with a manager for the crews working on each house who return with a breakdown of how they will report on progress in each house. The overall hierarchy of (sub)tasks is as follows, cleaning house1 bedrooms bathrooms bathroom1 bathroom2 outside lavatory attic kitchen living rooms lounge dining room conservatory playroom basement garage garden house2 upstairs bedrooms suite 1 suite 2 bedroom 3 bedroom 4 bathroom toilet attics groundfloor kitchen living rooms lounge dining room conservatory playroom wet room & toilet garage garden hot tub suite basement cellars wine cellar cinema The head of cleanup knows that her managers will report fractional completion of leaf tasks (tasks with no child tasks of their own), and she knows that she will want to modify the weight of values of completion as she sees fit. Some time into the cleaning, and some coverage reports have come in and she thinks see needs to weight the big house2 60-40 with respect to coverage from house1 She prefers a tabular view of her data where missing weights are assumed to be 1.0 and missing coverage 0.0. NAME_HIERARCHY |WEIGHT |COVERAGE | cleaning | | | house1 |40 | | bedrooms | |0.25 | bathrooms | | | bathroom1 | |0.5 | bathroom2 | | | outside_lavatory | |1 | attic | |0.75 | kitchen | |0.1 | living_rooms | | | lounge | | | dining_room | | | conservatory | | | playroom | |1 | basement | | | garage | | | garden | |0.8 | house2 |60 | | upstairs | | | bedrooms | | | suite_1 | | | suite_2 | | | bedroom_3 | | | bedroom_4 | | | bathroom | | | toilet | | | attics | |0.6 | groundfloor | | | kitchen | | | living_rooms | | | lounge | | | dining_room | | | conservatory | | | playroom | | | wet_room_&_toilet | | | garage | | | garden | |0.9 | hot_tub_suite | |1 | basement | | | cellars | |1 | wine_cellar | |1 | cinema | |0.75 | Calculation The coverage of a node in the tree is calculated as the weighted average of the coverage of its children evaluated bottom-upwards in the tree. The task is to calculate the overall coverage of the cleaning task and display the coverage at all levels of the hierarchy on this page, in a manner that visually shows the hierarchy, weights and coverage of all nodes. Extra Credit After calculating the coverage for all nodes, one can also calculate the additional/delta top level coverage that would occur if any (sub)task were to be fully covered from its current fractional coverage. This is done by multiplying the extra coverage that could be gained 1 − c o v e r a g e {\displaystyle 1-coverage} for any node, by the product of the `powers` of its parent nodes from the top down to the node. The power of a direct child of any parent is given by the power of the parent multiplied by the weight of the child divided by the sum of the weights of all the direct children. The pseudo code would be: method delta_calculation(this, power): sum_of_weights = sum(node.weight for node in children) this.delta = (1 - this.coverage) * power for node in self.children: node.delta_calculation(power * node.weight / sum_of_weights) return this.delta Followed by a call to: top.delta_calculation(power=1) Note: to aid in getting the data into your program you might want to use an alternative, more functional description of the starting data given on the discussion page.
#Kotlin
Kotlin
// version 1.2.10   class FCNode(val name: String, val weight: Int = 1, coverage: Double = 0.0) {   var coverage = coverage set(value) { if (field != value) { field = value // update any parent's coverage if (parent != null) parent!!.updateCoverage() } }   val children = mutableListOf<FCNode>() var parent: FCNode? = null   fun addChildren(nodes: List<FCNode>) { children.addAll(nodes) nodes.forEach { it.parent = this } updateCoverage() }   private fun updateCoverage() { val v1 = children.sumByDouble { it.weight * it.coverage } val v2 = children.sumBy { it.weight } coverage = v1 / v2 }   fun show(level: Int = 0) { val indent = level * 4 val nl = name.length + indent print(name.padStart(nl)) print("|".padStart(32 - nl)) print("  %3d |".format(weight)) println(" %8.6f |".format(coverage)) if (children.size == 0) return for (child in children) child.show(level + 1) } }   val houses = listOf( FCNode("house1", 40), FCNode("house2", 60) )   val house1 = listOf( FCNode("bedrooms", 1, 0.25), FCNode("bathrooms"), FCNode("attic", 1, 0.75), FCNode("kitchen", 1, 0.1), FCNode("living_rooms"), FCNode("basement"), FCNode("garage"), FCNode("garden", 1, 0.8) )   val house2 = listOf( FCNode("upstairs"), FCNode("groundfloor"), FCNode("basement") )   val h1Bathrooms = listOf( FCNode("bathroom1", 1, 0.5), FCNode("bathroom2"), FCNode("outside_lavatory", 1, 1.0) )   val h1LivingRooms = listOf( FCNode("lounge"), FCNode("dining_room"), FCNode("conservatory"), FCNode("playroom", 1, 1.0) )   val h2Upstairs = listOf( FCNode("bedrooms"), FCNode("bathroom"), FCNode("toilet"), FCNode("attics", 1, 0.6) )   val h2Groundfloor = listOf( FCNode("kitchen"), FCNode("living_rooms"), FCNode("wet_room_&_toilet"), FCNode("garage"), FCNode("garden", 1, 0.9), FCNode("hot_tub_suite", 1, 1.0) )   val h2Basement = listOf( FCNode("cellars", 1, 1.0), FCNode("wine_cellar", 1, 1.0), FCNode("cinema", 1, 0.75) )   val h2UpstairsBedrooms = listOf( FCNode("suite_1"), FCNode("suite_2"), FCNode("bedroom_3"), FCNode("bedroom_4") )   val h2GroundfloorLivingRooms = listOf( FCNode("lounge"), FCNode("dining_room"), FCNode("conservatory"), FCNode("playroom") )   fun main(args: Array<String>) { val cleaning = FCNode("cleaning")   house1[1].addChildren(h1Bathrooms) house1[4].addChildren(h1LivingRooms) houses[0].addChildren(house1)   h2Upstairs[0].addChildren(h2UpstairsBedrooms) house2[0].addChildren(h2Upstairs) h2Groundfloor[1].addChildren(h2GroundfloorLivingRooms) house2[1].addChildren(h2Groundfloor) house2[2].addChildren(h2Basement) houses[1].addChildren(house2)   cleaning.addChildren(houses) val topCoverage = cleaning.coverage println("TOP COVERAGE = ${"%8.6f".format(topCoverage)}\n") println("NAME HIERARCHY | WEIGHT | COVERAGE |") cleaning.show()   h2Basement[2].coverage = 1.0 // change Cinema node coverage to 1.0 val diff = cleaning.coverage - topCoverage println("\nIf the coverage of the Cinema node were increased from 0.75 to 1.0") print("the top level coverage would increase by ") println("${"%8.6f".format(diff)} to ${"%8.6f".format(topCoverage + diff)}") h2Basement[2].coverage = 0.75 // restore to original value if required }
http://rosettacode.org/wiki/Function_frequency
Function frequency
Display - for a program or runtime environment (whatever suits the style of your language) - the top ten most frequently occurring functions (or also identifiers or tokens, if preferred). This is a static analysis: The question is not how often each function is actually executed at runtime, but how often it is used by the programmer. Besides its practical usefulness, the intent of this task is to show how to do self-inspection within the language.
#BBC_BASIC
BBC BASIC
INSTALL @lib$+"SORTLIB" Sort% = FN_sortinit(1,0) : REM Descending   Valid$ = "0123456789@ABCDEFGHIJKLMNOPQRSTUVWXYZ_`abcdefghijklmnopqrstuvwxyz" DIM func$(1000), cnt%(1000) nFunc% = 0   file% = OPENIN("*.bbc") WHILE NOT EOF#file% ll% = BGET#file% no% = BGET#file% + 256*BGET#file% INPUT #file%, l$   i% = 1 REPEAT j% = INSTR(l$, CHR$&A4, i%) : REM Token for 'FN' k% = INSTR(l$, CHR$&F2, i%) : REM Token for 'PROC' IF k% IF j%=0 OR j%>k% THEN i% = k% f$ = "PROC" ELSE i% = j% f$ = "FN" ENDIF IF i% THEN REPEAT i% += 1 f$ += MID$(l$, i%, 1) UNTIL INSTR(Valid$, MID$(l$, i%+1, 1)) = 0 FOR j% = 0 TO nFunc%-1 IF f$ = func$(j%) EXIT FOR NEXT IF j% >= nFunc% nFunc% += 1 func$(j%) = f$ cnt%(j%) += 1 ENDIF UNTIL i%=0 ENDWHILE CLOSE #file%   C% = nFunc% CALL Sort%, cnt%(0), func$(0)   IF C% > 10 C% = 10 FOR i% = 0 TO C%-1 PRINT func$(i%) " (" ; cnt%(i%) ")" NEXT
http://rosettacode.org/wiki/Function_frequency
Function frequency
Display - for a program or runtime environment (whatever suits the style of your language) - the top ten most frequently occurring functions (or also identifiers or tokens, if preferred). This is a static analysis: The question is not how often each function is actually executed at runtime, but how often it is used by the programmer. Besides its practical usefulness, the intent of this task is to show how to do self-inspection within the language.
#C
C
  #define _POSIX_SOURCE #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <stddef.h> #include <sys/mman.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> struct functionInfo { char* name; int timesCalled; char marked; }; void addToList(struct functionInfo** list, struct functionInfo toAdd, \ size_t* numElements, size_t* allocatedSize) { static const char* keywords[32] = {"auto", "break", "case", "char", "const", \ "continue", "default", "do", "double", \ "else", "enum", "extern", "float", "for", \ "goto", "if", "int", "long", "register", \ "return", "short", "signed", "sizeof", \ "static", "struct", "switch", "typedef", \ "union", "unsigned", "void", "volatile", \ "while" }; int i; /* If the "function" being called is actually a keyword, then ignore it */ for (i = 0; i < 32; i++) { if (!strcmp(toAdd.name, keywords[i])) { return; } } if (!*list) { *allocatedSize = 10; *list = calloc(*allocatedSize, sizeof(struct functionInfo)); if (!*list) { printf("Failed to allocate %lu elements of %lu bytes each.\n", \ *allocatedSize, sizeof(struct functionInfo)); abort(); } (*list)[0].name = malloc(strlen(toAdd.name)+1); if (!(*list)[0].name) { printf("Failed to allocate %lu bytes.\n", strlen(toAdd.name)+1); abort(); } strcpy((*list)[0].name, toAdd.name); (*list)[0].timesCalled = 1; (*list)[0].marked = 0; *numElements = 1; } else { char found = 0; unsigned int i; for (i = 0; i < *numElements; i++) { if (!strcmp((*list)[i].name, toAdd.name)) { found = 1; (*list)[i].timesCalled++; break; } } if (!found) { struct functionInfo* newList = calloc((*allocatedSize)+10, \ sizeof(struct functionInfo)); if (!newList) { printf("Failed to allocate %lu elements of %lu bytes each.\n", \ (*allocatedSize)+10, sizeof(struct functionInfo)); abort(); } memcpy(newList, *list, (*allocatedSize)*sizeof(struct functionInfo)); free(*list); *allocatedSize += 10; *list = newList; (*list)[*numElements].name = malloc(strlen(toAdd.name)+1); if (!(*list)[*numElements].name) { printf("Failed to allocate %lu bytes.\n", strlen(toAdd.name)+1); abort(); } strcpy((*list)[*numElements].name, toAdd.name); (*list)[*numElements].timesCalled = 1; (*list)[*numElements].marked = 0; (*numElements)++; } } } void printList(struct functionInfo** list, size_t numElements) { char maxSet = 0; unsigned int i; size_t maxIndex = 0; for (i = 0; i<10; i++) { maxSet = 0; size_t j; for (j = 0; j<numElements; j++) { if (!maxSet || (*list)[j].timesCalled > (*list)[maxIndex].timesCalled) { if (!(*list)[j].marked) { maxSet = 1; maxIndex = j; } } } (*list)[maxIndex].marked = 1; printf("%s() called %d times.\n", (*list)[maxIndex].name, \ (*list)[maxIndex].timesCalled); } } void freeList(struct functionInfo** list, size_t numElements) { size_t i; for (i = 0; i<numElements; i++) { free((*list)[i].name); } free(*list); } char* extractFunctionName(char* readHead) { char* identifier = readHead; if (isalpha(*identifier) || *identifier == '_') { while (isalnum(*identifier) || *identifier == '_') { identifier++; } } /* Search forward for spaces and then an open parenthesis * but do not include this in the function name. */ char* toParen = identifier; if (toParen == readHead) return NULL; while (isspace(*toParen)) { toParen++; } if (*toParen != '(') return NULL; /* Copy the found function name to the output string */ ptrdiff_t size = (ptrdiff_t)((ptrdiff_t)identifier) \ - ((ptrdiff_t)readHead)+1; char* const name = malloc(size); if (!name) { printf("Failed to allocate %lu bytes.\n", size); abort(); } name[size-1] = '\0'; memcpy(name, readHead, size-1); /* Function names can't be blank */ if (strcmp(name, "")) { return name; } free(name); return NULL; } int main(int argc, char** argv) { int i; for (i = 1; i<argc; i++) { errno = 0; FILE* file = fopen(argv[i], "r"); if (errno || !file) { printf("fopen() failed with error code \"%s\"\n", \ strerror(errno)); abort(); } char comment = 0; #define DOUBLEQUOTE 1 #define SINGLEQUOTE 2 int string = 0; struct functionInfo* functions = NULL; struct functionInfo toAdd; size_t numElements = 0; size_t allocatedSize = 0; struct stat metaData; errno = 0; if (fstat(fileno(file), &metaData) < 0) { printf("fstat() returned error \"%s\"\n", strerror(errno)); abort(); } char* mmappedSource = (char*)mmap(NULL, metaData.st_size, PROT_READ, \ MAP_PRIVATE, fileno(file), 0); if (errno) { printf("mmap() failed with error \"%s\"\n", strerror(errno)); abort(); } if (!mmappedSource) { printf("mmap() returned NULL.\n"); abort(); } char* readHead = mmappedSource; while (readHead < mmappedSource + metaData.st_size) { while (*readHead) { /* Ignore comments inside strings */ if (!string) { if (*readHead == '/' && !strncmp(readHead, "/*", 2)) { comment = 1; } if (*readHead == '*' && !strncmp(readHead, "*/", 2)) { comment = 0; } } /* Ignore strings inside comments */ if (!comment) { if (*readHead == '"') { if (!string) { string = DOUBLEQUOTE; } else if (string == DOUBLEQUOTE) { /* Only toggle string mode if the quote character * is not escaped */ if (strncmp((readHead-1), "\\\"", 2)) { string = 0; } } } if (*readHead == '\'') { if (!string) { string = SINGLEQUOTE; } else if (string == SINGLEQUOTE) { if (strncmp((readHead-1), "\\\'", 2)) { string = 0; } } } } /* Look for identifiers outside of any comment or string */ if (!comment && !string) { char* name = extractFunctionName(readHead); /* Don't read part of an identifier on the next iteration */ if (name) { toAdd.name = name; addToList(&functions, toAdd, &numElements, &allocatedSize); readHead += strlen(name); } free(name); } readHead++; } } errno = 0; munmap(mmappedSource, metaData.st_size); if (errno) { printf("munmap() returned error \"%s\"\n", strerror(errno)); abort(); } errno = 0; fclose(file); if (errno) { printf("fclose() returned error \"%s\"\n", strerror(errno)); abort(); } printList(&functions, numElements); freeList(&functions, numElements); } return 0; }
http://rosettacode.org/wiki/Gamma_function
Gamma function
Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function. The Gamma function can be defined as: Γ ( x ) = ∫ 0 ∞ t x − 1 e − t d t {\displaystyle \Gamma (x)=\displaystyle \int _{0}^{\infty }t^{x-1}e^{-t}dt} This suggests a straightforward (but inefficient) way of computing the Γ {\displaystyle \Gamma } through numerical integration. Better suggested methods: Lanczos approximation Stirling's approximation
#Arturo
Arturo
A: @[ 1.00000000000000000000 0.57721566490153286061 neg 0.65587807152025388108 neg 0.04200263503409523553 0.16653861138229148950 neg 0.04219773455554433675 neg 0.00962197152787697356 0.00721894324666309954 neg 0.00116516759185906511 neg 0.00021524167411495097 0.00012805028238811619 neg 0.00002013485478078824 neg 0.00000125049348214267 0.00000113302723198170 neg 0.00000020563384169776 0.00000000611609510448 0.00000000500200764447 neg 0.00000000118127457049 0.00000000010434267117 0.00000000000778226344 neg 0.00000000000369680562 0.00000000000051003703 neg 0.00000000000002058326 neg 0.00000000000000534812 0.00000000000000122678 neg 0.00000000000000011813 0.00000000000000000119 0.00000000000000000141 neg 0.00000000000000000023 0.00000000000000000002 ]   ourGamma: function [x][ y: x - 1 result: last A loop ((size A)-1)..0 'n -> result: (result*y) + get A n result: 1 // result return result ]   loop 1..10 'z [ v1: ourGamma z // 3 v2: gamma z // 3 print [ pad (to :string z)++" =>" 10 pad (to :string v1)++" ~" 30 pad (to :string v2)++" :" 30 pad (to :string v1-v2) 30 ] ]
http://rosettacode.org/wiki/Galton_box_animation
Galton box animation
Example of a Galton Box at the end of animation. A   Galton device   Sir Francis Galton's device   is also known as a   bean machine,   a   Galton Board,   or a   quincunx. Description of operation In a Galton box, there are a set of pins arranged in a triangular pattern.   A number of balls are dropped so that they fall in line with the top pin, deflecting to the left or the right of the pin.   The ball continues to fall to the left or right of lower pins before arriving at one of the collection points between and to the sides of the bottom row of pins. Eventually the balls are collected into bins at the bottom   (as shown in the image),   the ball column heights in the bins approximate a   bell curve.   Overlaying   Pascal's triangle   onto the pins shows the number of different paths that can be taken to get to each bin. Task Generate an animated simulation of a Galton device. Task requirements   The box should have at least 5 pins on the bottom row.   A solution can use graphics or ASCII animation.   Provide a sample of the output/display such as a screenshot.   There can be one or more balls in flight at the same time.   If multiple balls are in flight, ensure they don't interfere with each other.   A solution should allow users to specify the number of balls, or it should run until full or a preset limit.   Optionally,   display the number of balls.
#D
D
import std.stdio, std.algorithm, std.random, std.array;   enum int boxW = 41, boxH = 37; // Galton box width and height. enum int pinsBaseW = 19; // Pins triangle base size. enum int nMaxBalls = 55; // Number of balls.   static assert(boxW >= 2 && boxH >= 2); static assert((boxW - 4) >= (pinsBaseW * 2 - 1)); static assert((boxH - 3) >= pinsBaseW); enum centerH = pinsBaseW + (boxW - (pinsBaseW * 2 - 1)) / 2 - 1;   enum Cell : char { empty = ' ', ball = 'o', wall = '|', corner = '+', floor = '-', pin = '.' }   Cell[boxW][boxH] box; // Galton box. Will be printed upside-down.   struct Ball { int x, y; // Position.   this(in int x_, in int y_) nothrow @safe @nogc in { assert(box[y_][x_] == Cell.empty); } body { this.x = x_; this.y = y_; box[y][x] = Cell.ball; }   nothrow const @safe @nogc invariant { assert(x >= 0 && x < boxW && y >= 0 && y < boxH); assert(box[y][x] == Cell.ball); }   void doStep() { if (y <= 0) return; // Reached the bottom of the box.   final switch (box[y - 1][x]) with (Cell) { case empty: box[y][x] = Cell.empty; y--; box[y][x] = Cell.ball; break; case ball, wall, corner, floor: // It's frozen. (It always piles on other balls). break; case pin: box[y][x] = Cell.empty; y--; if (box[y][x - 1] == Cell.empty && box[y][x + 1] == Cell.empty) { x += uniform(0, 2) * 2 - 1; box[y][x] = Cell.ball; return; } else if (box[y][x - 1] == Cell.empty) { x++; } else { x--; } box[y][x] = Cell.ball; break; } } }   void initializeBox() { // Set ceiling and floor: box[0][] = Cell.corner ~ [Cell.floor].replicate(boxW - 2) ~ Cell.corner; box[$ - 1][] = box[0][];   // Set walls: foreach (immutable r; 1 .. boxH - 1) box[r][0] = box[r][$ - 1] = Cell.wall;   // Set pins: foreach (immutable nPins; 1 .. pinsBaseW + 1) foreach (pin; 0 .. nPins) box[boxH - 2 - nPins][centerH + 1 - nPins + pin * 2] = Cell.pin; }   void drawBox() { foreach_reverse (const ref row; box) writefln("%(%c%)", row); }   void main() { initializeBox; Ball[] balls;   foreach (const i; 0 .. nMaxBalls + boxH) { writefln("\nStep %d:", i); if (i < nMaxBalls) balls ~= Ball(centerH, boxH - 2); // Add ball. drawBox;   // Next step for the simulation. // Frozen balls are kept in balls array for simplicity. foreach (ref b; balls) b.doStep; } }
http://rosettacode.org/wiki/Gapful_numbers
Gapful numbers
Numbers   (positive integers expressed in base ten)   that are (evenly) divisible by the number formed by the first and last digit are known as   gapful numbers. Evenly divisible   means divisible with   no   remainder. All   one─   and two─digit   numbers have this property and are trivially excluded.   Only numbers   ≥ 100   will be considered for this Rosetta Code task. Example 187   is a   gapful   number because it is evenly divisible by the number   17   which is formed by the first and last decimal digits of   187. About   7.46%   of positive integers are   gapful. Task   Generate and show all sets of numbers (below) on one line (horizontally) with a title,   here on this page   Show the first   30   gapful numbers   Show the first   15   gapful numbers   ≥          1,000,000   Show the first   10   gapful numbers   ≥   1,000,000,000 Related tasks   Harshad or Niven series.   palindromic gapful numbers.   largest number divisible by its digits. Also see   The OEIS entry:   A108343 gapful numbers.   numbersaplenty gapful numbers
#Delphi
Delphi
-module(gapful). -export([first_digit/1, last_digit/1, bookend_number/1, is_gapful/1]).   first_digit(N) -> list_to_integer(string:slice(integer_to_list(N),0,1)).   last_digit(N) -> N rem 10.   bookend_number(N) -> 10 * first_digit(N) + last_digit(N).   is_gapful(N) -> (N >= 100) and (0 == N rem bookend_number(N)).
http://rosettacode.org/wiki/Gaussian_elimination
Gaussian elimination
Task Solve   Ax=b   using Gaussian elimination then backwards substitution. A   being an   n by n   matrix. Also,   x and b   are   n by 1   vectors. To improve accuracy, please use partial pivoting and scaling. See also   the Wikipedia entry:   Gaussian elimination
#F.23
F#
  // Gaussian Elimination. Nigel Galloway: February 2nd., 2019 let gelim augM= let f=List.length augM let fG n (g:bigint list) t=n|>List.map(fun n->List.map2(fun n g->g-n)(List.map(fun n->n*g.[t])n)(List.map(fun g->g*n.[t])g)) let rec fN i (g::e as l)= match i with i when i=f->l|>List.mapi(fun n (g:bigint list)->(g.[f],g.[n])) |_->fN (i+1) (fG e g i@[g]) fN 0 augM  
http://rosettacode.org/wiki/Generate_random_chess_position
Generate random chess position
Task Generate a random chess position in FEN format. The position does not have to be realistic or even balanced,  but it must comply to the following rules: there is one and only one king of each color  (one black king and one white king); the kings must not be placed on adjacent squares; there can not be any pawn in the promotion square  (no white pawn in the eighth rank, and no black pawn in the first rank); including the kings, up to 32 pieces of either color can be placed. There is no requirement for material balance between sides. The picking of pieces does not have to comply to a regular chess set --- there can be five knights, twenty rooks, whatever ... as long as the total number of pieces do not exceed thirty-two. it is white's turn. It's assumed that both sides have lost castling rights and that there is no possibility for   en passant   (the FEN should thus end in w - - 0 1). No requirement is made regarding the probability distribution of your method, but your program should be able to span a reasonably representative sample of all possible positions. For instance, programs that would always generate positions with say five pieces on the board, or with kings on a corner, would not be considered truly random.
#Yabasic
Yabasic
dim grid(8, 8)   sub placeKings() local r1, r2, c1, c2   do r1 = int(ran(8)) c1 = int(ran(8)) r2 = int(ran(8)) c2 = int(ran(8)) if (r1 <> r2 and abs(r1 - r2) > 1 and abs(c1 - c2) > 1) then grid(r1, c1) = asc("K") grid(r2, c2) = asc("k") return end if loop end sub   sub placePieces(pieces$, isPawn) local n, r, c, numToPlace   numToPlace = int(ran(len(pieces$))) for n = 0 to numToPlace-1 repeat r = int(ran(8)) c = int(ran(8)) until(not(grid(r, c) or (isPawn and (r = 7 or r = 0)))) grid(r, c) = asc(mid$(pieces$, n, 1)) next end sub   sub toFen() local fen$, ch, r, c, countEmpty   for r = 0 to 8-1 for c = 0 to 8-1 ch = grid(r, c) if ch then print chr$(ch); else print "."; end if if not ch then countEmpty = countEmpty + 1 else if countEmpty then fen$ = fen$ + chr$(countEmpty + 48) countEmpty = 0 end if fen$ = fen$ + chr$(ch) end if next if countEmpty then fen$ = fen$ + chr$(countEmpty + 48) countEmpty = 0 end if fen$ = fen$ + "/" print next fen$ = fen$ + " w - - 0 1" print fen$ end sub   sub createFen() placeKings() placePieces("PPPPPPPP", TRUE) placePieces("pppppppp", TRUE) placePieces("RNBQBNR", FALSE) placePieces("rnbqbnr", FALSE) toFen() end sub   createFen()  
http://rosettacode.org/wiki/Generate_random_chess_position
Generate random chess position
Task Generate a random chess position in FEN format. The position does not have to be realistic or even balanced,  but it must comply to the following rules: there is one and only one king of each color  (one black king and one white king); the kings must not be placed on adjacent squares; there can not be any pawn in the promotion square  (no white pawn in the eighth rank, and no black pawn in the first rank); including the kings, up to 32 pieces of either color can be placed. There is no requirement for material balance between sides. The picking of pieces does not have to comply to a regular chess set --- there can be five knights, twenty rooks, whatever ... as long as the total number of pieces do not exceed thirty-two. it is white's turn. It's assumed that both sides have lost castling rights and that there is no possibility for   en passant   (the FEN should thus end in w - - 0 1). No requirement is made regarding the probability distribution of your method, but your program should be able to span a reasonably representative sample of all possible positions. For instance, programs that would always generate positions with say five pieces on the board, or with kings on a corner, would not be considered truly random.
#zkl
zkl
fcn pickFEN{ # First we chose how many pieces to place: 2 to 32 n := (0).random(2,33);   # Then we pick $n squares: first n of shuffle (0,1,2,3...63) n = [0..63].walk().shuffle()[0,n];   # We try to find suitable king positions on non-adjacent squares. # If we could not find any, we return recursively kings := Walker.cproduct(n,n).filter1(fcn([(a,b)]){ // Cartesian product a!=b and (a/8 - b/8).abs() or (a%8 - b%8).abs()>1 }); # (a,b) on success, False on fail if(not kings) return(pickFEN()); // tail recursion   # We make a list of pieces we can pick (apart from the kings) pieces,pnp,pnP := "p P n N b B r R q Q".split(" "), pieces-"p", pieces-"P";   # We make a list of two king symbols to pick randomly a black or white king k := "K k".split(" ").shuffle();   [0..63].apply('wrap(sq){ # look at each square if(kings.holds(sq)) k.pop(); else if(n.holds(sq)){ row,n,n2 := 7 - sq/8, (0).random(pieces.len()), (0).random(pnp.len()); if( row == 7) pnP[n2] // no white pawn in the promotion square else if(row == 0) pnp[n2] // no black pawn in the promotion square else pieces[n] // otherwise, any ole random piece } else "#" // empty square }) .pump(List,T(Void.Read,7),"".append,subst) // chunkize into groups of 8 chars (1 row) .concat("/") + " w - - 0 1" } fcn subst(str){ // replace "#" with count of #s re :=RegExp("#+"); while(re.search(str,1)){ n,m:=re.matched[0]; str=String(str[0,n],m,str[n+m,*]) } str }
http://rosettacode.org/wiki/Gauss-Jordan_matrix_inversion
Gauss-Jordan matrix inversion
Task Invert matrix   A   using Gauss-Jordan method. A   being an   n × n   matrix.
#jq
jq
# Create an m x n matrix, # it being understood that: # matrix(0; _; _) evaluates to [] def matrix(m; n; init): if m == 0 then [] elif m == 1 then [[range(0;n) | init]] elif m > 0 then [range(0;n) | init] as $row | [range(0;m) | $row ] else error("matrix\(m);_;_) invalid") end;   def mprint($dec): def max(s): reduce s as $x (null; if . == null or $x > . then $x else . end); def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;   pow(10; $dec) as $power | def p: (. * $power | round) / $power; (max(.[][] | p | tostring | length) + 1) as $w | . as $in | range(0; length) as $i | reduce range(0; .[$i]|length) as $j ("|"; . + ($in[$i][$j]|p|lpad($w))) | . + " |" ;   # Swaps two rows of the input matrix using IO==0 def swapRows(rowNum1; rowNum2): if (rowNum1 == rowNum2) then . else .[rowNum1] as $t | .[rowNum1] = .[rowNum2] | .[rowNum2] = $t end;   def toReducedRowEchelonForm: . as $in | length as $nr | (.[0]|length) as $nc | {a: $in, lead: 0 } | label $out | last(foreach range(0; $nr) as $r (.; if $nc <= .lead then ., break $out else . end | .i = $r | until( .a[.i][.lead] != 0; .i += 1 | if $nr == .i then .i = $r | .lead += 1 | if ($nc == .lead) then ., break $out else . end else . end ) | swapRows(.i; $r) | if .a[$r][.lead] != 0 then .a[$r][.lead] as $div | reduce range(0; $nc) as $j (.; .a[$r][$j] /= $div) else . end | reduce range(0; $nr) as $k (.; if $k != $r then .a[$k][.lead] as $mult | reduce range(0; $nc) as $j (.; .a[$k][$j] -= .a[$r][$j] * $mult) else . end) | .lead += 1 )) | .a ;     # Assumption: the input is a square matrix with an inverse # Uses the Gauss-Jordan method. def inverse: . as $a | length as $nr | reduce range(0; $nr) as $i ( matrix($nr; 2 * $nr; 0); reduce range( 0; $nr) as $j (.; .[$i][$j] = $a[$i][$j] | .[$i][$i + $nr] = 1 )) | last(toReducedRowEchelonForm) | . as $ary | reduce range(0; $nr) as $i ( matrix($nr; $nr; 0); reduce range($nr; 2 *$nr) as $j (.; .[$i][$j - $nr] = $ary[$i][$j] )) ;
http://rosettacode.org/wiki/General_FizzBuzz
General FizzBuzz
Task Write a generalized version of FizzBuzz that works for any list of factors, along with their words. This is basically a "fizzbuzz" implementation where the user supplies the parameters. The user will enter the max number, then they will enter the factors to be calculated along with the corresponding word to be printed. For simplicity's sake, assume the user will input an integer as the max number and 3 factors, each with a word associated with them. For example, given: >20 #This is the maximum number, supplied by the user >3 Fizz #The user now enters the starting factor (3) and the word they want associated with it (Fizz) >5 Buzz #The user now enters the next factor (5) and the word they want associated with it (Buzz) >7 Baxx #The user now enters the next factor (7) and the word they want associated with it (Baxx) In other words: For this example, print the numbers 1 through 20, replacing every multiple of 3 with "Fizz", every multiple of 5 with "Buzz", and every multiple of 7 with "Baxx". In the case where a number is a multiple of at least two factors, print each of the words associated with those factors in the order of least to greatest factor. For instance, the number 15 is a multiple of both 3 and 5; print "FizzBuzz". If the max number was 105 instead of 20, you would print "FizzBuzzBaxx" because it's a multiple of 3, 5, and 7. Output: 1 2 Fizz 4 Buzz Fizz Baxx 8 Fizz Buzz 11 Fizz 13 Baxx FizzBuzz 16 17 Fizz 19 Buzz
#Groovy
Groovy
def log = '' (1..40).each {Integer value -> log +=(value %3 == 0) ? (value %5 == 0)? 'FIZZBUZZ\n':(value %7 == 0)? 'FIZZBAXX\n':'FIZZ\n'  :(value %5 == 0) ? (value %7 == 0)? 'BUZBAXX\n':'BUZZ\n'  :(value %7 == 0) ?'BAXX\n'  :(value+'\n')} println log  
http://rosettacode.org/wiki/Hailstone_sequence
Hailstone sequence
The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the sequence   = (3 * n) + 1 The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates. This sequence was named by Lothar Collatz in 1937   (or possibly in 1939),   and is also known as (the):   hailstone sequence,   hailstone numbers   3x + 2 mapping,   3n + 1 problem   Collatz sequence   Hasse's algorithm   Kakutani's problem   Syracuse algorithm,   Syracuse problem   Thwaites conjecture   Ulam's problem The hailstone sequence is also known as   hailstone numbers   (because the values are usually subject to multiple descents and ascents like hailstones in a cloud). Task Create a routine to generate the hailstone sequence for a number. Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1 Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.   (But don't show the actual sequence!) See also   xkcd (humourous).   The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).   The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
#Wren
Wren
var hailstone = Fn.new { |n| if (n < 1) Fiber.abort("Parameter must be a positive integer.") var h = [n] while (n != 1) { n = (n%2 == 0) ? (n/2).floor : 3*n + 1 h.add(n) } return h }   var h = hailstone.call(27) System.print("For the Hailstone sequence starting with n = 27:") System.print(" Number of elements = %(h.count)") System.print(" First four elements = %(h[0..3])") System.print(" Final four elements = %(h[-4..-1])")   System.print("\nThe Hailstone sequence for n < 100,000 with the longest length is:") var longest = 0 var longlen = 0 for (n in 1..99999) { var h = hailstone.call(n) var c = h.count if (c > longlen) { longest = n longlen = c } } System.print(" Longest = %(longest)") System.print(" Length = %(longlen)")
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
Generate lower case ASCII alphabet
Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code. During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code: set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z} Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Common_Lisp
Common Lisp
(defvar *lower* (loop with a = (char-code #\a) for i below 26 collect (code-char (+ a i))))
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
Generate lower case ASCII alphabet
Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code. During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code: set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z} Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Cowgol
Cowgol
include "cowgol.coh";   # Generate the alphabet and store it at the given location # It is assumed that there is enough space (27 bytes) sub alph(buf: [uint8]): (out: [uint8]) is out := buf; var letter: uint8 := 'a'; while letter <= 'z' loop [buf] := letter; letter := letter + 1; buf := @next buf; end loop; [buf] := 0; end sub;   # Use the subroutine to print the alphabet var buf: uint8[27]; # make room for the alphabet print(alph(&buf as [uint8]));
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#Odin
Odin
package main import "core:fmt"   main :: proc() { fmt.println("Hellope!"); }
http://rosettacode.org/wiki/Generic_swap
Generic swap
Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericity. If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation. That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange. Generic swap is a task which brings together a few separate issues in programming language semantics. Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places. Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities. Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism). Do your best!
#Z80_Assembly
Z80 Assembly
push ix push iy pop ix ;the value that was once in IY is now in IX pop iy ;the value that was once in IX is now in IY
http://rosettacode.org/wiki/Generic_swap
Generic swap
Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericity. If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation. That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange. Generic swap is a task which brings together a few separate issues in programming language semantics. Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places. Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities. Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism). Do your best!
#zkl
zkl
class C{var v; fcn init(n){v=n}} var c1=C(1), c2=C(2); println(c1.v," : ",c2.v); fcn swap(ca,cb,name){ tmp:=ca.resove(name); ca.setVar(name,cb.resolve(name)); cb.setVar(name,tmp) } swap(c1,c2,"v"); println(c1.v," : ",c2.v);
http://rosettacode.org/wiki/Generator/Exponential
Generator/Exponential
A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided. Generators are often built on top of coroutines or objects so that the internal state of the object is handled “naturally”. Generators are often used in situations where a sequence is potentially infinite, and where it is possible to construct the next value of the sequence with only minimal state. Task Create a function that returns a generation of the m'th powers of the positive integers starting from zero, in order, and without obvious or simple upper limit. (Any upper limit to the generator should not be stated in the source but should be down to factors such as the languages natural integer size limit or computational time/size). Use it to create a generator of:   Squares.   Cubes. Create a new generator that filters all cubes from the generator of squares. Drop the first 20 values from this last generator of filtered results, and then show the next 10 values. Note that this task requires the use of generators in the calculation of the result. Also see Generator
#jq
jq
# Compute self^m where m is a non-negative integer: def pow(m): . as $in | reduce range(0;m) as $i (1; .*$in);   # state: [i, i^m] def next_power(m): .[0] + 1 | [., pow(m) ];
http://rosettacode.org/wiki/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related task   least common multiple. See also   MathWorld entry:   greatest common divisor.   Wikipedia entry:     greatest common divisor.
#Wortel
Wortel
@gcd a b
http://rosettacode.org/wiki/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related task   least common multiple. See also   MathWorld entry:   greatest common divisor.   Wikipedia entry:     greatest common divisor.
#Wren
Wren
var gcd = Fn.new { |x, y| while (y != 0) { var t = y y = x % y x = t } return x.abs }   System.print("gcd(33, 77) = %(gcd.call(33, 77))") System.print("gcd(49865, 69811) = %(gcd.call(49865, 69811))")
http://rosettacode.org/wiki/Generate_Chess960_starting_position
Generate Chess960 starting position
Chess960 is a variant of chess created by world champion Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints: as in the standard chess game, all eight white pawns must be placed on the second rank. White pieces must stand on the first rank as in the standard game, in random column order but with the two following constraints: the bishops must be placed on opposite color squares (i.e. they must be an odd number of spaces apart or there must be an even number of spaces between them) the King must be between two rooks (with any number of other pieces between them all) Black pawns and pieces must be placed respectively on the seventh and eighth ranks, mirroring the white pawns and pieces, just as in the standard game. (That is, their positions are not independently randomized.) With those constraints there are 960 possible starting positions, thus the name of the variant. Task The purpose of this task is to write a program that can randomly generate any one of the 960 Chess960 initial positions. You will show the result as the first rank displayed with Chess symbols in Unicode: ♔♕♖♗♘ or with the letters King Queen Rook Bishop kNight.
#Perl
Perl
sub rnd($) { int(rand(shift)) }   sub empties { grep !$_[0][$_], 0 .. 7 }   sub chess960 { my @s = (undef) x 8; @s[2*rnd(4), 1 + 2*rnd(4)] = qw/B B/;   for (qw/Q N N/) { my @idx = empties \@s; $s[$idx[rnd(@idx)]] = $_; }   @s[empties \@s] = qw/R K R/; @s } print "@{[chess960]}\n" for 0 .. 10;
http://rosettacode.org/wiki/Function_composition
Function composition
Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   g   to   x. Example compose(f, g) (x) = f(g(x)) Reference: Function composition Hint: In some languages, implementing compose correctly requires creating a closure.
#11l
11l
V compose = (f, g) -> (x -> @f(@g(x))) V sin_asin = compose(x -> sin(x), x -> asin(x)) print(sin_asin(0.5))
http://rosettacode.org/wiki/FTP
FTP
Task Connect to a server, change directory, list its contents and download a file as binary using the FTP protocol. Use passive mode if available.
#BaCon
BaCon
OPTION PARSE FALSE   PRAGMA INCLUDE <curl/curl.h> PRAGMA LDFLAGS -lcurl   DECLARE easyhandle TYPE CURL*   OPEN "data.txt" FOR WRITING AS download   easyhandle = curl_easy_init() curl_easy_setopt(easyhandle, CURLOPT_URL, "ftp://localhost/pub/data.txt") curl_easy_setopt(easyhandle, CURLOPT_WRITEDATA, download) curl_easy_setopt(easyhandle, CURLOPT_USERPWD, "anonymous") success = curl_easy_perform(easyhandle) curl_easy_cleanup(easyhandle)   CLOSE FILE download
http://rosettacode.org/wiki/Function_prototype
Function prototype
Some languages provide the facility to declare functions and subroutines through the use of function prototyping. Task Demonstrate the methods available for declaring prototypes within the language. The provided solutions should include: An explanation of any placement restrictions for prototype declarations A prototype declaration for a function that does not require arguments A prototype declaration for a function that requires two arguments A prototype declaration for a function that utilizes varargs A prototype declaration for a function that utilizes optional arguments A prototype declaration for a function that utilizes named parameters Example of prototype declarations for subroutines or procedures (if these differ from functions) An explanation and example of any special forms of prototyping not covered by the above Languages that do not provide function prototyping facilities should be omitted from this task.
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   ' The position regarding prototypes is broadly similar to that of the C language in that functions, ' sub-routines or operators (unless they have already been fully defined) must be declared before they can be used. ' This is usually done near the top of a file or in a separate header file which is then 'included'.   ' Parameter names are optional in declarations. When calling functions, using parameter names ' (as opposed to identifying arguments by position) is not supported.   Type MyType ' needed for operator declaration i As Integer End Type   Declare Function noArgs() As Integer ' function with no argument that returns an integer Declare Function twoArgs(As Integer, As Integer) As Integer ' function with two arguments that returns an integer Declare Function atLeastOneArg CDecl(As Integer, ...) As Integer ' one mandatory integer argument followed by varargs Declare Function optionalArg(As Integer = 0) As Integer ' function with a (single) optional argument with default value Declare Sub noArgs2() ' sub-routine with no argument Declare Operator + (As MyType, As MyType) As MyType ' operator declaration (no hidden 'This' parameter for MyType)     ' FreeBASIC also supports object-oriented programming and here all constructors, destructors, ' methods (function or sub), properties and operators (having a hidden 'This' parameter) must be ' declared within a user defined type and then defined afterwards.     Type MyType2 Public: Declare Constructor(As Integer) Declare Destructor() Declare Sub MySub() Declare Function MyFunction(As Integer) As Integer Declare Property MyProperty As Integer Declare Operator Cast() As String Private: i As Integer End Type
http://rosettacode.org/wiki/Function_prototype
Function prototype
Some languages provide the facility to declare functions and subroutines through the use of function prototyping. Task Demonstrate the methods available for declaring prototypes within the language. The provided solutions should include: An explanation of any placement restrictions for prototype declarations A prototype declaration for a function that does not require arguments A prototype declaration for a function that requires two arguments A prototype declaration for a function that utilizes varargs A prototype declaration for a function that utilizes optional arguments A prototype declaration for a function that utilizes named parameters Example of prototype declarations for subroutines or procedures (if these differ from functions) An explanation and example of any special forms of prototyping not covered by the above Languages that do not provide function prototyping facilities should be omitted from this task.
#Go
Go
func a() // function with no arguments func b(x, y int) // function with two arguments func c(...int) // varargs are called "variadic parameters" in Go.
http://rosettacode.org/wiki/Fusc_sequence
Fusc sequence
Definitions The   fusc   integer sequence is defined as:   fusc(0) = 0   fusc(1) = 1   for n>1,   the   nth   term is defined as:   if   n   is even;     fusc(n) = fusc(n/2)   if   n   is   odd;     fusc(n) = fusc((n-1)/2)   +   fusc((n+1)/2) Note that MathWorld's definition starts with unity, not zero.   This task will be using the OEIS' version   (above). An observation   fusc(A) = fusc(B) where   A   is some non-negative integer expressed in binary,   and where   B   is the binary value of   A   reversed. Fusc numbers are also known as:   fusc function   (named by Dijkstra, 1982)   Stern's Diatomic series   (although it starts with unity, not zero)   Stern-Brocot sequence   (although it starts with unity, not zero) Task   show the first   61   fusc numbers (starting at zero) in a horizontal format.   show the fusc number (and its index) whose length is greater than any previous fusc number length.   (the length is the number of decimal digits when the fusc number is expressed in base ten.)   show all numbers with commas   (if appropriate).   show all output here. Related task   RosettaCode Stern-Brocot sequence Also see   the MathWorld entry:   Stern's Diatomic Series.   the OEIS entry:   A2487.
#ALGOL_68
ALGOL 68
BEGIN # calculate some members of the fusc sequence # # f0 = 0, f1 = 1, fn = f(n/2) if n even # # = f(n-1)/2) + f((n+1)/2) if n odd #   # constructs an array of the first n elements of the fusc sequence # PROC fusc sequence = ( INT n )[]INT: BEGIN [ 0 : n ]INT a; IF n > 0 THEN a[ 0 ] := 0; IF n > 1 THEN a[ 1 ] := 1; INT i2 := 1; FOR i FROM 2 BY 2 TO n - 1 DO a[ i ] := a[ i2 ]; a[ i + 1 ] := a[ # j - i # i2 ] + a[ # ( j + 1 ) OVER 2 # i2 + 1 ]; i2 +:= 1 OD FI FI; a[ 0 : n - 1 AT 0 ] END ; # fusc #   []INT f = fusc sequence( 800 000 ); FOR i FROM 0 TO 60 DO print( ( " ", whole( f[ i ], 0 ) ) ) OD; print( ( newline ) ); # find the lowest elements of the sequence that have 1, 2, 3, etc. digits # print( ( "Sequence elements where number of digits of the value increase:", newline ) ); print( ( " n fusc(n)", newline ) ); INT digit power := 0; FOR i FROM LWB f TO UPB f DO IF f[ i ] >= digit power THEN # found the first number with this many digits # print( ( whole( i, -8 ), " ", whole( f[ i ], -10 ), newline ) ); IF digit power = 0 THEN digit power := 1 FI; digit power *:= 10 FI OD END
http://rosettacode.org/wiki/Functional_coverage_tree
Functional coverage tree
Functional coverage is a measure of how much a particular function of a system has been verified as correct. It is used heavily in tracking the completeness of the verification of complex System on Chip (SoC) integrated circuits, where it can also be used to track how well the functional requirements of the system have been verified. This task uses a sub-set of the calculations sometimes used in tracking functional coverage but uses a more familiar(?) scenario. Task Description The head of the clean-up crews for "The Men in a very dark shade of grey when viewed at night" has been tasked with managing the cleansing of two properties after an incident involving aliens. She arranges the task hierarchically with a manager for the crews working on each house who return with a breakdown of how they will report on progress in each house. The overall hierarchy of (sub)tasks is as follows, cleaning house1 bedrooms bathrooms bathroom1 bathroom2 outside lavatory attic kitchen living rooms lounge dining room conservatory playroom basement garage garden house2 upstairs bedrooms suite 1 suite 2 bedroom 3 bedroom 4 bathroom toilet attics groundfloor kitchen living rooms lounge dining room conservatory playroom wet room & toilet garage garden hot tub suite basement cellars wine cellar cinema The head of cleanup knows that her managers will report fractional completion of leaf tasks (tasks with no child tasks of their own), and she knows that she will want to modify the weight of values of completion as she sees fit. Some time into the cleaning, and some coverage reports have come in and she thinks see needs to weight the big house2 60-40 with respect to coverage from house1 She prefers a tabular view of her data where missing weights are assumed to be 1.0 and missing coverage 0.0. NAME_HIERARCHY |WEIGHT |COVERAGE | cleaning | | | house1 |40 | | bedrooms | |0.25 | bathrooms | | | bathroom1 | |0.5 | bathroom2 | | | outside_lavatory | |1 | attic | |0.75 | kitchen | |0.1 | living_rooms | | | lounge | | | dining_room | | | conservatory | | | playroom | |1 | basement | | | garage | | | garden | |0.8 | house2 |60 | | upstairs | | | bedrooms | | | suite_1 | | | suite_2 | | | bedroom_3 | | | bedroom_4 | | | bathroom | | | toilet | | | attics | |0.6 | groundfloor | | | kitchen | | | living_rooms | | | lounge | | | dining_room | | | conservatory | | | playroom | | | wet_room_&_toilet | | | garage | | | garden | |0.9 | hot_tub_suite | |1 | basement | | | cellars | |1 | wine_cellar | |1 | cinema | |0.75 | Calculation The coverage of a node in the tree is calculated as the weighted average of the coverage of its children evaluated bottom-upwards in the tree. The task is to calculate the overall coverage of the cleaning task and display the coverage at all levels of the hierarchy on this page, in a manner that visually shows the hierarchy, weights and coverage of all nodes. Extra Credit After calculating the coverage for all nodes, one can also calculate the additional/delta top level coverage that would occur if any (sub)task were to be fully covered from its current fractional coverage. This is done by multiplying the extra coverage that could be gained 1 − c o v e r a g e {\displaystyle 1-coverage} for any node, by the product of the `powers` of its parent nodes from the top down to the node. The power of a direct child of any parent is given by the power of the parent multiplied by the weight of the child divided by the sum of the weights of all the direct children. The pseudo code would be: method delta_calculation(this, power): sum_of_weights = sum(node.weight for node in children) this.delta = (1 - this.coverage) * power for node in self.children: node.delta_calculation(power * node.weight / sum_of_weights) return this.delta Followed by a call to: top.delta_calculation(power=1) Note: to aid in getting the data into your program you might want to use an alternative, more functional description of the starting data given on the discussion page.
#Lua
Lua
-- DATA: local function node(name, weight, coverage, children) return { name=name, weight=weight or 1.0, coverage=coverage or 0.0, sumofweights=0, delta=0, children=children } end   local root = node("cleaning", nil, nil, { node("house1", 40, nil, { node("bedrooms", nil, 0.25), node("bathrooms", nil, nil, { node("bathroom1", nil, 0.5), node("bathroom2"), node("outside_lavatory", nil, 1) }), node("attic", nil, 0.75), node("kitchen", nil, 0.1), node("living_rooms", nil, nil, { node("lounge"), node("dining_room"), node("conservatory"), node("playroom",nil,1) }), node("basement"), node("garage"), node("garden", nil, 0.8) }), node("house2", 60, nil, { node("upstairs", nil, nil, { node("bedrooms", nil, nil, { node("suite_1"), node("suite_2"), node("bedroom_3"), node("bedroom_4") }), node("bathroom"), node("toilet"), node("attics", nil, 0.6) }), node("groundfloor", nil, nil, { node("kitchen"), node("living_rooms", nil, nil, { node("lounge"), node("dining_room"), node("conservatory"), node("playroom") }), node("wet_room_&_toilet"), node("garage"), node("garden", nil, 0.9), node("hot_tub_suite", nil, 1) }), node("basement", nil, nil, { node("cellars", nil, 1), node("wine_cellar", nil, 1), node("cinema", nil, 0.75) }) }) })   -- TASK: local function calccover(node) if (node.children) then local cnt, sum = 0, 0 for _,child in ipairs(node.children) do local ccnt, csum = calccover(child) cnt, sum = cnt+ccnt, sum+csum end node.coverage = sum/cnt node.sumofweights = cnt -- just as prep for extra credit end return node.weight, node.coverage * node.weight end calccover(root)   -- EXTRA CREDIT: local function calcdelta(node, power) node.delta = (1.0 - node.coverage) * power if (node.children) then for _,child in ipairs(node.children) do calcdelta(child, power * child.weight / node.sumofweights) end end end calcdelta(root,1)   -- OUTPUT: local function printnode(node, space) print(string.format("%-32s|  %3.f | %8.6f | %8.6f |", string.rep(" ",space)..node.name, node.weight, node.coverage, node.delta)) if node.children then for _,child in ipairs(node.children) do printnode(child,space+4) end end end print("NAME_HIERARCHY |WEIGHT |COVERAGE |DELTA |") printnode(root,0)
http://rosettacode.org/wiki/Function_frequency
Function frequency
Display - for a program or runtime environment (whatever suits the style of your language) - the top ten most frequently occurring functions (or also identifiers or tokens, if preferred). This is a static analysis: The question is not how often each function is actually executed at runtime, but how often it is used by the programmer. Besides its practical usefulness, the intent of this task is to show how to do self-inspection within the language.
#Common_Lisp
Common Lisp
(defun mapc-tree (fn tree) "Apply FN to all elements in TREE." (cond ((consp tree) (mapc-tree fn (car tree)) (mapc-tree fn (cdr tree))) (t (funcall fn tree))))   (defun count-source (source) "Load and count all function-bound symbols in a SOURCE file." (load source) (with-open-file (s source) (let ((table (make-hash-table))) (loop for data = (read s nil nil) while data do (mapc-tree (lambda (x) (when (and (symbolp x) (fboundp x)) (incf (gethash x table 0)))) data)) table)))   (defun hash-to-alist (table) "Convert a hashtable to an alist." (let ((alist)) (maphash (lambda (k v) (push (cons k v) alist)) table) alist))   (defun take (n list) "Take at most N elements from LIST." (loop repeat n for x in list collect x))   (defun top-10 (table) "Get the top 10 from the source counts TABLE." (take 10 (sort (hash-to-alist table) '> :key 'cdr)))
http://rosettacode.org/wiki/Gamma_function
Gamma function
Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function. The Gamma function can be defined as: Γ ( x ) = ∫ 0 ∞ t x − 1 e − t d t {\displaystyle \Gamma (x)=\displaystyle \int _{0}^{\infty }t^{x-1}e^{-t}dt} This suggests a straightforward (but inefficient) way of computing the Γ {\displaystyle \Gamma } through numerical integration. Better suggested methods: Lanczos approximation Stirling's approximation
#AutoHotkey
AutoHotkey
/* Here is the upper incomplete Gamma function. Omitting or setting the second parameter to 0 we get the (complete) Gamma function. The code is based on: "Computation of Special Functions" Zhang and Jin, John Wiley and Sons, 1996 */   SetFormat FloatFast, 0.9e   Loop 10 MsgBox % GAMMA(A_Index/3) "`n" GAMMA(A_Index*10)   GAMMA(a,x=0) { ; upper incomplete gamma: Integral(t**(a-1)*e**-t, t = x..inf) If (a > 171 || x < 0) Return 2.e308 ; overflow   xam := x > 0 ? -x+a*ln(x) : 0 If (xam > 700) Return 2.e308 ; overflow   If (x > 1+a) { ; no need for gamma(a) t0 := 0, k := 60 Loop 60 t0 := (k-a)/(1+k/(x+t0)), --k Return exp(xam) / (x+t0) }   r := 1, ga := 1.0 ; compute ga = gamma(a) ... If (a = round(a)) ; if integer: factorial If (a > 0) Loop % a-1 ga *= A_Index Else ; negative integer ga := 1.7976931348623157e+308 ; Dmax Else { ; not integer If (abs(a) > 1) { z := abs(a) m := floor(z) Loop %m% r *= (z-A_Index) z -= m } Else z := a   gr := ((((((((((((((((((((((( 0.14e-14 *z - 0.54e-14) *z - 0.206e-13) *z + 0.51e-12) *z - 0.36968e-11) *z + 0.77823e-11) *z + 0.1043427e-9) *z - 0.11812746e-8) *z + 0.50020075e-8) *z + 0.6116095e-8) *z - 0.2056338417e-6) *z + 0.1133027232e-5) *z - 0.12504934821e-5) *z - 0.201348547807e-4) *z + 0.1280502823882e-3) *z - 0.2152416741149e-3) *z - 0.11651675918591e-2) *z + 0.7218943246663e-2) *z - 0.9621971527877e-2) *z - 0.421977345555443e-1) *z + 0.1665386113822915) *z - 0.420026350340952e-1) *z - 0.6558780715202538) *z + 0.5772156649015329) *z + 1   ga := 1.0/(gr*z) * r If (a < -1) ga := -3.1415926535897931/(a*ga*sin(3.1415926535897931*a)) }   If (x = 0) ; complete gamma requested Return ga   s := 1/a ; here x <= 1+a r := s Loop 60 { r *= x/(a+A_Index) s += r If (abs(r/s) < 1.e-15) break } Return ga - exp(xam)*s }   /* The 10 results shown: 2.678938535e+000 1.354117939e+000 1.0 8.929795115e-001 9.027452930e-001 3.628800000e+005 1.216451004e+017 8.841761994e+030 2.039788208e+046 6.082818640e+062   1.000000000e+000 1.190639348e+000 1.504575489e+000 2.000000000e+000 2.778158479e+000 1.386831185e+080 1.711224524e+098 8.946182131e+116 1.650795516e+136 9.332621544e+155 */
http://rosettacode.org/wiki/Galton_box_animation
Galton box animation
Example of a Galton Box at the end of animation. A   Galton device   Sir Francis Galton's device   is also known as a   bean machine,   a   Galton Board,   or a   quincunx. Description of operation In a Galton box, there are a set of pins arranged in a triangular pattern.   A number of balls are dropped so that they fall in line with the top pin, deflecting to the left or the right of the pin.   The ball continues to fall to the left or right of lower pins before arriving at one of the collection points between and to the sides of the bottom row of pins. Eventually the balls are collected into bins at the bottom   (as shown in the image),   the ball column heights in the bins approximate a   bell curve.   Overlaying   Pascal's triangle   onto the pins shows the number of different paths that can be taken to get to each bin. Task Generate an animated simulation of a Galton device. Task requirements   The box should have at least 5 pins on the bottom row.   A solution can use graphics or ASCII animation.   Provide a sample of the output/display such as a screenshot.   There can be one or more balls in flight at the same time.   If multiple balls are in flight, ensure they don't interfere with each other.   A solution should allow users to specify the number of balls, or it should run until full or a preset limit.   Optionally,   display the number of balls.
#Elm
Elm
import Html.App exposing (program) import Time exposing (Time, every, millisecond) import Color exposing (Color, black, red, blue, green) import Collage exposing (collage) import Collage exposing (collage,polygon, filled, move, Form, circle) import Element exposing (toHtml) import Html exposing (Attribute, Html, text, div, input, button) import Html.Attributes as A exposing (type', min, placeholder, value, style, disabled) import Html.Events exposing (onInput, targetValue, onClick) import Dict exposing (Dict, get, insert) import String exposing (toInt) import Result exposing (withDefault) import Random.Pcg as Random exposing (Seed, bool, initialSeed, independentSeed, step, map)   width = 500 height = 600 hscale = 10.0 vscale = hscale * 2 margin = 30 levelCount = 12 radius = hscale/ 2.0   type State = InBox Int Int Seed | Falling Int Float Float Float | Landed Int Float   type Coin = Coin State Color   colorCycle : Int -> Color colorCycle i = case i % 3 of 0 -> red 1 -> blue _ -> green   initCoin : Int -> Seed -> Coin initCoin indx seed = Coin (InBox 0 0 seed) (colorCycle indx)   drawCoin : Coin -> Form drawCoin (Coin state color) = let dropLevel = toFloat (height//2 - margin) (level, shift, distance) = case state of InBox level shift seed -> (level, shift, 0) Falling shift distance _ _-> (levelCount, shift, distance) Landed shift distance -> (levelCount, shift, distance) position = ( hscale * toFloat shift , dropLevel - vscale * (toFloat level) - distance + radius / 2.0)   in radius |> circle |> filled color |> move position   drawGaltonBox : List Form drawGaltonBox = let levels = [0..levelCount-1]   -- doubles : -- [0,2,4,6,8...] doubles = List.map (\n -> 2 * n) levels   -- sequences : -- [[0], [0,2], [0,2,4], [0,2,4,6], [0,2,4,6,8],...] sequences = case List.tail (List.scanl (::) [] (doubles)) of Nothing -> [] Just ls -> ls   -- galtonCoords : -- [ (0,0), -- (-1,1), (1,1), -- (-2,2), (0,2), (2,2), -- (-3,3), (-1,3), (1,3), (3,3), -- (-4,4), (-2,4), (0,4), (2,4), (4,4), ...] galtonCoords = List.map2 (\ls level -> List.map (\n -> (n - level, level)) ls) sequences levels |> List.concat   peg = polygon [(0,0), (-4, -8), (4, -8)] |> filled black   apex = toFloat (height//2 - margin)   in List.map (\(x,y) -> move (hscale*toFloat x, apex - vscale*toFloat y) peg) galtonCoords   coinsInBin : Int -> Dict Int Int -> Int coinsInBin binNumber bins = case get binNumber bins of Nothing -> 0 Just n -> n   addToBins : Int -> Dict Int Int -> Dict Int Int addToBins binNumber bins = insert binNumber (coinsInBin binNumber bins + 1) bins   updateCoin : (Coin, Dict Int Int) -> (Coin, Dict Int Int) updateCoin (Coin state color as coin, bins) = case state of InBox level shift seed -> let deltaShift = map (\b -> if b then 1 else -1) bool (delta, newSeed) = step deltaShift seed newShift = shift+delta newLevel = (level)+1 in if (newLevel < levelCount) then (Coin (InBox newLevel newShift newSeed) color, bins) else -- transition to falling let maxDrop = toFloat (height - 2 * margin) - toFloat (levelCount) * vscale floor = maxDrop - toFloat (coinsInBin newShift bins) * (radius*2 + 1) in (Coin (Falling newShift -((vscale)/2.0) 10 floor) color, addToBins newShift bins)   Falling shift distance velocity floor -> let newDistance = distance + velocity in if (newDistance < floor) then (Coin (Falling shift newDistance (velocity + 1) floor) color, bins) else -- transtion to landed (Coin (Landed shift floor) color, bins)   Landed _ _ -> (coin, bins) -- unchanged   type alias Model = { coins : List Coin , bins : Dict Int Int , count : Int , started : Bool , seedInitialized : Bool , seed : Seed }   init : (Model, Cmd Msg) init = ( { coins = [] , bins = Dict.empty , count = 0 , started = False , seedInitialized = False , seed = initialSeed 45 -- This will not get used. Actual seed used is time dependent and set when the first coin drops. }, Cmd.none)   type Msg = Drop Time | Tick Time | SetCount String | Go   update : Msg -> Model -> (Model, Cmd Msg) update action model = case action of Go -> ({model | started = model.count > 0}, Cmd.none)   SetCount countString -> ({ model | count = toInt countString |> withDefault 0 }, Cmd.none)   Drop t -> if (model.started && model.count > 0) then let newcount = model.count - 1 seed' = if model.seedInitialized then model.seed else initialSeed (truncate t) (seed'', coinSeed) = step independentSeed seed' in ({ model | coins = initCoin (truncate t) coinSeed :: model.coins , count = newcount , started = newcount > 0 , seedInitialized = True , seed = seed''}, Cmd.none) else (model, Cmd.none)   Tick _ -> -- foldr to execute update, append to coins, replace bins let (updatedCoins, updatedBins) = List.foldr (\coin (coinList, bins) -> let (updatedCoin, updatedBins) = updateCoin (coin, bins) in (updatedCoin :: coinList, updatedBins)) ([], model.bins) model.coins in ({ model | coins = updatedCoins, bins = updatedBins}, Cmd.none)   view : Model -> Html Msg view model = div [] [ input [ placeholder "How many?" , let showString = if model.count > 0 then model.count |> toString else "" in value showString , onInput SetCount , disabled model.started , style [ ("height", "20px") ] , type' "number" , A.min "1" ] []   , button [ onClick Go , disabled model.started , style [ ("height", "20px") ] ] [ Html.text "GO!" ]   , let coinForms = (List.map (drawCoin) model.coins) in collage width height (coinForms ++ drawGaltonBox) |> toHtml ]   subscriptions model = Sub.batch [ every (40*millisecond) Tick , every (200*millisecond) Drop ]   main = program { init = init , view = view , update = update , subscriptions = subscriptions }
http://rosettacode.org/wiki/Gapful_numbers
Gapful numbers
Numbers   (positive integers expressed in base ten)   that are (evenly) divisible by the number formed by the first and last digit are known as   gapful numbers. Evenly divisible   means divisible with   no   remainder. All   one─   and two─digit   numbers have this property and are trivially excluded.   Only numbers   ≥ 100   will be considered for this Rosetta Code task. Example 187   is a   gapful   number because it is evenly divisible by the number   17   which is formed by the first and last decimal digits of   187. About   7.46%   of positive integers are   gapful. Task   Generate and show all sets of numbers (below) on one line (horizontally) with a title,   here on this page   Show the first   30   gapful numbers   Show the first   15   gapful numbers   ≥          1,000,000   Show the first   10   gapful numbers   ≥   1,000,000,000 Related tasks   Harshad or Niven series.   palindromic gapful numbers.   largest number divisible by its digits. Also see   The OEIS entry:   A108343 gapful numbers.   numbersaplenty gapful numbers
#Erlang
Erlang
-module(gapful). -export([first_digit/1, last_digit/1, bookend_number/1, is_gapful/1]).   first_digit(N) -> list_to_integer(string:slice(integer_to_list(N),0,1)).   last_digit(N) -> N rem 10.   bookend_number(N) -> 10 * first_digit(N) + last_digit(N).   is_gapful(N) -> (N >= 100) and (0 == N rem bookend_number(N)).
http://rosettacode.org/wiki/Gaussian_elimination
Gaussian elimination
Task Solve   Ax=b   using Gaussian elimination then backwards substitution. A   being an   n by n   matrix. Also,   x and b   are   n by 1   vectors. To improve accuracy, please use partial pivoting and scaling. See also   the Wikipedia entry:   Gaussian elimination
#Fortran
Fortran
  program ge   real, allocatable :: a(:,:),b(:) a = reshape( & [1.0, 1.00, 1.00, 1.00, 1.00, 1.00, & 0.0, 0.63, 1.26, 1.88, 2.51, 3.14, & 0.0, 0.39, 1.58, 3.55, 6.32, 9.87, & 0.0, 0.25, 1.98, 6.70, 15.88, 31.01, & 0.0, 0.16, 2.49, 12.62, 39.90, 97.41, & 0.0, 0.10, 3.13, 23.80, 100.28, 306.02], [6,6] ) b = [-0.01, 0.61, 0.91, 0.99, 0.60, 0.02] print'(f15.7)',solve_wbs(ge_wpp(a,b))   contains   function solve_wbs(u) result(x) ! solve with backward substitution real :: u(:,:) integer :: i,n real , allocatable :: x(:) n = size(u,1) allocate(x(n)) forall (i=n:1:-1) x(i) = ( u(i,n+1) - sum(u(i,i+1:n)*x(i+1:n)) ) / u(i,i) end function   function ge_wpp(a,b) result(u) ! gaussian eliminate with partial pivoting real :: a(:,:),b(:),upi integer :: i,j,n,p real , allocatable :: u(:,:) n = size(a,1) u = reshape( [a,b], [n,n+1] ) do j=1,n p = maxloc(abs(u(j:n,j)),1) + j-1 ! maxloc returns indices between (1,n-j+1) if (p /= j) u([p,j],j) = u([j,p],j) u(j+1:,j) = u(j+1:,j)/u(j,j) do i=j+1,n+1 upi = u(p,i) if (p /= j) u([p,j],i) = u([j,p],i) u(j+1:n,i) = u(j+1:n,i) - upi*u(j+1:n,j) end do end do end function   end program  
http://rosettacode.org/wiki/Gauss-Jordan_matrix_inversion
Gauss-Jordan matrix inversion
Task Invert matrix   A   using Gauss-Jordan method. A   being an   n × n   matrix.
#Julia
Julia
A = [1 2 3; 4 1 6; 7 8 9] @show I / A @show inv(A)
http://rosettacode.org/wiki/General_FizzBuzz
General FizzBuzz
Task Write a generalized version of FizzBuzz that works for any list of factors, along with their words. This is basically a "fizzbuzz" implementation where the user supplies the parameters. The user will enter the max number, then they will enter the factors to be calculated along with the corresponding word to be printed. For simplicity's sake, assume the user will input an integer as the max number and 3 factors, each with a word associated with them. For example, given: >20 #This is the maximum number, supplied by the user >3 Fizz #The user now enters the starting factor (3) and the word they want associated with it (Fizz) >5 Buzz #The user now enters the next factor (5) and the word they want associated with it (Buzz) >7 Baxx #The user now enters the next factor (7) and the word they want associated with it (Baxx) In other words: For this example, print the numbers 1 through 20, replacing every multiple of 3 with "Fizz", every multiple of 5 with "Buzz", and every multiple of 7 with "Baxx". In the case where a number is a multiple of at least two factors, print each of the words associated with those factors in the order of least to greatest factor. For instance, the number 15 is a multiple of both 3 and 5; print "FizzBuzz". If the max number was 105 instead of 20, you would print "FizzBuzzBaxx" because it's a multiple of 3, 5, and 7. Output: 1 2 Fizz 4 Buzz Fizz Baxx 8 Fizz Buzz 11 Fizz 13 Baxx FizzBuzz 16 17 Fizz 19 Buzz
#Haskell
Haskell
fizz :: (Integral a, Show a) => a -> [(a, String)] -> String fizz a xs | null result = show a | otherwise = result where result = concatMap (fizz' a) xs fizz' a (factor, str) | a `mod` factor == 0 = str | otherwise = ""   main = do line <- getLine let n = read line contents <- getContents let multiples = map (convert . words) $ lines contents mapM_ (\ x -> putStrLn $ fizz x multiples) [1..n] where convert [x, y] = (read x, y)  
http://rosettacode.org/wiki/Hailstone_sequence
Hailstone sequence
The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the sequence   = (3 * n) + 1 The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates. This sequence was named by Lothar Collatz in 1937   (or possibly in 1939),   and is also known as (the):   hailstone sequence,   hailstone numbers   3x + 2 mapping,   3n + 1 problem   Collatz sequence   Hasse's algorithm   Kakutani's problem   Syracuse algorithm,   Syracuse problem   Thwaites conjecture   Ulam's problem The hailstone sequence is also known as   hailstone numbers   (because the values are usually subject to multiple descents and ascents like hailstones in a cloud). Task Create a routine to generate the hailstone sequence for a number. Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1 Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.   (But don't show the actual sequence!) See also   xkcd (humourous).   The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).   The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
#XPL0
XPL0
include c:\cxpl\codes; \intrinsic 'code' declarations int Seq(1000); \more than enough for longest sequence   func Hailstone(N); \Return length of Hailstone sequence starting at N int N; \ also fills Seq array with sequence int I; [I:= 0; loop [Seq(I):= N; I:= I+1; if N=1 then return I; N:= if N&1 then N*3+1 else N/2; ]; ];   int N, SN, Len, MaxLen; [Len:= Hailstone(27); Text(0, "27's Hailstone length = "); IntOut(0, Len); CrLf(0);   Text(0, "Sequence = "); for N:= 0 to 3 do [IntOut(0, Seq(N)); ChOut(0, ^ )]; Text(0, "... "); for N:= Len-4 to Len-1 do [IntOut(0, Seq(N)); ChOut(0, ^ )]; CrLf(0);   MaxLen:= 0; for N:= 1 to 100_000-1 do [Len:= Hailstone(N); if Len > MaxLen then [MaxLen:= Len; SN:= N]; \save N with max length ]; IntOut(0, SN); Text(0, "'s Hailstone length = "); IntOut(0, MaxLen); ]
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
Generate lower case ASCII alphabet
Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code. During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code: set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z} Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#D
D
import std.ascii: lowercase;   void main() {}
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
Generate lower case ASCII alphabet
Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code. During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code: set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z} Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#dc
dc
122 [ d 1 - d 97<L 256 * + ] d sL x P
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#Oforth
Oforth
"Hello world!" .
http://rosettacode.org/wiki/Generator/Exponential
Generator/Exponential
A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided. Generators are often built on top of coroutines or objects so that the internal state of the object is handled “naturally”. Generators are often used in situations where a sequence is potentially infinite, and where it is possible to construct the next value of the sequence with only minimal state. Task Create a function that returns a generation of the m'th powers of the positive integers starting from zero, in order, and without obvious or simple upper limit. (Any upper limit to the generator should not be stated in the source but should be down to factors such as the languages natural integer size limit or computational time/size). Use it to create a generator of:   Squares.   Cubes. Create a new generator that filters all cubes from the generator of squares. Drop the first 20 values from this last generator of filtered results, and then show the next 10 values. Note that this task requires the use of generators in the calculation of the result. Also see Generator
#Julia
Julia
drop(gen::Function, n::Integer) = (for _ in 1:n gen() end; gen) take(gen::Function, n::Integer) = collect(gen() for _ in 1:n)   function pgen(n::Number) x = 0 return () -> (x += 1) ^ n end   function genfilter(g1::Function, g2::Function) local r1 local r2 = g2() return () -> begin r1 = g1() while r2 < r1 r2 = g2() end while r1 == r2 r1 = g1() end return r1 end end   @show take(drop(genfilter(pgen(2), pgen(3)), 20), 10)
http://rosettacode.org/wiki/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related task   least common multiple. See also   MathWorld entry:   greatest common divisor.   Wikipedia entry:     greatest common divisor.
#x86_Assembly
x86 Assembly
.text .global pgcd   pgcd: push  %ebp mov  %esp, %ebp   mov 8(%ebp), %eax mov 12(%ebp), %ecx push  %edx   .loop: cmp $0, %ecx je .end xor  %edx, %edx div  %ecx mov  %ecx, %eax mov  %edx, %ecx jmp .loop   .end: pop  %edx leave ret
http://rosettacode.org/wiki/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related task   least common multiple. See also   MathWorld entry:   greatest common divisor.   Wikipedia entry:     greatest common divisor.
#XBasic
XBasic
' Greatest common divisor PROGRAM "gcddemo" VERSION "0.001"   DECLARE FUNCTION Entry() DECLARE FUNCTION GcdRecursive(u&, v&) DECLARE FUNCTION GcdIterative(u&, v&) DECLARE FUNCTION GcdBinary(u&, v&)   FUNCTION Entry() m& = 49865 n& = 69811 PRINT "GCD("; LTRIM$(STR$(m&)); ","; n&; "):"; GcdIterative(m&, n&); " (iterative)" PRINT "GCD("; LTRIM$(STR$(m&)); ","; n&; "):"; GcdRecursive(m&, n&); " (recursive)" PRINT "GCD("; LTRIM$(STR$(m&)); ","; n&; "):"; GcdBinary (m&, n&); " (binary)" END FUNCTION   FUNCTION GcdRecursive(u&, v&) IF u& MOD v& <> 0 THEN RETURN GcdRecursive(v&, u& MOD v&) ELSE RETURN v& END IF END FUNCTION   FUNCTION GcdIterative(u&, v&) DO WHILE v& <> 0 t& = u& u& = v& v& = t& MOD v& LOOP RETURN ABS(u&) END FUNCTION   FUNCTION GcdBinary(u&, v&) u& = ABS(u&) v& = ABS(v&) IF u& < v& THEN t& = u& u& = v& v& = t& END IF IF v& = 0 THEN RETURN u& ELSE k& = 1 DO WHILE (u& MOD 2 = 0) && (v& MOD 2 = 0) u& = u& >> 1 v& = v& >> 1 k& = k& << 1 LOOP IF u& MOD 2 = 0 THEN t& = u& ELSE t& = -v& END IF DO WHILE t& <> 0 DO WHILE t& MOD 2 = 0 t& = t& \ 2 LOOP IF t& > 0 THEN u& = t& ELSE v& = -t& END IF t& = u& - v& LOOP RETURN u& * k& END IF END FUNCTION   END PROGRAM  
http://rosettacode.org/wiki/Generate_Chess960_starting_position
Generate Chess960 starting position
Chess960 is a variant of chess created by world champion Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints: as in the standard chess game, all eight white pawns must be placed on the second rank. White pieces must stand on the first rank as in the standard game, in random column order but with the two following constraints: the bishops must be placed on opposite color squares (i.e. they must be an odd number of spaces apart or there must be an even number of spaces between them) the King must be between two rooks (with any number of other pieces between them all) Black pawns and pieces must be placed respectively on the seventh and eighth ranks, mirroring the white pawns and pieces, just as in the standard game. (That is, their positions are not independently randomized.) With those constraints there are 960 possible starting positions, thus the name of the variant. Task The purpose of this task is to write a program that can randomly generate any one of the 960 Chess960 initial positions. You will show the result as the first rank displayed with Chess symbols in Unicode: ♔♕♖♗♘ or with the letters King Queen Rook Bishop kNight.
#Phix
Phix
with javascript_semantics sequence solutions = {} --integer d = new_dict() for i=1 to factorial(8) do sequence s = permute(i,"RNBQKBNR") -- sequence s = permute(rand(factorial(8),"RNBQKBNR") integer b1 = find('B',s), b2 = find('B',s,b1+1) if and_bits(b2-b1,1)=1 then integer k = find('K',s) integer r1 = find('R',s) integer r2 = find('R',s,r1+1) if r1<k and k<r2 then if find(s,solutions)=0 then -- if getd_index(s,d)=0 then -- setd(s,0,d) solutions = append(solutions,s) end if end if end if end for printf(1,"Found %d solutions\n",{length(solutions)}) for i=1 to 5 do ?solutions[rand(length(solutions))] end for
http://rosettacode.org/wiki/Function_composition
Function composition
Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   g   to   x. Example compose(f, g) (x) = f(g(x)) Reference: Function composition Hint: In some languages, implementing compose correctly requires creating a closure.
#ActionScript
ActionScript
function compose(f:Function, g:Function):Function { return function(x:Object) {return f(g(x));}; } function test() { trace(compose(Math.atan, Math.tan)(0.5)); }
http://rosettacode.org/wiki/Function_composition
Function composition
Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   g   to   x. Example compose(f, g) (x) = f(g(x)) Reference: Function composition Hint: In some languages, implementing compose correctly requires creating a closure.
#Ada
Ada
generic type Argument is private; package Functions is type Primitive_Operation is not null access function (Value : Argument) return Argument; type Func (<>) is private; function "*" (Left : Func; Right : Argument) return Argument; function "*" (Left : Func; Right : Primitive_Operation) return Func; function "*" (Left, Right : Primitive_Operation) return Func; function "*" (Left, Right : Func) return Func; private type Func is array (Positive range <>) of Primitive_Operation; end Functions;
http://rosettacode.org/wiki/FTP
FTP
Task Connect to a server, change directory, list its contents and download a file as binary using the FTP protocol. Use passive mode if available.
#Batch_File
Batch File
::Playing with FTP ::Batch File Implementation   @echo off   set site="ftp.hq.nasa.gov" set user="anonymous" set pass="[email protected]" set dir="pub/issoutreach/Living in Space Stories (MP3 Files)" set download="Gravity in the Brain.mp3"   ( echo.open %site% echo.user %user% %pass% echo.dir echo.!echo. echo.!echo.This is a just a text to seperate two directory listings. echo.!echo. echo.cd %dir% echo.dir echo.binary echo.get %download% echo.disconnect )|ftp -n
http://rosettacode.org/wiki/FTP
FTP
Task Connect to a server, change directory, list its contents and download a file as binary using the FTP protocol. Use passive mode if available.
#C
C
  #include <ftplib.h>   int main(void) { netbuf *nbuf;   FtpInit(); FtpConnect("kernel.org", &nbuf); FtpLogin("anonymous", "", nbuf); FtpOptions(FTPLIB_CONNMODE, FTPLIB_PASSIVE, nbuf); FtpChdir("pub/linux/kernel", nbuf); FtpDir((void*)0, ".", nbuf); FtpGet("ftp.README", "README", FTPLIB_ASCII, nbuf); FtpQuit(nbuf);   return 0; }  
http://rosettacode.org/wiki/Function_prototype
Function prototype
Some languages provide the facility to declare functions and subroutines through the use of function prototyping. Task Demonstrate the methods available for declaring prototypes within the language. The provided solutions should include: An explanation of any placement restrictions for prototype declarations A prototype declaration for a function that does not require arguments A prototype declaration for a function that requires two arguments A prototype declaration for a function that utilizes varargs A prototype declaration for a function that utilizes optional arguments A prototype declaration for a function that utilizes named parameters Example of prototype declarations for subroutines or procedures (if these differ from functions) An explanation and example of any special forms of prototyping not covered by the above Languages that do not provide function prototyping facilities should be omitted from this task.
#Haskell
Haskell
  add :: Int -> Int -> Int add x y = x+y  
http://rosettacode.org/wiki/Function_prototype
Function prototype
Some languages provide the facility to declare functions and subroutines through the use of function prototyping. Task Demonstrate the methods available for declaring prototypes within the language. The provided solutions should include: An explanation of any placement restrictions for prototype declarations A prototype declaration for a function that does not require arguments A prototype declaration for a function that requires two arguments A prototype declaration for a function that utilizes varargs A prototype declaration for a function that utilizes optional arguments A prototype declaration for a function that utilizes named parameters Example of prototype declarations for subroutines or procedures (if these differ from functions) An explanation and example of any special forms of prototyping not covered by the above Languages that do not provide function prototyping facilities should be omitted from this task.
#J
J
NB. j assumes an unknown name f is a verb of infinite rank NB. f has infinite ranks f b. 0 _ _ _   NB. The verb g makes a table. g=: f/~   NB. * has rank 0 f=: *     NB. indeed, make a multiplication table f/~ i.5 0 0 0 0 0 0 1 2 3 4 0 2 4 6 8 0 3 6 9 12 0 4 8 12 16   NB. g was defined as if f had infinite rank. g i.5 0 1 4 9 16   NB. f is known to have rank 0. g=: f/~   NB. Now we reproduce the table g i.5 0 0 0 0 0 0 1 2 3 4 0 2 4 6 8 0 3 6 9 12 0 4 8 12 16       NB. change f to another rank 0 verb f=: +   NB. and construct an addition table g i.5 0 1 2 3 4 1 2 3 4 5 2 3 4 5 6 3 4 5 6 7 4 5 6 7 8     NB. f is multiplication at infinite rank f=: *"_     NB. g, however, has rank 0 g i.5 0 0 0 0 0 0 1 2 3 4 0 2 4 6 8 0 3 6 9 12 0 4 8 12 16
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
#11l
11l
F multiply(a, b) R a * b
http://rosettacode.org/wiki/French_Republican_calendar
French Republican calendar
Write a program to convert dates between the Gregorian calendar and the French Republican calendar. The year 1 of the Republican calendar began on 22 September 1792. There were twelve months (Vendémiaire, Brumaire, Frimaire, Nivôse, Pluviôse, Ventôse, Germinal, Floréal, Prairial, Messidor, Thermidor, and Fructidor) of 30 days each, followed by five intercalary days or Sansculottides (Fête de la vertu / Virtue Day, Fête du génie / Talent Day, Fête du travail / Labour Day, Fête de l'opinion / Opinion Day, and Fête des récompenses / Honours Day). In leap years (the years 3, 7, and 11) a sixth Sansculottide was added: Fête de la Révolution / Revolution Day. As a minimum, your program should give correct results for dates in the range from 1 Vendémiaire 1 = 22 September 1792 to 10 Nivôse 14 = 31 December 1805 (the last day when the Republican calendar was officially in use). If you choose to accept later dates, be aware that there are several different methods (described on the Wikipedia page) about how to determine leap years after the year 14. You should indicate which method you are using. (Because of these different methods, correct programs may sometimes give different results for dates after 1805.) Test your program by converting the following dates both from Gregorian to Republican and from Republican to Gregorian: • 1 Vendémiaire 1 = 22 September 1792 • 1 Prairial 3 = 20 May 1795 • 27 Messidor 7 = 15 July 1799 (Rosetta Stone discovered) • Fête de la Révolution 11 = 23 September 1803 • 10 Nivôse 14 = 31 December 1805
#BBC_BASIC
BBC BASIC
REM >frrepcal : DIM gregorian$(11) DIM gregorian%(11) DIM republican$(11) DIM sansculottides$(5) gregorian$() = "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" gregorian%() = 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 REM 7-bit ASCII encoding, so no accents on French words republican$() = "Vendemiaire", "Brumaire", "Frimaire", "Nivose", "Pluviose", "Ventose", "Germinal", "Floreal", "Prairial", "Messidor", "Thermidor", "Fructidor" sansculottides$() = "Fete de la vertu", "Fete du genie", "Fete du travail", "Fete de l'opinion", "Fete des recompenses", "Fete de la Revolution" : PRINT "*** French Republican ***" PRINT "*** calendar converter ***" PRINT "Enter a date to convert, in the format 'day month year'" PRINT "e.g.: 1 Prairial 3," PRINT " 20 May 1795." PRINT "For Sansculottides, use 'day year'" PRINT "e.g.: Fete de l'opinion 9." PRINT "Or just press 'RETURN' to exit the program." PRINT REPEAT INPUT LINE "> " src$ IF src$ <> "" THEN PROC_split(src$, day%, month%, year%) REM for simplicity, we assume that years up to 1791 are Republican REM and years from 1792 onwards are Gregorian IF year% < 1792 THEN REM convert Republican date to number of days elapsed REM since 21 September 1792, then convert that number REM to the Gregorian date PROC_day_to_gre(FN_rep_to_day(day%, month%, year%), day%, month%, year%) PRINT; day%; " "; gregorian$(month% - 1); " " year% ELSE REM convert Gregorian date to Republican, via REM number of days elapsed since 21 September 1792 PROC_day_to_rep(FN_gre_to_day(day%, month%, year%), day%, month%, year%) IF month% = 13 THEN PRINT sansculottides$(day% - 1); " "; year% ELSE PRINT; day%; " "; republican$(month% - 1); " "; year% ENDIF ENDIF ENDIF UNTIL src$ = "" END : DEF PROC_split(s$, RETURN d%, RETURN m%, RETURN y%) LOCAL month_and_year$, month$, months$(), i% DIM months$(11) IF LEFT$(s$, 4) = "Fete" THEN m% = 13 FOR i% = 0 TO 5 IF LEFT$(s$, LEN sansculottides$(i%)) = sansculottides$(i%) THEN d% = i% + 1 y% = VAL(RIGHT$(s$, LEN s$ - LEN sansculottides$(i%) - 1)) ENDIF NEXT ELSE d% = VAL(LEFT$(s$, INSTR(s$, " ") - 1)) month_and_year$ = MID$(s$, INSTR(s$, " ") + 1) month$ = LEFT$(month_and_year$, INSTR(month_and_year$, " ") - 1) y% = VAL(MID$(month_and_year$, INSTR(month_and_year$, " ") + 1)) IF y% < 1792 THEN months$() = republican$() ELSE months$() = gregorian$() FOR i% = 0 TO 11 IF months$(i%) = month$ THEN m% = i% + 1 NEXT ENDIF ENDPROC : DEF FN_gre_to_day(d%, m%, y%) REM modified & repurposed from code given at REM https://www.staff.science.uu.nl/~gent0113/calendar/isocalendar_text5.htm IF m% < 3 THEN y% -= 1 m% += 12 ENDIF = INT(365.25 * y%) - INT(y% / 100) + INT(y% / 400) + INT(30.6 * (m% + 1)) + d% - 654842 : DEF FN_rep_to_day(d%, m%, y%) REM assume that a year is a leap year iff the _following_ year is REM divisible by 4, but not by 100 unless also by 400 REM REM other methods for computing Republican leap years exist IF m% = 13 THEN m% -= 1 d% += 30 ENDIF IF FN_rep_leap(y%) THEN d% -= 1 = 365 * y% + INT((y% + 1) / 4) - INT((y% + 1) / 100) + INT((y% + 1) / 400) + 30 * m% + d% - 395 : DEF PROC_day_to_gre(day%, RETURN d%, RETURN m%, RETURN y%) y% = INT(day% / 365.25) d% = day% - INT(365.25 * y%) + 21 y% += 1792 d% += INT(y% / 100) - INT(y% / 400) - 13 m% = 8 WHILE d% > gregorian%(m%) d% -= gregorian%(m%) m% += 1 IF m% = 12 THEN m% = 0 y% += 1 IF FN_gre_leap(y%) THEN gregorian%(1) = 29 ELSE gregorian%(1) = 28 ENDIF ENDWHILE m% += 1 ENDPROC : DEF PROC_day_to_rep(day%, RETURN d%, RETURN m%, RETURN y%) LOCAL sansculottides% y% = INT(day% / 365.25) IF FN_rep_leap(y%) THEN y% -= 1 d% = day% - INT(365.25 * y%) + INT((y% + 1) / 100) - INT((y% + 1) / 400) y% += 1 m% = 1 IF FN_rep_leap(y%) THEN sansculottides% = 6 ELSE sansculottides% = 5 WHILE d% > 30 d% -= 30 m% += 1 IF m% = 13 THEN IF d% > sansculottides% THEN d% -= sansculottides% m% = 1 y% += 1 IF FN_rep_leap(y%) THEN sansculottides% = 6 ELSE sansculottides% = 5 ENDIF ENDIF ENDWHILE ENDPROC : DEF FN_rep_leap(year%) REM see comment at the beginning of FN_rep_to_day = ((year% + 1) MOD 4 = 0 AND ((year% + 1) MOD 100 <> 0 OR (year% + 1) MOD 400 = 0)) : DEF FN_gre_leap(year%) = (year% MOD 4 = 0 AND (year% MOD 100 <> 0 OR year% MOD 400 = 0))
http://rosettacode.org/wiki/Fusc_sequence
Fusc sequence
Definitions The   fusc   integer sequence is defined as:   fusc(0) = 0   fusc(1) = 1   for n>1,   the   nth   term is defined as:   if   n   is even;     fusc(n) = fusc(n/2)   if   n   is   odd;     fusc(n) = fusc((n-1)/2)   +   fusc((n+1)/2) Note that MathWorld's definition starts with unity, not zero.   This task will be using the OEIS' version   (above). An observation   fusc(A) = fusc(B) where   A   is some non-negative integer expressed in binary,   and where   B   is the binary value of   A   reversed. Fusc numbers are also known as:   fusc function   (named by Dijkstra, 1982)   Stern's Diatomic series   (although it starts with unity, not zero)   Stern-Brocot sequence   (although it starts with unity, not zero) Task   show the first   61   fusc numbers (starting at zero) in a horizontal format.   show the fusc number (and its index) whose length is greater than any previous fusc number length.   (the length is the number of decimal digits when the fusc number is expressed in base ten.)   show all numbers with commas   (if appropriate).   show all output here. Related task   RosettaCode Stern-Brocot sequence Also see   the MathWorld entry:   Stern's Diatomic Series.   the OEIS entry:   A2487.
#AppleScript
AppleScript
on fusc(n) if (n < 2) then return n else if (n mod 2 is 0) then return fusc(n div 2) else return fusc((n - 1) div 2) + fusc((n + 1) div 2) end if end fusc   set sequence to {} set longestSoFar to 0 repeat with i from 0 to 60 set fuscNumber to fusc(i) set end of sequence to fuscNumber set len to (count (fuscNumber as text)) if (len > longestSoFar) then set longestSoFar to len set firstLongest to fuscNumber set indexThereof to i + 1 -- AppleScript indices are 1-based. end if end repeat   return {sequence:sequence, firstLongest:firstLongest, indexThereof:indexThereof}
http://rosettacode.org/wiki/Functional_coverage_tree
Functional coverage tree
Functional coverage is a measure of how much a particular function of a system has been verified as correct. It is used heavily in tracking the completeness of the verification of complex System on Chip (SoC) integrated circuits, where it can also be used to track how well the functional requirements of the system have been verified. This task uses a sub-set of the calculations sometimes used in tracking functional coverage but uses a more familiar(?) scenario. Task Description The head of the clean-up crews for "The Men in a very dark shade of grey when viewed at night" has been tasked with managing the cleansing of two properties after an incident involving aliens. She arranges the task hierarchically with a manager for the crews working on each house who return with a breakdown of how they will report on progress in each house. The overall hierarchy of (sub)tasks is as follows, cleaning house1 bedrooms bathrooms bathroom1 bathroom2 outside lavatory attic kitchen living rooms lounge dining room conservatory playroom basement garage garden house2 upstairs bedrooms suite 1 suite 2 bedroom 3 bedroom 4 bathroom toilet attics groundfloor kitchen living rooms lounge dining room conservatory playroom wet room & toilet garage garden hot tub suite basement cellars wine cellar cinema The head of cleanup knows that her managers will report fractional completion of leaf tasks (tasks with no child tasks of their own), and she knows that she will want to modify the weight of values of completion as she sees fit. Some time into the cleaning, and some coverage reports have come in and she thinks see needs to weight the big house2 60-40 with respect to coverage from house1 She prefers a tabular view of her data where missing weights are assumed to be 1.0 and missing coverage 0.0. NAME_HIERARCHY |WEIGHT |COVERAGE | cleaning | | | house1 |40 | | bedrooms | |0.25 | bathrooms | | | bathroom1 | |0.5 | bathroom2 | | | outside_lavatory | |1 | attic | |0.75 | kitchen | |0.1 | living_rooms | | | lounge | | | dining_room | | | conservatory | | | playroom | |1 | basement | | | garage | | | garden | |0.8 | house2 |60 | | upstairs | | | bedrooms | | | suite_1 | | | suite_2 | | | bedroom_3 | | | bedroom_4 | | | bathroom | | | toilet | | | attics | |0.6 | groundfloor | | | kitchen | | | living_rooms | | | lounge | | | dining_room | | | conservatory | | | playroom | | | wet_room_&_toilet | | | garage | | | garden | |0.9 | hot_tub_suite | |1 | basement | | | cellars | |1 | wine_cellar | |1 | cinema | |0.75 | Calculation The coverage of a node in the tree is calculated as the weighted average of the coverage of its children evaluated bottom-upwards in the tree. The task is to calculate the overall coverage of the cleaning task and display the coverage at all levels of the hierarchy on this page, in a manner that visually shows the hierarchy, weights and coverage of all nodes. Extra Credit After calculating the coverage for all nodes, one can also calculate the additional/delta top level coverage that would occur if any (sub)task were to be fully covered from its current fractional coverage. This is done by multiplying the extra coverage that could be gained 1 − c o v e r a g e {\displaystyle 1-coverage} for any node, by the product of the `powers` of its parent nodes from the top down to the node. The power of a direct child of any parent is given by the power of the parent multiplied by the weight of the child divided by the sum of the weights of all the direct children. The pseudo code would be: method delta_calculation(this, power): sum_of_weights = sum(node.weight for node in children) this.delta = (1 - this.coverage) * power for node in self.children: node.delta_calculation(power * node.weight / sum_of_weights) return this.delta Followed by a call to: top.delta_calculation(power=1) Note: to aid in getting the data into your program you might want to use an alternative, more functional description of the starting data given on the discussion page.
#Nim
Nim
import strformat, strutils   type   FCNode = ref object name: string weight: int coverage: float children: seq[FCNode] parent: FCNode   func newFCNode(name: string; weight: int; coverage: float): FCNode = FCNode(name: name, weight: weight, coverage: coverage)   # Forward reference. func updateCoverage(n: FCNode)   func addChildren(n: FCNode; nodes: openArray[FCNode]) = for node in nodes: node.parent = n n.children = @nodes n.updateCoverage()   func setCoverage(n: FCNode; value: float) = if n.coverage != value: n.coverage = value # Update any parent's coverage. if not n.parent.isNil: n.parent.updateCoverage()   func updateCoverage(n: FCNode) = var v1 = 0.0 var v2 = 0 for node in n.children: v1 += node.weight.toFloat * node.coverage v2 += node.weight n.setCoverage(v1 / v2.toFloat)   proc show(n: FCNode; level: int) = let indent = level * 4 let nl = n.name.len + indent const Sep = "|" echo &"{n.name.align(nl)}{Sep.align(32-nl)} {n.weight:>3d} | {n.coverage:8.6f} |" for child in n.children: child.show(level + 1)   #———————————————————————————————————————————————————————————————————————————————————————————————————   let houses = [newFCNode("house1", 40, 0), newFCNode("house2", 60, 0)]   let house1 = [ newFCNode("bedrooms", 1, 0.25), newFCNode("bathrooms", 1, 0), newFCNode("attic", 1, 0.75), newFCNode("kitchen", 1, 0.1), newFCNode("living_rooms", 1, 0), newFCNode("basement", 1, 0), newFCNode("garage", 1, 0), newFCNode("garden", 1, 0.8)]   let house2 = [ newFCNode("upstairs", 1, 0), newFCNode("groundfloor", 1, 0), newFCNode("basement", 1, 0)]   let h1Bathrooms = [ newFCNode("bathroom1", 1, 0.5), newFCNode("bathroom2", 1, 0), newFCNode("outside_lavatory", 1, 1)]   let h1LivingRooms = [ newFCNode("lounge", 1, 0), newFCNode("dining_room", 1, 0), newFCNode("conservatory", 1, 0), newFCNode("playroom", 1, 1)]   let h2Upstairs = [ newFCNode("bedrooms", 1, 0), newFCNode("bathroom", 1, 0), newFCNode("toilet", 1, 0), newFCNode("attics", 1, 0.6)]   let h2Groundfloor = [ newFCNode("kitchen", 1, 0), newFCNode("living_rooms", 1, 0), newFCNode("wet_room_&_toilet", 1, 0), newFCNode("garage", 1, 0), newFCNode("garden", 1, 0.9), newFCNode("hot_tub_suite", 1, 1)]   let h2Basement = [ newFCNode("cellars", 1, 1), newFCNode("wine_cellar", 1, 1), newFCNode("cinema", 1, 0.75)]   let h2UpstairsBedrooms = [ newFCNode("suite_1", 1, 0), newFCNode("suite_2", 1, 0), newFCNode("bedroom_3", 1, 0), newFCNode("bedroom_4", 1, 0)]   let h2GroundfloorLivingRooms = [ newFCNode("lounge", 1, 0), newFCNode("dining_room", 1, 0), newFCNode("conservatory", 1, 0), newFCNode("playroom", 1, 0)]   let cleaning = newFCNode("cleaning", 1, 0)   house1[1].addChildren(h1Bathrooms) house1[4].addChildren(h1LivingRooms) houses[0].addChildren(house1)   h2Upstairs[0].addChildren(h2UpstairsBedrooms) house2[0].addChildren(h2Upstairs) h2Groundfloor[1].addChildren(h2GroundfloorLivingRooms) house2[1].addChildren(h2Groundfloor) house2[2].addChildren(h2Basement) houses[1].addChildren(house2)   cleaning.addChildren(houses) let topCoverage = cleaning.coverage echo &"TOP COVERAGE = {topCoverage:8.6f}\n" echo "NAME HIERARCHY | WEIGHT | COVERAGE |" cleaning.show(0)   h2Basement[2].setCoverage(1) # Change Cinema node coverage to 1. let diff = cleaning.coverage - topCoverage echo "\nIf the coverage of the Cinema node were increased from 0.75 to 1" echo &"the top level coverage would increase by {diff:8.6f} to {topCoverage + diff:8.6f}" h2Basement[2].setCoverage(0.75) # Restore to original value if required.
http://rosettacode.org/wiki/Functional_coverage_tree
Functional coverage tree
Functional coverage is a measure of how much a particular function of a system has been verified as correct. It is used heavily in tracking the completeness of the verification of complex System on Chip (SoC) integrated circuits, where it can also be used to track how well the functional requirements of the system have been verified. This task uses a sub-set of the calculations sometimes used in tracking functional coverage but uses a more familiar(?) scenario. Task Description The head of the clean-up crews for "The Men in a very dark shade of grey when viewed at night" has been tasked with managing the cleansing of two properties after an incident involving aliens. She arranges the task hierarchically with a manager for the crews working on each house who return with a breakdown of how they will report on progress in each house. The overall hierarchy of (sub)tasks is as follows, cleaning house1 bedrooms bathrooms bathroom1 bathroom2 outside lavatory attic kitchen living rooms lounge dining room conservatory playroom basement garage garden house2 upstairs bedrooms suite 1 suite 2 bedroom 3 bedroom 4 bathroom toilet attics groundfloor kitchen living rooms lounge dining room conservatory playroom wet room & toilet garage garden hot tub suite basement cellars wine cellar cinema The head of cleanup knows that her managers will report fractional completion of leaf tasks (tasks with no child tasks of their own), and she knows that she will want to modify the weight of values of completion as she sees fit. Some time into the cleaning, and some coverage reports have come in and she thinks see needs to weight the big house2 60-40 with respect to coverage from house1 She prefers a tabular view of her data where missing weights are assumed to be 1.0 and missing coverage 0.0. NAME_HIERARCHY |WEIGHT |COVERAGE | cleaning | | | house1 |40 | | bedrooms | |0.25 | bathrooms | | | bathroom1 | |0.5 | bathroom2 | | | outside_lavatory | |1 | attic | |0.75 | kitchen | |0.1 | living_rooms | | | lounge | | | dining_room | | | conservatory | | | playroom | |1 | basement | | | garage | | | garden | |0.8 | house2 |60 | | upstairs | | | bedrooms | | | suite_1 | | | suite_2 | | | bedroom_3 | | | bedroom_4 | | | bathroom | | | toilet | | | attics | |0.6 | groundfloor | | | kitchen | | | living_rooms | | | lounge | | | dining_room | | | conservatory | | | playroom | | | wet_room_&_toilet | | | garage | | | garden | |0.9 | hot_tub_suite | |1 | basement | | | cellars | |1 | wine_cellar | |1 | cinema | |0.75 | Calculation The coverage of a node in the tree is calculated as the weighted average of the coverage of its children evaluated bottom-upwards in the tree. The task is to calculate the overall coverage of the cleaning task and display the coverage at all levels of the hierarchy on this page, in a manner that visually shows the hierarchy, weights and coverage of all nodes. Extra Credit After calculating the coverage for all nodes, one can also calculate the additional/delta top level coverage that would occur if any (sub)task were to be fully covered from its current fractional coverage. This is done by multiplying the extra coverage that could be gained 1 − c o v e r a g e {\displaystyle 1-coverage} for any node, by the product of the `powers` of its parent nodes from the top down to the node. The power of a direct child of any parent is given by the power of the parent multiplied by the weight of the child divided by the sum of the weights of all the direct children. The pseudo code would be: method delta_calculation(this, power): sum_of_weights = sum(node.weight for node in children) this.delta = (1 - this.coverage) * power for node in self.children: node.delta_calculation(power * node.weight / sum_of_weights) return this.delta Followed by a call to: top.delta_calculation(power=1) Note: to aid in getting the data into your program you might want to use an alternative, more functional description of the starting data given on the discussion page.
#Perl
Perl
use strict; use warnings;   sub walktree { my @parts; while( $_[0] =~ /(?<head> (\s*) \N+\n ) # split off one level as 'head' (or terminal 'leaf') (?<body> (?:\2 \s\N+\n)*)/gx ) { # next sub-level is 'body' (defined by extra depth of indentation)   my($head, $body) = ($+{head}, $+{body}); $head =~ /^.*? \| # ignore name (\S*) \s* \| # save weight (\S*) /x; # save coverage my $weight = sprintf '%-8s', $1 || 1; my $coverage = sprintf '%-10s', $2 || 0; my($w, $wsum) = (0, 0);   $head .= $_->[0], $w += $_->[1], $wsum += $_->[1] * $_->[2] for walktree( $body );   $coverage = sprintf '%-10.2g', $wsum/$w unless $w == 0; push @parts, [ $head =~ s/\|.*/|$weight|$coverage|/r, $weight, $coverage ]; } return @parts; }   print $_->[0] for walktree( join '', <DATA> );   __DATA__ NAME_HIERARCHY |WEIGHT |COVERAGE | cleaning | | | house1 |40 | | bedrooms | |0.25 | bathrooms | | | bathroom1 | |0.5 | bathroom2 | | | outside_lavatory | |1 | attic | |0.75 | kitchen | |0.1 | living_rooms | | | lounge | | | dining_room | | | conservatory | | | playroom | |1 | basement | | | garage | | | garden | |0.8 | house2 |60 | | upstairs | | | bedrooms | | | suite_1 | | | suite_2 | | | bedroom_3 | | | bedroom_4 | | | bathroom | | | toilet | | | attics | |0.6 | groundfloor | | | kitchen | | | living_rooms | | | lounge | | | dining_room | | | conservatory | | | playroom | | | wet_room_&_toilet | | | garage | | | garden | |0.9 | hot_tub_suite | |1 | basement | | | cellars | |1 | wine_cellar | |1 | cinema | |0.75 |  
http://rosettacode.org/wiki/Function_frequency
Function frequency
Display - for a program or runtime environment (whatever suits the style of your language) - the top ten most frequently occurring functions (or also identifiers or tokens, if preferred). This is a static analysis: The question is not how often each function is actually executed at runtime, but how often it is used by the programmer. Besides its practical usefulness, the intent of this task is to show how to do self-inspection within the language.
#Erlang
Erlang
  -module( function_frequency ).   -export( [erlang_source/1, task/0] ).   erlang_source( File ) -> {ok, IO} = file:open( File, [read] ), Forms = parse_all( IO, io:parse_erl_form(IO, ''), [] ), Functions = lists:flatten( [erl_syntax_lib:fold(fun accumulate_functions/2, [], X) || X <- Forms] ), dict:to_list( lists:foldl(fun count/2, dict:new(), Functions) ).   task() -> Function_frequencies = erlang_source( "function_frequency.erl" ), {Top_tens, _Rest} = lists:split( 10, lists:reverse(lists:keysort(2, Function_frequencies)) ), [io:fwrite("Function ~p called ~p times.~n", [X, Y]) || {X, Y} <- Top_tens].       accumulate_functions( Tree, Acc ) -> accumulate_functions( erlang:element(1, Tree), Tree, Acc ).   accumulate_functions( call, Tree, Acc ) -> [accumulate_functions_name(Tree) | Acc]; accumulate_functions( _Other, _Tree, Acc ) -> Acc.   accumulate_functions_name( Tree ) -> accumulate_functions_name_scoop( erlang:element(3, Tree) ).   accumulate_functions_name_scoop( {atom, _Line, Name} ) -> Name; accumulate_functions_name_scoop( {remote, _Line, {atom, _Line, Module}, {atom, _Line, Name}} ) -> {Module, Name}.   count( Key, Dict ) -> dict:update_counter( Key, 1, Dict ).   parse_all( _IO, {eof, _End}, Acc ) -> Acc; parse_all( IO, {ok, Tokens, Location}, Acc ) -> parse_all( IO, io:parse_erl_form(IO, '', Location), [Tokens | Acc] ).  
http://rosettacode.org/wiki/Gamma_function
Gamma function
Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function. The Gamma function can be defined as: Γ ( x ) = ∫ 0 ∞ t x − 1 e − t d t {\displaystyle \Gamma (x)=\displaystyle \int _{0}^{\infty }t^{x-1}e^{-t}dt} This suggests a straightforward (but inefficient) way of computing the Γ {\displaystyle \Gamma } through numerical integration. Better suggested methods: Lanczos approximation Stirling's approximation
#AWK
AWK
  # syntax: GAWK -f GAMMA_FUNCTION.AWK BEGIN { e = (1+1/100000)^100000 pi = atan2(0,-1) leng = split("0.99999999999980993,676.5203681218851,-1259.1392167224028,771.32342877765313,-176.61502916214059,12.507343278686905,-0.13857109526572012,9.9843695780195716e-6,1.5056327351493116e-7",p,",") print("X Stirling") for (i=1; i<=20; i++) { d = i / 10 printf("%4.2f %9.5f\n",d,gamma_stirling(d)) } exit(0) } function gamma_stirling(x) { return sqrt(2*pi/x) * pow(x/e,x) } function pow(a,b) { return exp(b*log(a)) }  
http://rosettacode.org/wiki/Galton_box_animation
Galton box animation
Example of a Galton Box at the end of animation. A   Galton device   Sir Francis Galton's device   is also known as a   bean machine,   a   Galton Board,   or a   quincunx. Description of operation In a Galton box, there are a set of pins arranged in a triangular pattern.   A number of balls are dropped so that they fall in line with the top pin, deflecting to the left or the right of the pin.   The ball continues to fall to the left or right of lower pins before arriving at one of the collection points between and to the sides of the bottom row of pins. Eventually the balls are collected into bins at the bottom   (as shown in the image),   the ball column heights in the bins approximate a   bell curve.   Overlaying   Pascal's triangle   onto the pins shows the number of different paths that can be taken to get to each bin. Task Generate an animated simulation of a Galton device. Task requirements   The box should have at least 5 pins on the bottom row.   A solution can use graphics or ASCII animation.   Provide a sample of the output/display such as a screenshot.   There can be one or more balls in flight at the same time.   If multiple balls are in flight, ensure they don't interfere with each other.   A solution should allow users to specify the number of balls, or it should run until full or a preset limit.   Optionally,   display the number of balls.
#Factor
Factor
USING: accessors arrays calendar colors combinators combinators.short-circuit fonts fry generalizations kernel literals locals math math.ranges math.vectors namespaces opengl random sequences timers ui ui.commands ui.gadgets ui.gadgets.worlds ui.gestures ui.pens.solid ui.render ui.text ; IN: rosetta-code.galton-box-animation   CONSTANT: pegs $[ 20 300 40 <range> ] CONSTANT: speed 90 CONSTANT: balls 140 CONSTANT: peg-color T{ rgba f 0.60 0.4 0.60 1.0 } CONSTANT: ball-color T{ rgba f 0.80 1.0 0.20 1.0 } CONSTANT: slot-color T{ rgba f 0.00 0.2 0.40 1.0 } CONSTANT: bg-color T{ rgba f 0.02 0.0 0.02 1.0 }   CONSTANT: font $[ monospace-font t >>bold? T{ rgba f 0.80 1.0 0.20 1.0 } >>foreground T{ rgba f 0.02 0.0 0.02 1.0 } >>background ]   TUPLE: galton < gadget balls { frame initial: 1 } ;   DEFER: on-tick   : <galton-gadget> ( -- gadget ) galton new bg-color <solid> >>interior V{ } clone >>balls dup [ on-tick ] curry f speed milliseconds <timer> start-timer ;   : add-ball ( gadget -- ) dup frame>> balls < [ { 250 -20 } swap balls>> [ push ] keep ] when drop ;   : draw-msg ( -- ) { 10 10 } [ font "Press <space> for new animation" draw-text ] with-translation ;   : draw-slots ( -- ) slot-color gl-color { 70 350 } { 70 871 } 10 [ 2dup gl-line [ { 40 0 } v+ ] bi@ ] times 2drop { 70 871 } { 430 871 } gl-line ;   : diamond-side ( loc1 loc2 loc3 -- ) [ v+ dup ] [ v+ gl-line ] bi* ;   : draw-diamond ( loc color -- ) gl-color { [ { 0 -10 } { 10 10 } ] [ { 10 0 } { -10 10 } ] [ { 0 10 } { -10 -10 } ] [ { -10 0 } { 10 -10 } ] } [ diamond-side ] map-compose cleave ;   : draw-peg-row ( loc n -- ) <iota> [ 40 * 0 2array v+ peg-color draw-diamond ] with each ;   : draw-peg-triangle ( -- ) { 250 40 } 1 8 [ 2dup draw-peg-row [ { -20 40 } v+ ] dip 1 + ] times 2drop ;   : draw-balls ( gadget -- ) balls>> [ ball-color draw-diamond ] each ;   : rand-side ( loc -- loc' ) { { 20 20 } { -20 20 } } random v+ ;   :: collide? ( GADGET BALL -- ? ) BALL second :> y BALL { 0 20 } v+ :> tentative { [ y 860 = ] [ tentative GADGET balls>> member? ] } 0|| ;   :: update-ball ( GADGET BALL -- BALL' ) { { [ BALL second pegs member? ] [ BALL rand-side ] } { [ GADGET BALL collide? ] [ BALL ] } [ BALL { 0 20 } v+ ] } cond ;   : update-balls ( gadget -- ) dup '[ [ _ swap update-ball ] map ] change-balls drop ;   : on-tick ( gadget -- ) { [ dup frame>> odd? [ add-ball ] [ drop ] if ] [ relayout-1 ] [ update-balls ] [ [ 1 + ] change-frame drop ] } cleave ;   M: galton pref-dim* drop { 500 900 } ;   M: galton draw-gadget* draw-peg-triangle draw-msg draw-slots draw-balls ;   : com-new ( gadget -- ) V{ } clone >>balls 1 >>frame drop ;   galton "gestures" f { { T{ key-down { sym " " } } com-new } } define-command-map   MAIN-WINDOW: galton-box-animation { { title "Galton Box Animation" } { window-controls { normal-title-bar close-button minimize-button } } } <galton-gadget> >>gadgets ;
http://rosettacode.org/wiki/Gapful_numbers
Gapful numbers
Numbers   (positive integers expressed in base ten)   that are (evenly) divisible by the number formed by the first and last digit are known as   gapful numbers. Evenly divisible   means divisible with   no   remainder. All   one─   and two─digit   numbers have this property and are trivially excluded.   Only numbers   ≥ 100   will be considered for this Rosetta Code task. Example 187   is a   gapful   number because it is evenly divisible by the number   17   which is formed by the first and last decimal digits of   187. About   7.46%   of positive integers are   gapful. Task   Generate and show all sets of numbers (below) on one line (horizontally) with a title,   here on this page   Show the first   30   gapful numbers   Show the first   15   gapful numbers   ≥          1,000,000   Show the first   10   gapful numbers   ≥   1,000,000,000 Related tasks   Harshad or Niven series.   palindromic gapful numbers.   largest number divisible by its digits. Also see   The OEIS entry:   A108343 gapful numbers.   numbersaplenty gapful numbers
#Factor
Factor
USING: formatting kernel lists lists.lazy math math.functions math.text.utils sequences ;   : gapful? ( n -- ? ) dup 1 digit-groups [ first ] [ last 10 * + ] bi divisor? ;   30 100 15 1,000,000 10 1,000,000,000 [ 2dup lfrom [ gapful? ] lfilter ltake list>array "%d gapful numbers starting at %d:\n%[%d, %]\n\n" printf ] 2tri@
http://rosettacode.org/wiki/Gapful_numbers
Gapful numbers
Numbers   (positive integers expressed in base ten)   that are (evenly) divisible by the number formed by the first and last digit are known as   gapful numbers. Evenly divisible   means divisible with   no   remainder. All   one─   and two─digit   numbers have this property and are trivially excluded.   Only numbers   ≥ 100   will be considered for this Rosetta Code task. Example 187   is a   gapful   number because it is evenly divisible by the number   17   which is formed by the first and last decimal digits of   187. About   7.46%   of positive integers are   gapful. Task   Generate and show all sets of numbers (below) on one line (horizontally) with a title,   here on this page   Show the first   30   gapful numbers   Show the first   15   gapful numbers   ≥          1,000,000   Show the first   10   gapful numbers   ≥   1,000,000,000 Related tasks   Harshad or Niven series.   palindromic gapful numbers.   largest number divisible by its digits. Also see   The OEIS entry:   A108343 gapful numbers.   numbersaplenty gapful numbers
#Forth
Forth
variable cnt : Int>Str s>d <# #s #>  ; : firstDigit C@ [char] 0 -  ; : lastDigit + 1- c@ [char] 0 - ; : cnt++ cnt dup @ 1+ dup rot ! ; : GapfulNumber? dup dup Int>Str 2dup drop firstDigit 10 * -rot lastDigit + /mod drop 0= ; : main 0 cnt ! 2dup cr ." First " . ." gapful numbers >= " . begin dup cnt @ - while swap GapfulNumber? if dup cr cnt++ . ." : " . then 1+ swap repeat 2drop ;   100 30 main cr 1000000 15 main cr 1000000000 10 main cr  
http://rosettacode.org/wiki/Gaussian_elimination
Gaussian elimination
Task Solve   Ax=b   using Gaussian elimination then backwards substitution. A   being an   n by n   matrix. Also,   x and b   are   n by 1   vectors. To improve accuracy, please use partial pivoting and scaling. See also   the Wikipedia entry:   Gaussian elimination
#FreeBASIC
FreeBASIC
    Sub GaussJordan(matrix() As Double,rhs() As Double,ans() As Double) Dim As Long n=Ubound(matrix,1) Redim ans(0):Redim ans(1 To n) Dim As Double b(1 To n,1 To n),r(1 To n) For c As Long=1 To n 'take copies r(c)=rhs(c) For d As Long=1 To n b(c,d)=matrix(c,d) Next d Next c #macro pivot(num) For p1 As Long = num To n - 1 For p2 As Long = p1 + 1 To n If Abs(b(p1,num))<Abs(b(p2,num)) Then Swap r(p1),r(p2) For g As Long=1 To n Swap b(p1,g),b(p2,g) Next g End If Next p2 Next p1 #endmacro   For k As Long=1 To n-1 pivot(k) 'full pivoting For row As Long =k To n-1 If b(row+1,k)=0 Then Exit For Var f=b(k,k)/b(row+1,k) r(row+1)=r(row+1)*f-r(k) For g As Long=1 To n b((row+1),g)=b((row+1),g)*f-b(k,g) Next g Next row Next k 'back substitute For z As Long=n To 1 Step -1 ans(z)=r(z)/b(z,z) For j As Long = n To z+1 Step -1 ans(z)=ans(z)-(b(z,j)*ans(j)/b(z,z)) Next j Next z End Sub   dim as double a(1 to 6,1 to 6) = { _ {1.00, 0.00, 0.00, 0.00, 0.00, 0.00}, _ {1.00, 0.63, 0.39, 0.25, 0.16, 0.10}, _ {1.00, 1.26, 1.58, 1.98, 2.49, 3.13}, _ {1.00, 1.88, 3.55, 6.70, 12.62, 23.80}, _ {1.00, 2.51, 6.32, 15.88, 39.90, 100.28}, _ {1.00, 3.14, 9.87, 31.01, 97.41, 306.02} _ }   dim as double b(1 to 6) = { -0.01, 0.61, 0.91, 0.99, 0.60, 0.02 }   redim as double result() GaussJordan(a(),b(),result())   for n as long=lbound(result) to ubound(result) print result(n) next n sleep  
http://rosettacode.org/wiki/Gauss-Jordan_matrix_inversion
Gauss-Jordan matrix inversion
Task Invert matrix   A   using Gauss-Jordan method. A   being an   n × n   matrix.
#Kotlin
Kotlin
// version 1.2.21   typealias Matrix = Array<DoubleArray>   fun Matrix.inverse(): Matrix { val len = this.size require(this.all { it.size == len }) { "Not a square matrix" } val aug = Array(len) { DoubleArray(2 * len) } for (i in 0 until len) { for (j in 0 until len) aug[i][j] = this[i][j] // augment by identity matrix to right aug[i][i + len] = 1.0 } aug.toReducedRowEchelonForm() val inv = Array(len) { DoubleArray(len) } // remove identity matrix to left for (i in 0 until len) { for (j in len until 2 * len) inv[i][j - len] = aug[i][j] } return inv }   fun Matrix.toReducedRowEchelonForm() { var lead = 0 val rowCount = this.size val colCount = this[0].size for (r in 0 until rowCount) { if (colCount <= lead) return var i = r   while (this[i][lead] == 0.0) { i++ if (rowCount == i) { i = r lead++ if (colCount == lead) return } }   val temp = this[i] this[i] = this[r] this[r] = temp   if (this[r][lead] != 0.0) { val div = this[r][lead] for (j in 0 until colCount) this[r][j] /= div }   for (k in 0 until rowCount) { if (k != r) { val mult = this[k][lead] for (j in 0 until colCount) this[k][j] -= this[r][j] * mult } }   lead++ } }   fun Matrix.printf(title: String) { println(title) val rowCount = this.size val colCount = this[0].size   for (r in 0 until rowCount) { for (c in 0 until colCount) { if (this[r][c] == -0.0) this[r][c] = 0.0 // get rid of negative zeros print("${"% 10.6f".format(this[r][c])} ") } println() }   println() }   fun main(args: Array<String>) { val a = arrayOf( doubleArrayOf(1.0, 2.0, 3.0), doubleArrayOf(4.0, 1.0, 6.0), doubleArrayOf(7.0, 8.0, 9.0) ) a.inverse().printf("Inverse of A is :\n")   val b = arrayOf( doubleArrayOf( 2.0, -1.0, 0.0), doubleArrayOf(-1.0, 2.0, -1.0), doubleArrayOf( 0.0, -1.0, 2.0) ) b.inverse().printf("Inverse of B is :\n") }
http://rosettacode.org/wiki/General_FizzBuzz
General FizzBuzz
Task Write a generalized version of FizzBuzz that works for any list of factors, along with their words. This is basically a "fizzbuzz" implementation where the user supplies the parameters. The user will enter the max number, then they will enter the factors to be calculated along with the corresponding word to be printed. For simplicity's sake, assume the user will input an integer as the max number and 3 factors, each with a word associated with them. For example, given: >20 #This is the maximum number, supplied by the user >3 Fizz #The user now enters the starting factor (3) and the word they want associated with it (Fizz) >5 Buzz #The user now enters the next factor (5) and the word they want associated with it (Buzz) >7 Baxx #The user now enters the next factor (7) and the word they want associated with it (Baxx) In other words: For this example, print the numbers 1 through 20, replacing every multiple of 3 with "Fizz", every multiple of 5 with "Buzz", and every multiple of 7 with "Baxx". In the case where a number is a multiple of at least two factors, print each of the words associated with those factors in the order of least to greatest factor. For instance, the number 15 is a multiple of both 3 and 5; print "FizzBuzz". If the max number was 105 instead of 20, you would print "FizzBuzzBaxx" because it's a multiple of 3, 5, and 7. Output: 1 2 Fizz 4 Buzz Fizz Baxx 8 Fizz Buzz 11 Fizz 13 Baxx FizzBuzz 16 17 Fizz 19 Buzz
#J
J
genfb=:1 :0 : b=. * x|/1+i.y >,&":&.>/(m#inv"_1~-.b),(*/b)#&.>1+i.y )