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/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
#Forth
Forth
: printit 26 0 do [char] a I + emit loop ;
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
#Fortran
Fortran
character(26) :: alpha integer :: i   do i = 1, 26 alpha(i:i) = achar(iachar('a') + i - 1) end do
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
#Oz
Oz
{Show "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
#PARI.2FGP
PARI/GP
g = List(1); \\ generator stack   genpow(p) = my(a=g[1]++);listput(g,[0,p]);()->g[a][1]++^g[a][2];   genpowf(p,f) = my(a=g[1]++);listput(g,[0,p]);(s=0)->my(q);while(ispower(p=g[a][1]++^g[a][2],f)||(s&&q++<=s),);p;
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.
#Scheme
Scheme
(import (scheme base) (scheme write) (srfi 1) ; list library (srfi 27)) ; random numbers   (random-source-randomize! default-random-source)   ;; Random integer in [start, end) (define (random-between start end) (let ((len (- end start 1))) (if (< len 2) start (+ start (random-integer len)))))   ;; Random item in list (define (random-pick lst) (if (= 1 (length lst)) (car lst) (list-ref lst (random-integer (length lst)))))   ;; Construct a random piece placement for Chess960 (define (random-piece-positions) (define (free-indices positions) ; return list of empty slot indices (let loop ((i 0) (free '())) (if (= 8 i) free (loop (+ 1 i) (if (string=? "." (vector-ref positions i)) (cons i free) free))))) ; (define (place-king+rooks positions) (let ((king-posn (random-between 1 8))) (vector-set! positions king-posn "K") ; left-rook is between left-edge and king (vector-set! positions (random-between 0 king-posn) "R") ; right-rook is between right-edge and king (vector-set! positions (random-between (+ 1 king-posn) 8) "R"))) ; (define (place-bishops positions) (let-values (((evens odds) (partition even? (free-indices positions)))) (vector-set! positions (random-pick evens) "B") (vector-set! positions (random-pick odds) "B"))) ; (let ((positions (make-vector 8 "."))) (place-king+rooks positions) (place-bishops positions) ;; place the queen in a random remaining slot (vector-set! positions (random-pick (free-indices positions)) "Q") ;; place the two knights in the remaining slots (for-each (lambda (idx) (vector-set! positions idx "N")) (free-indices positions))   positions))   (display "First rank: ") (display (random-piece-positions)) (newline)  
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.
#Bracmat
Bracmat
( ( compose = f g . !arg:(?f.?g)&'(.($f)$(($g)$!arg)) ) & compose $ ( (=.flt$(!arg,2)) . compose$((=.!arg*5/9).(=.!arg+-32)) )  : (=?FahrenheitToCelsius) & ( FahrenheitToCelsiusExample = deg . chu$(x2d$b0):?deg & out $ ( str $ (!arg " " !deg "F in " !deg "C = " FahrenheitToCelsius$!arg) ) ) & FahrenheitToCelsiusExample$0 & FahrenheitToCelsiusExample$100 )
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.
#Brat
Brat
compose = { f, g | { x | f g x } }   #Test add1 = { x | x + 1 } double = { x | x * 2 } b = compose(->double ->add1) p b 1 #should print 4
http://rosettacode.org/wiki/Fractal_tree
Fractal tree
Generate and draw a fractal tree. Draw the trunk At the end of the trunk, split by some angle and draw two branches Repeat at the end of each branch until a sufficient level of branching is reached Related tasks Pythagoras Tree
#BASIC
BASIC
graphsize 300,300   level = 12 : len =63 # initial values x = 230: y = 285 rotation = pi/2   A1 = pi/27 : A2 = pi/8 # constants which determine shape C1 = 0.7 : C2 = 0.85   dim xs(level+1) : dim ys(level+1) # stacks   fastgraphics color black rect 0,0,graphwidth,graphheight refresh color green gosub tree refresh imgsave "Fractal_tree_BASIC-256.png", "PNG" end   tree: xs[level] = x : ys[level] = y gosub putline if level>0 then level = level - 1 len = len*C1 rotation = rotation - A1 gosub tree len = len/C1*C2 rotation = rotation + A1 + A2 gosub tree rotation = rotation - A2 len = len/C2 level = level + 1 end if x = xs[level] : y = ys[level] return   putline: yn = -sin(rotation)*len + y xn = cos(rotation)*len + x line x,y,xn,yn x = xn : y = yn return
http://rosettacode.org/wiki/Fractal_tree
Fractal tree
Generate and draw a fractal tree. Draw the trunk At the end of the trunk, split by some angle and draw two branches Repeat at the end of each branch until a sufficient level of branching is reached Related tasks Pythagoras Tree
#C
C
#include <SDL/SDL.h> #ifdef WITH_CAIRO #include <cairo.h> #else #include <SDL/sge.h> #endif #include <cairo.h> #include <stdlib.h> #include <time.h> #include <math.h>   #ifdef WITH_CAIRO #define PI 3.1415926535 #endif   #define SIZE 800 // determines size of window #define SCALE 5 // determines how quickly branches shrink (higher value means faster shrinking) #define BRANCHES 14 // number of branches #define ROTATION_SCALE 0.75 // determines how slowly the angle between branches shrinks (higher value means slower shrinking) #define INITIAL_LENGTH 50 // length of first branch   double rand_fl(){ return (double)rand() / (double)RAND_MAX; }   void draw_tree(SDL_Surface * surface, double offsetx, double offsety, double directionx, double directiony, double size, double rotation, int depth) { #ifdef WITH_CAIRO cairo_surface_t *surf = cairo_image_surface_create_for_data( surface->pixels, CAIRO_FORMAT_RGB24, surface->w, surface->h, surface->pitch ); cairo_t *ct = cairo_create(surf);   cairo_set_line_width(ct, 1); cairo_set_source_rgba(ct, 0,0,0,1); cairo_move_to(ct, (int)offsetx, (int)offsety); cairo_line_to(ct, (int)(offsetx + directionx * size), (int)(offsety + directiony * size)); cairo_stroke(ct); #else sge_AALine(surface, (int)offsetx, (int)offsety, (int)(offsetx + directionx * size), (int)(offsety + directiony * size), SDL_MapRGB(surface->format, 0, 0, 0)); #endif if (depth > 0){ // draw left branch draw_tree(surface, offsetx + directionx * size, offsety + directiony * size, directionx * cos(rotation) + directiony * sin(rotation), directionx * -sin(rotation) + directiony * cos(rotation), size * rand_fl() / SCALE + size * (SCALE - 1) / SCALE, rotation * ROTATION_SCALE, depth - 1);   // draw right branch draw_tree(surface, offsetx + directionx * size, offsety + directiony * size, directionx * cos(-rotation) + directiony * sin(-rotation), directionx * -sin(-rotation) + directiony * cos(-rotation), size * rand_fl() / SCALE + size * (SCALE - 1) / SCALE, rotation * ROTATION_SCALE, depth - 1); } }   void render(SDL_Surface * surface){ SDL_FillRect(surface, NULL, SDL_MapRGB(surface->format, 255, 255, 255)); draw_tree(surface, surface->w / 2.0, surface->h - 10.0, 0.0, -1.0, INITIAL_LENGTH, PI / 8, BRANCHES); SDL_UpdateRect(surface, 0, 0, 0, 0); }   int main(){ SDL_Surface * screen; SDL_Event evt;   SDL_Init(SDL_INIT_VIDEO);   srand((unsigned)time(NULL));   screen = SDL_SetVideoMode(SIZE, SIZE, 32, SDL_HWSURFACE);   render(screen); while(1){ if (SDL_PollEvent(&evt)){ if(evt.type == SDL_QUIT) break; } SDL_Delay(1); } SDL_Quit(); return 0; }
http://rosettacode.org/wiki/Fraction_reduction
Fraction reduction
There is a fine line between numerator and denominator.       ─── anonymous A method to   "reduce"   some reducible fractions is to   cross out   a digit from the numerator and the denominator.   An example is: 16 16 ──── and then (simply) cross─out the sixes: ──── 64 64 resulting in: 1 ─── 4 Naturally,   this "method" of reduction must reduce to the proper value   (shown as a fraction). This "method" is also known as   anomalous cancellation   and also   accidental cancellation. (Of course,   this "method" shouldn't be taught to impressionable or gullible minds.)       😇 Task Find and show some fractions that can be reduced by the above "method".   show 2-digit fractions found   (like the example shown above)   show 3-digit fractions   show 4-digit fractions   show 5-digit fractions   (and higher)       (optional)   show each (above) n-digit fractions separately from other different n-sized fractions, don't mix different "sizes" together   for each "size" fraction,   only show a dozen examples   (the 1st twelve found)   (it's recognized that not every programming solution will have the same generation algorithm)   for each "size" fraction:   show a count of how many reducible fractions were found.   The example (above) is size 2   show a count of which digits were crossed out   (one line for each different digit)   for each "size" fraction,   show a count of how many were found.   The example (above) is size 2   show each n-digit example   (to be shown on one line):   show each n-digit fraction   show each reduced n-digit fraction   show what digit was crossed out for the numerator and the denominator Task requirements/restrictions   only proper fractions and their reductions   (the result)   are to be used   (no vulgar fractions)   only positive fractions are to be used   (no negative signs anywhere)   only base ten integers are to be used for the numerator and denominator   no zeros   (decimal digit)   can be used within the numerator or the denominator   the numerator and denominator should be composed of the same number of digits   no digit can be repeated in the numerator   no digit can be repeated in the denominator   (naturally)   there should be a shared decimal digit in the numerator   and   the denominator   fractions can be shown as   16/64   (for example) Show all output here, on this page. Somewhat related task   Farey sequence       (It concerns fractions.) References   Wikipedia entry:   proper and improper fractions.   Wikipedia entry:   anomalous cancellation and/or accidental cancellation.
#11l
11l
F indexOf(haystack, needle) V idx = 0 L(straw) haystack I straw == needle R idx E idx++ R -1   F getDigits(=n, =le, &digits) L n > 0 V r = n % 10 I r == 0 | indexOf(digits, r) >= 0 R 0B le-- digits[le] = r n = Int(n / 10) R 1B   F removeDigit(digits, le, idx) V pows = [1, 10, 100, 1000, 10000] V sum = 0 V pow = pows[le - 2] V i = 0 L i < le I i == idx i++ L.continue sum = sum + digits[i] * pow pow = Int(pow / 10) i++ R sum   V lims = [ [ 12, 97 ], [ 123, 986 ], [ 1234, 9875 ], [ 12345, 98764 ] ] V count = [0] * 5 V omitted = [[0] * 10] * 5   V i = 0 L i < lims.len V n = lims[i][0] L n < lims[i][1] V nDigits = [0] * (i + 2) V nOk = getDigits(n, i + 2, &nDigits) I !nOk n++ L.continue V d = n + 1 L d <= lims[i][1] + 1 V dDigits = [0] * (i + 2) V dOk = getDigits(d, i + 2, &dDigits) I !dOk d++ L.continue V nix = 0 L nix < nDigits.len V digit = nDigits[nix] V dix = indexOf(dDigits, digit) I dix >= 0 V rn = removeDigit(nDigits, i + 2, nix) V rd = removeDigit(dDigits, i + 2, dix) I (1.0 * n / d) == (1.0 * rn / rd) count[i]++ omitted[i][digit]++ I count[i] <= 12 print(‘#./#. = #./#. by omitting #.'s’.format(n, d, rn, rd, digit)) nix++ d++ n++ print() i++   i = 2 L i <= 5 print(‘There are #. #.-digit fractions of which:’.format(count[i - 2], i)) V j = 1 L j <= 9 I omitted[i - 2][j] == 0 j++ L.continue print(‘#6 have #.'s omitted’.format(omitted[i - 2][j], j)) j++ print() i++
http://rosettacode.org/wiki/Fractran
Fractran
FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway. A FRACTRAN program is an ordered list of positive fractions P = ( f 1 , f 2 , … , f m ) {\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})} , together with an initial positive integer input n {\displaystyle n} . The program is run by updating the integer n {\displaystyle n} as follows: for the first fraction, f i {\displaystyle f_{i}} , in the list for which n f i {\displaystyle nf_{i}} is an integer, replace n {\displaystyle n} with n f i {\displaystyle nf_{i}}  ; repeat this rule until no fraction in the list produces an integer when multiplied by n {\displaystyle n} , then halt. Conway gave a program for primes in FRACTRAN: 17 / 91 {\displaystyle 17/91} , 78 / 85 {\displaystyle 78/85} , 19 / 51 {\displaystyle 19/51} , 23 / 38 {\displaystyle 23/38} , 29 / 33 {\displaystyle 29/33} , 77 / 29 {\displaystyle 77/29} , 95 / 23 {\displaystyle 95/23} , 77 / 19 {\displaystyle 77/19} , 1 / 17 {\displaystyle 1/17} , 11 / 13 {\displaystyle 11/13} , 13 / 11 {\displaystyle 13/11} , 15 / 14 {\displaystyle 15/14} , 15 / 2 {\displaystyle 15/2} , 55 / 1 {\displaystyle 55/1} Starting with n = 2 {\displaystyle n=2} , this FRACTRAN program will change n {\displaystyle n} to 15 = 2 × ( 15 / 2 ) {\displaystyle 15=2\times (15/2)} , then 825 = 15 × ( 55 / 1 ) {\displaystyle 825=15\times (55/1)} , generating the following sequence of integers: 2 {\displaystyle 2} , 15 {\displaystyle 15} , 825 {\displaystyle 825} , 725 {\displaystyle 725} , 1925 {\displaystyle 1925} , 2275 {\displaystyle 2275} , 425 {\displaystyle 425} , 390 {\displaystyle 390} , 330 {\displaystyle 330} , 290 {\displaystyle 290} , 770 {\displaystyle 770} , … {\displaystyle \ldots } After 2, this sequence contains the following powers of 2: 2 2 = 4 {\displaystyle 2^{2}=4} , 2 3 = 8 {\displaystyle 2^{3}=8} , 2 5 = 32 {\displaystyle 2^{5}=32} , 2 7 = 128 {\displaystyle 2^{7}=128} , 2 11 = 2048 {\displaystyle 2^{11}=2048} , 2 13 = 8192 {\displaystyle 2^{13}=8192} , 2 17 = 131072 {\displaystyle 2^{17}=131072} , 2 19 = 524288 {\displaystyle 2^{19}=524288} , … {\displaystyle \ldots } which are the prime powers of 2. Task Write a program that reads a list of fractions in a natural format from the keyboard or from a string, to parse it into a sequence of fractions (i.e. two integers), and runs the FRACTRAN starting from a provided integer, writing the result at each step. It is also required that the number of steps is limited (by a parameter easy to find). Extra credit Use this program to derive the first 20 or so prime numbers. See also For more on how to program FRACTRAN as a universal programming language, see: J. H. Conway (1987). Fractran: A Simple Universal Programming Language for Arithmetic. In: Open Problems in Communication and Computation, pages 4–26. Springer. J. H. Conway (2010). "FRACTRAN: A simple universal programming language for arithmetic". In Jeffrey C. Lagarias. The Ultimate Challenge: the 3x+1 problem. American Mathematical Society. pp. 249–264. ISBN 978-0-8218-4940-8. Zbl 1216.68068. Number Pathology: Fractran by Mark C. Chu-Carroll; October 27, 2006.
#bash
bash
#! /bin/bash program="1/1 455/33 11/13 1/11 3/7 11/2 1/3" echo $program | tr " " "\n" | cut -d"/" -f1 | tr "\n" " " > "data" read -a ns < "data" echo $program | tr " " "\n" | cut -d"/" -f2 | tr "\n" " " > "data" read -a ds < "data"     t=0 n=72 echo "steps of computation" > steps.csv while [ $t -le 6 ]; do if [ $(($n*${ns[$t]}%${ds[$t]})) -eq 0 ]; then let "n=$(($n*${ns[$t]}/${ds[$t]}))" let "t=0" factor $n >> steps.csv fi let "t=$t+1" done  
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.
#PHP
PHP
  $server = "speedtest.tele2.net"; $user = "anonymous"; $pass = "[email protected]";   $conn = ftp_connect($server); if (!$conn) { die('unable to connect to: '. $server); } $login = ftp_login($conn, $user, $pass); if (!$login) { echo 'unable to log in to '. $server. ' with user: '.$user.' and pass: '. $pass; } else{ echo 'connected successfully'.PHP_EOL; $directory = ftp_nlist($conn,''); print_r($directory); } if (ftp_get($conn, '1KB.zip', '1KB.zip', FTP_BINARY)) { echo "Successfully downloaded file".PHP_EOL; } else { echo "failed to download file"; }
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.
#PicoLisp
PicoLisp
(in '(curl "-sl" "ftp://kernel.org/pub/site/") (while (line) (prinl @) ) ) (call "curl" "-s" "-o" "sha256sums.asc" "ftp://kernel.org/pub/site/sha256sums.asc")
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.
#Python
Python
  from ftplib import FTP ftp = FTP('kernel.org') ftp.login() ftp.cwd('/pub/linux/kernel') ftp.set_pasv(True) # Default since Python 2.1 print ftp.retrlines('LIST') print ftp.retrbinary('RETR README', open('README', 'wb').write) ftp.quit()  
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.
#Quackery
Quackery
forward is fibonacci ( n --> n )   [ dup 2 < if done dup 1 - fibonacci swap 2 - fibonacci + ] resolves fibonacci ( n --> n )
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.
#Racket
Racket
  #lang racket   (define (no-arg) (void))   (define (two-args a b) (void)) ;arguments are always named   (define (varargs . args) (void)) ;the extra arguments are stored in a list   (define (varargs2 a . args) (void)) ;one obligatory argument and the rest are contained in the list   (define (optional-arg (a 5)) (void)) ;a defaults to 5
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.
#Raku
Raku
sub foo ( --> Int) {...}
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
#ActionScript
ActionScript
function multiply(a:Number, b:Number):Number { return 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
#Sidef
Sidef
require('DateTime')   var month_names = %w( Vendémiaire Brumaire Frimaire Nivôse Pluviôse Ventôse Germinal Floréal Prairial Messidor Thermidor Fructidor )   var intercalary = [ 'Fête de la vertu', 'Fête du génie', 'Fête du travail', "Fête de l'opinion", 'Fête des récompenses', 'Fête de la Révolution', ]   var i_cal_month = 13 var epoch = %O<DateTime>.new(year => 1792, month => 9, day => 22)   var month_nums = Hash(month_names.kv.map {|p| [p[1], p[0]+1] }.flat...) var i_cal_nums = Hash(intercalary.kv.map {|p| [p[1], p[0]+1] }.flat...)   func is_republican_leap_year(Number year) -> Bool { var y = (year + 1)  !!(4.divides(y) && (!100.divides(y) || 400.divides(y))) }   func Republican_to_Gregorian(String rep_date) -> String { static months = month_names.map { .escape }.join('|') static intercal = intercalary.map { .escape }.join('|') static re = Regex("^ \\s* (?: (?<ic> #{intercal}) | (?<day> \\d+) \\s+ (?<month> #{months}) ) \\s+ (?<year> \\d+) \\s* \\z", 'x')   var m = (rep_date =~ re) m || die "Republican date not recognized: '#{rep_date}'"   var ncap = m.named_captures   var day1 = Number(ncap{:ic}  ? i_cal_nums{ncap{:ic}}  : ncap{:day}) var month1 = Number(ncap{:month} ? month_nums{ncap{:month}} : i_cal_month) var year1 = Number(ncap{:year})   var days_since_epoch = (365*(year1 - 1) + 30*(month1 - 1) + (day1 - 1))   var leap_days = (1 ..^ year1 -> grep { is_republican_leap_year(_) }) epoch.clone.add(days => (days_since_epoch + leap_days)).strftime("%Y-%m-%d") }   func Gregorian_to_Republican(String greg_date) -> String { var m = (greg_date =~ /^(\d{4})-(\d{2})-(\d{2})\z/) m || die "Gregorian date not recognized: '#{greg_date}'"   var g = %O<DateTime>.new(year => m[0], month => m[1], day => m[2]) var days_since_epoch = epoch.delta_days(g).in_units('days') days_since_epoch < 0 && die "unexpected error" var (year, days) = (1, days_since_epoch)   loop { var year_length = (365 + (is_republican_leap_year(year) ? 1 : 0)) days < year_length && break days -= year_length year += 1; }   var day0 = (days % 30) var month0 = (days - day0)/30   var (day1, month1) = (day0 + 1, month0 + 1)   (month1 == i_cal_month  ? "#{intercalary[day0]} #{year}"  : "#{day1} #{month_names[month0]} #{year}") }   for line in DATA {   line.sub!(/\s*\#.+\R?\z/, '')   var m = (line =~ /^(\d{4})-(\d{2})-(\d{2})\s+(\S.+?\S)\s*$/) m || die "error for: #{line.dump}"   var g = "#{m[0]}-#{m[1]}-#{m[2]}" var r = m[3]   var r2g = Republican_to_Gregorian(r) var g2r = Gregorian_to_Republican(g)   #say "#{r} -> #{r2g}" #say "#{g} -> #{g2r}"   if ((g2r != r) || (r2g != g)) { die "1-way error" }   if ((Gregorian_to_Republican(r2g) != r) || (Republican_to_Gregorian(g2r) != g) ) { die "2-way error" } }   say 'All tests successful.'   __DATA__ 1792-09-22 1 Vendémiaire 1 1795-05-20 1 Prairial 3 1799-07-15 27 Messidor 7 1803-09-23 Fête de la Révolution 11 1805-12-31 10 Nivôse 14 1871-03-18 27 Ventôse 79 1944-08-25 7 Fructidor 152 2016-09-19 Fête du travail 224 1871-05-06 16 Floréal 79 # Paris Commune begins 1871-05-23 3 Prairial 79 # Paris Commune ends 1799-11-09 18 Brumaire 8 # Revolution ends by Napoléon coup 1804-12-02 11 Frimaire 13 # Republic ends by Napoléon coronation 1794-10-30 9 Brumaire 3 # École Normale Supérieure established 1794-07-27 9 Thermidor 2 # Robespierre falls 1799-05-27 8 Prairial 7 # Fromental Halévy born 1792-09-22 1 Vendémiaire 1 1793-09-22 1 Vendémiaire 2 1794-09-22 1 Vendémiaire 3 1795-09-23 1 Vendémiaire 4 1796-09-22 1 Vendémiaire 5 1797-09-22 1 Vendémiaire 6 1798-09-22 1 Vendémiaire 7 1799-09-23 1 Vendémiaire 8 1800-09-23 1 Vendémiaire 9 1801-09-23 1 Vendémiaire 10 1802-09-23 1 Vendémiaire 11 1803-09-24 1 Vendémiaire 12 1804-09-23 1 Vendémiaire 13 1805-09-23 1 Vendémiaire 14 1806-09-23 1 Vendémiaire 15 1807-09-24 1 Vendémiaire 16 1808-09-23 1 Vendémiaire 17 1809-09-23 1 Vendémiaire 18 1810-09-23 1 Vendémiaire 19 1811-09-24 1 Vendémiaire 20 2015-09-23 1 Vendémiaire 224 2016-09-22 1 Vendémiaire 225 2017-09-22 1 Vendémiaire 226
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.
#Delphi
Delphi
let n = 61 let l = [0, 1]   func fusc(n) { return l[n] when n < l.Length() let f = (n &&& 1) == 0 ? l[n >>> 1] : l[(n - 1) >>> 1] + l[(n + 1) >>> 1] l.Add(f) return f }   var lst = true var w = -1 var c = 0 var t = nil var res = ""   print("First \(n) numbers in the fusc sequence:") for i in 0..Integer.Max { let f = fusc(i) if lst { if i < 61 { print("\(f) ", terminator: "") } else { lst = false print("") print("Points in the sequence where an item has more digits than any previous items:") print("Index/Value:") print(res) res = "" } } t = f.ToString().Length() if t > w { w = t res += (res == "" ? "" : "\n") + "\(i)/\(f)" if !lst { print(res) res = "" } c += 1 if c > 5 { break } } } l.Clear()
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.
#Dyalect
Dyalect
let n = 61 let l = [0, 1]   func fusc(n) { return l[n] when n < l.Length() let f = (n &&& 1) == 0 ? l[n >>> 1] : l[(n - 1) >>> 1] + l[(n + 1) >>> 1] l.Add(f) return f }   var lst = true var w = -1 var c = 0 var t = nil var res = ""   print("First \(n) numbers in the fusc sequence:") for i in 0..Integer.Max { let f = fusc(i) if lst { if i < 61 { print("\(f) ", terminator: "") } else { lst = false print("") print("Points in the sequence where an item has more digits than any previous items:") print("Index/Value:") print(res) res = "" } } t = f.ToString().Length() if t > w { w = t res += (res == "" ? "" : "\n") + "\(i)/\(f)" if !lst { print(res) res = "" } c += 1 if c > 5 { break } } } l.Clear()
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.
#REXX
REXX
fid='pgm.rex' cnt.=0 funl='' Do While lines(fid)>0 l=linein(fid) Do Until p=0 p=pos('(',l) If p>0 Then Do do i=p-1 To 1 By -1 While is_tc(substr(l,i,1)) End fn=substr(l,i+1,p-i-1) If fn<>'' Then Call store fn l=substr(l,p+1) End End End Do While funl<>'' Parse Var funl fn funl Say right(cnt.fn,3) fn End Exit x=a(3)+bbbbb(5,c(555)) special=date('S') 'DATE'() "date"() is_tc: abc='abcdefghijklmnopqrstuvwxyz' Return pos(arg(1),abc||translate(abc)'1234567890_''"')>0   store: Parse Arg fun cnt.fun=cnt.fun+1 If cnt.fun=1 Then funl=funl fun Return
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.
#Sidef
Sidef
func foo { } func bar { }   foo(); foo(); foo() bar(); bar();   var data = Perl.to_sidef(Parser{:vars}{:main}).flatten   data.sort_by { |v| -v{:count} }.first(10).each { |entry| if (entry{:type} == :func) { say ("Function `#{entry{:name}}` (declared at line", " #{entry{:line}}) is used #{entry{:count}} times") } }
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
#Crystal
Crystal
# Taylor Series def a [ 1.00000_00000_00000_00000, 0.57721_56649_01532_86061, -0.65587_80715_20253_88108, -0.04200_26350_34095_23553, 0.16653_86113_82291_48950, -0.04219_77345_55544_33675, -0.00962_19715_27876_97356, 0.00721_89432_46663_09954, -0.00116_51675_91859_06511, -0.00021_52416_74114_95097, 0.00012_80502_82388_11619, -0.00002_01348_54780_78824, -0.00000_12504_93482_14267, 0.00000_11330_27231_98170, -0.00000_02056_33841_69776, 0.00000_00061_16095_10448, 0.00000_00050_02007_64447, -0.00000_00011_81274_57049, 0.00000_00001_04342_67117, 0.00000_00000_07782_26344, -0.00000_00000_03696_80562, 0.00000_00000_00510_03703, -0.00000_00000_00020_58326, -0.00000_00000_00005_34812, 0.00000_00000_00001_22678, -0.00000_00000_00000_11813, 0.00000_00000_00000_00119, 0.00000_00000_00000_00141, -0.00000_00000_00000_00023, 0.00000_00000_00000_00002 ] end   def taylor_gamma(x) y = x.to_f - 1 1.0 / a.reverse.reduce(0) { |sum, an| sum * y + an } end   # Lanczos Method def p [ 0.99999_99999_99809_93, 676.52036_81218_851, -1259.13921_67224_028, 771.32342_87776_5313, -176.61502_91621_4059, 12.50734_32786_86905, -0.13857_10952_65720_12, 9.98436_95780_19571_6e-6, 1.50563_27351_49311_6e-7 ] end   def lanczos_gamma(z) # Reflection formula z = z.to_f if z < 0.5 Math::PI / (Math.sin(Math::PI * z) * lanczos_gamma(1 - z)) else z -= 1 x = p[0] (1..p.size - 1).each { |i| x += p[i] / (z + i) } t = z + p.size - 1.5 Math.sqrt(2 * Math::PI) * t**(z + 0.5) * Math.exp(-t) * x end end   puts " Taylor Series Lanczos Method Builtin Function" (1..27).each { |i| n = i/3.0; puts "gamma(%.2f) = %.14e  %.14e  %.14e" % [n, taylor_gamma(n), lanczos_gamma(n), Math.gamma(n)] }  
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.
#Liberty_BASIC
Liberty BASIC
  [setup] nomainwin   speed=50   prompt "Number of balls to drop: ";cycleMax cycleMax=abs(int(cycleMax))   'create window WindowWidth=400 WindowHeight=470 UpperLeftX=1 UpperLeftY=1 graphicbox #1.gb, 10, 410,370,25 open "Galton Machine" for graphics_nf_nsb as #1 #1 "trapclose [q];down;fill black;flush" #1.gb "font courier_new 12"   'Create graphical sprites #1 "getbmp bg 1 1 400 600" #1 "place 0 0; color white;backcolor white;boxfilled 17 17;place 8 8;color black;backcolor black;circlefilled 8;" #1 "place 8 25;color white;backcolor white;circlefilled 8;" #1 "getbmp ball 0 0 17 34" #1 "place 8 25;color red;backcolor red;circlefilled 8;" #1 "getbmp pin 0 0 17 34" #1 "background bg"   'add sprites to program for pinCount = 1 to 28 #1 "addsprite pin";pinCount;" pin;spriteround pin";pinCount next pinCount   for ballCount = 1 to 7 #1 "addsprite ball";ballCount;" ball;spriteround ball";ballCount next ballCount   'place pins on page for y = 1 to 7 for x = 1 to y pin=pin+1 xp=200-x*50+y*25 yp=y*35+100 #1 "spritexy pin";pin;" ";xp;" ";yp #1 "drawsprites" next x next y   'set balls in motion for a = 1 to 7 #1 "spritexy ball";a;" 174 ";a*60-350 #1 "spritemovexy ball";a;" 0 5" next a   [start] 'update every 50ms - lower number means faster updates timer speed, [move] wait   [move] 'cycle through the sprites to check for contact with pins or dropping off board #1 "drawsprites" for ballNum = 1 to 7 gosub [checkCollide] next ballNum timer speed, [move] wait   [checkCollide] 'check for contact with pins or dropping off board timer 0 #1 "spritexy? ball";ballNum;" x y" 'get current ball position #1 "spritecollides ball";ballNum;" hits$" 'collect any collisions if hits$<>"" then 'any collisions? if so... direction = rnd(1) 'randomly bounce either left or right if direction >0.4999999 then #1 "spritexy ball";ballNum;" ";x+25;" ";y else #1 "spritexy ball";ballNum;" ";x-25;" ";y #1 "spritemovexy ball";ballNum;" 0 5"'set ball in motion again end if #1 "spritexy? ball";ballNum;" x y" 'get current ball position if y > 400 then 'if ball has dropped off board, then... select case 'figure out which slot it has landed in and increment the counter for that slot case x<49 slot(1)=slot(1)+1 case x=49 slot(2)=slot(2)+1 case x=99 slot(3)=slot(3)+1 case x=149 slot(4)=slot(4)+1 case x=199 slot(5)=slot(5)+1 case x=249 slot(6)=slot(6)+1 case x=299 slot(7)=slot(7)+1 case x>299 slot(8)=slot(8)+1 end select for a = 1 to 8 'write the slot counts in the small graphic box update$="place "+str$((a-1)*48+1)+" 20;\"+str$(slot(a)) #1.gb, update$ next a #1 "spritexy ball";ballNum;" 174 ";0-10 'reposition the sprite just off the top of the screen #1 "spritemovexy ball";ballNum;" 0 5" 'set the ball in motion again cycles = cycles + 1 'increment the fallen ball count if cycles >= cycleMax then timer 0 'stop animation 'make the visible balls go away for a = 1 to 7 #1 "spritexy ball";a;" 174 700" #1 "spritemovexy ball";a;" 0 0" next a #1 "drawsprites" notice "Complete" wait end if end if return   [q] close #1 'It is IMPORTANT to unload the bitmaps and clear memory unloadbmp "pin" unloadbmp "ball" unloadbmp "bg" end  
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
#jq
jq
# emit a stream of gapful numbers greater than or equal to $start, # which is assumed to be an integer def gapful($start): range($start; infinite) | . as $i | tostring as $s | (($s[:1] + $s[-1:]) | tonumber) as $x | select($i % $x == 0);   "First 30 gapful numbersstarting from 100:", ([limit(30;gapful(100))] | join(" ")), "First 15 gapful numbers starting from 1,000,000:", ([limit(15;gapful(1000000))] | join(" ")), "First 10 gapful numbers starting from 10^9:", ([limit(10;gapful(pow(10;9)))] | join(" "))
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
#Julia
Julia
using Lazy, Formatting   firstlast(a) = 10 * a[end] + a[1] isgapful(n) = (d = digits(n); length(d) < 3 || (m = firstlast(d)) != 0 && mod(n, m) == 0) gapfuls(start) = filter(isgapful, Lazy.range(start))   for (x, n) in [(100, 30), (1_000_000, 15), (1_000_000_000, 10)] println("First $n gapful numbers starting at ", format(x, commas=true), ":\n", take(n, gapfuls(x))) end  
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
#Julia
Julia
x = A \ b
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.
#Python
Python
  import numpy as np from numpy.linalg import inv a = np.array([[1., 2., 3.], [4., 1., 6.],[ 7., 8., 9.]]) ainv = inv(a)   print(a) print(ainv)  
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
#PARI.2FGP
PARI/GP
fizz(n,v[..])= { v=vecsort(v,1); for(k=1,n, my(t); for(i=1,#v, if(k%v[i][1]==0, print1(v[i][2]); t=1 ) ); print(if(t,"",k)) ); } fizz(20,[3,"Fizz"],[5,"Buzz"],[7,"Baxx"])
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
#Free_Pascal
Free Pascal
program lowerCaseAscii(input, output, stdErr); const alphabet = ['a'..'z']; begin end.
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
#Frink
Frink
map["char", char["a"] to char["z"]]
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
#PARI.2FGP
PARI/GP
print("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
#Perl
Perl
# gen_pow($m) creates and returns an anonymous subroutine that will # generate and return the powers 0**m, 1**m, 2**m, ... sub gen_pow { my $m = shift; my $e = 0; return sub { return $e++ ** $m; }; }   # gen_filter($g1, $g2) generates everything returned from $g1 that # is not also returned from $g2. Both $g1 and $g2 must be references # to subroutines that generate numbers in increasing order. gen_filter # creates and returns an anonymous subroutine. sub gen_filter { my($g1, $g2) = @_; my $v1; my $v2 = $g2->(); return sub { for (;;) { $v1 = $g1->(); $v2 = $g2->() while $v1 > $v2; return $v1 unless $v1 == $v2; } }; }   # Create generators. my $squares = gen_pow(2); my $cubes = gen_pow(3); my $squares_without_cubes = gen_filter($squares, $cubes);   # Drop 20 values. $squares_without_cubes->() for (1..20);   # Print 10 values. my @answer; push @answer, $squares_without_cubes->() for (1..10); print "[", join(", ", @answer), "]\n";
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.
#Seed7
Seed7
$ include "seed7_05.s7i";   const proc: main is func local var string: start is "RKR"; var char: piece is ' '; var integer: pos is 0; begin for piece range "QNN" do pos := rand(1, succ(length(start))); start := start[.. pred(pos)] & str(piece) & start[pos ..]; end for; pos := rand(1, succ(length(start))); start := start[.. pred(pos)] & "B" & start[pos ..]; pos := succ(pos) + 2 * rand(0, (length(start) - pos) div 2); start := start[.. pred(pos)] & "B" & start[pos ..]; writeln(start); end func;
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.
#Sidef
Sidef
func is_valid_960 (backrank) { var king = backrank.index('♚') var (rook1, rook2) = backrank.indices_of('♜')... king.is_between(rook1, rook2) || return false var (bishop1, bishop2) = backrank.indices_of('♝')... bishop1+bishop2 -> is_odd }   func random_960_position(pieces = <♛ ♚ ♜ ♜ ♝ ♝ ♞ ♞>) { pieces.shuffle.permutations {|*a| return a if is_valid_960(a) } }   say random_960_position().join(' ')
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.
#C
C
#include <stdlib.h>   /* generic interface for functors from double to double */ typedef struct double_to_double { double (*fn)(struct double_to_double *, double); } double_to_double;   #define CALL(f, x) f->fn(f, x)     /* functor returned by compose */ typedef struct compose_functor { double (*fn)(struct compose_functor *, double); double_to_double *f; double_to_double *g; } compose_functor; /* function to be used in "fn" in preceding functor */ double compose_call(compose_functor *this, double x) { return CALL(this->f, CALL(this->g, x)); } /* returns functor that is the composition of functors f & g. caller is responsible for deallocating memory */ double_to_double *compose(double_to_double *f, double_to_double *g) { compose_functor *result = malloc(sizeof(compose_functor)); result->fn = &compose_call; result->f = f; result->g = g; return (double_to_double *)result; }       #include <math.h>   /* we can make functors for sin and asin by using the following as "fn" in a functor */ double sin_call(double_to_double *this, double x) { return sin(x); } double asin_call(double_to_double *this, double x) { return asin(x); }       #include <stdio.h>   int main() { double_to_double *my_sin = malloc(sizeof(double_to_double)); my_sin->fn = &sin_call; double_to_double *my_asin = malloc(sizeof(double_to_double)); my_asin->fn = &asin_call;   double_to_double *sin_asin = compose(my_sin, my_asin);   printf("%f\n", CALL(sin_asin, 0.5)); /* prints "0.500000" */   free(sin_asin); free(my_sin); free(my_asin);   return 0; }
http://rosettacode.org/wiki/Fractal_tree
Fractal tree
Generate and draw a fractal tree. Draw the trunk At the end of the trunk, split by some angle and draw two branches Repeat at the end of each branch until a sufficient level of branching is reached Related tasks Pythagoras Tree
#C.2B.2B
C++
  #include <windows.h> #include <string> #include <math.h>   //-------------------------------------------------------------------------------------------------- using namespace std;   //-------------------------------------------------------------------------------------------------- const float PI = 3.1415926536f;   //-------------------------------------------------------------------------------------------------- class myBitmap { public: myBitmap() : pen( NULL ) {} ~myBitmap() { DeleteObject( pen ); DeleteDC( hdc ); DeleteObject( bmp ); }   bool create( int w, int h ) { BITMAPINFO bi; void *pBits; 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 setPenColor( DWORD clr ) { if( pen ) DeleteObject( pen ); pen = CreatePen( PS_SOLID, 1, clr ); SelectObject( hdc, pen ); }   void saveBitmap( string path ) { BITMAPFILEHEADER fileheader; BITMAPINFO infoheader; BITMAP bitmap; DWORD* dwpBits; DWORD wb; HANDLE file;   GetObject( bmp, sizeof( bitmap ), &bitmap );   dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight]; ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) ); ZeroMemory( &infoheader, sizeof( BITMAPINFO ) ); ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );   infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8; infoheader.bmiHeader.biCompression = BI_RGB; infoheader.bmiHeader.biPlanes = 1; infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader ); infoheader.bmiHeader.biHeight = bitmap.bmHeight; infoheader.bmiHeader.biWidth = bitmap.bmWidth; infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );   fileheader.bfType = 0x4D42; fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER ); fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;   GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );   file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL ); WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL ); WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL ); CloseHandle( file );   delete [] dwpBits; }   HDC getDC() { return hdc; } int getWidth() { return width; } int getHeight() { return height; }   private: HBITMAP bmp; HDC hdc; HPEN pen; int width, height; }; //-------------------------------------------------------------------------------------------------- class vector2 { public: vector2() { x = y = 0; } vector2( int a, int b ) { x = a; y = b; } void set( int a, int b ) { x = a; y = b; } void rotate( float angle_r ) { float _x = static_cast<float>( x ), _y = static_cast<float>( y ), s = sinf( angle_r ), c = cosf( angle_r ), a = _x * c - _y * s, b = _x * s + _y * c;   x = static_cast<int>( a ); y = static_cast<int>( b ); }   int x, y; }; //-------------------------------------------------------------------------------------------------- class fractalTree { public: fractalTree() { _ang = DegToRadian( 24.0f ); } float DegToRadian( float degree ) { return degree * ( PI / 180.0f ); }   void create( myBitmap* bmp ) { _bmp = bmp; float line_len = 130.0f;   vector2 sp( _bmp->getWidth() / 2, _bmp->getHeight() - 1 ); MoveToEx( _bmp->getDC(), sp.x, sp.y, NULL ); sp.y -= static_cast<int>( line_len ); LineTo( _bmp->getDC(), sp.x, sp.y);   drawRL( &sp, line_len, 0, true ); drawRL( &sp, line_len, 0, false ); }   private: void drawRL( vector2* sp, float line_len, float a, bool rg ) { line_len *= .75f; if( line_len < 2.0f ) return;   MoveToEx( _bmp->getDC(), sp->x, sp->y, NULL ); vector2 r( 0, static_cast<int>( line_len ) );   if( rg ) a -= _ang; else a += _ang;   r.rotate( a ); r.x += sp->x; r.y = sp->y - r.y;   LineTo( _bmp->getDC(), r.x, r.y );   drawRL( &r, line_len, a, true ); drawRL( &r, line_len, a, false ); }   myBitmap* _bmp; float _ang; }; //-------------------------------------------------------------------------------------------------- int main( int argc, char* argv[] ) { ShowWindow( GetConsoleWindow(), SW_MAXIMIZE );   myBitmap bmp; bmp.create( 640, 512 ); bmp.setPenColor( RGB( 255, 255, 0 ) );   fractalTree tree; tree.create( &bmp );   BitBlt( GetDC( GetConsoleWindow() ), 0, 20, 648, 512, bmp.getDC(), 0, 0, SRCCOPY );   bmp.saveBitmap( "f://rc//fracTree.bmp" );   system( "pause" );   return 0; } //--------------------------------------------------------------------------------------------------  
http://rosettacode.org/wiki/Fraction_reduction
Fraction reduction
There is a fine line between numerator and denominator.       ─── anonymous A method to   "reduce"   some reducible fractions is to   cross out   a digit from the numerator and the denominator.   An example is: 16 16 ──── and then (simply) cross─out the sixes: ──── 64 64 resulting in: 1 ─── 4 Naturally,   this "method" of reduction must reduce to the proper value   (shown as a fraction). This "method" is also known as   anomalous cancellation   and also   accidental cancellation. (Of course,   this "method" shouldn't be taught to impressionable or gullible minds.)       😇 Task Find and show some fractions that can be reduced by the above "method".   show 2-digit fractions found   (like the example shown above)   show 3-digit fractions   show 4-digit fractions   show 5-digit fractions   (and higher)       (optional)   show each (above) n-digit fractions separately from other different n-sized fractions, don't mix different "sizes" together   for each "size" fraction,   only show a dozen examples   (the 1st twelve found)   (it's recognized that not every programming solution will have the same generation algorithm)   for each "size" fraction:   show a count of how many reducible fractions were found.   The example (above) is size 2   show a count of which digits were crossed out   (one line for each different digit)   for each "size" fraction,   show a count of how many were found.   The example (above) is size 2   show each n-digit example   (to be shown on one line):   show each n-digit fraction   show each reduced n-digit fraction   show what digit was crossed out for the numerator and the denominator Task requirements/restrictions   only proper fractions and their reductions   (the result)   are to be used   (no vulgar fractions)   only positive fractions are to be used   (no negative signs anywhere)   only base ten integers are to be used for the numerator and denominator   no zeros   (decimal digit)   can be used within the numerator or the denominator   the numerator and denominator should be composed of the same number of digits   no digit can be repeated in the numerator   no digit can be repeated in the denominator   (naturally)   there should be a shared decimal digit in the numerator   and   the denominator   fractions can be shown as   16/64   (for example) Show all output here, on this page. Somewhat related task   Farey sequence       (It concerns fractions.) References   Wikipedia entry:   proper and improper fractions.   Wikipedia entry:   anomalous cancellation and/or accidental cancellation.
#Ada
Ada
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; with Ada.Text_IO; use Ada.Text_IO; procedure Fraction_Reduction is   type Int_Array is array (Natural range <>) of Integer;   function indexOf(haystack : Int_Array; needle : Integer) return Integer is idx : Integer := 0; begin for straw of haystack loop if straw = needle then return idx; else idx := idx + 1; end if; end loop; return -1; end IndexOf;   function getDigits(n, le : in Integer; digit_array : in out Int_Array) return Boolean is n_local : Integer := n; le_local : Integer := le; r : Integer; begin while n_local > 0 loop r := n_local mod 10; if r = 0 or indexOf(digit_array, r) >= 0 then return False; end if; le_local := le_local - 1; digit_array(le_local) := r; n_local := n_local / 10; end loop; return True; end getDigits;   function removeDigit(digit_array : Int_Array; le, idx : Integer) return Integer is sum : Integer := 0; pow : Integer := 10 ** (le - 2); begin for i in 0 .. le - 1 loop if i /= idx then sum := sum + digit_array(i) * pow; pow := pow / 10; end if; end loop; return sum; end removeDigit;   lims : constant array (0 .. 3) of Int_Array (0 .. 1) := ((12, 97), (123, 986), (1234, 9875), (12345, 98764)); count : Int_Array (0 .. 4) := (others => 0); omitted : array (0 .. 4) of Int_Array (0 .. 9) := (others => (others => 0)); begin Ada.Integer_Text_IO.Default_Width := 0; for i in lims'Range loop declare nDigits, dDigits : Int_Array (0 .. i + 1); digit, dix, rn, rd : Integer; begin for n in lims(i)(0) .. lims(i)(1) loop nDigits := (others => 0); if getDigits(n, i + 2, nDigits) then for d in n + 1 .. lims(i)(1) + 1 loop dDigits := (others => 0); if getDigits(d, i + 2, dDigits) then for nix in nDigits'Range loop digit := nDigits(nix); dix := indexOf(dDigits, digit); if dix >= 0 then rn := removeDigit(nDigits, i + 2, nix); rd := removeDigit(dDigits, i + 2, dix); -- 'n/d = rn/rd' is same as 'n*rd = rn*d' if n*rd = rn*d then count(i) := count(i) + 1; omitted(i)(digit) := omitted(i)(digit) + 1; if count(i) <= 12 then Put (n); Put ("/"); Put (d); Put (" = "); Put (rn); Put ("/"); Put (rd); Put (" by omitting "); Put (digit); Put_Line ("'s"); end if; end if; end if; end loop; end if; end loop; end if; end loop; end; New_Line; end loop; for i in 2 .. 5 loop Put ("There are "); Put (count(i - 2)); Put (" "); Put (i); Put_Line ("-digit fractions of which:"); for j in 1 .. 9 loop if omitted(i - 2)(j) /= 0 then Put (omitted(i - 2)(j), Width => 6); Put (" have "); Put (j); Put_Line ("'s omitted"); end if; end loop; New_Line; end loop;   end Fraction_Reduction;
http://rosettacode.org/wiki/Fractran
Fractran
FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway. A FRACTRAN program is an ordered list of positive fractions P = ( f 1 , f 2 , … , f m ) {\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})} , together with an initial positive integer input n {\displaystyle n} . The program is run by updating the integer n {\displaystyle n} as follows: for the first fraction, f i {\displaystyle f_{i}} , in the list for which n f i {\displaystyle nf_{i}} is an integer, replace n {\displaystyle n} with n f i {\displaystyle nf_{i}}  ; repeat this rule until no fraction in the list produces an integer when multiplied by n {\displaystyle n} , then halt. Conway gave a program for primes in FRACTRAN: 17 / 91 {\displaystyle 17/91} , 78 / 85 {\displaystyle 78/85} , 19 / 51 {\displaystyle 19/51} , 23 / 38 {\displaystyle 23/38} , 29 / 33 {\displaystyle 29/33} , 77 / 29 {\displaystyle 77/29} , 95 / 23 {\displaystyle 95/23} , 77 / 19 {\displaystyle 77/19} , 1 / 17 {\displaystyle 1/17} , 11 / 13 {\displaystyle 11/13} , 13 / 11 {\displaystyle 13/11} , 15 / 14 {\displaystyle 15/14} , 15 / 2 {\displaystyle 15/2} , 55 / 1 {\displaystyle 55/1} Starting with n = 2 {\displaystyle n=2} , this FRACTRAN program will change n {\displaystyle n} to 15 = 2 × ( 15 / 2 ) {\displaystyle 15=2\times (15/2)} , then 825 = 15 × ( 55 / 1 ) {\displaystyle 825=15\times (55/1)} , generating the following sequence of integers: 2 {\displaystyle 2} , 15 {\displaystyle 15} , 825 {\displaystyle 825} , 725 {\displaystyle 725} , 1925 {\displaystyle 1925} , 2275 {\displaystyle 2275} , 425 {\displaystyle 425} , 390 {\displaystyle 390} , 330 {\displaystyle 330} , 290 {\displaystyle 290} , 770 {\displaystyle 770} , … {\displaystyle \ldots } After 2, this sequence contains the following powers of 2: 2 2 = 4 {\displaystyle 2^{2}=4} , 2 3 = 8 {\displaystyle 2^{3}=8} , 2 5 = 32 {\displaystyle 2^{5}=32} , 2 7 = 128 {\displaystyle 2^{7}=128} , 2 11 = 2048 {\displaystyle 2^{11}=2048} , 2 13 = 8192 {\displaystyle 2^{13}=8192} , 2 17 = 131072 {\displaystyle 2^{17}=131072} , 2 19 = 524288 {\displaystyle 2^{19}=524288} , … {\displaystyle \ldots } which are the prime powers of 2. Task Write a program that reads a list of fractions in a natural format from the keyboard or from a string, to parse it into a sequence of fractions (i.e. two integers), and runs the FRACTRAN starting from a provided integer, writing the result at each step. It is also required that the number of steps is limited (by a parameter easy to find). Extra credit Use this program to derive the first 20 or so prime numbers. See also For more on how to program FRACTRAN as a universal programming language, see: J. H. Conway (1987). Fractran: A Simple Universal Programming Language for Arithmetic. In: Open Problems in Communication and Computation, pages 4–26. Springer. J. H. Conway (2010). "FRACTRAN: A simple universal programming language for arithmetic". In Jeffrey C. Lagarias. The Ultimate Challenge: the 3x+1 problem. American Mathematical Society. pp. 249–264. ISBN 978-0-8218-4940-8. Zbl 1216.68068. Number Pathology: Fractran by Mark C. Chu-Carroll; October 27, 2006.
#Batch_File
Batch File
@echo off setlocal enabledelayedexpansion ::Set the inputs set "code=17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1" set "n=2" ::Basic validation of code for %%. in (!code!) do ( echo.%%.|findstr /r /c:"^[0-9][0-9]*/[1-9][0-9]*$">nul||goto error_code ) ::Validate the input set /a "tst=1*!n!" 2>nul if !tst! lss 0 goto error_input if !tst! equ 0 (if not "!n!"=="0" (goto error_input)) ::Set the limit outputs set limit=20 ::Execute the code echo.Input: echo. !n! echo.Output: for /l %%? in (1,1,!limit!) do ( set shouldwehalt=1 for %%A in (!code!) do ( for /f "tokens=1,2 delims=/" %%B in ("%%A") do ( set /a "tst=!n! %% %%C" if !tst! equ 0 ( if !shouldwehalt! equ 1 ( set shouldwehalt=0 set /a "n=n*%%B/%%C" echo. !n! ) ) ) ) if !shouldwehalt! equ 1 goto halt )   :halt echo. pause exit /b 0   :error_code echo.Syntax error in code. echo. pause exit /b 1   :error_input echo.Invalid input. echo. pause exit /b 1
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.
#Racket
Racket
  #lang racket (require net/ftp) (let* ([server "kernel.org"] [remote-dir "/pub/linux/kernel/"] [conn (ftp-establish-connection server 21 "anonymous" "")]) (ftp-cd conn remote-dir) (map (lambda (elem) (displayln (string-join elem "\t"))) (ftp-directory-list conn ".")) (ftp-download-file conn "." "README") (ftp-close-connection conn))  
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.
#Raku
Raku
use Net::FTP;   my $host = 'speedtest.tele2.net'; my $user = 'anonymous'; my $password = '';   my $ftp = Net::FTP.new( host => $host, :passive );   $ftp.login( user => $user, pass => $password );   $ftp.cwd( 'upload' );   $ftp.cwd( '/' );   say $_<name> for $ftp.ls;   $ftp.get( '1KB.zip', :binary );
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.
#REBOL
REBOL
  system/schemes/ftp/passive: on print read ftp://kernel.org/pub/linux/kernel/ write/binary %README read/binary ftp://kernel.org/pub/linux/kernel/README  
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.
#REXX
REXX
define('multiply(a,b)') :(mul_end) multiply multiply = a * b  :(return) mul_end   * Test output = multiply(10.1,12.2) output = multiply(10,12) end
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.
#SNOBOL4
SNOBOL4
define('multiply(a,b)') :(mul_end) multiply multiply = a * b  :(return) mul_end   * Test output = multiply(10.1,12.2) output = multiply(10,12) end
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.
#Wren
Wren
var factorial // forward declaration   factorial = Fn.new { |n| (n <= 1) ? 1 : factorial.call(n-1) * n }   System.print(factorial.call(5))
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
#Ada
Ada
function Multiply (A, B : Float) return Float;
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
#Wren
Wren
import "/date" for Date import "/seq" for Lst import "/fmt" for Fmt   class FrenchRCDate { /* uses the 'continuous method' for years after 1805 */ static isLeapYear(y) { var yy = y + 1 return (yy % 4 == 0) && (yy % 100 != 0 || yy % 400 == 0) }   static parse(frcDate) { var splits = frcDate.trim().split(" ") if (splits.count == 3) { var month = Lst.indexOf(months, splits[1]) + 1 if (month < 1 || month > 13) Fiber.abort("Invalid month.") var year = Num.fromString(splits[2]) if (year < 1) Fiber.abort("Invalid year.") var monthLength = (month < 13) ? 30 : (isLeapYear(year) ? 6 : 5) var day = Num.fromString(splits[0]) if (day < 1 || day > monthLength) Fiber.abort("Invalid day.") return FrenchRCDate.new(year, month, day) } else if (splits.count == 4 || splits.count == 5) { var yearStr = splits[-1] var year = Num.fromString(yearStr) if (year < 1) Fiber.abort("Invalid year.") var scDay = frcDate.trim()[0...-(yearStr.count + 1)] var day = Lst.indexOf(intercal, scDay) + 1 var maxDay = isLeapYear(year) ? 6 : 5 if (day < 1 || day > maxDay) Fiber.abort("Invalid day.") return FrenchRCDate.new(year, 13, day) } else Fiber.abort("Invalid French Republican date.") }   /* for convenience we treat 'Sansculottide' as an extra month with 5 or 6 days */ static months { return ["Vendémiaire", "Brumaire", "Frimaire", "Nivôse", "Pluviôse", "Ventôse", "Germinal", "Floréal", "Prairial", "Messidor", "Thermidor", "Fructidor", "Sansculottide"] }   static intercal { return ["Fête de la vertu", "Fête du génie", "Fête du travail", "Fête de l'opinion", "Fête des récompenses", "Fête de la Révolution"] }   static introductionDate { Date.new(1792, 9, 22) }   /* year = 1.. month = 1..13 day = 1..30 */ construct new(year, month, day) { if (year <= 0 || month < 1 || month > 13) Fiber.abort("Invalid date.") if (month < 13) { if (day < 1 || day > 30) Fiber.abort("Invalid date.") } else { var leap = FrenchRCDate.isLeapYear(year) if (leap && (day < 1 || day > 6)) Fiber.abort("Invalid date.") if (!leap && (day < 1 || day > 5)) Fiber.abort("Invalid date.") } _year = year _month = month _day = day }   static fromLocalDate(ldate) { var daysDiff = (ldate - introductionDate).days + 1 if (daysDiff <= 0) Fiber.abort("Date can't be before 22 September 1792.") var year = 1 var startDay = 1 while (true) { var endDay = startDay + (isLeapYear(year) ? 365 : 364) if (daysDiff >= startDay && daysDiff <= endDay) break year = year + 1 startDay = endDay + 1 } var remDays = daysDiff - startDay var month = (remDays / 30).floor var day = remDays - month * 30 return FrenchRCDate.new(year, month + 1, day + 1) }   toString { if (_month < 13) return "%(_day) %(FrenchRCDate.months[_month - 1]) %(_year)" return "%(FrenchRCDate.intercal[_day - 1]) %(_year)" }   toLocalDate { var sumDays = 0 for (i in 1..._year) sumDays = sumDays + (FrenchRCDate.isLeapYear(i) ? 366 : 365) var dayInYear = (_month - 1) * 30 + _day - 1 return FrenchRCDate.introductionDate.addDays(sumDays + dayInYear) } }   var fmt = "d| |mmmm| |yyyy" var dates = [ "22 September 1792", "20 May 1795", "15 July 1799", "23 September 1803", "31 December 1805", "18 March 1871", "25 August 1944", "19 September 2016", "22 September 2017", "28 September 2017" ] var frcDates = List.filled(dates.count, null) var i = 0 for (date in dates) { var thisDate = Date.parse(date, fmt) var frcd = FrenchRCDate.fromLocalDate(thisDate) frcDates[i] = frcd.toString Fmt.print("$-25s => $s", date, frcd) i = i + 1 }   // now process the other way around System.print() for (frcDate in frcDates) { var thisDate = FrenchRCDate.parse(frcDate) var lds = thisDate.toLocalDate.format(fmt) Fmt.print("$-25s => $s", frcDate, lds) }
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.
#F.23
F#
  // Generate the fusc sequence. Nigel Galloway: March 20th., 2019 let fG n=seq{for (n,g) in Seq.append n [1] |> Seq.pairwise do yield n; yield n+g} let fusc=seq{yield 0; yield! Seq.unfold(fun n->Some(n,fG n))(seq[1])|>Seq.concat}|> Seq.mapi(fun n g->(n,g))  
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.
#Smalltalk
Smalltalk
bagOfCalls := Bag new. Smalltalk allClassesDo:[:cls | cls instAndClassMethodsDo:[:mthd | bagOfCalls addAll:mthd messagesSent ]. ]. (bagOfCalls sortedCounts to:10) do:[:assoc | Stdout printCR: e'method {assoc value} is called {assoc key} times.' ].
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.
#Tcl
Tcl
package require Tcl 8.6   proc examine {filename} { global cmds set RE "(?:^|\[\[\{\])\[\\w:.\]+" set f [open $filename] while {[gets $f line] >= 0} { set line [string trim $line] if {$line eq "" || [string match "#*" $line]} { continue } foreach cmd [regexp -all -inline $RE $line] { incr cmds([string trim $cmd "\{\["]) } } close $f }   # Parse each file on the command line foreach filename $argv { examine $filename } # Get the command list in order of frequency set cmdinfo [lsort -stride 2 -index 1 -integer -decreasing [array get cmds]] # Print the top 10 (two list items per entry, so 0-19, not 0-9) foreach {cmd count} [lrange $cmdinfo 0 19] { puts [format "%-20s%d" $cmd $count] }
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
#D
D
import std.stdio, std.math, std.mathspecial;   real taylorGamma(in real x) pure nothrow @safe @nogc { static immutable real[30] table = [ 0x1p+0, 0x1.2788cfc6fb618f4cp-1, -0x1.4fcf4026afa2dcecp-1, -0x1.5815e8fa27047c8cp-5, 0x1.5512320b43fbe5dep-3, -0x1.59af103c340927bep-5, -0x1.3b4af28483e214e4p-7, 0x1.d919c527f60b195ap-8, -0x1.317112ce3a2a7bd2p-10, -0x1.c364fe6f1563ce9cp-13, 0x1.0c8a78cd9f9d1a78p-13, -0x1.51ce8af47eabdfdcp-16, -0x1.4fad41fc34fbb2p-20, 0x1.302509dbc0de2c82p-20, -0x1.b9986666c225d1d4p-23, 0x1.a44b7ba22d628acap-28, 0x1.57bc3fc384333fb2p-28, -0x1.44b4cedca388f7c6p-30, 0x1.cae7675c18606c6p-34, 0x1.11d065bfaf06745ap-37, -0x1.0423bac8ca3faaa4p-38, 0x1.1f20151323cd0392p-41, -0x1.72cb88ea5ae6e778p-46, -0x1.815f72a05f16f348p-48, 0x1.6198491a83bccbep-50, -0x1.10613dde57a88bd6p-53, 0x1.5e3fee81de0e9c84p-60, 0x1.a0dc770fb8a499b6p-60, -0x1.0f635344a29e9f8ep-62, 0x1.43d79a4b90ce8044p-66];   immutable real y = x - 1.0L; real sm = table[$ - 1]; foreach_reverse (immutable an; table[0 .. $ - 1]) sm = sm * y + an; return 1.0L / sm; }   real lanczosGamma(real z) pure nothrow @safe @nogc { // Coefficients used by the GNU Scientific Library. // http://en.wikipedia.org/wiki/Lanczos_approximation enum g = 7; static immutable real[9] table = [ 0.99999_99999_99809_93, 676.52036_81218_851, -1259.13921_67224_028, 771.32342_87776_5313, -176.61502_91621_4059, 12.50734_32786_86905, -0.13857_10952_65720_12, 9.98436_95780_19571_6e-6, 1.50563_27351_49311_6e-7];   // Reflection formula. if (z < 0.5L) { return PI / (sin(PI * z) * lanczosGamma(1 - z)); } else { z -= 1; real x = table[0]; foreach (immutable i; 1 .. g + 2) x += table[i] / (z + i); immutable real t = z + g + 0.5L; return sqrt(2 * PI) * t ^^ (z + 0.5L) * exp(-t) * x; } }   void main() { foreach (immutable i; 1 .. 11) { immutable real x = i / 3.0L; writefln("%f: %20.19e %20.19e %20.19e", x, x.taylorGamma, x.lanczosGamma, x.gamma); } }
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.
#Lua
Lua
Bitmap.render = function(self) for y = 1, self.height do print(table.concat(self.pixels[y], " ")) end end   -- globals (tweak here as desired) math.randomseed(os.time()) local W, H, MIDX = 15, 40, 7 local bitmap = Bitmap(W, H) local AIR, PIN, BALL, FLOOR = ".", "▲", "☻", "■" local nballs, balls = 60, {} local frame, showEveryFrame = 1, false   -- the game board: bitmap:clear(AIR) for row = 1, 7 do for col = 0, row-1 do bitmap:set(MIDX-row+col*2+1, 1+row*2, PIN) end end for col = 0, W-1 do bitmap:set(col, H-1, FLOOR) end   -- ball class Ball = { new = function(self, x, y, bitmap) local instance = setmetatable({ x=x, y=y, bitmap=bitmap, alive=true }, self) return instance end, update = function(self) if not self.alive then return end self.bitmap:set(self.x, self.y, AIR) local newx, newy = self.x, self.y+1 local below = self.bitmap:get(newx, newy) if below==PIN then newx = newx + (math.random(2)-1)*2-1 end local there = self.bitmap:get(newx, newy) if there==AIR then self.x, self.y = newx, newy else self.alive = false end self.bitmap:set(self.x, self.y, BALL) end, } Ball.__index = Ball setmetatable(Ball, { __call = function (t, ...) return t:new(...) end })   -- simulation: local function spawn() if nballs > 0 then balls[#balls+1] = Ball(MIDX, 0, bitmap) nballs = nballs - 1 end end   spawn() while #balls > 0 do if frame%2==0 then spawn() end alive = {} for _,ball in ipairs(balls) do ball:update() if ball.alive then alive[#alive+1]=ball end end balls = alive if frame%50==0 or #alive==0 or showEveryFrame then print("FRAME "..frame..":") bitmap:render() end frame = frame + 1 end
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
#Kotlin
Kotlin
private fun commatize(n: Long): String { val sb = StringBuilder(n.toString()) val le = sb.length var i = le - 3 while (i >= 1) { sb.insert(i, ',') i -= 3 } return sb.toString() }   fun main() { val starts = listOf(1e2.toLong(), 1e6.toLong(), 1e7.toLong(), 1e9.toLong(), 7123.toLong()) val counts = listOf(30, 15, 15, 10, 25) for (i in starts.indices) { var count = 0 var j = starts[i] var pow: Long = 100 while (j >= pow * 10) { pow *= 10 } System.out.printf( "First %d gapful numbers starting at %s:\n", counts[i], commatize(starts[i]) ) while (count < counts[i]) { val fl = j / pow * 10 + j % 10 if (j % fl == 0L) { System.out.printf("%d ", j) count++ } j++ if (j >= 10 * pow) { pow *= 10 } } println('\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
#Klong
Klong
  elim::{[h m];h::*m::x@>*'x;  :[2>#x;x;(,h),0,:\.f({1_x}'{x-h**x%*h}'1_m)]} subst::{[v];v::[]; {v::v,((*x)-/:[[]~v;[];v*x@1+!#v])%x@1+#v}'||'x;|v} gauss::{subst(elim(x))}  
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.
#Racket
Racket
#lang racket   (require math/matrix math/array)   (define (inverse M) (define dim (square-matrix-size M)) (define MI (matrix-augment (list M (identity-matrix dim)))) (submatrix (matrix-row-echelon MI #t #t) (::) (:: dim #f)))   (define A (matrix [[1 2 3] [4 1 6] [7 8 9]]))   (inverse A) (matrix-inverse A)
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.
#Raku
Raku
sub gauss-jordan-invert (@m where &is-square) { ^@m .map: { @m[$_].append: identity(+@m)[$_] }; @m.&rref[*]»[+@m .. *]; }   sub is-square (@m) { so @m == all @m[*] }   sub identity ($n) { [ 1, |(0 xx $n-1) ], *.rotate(-1).Array ... *.tail }   # reduced row echelon form (from 'Gauss-Jordan elimination' task) sub rref (@m) { my ($lead, $rows, $cols) = 0, @m, @m[0];   for ^$rows -> $r { $lead < $cols or return @m; my $i = $r; until @m[$i;$lead] { ++$i == $rows or next; $i = $r; ++$lead == $cols and return @m; } @m[$i, $r] = @m[$r, $i] if $r != $i; @m[$r] »/=» $ = @m[$r;$lead]; for ^$rows -> $n { next if $n == $r; @m[$n] »-=» @m[$r] »×» (@m[$n;$lead] // 0); } ++$lead; } @m } sub rat-or-int ($num) { return $num unless $num ~~ Rat|FatRat; return $num.narrow if $num.narrow ~~ Int; $num.nude.join: '/'; }   sub say_it ($message, @array) { my $max; @array.map: {$max max= max $_».&rat-or-int.comb(/\S+/)».chars}; say "\n$message"; $_».&rat-or-int.fmt(" %{$max}s").put for @array; }   multi to-matrix ($str) { [$str.split(';').map(*.words.Array)] } multi to-matrix (@array) { @array }   sub hilbert-matrix ($h) { [ (1..$h).map( -> $n { [ ($n ..^ $n + $h).map: { (1/$_).FatRat } ] } ) ] }   my @tests = '1 2 3; 4 1 6; 7 8 9', '2 -1 0; -1 2 -1; 0 -1 2', '-1 -2 3 2; -4 -1 6 2; 7 -8 9 1; 1 -2 1 3', '1 2 3 4; 5 6 7 8; 9 33 11 12; 13 14 15 17', '3 1 8 9 6; 6 2 8 10 1; 5 7 2 10 3; 3 2 7 7 9; 3 5 6 1 1',   # Test with a Hilbert matrix hilbert-matrix 10;   @tests.map: { my @matrix = .&to-matrix; say_it( " {'=' x 20} Original Matrix: {'=' x 20}", @matrix ); say_it( ' Gauss-Jordan Inverted:', my @invert = gauss-jordan-invert @matrix ); say_it( ' Re-inverted:', gauss-jordan-invert @invert».Array ); }
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
#Perl
Perl
  #!bin/usr/perl use 5.020; use strict; use warnings;   #Get a max number from the user say("Please enter the maximum possible multiple. "); my $max = <STDIN>;   #Get the factors from the user my @factors = (); my $buffer; say("Now enter the first factor and its associated word. Ex: 3 Fizz "); chomp($buffer = <STDIN>); push @factors, $buffer; say("Now enter the second factor and its associated word. Ex: 5 Buzz "); chomp($buffer = <STDIN>); push @factors, $buffer; say("Now enter the third factor and its associated word. Ex: 7 Baxx "); chomp($buffer = <STDIN>); push @factors, $buffer;   #Counting from 1 to max for(my $i = 1; $i <= $max; $i++) { #Create a secondary buffer as well as set the original buffer to the current index my $oBuffer; $buffer = $i; #Run through each element in our array foreach my $element (@factors) { #Look for white space $element =~ /\s/; #If the int is a factor of max, append it to oBuffer as a string to be printed if($i % substr($element, 0, @-) == 0) { $oBuffer = $oBuffer . substr($element, @+ + 1, length($element)); #This is essentially setting a flag saying that at least one element is a factor $buffer = ""; } } #If there are any factors for that number, print their words. If not, print the number. if(length($buffer) > 0) { print($buffer . "\n"); } else { print($oBuffer . "\n"); } }  
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
#Furor
Furor
  #k 'a 'z ++ {|| {} print SPACE |} NL end  
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
#Gambas
Gambas
Public Sub Main() Dim siCount As Short   For siCount = Asc("a") To Asc("z") Print Chr(siCount); Next   End
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#Pascal
Pascal
program byeworld; begin writeln('Hello world!'); end.
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
#Phix
Phix
-- -- demo\rosetta\Generator_Exponential.exw -- ====================================== -- without js -- tasks bool terminate = false atom res procedure powers(integer p) integer i=0 while not terminate do res = power(i,p) task_suspend(task_self()) task_yield() i += 1 end while end procedure constant squares = task_create(powers,{2}), cubes = task_create(powers,{3}) atom square, cube task_schedule(cubes,1) task_yield() cube = res for i=1 to 30 do while 1 do task_schedule(squares,1) task_yield() square = res while cube<square do task_schedule(cubes,1) task_yield() cube = res end while if square!=cube then exit end if end while if i>20 then ?square end if end for terminate = 1 {} = wait_key()
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.
#Swift
Swift
func isValid960Position(_ firstRank: String) -> Bool { var rooksPlaced = 0 var bishopColor = -1   for (i, piece) in firstRank.enumerated() { switch piece { case "♚" where rooksPlaced != 1: return false case "♜": rooksPlaced += 1 case "♝" where bishopColor == -1: bishopColor = i & 1 case "♝" where bishopColor == i & 1: return false case _: continue } }   return true }   struct Chess960Counts { var king = 0, queen = 0, rook = 0, bishop = 0, knight = 0   subscript(_ piece: String) -> Int { get { switch piece { case "♚": return king case "♛": return queen case "♜": return rook case "♝": return bishop case "♞": return knight case _: fatalError() } }   set { switch piece { case "♚": king = newValue case "♛": queen = newValue case "♜": rook = newValue case "♝": bishop = newValue case "♞": knight = newValue case _: fatalError() } } } }   func get960Position() -> String { var counts = Chess960Counts() var bishopColor = -1 // 0 - white 1 - black var output = ""   for i in 1...8 { let validPieces = [ counts["♜"] == 1 && counts["♚"] == 0 ? "♚" : nil, // king i == 1 || (counts["♛"] == 0) ? "♛" : nil, // queen i == 1 || (counts["♜"] == 0 || counts["♜"] < 2 && counts["♚"] == 1) ? "♜" : nil, // rook i == 1 || (counts["♝"] < 2 && bishopColor == -1 || bishopColor != i & 1) ? "♝" : nil, // bishop i == 1 || (counts["♞"] < 2) ? "♞" : nil // knight ].lazy.compactMap({ $0 })   guard let chosenPiece = validPieces.randomElement() else { // Need to swap last piece with a bishop output.insert("♝", at: output.index(before: output.endIndex))   break }   counts[chosenPiece] += 1 output += chosenPiece   if bishopColor == -1 && chosenPiece == "♝" { bishopColor = i & 1 } }   assert(isValid960Position(output), "invalid 960 position \(output)")   return output }   var positions = Set<String>()   while positions.count != 960 { positions.insert(get960Position()) }   print(positions.count, positions.randomElement()!)
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.
#Tcl
Tcl
package require struct::list   proc chess960 {} { while true { set pos [join [struct::list shuffle {N N B B R R Q K}] ""] if {[regexp {R.*K.*R} $pos] && [regexp {B(..)*B} $pos]} { return $pos } } }   # A simple renderer proc chessRender {position} { string map {P ♙ N ♘ B ♗ R ♖ Q ♕ K ♔} $position }   # Output multiple times just to show scope of positions foreach - {1 2 3 4 5} {puts [chessRender [chess960]]}
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.
#C.23
C#
using System; class Program { static void Main(string[] args) { Func<int, int> outfunc = Composer<int, int, int>.Compose(functA, functB); Console.WriteLine(outfunc(5)); //Prints 100 } static int functA(int i) { return i * 10; } static int functB(int i) { return i + 5; } class Composer<A, B, C> { public static Func<C, A> Compose(Func<B, A> a, Func<C, B> b) { return delegate(C i) { return a(b(i)); }; } } }
http://rosettacode.org/wiki/Fractal_tree
Fractal tree
Generate and draw a fractal tree. Draw the trunk At the end of the trunk, split by some angle and draw two branches Repeat at the end of each branch until a sufficient level of branching is reached Related tasks Pythagoras Tree
#Ceylon
Ceylon
import javax.swing {   JFrame { exitOnClose } } import java.awt {   Color { white, black }, Graphics } import ceylon.numeric.float {   cos, toRadians, sin }   shared void run() {   value fractalTree = object extends JFrame("fractal tree") {   background = black; setBounds(100, 100, 800, 600); resizable = false; defaultCloseOperation = exitOnClose;   shared actual void paint(Graphics g) {   void drawTree(Integer x1, Integer y1, Float angle, Integer depth) { if (depth <= 0) { return; } value x2 = x1 + (cos(toRadians(angle)) * depth * 10.0).integer; value y2 = y1 + (sin(toRadians(angle)) * depth * 10.0).integer; g.drawLine(x1, y1, x2, y2); drawTree(x2, y2, angle - 20, depth - 1); drawTree(x2, y2, angle + 20, depth - 1); }   g.color = white; drawTree(400, 500, -90.0, 9); } };   fractalTree.visible = true; }
http://rosettacode.org/wiki/Fractal_tree
Fractal tree
Generate and draw a fractal tree. Draw the trunk At the end of the trunk, split by some angle and draw two branches Repeat at the end of each branch until a sufficient level of branching is reached Related tasks Pythagoras Tree
#Clojure
Clojure
(import '[java.awt Color Graphics] 'javax.swing.JFrame)   (defn deg-to-radian [deg] (* deg Math/PI 1/180)) (defn cos-deg [angle] (Math/cos (deg-to-radian angle))) (defn sin-deg [angle] (Math/sin (deg-to-radian angle)))   (defn draw-tree [^Graphics g, x y angle depth] (when (pos? depth) (let [x2 (+ x (int (* depth 10 (cos-deg angle)))) y2 (+ y (int (* depth 10 (sin-deg angle))))] (.drawLine g x y x2 y2) (draw-tree g x2 y2 (- angle 20) (dec depth)) (recur g x2 y2 (+ angle 20) (dec depth)))))   (defn fractal-tree [depth] (doto (proxy [JFrame] [] (paint [g] (.setColor g Color/BLACK) (draw-tree g 400 500 -90 depth))) (.setBounds 100 100 800 600) (.setResizable false) (.setDefaultCloseOperation JFrame/DISPOSE_ON_CLOSE) (.show)))   (fractal-tree 9)
http://rosettacode.org/wiki/Fraction_reduction
Fraction reduction
There is a fine line between numerator and denominator.       ─── anonymous A method to   "reduce"   some reducible fractions is to   cross out   a digit from the numerator and the denominator.   An example is: 16 16 ──── and then (simply) cross─out the sixes: ──── 64 64 resulting in: 1 ─── 4 Naturally,   this "method" of reduction must reduce to the proper value   (shown as a fraction). This "method" is also known as   anomalous cancellation   and also   accidental cancellation. (Of course,   this "method" shouldn't be taught to impressionable or gullible minds.)       😇 Task Find and show some fractions that can be reduced by the above "method".   show 2-digit fractions found   (like the example shown above)   show 3-digit fractions   show 4-digit fractions   show 5-digit fractions   (and higher)       (optional)   show each (above) n-digit fractions separately from other different n-sized fractions, don't mix different "sizes" together   for each "size" fraction,   only show a dozen examples   (the 1st twelve found)   (it's recognized that not every programming solution will have the same generation algorithm)   for each "size" fraction:   show a count of how many reducible fractions were found.   The example (above) is size 2   show a count of which digits were crossed out   (one line for each different digit)   for each "size" fraction,   show a count of how many were found.   The example (above) is size 2   show each n-digit example   (to be shown on one line):   show each n-digit fraction   show each reduced n-digit fraction   show what digit was crossed out for the numerator and the denominator Task requirements/restrictions   only proper fractions and their reductions   (the result)   are to be used   (no vulgar fractions)   only positive fractions are to be used   (no negative signs anywhere)   only base ten integers are to be used for the numerator and denominator   no zeros   (decimal digit)   can be used within the numerator or the denominator   the numerator and denominator should be composed of the same number of digits   no digit can be repeated in the numerator   no digit can be repeated in the denominator   (naturally)   there should be a shared decimal digit in the numerator   and   the denominator   fractions can be shown as   16/64   (for example) Show all output here, on this page. Somewhat related task   Farey sequence       (It concerns fractions.) References   Wikipedia entry:   proper and improper fractions.   Wikipedia entry:   anomalous cancellation and/or accidental cancellation.
#C
C
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h>   typedef struct IntArray_t { int *ptr; size_t length; } IntArray;   IntArray make(size_t size) { IntArray temp; temp.ptr = calloc(size, sizeof(int)); temp.length = size; return temp; }   void destroy(IntArray *ia) { if (ia->ptr != NULL) { free(ia->ptr);   ia->ptr = NULL; ia->length = 0; } }   void zeroFill(IntArray dst) { memset(dst.ptr, 0, dst.length * sizeof(int)); }   int indexOf(const int n, const IntArray ia) { size_t i; for (i = 0; i < ia.length; i++) { if (ia.ptr[i] == n) { return i; } } return -1; }   bool getDigits(int n, int le, IntArray digits) { while (n > 0) { int r = n % 10; if (r == 0 || indexOf(r, digits) >= 0) { return false; } le--; digits.ptr[le] = r; n /= 10; } return true; }   int removeDigit(IntArray digits, size_t le, size_t idx) { static const int POWS[] = { 1, 10, 100, 1000, 10000 }; int sum = 0; int pow = POWS[le - 2]; size_t i; for (i = 0; i < le; i++) { if (i == idx) continue; sum += digits.ptr[i] * pow; pow /= 10; } return sum; }   int main() { int lims[4][2] = { { 12, 97 }, { 123, 986 }, { 1234, 9875 }, { 12345, 98764 } }; int count[5] = { 0 }; int omitted[5][10] = { {0} }; size_t upperBound = sizeof(lims) / sizeof(lims[0]); size_t i;   for (i = 0; i < upperBound; i++) { IntArray nDigits = make(i + 2); IntArray dDigits = make(i + 2); int n;   for (n = lims[i][0]; n <= lims[i][1]; n++) { int d; bool nOk;   zeroFill(nDigits); nOk = getDigits(n, i + 2, nDigits); if (!nOk) { continue; } for (d = n + 1; d <= lims[i][1] + 1; d++) { size_t nix; bool dOk;   zeroFill(dDigits); dOk = getDigits(d, i + 2, dDigits); if (!dOk) { continue; } for (nix = 0; nix < nDigits.length; nix++) { int digit = nDigits.ptr[nix]; int dix = indexOf(digit, dDigits); if (dix >= 0) { int rn = removeDigit(nDigits, i + 2, nix); int rd = removeDigit(dDigits, i + 2, dix); if ((double)n / d == (double)rn / rd) { count[i]++; omitted[i][digit]++; if (count[i] <= 12) { printf("%d/%d = %d/%d by omitting %d's\n", n, d, rn, rd, digit); } } } } } }   printf("\n");   destroy(&nDigits); destroy(&dDigits); }   for (i = 2; i <= 5; i++) { int j;   printf("There are %d %d-digit fractions of which:\n", count[i - 2], i);   for (j = 1; j <= 9; j++) { if (omitted[i - 2][j] == 0) { continue; } printf("%6d have %d's omitted\n", omitted[i - 2][j], j); }   printf("\n"); }   return 0; }
http://rosettacode.org/wiki/Fractran
Fractran
FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway. A FRACTRAN program is an ordered list of positive fractions P = ( f 1 , f 2 , … , f m ) {\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})} , together with an initial positive integer input n {\displaystyle n} . The program is run by updating the integer n {\displaystyle n} as follows: for the first fraction, f i {\displaystyle f_{i}} , in the list for which n f i {\displaystyle nf_{i}} is an integer, replace n {\displaystyle n} with n f i {\displaystyle nf_{i}}  ; repeat this rule until no fraction in the list produces an integer when multiplied by n {\displaystyle n} , then halt. Conway gave a program for primes in FRACTRAN: 17 / 91 {\displaystyle 17/91} , 78 / 85 {\displaystyle 78/85} , 19 / 51 {\displaystyle 19/51} , 23 / 38 {\displaystyle 23/38} , 29 / 33 {\displaystyle 29/33} , 77 / 29 {\displaystyle 77/29} , 95 / 23 {\displaystyle 95/23} , 77 / 19 {\displaystyle 77/19} , 1 / 17 {\displaystyle 1/17} , 11 / 13 {\displaystyle 11/13} , 13 / 11 {\displaystyle 13/11} , 15 / 14 {\displaystyle 15/14} , 15 / 2 {\displaystyle 15/2} , 55 / 1 {\displaystyle 55/1} Starting with n = 2 {\displaystyle n=2} , this FRACTRAN program will change n {\displaystyle n} to 15 = 2 × ( 15 / 2 ) {\displaystyle 15=2\times (15/2)} , then 825 = 15 × ( 55 / 1 ) {\displaystyle 825=15\times (55/1)} , generating the following sequence of integers: 2 {\displaystyle 2} , 15 {\displaystyle 15} , 825 {\displaystyle 825} , 725 {\displaystyle 725} , 1925 {\displaystyle 1925} , 2275 {\displaystyle 2275} , 425 {\displaystyle 425} , 390 {\displaystyle 390} , 330 {\displaystyle 330} , 290 {\displaystyle 290} , 770 {\displaystyle 770} , … {\displaystyle \ldots } After 2, this sequence contains the following powers of 2: 2 2 = 4 {\displaystyle 2^{2}=4} , 2 3 = 8 {\displaystyle 2^{3}=8} , 2 5 = 32 {\displaystyle 2^{5}=32} , 2 7 = 128 {\displaystyle 2^{7}=128} , 2 11 = 2048 {\displaystyle 2^{11}=2048} , 2 13 = 8192 {\displaystyle 2^{13}=8192} , 2 17 = 131072 {\displaystyle 2^{17}=131072} , 2 19 = 524288 {\displaystyle 2^{19}=524288} , … {\displaystyle \ldots } which are the prime powers of 2. Task Write a program that reads a list of fractions in a natural format from the keyboard or from a string, to parse it into a sequence of fractions (i.e. two integers), and runs the FRACTRAN starting from a provided integer, writing the result at each step. It is also required that the number of steps is limited (by a parameter easy to find). Extra credit Use this program to derive the first 20 or so prime numbers. See also For more on how to program FRACTRAN as a universal programming language, see: J. H. Conway (1987). Fractran: A Simple Universal Programming Language for Arithmetic. In: Open Problems in Communication and Computation, pages 4–26. Springer. J. H. Conway (2010). "FRACTRAN: A simple universal programming language for arithmetic". In Jeffrey C. Lagarias. The Ultimate Challenge: the 3x+1 problem. American Mathematical Society. pp. 249–264. ISBN 978-0-8218-4940-8. Zbl 1216.68068. Number Pathology: Fractran by Mark C. Chu-Carroll; October 27, 2006.
#Befunge
Befunge
p0" :snoitcarF">:#,_>&00g5p~$&00g:v v"Starting value: "_^#-*84~p6p00+1< >:#,_&0" :snoitaretI">:#,_#@>>$&\:v :$_\:10g5g*:10g6g%v1:\1$\$<|!:-1\.< g0^<!:-1\p01+1g01$_10g6g/\^>\010p00
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.
#Ruby
Ruby
require 'net/ftp'   Net::FTP.open('ftp.ed.ac.uk', "anonymous","[email protected]" ) do |ftp| ftp.passive = true # default since Ruby 2.3 ftp.chdir('pub/courses') puts ftp.list ftp.getbinaryfile("make.notes.tar") end
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.
#Rust
Rust
use std::{error::Error, fs::File, io::copy}; use ftp::FtpStream;   fn main() -> Result<(), Box<dyn Error>> { let mut ftp = FtpStream::connect("ftp.easynet.fr:21")?; ftp.login("anonymous", "")?; ftp.cwd("debian")?; for file in ftp.list(None)? { println!("{}", file); } let mut stream = ftp.get("README")?; let mut file = File::create("README")?; copy(&mut stream, &mut file)?; Ok(()) }
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.
#Scala
Scala
import java.io.{File, FileOutputStream, InputStream}   import org.apache.commons.net.ftp.{FTPClient, FTPFile, FTPReply}   import scala.util.{Failure, Try}   object FTPconn extends App { val (server, pass) = ("ftp.ed.ac.uk", "[email protected]") val (dir, filename, ftpClient) = ("/pub/cartonet/", "readme.txt", new FTPClient())   def canConnect(host: String): Boolean = { ftpClient.connect(host) val connectionWasEstablished = ftpClient.isConnected ftpClient.disconnect() connectionWasEstablished }   def downloadFileStream(remote: String): InputStream = { val stream: InputStream = ftpClient.retrieveFileStream(remote) ftpClient.completePendingCommand() stream }   def uploadFile(remote: String, input: InputStream): Boolean = ftpClient.storeFile(remote, input)   if (Try { def cwd(path: String): Boolean = ftpClient.changeWorkingDirectory(path)   def filesInCurrentDirectory: Seq[String] = listFiles().map(_.getName)   def listFiles(): List[FTPFile] = ftpClient.listFiles.toList   def downloadFile(remote: String): Boolean = { val os = new FileOutputStream(new File(remote)) ftpClient.retrieveFile(remote, os) }   def connectWithAuth(host: String, password: String, username: String = "anonymous", port: Int = 21): Try[Boolean] = { def connect(): Try[Unit] = Try { try { ftpClient.connect(host, port) } catch { case ex: Throwable => println(ex.getMessage) Failure } ftpClient.enterLocalPassiveMode() serverReply(ftpClient)   val replyCode = ftpClient.getReplyCode if (!FTPReply.isPositiveCompletion(replyCode)) println("Failure. Server reply code: " + replyCode) }   for { connection <- connect() login <- Try { ftpClient.login(username, password) } } yield login }   def serverReply(ftpClient: FTPClient): Unit = for (reply <- ftpClient.getReplyStrings) println(reply)   connectWithAuth(server, pass)   cwd(dir) listFiles().foreach(println)   downloadFile(filename) serverReply(ftpClient) ftpClient.logout }.isFailure) println(s"Failure.") }
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.
#zkl
zkl
fcn{"Hello World"} // no expected args fcn(){"Hello World"} // ditto   fcn{vm.arglist}(1,2) // ask the VM for the passed in args -->L(1,2) fcn f(a,b){a+b} // fcn(1,2,3) works just fine fcn f(args){}(1,2,3) //args = 1 fcn(args){vm.arglist.sum()}(1,2,3) //-->6   fcn(a=1,b=2){vm.arglist}() //-->L(1,2) fcn(a=1,b=2){vm.arglist}(5) //-->L(5,2) fcn(a=1,b){vm.arglist}() //-->L(1), error if you try to use b fcn(a,b=2){vm.arglist}(5) //-->L(5,2) fcn(a,b=2,c){vm.arglist}(1) //-->L(1,2)   fcn(){vm.nthArg(1)}(5,6) //-->6 fcn{vm.numArgs}(1,2,3,4,5,6,7,8,9) //-->9 fcn{vm.argsMatch(...)} // a somewhat feeble attempt arg pattern matching based on type (vs value)   // you can do list assignment in the prototype: fcn(a,[(b,c)],d){vm.arglist}(1,L(2,3,4),5) //-->L(1,L(2,3,4),5) fcn(a,[(b,c)],d){"%s,%s,%s,%s".fmt(a,b,c,d)}(1,L(2,3,4),5) //-->1,2,3,5   // no type enforcement but you can give a hint to the compiler fcn([Int]n){n.sin()} //--> syntax error as Ints don't do sin
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
#Aime
Aime
real multiply(real a, real b) { return a * b; }
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.
#Factor
Factor
USING: arrays assocs formatting io kernel make math math.parser math.ranges namespaces prettyprint sequences tools.memory.private ; IN: rosetta-code.fusc   <PRIVATE   : (fusc) ( n -- seq ) [ 2 ] dip [a,b) [ 0 , 1 , [ [ building get ] dip dup even? [ 2/ swap nth ] [ [ 1 - 2/ ] [ 1 + 2/ ] 2bi [ swap nth ] 2bi@ + ] if , ] each ] { } make ;   : increases ( seq -- assoc ) [ 0 ] dip [ [ 2array 2dup first number>string length < [ [ 1 + ] [ , ] bi* ] [ drop ] if ] each-index ] { } make nip ;   PRIVATE>   : fusc ( n -- seq ) dup 3 < [ { 0 1 } swap head ] [ (fusc) ] if ;   : fusc-demo ( -- ) "First 61 fusc numbers:" print 61 fusc [ pprint bl ] each nl nl "Fusc numbers with more digits than all previous ones:" print "Value Index\n====== =======" print 1,000,000 fusc increases [ [ commas ] bi@ "%-6s  %-7s\n" printf ] assoc-each ;   MAIN: fusc-demo
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.
#Forth
Forth
\ Gforth 0.7.9_20211014   : fusc ( n -- n) \ input n -- output fusc(n) dup dup 0= swap 1 = or \ n = 0 or 1 if exit \ return n else dup 2 mod 0= \ test even if 2/ recurse \ even fusc(n)= fusc(n/2) else dup 1- 2/ recurse \ odd fusc(n) = fusc((n-1)/2) + swap 1+ 2/ recurse + \ fusc((n+1)/2) then then ;   : cntDigits ( n -- n ) \ returns the numbers of digits 0 begin 1+ swap 10 / swap over 0= until swap drop ;   : fuscLen ( n -- ) \ count until end index cr 1 swap 0 do i fusc cntDigits over > if 1+ ." fusc( " i . ." ) : " i fusc . cr then loop ;   : firstFusc ( n -- ) \ show fusc(i) until limit dup ." First " . ." fusc(n) : " cr 0 do I fusc . loop cr ;   61 firstFusc   20 1000 1000 * * fuscLen   bye  
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.
#Wren
Wren
import "io" for File import "os" for Process import "/pattern" for Pattern import "/set" for Bag import "/sort" for Sort import "/fmt" for Fmt   var args = Process.arguments if (args.count != 1) { Fiber.abort("There should be exactly one argument - the file path to be analyzed") } var p = Pattern.new("[+1/x.+1/x](") var source = File.read(args[0]) var matches = p.findAll(source) var bag = Bag.new(matches.map { |m| m.captures[0].text }) var methodCalls = bag.toMap.toList var cmp = Fn.new { |i, j| (j.value - i.value).sign } Sort.quick(methodCalls, 0, methodCalls.count-1, cmp) System.print("Top ten method/function calls in %(args[0]):\n") System.print("Called Method/Function") System.print("------ ----------------") for (mc in methodCalls.take(10)) { Fmt.print(" $2d $s", mc.value, mc.key) }
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
#Delphi
Delphi
  program Gamma_function;   {$APPTYPE CONSOLE}   uses System.SysUtils, System.Math;   function lanczos7(z: double): Double; begin var t := z + 6.5; var x := 0.99999999999980993 + 676.5203681218851 / z - 1259.1392167224028 / (z + 1) + 771.32342877765313 / (z + 2) - 176.61502916214059 / (z + 3) + 12.507343278686905 / (z + 4) - 0.13857109526572012 / (z + 5) + 9.9843695780195716e-6 / (z + 6) + 1.5056327351493116e-7 / (z + 7);   Result := Sqrt(2) * Sqrt(pi) * Power(t, z - 0.5) * exp(-t) * x; end;   begin var xs: TArray<double> := [-0.5, 0.1, 0.5, 1, 1.5, 2, 3, 10, 140, 170]; writeln(' x Lanczos7'); for var x in xs do writeln(format('%5.1f %24.16g', [x, lanczos7(x)])); readln; end.
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.
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
ClearAll[MakePathFunction] MakePathFunction[{path_, acumpath_}] := Module[{f1, f2, f3, pf, n = Length[path]}, f1 = MapThread[{#1/2, #2 + 0.5 < z <= #2 + 1} &, {acumpath, n - Range[n + 1]}]; f2 = MapThread[{#1/2 + #2 Sqrt[1/4 - (z - #3)^2], #3 < z <= #3 + 1/2} &, {acumpath // Most, path, n - Range[n]}]; f3 = {{acumpath[[-1]]/2, z <= 0}}; pf = Piecewise[Evaluate[Join[f1, f2, f3]], 0]; pf ] MakeScene[pfs_List, zfinals_List, n_Integer, t_] := Module[{durations, accumduration, if, part, fixed, relt}, durations = n - zfinals; accumduration = Accumulate[Prepend[durations, 0]]; if = Interpolation[{accumduration, Range[Length[zfinals] + 1]} // Transpose, InterpolationOrder -> 1]; part = Floor[if[t]]; If[part > 0, fixed = Table[{pfs[[i]], z} /. z -> zfinals[[i]], {i, part - 1}]; , fixed = {}; ]; relt = t - accumduration[[part]]; relt = n - relt; Append[fixed, {pfs[[part]] /. z -> relt, relt}] ] SeedRandom[1234]; n = 6; m = 150; r = 0.25; (* fixed *) dots = Catenate@Table[{# - i/2 - 1/2, n - i} & /@ Range[i], {i, n}]; g = Graphics[Disk[#, r] & /@ dots, Axes -> True];   paths = RandomChoice[{-1, 1}, {m, n}]; paths = {#, Accumulate[Prepend[#, 0]]} & /@ paths; xfinals = paths[[All, 2, -1]]; types = DeleteDuplicates[xfinals]; zfinals = ConstantArray[0, Length[paths]]; Do[ pos = Flatten[Position[xfinals, t]]; zfinals[[pos]] += 0.5 Range[Length[pos]]; , {t, types} ]; max = Max[zfinals] + 1; zfinals -= max; pfs = MakePathFunction /@ paths; Manipulate[ Graphics[{Disk[#, r] & /@ dots, Red, Disk[#, r] & /@ MakeScene[pfs, zfinals, n, t]}, PlotRange -> {{-n, n}, {Min[zfinals] - 1, n + 2}}, ImageSize -> 150], {t, 0, Total[n - zfinals] - 0.001}]
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.
#Nim
Nim
import random, strutils   const BoxW = 41 # Galton box width. BoxH = 37 # Galton box height. PinsBaseW = 19 # Pins triangle base. NMaxBalls = 55 # Number of balls.   const CenterH = PinsBaseW + (BoxW - (PinsBaseW * 2 - 1)) div 2 - 1   type   Cell = enum cEmpty = " " cBall = "o" cWall = "|" cCorner = "+" cFloor = "-" cPin = "."   # Galton box. Will be printed upside-down. Box = array[BoxH, array[BoxW, Cell]]   Ball = ref object x, y: int     func initBox(): Box =   # Set ceiling and floor. result[0][0] = cCorner result[0][^1] = cCorner for i in 1..(BoxW - 2): result[0][i] = cFloor result[^1] = result[0]   # Set walls. for i in 1..(BoxH - 2): result[i][0] = cWall result[i][^1] = cWall   # Set rest to Empty initially. for i in 1..(BoxH - 2): for j in 1..(BoxW - 2): result[i][j] = cEmpty   # Set pins. for nPins in 1..PinsBaseW: for p in 0..<nPins: result[BoxH - 2 - nPins][CenterH + 1 - nPins + p * 2] = cPin     func newBall(box: var Box; x, y: int): Ball =   doAssert box[y][x] == cEmpty, "Tried to create a new ball in a non-empty cell" result = Ball(x: x, y: y) box[y][x] = cBall     proc doStep(box: var Box; b: Ball) =   if b.y <= 0: return # Reached the bottom of the box.   case box[b.y-1][b.x]   of cEmpty: box[b.y][b.x] = cEmpty dec b.y box[b.y][b.x] = cBall   of cPin: box[b.y][b.x] = cEmpty dec b.y if box[b.y][b.x-1] == cEmpty and box[b.y][b.x+1] == cEmpty: inc b.x, 2 * rand(1) - 1 elif box[b.y][b.x-1] == cEmpty: inc b.x else: dec b.x box[b.y][b.x] = cBall   else: # It's frozen - it always piles on other balls. discard     proc draw(box: Box) = for r in countdown(BoxH - 1, 0): echo box[r].join()     #———————————————————————————————————————————————————————————————————————————————————————————————————   randomize() var box = initBox() var balls: seq[Ball]   for i in 0..<(NMaxBalls + BoxH):   echo "Step ", i, ':' if i < NMaxBalls: balls.add box.newBall(CenterH, BoxH - 2) box.draw()   # Next step for the simulation. # Frozen balls are kept in balls slice for simplicity. for ball in balls: box.doStep(ball)
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
#Lambdatalk
Lambdatalk
  {def gapfuls {lambda {:n :i :N} {if {>= :i :N} then else {if {= {% :n {W.first :n}{W.last :n}} 0} then :n {gapfuls {+ :n 1} {+ :i 1} :N} else {gapfuls {+ :n 1}  :i  :N}}}}} -> gapfuls   {gapfuls 100 0 30} -> 100 105 108 110 120 121 130 132 135 140 143 150 154 160 165 170 176 180 187 190 192 195 198 200 220 225 231 240 242 253   {gapfuls 1000000 0 15} -> 1000000 1000005 1000008 1000010 1000016 1000020 1000021 1000030 1000032 1000034 1000035 1000040 1000050 1000060 1000065   {gapfuls 1000000000 0 10} -> 1000000000 1000000001 1000000005 1000000008 1000000010 1000000016 1000000020 1000000027 1000000030 1000000032  
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
#Kotlin
Kotlin
// version 1.1.51   val ta = arrayOf( doubleArrayOf(1.00, 0.00, 0.00, 0.00, 0.00, 0.00), doubleArrayOf(1.00, 0.63, 0.39, 0.25, 0.16, 0.10), doubleArrayOf(1.00, 1.26, 1.58, 1.98, 2.49, 3.13), doubleArrayOf(1.00, 1.88, 3.55, 6.70, 12.62, 23.80), doubleArrayOf(1.00, 2.51, 6.32, 15.88, 39.90, 100.28), doubleArrayOf(1.00, 3.14, 9.87, 31.01, 97.41, 306.02) )   val tb = doubleArrayOf(-0.01, 0.61, 0.91, 0.99, 0.60, 0.02)   val tx = doubleArrayOf( -0.01, 1.602790394502114, -1.6132030599055613, 1.2454941213714368, -0.4909897195846576, 0.065760696175232 )   const val EPSILON = 1e-14 // tolerance required   fun gaussPartial(a0: Array<DoubleArray>, b0: DoubleArray): DoubleArray { val m = b0.size val a = Array(m) { DoubleArray(m) } for ((i, ai) in a0.withIndex()) { val row = ai.copyOf(m + 1) row[m] = b0[i] a[i] = row } for (k in 0 until a.size) { var iMax = 0 var max = -1.0 for (i in k until m) { val row = a[i] // compute scale factor s = max abs in row var s = -1.0 for (j in k until m) { val e = Math.abs(row[j]) if (e > s) s = e } // scale the abs used to pick the pivot val abs = Math.abs(row[k]) / s if (abs > max) { iMax = i max = abs } } if (a[iMax][k] == 0.0) { throw RuntimeException("Matrix is singular.") } val tmp = a[k] a[k] = a[iMax] a[iMax] = tmp for (i in k + 1 until m) { for (j in k + 1..m) { a[i][j] -= a[k][j] * a[i][k] / a[k][k] } a[i][k] = 0.0 } } val x = DoubleArray(m) for (i in m - 1 downTo 0) { x[i] = a[i][m] for (j in i + 1 until m) { x[i] -= a[i][j] * x[j] } x[i] /= a[i][i] } return x }   fun main(args: Array<String>) { val x = gaussPartial(ta, tb) println(x.asList()) for ((i, xi) in x.withIndex()) { if (Math.abs(tx[i] - xi) > EPSILON) { println("Out of tolerance.") println("Expected values are ${tx.asList()}") return } } }
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.
#REXX
REXX
/* REXX */ Parse Arg seed nn If seed='' Then seed=23345 If nn='' Then nn=5 If seed='?' Then Do Say 'rexx gjmi seed n computes a random matrix with n rows and columns' Say 'Default is 23345 5' Exit End Numeric Digits 50 Call random 1,2,seed a='' Do i=1 To nn**2 a=a random(9)+1 End n2=words(a) Do n=2 To n2/2 If n**2=n2 Then Leave End If n>n2/2 Then Call exit 'Not a square matrix:' a '('n2 'elements).' det=determinante(a,n) If det=0 Then Call exit 'Determinant is 0' Do j=1 To n Do i=1 To n Parse Var A a.i.j a aa.i.j=a.i.j End Do ii=1 To n z=(ii=j) iii=ii+n a.iii.j=z End End Call show 1,'The given matrix' Do m=1 To n-1 If a.m.m=0 Then Do Do j=m+1 To n If a.m.j<>0 Then Leave End If j>n Then Do Say 'No pivot>0 found in column' m Exit End Do i=1 To n*2 temp=a.i.m a.i.m=a.i.j a.i.j=temp End End Do j=m+1 To n If a.m.j<>0 Then Do jj=m fact=divide(a.m.m,a.m.j) Do i=1 To n*2 a.i.j=subtract(multiply(a.i.j,fact),a.i.jj) End End End Call show 2 m End Say 'Lower part has all zeros' Say ''   Do j=1 To n If denom(a.j.j)<0 Then Do Do i=1 To 2*n a.i.j=subtract(0,a.i.j) End End End Call show 3   Do m=n To 2 By -1 Do j=1 To m-1 jj=m fact=divide(a.m.j,a.m.jj) Do i=1 To n*2 a.i.j=subtract(a.i.j,multiply(a.i.jj,fact)) End End Call show 4 m End Say 'Upper half has all zeros' Say '' Do j=1 To n If decimal(a.j.j)<>1 Then Do z=a.j.j Do i=1 To 2*n a.i.j=divide(a.i.j,z) End End End Call show 5 Say 'Main diagonal has all ones' Say ''   Do j=1 To n Do i=1 To n z=i+n a.i.j=a.z.j End End Call show 6,'The inverse matrix'   do i = 1 to n do j = 1 to n sum=0 Do k=1 To n sum=add(sum,multiply(aa.i.k,a.k.j)) End c.i.j = sum end End Call showc 7,'The product of input and inverse matrix' Exit   show: Parse Arg num,text Say 'show' arg(1) text If arg(1)<>6 Then rows=n*2 Else rows=n len=0 Do j=1 To n Do i=1 To rows len=max(len,length(a.i.j)) End End Do j=1 To n ol='' Do i=1 To rows ol=ol||right(a.i.j,len+1) End Say ol End Say '' Return   showc: Parse Arg num,text Say text clen=0 Do j=1 To n Do i=1 To n clen=max(clen,length(c.i.j)) End End Do j=1 To n ol='' Do i=1 To n ol=ol||right(c.i.j,clen+1) End Say ol End Say '' Return   denom: Procedure /* Return the denominator */ Parse Arg d '/' n Return d   decimal: Procedure /* compute the fraction's value */ Parse Arg a If pos('/',a)=0 Then a=a'/1'; Parse Var a ad '/' an Return ad/an   gcd: procedure /********************************************************************** * Greatest commn divisor **********************************************************************/ Parse Arg a,b If b = 0 Then Return abs(a) Return gcd(b,a//b)   add: Procedure Parse Arg a,b If pos('/',a)=0 Then a=a'/1'; Parse Var a ad '/' an If pos('/',b)=0 Then b=b'/1'; Parse Var b bd '/' bn sum=divide(ad*bn+bd*an,an*bn) Return sum   multiply: Procedure Parse Arg a,b If pos('/',a)=0 Then a=a'/1'; Parse Var a ad '/' an If pos('/',b)=0 Then b=b'/1'; Parse Var b bd '/' bn prd=divide(ad*bd,an*bn) Return prd   subtract: Procedure Parse Arg a,b If pos('/',a)=0 Then a=a'/1'; Parse Var a ad '/' an If pos('/',b)=0 Then b=b'/1'; Parse Var b bd '/' bn div=divide(ad*bn-bd*an,an*bn) Return div   divide: Procedure Parse Arg a,b If pos('/',a)=0 Then a=a'/1'; Parse Var a ad '/' an If pos('/',b)=0 Then b=b'/1'; Parse Var b bd '/' bn sd=ad*bn sn=an*bd g=gcd(sd,sn) Select When sd=0 Then res='0' When abs(sn/g)=1 Then res=(sd/g)*sign(sn/g) Otherwise Do den=sd/g nom=sn/g If nom<0 Then Do If den<0 Then den=abs(den) Else den=-den nom=abs(nom) End res=den'/'nom End End Return res   determinante: Procedure /* REXX *************************************************************** * determinant.rex * compute the determinant of the given square matrix * Input: as: the representation of the matrix as vector (n**2 elements) * 21.05.2013 Walter Pachl **********************************************************************/ Parse Arg as,n Do i=1 To n Do j=1 To n Parse Var as a.i.j as End End Select When n=2 Then det=subtract(multiply(a.1.1,a.2.2),multiply(a.1.2,a.2.1)) When n=3 Then Do det=multiply(multiply(a.1.1,a.2.2),a.3.3) det=add(det,multiply(multiply(a.1.2,a.2.3),a.3.1)) det=add(det,multiply(multiply(a.1.3,a.2.1),a.3.2)) det=subtract(det,multiply(multiply(a.1.3,a.2.2),a.3.1)) det=subtract(det,multiply(multiply(a.1.2,a.2.1),a.3.3)) det=subtract(det,multiply(multiply(a.1.1,a.2.3),a.3.2)) End Otherwise Do det=0 Do k=1 To n sign=((-1)**(k+1)) If sign=1 Then det=add(det,multiply(a.1.k,determinante(subm(k),n-1))) Else det=subtract(det,multiply(a.1.k,determinante(subm(k),n-1))) End End End Return det   subm: Procedure Expose a. n /********************************************************************** * compute the submatrix resulting when row 1 and column k are removed * Input: a.*.*, k * Output: bs the representation of the submatrix as vector **********************************************************************/ Parse Arg k bs='' do i=2 To n Do j=1 To n If j=k Then Iterate bs=bs a.i.j End End Return bs   Exit: Say arg(1)
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
#Phix
Phix
procedure general_fizz_buzz(integer lim, sequence words, facts) for i=1 to lim do string word = "" for j=1 to length(facts) do if remainder(i,facts[j])=0 then word &= words[j] end if end for if length(word)=0 then word = sprintf("%d",i) end if printf(1,"%s\n",{word}) end for end procedure general_fizz_buzz(20, {"Fizz","Buzz","Baxx"}, {3,5,7})
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
#Go
Go
func loweralpha() string { p := make([]byte, 26) for i := range p { p[i] = 'a' + byte(i) } return string(p) }
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
#Groovy
Groovy
def lower = ('a'..'z')
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
#PASM
PASM
print "Hello world!\n" end
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
#PHP
PHP
<?php function powers($m) { for ($n = 0; ; $n++) { yield pow($n, $m); } }   function filtered($s1, $s2) { while (true) { list($v, $f) = [$s1->current(), $s2->current()]; if ($v > $f) { $s2->next(); continue; } else if ($v < $f) { yield $v; } $s1->next(); } }   list($squares, $cubes) = [powers(2), powers(3)]; $f = filtered($squares, $cubes); foreach (range(0, 19) as $i) { $f->next(); } foreach (range(20, 29) as $i) { echo $i, "\t", $f->current(), "\n"; $f->next(); } ?>
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.
#Wren
Wren
import "random" for Random import "/dynamic" for Tuple import "/fmt" for Fmt   var Symbols = Tuple.create("Symbols", ["k", "q", "r", "b", "n"])   var A = Symbols.new("K", "Q", "R", "B", "N") var W = Symbols.new("♔", "♕", "♖", "♗", "♘") var B = Symbols.new("♚", "♛", "♜", "♝", "♞")   var krn = [ "nnrkr", "nrnkr", "nrknr", "nrkrn", "rnnkr", "rnknr", "rnkrn", "rknnr", "rknrn", "rkrnn" ]   var NUL = "\0"   var chess960 = Fn.new { |sym, id| var pos = List.filled(8, NUL) var q = (id/4).floor var r = id % 4 pos[r*2+1]= sym.b var t = q q = (q/4).floor r = t % 4 pos[r*2] = sym.b t = q q = (q/6).floor r = t % 6 var i = 0 while (true) { if (pos[i] == NUL) { if (r == 0) { pos[i] = sym.q break } r = r - 1 } i = i + 1 } i = 0 for (f in krn[q]) { while (pos[i] != NUL) i = i + 1 pos[i] = (f == "k") ? sym.k : (f == "r") ? sym.r : (f == "n") ? sym.n : pos[i] } return pos.join(" ") }   System.print(" ID Start position") for (id in [0, 518, 959]) Fmt.print("$3d $s", id, chess960.call(A, id)) System.print("\nRandom") var rand = Random.new() for (i in 0..4) System.print(chess960.call(W, rand.int(960)))
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.
#C.2B.2B
C++
#include <functional> #include <cmath> #include <iostream>   // functor class to be returned by compose function template <class Fun1, class Fun2> class compose_functor : public std::unary_function<typename Fun2::argument_type, typename Fun1::result_type> { protected: Fun1 f; Fun2 g;   public: compose_functor(const Fun1& _f, const Fun2& _g) : f(_f), g(_g) { }   typename Fun1::result_type operator()(const typename Fun2::argument_type& x) const { return f(g(x)); } };   // we wrap it in a function so the compiler infers the template arguments // whereas if we used the class directly we would have to specify them explicitly template <class Fun1, class Fun2> inline compose_functor<Fun1, Fun2> compose(const Fun1& f, const Fun2& g) { return compose_functor<Fun1,Fun2>(f, g); }   int main() { std::cout << compose(std::ptr_fun(::sin), std::ptr_fun(::asin))(0.5) << std::endl;   return 0; }
http://rosettacode.org/wiki/Fractal_tree
Fractal tree
Generate and draw a fractal tree. Draw the trunk At the end of the trunk, split by some angle and draw two branches Repeat at the end of each branch until a sufficient level of branching is reached Related tasks Pythagoras Tree
#Common_Lisp
Common Lisp
;; (require :lispbuilder-sdl)   (defun deg-to-radian (deg) "converts degrees to radians" (* deg pi 1/180))   (defun cos-deg (angle) "returns cosin of the angle expressed in degress" (cos (deg-to-radian angle)))   (defun sin-deg (angle) "returns sin of the angle expressed in degress" (sin (deg-to-radian angle)))   (defun draw-tree (surface x y angle depth) "draws a branch of the tree on the sdl-surface" (when (plusp depth) (let ((x2 (+ x (round (* depth 10 (cos-deg angle))))) (y2 (+ y (round (* depth 10 (sin-deg angle)))))) (sdl:draw-line-* x y x2 y2 :surface surface :color sdl:*green*) (draw-tree surface x2 y2 (- angle 20) (1- depth)) (draw-tree surface x2 y2 (+ angle 20) (1- depth)))))   (defun fractal-tree (depth) "shows a window with a fractal tree" (sdl:with-init () (sdl:window 800 600 :title-caption "fractal-tree") (sdl:clear-display sdl:*black*) (draw-tree sdl:*default-surface* 400 500 -90 depth) (sdl:update-display) (sdl:with-events () (:video-expose-event () (sdl:update-display)) (:quit-event () t))))   (fractal-tree 9)  
http://rosettacode.org/wiki/Fraction_reduction
Fraction reduction
There is a fine line between numerator and denominator.       ─── anonymous A method to   "reduce"   some reducible fractions is to   cross out   a digit from the numerator and the denominator.   An example is: 16 16 ──── and then (simply) cross─out the sixes: ──── 64 64 resulting in: 1 ─── 4 Naturally,   this "method" of reduction must reduce to the proper value   (shown as a fraction). This "method" is also known as   anomalous cancellation   and also   accidental cancellation. (Of course,   this "method" shouldn't be taught to impressionable or gullible minds.)       😇 Task Find and show some fractions that can be reduced by the above "method".   show 2-digit fractions found   (like the example shown above)   show 3-digit fractions   show 4-digit fractions   show 5-digit fractions   (and higher)       (optional)   show each (above) n-digit fractions separately from other different n-sized fractions, don't mix different "sizes" together   for each "size" fraction,   only show a dozen examples   (the 1st twelve found)   (it's recognized that not every programming solution will have the same generation algorithm)   for each "size" fraction:   show a count of how many reducible fractions were found.   The example (above) is size 2   show a count of which digits were crossed out   (one line for each different digit)   for each "size" fraction,   show a count of how many were found.   The example (above) is size 2   show each n-digit example   (to be shown on one line):   show each n-digit fraction   show each reduced n-digit fraction   show what digit was crossed out for the numerator and the denominator Task requirements/restrictions   only proper fractions and their reductions   (the result)   are to be used   (no vulgar fractions)   only positive fractions are to be used   (no negative signs anywhere)   only base ten integers are to be used for the numerator and denominator   no zeros   (decimal digit)   can be used within the numerator or the denominator   the numerator and denominator should be composed of the same number of digits   no digit can be repeated in the numerator   no digit can be repeated in the denominator   (naturally)   there should be a shared decimal digit in the numerator   and   the denominator   fractions can be shown as   16/64   (for example) Show all output here, on this page. Somewhat related task   Farey sequence       (It concerns fractions.) References   Wikipedia entry:   proper and improper fractions.   Wikipedia entry:   anomalous cancellation and/or accidental cancellation.
#C.23
C#
using System;   namespace FractionReduction { class Program { static int IndexOf(int n, int[] s) { for (int i = 0; i < s.Length; i++) { if (s[i] == n) { return i; } } return -1; }   static bool GetDigits(int n, int le, int[] digits) { while (n > 0) { var r = n % 10; if (r == 0 || IndexOf(r, digits) >= 0) { return false; } le--; digits[le] = r; n /= 10; } return true; }   static int RemoveDigit(int[] digits, int le, int idx) { int[] pows = { 1, 10, 100, 1000, 10000 };   var sum = 0; var pow = pows[le - 2]; for (int i = 0; i < le; i++) { if (i == idx) continue; sum += digits[i] * pow; pow /= 10;   } return sum; }   static void Main() { var lims = new int[,] { { 12, 97 }, { 123, 986 }, { 1234, 9875 }, { 12345, 98764 } }; var count = new int[5]; var omitted = new int[5, 10]; var upperBound = lims.GetLength(0); for (int i = 0; i < upperBound; i++) { var nDigits = new int[i + 2]; var dDigits = new int[i + 2]; var blank = new int[i + 2]; for (int n = lims[i, 0]; n <= lims[i, 1]; n++) { blank.CopyTo(nDigits, 0); var nOk = GetDigits(n, i + 2, nDigits); if (!nOk) { continue; } for (int d = n + 1; d <= lims[i, 1] + 1; d++) { blank.CopyTo(dDigits, 0); var dOk = GetDigits(d, i + 2, dDigits); if (!dOk) { continue; } for (int nix = 0; nix < nDigits.Length; nix++) { var digit = nDigits[nix]; var dix = IndexOf(digit, dDigits); if (dix >= 0) { var rn = RemoveDigit(nDigits, i + 2, nix); var rd = RemoveDigit(dDigits, i + 2, dix); if ((double)n / d == (double)rn / rd) { count[i]++; omitted[i, digit]++; if (count[i] <= 12) { Console.WriteLine("{0}/{1} = {2}/{3} by omitting {4}'s", n, d, rn, rd, digit); } } } } } } Console.WriteLine(); }   for (int i = 2; i <= 5; i++) { Console.WriteLine("There are {0} {1}-digit fractions of which:", count[i - 2], i); for (int j = 1; j <= 9; j++) { if (omitted[i - 2, j] == 0) { continue; } Console.WriteLine("{0,6} have {1}'s omitted", omitted[i - 2, j], j); } Console.WriteLine(); } } } }
http://rosettacode.org/wiki/Fractran
Fractran
FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway. A FRACTRAN program is an ordered list of positive fractions P = ( f 1 , f 2 , … , f m ) {\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})} , together with an initial positive integer input n {\displaystyle n} . The program is run by updating the integer n {\displaystyle n} as follows: for the first fraction, f i {\displaystyle f_{i}} , in the list for which n f i {\displaystyle nf_{i}} is an integer, replace n {\displaystyle n} with n f i {\displaystyle nf_{i}}  ; repeat this rule until no fraction in the list produces an integer when multiplied by n {\displaystyle n} , then halt. Conway gave a program for primes in FRACTRAN: 17 / 91 {\displaystyle 17/91} , 78 / 85 {\displaystyle 78/85} , 19 / 51 {\displaystyle 19/51} , 23 / 38 {\displaystyle 23/38} , 29 / 33 {\displaystyle 29/33} , 77 / 29 {\displaystyle 77/29} , 95 / 23 {\displaystyle 95/23} , 77 / 19 {\displaystyle 77/19} , 1 / 17 {\displaystyle 1/17} , 11 / 13 {\displaystyle 11/13} , 13 / 11 {\displaystyle 13/11} , 15 / 14 {\displaystyle 15/14} , 15 / 2 {\displaystyle 15/2} , 55 / 1 {\displaystyle 55/1} Starting with n = 2 {\displaystyle n=2} , this FRACTRAN program will change n {\displaystyle n} to 15 = 2 × ( 15 / 2 ) {\displaystyle 15=2\times (15/2)} , then 825 = 15 × ( 55 / 1 ) {\displaystyle 825=15\times (55/1)} , generating the following sequence of integers: 2 {\displaystyle 2} , 15 {\displaystyle 15} , 825 {\displaystyle 825} , 725 {\displaystyle 725} , 1925 {\displaystyle 1925} , 2275 {\displaystyle 2275} , 425 {\displaystyle 425} , 390 {\displaystyle 390} , 330 {\displaystyle 330} , 290 {\displaystyle 290} , 770 {\displaystyle 770} , … {\displaystyle \ldots } After 2, this sequence contains the following powers of 2: 2 2 = 4 {\displaystyle 2^{2}=4} , 2 3 = 8 {\displaystyle 2^{3}=8} , 2 5 = 32 {\displaystyle 2^{5}=32} , 2 7 = 128 {\displaystyle 2^{7}=128} , 2 11 = 2048 {\displaystyle 2^{11}=2048} , 2 13 = 8192 {\displaystyle 2^{13}=8192} , 2 17 = 131072 {\displaystyle 2^{17}=131072} , 2 19 = 524288 {\displaystyle 2^{19}=524288} , … {\displaystyle \ldots } which are the prime powers of 2. Task Write a program that reads a list of fractions in a natural format from the keyboard or from a string, to parse it into a sequence of fractions (i.e. two integers), and runs the FRACTRAN starting from a provided integer, writing the result at each step. It is also required that the number of steps is limited (by a parameter easy to find). Extra credit Use this program to derive the first 20 or so prime numbers. See also For more on how to program FRACTRAN as a universal programming language, see: J. H. Conway (1987). Fractran: A Simple Universal Programming Language for Arithmetic. In: Open Problems in Communication and Computation, pages 4–26. Springer. J. H. Conway (2010). "FRACTRAN: A simple universal programming language for arithmetic". In Jeffrey C. Lagarias. The Ultimate Challenge: the 3x+1 problem. American Mathematical Society. pp. 249–264. ISBN 978-0-8218-4940-8. Zbl 1216.68068. Number Pathology: Fractran by Mark C. Chu-Carroll; October 27, 2006.
#BQN
BQN
# Fractran interpreter   # Helpers _while_ ← {𝔽⍟𝔾∘𝔽_𝕣_𝔾∘𝔽⍟𝔾𝕩} ToInt ← 10⊸×⊸+˜´·⌽-⟜'0' ToFrac ← { i ← ⊑/'/'=𝕩 ToInt¨i(↑⋈1⊸+⊸↓)𝕩 } Split ← ((¬-˜⊢×·+`»⊸>)∘≠⊔⊢)   Fractran ← { 𝕊 n‿num‿den: ind ← ⊑/0=den|num×n ⟨(n×ind⊑num)÷ind⊑den ⋄ num ⋄ den⟩ }   RunFractran ← { steps 𝕊 inp‿prg: num‿den ← <˘⍉>ToFrac¨' 'Split prg step ← 1 list ← ⟨inp⟩ { step +↩ 1 out ← Fractran 𝕩 list ∾↩ ⊑out out } _while_ {𝕊 n‿num‿den: (step<steps)∧ ∨´0=den|num} inp‿num‿den list }   seq ← 200 RunFractran 2‿"17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1" •Out "Generated numbers: "∾•Repr seq •Out "Primes: "∾•Repr 1↓⌊2⋆⁼(⌈=⌊)∘(2⊸(⋆⁼))⊸/ seq
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.
#Seed7
Seed7
$ include "seed7_05.s7i"; include "ftp.s7i";   const proc: main is func local var ftpFileSys: ftp is fileSys.value; var string: line is ""; begin ftp := openFtp("kernel.org"); setActiveMode(ftp, FALSE); # Passive is the default. chdir(ftp, "/pub/linux/kernel"); for line range listDir(ftp, ".") do writeln(line); end for; setAsciiTransfer(ftp, FALSE); writeln(getFile(ftp, "README")); close(ftp); end func;
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.
#Sidef
Sidef
require('Net::FTP');   var ftp = %s'Net::FTP'.new('ftp.ed.ac.uk', Passive => 1); ftp.login('anonymous','[email protected]'); ftp.cwd('pub/courses'); [ftp.dir].each {|line| say line }; ftp.binary; # set binary mode ftp.get("make.notes.tar"); ftp.quit;
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.
#Tcl
Tcl
  package require ftp   set conn [::ftp::Open kernel.org anonymous "" -mode passive] ::ftp::Cd $conn /pub/linux/kernel foreach line [ftp::NList $conn] { puts $line } ::ftp::Type $conn binary ::ftp::Get $conn README README  
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
#ALGOL_60
ALGOL 60
begin comment Function definition; integer procedure multiply(a,b); integer a,b; begin multiply:=a*b; end; integer c; c:=multiply(2,2); outinteger(1,c) 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.
#FreeBASIC
FreeBASIC
' version 01-03-2019 ' compile with: fbc -s console   #Define max 20000000   Dim Shared As UInteger f(max)   Sub fusc   f(0) = 0 f(1) = 1   For n As UInteger = 2 To max If n And 1 Then f(n) = f((n -1) \ 2) + f((n +1) \ 2) Else f(n) = f(n \ 2) End If Next   End Sub   ' ------=< MAIN >=------   Dim As UInteger i, d Dim As String fs   fusc   For i = 0 To 60 Print f(i); " "; Next   Print : Print Print " Index Value" For i = 0 To max If f(i) >= d Then Print Using "###########," ; i; f(i) If d = 0 Then d = 1 d *= 10 End If Next   ' empty keyboard buffer While Inkey <> "" : Wend Print : Print "hit any key to end program" Sleep End
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
#Elixir
Elixir
defmodule Gamma do @a [ 1.00000_00000_00000_00000, 0.57721_56649_01532_86061, -0.65587_80715_20253_88108, -0.04200_26350_34095_23553, 0.16653_86113_82291_48950, -0.04219_77345_55544_33675, -0.00962_19715_27876_97356, 0.00721_89432_46663_09954, -0.00116_51675_91859_06511, -0.00021_52416_74114_95097, 0.00012_80502_82388_11619, -0.00002_01348_54780_78824, -0.00000_12504_93482_14267, 0.00000_11330_27231_98170, -0.00000_02056_33841_69776, 0.00000_00061_16095_10448, 0.00000_00050_02007_64447, -0.00000_00011_81274_57049, 0.00000_00001_04342_67117, 0.00000_00000_07782_26344, -0.00000_00000_03696_80562, 0.00000_00000_00510_03703, -0.00000_00000_00020_58326, -0.00000_00000_00005_34812, 0.00000_00000_00001_22678, -0.00000_00000_00000_11813, 0.00000_00000_00000_00119, 0.00000_00000_00000_00141, -0.00000_00000_00000_00023, 0.00000_00000_00000_00002 ] |> Enum.reverse def taylor(x) do y = x - 1 1 / Enum.reduce(@a, 0, fn a,sum -> sum * y + a end) end end   Enum.each(Enum.map(1..10, &(&1/3)), fn x ->  :io.format "~f ~18.15f~n", [x, Gamma.taylor(x)] end)
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.
#Perl
Perl
use strict; use warnings;   use List::Util 'any'; use Time::HiRes qw(sleep); use List::AllUtils <pairwise pairs>;   use utf8; binmode STDOUT, ':utf8';   my $coins = shift || 100; my $peg_lines = shift || 13; my $row_count = $peg_lines; my $peg = '^'; my @coin_icons = ("\N{UPPER HALF BLOCK}", "\N{LOWER HALF BLOCK}");   my @coins = (undef) x (3 + $row_count + 4); my @stats = (0) x ($row_count * 2); $coins[0] = 0; # initialize with first coin   while (1) { my $active = 0; # if a coin falls through the bottom, count it $stats[$coins[-1] + $row_count]++ if defined $coins[-1];   # move every coin down one row for my $line (reverse 1..(3+$row_count+3) ) { my $coinpos = $coins[$line - 1];   #$coins[$line] = do if (! defined $coinpos) x if (! defined $coinpos) { $coins[$line] = undef } elsif (hits_peg($coinpos, $line)) { # when a coin from above hits a peg, it will bounce to either side. $active = 1; $coinpos += rand() < .5 ? -1 : 1; $coins[$line] = $coinpos } else { # if there was a coin above, it will fall to this position. $active = 1; $coins[$line] = $coinpos; } } # let the coin dispenser blink and turn it off if we run out of coins if (defined $coins[0]) { $coins[0] = undef; } elsif (--$coins > 0) { $coins[0] = 0 }   for (<0 1>) { display_board(\@coins, \@stats, $_); sleep .1; } exit unless $active; }   sub display_board { my($p_ref, $s_ref, $halfstep) = @_; my @positions = @$p_ref; my @stats = @$s_ref; my $coin = $coin_icons[$halfstep];   my @board = do { my @tmpl;   sub out { my(@stuff) = split '', shift; my @line; push @line, ord($_) for @stuff; [@line]; }   push @tmpl, out(" " . " "x(2 * $row_count)) for 1..3; my @a = reverse 1..$row_count; my @b = 1..$row_count; my @pairs = pairwise { ($a, $b) } @a, @b; for ( pairs @pairs ) { my ( $spaces, $pegs ) = @$_; push @tmpl, out(" " . " "x$spaces . join(' ',($peg) x $pegs) . " "x$spaces); } push @tmpl, out(" " . " "x(2 * $row_count)) for 1..4; @tmpl; };   my $midpos = $row_count + 2;   our @output; { # collect all the output and output it all at once at the end sub printnl { my($foo) = @_; push @output, $foo . "\n" } sub printl { my($foo) = @_; push @output, $foo }   # make some space above the picture printnl("") for 0..9;   # place the coins for my $line (0..$#positions) { my $pos = $positions[$line]; next unless defined $pos; $board[$line][$pos + $midpos] = ord($coin); } # output the board with its coins for my $line (@board) { printnl join '', map { chr($_) } @$line; }   # show the statistics my $padding = 0; while (any {$_> 0} @stats) { $padding++; printl " "; for my $i (0..$#stats) { if ($stats[$i] == 1) { printl "\N{UPPER HALF BLOCK}"; $stats[$i]--; } elsif ($stats[$i] <= 0) { printl " "; $stats[$i] = 0 } else { printl "\N{FULL BLOCK}"; $stats[$i]--; $stats[$i]--; } } printnl(""); } printnl("") for $padding..(10-1); }   print join('', @output) . "\n"; }   sub hits_peg { my($x, $y) = @_; 3 <= $y && $y < (3 + $row_count) and -($y - 2) <= $x && $x <= $y - 2 ? not 0 == ($x - $y) % 2 : 0 }