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/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
#Perl
Perl
use strict; use warnings; use feature 'say';   sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r }   sub is_gapful { my $n = shift; 0 == $n % join('', (split //, $n)[0,-1]) }   use constant Inf => 1e10; for ([1e2, 30], [1e6, 15], [1e9, 10], [7123, 25]) { my($start, $count) = @$_; printf "\nFirst $count gapful numbers starting at %s:\n", comma $start; my $n = 0; my $g = ''; $g .= do { $n < $count ? (is_gapful($_) and ++$n and "$_ ") : last } for $start .. Inf; say $g; }
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
#Modula-3
Modula-3
GENERIC INTERFACE Matrix(RingElem);   (* "RingElem" must export the following: - a type T; - procedures + "Nonzero(a: T): BOOLEAN", which indicates whether "a" is nonzero; + "Minus(a, b: T): T" and "Times(a, b: T): T", which return the results you'd guess from the procedures' names; and + "Print(a: T)", which does what the name implies. *)   TYPE   T <: Public;   Public = OBJECT METHODS init(READONLY data: ARRAY OF ARRAY OF RingElem.T): T; (* use this to copy the entries in "data"; returns "self" *) initDimensions(m, n: CARDINAL): T; (* use this for an mxn matrix of random entries *) num_rows(): CARDINAL; (* returns the number of rows in "self" *) num_cols(): CARDINAL; (* returns the number of columns in "self" *) entries(): REF ARRAY OF ARRAY OF RingElem.T; (* returns the entries in "self" *) triangularize(); (* Performs Gaussian elimination in the context of a ring. We can add scalar multiples of rows, and we can swap rows, but we may lack multiplicative inverses, so we cannot necessarily obtain 1 as a row's first entry. *) END;   PROCEDURE PrintMatrix(m: T); (* prints the matrix row-by-row; sorry, no special padding to line up columns *)   END Matrix.
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
#Racket
Racket
#lang racket/base   (define (get-matches num factors/words) (for*/list ([factor/word (in-list factors/words)] [factor (in-value (car factor/word))] [word (in-value (cadr factor/word))] #:when (zero? (remainder num factor))) word))   (define (gen-fizzbuzz from to factors/words) (for ([num (in-range from to)]) (define matches (get-matches num factors/words)) (displayln (if (null? matches) (number->string num) (apply string-append matches)))))   (gen-fizzbuzz 1 21 '((3 "Fizz") (5 "Buzz") (7 "Baxx")))
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
#Raku
Raku
# General case implementation of a "FizzBuzz" class. # Defaults to standard FizzBuzz unless a new schema is passed in. class FizzBuzz { has $.schema is rw = < 3 Fizz 5 Buzz >.hash; method filter (Int $this) { my $fb; for $.schema.sort: { +.key } -> $p { $fb ~= $this %% +$p.key ?? $p.value !! ''}; return $fb || $this; } }     # Sub implementing the specific requirements of the task. sub GeneralFizzBuzz (Int $upto, @schema?) { my $ping = FizzBuzz.new; $ping.schema = @schema.hash if @schema; map { $ping.filter: $_ }, 1 .. $upto; }   # The task say 'Using: 20 ' ~ <3 Fizz 5 Buzz 7 Baxx>; .say for GeneralFizzBuzz(20, <3 Fizz 5 Buzz 7 Baxx>);   say '';   # And for fun say 'Using: 21 ' ~ <2 Pip 4 Squack 5 Pocketa 7 Queep>; say join ', ', GeneralFizzBuzz(21, <2 Pip 4 Squack 5 Pocketa 7 Queep>);
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
#Keg
Keg
a(55*|:1+)
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
#Kotlin
Kotlin
// version 1.3.72   fun main() { val alphabet = CharArray(26) { (it + 97).toChar() }.joinToString("")   println(alphabet) }
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#Pharo
Pharo
"Comments are in double quotes" "Sending message printString to 'Hello World' string"   'Hello World' printString
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
#Racket
Racket
  #lang racket   (require racket/generator)   ;; this is a function that returns a powers generator, not a generator (define (powers m) (generator () (for ([n (in-naturals)]) (yield (expt n m)))))   (define squares (powers 2)) (define cubes (powers 3))   ;; same here (define (filtered g1 g2) (generator () (let loop ([n1 (g1)] [n2 (g2)]) (cond [(< n1 n2) (yield n1) (loop (g1) n2)] [(> n1 n2) (loop n1 (g2))] [else (loop (g1) (g2))]))))   (for/list ([x (in-producer (filtered squares cubes) (lambda (_) #f))] [i 30] #:when (>= i 20)) x)  
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.
#EchoLisp
EchoLisp
  ;; By decreasing order of performance ;; 1) user definition : lambda and closure   (define (ucompose f g ) (lambda (x) ( f ( g x)))) (ucompose sin cos) → (🔒 λ (_x) (f (g _x)))   ;; 2) built-in compose : lambda   (compose sin cos) → (λ (_#:g1002) (#apply-compose (#list #cos #sin) _#:g1002))   ;; 3) compiled composition   (define (sincos x) (sin (cos x))) sincos → (λ (_x) (⭕️ #sin (#cos _x)))  
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.
#Ela
Ela
let compose f g x = f (g x)
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
#Haskell
Haskell
import Graphics.Gloss   type Model = [Picture -> Picture]   fractal :: Int -> Model -> Picture -> Picture fractal n model pict = pictures $ take n $ iterate (mconcat model) pict   tree1 _ = fractal 10 branches $ Line [(0,0),(0,100)] where branches = [ Translate 0 100 . Scale 0.75 0.75 . Rotate 30 , Translate 0 100 . Scale 0.5 0.5 . Rotate (-30) ]   main = animate (InWindow "Tree" (800, 800) (0, 0)) white $ tree1 . (* 60)
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
#Icon_and_Unicon
Icon and Unicon
procedure main() WOpen("size=800,600", "bg=black", "fg=white") | stop("*** cannot open window") drawtree(400,500,-90,9) WDone() end   link WOpen   procedure drawtree(x,y,angle,depth) if depth > 0 then { x2 := integer(x + cos(dtor(angle)) * depth * 10) y2 := integer(y + sin(dtor(angle)) * depth * 10) DrawLine(x,y,x2,y2) drawtree(x2,y2,angle-20, depth-1) drawtree(x2,y2,angle+20, depth-1) } return end
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.
#Haskell
Haskell
import Control.Monad (guard) import Data.List (intersect, unfoldr, delete, nub, group, sort) import Text.Printf (printf)   type Fraction = (Int, Int) type Reduction = (Fraction, Fraction, Int)   validIntegers :: [Int] -> [Int] validIntegers xs = [x | x <- xs, not $ hasZeros x, hasUniqueDigits x] where hasZeros = elem 0 . digits 10 hasUniqueDigits n = length ds == length ul where ds = digits 10 n ul = nub ds   possibleFractions :: [Int] -> [Fraction] possibleFractions = (\ys -> [(n,d) | n <- ys, d <- ys, n < d, gcd n d /= 1]) . validIntegers   digits :: Integral a => a -> a -> [a] digits b = unfoldr (\n -> guard (n /= 0) >> pure (n `mod` b, n `div` b))   digitsToIntegral :: Integral a => [a] -> a digitsToIntegral = sum . zipWith (*) (iterate (*10) 1)   findReductions :: Fraction -> [Reduction] findReductions z@(n1, d1) = [ (z, (n2, d2), x) | x <- digits 10 n1 `intersect` digits 10 d1, let n2 = dropDigit x n1 d2 = dropDigit x d1 decimalWithDrop = realToFrac n2 / realToFrac d2, decimalWithDrop == decimal ] where dropDigit d = digitsToIntegral . delete d . digits 10 decimal = realToFrac n1 / realToFrac d1   findGroupReductions :: [Int] -> [Reduction] findGroupReductions = (findReductions =<<) . possibleFractions   showReduction :: Reduction -> IO () showReduction ((n1,d1),(n2,d2),d) = printf "%d/%d = %d/%d by dropping %d\n" n1 d1 n2 d2 d   showCount :: [Reduction] -> Int -> IO () showCount xs n = do printf "There are %d %d-digit fractions of which:\n" (length xs) n mapM_ (uncurry (printf "%5d have %d's omitted\n")) (countReductions xs) >> printf "\n" where countReductions = fmap ((,) . length <*> head) . group . sort . fmap (\(_, _, x) -> x)   main :: IO () main = do mapM_ (\g -> mapM_ showReduction (take 12 g) >> printf "\n") groups mapM_ (uncurry showCount) $ zip groups [2..] where groups = [ findGroupReductions [10^1..99], findGroupReductions [10^2..999] , findGroupReductions [10^3..9999], findGroupReductions [10^4..99999] ]
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.
#Delphi
Delphi
  program FractranTest;   {$APPTYPE CONSOLE}   uses System.SysUtils, System.RegularExpressions;   type TFractan = class private limit: Integer; num, den: TArray<Integer>; procedure compile(prog: string); procedure exec(val: Integer); function step(val: Integer): integer; procedure dump(); public constructor Create(prog: string; val: Integer); end;   { TFractan }   constructor TFractan.Create(prog: string; val: Integer); begin limit := 15; compile(prog); dump(); exec(2); end;   procedure TFractan.compile(prog: string); var reg: TRegEx; m: TMatch; begin reg := TRegEx.Create('\s*(\d*)\s*\/\s*(\d*)\s*'); m := reg.Match(prog); while m.Success do begin SetLength(num, Length(num) + 1); num[high(num)] := StrToIntDef(m.Groups[1].Value, 0);   SetLength(den, Length(den) + 1); den[high(den)] := StrToIntDef(m.Groups[2].Value, 0);   m := m.NextMatch; end; end;   procedure TFractan.exec(val: Integer); var n: Integer; begin n := 0; while (n < limit) and (val <> -1) do begin Writeln(n, ': ', val); val := step(val); inc(n); end; end;   function TFractan.step(val: Integer): integer; var i: integer; begin i := 0; while (i < length(den)) and (val mod den[i] <> 0) do inc(i); if i < length(den) then exit(round(num[i] * val / den[i])); result := -1; end;   procedure TFractan.dump(); var i: Integer; begin for i := 0 to high(den) do Write(num[i], '/', den[i], ' '); Writeln; end;   const DATA = '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';   begin TFractan.Create(DATA, 2).Free; Readln; end.
http://rosettacode.org/wiki/Function_definition
Function definition
A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract from showing how functions are created and values returned). Related task   Function prototype
#APL
APL
  ⍝⍝ APL2 'tradfn' (traditional function) ⍝⍝ This syntax works in all dialects including GNU APL and Dyalog. ∇ product ← a multiply b product ← a × b ∇   ⍝⍝ A 'dfn' or 'lambda' (anonymous function) multiply ← {⍺×⍵}  
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.
#Java
Java
    public class FuscSequence {   public static void main(String[] args) { System.out.println("Show the first 61 fusc numbers (starting at zero) in a horizontal format"); for ( int n = 0 ; n < 61 ; n++ ) { System.out.printf("%,d ", fusc[n]); }   System.out.printf("%n%nShow the fusc number (and its index) whose length is greater than any previous fusc number length.%n"); int start = 0; for (int i = 0 ; i <= 5 ; i++ ) { int val = i != 0 ? (int) Math.pow(10, i) : -1; for ( int j = start ; j < FUSC_MAX ; j++ ) { if ( fusc[j] > val ) { System.out.printf("fusc[%,d] = %,d%n", j, fusc[j] ); start = j; break; } } } }   private static final int FUSC_MAX = 30000000; private static int[] fusc = new int[FUSC_MAX];   static { fusc[0] = 0; fusc[1] = 1; for ( int n = 2 ; n < FUSC_MAX ; n++ ) { fusc[n] = (n % 2 == 0 ? fusc[n/2] : fusc[(n-1)/2] + fusc[(n+1)/2]); } } }  
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
#Go
Go
package main   import ( "fmt" "math" )   func main() { fmt.Println(" x math.Gamma Lanczos7") for _, x := range []float64{-.5, .1, .5, 1, 1.5, 2, 3, 10, 140, 170} { fmt.Printf("%5.1f %24.16g %24.16g\n", x, math.Gamma(x), lanczos7(x)) } }   func lanczos7(z float64) float64 { t := z + 6.5 x := .99999999999980993 + 676.5203681218851/z - 1259.1392167224028/(z+1) + 771.32342877765313/(z+2) - 176.61502916214059/(z+3) + 12.507343278686905/(z+4) - .13857109526572012/(z+5) + 9.9843695780195716e-6/(z+6) + 1.5056327351493116e-7/(z+7) return math.Sqrt2 * math.SqrtPi * math.Pow(t, z-.5) * math.Exp(-t) * x }
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.
#REXX
REXX
/*REXX pgm simulates Sir Francis Galton's box, aka: Galton Board, quincunx, bean machine*/ trace off /*suppress any messages for negative RC*/ if !all(arg()) then exit /*Any documentation was wanted? Done.*/ signal on halt /*allow the user to halt the program.*/ parse arg rows balls freeze seed . /*obtain optional arguments from the CL*/ if rows =='' | rows=="," then rows= 0 /*Not specified? Then use the default.*/ if balls=='' | balls=="," then balls= 100 /* " " " " " " */ if freeze=='' | freeze=="," then freeze= 0 /* " " " " " " */ if datatype(seed, 'W') then call random ,,seed /*Was a seed specified? Then use seed.*/ pin = '·'; ball = '☼' /*define chars for a pin and a ball.*/ parse value scrsize() with sd sw . /*obtain the terminal depth and width. */ if sd==0 then sd= 40 /*Not defined by the OS? Use a default*/ if sw==0 then sw= 80 /* " " " " " " " " */ sd= sd - 3 /*define the usable screen depth.*/ sw= sw - 1; if sw//2 then sw= sw - 1 /* " " " odd " width.*/ if rows==0 then rows= (sw - 2 ) % 3 /*pins are on the first third of screen*/ call gen /*gen a triangle of pins with some rows*/ do step=1; call drop; call show /*show animation 'til run out of balls.*/ end /*step*/ /* [↑] the dropping/showing " " */ exit 0 /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ gen: @.=; do r=0 by 2 to rows; $= /*build a triangle of pins for the box.*/ do pins=1 for r%2; $= $ pin /*build a row of pins to be displayed. */ end /*pins*/ @.r= center( strip($, 'T'), sw) /*an easy method to build a triangle. */ end /*r*/; #= 0; return /*#: is the number of balls dropped. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ drop: static= 1 /*used to indicate all balls are static*/ do c=sd-1 by -1 for sd-1; n= c + 1 /*D: current row; N: the next row. */ x= pos(ball, @.c); y= x - 1 /*X: position of a ball on the C line.*/ if x==0 then iterate /*No balls here? Then nothing to drop.*/ do forever; y= pos(ball, @.c, y+1) /*drop most balls down to the next row.*/ if y==0 then iterate c /*down with this row, go look at next. */ z= substr(@.n, y, 1) /*another ball is blocking this fall. */ if z==' ' then do; @.n= overlay(ball, @.n, y) /*drop a ball straight down.*/ @.c= overlay(' ' , @.c, y) /*make current ball a ghost.*/ static= 0 /*indicate balls are moving.*/ iterate /*go keep looking for balls.*/ end if z==pin then do;  ?= random(,999); d= -1 /*assume falling to the left*/ if ?//2 then d= 1 /*if odd random#, fall right*/ if substr(@.n, y+d, 1)\==' ' then iterate /*blocked fall*/ @.n= overlay(ball, @.n, y+d) @.c= overlay(' ' , @.c, y ) static= 0 /*indicate balls are moving.*/ iterate /*go keep looking for balls.*/ end end /*forever*/ end /*c*/ /* [↓] step//2 is used to avoid collisions. */ /* [↓] drop a new ball ? */ if #<balls & step//2 then do; @.1= center(ball, sw+1); # = # + 1; end else if static then exit 2 /*insure balls are static. */ return /*──────────────────────────────────────────────────────────────────────────────────────*/ show: !cls; do LR=sd by -1 until @.LR\=='' /*LR: last row of data.*/ end /*LR*/; ss= 'step' step /* [↓] display a row. */ do r=1 for LR; _= strip(@.r, 'T'); if r==2 then _= overlay(ss, _, sw-12); say _ end /*r*/; if step==freeze then do; say 'press ENTER ···'; pull; end return /*══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════*/ halt: say '***warning*** REXX program'  !fn "execution halted by user."; exit 1 !all:  !!=!;!=space(!);upper !;call !fid;!nt=right(!var('OS'),2)=='NT';!cls=word('CLS VMFCLEAR CLRSCREEN',1+!cms+!tso*2);if arg(1)\==1 then return 0;if wordpos(!,'? ?SAMPLES ?AUTHOR ?FLOW')==0 then return 0;!call=']$H';call '$H' !fn !;!call=;return 1 !cal: if symbol('!CALL')\=="VAR" then !call=; return !call !env:  !env='ENVIRONMENT'; if !sys=='MSDOS' | !brexx | !r4 | !roo then !env= 'SYSTEM'; if !os2 then !env= 'OS2'!env;  !ebcdic= 2=='f2'x; if !crx then !env= 'DOS'; return !fid: parse upper source !sys !fun !fid . 1 . . !fn !ft !fm .; call !sys; if !dos then do; _= lastpos('\', !fn);  !fm= left(!fn, _);  !fn= substr(!fn, _+1); parse var !fn !fn '.' !ft; end; return word(0 !fn !ft !fm, 1 + ('0'arg(1) ) ) !rex: parse upper version !ver !vernum !verdate .; !brexx= 'BY'==!vernum; !kexx= 'KEXX'==!ver; !pcrexx= 'REXX/PERSONAL'==!ver | 'REXX/PC'==!ver; !r4= 'REXX-R4'==!ver; !regina= 'REXX-REGINA'==left(!ver, 11); !roo= 'REXX-ROO'==!ver; call !env; return !sys:  !cms= !sys=='CMS';  !os2= !sys=='OS2';  !tso= !sys=='TSO' | !sys=='MVS';  !vse= !sys=='VSE';  !dos= pos('DOS', !sys)\==0 | pos('WIN', !sys)\==0 | !sys=='CMD';  !crx= left(!sys, 6)=='DOSCRX'; call !rex; return !var: call !fid; if !kexx then return space( dosenv( arg(1) ) ); return space( value( arg(1), , !env) )
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
#Phix
Phix
constant starts = {1e2, 1e6, 1e7, 1e9, 7123}, counts = {30, 15, 15, 10, 25} for i=1 to length(starts) do integer count = counts[i], j = starts[i], pow = 100 while j>=pow*10 do pow *= 10 end while printf(1,"First %d gapful numbers starting at %,d: ", {count, j}) while count do integer fl = floor(j/pow)*10 + remainder(j,10) if remainder(j,fl)==0 then printf(1,"%d ", j) count -= 1 end if j += 1 if j>=10*pow then pow *= 10 end if end while printf(1,"\n") end for
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
#Nim
Nim
const Eps = 1e-14 # Tolerance required.   type   Vector[N: static Positive] = array[N, float] Matrix[M, N: static Positive] = array[M, Vector[N]] SquareMatrix[N: static Positive] = Matrix[N, N]   func gaussPartialScaled(a: SquareMatrix; b: Vector): Vector =   doAssert a.N == b.N, "matrix and vector have incompatible dimensions" const N = a.N   var m: Matrix[N, N + 1] for i, row in a: m[i][0..<N] = row m[i][N] = b[i]   for k in 0..<N: var imax = 0 var vmax = -1.0   for i in k..<N: # Compute scale factor s = max abs in row. var s = -1.0 for j in k..N: let e = abs(m[i][j]) if e > s: s = e # Scale the abs used to pick the pivot. let val = abs(m[i][k]) / s if val > vmax: imax = i vmax = val   if m[imax][k] == 0: raise newException(ValueError, "matrix is singular")   swap m[imax], m[k]   for i in (k + 1)..<N: for j in (k + 1)..N: m[i][j] -= m[k][j] * m[i][k] / m[k][k] m[i][k] = 0   for i in countdown(N - 1, 0): result[i] = m[i][N] for j in (i + 1)..<N: result[i] -= m[i][j] * result[j] result[i] /= m[i][i]     #———————————————————————————————————————————————————————————————————————————————————————————————————   let a: SquareMatrix[6] = [[1.00, 0.00, 0.00, 0.00, 0.00, 0.00], [1.00, 0.63, 0.39, 0.25, 0.16, 0.10], [1.00, 1.26, 1.58, 1.98, 2.49, 3.13], [1.00, 1.88, 3.55, 6.70, 12.62, 23.80], [1.00, 2.51, 6.32, 15.88, 39.90, 100.28], [1.00, 3.14, 9.87, 31.01, 97.41, 306.02]]   let b: Vector[6] = [-0.01, 0.61, 0.91, 0.99, 0.60, 0.02]   let refx: Vector[6] = [-0.01, 1.602790394502114, -1.6132030599055613, 1.2454941213714368, -0.4909897195846576, 0.065760696175232]   let x = gaussPartialScaled(a, b) echo x for i, xi in x: if abs(xi - refx[i]) > Eps: echo "Out of tolerance." echo "Expected values are ", refx break
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
#Red
Red
Red ["FizzBuzz"]   nmax: to-integer ask "Max number: " while ["" <> trim rule: ask "New rule (empty to end): "][ append rules: [] load rule ] repeat n nmax [ res: copy "" foreach [x blah] rules [ if n % x = 0 [append res blah] ] print either empty? res [n] [res] ] halt
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
#REXX
REXX
/*REXX program shows a generalized FizzBuzz program: #1 name1 #2 name2 ··· */ parse arg h $ /*obtain optional arguments from the CL*/ if h='' | h="," then h= 20 /*Not specified? Then use the default.*/ if $='' | $="," then $= "3 Fizz 5 Buzz 7 Baxx" /* " " " " " " */ factors= words($) % 2 /*determine number of factors to use. */   do i=1 by 2 for factors /*parse the number factors to be used. */ #.i=word($, i); @.i=word($, i+1) /*obtain the factor and its "name". */ end /*i*/   do j=1 for h; z= /*traipse through the numbers to H. */ do k=1 by 2 for factors /* " " " factors in J. */ if j//#.k==0 then z= z || @.k /*Is it a factor? Then append it to Z.*/ end /*k*/ /* [↑] Note: the factors may be zero.*/ say word(z j, 1) /*display the number or its factors. */ end /*j*/ /*stick a fork in it, we're all done. */
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
#Lambdatalk
Lambdatalk
    1) We define code2char & char2code as primitives:   {script LAMBDATALK.DICT["char2code"] = function() { var args = arguments[0].trim(); return args.charCodeAt(0); };   LAMBDATALK.DICT["code2char"] = function() { var args = arguments[0].trim(); return String.fromCharCode(args); }; }   2) and we use them:   {S.map code2char {S.serie {char2code a} {char2code z}}} -> a b c d e f g h i j k l m n o p q r s t u v w x y z   {S.map code2char {S.serie {char2code 0} {char2code 9}}} -> 0 1 2 3 4 5 6 7 8 9  
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
#Phix
Phix
puts(1,"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
#Raku
Raku
sub powers($m) { $m XR** 0..* }   my @squares = powers(2); my @cubes = powers(3);   sub infix:<with-out> (@orig,@veto) { gather for @veto -> $veto { take @orig.shift while @orig[0] before $veto; @orig.shift if @orig[0] eqv $veto; } }   say (@squares with-out @cubes)[20 ..^ 20+10].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.
#Elena
Elena
import extensions;   extension op : Func1 { compose(Func1 f) = (x => self(f(x))); }   public program() { var fg := (x => x + 1).compose:(x => x * x);   console.printLine(fg(3)) }
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.
#Elixir
Elixir
defmodule RC do def compose(f, g), do: fn(x) -> f.(g.(x)) end   def multicompose(fs), do: List.foldl(fs, fn(x) -> x end, &compose/2) end   sin_asin = RC.compose(&:math.sin/1, &:math.asin/1) IO.puts sin_asin.(0.5)   IO.puts RC.multicompose([&:math.sin/1, &:math.asin/1, fn x->1/x end]).(0.5) IO.puts RC.multicompose([&(&1*&1), &(1/&1), &(&1*&1)]).(0.5)
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
#J
J
require'gl2' coinsert'jgl2'   L0=: 50 NB. initial length A0=: 1r8p1 NB. initial angle: pi divided by 8 dL=: 0.9 NB. shrink factor for length dA=: 0.75 NB. shrink factor for angle N=: 14 NB. number of branches   L=: L0*dL^1+i.N NB. lengths of line segments   NB. relative angles of successive line segments A=: A0*(dA^i.N) +/\@:*("1) _1 ^ #:i.2 ^ N   NB. end points for each line segment P=: 0 0+/\@,"2 +.*.inv (L0,0),"2 L,"0"1 A   wd {{)n pc P closeok; setp wh 480 640; cc C isidraw flush; pshow; }}   gllines <.(10 + ,/"2 P-"1<./,/P)
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
#Java
Java
import java.awt.Color; import java.awt.Graphics; import javax.swing.JFrame;   public class FractalTree extends JFrame {   public FractalTree() { super("Fractal Tree"); setBounds(100, 100, 800, 600); setResizable(false); setDefaultCloseOperation(EXIT_ON_CLOSE); }   private void drawTree(Graphics g, int x1, int y1, double angle, int depth) { if (depth == 0) return; int x2 = x1 + (int) (Math.cos(Math.toRadians(angle)) * depth * 10.0); int y2 = y1 + (int) (Math.sin(Math.toRadians(angle)) * depth * 10.0); g.drawLine(x1, y1, x2, y2); drawTree(g, x2, y2, angle - 20, depth - 1); drawTree(g, x2, y2, angle + 20, depth - 1); }   @Override public void paint(Graphics g) { g.setColor(Color.BLACK); drawTree(g, 400, 500, -90, 9); }   public static void main(String[] args) { new FractalTree().setVisible(true); } }
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.
#J
J
  Filter=: (#~`)(`:6) assert 'ac' -: 1 0 1"_ Filter 'abc'   intersect=:-.^:2 assert 'ab' -: 'abc'intersect'razb'   odometer=: (4$.$.)@:($&1) Note 'odometer 2 3' 0 0 0 1 0 2 1 0 1 1 1 2 )   common=: 0 e. ~: assert common 1 2 1 assert -. common 1 2 3   o=: '123456789' {~ [: -.@:common"1 Filter odometer@:(#&9) NB. o is y unique digits, all of them   f=: ,:"1/&g~ NB. f computes a table of all numerators and denominators pairs   mask=: [: </~&i. # NB. the lower triangle will become proper fractions   av=: (([: , mask) # ,/)@:f NB. anti-vulgarization   c=: [: common@:,/"2 Filter av NB. ensure common digit(s)   fac=: [: ([: common ,&:~.&:q:&:"./)"2 Filter c NB. assure a common factor NB. This common factor filter might be useful in a future fully tacit version of the program.   cancellation=: monad define NDL =. c y NB. vector of literal numerator and denominator NB. retain reducible fractions ND =. ". NDL NB. integral version of NDL MASK=. ([: common ,&:~.&:q:/)"1 ND NB. assure a common factor FRAC=. _2 x: MASK # ND NB. division CANDIDATES=. MASK # NDL rat=. , 'r'&, result=. 0 3 $ a: for_i. i. # CANDIDATES do. fraction =. i { FRAC pair=. i { CANDIDATES for_d. intersect/ pair do. trial=. pair -."1 d if. fraction = _2 x: ". trial do. result =. result , (rat/pair) ; (rat/trial) ; d end. end. end. result )  
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.
#Elixir
Elixir
defmodule Fractran do use Bitwise   defp binary_to_ratio(b) do [_, num, den] = Regex.run(~r/(\d+)\/(\d+)/, b) {String.to_integer(num), String.to_integer(den)} end   def load(program) do String.split(program) |> Enum.map(&binary_to_ratio(&1)) end   defp step(_, []), do: :halt defp step(n, [f|fs]) do {p, q} = mulrat(f, {n, 1}) case q do 1 -> p _ -> step(n, fs) end end   def exec(k, n, program) do exec(k-1, n, fn (_) -> true end, program, [n]) |> Enum.reverse end   def exec(k, n, pred, program) do exec(k-1, n, pred, program, [n]) |> Enum.reverse end   defp exec(0, _, _, _, steps), do: steps defp exec(k, n, pred, program, steps) do case step(n, program) do  :halt -> steps m -> if pred.(m), do: exec(k-1, m, pred, program, [m|steps]), else: exec(k, m, pred, program, steps) end end   def is_pow2(n), do: band(n, n-1) == 0   def lowbit(n), do: lowbit(n, 0)   defp lowbit(n, k) do case band(n, 1) do 0 -> lowbit(bsr(n, 1), k + 1) 1 -> k end end   # rational multiplication defp mulrat({a, b}, {c, d}) do {p, q} = {a*c, b*d} g = gcd(p, q) {div(p, g), div(q, g)} end   defp gcd(a, 0), do: a defp gcd(a, b), do: gcd(b, rem(a, b)) end   primegen = Fractran.load("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") IO.puts "The first few states of the Fractran prime automaton are:\n#{inspect Fractran.exec(20, 2, primegen)}\n" prime = Fractran.exec(26, 2, &Fractran.is_pow2/1, primegen) |> Enum.map(&Fractran.lowbit/1) |> tl IO.puts "The first few primes are:\n#{inspect prime}"
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
#AppleScript
AppleScript
to multiply(a as number, b as number) return a * b 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.
#JavaScript
JavaScript
(() => { "use strict";   // ---------------------- FUSC -----------------------   // fusc :: Int -> Int const fusc = i => { const go = n => 0 === n ? [ 1, 0 ] : (() => { const [x, y] = go(Math.floor(n / 2));   return 0 === n % 2 ? ( [x + y, y] ) : [x, x + y]; })();   return 1 > i ? ( 0 ) : go(i - 1)[0]; };     // ---------------------- TEST ----------------------- const main = () => { const terms = enumFromTo(0)(60).map(fusc);   return [ "First 61 terms:", `[${terms.join(",")}]`, "", "(Index, Value):", firstWidths(5).reduce( (a, x) => [x.slice(1), ...a], [] ) .map(([i, x]) => `(${i}, ${x})`) .join("\n") ] .join("\n"); };     // firstWidths :: Int -> [(Int, Int)] const firstWidths = n => { const nxtWidth = xs => { const fi = fanArrow(fusc)(x => x), [w, i] = xs[0], [x, j] = Array.from( until( v => w <= `${v[0]}`.length )( v => fi(1 + v[1]) )(fi(i)) );   return [ [1 + w, j, x], ...xs ]; };   return until(x => n < x[0][0])( nxtWidth )([ [2, 0, 0] ]); };     // ---------------- GENERIC FUNCTIONS ----------------   // enumFromTo :: Int -> Int -> [Int] const enumFromTo = m => n => Array.from({ length: 1 + n - m }, (_, i) => m + i);     // fanArrow (&&&) :: // (a -> b) -> (a -> c) -> (a -> (b, c)) const fanArrow = f => // A combined function, given f and g, // from x to a tuple of (f(x), g(x)) // ((,) . f <*> g) g => x => [f(x), g(x)];     // until :: (a -> Bool) -> (a -> a) -> a -> a const until = p => // The value resulting from successive applications // of f to f(x), starting with a seed value x, // and terminating when the result returns true // for the predicate p. f => { const go = x => p(x) ? x : go(f(x));   return go; };   // MAIN --- return main(); })();
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
#Groovy
Groovy
a = [ 1.00000000000000000000, 0.57721566490153286061, -0.65587807152025388108, -0.04200263503409523553, 0.16653861138229148950, -0.04219773455554433675, -0.00962197152787697356, 0.00721894324666309954, -0.00116516759185906511, -0.00021524167411495097, 0.00012805028238811619, -0.00002013485478078824, -0.00000125049348214267, 0.00000113302723198170, -0.00000020563384169776, 0.00000000611609510448, 0.00000000500200764447, -0.00000000118127457049, 0.00000000010434267117, 0.00000000000778226344, -0.00000000000369680562, 0.00000000000051003703, -0.00000000000002058326, -0.00000000000000534812, 0.00000000000000122678, -0.00000000000000011813, 0.00000000000000000119, 0.00000000000000000141, -0.00000000000000000023, 0.00000000000000000002].reverse()   def gamma = { 1.0 / a.inject(0) { sm, a_i -> sm * (it - 1) + a_i } }   (1..10).each{ printf("% 1.9e\n", gamma(it / 3.0)) }  
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.
#Ruby
Ruby
$rows_of_pins = 12 $width = $rows_of_pins * 10 + ($rows_of_pins+1)*14   Shoes.app( :width => $width + 14, :title => "Galton Box" ) do @bins = Array.new($rows_of_pins+1, 0)   @x_coords = Array.new($rows_of_pins) {Array.new} @y_coords = Array.new($rows_of_pins) stack(:width => $width) do stroke gray fill gray 1.upto($rows_of_pins) do |row| y = 14 + 24*row @y_coords[row-1] = y row.times do |i| x = $width / 2 + (i - 0.5*row)*24 + 14 @x_coords[row-1] << x oval x+2, y, 6 end end end @y_coords << @y_coords[-1] + 24 @x_coords << @x_coords[-1].map {|x| x-12} + [@x_coords[-1][-1]+12]   @balls = stack(:width => $width) do stroke red fill red end.move(0,0)   @histogram = stack(:width => $width) do nostroke fill black end.move(0, @y_coords[-1] + 10)   @paused = false keypress do |key| case key when "\x11", :control_q exit when "\x10", :control_p @paused = !@paused end end   @ball_row = 0 @ball_col = 0 animate(2*$rows_of_pins) do if not @paused y = @y_coords[@ball_row] - 12 x = @x_coords[@ball_row][@ball_col] @balls.clear {oval x, y, 10} @ball_row += 1 if @ball_row <= $rows_of_pins @ball_col += 1 if rand >= 0.5 else @bins[@ball_col] += 1 @ball_row = @ball_col = 0 update_histogram end end end   def update_histogram y = @y_coords[-1] + 10 @histogram.clear do @bins.each_with_index do |num, i| if num > 0 x = @x_coords[-1][i] rect x-6, 0, 24, num end end end end 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
#Plain_English
Plain English
To run: Start up. Show the gapful numbers at various spots. Wait for the escape key. Shut down.   A digit is a number.   To get a digit of a number (last): Privatize the number. Divide the number by 10 giving a quotient and a remainder. Put the remainder into the digit.   To get a digit of a number (first): Privatize the number. Loop. Divide the number by 10 giving a quotient and a remainder. Put the quotient into the number. If the number is 0, put the remainder into the digit; exit. Repeat.   To make a number from the first and last digits of another number: Get a digit of the other number (first). Get another digit of the other number (last). Put the digit times 10 plus the other digit into the number.   To decide if a number is gapful: Make another number from the first and last digits of the number. If the number is evenly divisible by the other number, say yes. Say no.   To show a number of the gapful numbers starting from another number: Privatize the other number. Put 0 into a gapful counter. Loop. If the other number is gapful, write "" then the other number then " " on the console without advancing; bump the gapful counter. If the gapful counter is the number, break. Bump the other number. Repeat. Write "" then the return byte on the console.   To show the gapful numbers at various spots: Write "30 gapful numbers starting at 100:" on the console. Show 30 of the gapful numbers starting from 100. Write "15 gapful numbers starting at 1000000:" on the console. Show 15 of the gapful numbers starting from 1000000. Write "10 gapful numbers starting at 1000000000:" on the console. Show 10 of the gapful numbers starting from 1000000000.
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
#OCaml
OCaml
  module Array = struct include Array (* Computes: f a.(0) + f a.(1) + ... where + is 'g'. *) let foldmap g f a = let n = Array.length a in let rec aux acc i = if i >= n then acc else aux (g acc (f a.(i))) (succ i) in aux (f a.(0)) 1   (* like the stdlib fold_left, but also provides index to f *) let foldi_left f x a = let r = ref x in for i = 0 to length a - 1 do r := f i !r (unsafe_get a i) done; !r end   let foldmap_range g f (a,b) = let rec aux acc n = let n = succ n in if n > b then acc else aux (g acc (f n)) n in aux (f a) a   let fold_range f init (a,b) = let rec aux acc n = if n > b then acc else aux (f acc n) (succ n) in aux init a  
http://rosettacode.org/wiki/General_FizzBuzz
General FizzBuzz
Task Write a generalized version of FizzBuzz that works for any list of factors, along with their words. This is basically a "fizzbuzz" implementation where the user supplies the parameters. The user will enter the max number, then they will enter the factors to be calculated along with the corresponding word to be printed. For simplicity's sake, assume the user will input an integer as the max number and 3 factors, each with a word associated with them. For example, given: >20 #This is the maximum number, supplied by the user >3 Fizz #The user now enters the starting factor (3) and the word they want associated with it (Fizz) >5 Buzz #The user now enters the next factor (5) and the word they want associated with it (Buzz) >7 Baxx #The user now enters the next factor (7) and the word they want associated with it (Baxx) In other words: For this example, print the numbers 1 through 20, replacing every multiple of 3 with "Fizz", every multiple of 5 with "Buzz", and every multiple of 7 with "Baxx". In the case where a number is a multiple of at least two factors, print each of the words associated with those factors in the order of least to greatest factor. For instance, the number 15 is a multiple of both 3 and 5; print "FizzBuzz". If the max number was 105 instead of 20, you would print "FizzBuzzBaxx" because it's a multiple of 3, 5, and 7. Output: 1 2 Fizz 4 Buzz Fizz Baxx 8 Fizz Buzz 11 Fizz 13 Baxx FizzBuzz 16 17 Fizz 19 Buzz
#Ring
Ring
  limit = 20 for n = 1 to limit if n % 3 = 0 see "" + n + " = " + "Fizz"+ nl but n % 5 = 0 see "" + n + " = " + "Buzz" + nl but n % 7 = 0 see "" + n + " = " + "Baxx" + nl else see "" + n + " = " + n + nl ok next    
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
#Ruby
Ruby
def general_fizzbuzz(text) num, *nword = text.split num = num.to_i dict = nword.each_slice(2).map{|n,word| [n.to_i,word]} (1..num).each do |i| str = dict.map{|n,word| word if i%n==0}.join puts str.empty? ? i : str end end   text = <<EOS 20 3 Fizz 5 Buzz 7 Baxx EOS   general_fizzbuzz(text)
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
#LC3_Assembly
LC3 Assembly
.ORIG 0x3000   LD R0,ASCIIa LD R1,ASCIIz NOT R1,R1   LOOP OUT ADD R0,R0,1 ADD R2,R0,R1 BRN LOOP   HALT   ASCIIa .FILL 0x61 ASCIIz .FILL 0x7A
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
#Lingo
Lingo
alphabet = [] repeat with i = 97 to 122 alphabet.add(numtochar(i)) end repeat put alphabet -- ["a", "b", "c", ... , "x", "y", "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
#PHL
PHL
module helloworld; extern printf;   @Integer main [ printf("Hello world!"); return 0; ]
http://rosettacode.org/wiki/Generator/Exponential
Generator/Exponential
A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided. Generators are often built on top of coroutines or objects so that the internal state of the object is handled “naturally”. Generators are often used in situations where a sequence is potentially infinite, and where it is possible to construct the next value of the sequence with only minimal state. Task Create a function that returns a generation of the m'th powers of the positive integers starting from zero, in order, and without obvious or simple upper limit. (Any upper limit to the generator should not be stated in the source but should be down to factors such as the languages natural integer size limit or computational time/size). Use it to create a generator of:   Squares.   Cubes. Create a new generator that filters all cubes from the generator of squares. Drop the first 20 values from this last generator of filtered results, and then show the next 10 values. Note that this task requires the use of generators in the calculation of the result. Also see Generator
#REXX
REXX
/*REXX program demonstrates how to use a generator (also known as an iterator). */ parse arg N .; if N=='' | N=="," then N=20 /*N not specified? Then use default.*/ @.= /* [↓] calculate squares,cubes,pureSq.*/ do i=1 for N; call Gsquare i call Gcube i call GpureSquare i /*these are cube─free square numbers.*/ end /*i*/   do k=1 for N; @.pureSquare.k=; end /*k*/ /*this is used to drop 1st N values.*/   w=length(N+10); ps= 'pure square' /*the width of the numbers; a literal.*/   do m=N+1 for 10; say ps right(m, w)":" right(GpureSquare(m), 3*w) end /*m*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ Gpower: procedure expose @.; parse arg x,p; [email protected] if q\=='' then return q; _=x**p; @.pow.x.p=_ return _ /*──────────────────────────────────────────────────────────────────────────────────────*/ Gsquare: procedure expose @.; parse arg x; [email protected] if q=='' then @.square.x=Gpower(x, 2) return @.square.x /*──────────────────────────────────────────────────────────────────────────────────────*/ Gcube: procedure expose @.; parse arg x; [email protected] if q=='' then @.cube.x=Gpower(x, 3) [email protected]; @.3pow._=1 return @.cube.x /*──────────────────────────────────────────────────────────────────────────────────────*/ GpureSquare: procedure expose @.; parse arg x; [email protected] if q\=='' then return q #=0 do j=1 until #==x;  ?=Gpower(j, 2) /*search for pure square. */ if @.3pow.?==1 then iterate /*is it a power of three? */ #=#+1; @.pureSquare.#=? /*assign next pureSquare. */ end /*j*/ return @.pureSquare.x
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.
#Emacs_Lisp
Emacs Lisp
;; lexical-binding: t (defun compose (f g) (lambda (x) (funcall f (funcall g x))))   (let ((func (compose '1+ '1+))) (funcall func 5)) ;=> 7
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.
#Erlang
Erlang
-module(fn). -export([compose/2, multicompose/1]).   compose(F,G) -> fun(X) -> F(G(X)) end.   multicompose(Fs) -> lists:foldl(fun compose/2, fun(X) -> X end, Fs).
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
#JavaScript
JavaScript
<html> <body> <canvas id="canvas" width="600" height="500"></canvas>   <script type="text/javascript"> var elem = document.getElementById('canvas'); var context = elem.getContext('2d');   context.fillStyle = '#C0C0C0'; context.lineWidth = 1;   var deg_to_rad = Math.PI / 180.0; var depth = 9;   function drawLine(x1, y1, x2, y2, brightness){ context.moveTo(x1, y1); context.lineTo(x2, y2); }   function drawTree(x1, y1, angle, depth){ if (depth !== 0){ var x2 = x1 + (Math.cos(angle * deg_to_rad) * depth * 10.0); var y2 = y1 + (Math.sin(angle * deg_to_rad) * depth * 10.0); drawLine(x1, y1, x2, y2, depth); drawTree(x2, y2, angle - 20, depth - 1); drawTree(x2, y2, angle + 20, depth - 1); } }   context.beginPath(); drawTree(300, 500, -90, depth); context.closePath(); context.stroke(); </script>   </body> </html>
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.
#Java
Java
  import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map;   public class FractionReduction {   public static void main(String[] args) { for ( int size = 2 ; size <= 5 ; size++ ) { reduce(size); } }   private static void reduce(int numDigits) { System.out.printf("Fractions with digits of length %d where cancellation is valid. Examples:%n", numDigits);   // Generate allowed numerator's and denominator's int min = (int) Math.pow(10, numDigits-1); int max = (int) Math.pow(10, numDigits) - 1; List<Integer> values = new ArrayList<>(); for ( int number = min ; number <= max ; number++ ) { if ( isValid(number) ) { values.add(number); } }   Map<Integer,Integer> cancelCount = new HashMap<>(); int size = values.size(); int solutions = 0; for ( int nIndex = 0 ; nIndex < size - 1 ; nIndex++ ) { int numerator = values.get(nIndex); // Must be proper fraction for ( int dIndex = nIndex + 1 ; dIndex < size ; dIndex++ ) { int denominator = values.get(dIndex); for ( int commonDigit : digitsInCommon(numerator, denominator) ) { int numRemoved = removeDigit(numerator, commonDigit); int denRemoved = removeDigit(denominator, commonDigit); if ( numerator * denRemoved == denominator * numRemoved ) { solutions++; cancelCount.merge(commonDigit, 1, (v1, v2) -> v1 + v2); if ( solutions <= 12 ) { System.out.printf(" When %d is removed, %d/%d = %d/%d%n", commonDigit, numerator, denominator, numRemoved, denRemoved); } } } } } System.out.printf("Number of fractions where cancellation is valid = %d.%n", solutions); List<Integer> sorted = new ArrayList<>(cancelCount.keySet()); Collections.sort(sorted); for ( int removed : sorted ) { System.out.printf(" The digit %d was removed %d times.%n", removed, cancelCount.get(removed)); } System.out.println(); }   private static int[] powers = new int[] {1, 10, 100, 1000, 10000, 100000};   // Remove the specified digit. private static int removeDigit(int n, int removed) { int m = 0; int pow = 0; while ( n > 0 ) { int r = n % 10; if ( r != removed ) { m = m + r*powers[pow]; pow++; } n /= 10; } return m; }   // Assumes no duplicate digits individually in n1 or n2 - part of task private static List<Integer> digitsInCommon(int n1, int n2) { int[] count = new int[10]; List<Integer> common = new ArrayList<>(); while ( n1 > 0 ) { int r = n1 % 10; count[r] += 1; n1 /= 10; } while ( n2 > 0 ) { int r = n2 % 10; if ( count[r] > 0 ) { common.add(r); } n2 /= 10; } return common; }   // No repeating digits, no digit is zero. private static boolean isValid(int num) { int[] count = new int[10]; while ( num > 0 ) { int r = num % 10; if ( r == 0 || count[r] == 1 ) { return false; } count[r] = 1; num /= 10; } return true; }   }  
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.
#Erlang
Erlang
#! /usr/bin/escript   -mode(native). -import(lists, [map/2, reverse/1]).   binary_to_ratio(B) -> {match, [_, Num, Den]} = re:run(B, "([0-9]+)/([0-9]+)"), {binary_to_integer(binary:part(B, Num)), binary_to_integer(binary:part(B, Den))}.   load(Program) -> map(fun binary_to_ratio/1, re:split(Program, "[ ]+")).   step(_, []) -> halt; step(N, [F|Fs]) -> {P, Q} = mulrat(F, {N, 1}), case Q of 1 -> P; _ -> step(N, Fs) end.   exec(K, N, Program) -> reverse(exec(K - 1, N, fun (_) -> true end, Program, [N])). exec(K, N, Pred, Program) -> reverse(exec(K - 1, N, Pred, Program, [N])).   exec(0, _, _, _, Steps) -> Steps; exec(K, N, Pred, Program, Steps) -> case step(N, Program) of halt -> Steps; M -> case Pred(M) of true -> exec(K - 1, M, Pred, Program, [M|Steps]); false -> exec(K, M, Pred, Program, Steps) end end.     is_pow2(N) -> N band (N - 1) =:= 0.   lowbit(N) -> lowbit(N, 0). lowbit(N, K) -> case N band 1 of 0 -> lowbit(N bsr 1, K + 1); 1 -> K end.   main(_) -> PrimeGen = load("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"), io:format("The first few states of the Fractran prime automaton are: ~p~n~n", [exec(20, 2, PrimeGen)]), io:format("The first few primes are: ~p~n", [tl(map(fun lowbit/1, exec(26, 2, fun is_pow2/1, PrimeGen)))]).     % rational multiplication   mulrat({A, B}, {C, D}) -> {P, Q} = {A*C, B*D}, G = gcd(P, Q), {P div G, Q div G}.   gcd(A, 0) -> A; gcd(A, B) -> gcd(B, A rem B).  
http://rosettacode.org/wiki/Function_definition
Function definition
A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract from showing how functions are created and values returned). Related task   Function prototype
#Applesoft_BASIC
Applesoft BASIC
10 DEF FN MULTIPLY(P) = P(P) * P(P+1) 20 P(1) = 611 : P(2) = 78 : PRINT FN MULTIPLY(1)
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.
#jq
jq
# input should be a non-negative integer def commatize: # "," is 44 def digits: tostring | explode | reverse; [foreach digits[] as $d (-1; .+1; (select(. > 0 and . % 3 == 0)|44), $d)] | reverse | implode  ;   def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;
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.
#Julia
Julia
using Memoize, Formatting   @memoize function sternbrocot(n) if n < 2 return n elseif iseven(n) return sternbrocot(div(n, 2)) else m = div(n - 1, 2) return sternbrocot(m) + sternbrocot(m + 1) end end   function fusclengths(N=100000000) println("sequence number : fusc value") maxlen = 0 for i in 0:N x = sternbrocot(i) if (len = length(string(x))) > maxlen println(lpad(format(i, commas=true), 15), " : ", format(x, commas=true)) maxlen = len end end end   println("The first 61 fusc numbers are: ", [sternbrocot(x) for x in 0:60]) fusclengths()  
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
#Haskell
Haskell
cof :: [Double] cof = [ 76.18009172947146 , -86.50532032941677 , 24.01409824083091 , -1.231739572450155 , 0.001208650973866179 , -0.000005395239384953 ]   ser :: Double ser = 1.000000000190015   gammaln :: Double -> Double gammaln xx = let tmp_ = (xx + 5.5) - (xx + 0.5) * log (xx + 5.5) ser_ = ser + sum (zipWith (/) cof [xx + 1 ..]) in -tmp_ + log (2.5066282746310005 * ser_ / xx)   main :: IO () main = mapM_ print $ gammaln <$> [0.1,0.2 .. 1.0]
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.
#Tcl
Tcl
package require Tcl 8.6   oo::class create GaltonBox { variable b w h n x y cnt step dropping   constructor {BALLS {NUMPEGS 5} {HEIGHT 24}} { set n $NUMPEGS set w [expr {$n*2 + 1}] set h $HEIGHT puts -nonewline "\033\[H\033\[J" set x [set y [lrepeat $BALLS 0]] set cnt 0 set step 0 set dropping 1   set b [lrepeat $h [lrepeat $w " "]] for {set i 0} {$i < $n} {incr i} { for {set j [expr {-$i}]} {$j <= $i} {incr j 2} { lset b [expr {2*$i+2}] [expr {$j+$w/2}] "*" } } }   method show {} { puts -nonewline "\033\[H" set oldrow {} foreach row $b { foreach char $row oldchar $oldrow { if {$char ne "*"} { puts -nonewline "$char " } elseif {$oldchar eq " "} { puts -nonewline "\033\[32m*\033\[m " } else { puts -nonewline "\033\[31m*\033\[m " } } set oldrow $row puts "" } }   method Move idx { set xx [lindex $x $idx] set yy [lindex $y $idx] set kill 0   if {$yy < 0} {return 0} if {$yy == $h-1} { lset y $idx -1 return 0 }   switch [lindex $b [incr yy] $xx] { "*" { incr xx [expr {2*int(2 * rand()) - 1}] if {[lindex $b [incr yy -1] $xx] ne " "} { set dropping 0 } } "o" { incr yy -1 set kill 1 } }   set c [lindex $b [lindex $y $idx] [lindex $x $idx]] lset b [lindex $y $idx] [lindex $x $idx] " " lset b $yy $xx $c if {$kill} { lset y $idx -1 } else { lset y $idx $yy } lset x $idx $xx return [expr {!$kill}] }   method step {} { set moving 0 for {set i 0} {$i < $cnt} {incr i} { set moving [expr {[my Move $i] || $moving}] } if {2 == [incr step] && $cnt < [llength $x] && $dropping} { set step 0 lset x $cnt [expr {$w / 2}] lset y $cnt 0 if {[lindex $b [lindex $y $cnt] [lindex $x $cnt]] ne " "} { return 0 } lset b [lindex $y $cnt] [lindex $x $cnt] "o" incr cnt } return [expr {($moving || $dropping)}] } }   GaltonBox create board 1024 {*}$argv while true { board show if {[board step]} {after 60} break }
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
#PL.2FM
PL/M
100H: /* FIND SOME GAPFUL NUMBERS: NUMBERS DIVISIBLE BY 10F + L WHERE F IS */ /* THE FIRST DIGIT AND L IS THE LAST DIGIT */ BDOS: PROCEDURE( FN, ARG ); /* CP/M BDOS SYSTEM CALL */ DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END BDOS; PR$CHAR: PROCEDURE( C ); DECLARE C BYTE; CALL BDOS( 2, C ); END; PR$STRING: PROCEDURE( S ); DECLARE S ADDRESS; CALL BDOS( 9, S ); END; PR$NL: PROCEDURE; CALL PR$CHAR( 0DH ); CALL PR$CHAR( 0AH ); END; PR$NUMBER: PROCEDURE( N ); DECLARE N ADDRESS; DECLARE V ADDRESS, N$STR( 6 ) BYTE, W BYTE; V = N; W = LAST( N$STR ); N$STR( W ) = '$'; N$STR( W := W - 1 ) = '0' + ( V MOD 10 ); DO WHILE( ( V := V / 10 ) > 0 ); N$STR( W := W - 1 ) = '0' + ( V MOD 10 ); END; CALL PR$STRING( .N$STR( W ) ); END PR$NUMBER; /* RETURNS TRUE IF N IS GAPFUL, FALSE OTHERWISE */ IS$GAPFUL: PROCEDURE( N )BYTE; DECLARE N ADDRESS; DECLARE F ADDRESS; F = N / 10; DO WHILE ( F > 9 ); F = F / 10; END; RETURN N MOD ( ( F * 10 ) + ( N MOD 10 ) ) = 0; END IS$GAPFUL; /* FIND THE FIRST 30 GAPFUL NUMBERS >= 100 */ CALL PR$STRING( .'FIRST 30 GAPFUL NUMBERS STARTING FROM 100:$' ); CALL PR$NL; DECLARE N ADDRESS, G$COUNT BYTE; G$COUNT = 0; N = 100; DO WHILE ( G$COUNT < 30 ); IF IS$GAPFUL( N ) THEN DO; /* HAVE A GAPFUL NUMBER */ G$COUNT = G$COUNT + 1; CALL PR$CHAR( ' ' ); CALL PR$NUMBER( N ); END; N = N + 1; END; CALL PR$NL;   EOF
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
#PARI.2FGP
PARI/GP
matsolve(A,B)
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
#Rust
Rust
use std::io; use std::io::BufRead;   fn parse_entry(l: &str) -> (i32, String) { let params: Vec<&str> = l.split(' ').collect();   let divisor = params[0].parse::<i32>().unwrap(); let word = params[1].to_string(); (divisor, word) }   fn main() { let stdin = io::stdin(); let mut lines = stdin.lock().lines().map(|l| l.unwrap());   let l = lines.next().unwrap(); let high = l.parse::<i32>().unwrap();   let mut entries = Vec::new(); for l in lines { if &l == "" { break } let entry = parse_entry(&l); entries.push(entry); }   for i in 1..(high + 1) { let mut line = String::new(); for &(divisor, ref word) in &entries { if i % divisor == 0 { line = line + &word; } } if line == "" { println!("{}", i); } else { println!("{}", line); } } }
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
#Scala
Scala
$ scala GeneralFizzBuzz.scala 20 3 Fizz 5 Buzz 7 Baxx ^D 1 2 Fizz 4 Buzz Fizz Baxx 8 Fizz Buzz 11 Fizz 13 Baxx FizzBuzz 16 17 Fizz 19 Buzz
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
#Logo
Logo
show map "char iseq 97 122
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
Generate lower case ASCII alphabet
Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code. During code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code: set alpha {a b c d e f g h i j k m n o p q r s t u v w x y z} Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Lua
Lua
function getAlphabet () local letters = {} for ascii = 97, 122 do table.insert(letters, string.char(ascii)) end return letters end   local alpha = getAlphabet() print(alpha[25] .. alpha[1] .. alpha[25])
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
#PHP
PHP
<?php echo "Hello world!\n"; ?>
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
#Ruby
Ruby
# This solution cheats and uses only one generator!   def powers(m) return enum_for(__method__, m) unless block_given? 0.step{|n| yield n**m} end   def squares_without_cubes return enum_for(__method__) unless block_given?   cubes = powers(3) c = cubes.next powers(2) do |s| c = cubes.next while c < s yield s unless c == s end end   p squares_without_cubes.take(30).drop(20) # p squares_without_cubes.lazy.drop(20).first(10) # Ruby 2.0+
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.
#F.23
F#
> let compose f g x = f (g x);;   val compose : ('a -> 'b) -> ('c -> 'a) -> 'c -> 'b
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.
#Factor
Factor
( scratchpad ) [ 2 * ] [ 1 + ] compose . [ 2 * 1 + ] ( scratchpad ) 4 [ 2 * ] [ 1 + ] compose call . 9
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
#jq
jq
# width and height define the outer dimensions; # len defines the trunk size; # scale defines the branch length relative to the trunk; def main(width; height; len; scale):   def PI: (1|atan)*4;   def precision(n): def pow(k): . as $in | reduce range(0;k) as $i (1; .*$in); if . < 0 then - (-. | precision(n)) else (10|pow(n)) as $power | (. * 10 * $power) | floor as $x | ($x % 10) as $r | ((if $r < 5 then $x else $x + 5 end) / 10 | floor) / $power end;   def p2: precision(2);   def tree(x; y; len; angle): if len < 1 then empty else (x + len * (angle|cos)) as $x2 | (y + len * (angle|sin)) as $y2 | (if len < 10 then 1 else 2 end) as $swidth | (if len < 10 then "blue" else "black" end) as $stroke | "<line x1='\(x|p2)' y1='\(y|p2)' x2='\($x2|p2)' y2='\($y2|p2)' style='stroke:\($stroke); stroke-width:\($swidth)'/>", tree($x2; $y2; len * scale; angle + PI / 5), tree($x2; $y2; len * scale; angle - PI / 5) end  ;   "<svg width='100%' height='100%' version='1.1' xmlns='http://www.w3.org/2000/svg'>", tree(width / 2; height; len; 3 * PI / 2), "</svg>" ;   main(1000; 1000; 400; 6/10)
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
#Julia
Julia
  const width = height = 1000.0 const trunklength = 400.0 const scalefactor = 0.6 const startingangle = 1.5 * pi const deltaangle = 0.2 * pi   function tree(fh, x, y, len, theta) if len >= 1.0 x2 = x + len * cos(theta) y2 = y + len * sin(theta) write(fh, "<line x1='$x' y1='$y' x2='$x2' y2='$y2' style='stroke:rgb(0,0,0);stroke-width:1'/>\n") tree(fh, x2, y2, len * scalefactor, theta + deltaangle) tree(fh, x2, y2, len * scalefactor, theta - deltaangle) end end   outsvg = open("tree.svg", "w") write(outsvg, """<?xml version='1.0' encoding='utf-8' standalone='no'?> <!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN' 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'> <svg width='100%%' height='100%%' version='1.1' xmlns='http://www.w3.org/2000/svg'>\n""")   tree(outsvg, 0.5 * width, height, trunklength, startingangle)   write(outsvg, "</svg>\n") # view file tree.svg in browser  
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.
#Julia
Julia
using Combinatorics   toi(set) = parse(Int, join(set, "")) drop1(c, set) = toi(filter(x -> x != c, set))   function anomalouscancellingfractions(numdigits) ret = Vector{Tuple{Int, Int, Int, Int, Int}}() for nset in permutations(1:9, numdigits), dset in permutations(1:9, numdigits) if nset < dset # only proper fractions for c in nset if c in dset # a common digit exists n, d, nn, dd = toi(nset), toi(dset), drop1(c, nset), drop1(c, dset) if n // d == nn // dd # anomalous cancellation push!(ret, (n, d, nn, dd, c)) end end end end end ret end   function testfractionreduction(maxdigits=5) for i in 2:maxdigits results = anomalouscancellingfractions(i) println("\nFor $i digits, there were ", length(results), " fractions with anomalous cancellation.") numcounts = zeros(Int, 9) for r in results numcounts[r[5]] += 1 end for (j, count) in enumerate(numcounts) count > 0 && println("The digit $j was crossed out $count times.") end println("Examples:") for j in 1:min(length(results), 12) r = results[j] println(r[1], "/", r[2], " = ", r[3], "/", r[4], " ($(r[5]) crossed out)") end end end   testfractionreduction()  
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.
#Factor
Factor
USING: io kernel math math.functions math.parser multiline prettyprint sequences splitting ; IN: rosetta-code.fractran   STRING: fractran-string 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 ;   : fractran-parse ( str -- seq ) " \n" split [ string>number ] map ;   : fractran-step ( seq n -- seq n'/f ) 2dup [ * integer? ] curry find nip dup [ * ] [ nip ] if ;   : fractran-run-full ( seq n -- ) [ dup ] [ dup . fractran-step ] while 2drop ;   : fractran-run-limited ( seq n steps -- ) [ dup pprint bl fractran-step ] times 2drop nl ;   : fractran-primes ( #primes seq n -- ) [ pick zero? ] [ dup 2 logn dup [ floor 1e-9 ~ ] [ 1. = not ] bi and [ dup 2 logn >integer pprint bl [ 1 - ] 2dip ] when fractran-step ] until 3drop nl ;   : main ( -- ) fractran-string fractran-parse 2 [ "First 20 numbers: " print 20 fractran-run-limited nl ] [ "First 20 primes: " print [ 20 ] 2dip fractran-primes ] 2bi ;   MAIN: main
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
#Argile
Argile
use std .: multiply <real a, real b> :. -> real {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.
#Kotlin
Kotlin
// Version 1.3.21   fun fusc(n: Int): IntArray { if (n <= 0) return intArrayOf() if (n == 1) return intArrayOf(0) val res = IntArray(n) res[1] = 1 for (i in 2 until n) { if (i % 2 == 0) { res[i] = res[i / 2] } else { res[i] = res[(i - 1) / 2] + res[(i + 1) / 2] } } return res }   fun fuscMaxLen(n: Int): List<Pair<Int, Int>> { var maxLen = -1 var maxFusc = -1 val f = fusc(n) val res = mutableListOf<Pair<Int, Int>>() for (i in 0 until n) { if (f[i] <= maxFusc) continue // avoid string conversion maxFusc = f[i] val len = f[i].toString().length if (len > maxLen) { res.add(Pair(i, f[i])) maxLen = len } } return res }   fun main() { println("The first 61 fusc numbers are:") println(fusc(61).asList()) println("\nThe fusc numbers whose length > any previous fusc number length are:") val res = fuscMaxLen(20_000_000) // examine first 20 million numbers say for (r in res) { System.out.printf("%,7d (index %,10d)\n", r.second, r.first) } }
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
#Icon_and_Unicon
Icon and Unicon
procedure main() every write(left(i := !10/10.0,5),gamma(.i)) end   procedure gamma(z) # Stirling's approximation return (2*&pi/z)^0.5 * (z/&e)^z 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.
#Wren
Wren
import "random" for Random import "/trait" for Reversed   var boxW = 41 // Galton box width. var boxH = 37 // Galton box height. var pinsBaseW = 19 // Pins triangle base. var nMaxBalls = 55 // Number of balls.   var centerH = pinsBaseW + (boxW - pinsBaseW * 2 + 1) / 2 - 1 var Rand = Random.new()   class Cell { static EMPTY { " " } static BALL { "o" } static WALL { "|" } static CORNER { "+" } static FLOOR { "-" } static PIN { "." } }   /* Galton box. Will be printed upside down. */ var Box = List.filled(boxH, null) for (i in 0...boxH) Box[i] = List.filled(boxW, Cell.EMPTY)   class Ball { construct new(x, y) { if (Box[x][y] != Cell.EMPTY) Fiber.abort("The cell at (x, y) is not empty.") Box[y][x] = Cell.BALL _x = x _y = y }   doStep() { if (_y <= 0) return // Reached the bottom of the box. var cell = Box[_y - 1][_x] if (cell == Cell.EMPTY) { Box[_y][_x] = Cell.EMPTY _y = _y - 1 Box[_y][_x] = Cell.BALL } else if (cell == Cell.PIN) { Box[_y][_x] = Cell.EMPTY _y = _y - 1 if (Box[_y][_x - 1] == Cell.EMPTY && Box[_y][_x + 1] == Cell.EMPTY) { _x = _x + Rand.int(2) * 2 - 1 Box[_y][_x] = Cell.BALL return } else if (Box[_y][_x - 1] == Cell.EMPTY){ _x = _x + 1 } else _x = _x - 1 Box[_y][_x] = Cell.BALL } else { // It's frozen - it always piles on other balls. } } }   var initializeBox = Fn.new { // Set ceiling and floor: Box[0][0] = Cell.CORNER Box[0][boxW - 1] = Cell.CORNER for (i in 1...boxW - 1) Box[0][i] = Cell.FLOOR for (i in 0...boxW) Box[boxH - 1][i] = Box[0][i]   // Set walls: for (r in 1...boxH - 1) { Box[r][0] = Cell.WALL Box[r][boxW - 1] = Cell.WALL }   // Set pins: for (nPins in 1..pinsBaseW) { for (pin in 0...nPins) { Box[boxH - 2 - nPins][centerH + 1 - nPins + pin * 2] = Cell.PIN } } }   var drawBox = Fn.new() { for (row in Reversed.new(Box, 1)) { for (c in row) System.write(c) System.print() } }   initializeBox.call() var balls = [] for (i in 0...nMaxBalls + boxH) { System.print("\nStep %(i):") if (i < nMaxBalls) balls.add(Ball.new(centerH, boxH - 2)) // Add ball. drawBox.call()   // Next step for the simulation. // Frozen balls are kept in balls list for simplicity for (b in balls) b.doStep() }
http://rosettacode.org/wiki/Gapful_numbers
Gapful numbers
Numbers   (positive integers expressed in base ten)   that are (evenly) divisible by the number formed by the first and last digit are known as   gapful numbers. Evenly divisible   means divisible with   no   remainder. All   one─   and two─digit   numbers have this property and are trivially excluded.   Only numbers   ≥ 100   will be considered for this Rosetta Code task. Example 187   is a   gapful   number because it is evenly divisible by the number   17   which is formed by the first and last decimal digits of   187. About   7.46%   of positive integers are   gapful. Task   Generate and show all sets of numbers (below) on one line (horizontally) with a title,   here on this page   Show the first   30   gapful numbers   Show the first   15   gapful numbers   ≥          1,000,000   Show the first   10   gapful numbers   ≥   1,000,000,000 Related tasks   Harshad or Niven series.   palindromic gapful numbers.   largest number divisible by its digits. Also see   The OEIS entry:   A108343 gapful numbers.   numbersaplenty gapful numbers
#PowerShell
PowerShell
function Get-FirstDigit { param ( [int] $Number ) [int]$Number.ToString().Substring(0,1) }   function Get-LastDigit { param ( [int] $Number ) $Number % 10 }   function Get-BookendNumber { param ( [Int] $Number ) 10 * (Get-FirstDigit $Number) + (Get-LastDigit $Number) }   function Test-Gapful { param ( [Int] $Number ) 100 -lt $Number -and 0 -eq $Number % (Get-BookendNumber $Number) }   function Find-Gapfuls { param ( [Int] $Start, [Int] $Count ) $result = @()   While ($result.Count -lt $Count) { If (Test-Gapful $Start) { $result += @($Start) } $Start += 1 } return $result }   function Search-Range { param ( [Int] $Start, [Int] $Count ) Write-Output "The first $Count gapful numbers >= $($Start):" Write-Output( (Find-Gapfuls $Start $Count) -join ",") Write-Output "" }   Search-Range 1 30 Search-Range 1000000 15 Search-Range 1000000000 10  
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
#Perl
Perl
use Math::Matrix; my $a = Math::Matrix->new([0,1,0], [0,0,1], [2,0,1]); my $b = Math::Matrix->new([1], [2], [4]); my $x = $a->concat($b)->solve; print $x;
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
#Sidef
Sidef
class FizzBuzz(schema=Hash(<3 Fizz 5 Buzz>...)) { method filter(this) { var fb = '' schema.sort_by {|k,_| k.to_i }.each { |pair| fb += (pair[0].to_i `divides` this ? pair[1] : '') } fb.len > 0 ? fb : this } }   func GeneralFizzBuzz(upto, schema) { var ping = FizzBuzz() if (nil != schema) { ping.schema = schema.to_hash } (1..upto).map {|i| ping.filter(i) } }   GeneralFizzBuzz(20, <3 Fizz 5 Buzz 7 Baxx>).each { .say }
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
#M2000_Interpreter
M2000 Interpreter
  \\ old style Basic, including a Binary.Or() function Module OldStyle { 10 LET A$="" 20 FOR I=ASC("A") TO ASC("Z") 30 LET A$=A$+CHR$(BINARY.OR(I, 32)) 40 NEXT I 50 PRINT A$ } CALL OldStyle  
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
#Maple
Maple
seq(StringTools:-Char(c), c = 97 .. 122);
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
#Picat
Picat
println("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
#Rust
Rust
use std::cmp::Ordering; use std::iter::Peekable;   fn powers(m: u32) -> impl Iterator<Item = u64> { (0u64..).map(move |x| x.pow(m)) }   fn noncubic_squares() -> impl Iterator<Item = u64> { NoncubicSquares { squares: powers(2).peekable(), cubes: powers(3).peekable(), } }   struct NoncubicSquares<T: Iterator<Item = u64>, U: Iterator<Item = u64>> { squares: Peekable<T>, cubes: Peekable<U>, }   impl<T: Iterator<Item = u64>, U: Iterator<Item = u64>> Iterator for NoncubicSquares<T, U> { type Item = u64; fn next(&mut self) -> Option<u64> { loop { match self.squares.peek()?.cmp(self.cubes.peek()?) { Ordering::Equal => self.squares.next(), Ordering::Greater => self.cubes.next(), Ordering::Less => return self.squares.next(), }; } } }   fn main() { noncubic_squares() .skip(20) .take(10) .for_each(|x| print!("{} ", x)); println!(); }
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.
#Fantom
Fantom
  class Compose { static |Obj -> Obj| compose (|Obj -> Obj| fn1, |Obj -> Obj| fn2) { return |Obj x -> Obj| { fn2 (fn1 (x)) } }   public static Void main () { double := |Int x -> Int| { 2 * x } |Int -> Int| quad := compose(double, double) echo ("Double 3 = ${double(3)}") echo ("Quadruple 3 = ${quad (3)}") } }  
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.
#Forth
Forth
: compose ( xt1 xt2 -- xt3 ) >r >r :noname r> compile, r> compile, postpone ; ;   ' 2* ' 1+ compose ( xt ) 3 swap execute . \ 7
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
#Kotlin
Kotlin
// version 1.1.2   import java.awt.Color import java.awt.Graphics import javax.swing.JFrame   class FractalTree : JFrame("Fractal Tree") { init { background = Color.black setBounds(100, 100, 800, 600) isResizable = false defaultCloseOperation = EXIT_ON_CLOSE }   private fun drawTree(g: Graphics, x1: Int, y1: Int, angle: Double, depth: Int) { if (depth == 0) return val x2 = x1 + (Math.cos(Math.toRadians(angle)) * depth * 10.0).toInt() val y2 = y1 + (Math.sin(Math.toRadians(angle)) * depth * 10.0).toInt() g.drawLine(x1, y1, x2, y2) drawTree(g, x2, y2, angle - 20, depth - 1) drawTree(g, x2, y2, angle + 20, depth - 1) }   override fun paint(g: Graphics) { g.color = Color.white drawTree(g, 400, 500, -90.0, 9) } }   fun main(args: Array<String>) { FractalTree().isVisible = true }
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.
#Kotlin
Kotlin
fun indexOf(n: Int, s: IntArray): Int { for (i_j in s.withIndex()) { if (n == i_j.value) { return i_j.index } } return -1 }   fun getDigits(n: Int, le: Int, digits: IntArray): Boolean { var mn = n var mle = le while (mn > 0) { val r = mn % 10 if (r == 0 || indexOf(r, digits) >= 0) { return false } mle-- digits[mle] = r mn /= 10 } return true }   val pows = intArrayOf(1, 10, 100, 1_000, 10_000)   fun removeDigit(digits: IntArray, le: Int, idx: Int): Int { var sum = 0 var pow = pows[le - 2] for (i in 0 until le) { if (i == idx) { continue } sum += digits[i] * pow pow /= 10 } return sum }   fun main() { val lims = listOf( Pair(12, 97), Pair(123, 986), Pair(1234, 9875), Pair(12345, 98764) ) val count = IntArray(5) var omitted = arrayOf<Array<Int>>() for (i in 0 until 5) { var array = arrayOf<Int>() for (j in 0 until 10) { array += 0 } omitted += array } for (i_lim in lims.withIndex()) { val i = i_lim.index val lim = i_lim.value   val nDigits = IntArray(i + 2) val dDigits = IntArray(i + 2) val blank = IntArray(i + 2) { 0 } for (n in lim.first..lim.second) { blank.copyInto(nDigits) val nOk = getDigits(n, i + 2, nDigits) if (!nOk) { continue } for (d in n + 1..lim.second + 1) { blank.copyInto(dDigits) val dOk = getDigits(d, i + 2, dDigits) if (!dOk) { continue } for (nix_digit in nDigits.withIndex()) { val dix = indexOf(nix_digit.value, dDigits) if (dix >= 0) { val rn = removeDigit(nDigits, i + 2, nix_digit.index) val rd = removeDigit(dDigits, i + 2, dix) if (n.toDouble() / d.toDouble() == rn.toDouble() / rd.toDouble()) { count[i]++ omitted[i][nix_digit.value]++ if (count[i] <= 12) { println("$n/$d = $rn/$rd by omitting ${nix_digit.value}'s") } } } } } } println() }   for (i in 2..5) { println("There are ${count[i - 2]} $i-digit fractions of which:") for (j in 1..9) { if (omitted[i - 2][j] == 0) { continue } println("%6d have %d's omitted".format(omitted[i - 2][j], j)) } println() } }
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.
#Fermat
Fermat
Func FT( arr, n, m ) =  ;{executes John H. Conway's FRACTRAN language for a program stored in [arr], an}  ;{input integer stored in n, for a maximum of m steps}  ;{To allow the program to run indefinitely, give it negative or noninteger m} exec:=1; {boolean to track whether the program needs to halt} len:=Cols[arr]; {length of the input program} while exec=1 and m<>0 do m:-;  !!n; {output the memory} i:=1; {index variable} exec:=0; while i<=len and exec=0 do nf:=n*arr[i]; if Denom(nf) = 1 then n:=nf; {did we find an instruction to execute?} exec:=1 fi; i:+; od; od; .;   ;{Here is the program to run} [arr]:=[( 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 )];   FT( [arr], 2, 20 );
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
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI */ /* program functMul.s */ /* Constantes */ .equ STDOUT, 1 .equ WRITE, 4 .equ EXIT, 1   /***********************/ /* Initialized data */ /***********************/ .data szRetourLigne: .asciz "\n" szMessResult: .ascii "Resultat : " @ message result sMessValeur: .fill 12, 1, ' ' .asciz "\n" /*********************** /* No Initialized data */ /***********************/ .bss   .text .global main main: push {fp,lr} /* save 2 registers */   @ function multiply mov r0,#8 mov r1,#50 bl multiply @ call function ldr r1,iAdrsMessValeur bl conversion10S @ call function with 2 parameter (r0,r1) ldr r0,iAdrszMessResult bl affichageMess @ display message   mov r0, #0 @ return code   100: /* end of program */ mov r7, #EXIT @ request to exit program swi 0 @ perform the system call iAdrsMessValeur: .int sMessValeur iAdrszMessResult: .int szMessResult /******************************************************************/ /* Function multiply */ /******************************************************************/ /* r0 contains value 1 */ /* r1 contains value 2 */ /* r0 return résult */ multiply: mul r0,r1,r0 bx lr /* return function */   /******************************************************************/ /* display text with size calculation */ /******************************************************************/ /* r0 contains the address of the message */ affichageMess: push {fp,lr} /* save registres */ push {r0,r1,r2,r7} /* save others registers */ mov r2,#0 /* counter length */ 1: /* loop length calculation */ ldrb r1,[r0,r2] /* read octet start position + index */ cmp r1,#0 /* if 0 its over */ addne r2,r2,#1 /* else add 1 in the length */ bne 1b /* and loop */ /* so here r2 contains the length of the message */ mov r1,r0 /* address message in r1 */ mov r0,#STDOUT /* code to write to the standard output Linux */ mov r7, #WRITE /* code call system "write" */ swi #0 /* call systeme */ pop {r0,r1,r2,r7} /* restaur others registers */ pop {fp,lr} /* restaur des 2 registres */ bx lr /* return */     /***************************************************/ /* conversion register in string décimal signed */ /***************************************************/ /* r0 contains the register */ /* r1 contains address of conversion area */ conversion10S: push {fp,lr} /* save registers frame and return */ push {r0-r5} /* save other registers */ mov r2,r1 /* early storage area */ mov r5,#'+' /* default sign is + */ cmp r0,#0 /* négatif number ? */ movlt r5,#'-' /* yes sign is - */ mvnlt r0,r0 /* and inverse in positive value */ addlt r0,#1 mov r4,#10 /* area length */ 1: /* conversion loop */ bl divisionpar10 /* division */ add r1,#48 /* add 48 at remainder for conversion ascii */ strb r1,[r2,r4] /* store byte area r5 + position r4 */ sub r4,r4,#1 /* previous position */ cmp r0,#0 bne 1b /* loop if quotient not equal zéro */ strb r5,[r2,r4] /* store sign at current position */ subs r4,r4,#1 /* previous position */ blt 100f /* if r4 < 0 end */ /* else complete area with space */ mov r3,#' ' /* character space */ 2: strb r3,[r2,r4] /* store byte */ subs r4,r4,#1 /* previous position */ bge 2b /* loop if r4 greather or equal zero */ 100: /* standard end of function */ pop {r0-r5} /*restaur others registers */ pop {fp,lr} /* restaur des 2 registers frame et return */ bx lr     /***************************************************/ /* division par 10 signé */ /* Thanks to http://thinkingeek.com/arm-assembler-raspberry-pi/* /* and http://www.hackersdelight.org/ */ /***************************************************/ /* r0 contient le dividende */ /* r0 retourne le quotient */ /* r1 retourne le reste */ divisionpar10: /* r0 contains the argument to be divided by 10 */ push {r2-r4} /* save autres registres */ mov r4,r0 ldr r3, .Ls_magic_number_10 /* r1 <- magic_number */ smull r1, r2, r3, r0 /* r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0) */ mov r2, r2, ASR #2 /* r2 <- r2 >> 2 */ mov r1, r0, LSR #31 /* r1 <- r0 >> 31 */ add r0, r2, r1 /* r0 <- r2 + r1 */ add r2,r0,r0, lsl #2 /* r2 <- r0 * 5 */ sub r1,r4,r2, lsl #1 /* r1 <- r4 - (r2 * 2) = r4 - (r0 * 10) */ pop {r2-r4} bx lr /* leave function */ .align 4 .Ls_magic_number_10: .word 0x66666667        
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.
#Lua
Lua
function fusc(n) n = math.floor(n) if n == 0 or n == 1 then return n elseif n % 2 == 0 then return fusc(n / 2) else return fusc((n - 1) / 2) + fusc((n + 1) / 2) end end   function numLen(n) local sum = 1 while n > 9 do n = math.floor(n / 10) sum = sum + 1 end return sum end   function printLargeFuscs(limit) print("Printing all largest Fusc numbers up to " .. limit) print("Index-------Value") local maxLen = 1 for i=0,limit do local f = fusc(i) local le = numLen(f) if le > maxLen then maxLen = le print(string.format("%5d%12d", i, f)) end end end   function main() print("Index-------Value") for i=0,60 do print(string.format("%5d%12d", i, fusc(i))) end printLargeFuscs(math.pow(2, 31) - 1) end   main()
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
#J
J
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.
#XPL0
XPL0
include c:\cxpl\codes; \intrinsic code declarations define Balls = 80; \maximum number of balls int Bx(Balls), By(Balls), \character cell coordinates of each ball W, I, J, Peg, Dir; [W:= Peek($40, $4A); \get screen width in characters Clear; CrLf(6); CrLf(6); for Peg:= 1 to 10 do \draw pegs [for I:= 1 to 12-Peg do ChOut(6,^ ); \space over to first peg for I:= 1 to Peg do [ChOut(6,^.); ChOut(6,^ )]; CrLf(6); ]; for J:= 0 to 12-1 do \draw slots [for I:= 0 to 12-1 do [ChOut(6,^:); ChOut(6,^ )]; CrLf(6); ]; for I:= 0 to 23-1 do ChOut(6,^.); \draw bottom for I:= 0 to Balls-1 do \make source of balls at top [Bx(I):= 11; By(I):= 1]; Attrib($C); \make balls bright red repeat \balls away! ... for I:= 0 to Balls-1 do \for all the balls ... [Cursor(Bx(I), By(I)); ChOut(6, ^ ); \erase ball's initial position if Peek($B800, (Bx(I)+(By(I)+1)*W)*2) = ^ \is ball above empty location? then By(I):= By(I)+1 \yes: fall straight down else [Dir:= Ran(3)-1; \no: randomly fall right or left if Peek($B800, (Bx(I)+Dir+(By(I)+1)*W)*2) = ^ then [Bx(I):= Bx(I)+Dir; By(I):= By(I)+1]; ]; Cursor(Bx(I), By(I)); ChOut(6, ^o); \draw ball at its new position ]; Sound(0, 3, 1); \delay about 1/6 second until KeyHit; \continue until a key is struck ]
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.
#Yabasic
Yabasic
bola$ = "0000ff" obst$ = "000000"   maxBalls = 10 cx = 1 cy = 2 dim Balls(maxBalls, 2)   open window 600,600 window origin "ct"   maxh = peek("winheight")   REM Draw the pins:   FOR row = 1 TO 7 FOR col = 1 TO row FILL circle 40*col - 20*row, 40*row+80, 10 NEXT col NEXT row   REM Animate tick = 0 bolas = 0 color 0,0,255   do if (bolas < maxBalls) then if tick = 3 then tick = 0 bolas = bolas + 1 Balls(bolas, cx) = 20 Balls(bolas, cy) = 10 end if tick = tick + 1 end if for n = 1 to bolas if Balls(n, cy) then color$ = right$(getbit$(Balls(n,cx),Balls(n,cy) + 10,Balls(n,cx),Balls(n,cy) + 10),6) if (color$ = bola$) or (Balls(n,cy) >= maxh - 15) then Balls(n,cy) = 0 break end if clear fill circle Balls(n,cx),Balls(n,cy),10 if color$ = obst$ then if int(ran(2)) then Balls(n,cx) = Balls(n,cx) - 20 else Balls(n,cx) = Balls(n,cx) + 20 end if end if Balls(n,cy) = Balls(n,cy)+10 fill circle Balls(n,cx),Balls(n,cy),10 wait .001 else wait .001 end if next n loop  
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
#PureBasic
PureBasic
Procedure.b isGapNum(n.i) n1.i=n%10 n2.i=Val(Left(Str(n),1)) If n%(n2*10+n1)=0 ProcedureReturn #True Else ProcedureReturn #False EndIf EndProcedure   Procedure PutGapNum(start.i,rep.i,lfi.i=10) n.i=start While rep If isGapNum(n) Print(Str(n)+" ") rep-1 If rep%lfi=0 : PrintN("") : EndIf EndIf n+1 Wend EndProcedure   OpenConsole() PrintN("First 30 gapful numbers ≥ 100:") PutGapNum(100,30) PrintN(~"\nFirst 15 gapful numbers ≥ 1,000,000:") PutGapNum(1000000,15,5) PrintN(~"\nFirst 10 gapful numbers ≥ 1,000,000,000:") PutGapNum(1000000000,10,5) Input()
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
#Phix
Phix
with javascript_semantics function gauss_eliminate(sequence a, b) {a, b} = deep_copy({a,b}) integer n = length(b) atom tmp for col=1 to n do integer m = col atom mx = a[m][m] for i=col+1 to n do tmp = abs(a[i][col]) if tmp>mx then {m,mx} = {i,tmp} end if end for if col!=m then {a[col],a[m]} = {a[m],a[col]} {b[col],b[m]} = {b[m],b[col]} end if for i=col+1 to n do tmp = a[i][col]/a[col][col] for j=col+1 to n do a[i][j] -= tmp*a[col][j] end for a[i][col] = 0 b[i] -= tmp*b[col] end for end for sequence x = repeat(0,n) for col=n to 1 by -1 do tmp = b[col] for j=n to col+1 by -1 do tmp -= x[j]*a[col][j] end for x[col] = tmp/a[col][col] end for return x end function constant a = {{1.00, 0.00, 0.00, 0.00, 0.00, 0.00}, {1.00, 0.63, 0.39, 0.25, 0.16, 0.10}, {1.00, 1.26, 1.58, 1.98, 2.49, 3.13}, {1.00, 1.88, 3.55, 6.70, 12.62, 23.80}, {1.00, 2.51, 6.32, 15.88, 39.90, 100.28}, {1.00, 3.14, 9.87, 31.01, 97.41, 306.02}}, b = {-0.01, 0.61, 0.91, 0.99, 0.60, 0.02} pp(gauss_eliminate(a, b))
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
#Swift
Swift
import Foundation   print("Input max number: ", terminator: "")   guard let maxN = Int(readLine() ?? "0"), maxN > 0 else { fatalError("Please input a number greater than 0") }   func getFactor() -> (Int, String) { print("Enter a factor and phrase: ", terminator: "")   guard let factor1Input = readLine() else { fatalError("Please enter a factor") }   let sep1 = factor1Input.components(separatedBy: " ") let phrase = sep1.dropFirst().joined(separator: " ")   guard let factor = Int(sep1[0]), factor != 0, !phrase.isEmpty else { fatalError("Please enter a factor and phrase") }   return (factor, phrase) }   let (factor1, phrase1) = getFactor() let (factor2, phrase2) = getFactor() let (factor3, phrase3) = getFactor()   for i in 1...maxN { let factors = [ (i.isMultiple(of: factor1), phrase1), (i.isMultiple(of: factor2), phrase2), (i.isMultiple(of: factor3), phrase3) ].filter({ $0.0 }).map({ $0.1 }).joined()   print("\(factors.isEmpty ? String(i) : factors)") }
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
#Tailspin
Tailspin
  def input: {N: 110"1", words: [ { mod: 3"1", word: 'Fizz' }, { mod: 5"1", word: 'Buzz'}, {mod:7"1", word: 'Baxx'}]};   templates sayWords def i: $; templates maybeSay def word: $.word; $i mod $.mod -> \(<=0"1"> $word !\) ! end maybeSay $input.words... -> maybeSay ! end sayWords   [ 1"1"..$input.N -> '$->sayWords;' ] -> \[i](<=''> $i ! <> $ !\) -> '$; ' -> !OUT::write  
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
#Mathcad
Mathcad
  -- user-defined function that returns the ASCII code for string character ch. code(ch):=str2vec(ch)[0   -- number of lower-case ASCII characters N:=26   -- range variable covering the relative indices of the lower-case characters within the ASCII character set (0 = 'a', 25 = 'z'). k:=0..N-1   -- ASCII code for letter 'a' (a=97 ). a:=code("a")   -- iterate over k to produce a vector of lower case ASCII character codes lcCodes[k:=k+a   -- convert vector to string of ordered ASCII lower-case characters. lcString:=vec2str(lcCodes) lcString="abcdefghijklmnopqrstuvwxyz"   -- Characters are indexable within the string; for example: substr(lcString,3,1)="d"  
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
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
start = 97; lowerCaseLetters = Table[FromCharacterCode[start + i], {i, 0, 25}]
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
#PicoLisp
PicoLisp
(prinl "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
#Scala
Scala
object Generators { def main(args: Array[String]): Unit = { def squares(n:Int=0):Stream[Int]=(n*n) #:: squares(n+1) def cubes(n:Int=0):Stream[Int]=(n*n*n) #:: cubes(n+1)   def filtered(s:Stream[Int], c:Stream[Int]):Stream[Int]={ if(s.head>c.head) filtered(s, c.tail) else if(s.head<c.head) Stream.cons(s.head, filtered(s.tail, c)) else filtered(s.tail, c) }   filtered(squares(), cubes()) drop 20 take 10 print } }
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.
#Fortran
Fortran
  module functions_module implicit none private ! all by default public :: f,g   contains   pure function f(x) implicit none real, intent(in) :: x real :: f f = sin(x) end function f   pure function g(x) implicit none real, intent(in) :: x real :: g g = cos(x) end function g   end module functions_module   module compose_module implicit none private ! all by default public :: compose   interface pure function f(x) implicit none real, intent(in) :: x real :: f end function f   pure function g(x) implicit none real, intent(in) :: x real :: g end function g end interface   contains   impure function compose(x, fi, gi) implicit none real, intent(in) :: x procedure(f), optional :: fi procedure(g), optional :: gi real :: compose   procedure (f), pointer, save :: fpi => null() procedure (g), pointer, save :: gpi => null()   if(present(fi) .and. present(gi))then fpi => fi gpi => gi compose = 0 return endif   if(.not. associated(fpi)) error stop "fpi" if(.not. associated(gpi)) error stop "gpi"   compose = fpi(gpi(x))   contains   end function compose   end module compose_module   program test_compose use functions_module use compose_module implicit none write(*,*) "prepare compose:", compose(0.0, f,g) write(*,*) "run compose:", compose(0.5) end program test_compose  
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
#Lambdatalk
Lambdatalk
  1) defining the function tree:   {def tree {lambda {:e // last branch length :s // trunks length :k // ratio between two following branches :a // rotate left :b} // rotate right {if {< :s :e} then else M:s T:a {tree :e {* :k :s} :k :a :b} T-{+ :a :b} {tree :e {* :k :s} :k :a :b} T:b M-:s }}}   2) Calling this function generates a sequence of commands mooving a pen: • Tθ rotates the drawing direction "θ" degrees from the previous one • and Md draws a segment "d" pixels in this direction.   {def T {tree 1 190 {/ 2 3} 15 45}}   and produces 40995 words beginning with:   M190 T15 M126.66666666666666 T15 M84.44444444444443 T15 M56.29629629629628 T15 M37.53086419753085 T15 M25.020576131687235 T15 M16.680384087791488 T15 M11.120256058527659 T15 M7.413504039018439 T15 M4.942336026012292 T15 M3.2948906840081946 ...   3) These words are sent to a the turtle lambdatalk primitive which is a graphic device translating the sequence of Md and Tθ into a sequence of SVG points x0 y0 x1 y1 ... xn yn which will feed the points attribute of a polyline SVG element:   {svg {@ width="580px" height="580px" style="box-shadow:0 0 8px #000;"} {polyline {@ points="{turtle 230 570 180 {T}}" fill="transparent" stroke="#fff" stroke-width="1" }}}   This is an abstract of the output:   <svg width="580px" height="580px" style="box-shadow:0 0 8px #000;"> <polyline points="230 580 230 380 195 251 151 174 109 132 75 113 49 106 32 106 21 109 ... ... 413 286 324 286 230 380 230 580 " fill="transparent" stroke="#888" stroke-width="1"> </polyline> </svg>   The complete ouput can be seen displayed in http://lambdaway.free.fr/lambdawalks/?view=fractal_tree  
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.
#Lua
Lua
function indexOf(haystack, needle) for idx,straw in pairs(haystack) do if straw == needle then return idx end end   return -1 end   function getDigits(n, le, digits) while n > 0 do local r = n % 10 if r == 0 or indexOf(digits, r) > 0 then return false end le = le - 1 digits[le + 1] = r n = math.floor(n / 10) end return true end   function removeDigit(digits, le, idx) local pows = { 1, 10, 100, 1000, 10000 }   local sum = 0 local pow = pows[le - 2 + 1] for i = 1, le do if i ~= idx then sum = sum + digits[i] * pow pow = math.floor(pow / 10) end end return sum end   function main() local lims = { {12, 97}, {123, 986}, {1234, 9875}, {12345, 98764} } local count = { 0, 0, 0, 0, 0 } local omitted = { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, }   for i,_ in pairs(lims) do local nDigits = {} local dDigits = {} for j = 1, i + 2 - 1 do nDigits[j] = -1 dDigits[j] = -1 end   for n = lims[i][1], lims[i][2] do for j,_ in pairs(nDigits) do nDigits[j] = 0 end local nOk = getDigits(n, i + 2 - 1, nDigits) if nOk then for d = n + 1, lims[i][2] + 1 do for j,_ in pairs(dDigits) do dDigits[j] = 0 end local dOk = getDigits(d, i + 2 - 1, dDigits) if dOk then for nix,_ in pairs(nDigits) do local digit = nDigits[nix] local dix = indexOf(dDigits, digit) if dix >= 0 then local rn = removeDigit(nDigits, i + 2 - 1, nix) local rd = removeDigit(dDigits, i + 2 - 1, dix) if (n / d) == (rn / rd) then count[i] = count[i] + 1 omitted[i][digit + 1] = omitted[i][digit + 1] + 1 if count[i] <= 12 then print(string.format("%d/%d = %d/%d by omitting %d's", n, d, rn, rd, digit)) end end end end end end end end   print() end   for i = 2, 5 do print("There are "..count[i - 2 + 1].." "..i.."-digit fractions of which:") for j = 1, 9 do if omitted[i - 2 + 1][j + 1] > 0 then print(string.format("%6d have %d's omitted", omitted[i - 2 + 1][j + 1], j)) end end print() end end   main()
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.
#Fortran
Fortran
C:\Nicky\RosettaCode\FRACTRAN\FRACTRAN.for(6) : Warning: This name has not been given an explicit type. [M] INTEGER P(M),Q(M)!The terms of the fractions.