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/Evolutionary_algorithm
Evolutionary algorithm
Starting with: The target string: "METHINKS IT IS LIKE A WEASEL". An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). A fitness function that computes the ‘closeness’ of its argument to the target string. A mutate function that given a string and a mutation rate returns a copy of the string, with some characters probably mutated. While the parent is not yet the target: copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Assess the fitness of the parent and all the copies to the target and make the most fit string the new parent, discarding the others. repeat until the parent converges, (hopefully), to the target. See also   Wikipedia entry:   Weasel algorithm.   Wikipedia entry:   Evolutionary algorithm. Note: to aid comparison, try and ensure the variables and functions mentioned in the task description appear in solutions A cursory examination of a few of the solutions reveals that the instructions have not been followed rigorously in some solutions. Specifically, While the parent is not yet the target: copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Note that some of the the solutions given retain characters in the mutated string that are correct in the target string. However, the instruction above does not state to retain any of the characters while performing the mutation. Although some may believe to do so is implied from the use of "converges" (:* repeat until the parent converges, (hopefully), to the target. Strictly speaking, the new parent should be selected from the new pool of mutations, and then the new parent used to generate the next set of mutations with parent characters getting retained only by not being mutated. It then becomes possible that the new set of mutations has no member that is fitter than the parent! As illustration of this error, the code for 8th has the following remark. Create a new string based on the TOS, changing randomly any characters which don't already match the target: NOTE: this has been changed, the 8th version is completely random now Clearly, this algo will be applying the mutation function only to the parent characters that don't match to the target characters! To ensure that the new parent is never less fit than the prior parent, both the parent and all of the latest mutations are subjected to the fitness test to select the next parent.
#Racket
Racket
  #lang racket   (define alphabet " ABCDEFGHIJKLMNOPQRSTUVWXYZ") (define (randch) (string-ref alphabet (random 27)))   (define (fitness s1 s2) (for/sum ([c1 (in-string s1)] [c2 (in-string s2)]) (if (eq? c1 c2) 1 0)))   (define (mutate s P) (define r (string-copy s)) (for ([i (in-range (string-length r))] #:when (<= (random) P)) (string-set! r i (randch))) r)   (define (evolution target C P) (let loop ([parent (mutate target 1.0)] [n 0])  ;; (printf "~a: ~a\n" n parent) (if (equal? parent target) n (let cloop ([children (for/list ([i (in-range C)]) (mutate parent P))] [best #f] [fit -1]) (if (null? children) (loop best (add1 n)) (let ([f (fitness target (car children))]) (if (> f fit) (cloop (cdr children) (car children) f) (cloop (cdr children) best fit))))))))   ;; Some random experiment using all of this (define (try-run C P) (define ns (for/list ([i 10]) (evolution "METHINKS IT IS LIKE A WEASEL" C P))) (printf "~s Average generation: ~s\n" C (/ (apply + 0.0 ns) (length ns))) (printf "~s Total strings: ~s\n" C (for/sum ([n ns]) (* n 50)))) (for ([C (in-range 10 501 10)]) (try-run C 0.001))  
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion). The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition: Fn = Fn+2 - Fn+1, if n<0 support for negative     n     in the solution is optional. Related tasks   Fibonacci n-step number sequences‎   Leonardo numbers References   Wikipedia, Fibonacci number   Wikipedia, Lucas number   MathWorld, Fibonacci Number   Some identities for r-Fibonacci numbers   OEIS Fibonacci numbers   OEIS Lucas numbers
#Pascal
Pascal
function fib(n: integer):longInt; const Sqrt5 = sqrt(5.0); C1 = ln((Sqrt5+1.0)*0.5);//ln( 1.618..) //C2 = ln((1.0-Sqrt5)*0.5);//ln(-0.618 )) tsetsetse C2 = ln((Sqrt5-1.0)*0.5);//ln(+0.618 )) begin IF n>0 then begin IF odd(n) then fib := round((exp(C1*n) + exp(C2*n) )/Sqrt5) else fib := round((exp(C1*n) - exp(C2*n) )/Sqrt5) end else Fibdirekt := 0 end;
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterative or recursive. Support for trapping negative   n   errors is optional. Related task   Primorial numbers
#Eiffel
Eiffel
  note description: "recursive and iterative factorial example of a positive integer."   class FACTORIAL_EXAMPLE   create make   feature -- Initialization   make local n: NATURAL do n := 5 print ("%NFactorial of " + n.out + " = ") print (recursive_factorial (n)) end   feature -- Access   recursive_factorial (n: NATURAL): NATURAL -- factorial of 'n' do if n = 0 then Result := 1 else Result := n * recursive_factorial (n - 1) end end   iterative_factorial (n: NATURAL): NATURAL -- factorial of 'n' local v: like n do from Result := 1 v := n until v <= 1 loop Result := Result * v v := v - 1 end end   end  
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) The   FizzBuzz   problem was presented as the lowest level of comprehension required to illustrate adequacy. Also see   (a blog)   dont-overthink-fizzbuzz   (a blog)   fizzbuzz-the-programmers-stairway-to-heaven
#Z80_Assembly
Z80 Assembly
foreach n in ([1..100]) { if(n % 3 == 0) print("Fizz"); if(not (n%5)) "Buzz".print(); if(n%3 and n%5) print(n); println(); }
http://rosettacode.org/wiki/Execute_Brain****
Execute Brain****
Execute Brain**** is an implementation of Brainf***. Other implementations of Brainf***. RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages. Below are links to each of the versions of RCBF. An implementation need only properly implement the following instructions: Command Description > Move the pointer to the right < Move the pointer to the left + Increment the memory cell under the pointer - Decrement the memory cell under the pointer . Output the character signified by the cell at the pointer , Input a character and store it in the cell at the pointer [ Jump past the matching ] if the cell under the pointer is 0 ] Jump back to the matching [ if the cell under the pointer is nonzero Any cell size is allowed,   EOF   (End-O-File)   support is optional, as is whether you have bounded or unbounded memory.
#Python
Python
[ stack ] is switch.arg ( --> [ )   [ switch.arg put ] is switch ( x --> )   [ switch.arg release ] is otherwise ( --> )   [ switch.arg share != iff ]else[ done otherwise ]'[ do ]done[ ] is case ( x --> )   [ dip tuck unrot poke swap ] is poketape ( [ n n --> [ n )   [ 1+ over size over = if [ dip [ 0 join ] ] ] is stepright ( [ n --> [ n )   [ dup 0 = iff [ 0 rot join swap ] else [ 1 - ] ] is stepleft ( [ n --> [ n )   [ 2dup peek 1 + poketape ] is increment ( [ n --> [ n )   [ 2dup peek 1 - poketape ] is decrement ( [ n --> [ n )   [ 2dup peek emit ] is print ( [ n --> [ n )   [ temp take dup $ "" = iff 0 else behead swap temp put poketape ] is getchar ( [ n --> [ n )   [ 2dup peek 0 = ] is zero ( [ n --> [ n b )   [ temp put $ "" swap witheach [ switch [ char > case [ $ "stepright " join ] char < case [ $ "stepleft " join ] char + case [ $ "increment " join ] char - case [ $ "decrement " join ] char . case [ $ "print " join ] char , case [ $ "getchar " join ] char [ case [ $ "[ zero if done " join ] char ] case [ $ "zero until ] " join ] otherwise ( ignore ) ] ] 0 nested 0 rot quackery temp release 2drop ] is brainf*** ( $ $ --> )
http://rosettacode.org/wiki/Evolutionary_algorithm
Evolutionary algorithm
Starting with: The target string: "METHINKS IT IS LIKE A WEASEL". An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). A fitness function that computes the ‘closeness’ of its argument to the target string. A mutate function that given a string and a mutation rate returns a copy of the string, with some characters probably mutated. While the parent is not yet the target: copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Assess the fitness of the parent and all the copies to the target and make the most fit string the new parent, discarding the others. repeat until the parent converges, (hopefully), to the target. See also   Wikipedia entry:   Weasel algorithm.   Wikipedia entry:   Evolutionary algorithm. Note: to aid comparison, try and ensure the variables and functions mentioned in the task description appear in solutions A cursory examination of a few of the solutions reveals that the instructions have not been followed rigorously in some solutions. Specifically, While the parent is not yet the target: copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Note that some of the the solutions given retain characters in the mutated string that are correct in the target string. However, the instruction above does not state to retain any of the characters while performing the mutation. Although some may believe to do so is implied from the use of "converges" (:* repeat until the parent converges, (hopefully), to the target. Strictly speaking, the new parent should be selected from the new pool of mutations, and then the new parent used to generate the next set of mutations with parent characters getting retained only by not being mutated. It then becomes possible that the new set of mutations has no member that is fitter than the parent! As illustration of this error, the code for 8th has the following remark. Create a new string based on the TOS, changing randomly any characters which don't already match the target: NOTE: this has been changed, the 8th version is completely random now Clearly, this algo will be applying the mutation function only to the parent characters that don't match to the target characters! To ensure that the new parent is never less fit than the prior parent, both the parent and all of the latest mutations are subjected to the fitness test to select the next parent.
#Raku
Raku
constant target = "METHINKS IT IS LIKE A WEASEL"; constant mutate_chance = .08; constant @alphabet = flat 'A'..'Z',' '; constant C = 100;   sub mutate { [~] (rand < mutate_chance ?? @alphabet.pick !! $_ for $^string.comb) } sub fitness { [+] $^string.comb Zeq target.comb }   loop ( my $parent = @alphabet.roll(target.chars).join; $parent ne target; $parent = max :by(&fitness), mutate($parent) xx C ) { printf "%6d: '%s'\n", $++, $parent }
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion). The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition: Fn = Fn+2 - Fn+1, if n<0 support for negative     n     in the solution is optional. Related tasks   Fibonacci n-step number sequences‎   Leonardo numbers References   Wikipedia, Fibonacci number   Wikipedia, Lucas number   MathWorld, Fibonacci Number   Some identities for r-Fibonacci numbers   OEIS Fibonacci numbers   OEIS Lucas numbers
#Perl
Perl
sub fib_iter { my $n = shift; use bigint try => "GMP,Pari"; my ($v2,$v1) = (-1,1); ($v2,$v1) = ($v1,$v2+$v1) for 0..$n; $v1; }
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterative or recursive. Support for trapping negative   n   errors is optional. Related task   Primorial numbers
#Ela
Ela
fact = fact' 1L where fact' acc 0 = acc fact' acc n = fact' (n * acc) (n - 1)
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) The   FizzBuzz   problem was presented as the lowest level of comprehension required to illustrate adequacy. Also see   (a blog)   dont-overthink-fizzbuzz   (a blog)   fizzbuzz-the-programmers-stairway-to-heaven
#zkl
zkl
foreach n in ([1..100]) { if(n % 3 == 0) print("Fizz"); if(not (n%5)) "Buzz".print(); if(n%3 and n%5) print(n); println(); }
http://rosettacode.org/wiki/Execute_Brain****
Execute Brain****
Execute Brain**** is an implementation of Brainf***. Other implementations of Brainf***. RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages. Below are links to each of the versions of RCBF. An implementation need only properly implement the following instructions: Command Description > Move the pointer to the right < Move the pointer to the left + Increment the memory cell under the pointer - Decrement the memory cell under the pointer . Output the character signified by the cell at the pointer , Input a character and store it in the cell at the pointer [ Jump past the matching ] if the cell under the pointer is 0 ] Jump back to the matching [ if the cell under the pointer is nonzero Any cell size is allowed,   EOF   (End-O-File)   support is optional, as is whether you have bounded or unbounded memory.
#Quackery
Quackery
[ stack ] is switch.arg ( --> [ )   [ switch.arg put ] is switch ( x --> )   [ switch.arg release ] is otherwise ( --> )   [ switch.arg share != iff ]else[ done otherwise ]'[ do ]done[ ] is case ( x --> )   [ dip tuck unrot poke swap ] is poketape ( [ n n --> [ n )   [ 1+ over size over = if [ dip [ 0 join ] ] ] is stepright ( [ n --> [ n )   [ dup 0 = iff [ 0 rot join swap ] else [ 1 - ] ] is stepleft ( [ n --> [ n )   [ 2dup peek 1 + poketape ] is increment ( [ n --> [ n )   [ 2dup peek 1 - poketape ] is decrement ( [ n --> [ n )   [ 2dup peek emit ] is print ( [ n --> [ n )   [ temp take dup $ "" = iff 0 else behead swap temp put poketape ] is getchar ( [ n --> [ n )   [ 2dup peek 0 = ] is zero ( [ n --> [ n b )   [ temp put $ "" swap witheach [ switch [ char > case [ $ "stepright " join ] char < case [ $ "stepleft " join ] char + case [ $ "increment " join ] char - case [ $ "decrement " join ] char . case [ $ "print " join ] char , case [ $ "getchar " join ] char [ case [ $ "[ zero if done " join ] char ] case [ $ "zero until ] " join ] otherwise ( ignore ) ] ] 0 nested 0 rot quackery temp release 2drop ] is brainf*** ( $ $ --> )
http://rosettacode.org/wiki/Evolutionary_algorithm
Evolutionary algorithm
Starting with: The target string: "METHINKS IT IS LIKE A WEASEL". An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). A fitness function that computes the ‘closeness’ of its argument to the target string. A mutate function that given a string and a mutation rate returns a copy of the string, with some characters probably mutated. While the parent is not yet the target: copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Assess the fitness of the parent and all the copies to the target and make the most fit string the new parent, discarding the others. repeat until the parent converges, (hopefully), to the target. See also   Wikipedia entry:   Weasel algorithm.   Wikipedia entry:   Evolutionary algorithm. Note: to aid comparison, try and ensure the variables and functions mentioned in the task description appear in solutions A cursory examination of a few of the solutions reveals that the instructions have not been followed rigorously in some solutions. Specifically, While the parent is not yet the target: copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Note that some of the the solutions given retain characters in the mutated string that are correct in the target string. However, the instruction above does not state to retain any of the characters while performing the mutation. Although some may believe to do so is implied from the use of "converges" (:* repeat until the parent converges, (hopefully), to the target. Strictly speaking, the new parent should be selected from the new pool of mutations, and then the new parent used to generate the next set of mutations with parent characters getting retained only by not being mutated. It then becomes possible that the new set of mutations has no member that is fitter than the parent! As illustration of this error, the code for 8th has the following remark. Create a new string based on the TOS, changing randomly any characters which don't already match the target: NOTE: this has been changed, the 8th version is completely random now Clearly, this algo will be applying the mutation function only to the parent characters that don't match to the target characters! To ensure that the new parent is never less fit than the prior parent, both the parent and all of the latest mutations are subjected to the fitness test to select the next parent.
#Red
Red
Red[]   ; allowed characters alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ " ; target string target: "METHINKS IT IS LIKE A WEASEL" ; parameter controlling the number of children C: 10 ; parameter controlling the evolution rate RATE: 0.05   ; compute closeness of 'string' to 'target' fitness: function [string] [ sum: 0   repeat i length? string [ if not-equal? pick string i pick target i [ sum: sum + 1 ] ]   sum ]   ; return copy of 'string' with mutations, frequency based on given 'rate' mutate: function [string rate] [ result: copy string   repeat i length? result [ if rate > random 1.0 [ poke result i random/only alphabet ] ]   result ]   ; create initial random parent parent: "" repeat i length? target [ append parent random/only alphabet ]   ; main loop, displaying progress while [not-equal? parent target] [ print parent children: copy []   repeat i C [ append children mutate parent RATE ] sort/compare children function [a b] [lesser? fitness a fitness b]   parent: pick children 1 ] print parent  
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion). The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition: Fn = Fn+2 - Fn+1, if n<0 support for negative     n     in the solution is optional. Related tasks   Fibonacci n-step number sequences‎   Leonardo numbers References   Wikipedia, Fibonacci number   Wikipedia, Lucas number   MathWorld, Fibonacci Number   Some identities for r-Fibonacci numbers   OEIS Fibonacci numbers   OEIS Lucas numbers
#Phix
Phix
function fibonacci(integer n) -- iterative, works for -ve numbers atom a=0, b=1 if n=0 then return 0 end if if abs(n)>=79 then ?9/0 end if -- inaccuracies creep in above 78 for i=1 to abs(n)-1 do {a,b} = {b,a+b} end for if n<0 and remainder(n,2)=0 then return -b end if return b end function for i=0 to 28 do if i then puts(1,", ") end if printf(1,"%d", fibonacci(i)) end for puts(1,"\n")
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterative or recursive. Support for trapping negative   n   errors is optional. Related task   Primorial numbers
#Elixir
Elixir
defmodule Factorial do # Simple recursive function def fac(0), do: 1 def fac(n) when n > 0, do: n * fac(n - 1)   # Tail recursive function def fac_tail(0), do: 1 def fac_tail(n), do: fac_tail(n, 1) def fac_tail(1, acc), do: acc def fac_tail(n, acc) when n > 1, do: fac_tail(n - 1, acc * n)   # Tail recursive function with default parameter def fac_default(n, acc \\ 1) def fac_default(0, acc), do: acc def fac_default(n, acc) when n > 0, do: fac_default(n - 1, acc * n)   # Using Enumeration features def fac_reduce(0), do: 1 def fac_reduce(n) when n > 0, do: Enum.reduce(1..n, 1, &*/2)   # Using Enumeration features with pipe operator def fac_pipe(0), do: 1 def fac_pipe(n) when n > 0, do: 1..n |> Enum.reduce(1, &*/2)   end
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) The   FizzBuzz   problem was presented as the lowest level of comprehension required to illustrate adequacy. Also see   (a blog)   dont-overthink-fizzbuzz   (a blog)   fizzbuzz-the-programmers-stairway-to-heaven
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 DEF FN m(a,b)=a-INT (a/b)*b 20 FOR a=1 TO 100 30 LET o$="" 40 IF FN m(a,3)=0 THEN LET o$="Fizz" 50 IF FN m(a,5)=0 THEN LET o$=o$+"Buzz" 60 IF o$="" THEN LET o$=STR$ a 70 PRINT o$ 80 NEXT a
http://rosettacode.org/wiki/Execute_Brain****
Execute Brain****
Execute Brain**** is an implementation of Brainf***. Other implementations of Brainf***. RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages. Below are links to each of the versions of RCBF. An implementation need only properly implement the following instructions: Command Description > Move the pointer to the right < Move the pointer to the left + Increment the memory cell under the pointer - Decrement the memory cell under the pointer . Output the character signified by the cell at the pointer , Input a character and store it in the cell at the pointer [ Jump past the matching ] if the cell under the pointer is 0 ] Jump back to the matching [ if the cell under the pointer is nonzero Any cell size is allowed,   EOF   (End-O-File)   support is optional, as is whether you have bounded or unbounded memory.
#Racket
Racket
  #lang planet dyoo/bf ++++++[>++++++++++++<-]>. >++++++++++[>++++++++++<-]>+. +++++++..+++.>++++[>+++++++++++<-]>. <+++[>----<-]>.<<<<<+++[>+++++<-]>. >>.+++.------.--------.>>+.  
http://rosettacode.org/wiki/Evolutionary_algorithm
Evolutionary algorithm
Starting with: The target string: "METHINKS IT IS LIKE A WEASEL". An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). A fitness function that computes the ‘closeness’ of its argument to the target string. A mutate function that given a string and a mutation rate returns a copy of the string, with some characters probably mutated. While the parent is not yet the target: copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Assess the fitness of the parent and all the copies to the target and make the most fit string the new parent, discarding the others. repeat until the parent converges, (hopefully), to the target. See also   Wikipedia entry:   Weasel algorithm.   Wikipedia entry:   Evolutionary algorithm. Note: to aid comparison, try and ensure the variables and functions mentioned in the task description appear in solutions A cursory examination of a few of the solutions reveals that the instructions have not been followed rigorously in some solutions. Specifically, While the parent is not yet the target: copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Note that some of the the solutions given retain characters in the mutated string that are correct in the target string. However, the instruction above does not state to retain any of the characters while performing the mutation. Although some may believe to do so is implied from the use of "converges" (:* repeat until the parent converges, (hopefully), to the target. Strictly speaking, the new parent should be selected from the new pool of mutations, and then the new parent used to generate the next set of mutations with parent characters getting retained only by not being mutated. It then becomes possible that the new set of mutations has no member that is fitter than the parent! As illustration of this error, the code for 8th has the following remark. Create a new string based on the TOS, changing randomly any characters which don't already match the target: NOTE: this has been changed, the 8th version is completely random now Clearly, this algo will be applying the mutation function only to the parent characters that don't match to the target characters! To ensure that the new parent is never less fit than the prior parent, both the parent and all of the latest mutations are subjected to the fitness test to select the next parent.
#REXX
REXX
/*REXX program demonstrates an evolutionary algorithm (by using mutation). */ parse arg children MR seed . /*get optional arguments from the C.L. */ if children=='' | children=="," then children=10 /*# children produced each generation. */ if MR =='' | MR =="," then MR= "4%" /*the character Mutation Rate each gen.*/ if right(MR,1)=='%' then MR= strip(MR,,"%")/100 /*expressed as a percent? Then adjust.*/ if seed\=='' then call random ,,seed /*SEED allow the runs to be repeatable.*/ abc = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ '  ; Labc= length(abc) target= 'METHINKS IT IS LIKE A WEASEL' ; Ltar= length(target) parent= mutate( left('', Ltar), 1) /*gen rand string,same length as target*/ say center('target string', Ltar, "─") 'children' "mutationRate" say target center(children, 8) center((MR*100/1)'%', 12); say say center('new string' ,Ltar, "─") "closeness" 'generation'   do gen=0 until parent==target; close= fitness(parent) almost= parent do children; child= mutate(parent,MR) _= fitness(child); if _<=close then iterate close= _; almost= child say almost right(close, 9) right(gen, 10) end /*children*/ parent= almost end /*gen*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ fitness: parse arg x; $=0; do k=1 for Ltar; $= $+(substr(x,k,1)==substr(target,k,1)); end return $ /*──────────────────────────────────────────────────────────────────────────────────────*/ mutate: parse arg x,rate; $= /*set X to 1st argument, RATE to 2nd.*/ do j=1 for Ltar; r= random(1, 100000) /*REXX's max for RANDOM*/ if .00001*r<=rate then $= $ || substr(abc, r//Labc+1, 1) else $= $ || substr(x , j , 1) end /*j*/ return $
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion). The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition: Fn = Fn+2 - Fn+1, if n<0 support for negative     n     in the solution is optional. Related tasks   Fibonacci n-step number sequences‎   Leonardo numbers References   Wikipedia, Fibonacci number   Wikipedia, Lucas number   MathWorld, Fibonacci Number   Some identities for r-Fibonacci numbers   OEIS Fibonacci numbers   OEIS Lucas numbers
#Phixmonti
Phixmonti
def Fibonacci dup 0 < if "Invalid argument: " print else 1 1 rot 2 - for drop over over + endfor endif enddef   10 Fibonacci pstack print nl -10 Fibonacci print
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterative or recursive. Support for trapping negative   n   errors is optional. Related task   Primorial numbers
#Elm
Elm
  factorial : Int -> Int factorial n = if n < 1 then 1 else n*factorial(n-1)  
http://rosettacode.org/wiki/Execute_Brain****
Execute Brain****
Execute Brain**** is an implementation of Brainf***. Other implementations of Brainf***. RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages. Below are links to each of the versions of RCBF. An implementation need only properly implement the following instructions: Command Description > Move the pointer to the right < Move the pointer to the left + Increment the memory cell under the pointer - Decrement the memory cell under the pointer . Output the character signified by the cell at the pointer , Input a character and store it in the cell at the pointer [ Jump past the matching ] if the cell under the pointer is 0 ] Jump back to the matching [ if the cell under the pointer is nonzero Any cell size is allowed,   EOF   (End-O-File)   support is optional, as is whether you have bounded or unbounded memory.
#Raku
Raku
  rebol [Title: "Brainfuck interpreter"]   tape: make object! [ pos: 1 data: [0] inc: does [ data/:pos: data/:pos + 1 ] dec: does [ data/:pos: data/:pos - 1 ] advance: does [ pos: pos + 1 if (length? data) <= pos [ append data 0 ] ] devance: does [ if pos > 1 [ pos: pos - 1 ] ] get: does [ data/:pos ] ]   brainfuck: make object! [ data: string! code: "" init: func [instr] [ self/data: instr ] bracket-map: func [text] [ leftstack: [] bm: make map! [] pc: 1 for i 1 (length? text) 1 [ c: text/:i if not find "+-<>[].," c [ continue ] if c == #"[" [ append leftstack pc ] if c == #"]" & ((length? leftstack) > 0) [ left: last leftstack take/last leftstack append bm reduce [left pc] append bm reduce [pc left] ] append code c pc: pc + 1 ] return bm ] run: function [] [ pc: 0 tp: make tape [] bm: bracket-map self/data while [pc <= (length? code)] [ switch/default code/:pc [ #"+" [tp/inc] #"-" [tp/dec] #">" [tp/advance] #"<" [tp/devance] #"[" [if tp/get == 0 [ pc: bm/:pc ]] #"]" [if tp/get != 0 [ pc: bm/:pc ]] #"." [prin to-string to-char tp/get] ] [] pc: pc + 1 ] print newline ] ]   bf: make brainfuck [] bf/init input bf/run  
http://rosettacode.org/wiki/Evolutionary_algorithm
Evolutionary algorithm
Starting with: The target string: "METHINKS IT IS LIKE A WEASEL". An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). A fitness function that computes the ‘closeness’ of its argument to the target string. A mutate function that given a string and a mutation rate returns a copy of the string, with some characters probably mutated. While the parent is not yet the target: copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Assess the fitness of the parent and all the copies to the target and make the most fit string the new parent, discarding the others. repeat until the parent converges, (hopefully), to the target. See also   Wikipedia entry:   Weasel algorithm.   Wikipedia entry:   Evolutionary algorithm. Note: to aid comparison, try and ensure the variables and functions mentioned in the task description appear in solutions A cursory examination of a few of the solutions reveals that the instructions have not been followed rigorously in some solutions. Specifically, While the parent is not yet the target: copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Note that some of the the solutions given retain characters in the mutated string that are correct in the target string. However, the instruction above does not state to retain any of the characters while performing the mutation. Although some may believe to do so is implied from the use of "converges" (:* repeat until the parent converges, (hopefully), to the target. Strictly speaking, the new parent should be selected from the new pool of mutations, and then the new parent used to generate the next set of mutations with parent characters getting retained only by not being mutated. It then becomes possible that the new set of mutations has no member that is fitter than the parent! As illustration of this error, the code for 8th has the following remark. Create a new string based on the TOS, changing randomly any characters which don't already match the target: NOTE: this has been changed, the 8th version is completely random now Clearly, this algo will be applying the mutation function only to the parent characters that don't match to the target characters! To ensure that the new parent is never less fit than the prior parent, both the parent and all of the latest mutations are subjected to the fitness test to select the next parent.
#Ring
Ring
  # Project : Evolutionary algorithm   target = "METHINKS IT IS LIKE A WEASEL" parent = "IU RFSGJABGOLYWF XSMFXNIABKT" num = 0 mutationrate = 0.5 children = len(target) child = list(children) while parent != target bestfitness = 0 bestindex = 0 for index = 1 to children child[index] = mutate(parent, mutationrate) fitness = fitness(target, child[index]) if fitness > bestfitness bestfitness = fitness bestindex = index ok next if bestindex > 0 parent = child[bestindex] num = num + 1 see "" + num + ": " + parent + nl ok end   func fitness(text, ref) f = 0 for i = 1 to len(text) if substr(text, i, 1) = substr(ref, i, 1) f = f + 1 ok next return (f / len(text))   func mutate(text, rate) rnd = randomf() if rate > rnd c = 63+random(27) if c = 64 c = 32 ok rnd2 = random(len(text)) if rnd2 > 0 text[rnd2] = char(c) ok ok return text   func randomf() decimals(10) str = "0." for i = 1 to 10 nr = random(9) str = str + string(nr) next return number(str)  
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion). The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition: Fn = Fn+2 - Fn+1, if n<0 support for negative     n     in the solution is optional. Related tasks   Fibonacci n-step number sequences‎   Leonardo numbers References   Wikipedia, Fibonacci number   Wikipedia, Lucas number   MathWorld, Fibonacci Number   Some identities for r-Fibonacci numbers   OEIS Fibonacci numbers   OEIS Lucas numbers
#PHP
PHP
function fibIter($n) { if ($n < 2) { return $n; } $fibPrev = 0; $fib = 1; foreach (range(1, $n-1) as $i) { list($fibPrev, $fib) = array($fib, $fib + $fibPrev); } return $fib; }
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterative or recursive. Support for trapping negative   n   errors is optional. Related task   Primorial numbers
#Emacs_Lisp
Emacs Lisp
  ;; Functional (most elegant and best suited to Lisp dialects): (defun fact (n) "Return the factorial of integer N, which require to be positive or 0." ;; Elisp won't do any type checking automatically, so ;; good practice would be doing that ourselves: (if (not (and (integerp n) (>= n 0))) (error "Function fact (N): Not a natural number or 0: %S" n)) ;; But the actual code is very short: (apply '* (number-sequence 1 n))) ;; (For N = 0, number-sequence returns the empty list, resp. nil, ;; and the * function works with zero arguments, returning 1.)  
http://rosettacode.org/wiki/Execute_Brain****
Execute Brain****
Execute Brain**** is an implementation of Brainf***. Other implementations of Brainf***. RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages. Below are links to each of the versions of RCBF. An implementation need only properly implement the following instructions: Command Description > Move the pointer to the right < Move the pointer to the left + Increment the memory cell under the pointer - Decrement the memory cell under the pointer . Output the character signified by the cell at the pointer , Input a character and store it in the cell at the pointer [ Jump past the matching ] if the cell under the pointer is 0 ] Jump back to the matching [ if the cell under the pointer is nonzero Any cell size is allowed,   EOF   (End-O-File)   support is optional, as is whether you have bounded or unbounded memory.
#Rebol
Rebol
  rebol [Title: "Brainfuck interpreter"]   tape: make object! [ pos: 1 data: [0] inc: does [ data/:pos: data/:pos + 1 ] dec: does [ data/:pos: data/:pos - 1 ] advance: does [ pos: pos + 1 if (length? data) <= pos [ append data 0 ] ] devance: does [ if pos > 1 [ pos: pos - 1 ] ] get: does [ data/:pos ] ]   brainfuck: make object! [ data: string! code: "" init: func [instr] [ self/data: instr ] bracket-map: func [text] [ leftstack: [] bm: make map! [] pc: 1 for i 1 (length? text) 1 [ c: text/:i if not find "+-<>[].," c [ continue ] if c == #"[" [ append leftstack pc ] if c == #"]" & ((length? leftstack) > 0) [ left: last leftstack take/last leftstack append bm reduce [left pc] append bm reduce [pc left] ] append code c pc: pc + 1 ] return bm ] run: function [] [ pc: 0 tp: make tape [] bm: bracket-map self/data while [pc <= (length? code)] [ switch/default code/:pc [ #"+" [tp/inc] #"-" [tp/dec] #">" [tp/advance] #"<" [tp/devance] #"[" [if tp/get == 0 [ pc: bm/:pc ]] #"]" [if tp/get != 0 [ pc: bm/:pc ]] #"." [prin to-string to-char tp/get] ] [] pc: pc + 1 ] print newline ] ]   bf: make brainfuck [] bf/init input bf/run  
http://rosettacode.org/wiki/Evolutionary_algorithm
Evolutionary algorithm
Starting with: The target string: "METHINKS IT IS LIKE A WEASEL". An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). A fitness function that computes the ‘closeness’ of its argument to the target string. A mutate function that given a string and a mutation rate returns a copy of the string, with some characters probably mutated. While the parent is not yet the target: copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Assess the fitness of the parent and all the copies to the target and make the most fit string the new parent, discarding the others. repeat until the parent converges, (hopefully), to the target. See also   Wikipedia entry:   Weasel algorithm.   Wikipedia entry:   Evolutionary algorithm. Note: to aid comparison, try and ensure the variables and functions mentioned in the task description appear in solutions A cursory examination of a few of the solutions reveals that the instructions have not been followed rigorously in some solutions. Specifically, While the parent is not yet the target: copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Note that some of the the solutions given retain characters in the mutated string that are correct in the target string. However, the instruction above does not state to retain any of the characters while performing the mutation. Although some may believe to do so is implied from the use of "converges" (:* repeat until the parent converges, (hopefully), to the target. Strictly speaking, the new parent should be selected from the new pool of mutations, and then the new parent used to generate the next set of mutations with parent characters getting retained only by not being mutated. It then becomes possible that the new set of mutations has no member that is fitter than the parent! As illustration of this error, the code for 8th has the following remark. Create a new string based on the TOS, changing randomly any characters which don't already match the target: NOTE: this has been changed, the 8th version is completely random now Clearly, this algo will be applying the mutation function only to the parent characters that don't match to the target characters! To ensure that the new parent is never less fit than the prior parent, both the parent and all of the latest mutations are subjected to the fitness test to select the next parent.
#Ruby
Ruby
@target = "METHINKS IT IS LIKE A WEASEL" Charset = [" ", *"A".."Z"] COPIES = 100   def random_char; Charset.sample end   def fitness(candidate) sum = 0 candidate.chars.zip(@target.chars) {|x,y| sum += (x[0].ord - y[0].ord).abs} 100.0 * Math.exp(Float(sum) / -10.0) end   def mutation_rate(candidate) 1.0 - Math.exp( -(100.0 - fitness(candidate)) / 400.0) end   def mutate(parent, rate) parent.each_char.collect {|ch| rand <= rate ? random_char : ch}.join end   def log(iteration, rate, parent) puts "%4d %.2f %5.1f %s" % [iteration, rate, fitness(parent), parent] end   iteration = 0 parent = Array.new(@target.length) {random_char}.join prev = ""   while parent != @target iteration += 1 rate = mutation_rate(parent) if prev != parent log(iteration, rate, parent) prev = parent end copies = [parent] + Array.new(COPIES) {mutate(parent, rate)} parent = copies.max_by {|c| fitness(c)} end log(iteration, rate, parent)
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion). The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition: Fn = Fn+2 - Fn+1, if n<0 support for negative     n     in the solution is optional. Related tasks   Fibonacci n-step number sequences‎   Leonardo numbers References   Wikipedia, Fibonacci number   Wikipedia, Lucas number   MathWorld, Fibonacci Number   Some identities for r-Fibonacci numbers   OEIS Fibonacci numbers   OEIS Lucas numbers
#Picat
Picat
go => println([fib_fun(I) : I in 1..10]), F1=fib_fun(2**10), println(f1=F1), nl.   table fib_fun(0) = 0. fib_fun(1) = 1. fib_fun(N) = fib_fun(N-1) + fib_fun(N-2).
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterative or recursive. Support for trapping negative   n   errors is optional. Related task   Primorial numbers
#embedded_C_for_AVR_MCU
embedded C for AVR MCU
long factorial(int n) { long result = 1; do { result *= n; while(--n); return result; }
http://rosettacode.org/wiki/Execute_Brain****
Execute Brain****
Execute Brain**** is an implementation of Brainf***. Other implementations of Brainf***. RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages. Below are links to each of the versions of RCBF. An implementation need only properly implement the following instructions: Command Description > Move the pointer to the right < Move the pointer to the left + Increment the memory cell under the pointer - Decrement the memory cell under the pointer . Output the character signified by the cell at the pointer , Input a character and store it in the cell at the pointer [ Jump past the matching ] if the cell under the pointer is 0 ] Jump back to the matching [ if the cell under the pointer is nonzero Any cell size is allowed,   EOF   (End-O-File)   support is optional, as is whether you have bounded or unbounded memory.
#REXX
REXX
/*REXX program implements the Brainf*ck (self─censored) language. */ @.=0 /*initialize the infinite "tape". */ p =0 /*the "tape" cell pointer. */ ! =0 /* ! is the instruction pointer (IP).*/ parse arg $ /*allow user to specify a BrainF*ck pgm*/ /* ┌──◄── No program? Then use default;*/ if $='' then $=, /* ↓ it displays: Hello, World! */ "++++++++++ initialize cell #0 to 10; then loop: ", "[ > +++++++ add 7 to cell #1; final result: 70 ", " > ++++++++++ add 10 to cell #2; final result: 100 ", " > +++ add 3 to cell #3; final result 30 ", " > + add 1 to cell #4; final result 10 ", " <<<< - ] decrement cell #0 ", "> ++ . display 'H' which is ASCII 72 (decimal) ", "> + . display 'e' which is ASCII 101 (decimal) ", "+++++++ .. display 'll' which is ASCII 108 (decimal) {2}", "+++ . display 'o' which is ASCII 111 (decimal) ", "> ++ . display ' ' which is ASCII 32 (decimal) ", "<< +++++++++++++++ . display 'W' which is ASCII 87 (decimal) ", "> . display 'o' which is ASCII 111 (decimal) ", "+++ . display 'r' which is ASCII 114 (decimal) ", "------ . display 'l' which is ASCII 108 (decimal) ", "-------- . display 'd' which is ASCII 100 (decimal) ", "> + . display '!' which is ASCII 33 (decimal) " /* [↑] note the Brainf*ck comments.*/ do !=1 while  !\==0 &  !<=length($) /*keep executing BF as long as IP ¬ 0*/ parse var $ =(!) x +1 /*obtain a Brainf*ck instruction (x),*/ /*···it's the same as x=substr($,!,1) */ select /*examine the current instruction. */ when x=='+' then @[email protected] + 1 /*increment the "tape" cell by 1 */ when x=='-' then @[email protected] - 1 /*decrement " " " " " */ when x=='>' then p= p + 1 /*increment " instruction ptr " " */ when x=='<' then p= p - 1 /*decrement " " " " " */ when x=='[' then != forward() /*go forward to ]+1 if @.P = 0. */ when x==']' then !=backward() /* " backward " [+1 " " ¬ " */ when x== . then call charout , d2c(@.p) /*display a "tape" cell to terminal. */ when x==',' then do; say 'input a value:'; parse pull @.p; end otherwise iterate end /*select*/ end /*forever*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ forward: if @.p\==0 then return !; c=1 /*C: ◄─── is the [ nested counter.*/ do k=!+1 to length($);  ?=substr($, k, 1) if ?=='[' then do; c=c+1; iterate; end if ?==']' then do; c=c-1; if c==0 then leave; end end /*k*/ return k /*──────────────────────────────────────────────────────────────────────────────────────*/ backward: if @.p==0 then return !; c=1 /*C: ◄─── is the ] nested counter.*/ do k=!-1 to 1 by -1;  ?=substr($, k, 1) if ?==']' then do; c=c+1; iterate; end if ?=='[' then do; c=c-1; if c==0 then return k+1; end end /*k*/ return k
http://rosettacode.org/wiki/Evolutionary_algorithm
Evolutionary algorithm
Starting with: The target string: "METHINKS IT IS LIKE A WEASEL". An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). A fitness function that computes the ‘closeness’ of its argument to the target string. A mutate function that given a string and a mutation rate returns a copy of the string, with some characters probably mutated. While the parent is not yet the target: copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Assess the fitness of the parent and all the copies to the target and make the most fit string the new parent, discarding the others. repeat until the parent converges, (hopefully), to the target. See also   Wikipedia entry:   Weasel algorithm.   Wikipedia entry:   Evolutionary algorithm. Note: to aid comparison, try and ensure the variables and functions mentioned in the task description appear in solutions A cursory examination of a few of the solutions reveals that the instructions have not been followed rigorously in some solutions. Specifically, While the parent is not yet the target: copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Note that some of the the solutions given retain characters in the mutated string that are correct in the target string. However, the instruction above does not state to retain any of the characters while performing the mutation. Although some may believe to do so is implied from the use of "converges" (:* repeat until the parent converges, (hopefully), to the target. Strictly speaking, the new parent should be selected from the new pool of mutations, and then the new parent used to generate the next set of mutations with parent characters getting retained only by not being mutated. It then becomes possible that the new set of mutations has no member that is fitter than the parent! As illustration of this error, the code for 8th has the following remark. Create a new string based on the TOS, changing randomly any characters which don't already match the target: NOTE: this has been changed, the 8th version is completely random now Clearly, this algo will be applying the mutation function only to the parent characters that don't match to the target characters! To ensure that the new parent is never less fit than the prior parent, both the parent and all of the latest mutations are subjected to the fitness test to select the next parent.
#Rust
Rust
//! Author : Thibault Barbie //! //! A simple evolutionary algorithm written in Rust.   extern crate rand;   use rand::Rng;   fn main() { let target = "METHINKS IT IS LIKE A WEASEL"; let copies = 100; let mutation_rate = 20; // 1/20 = 0.05 = 5%   let mut rng = rand::weak_rng();   // Generate first sentence, mutating each character let start = mutate(&mut rng, target, 1); // 1/1 = 1 = 100%   println!("{}", target); println!("{}", start);   evolve(&mut rng, target, start, copies, mutation_rate); }   /// Evolution algorithm /// /// Evolves `parent` to match `target`. Returns the number of evolutions performed. fn evolve<R: Rng>( rng: &mut R, target: &str, mut parent: String, copies: usize, mutation_rate: u32, ) -> usize { let mut counter = 0; let mut parent_fitness = target.len() + 1;   loop { counter += 1;   let (best_fitness, best_sentence) = (0..copies) .map(|_| { // Copy and mutate a new sentence. let sentence = mutate(rng, &parent, mutation_rate); // Find the fitness of the new mutation (fitness(target, &sentence), sentence) }) .min_by_key(|&(f, _)| f) // find the closest mutation to the target .unwrap(); // fails if `copies == 0`   // If the best mutation of this generation is better than `parent` then "the fittest // survives" and the next parent becomes the best of this generation. if best_fitness < parent_fitness { parent = best_sentence; parent_fitness = best_fitness; println!( "{} : generation {} with fitness {}", parent, counter, best_fitness );   if best_fitness == 0 { return counter; } } } }   /// Computes the fitness of a sentence against a target string, returning the number of /// incorrect characters. fn fitness(target: &str, sentence: &str) -> usize { sentence .chars() .zip(target.chars()) .filter(|&(c1, c2)| c1 != c2) .count() }   /// Mutation algorithm. /// /// It mutates each character of a string, according to a `mutation_rate`. fn mutate<R: Rng>(rng: &mut R, sentence: &str, mutation_rate: u32) -> String { let maybe_mutate = |c| { if rng.gen_weighted_bool(mutation_rate) { random_char(rng) } else { c } }; sentence.chars().map(maybe_mutate).collect() }   /// Generates a random letter or space. fn random_char<R: Rng>(rng: &mut R) -> char { // Returns a value in the range [A, Z] + an extra slot for the space character. (The `u8` // values could be cast to larger integers for a better chance of the RNG hitting the proper // range). match rng.gen_range(b'A', b'Z' + 2) { c if c == b'Z' + 1 => ' ', // the `char` after 'Z' c => c as char, } }
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion). The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition: Fn = Fn+2 - Fn+1, if n<0 support for negative     n     in the solution is optional. Related tasks   Fibonacci n-step number sequences‎   Leonardo numbers References   Wikipedia, Fibonacci number   Wikipedia, Lucas number   MathWorld, Fibonacci Number   Some identities for r-Fibonacci numbers   OEIS Fibonacci numbers   OEIS Lucas numbers
#PicoLisp
PicoLisp
(de fibo (N) (if (>= 2 N) 1 (+ (fibo (dec N)) (fibo (- N 2))) ) )
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterative or recursive. Support for trapping negative   n   errors is optional. Related task   Primorial numbers
#Erlang
Erlang
lists:foldl(fun(X,Y) -> X*Y end, 1, lists:seq(1,N)).
http://rosettacode.org/wiki/Execute_Brain****
Execute Brain****
Execute Brain**** is an implementation of Brainf***. Other implementations of Brainf***. RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages. Below are links to each of the versions of RCBF. An implementation need only properly implement the following instructions: Command Description > Move the pointer to the right < Move the pointer to the left + Increment the memory cell under the pointer - Decrement the memory cell under the pointer . Output the character signified by the cell at the pointer , Input a character and store it in the cell at the pointer [ Jump past the matching ] if the cell under the pointer is 0 ] Jump back to the matching [ if the cell under the pointer is nonzero Any cell size is allowed,   EOF   (End-O-File)   support is optional, as is whether you have bounded or unbounded memory.
#Ruby
Ruby
use std::collections::HashMap; use std::env; use std::fs::File; use std::io::prelude::*; use std::io::stdin; use std::num::Wrapping;   fn main() { let args: Vec<_> = env::args().collect(); if args.len() < 2 { println!("Usage: {} [path] (--debug)", args[0]); return; }   let src: Vec<char> = { let mut buf = String::new(); match File::open(&args[1]) { Ok(mut f) => { f.read_to_string(&mut buf).unwrap(); } Err(e) => { println!("Error opening '{}': {}", args[1], e); return; } }   buf.chars().collect() };   // Launch options let debug = args.contains(&"--debug".to_owned());   // One pass to find bracket pairs. let brackets: HashMap<usize, usize> = { let mut m = HashMap::new(); let mut scope_stack = Vec::new(); for (idx, ch) in src.iter().enumerate() { match ch { &'[' => { scope_stack.push(idx); } &']' => { m.insert(scope_stack.pop().unwrap(), idx); } _ => { /* ignore */ } } }   m };   let mut pc: usize = 0; // Program counter let mut mem: [Wrapping<u8>;5000] = [Wrapping(0);5000]; // Program cemory let mut ptr: usize = 0; // Pointer let mut stack: Vec<usize> = Vec::new(); // Bracket stack   let stdin_ = stdin(); let mut reader = stdin_.lock().bytes(); while pc < src.len() { let Wrapping(val) = mem[ptr];   if debug { println!("(BFDB) PC: {:04} \tPTR: {:04} \t$PTR: {:03} \tSTACK_DEPTH: {} \tSYMBOL: {}", pc, ptr, val, stack.len(), src[pc]); }   const ONE: Wrapping<u8> = Wrapping(1); match src[pc] { '>' => { ptr += 1; } '<' => { ptr -= 1; }   '+' => { mem[ptr] = mem[ptr] + ONE; } '-' => { mem[ptr] = mem[ptr] - ONE; }   '[' => { if val == 0 { pc = brackets[&pc]; } else { stack.push(pc); } } ']' => { let matching_bracket = stack.pop().unwrap(); if val != 0 { pc = matching_bracket - 1; } }   '.' => { if debug { println!("(BFDB) STDOUT: '{}'", val as char); // Intercept output } else { print!("{}", val as char); } } ',' => { mem[ptr] = Wrapping(reader.next().unwrap().unwrap()); }   _ => { /* ignore */ } }   pc += 1; } }
http://rosettacode.org/wiki/Evolutionary_algorithm
Evolutionary algorithm
Starting with: The target string: "METHINKS IT IS LIKE A WEASEL". An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). A fitness function that computes the ‘closeness’ of its argument to the target string. A mutate function that given a string and a mutation rate returns a copy of the string, with some characters probably mutated. While the parent is not yet the target: copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Assess the fitness of the parent and all the copies to the target and make the most fit string the new parent, discarding the others. repeat until the parent converges, (hopefully), to the target. See also   Wikipedia entry:   Weasel algorithm.   Wikipedia entry:   Evolutionary algorithm. Note: to aid comparison, try and ensure the variables and functions mentioned in the task description appear in solutions A cursory examination of a few of the solutions reveals that the instructions have not been followed rigorously in some solutions. Specifically, While the parent is not yet the target: copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Note that some of the the solutions given retain characters in the mutated string that are correct in the target string. However, the instruction above does not state to retain any of the characters while performing the mutation. Although some may believe to do so is implied from the use of "converges" (:* repeat until the parent converges, (hopefully), to the target. Strictly speaking, the new parent should be selected from the new pool of mutations, and then the new parent used to generate the next set of mutations with parent characters getting retained only by not being mutated. It then becomes possible that the new set of mutations has no member that is fitter than the parent! As illustration of this error, the code for 8th has the following remark. Create a new string based on the TOS, changing randomly any characters which don't already match the target: NOTE: this has been changed, the 8th version is completely random now Clearly, this algo will be applying the mutation function only to the parent characters that don't match to the target characters! To ensure that the new parent is never less fit than the prior parent, both the parent and all of the latest mutations are subjected to the fitness test to select the next parent.
#Scala
Scala
import scala.annotation.tailrec   case class LearnerParams(target:String,rate:Double,C:Int)   val chars = ('A' to 'Z') ++ List(' ') val randgen = new scala.util.Random def randchar = { val charnum = randgen.nextInt(chars.size) chars(charnum) }   class RichTraversable[T](t: Traversable[T]) { def maxBy[B](fn: T => B)(implicit ord: Ordering[B]) = t.max(ord on fn) def minBy[B](fn: T => B)(implicit ord: Ordering[B]) = t.min(ord on fn) }   implicit def toRichTraversable[T](t: Traversable[T]) = new RichTraversable(t)   def fitness(candidate:String)(implicit params:LearnerParams) = (candidate zip params.target).map { case (a,b) => if (a==b) 1 else 0 }.sum   def mutate(initial:String)(implicit params:LearnerParams) = initial.map{ samechar => if(randgen.nextDouble < params.rate) randchar else samechar }   @tailrec def evolve(generation:Int, initial:String)(implicit params:LearnerParams){ import params._ printf("Generation: %3d  %s\n",generation, initial) if(initial == target) return () val candidates = for (number <- 1 to C) yield mutate(initial) val next = candidates.maxBy(fitness) evolve(generation+1,next) }   implicit val params = LearnerParams("METHINKS IT IS LIKE A WEASEL",0.01,100) val initial = (1 to params.target.size) map(x => randchar) mkString evolve(0,initial)
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion). The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition: Fn = Fn+2 - Fn+1, if n<0 support for negative     n     in the solution is optional. Related tasks   Fibonacci n-step number sequences‎   Leonardo numbers References   Wikipedia, Fibonacci number   Wikipedia, Lucas number   MathWorld, Fibonacci Number   Some identities for r-Fibonacci numbers   OEIS Fibonacci numbers   OEIS Lucas numbers
#Pike
Pike
int fibIter(int n) { int fibPrev, fib, i; if (n < 2) { return 1; } fibPrev = 0; fib = 1; for (i = 1; i < n; i++) { int oldFib = fib; fib += fibPrev; fibPrev = oldFib; } return fib; }
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterative or recursive. Support for trapping negative   n   errors is optional. Related task   Primorial numbers
#ERRE
ERRE
  PROCEDURE FACTORIAL(X%->F) F=1 IF X%<>0 THEN FOR I%=X% TO 2 STEP Ä1 DO F=F*X% END FOR END IF END PROCEDURE  
http://rosettacode.org/wiki/Execute_Brain****
Execute Brain****
Execute Brain**** is an implementation of Brainf***. Other implementations of Brainf***. RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages. Below are links to each of the versions of RCBF. An implementation need only properly implement the following instructions: Command Description > Move the pointer to the right < Move the pointer to the left + Increment the memory cell under the pointer - Decrement the memory cell under the pointer . Output the character signified by the cell at the pointer , Input a character and store it in the cell at the pointer [ Jump past the matching ] if the cell under the pointer is 0 ] Jump back to the matching [ if the cell under the pointer is nonzero Any cell size is allowed,   EOF   (End-O-File)   support is optional, as is whether you have bounded or unbounded memory.
#Rust
Rust
use std::collections::HashMap; use std::env; use std::fs::File; use std::io::prelude::*; use std::io::stdin; use std::num::Wrapping;   fn main() { let args: Vec<_> = env::args().collect(); if args.len() < 2 { println!("Usage: {} [path] (--debug)", args[0]); return; }   let src: Vec<char> = { let mut buf = String::new(); match File::open(&args[1]) { Ok(mut f) => { f.read_to_string(&mut buf).unwrap(); } Err(e) => { println!("Error opening '{}': {}", args[1], e); return; } }   buf.chars().collect() };   // Launch options let debug = args.contains(&"--debug".to_owned());   // One pass to find bracket pairs. let brackets: HashMap<usize, usize> = { let mut m = HashMap::new(); let mut scope_stack = Vec::new(); for (idx, ch) in src.iter().enumerate() { match ch { &'[' => { scope_stack.push(idx); } &']' => { m.insert(scope_stack.pop().unwrap(), idx); } _ => { /* ignore */ } } }   m };   let mut pc: usize = 0; // Program counter let mut mem: [Wrapping<u8>;5000] = [Wrapping(0);5000]; // Program cemory let mut ptr: usize = 0; // Pointer let mut stack: Vec<usize> = Vec::new(); // Bracket stack   let stdin_ = stdin(); let mut reader = stdin_.lock().bytes(); while pc < src.len() { let Wrapping(val) = mem[ptr];   if debug { println!("(BFDB) PC: {:04} \tPTR: {:04} \t$PTR: {:03} \tSTACK_DEPTH: {} \tSYMBOL: {}", pc, ptr, val, stack.len(), src[pc]); }   const ONE: Wrapping<u8> = Wrapping(1); match src[pc] { '>' => { ptr += 1; } '<' => { ptr -= 1; }   '+' => { mem[ptr] = mem[ptr] + ONE; } '-' => { mem[ptr] = mem[ptr] - ONE; }   '[' => { if val == 0 { pc = brackets[&pc]; } else { stack.push(pc); } } ']' => { let matching_bracket = stack.pop().unwrap(); if val != 0 { pc = matching_bracket - 1; } }   '.' => { if debug { println!("(BFDB) STDOUT: '{}'", val as char); // Intercept output } else { print!("{}", val as char); } } ',' => { mem[ptr] = Wrapping(reader.next().unwrap().unwrap()); }   _ => { /* ignore */ } }   pc += 1; } }
http://rosettacode.org/wiki/Evolutionary_algorithm
Evolutionary algorithm
Starting with: The target string: "METHINKS IT IS LIKE A WEASEL". An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). A fitness function that computes the ‘closeness’ of its argument to the target string. A mutate function that given a string and a mutation rate returns a copy of the string, with some characters probably mutated. While the parent is not yet the target: copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Assess the fitness of the parent and all the copies to the target and make the most fit string the new parent, discarding the others. repeat until the parent converges, (hopefully), to the target. See also   Wikipedia entry:   Weasel algorithm.   Wikipedia entry:   Evolutionary algorithm. Note: to aid comparison, try and ensure the variables and functions mentioned in the task description appear in solutions A cursory examination of a few of the solutions reveals that the instructions have not been followed rigorously in some solutions. Specifically, While the parent is not yet the target: copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Note that some of the the solutions given retain characters in the mutated string that are correct in the target string. However, the instruction above does not state to retain any of the characters while performing the mutation. Although some may believe to do so is implied from the use of "converges" (:* repeat until the parent converges, (hopefully), to the target. Strictly speaking, the new parent should be selected from the new pool of mutations, and then the new parent used to generate the next set of mutations with parent characters getting retained only by not being mutated. It then becomes possible that the new set of mutations has no member that is fitter than the parent! As illustration of this error, the code for 8th has the following remark. Create a new string based on the TOS, changing randomly any characters which don't already match the target: NOTE: this has been changed, the 8th version is completely random now Clearly, this algo will be applying the mutation function only to the parent characters that don't match to the target characters! To ensure that the new parent is never less fit than the prior parent, both the parent and all of the latest mutations are subjected to the fitness test to select the next parent.
#Scheme
Scheme
  (import (scheme base) (scheme write) (srfi 27)) ; random numbers   (random-source-randomize! default-random-source)   (define target "METHINKS IT IS LIKE A WEASEL") ; target string (define C 100) ; size of population (define p 0.1) ; chance any char is mutated   ;; return a random character in given range (define (random-char) (string-ref "ABCDEFGHIJKLMNOPQRSTUVWXYZ " (random-integer 27)))   ;; compute distance of given string from target (define (fitness str) (apply + (map (lambda (c1 c2) (if (char=? c1 c2) 0 1)) (string->list str) (string->list target))))   ;; mutate given parent string, returning a new string (define (mutate str) (string-map (lambda (c) (if (< (random-real) p) (random-char) c)) str))   ;; create a population by mutating parent, ;; returning a list of variations (define (make-population parent) (do ((pop '() (cons (mutate parent) pop))) ((= C (length pop)) pop)))   ;; find the most fit candidate in given list (define (find-best candidates) (define (select-best a b) (if (< (fitness a) (fitness b)) a b)) ; (do ((best (car candidates) (select-best best (car rem))) (rem (cdr candidates) (cdr rem))) ((null? rem) best)))   ;; create first parent from random characters ;; of same size as target string (define (initial-parent) (do ((res '() (cons (random-char) res))) ((= (length res) (string-length target)) (list->string res))))   ;; run the search (do ((parent (initial-parent) (find-best (cons parent (make-population parent))))) ; select best from parent and population ((string=? parent target) (display (string-append "Found: " parent "\n"))) (display parent) (newline))  
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion). The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition: Fn = Fn+2 - Fn+1, if n<0 support for negative     n     in the solution is optional. Related tasks   Fibonacci n-step number sequences‎   Leonardo numbers References   Wikipedia, Fibonacci number   Wikipedia, Lucas number   MathWorld, Fibonacci Number   Some identities for r-Fibonacci numbers   OEIS Fibonacci numbers   OEIS Lucas numbers
#PIR
PIR
.sub fib .param int n .local int nt .local int ft if n < 2 goto RETURNN nt = n - 1 ft = fib( nt ) dec nt nt = fib(nt) ft = ft + nt .return( ft ) RETURNN: .return( n ) end .end   .sub main :main .local int counter .local int f counter=0 LOOP: if counter > 20 goto DONE f = fib(counter) print f print "\n" inc counter goto LOOP DONE: end .end
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterative or recursive. Support for trapping negative   n   errors is optional. Related task   Primorial numbers
#Euphoria
Euphoria
function factorial(integer n) atom f = 1 while n > 1 do f *= n n -= 1 end while   return f end function
http://rosettacode.org/wiki/Execute_Brain****
Execute Brain****
Execute Brain**** is an implementation of Brainf***. Other implementations of Brainf***. RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages. Below are links to each of the versions of RCBF. An implementation need only properly implement the following instructions: Command Description > Move the pointer to the right < Move the pointer to the left + Increment the memory cell under the pointer - Decrement the memory cell under the pointer . Output the character signified by the cell at the pointer , Input a character and store it in the cell at the pointer [ Jump past the matching ] if the cell under the pointer is 0 ] Jump back to the matching [ if the cell under the pointer is nonzero Any cell size is allowed,   EOF   (End-O-File)   support is optional, as is whether you have bounded or unbounded memory.
#Scala
Scala
  import scala.annotation._   trait Func[T] { val zero: T def inc(t: T): T def dec(t: T): T def in: T def out(t: T): Unit }   object ByteFunc extends Func[Byte] { override val zero: Byte = 0 override def inc(t: Byte) = ((t + 1) & 0xFF).toByte override def dec(t: Byte) = ((t - 1) & 0xFF).toByte override def in: Byte = readByte override def out(t: Byte) { print(t.toChar) } }   case class Tape[T](left: List[T], cell: T, right: List[T])(implicit func: Func[T]) { private def headOf(list:List[T]) = if (list.isEmpty) func.zero else list.head private def tailOf(list:List[T]) = if (list.isEmpty) Nil else list.tail def isZero = cell == func.zero def execute(ch: Char) = (ch: @switch) match { case '+' => copy(cell = func.inc(cell)) case '-' => copy(cell = func.dec(cell)) case '<' => Tape(tailOf(left), headOf(left), cell :: right) case '>' => Tape(cell :: left, headOf(right), tailOf(right)) case '.' => func.out(cell); this case ',' => copy(cell = func.in) case '[' | ']' => this case _ => error("Unexpected token: " + ch) } }   object Tape { def empty[T](func: Func[T]) = Tape(Nil, func.zero, Nil)(func) }   class Brainfuck[T](func:Func[T]) {   def execute(p: String) { val prog = p.replaceAll("[^\\+\\-\\[\\]\\.\\,\\>\\<]", "")   @tailrec def braceMatcher(pos: Int, stack: List[Int], o2c: Map[Int, Int]): Map[Int,Int] = if(pos == prog.length) o2c else (prog(pos): @switch) match { case '[' => braceMatcher(pos + 1, pos :: stack, o2c) case ']' => braceMatcher(pos + 1, stack.tail, o2c + (stack.head -> pos)) case _ => braceMatcher(pos + 1, stack, o2c) }   val open2close = braceMatcher(0, Nil, Map()) val close2open = open2close.map(_.swap)   @tailrec def ex(pos:Int, tape:Tape[T]): Unit = if(pos < prog.length) ex((prog(pos): @switch) match { case '[' if tape.isZero => open2close(pos) case ']' if ! tape.isZero => close2open(pos) case _ => pos + 1 }, tape.execute(prog(pos)))   println("---running---") ex(0, Tape.empty(func)) println("\n---done---") } }  
http://rosettacode.org/wiki/Evolutionary_algorithm
Evolutionary algorithm
Starting with: The target string: "METHINKS IT IS LIKE A WEASEL". An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). A fitness function that computes the ‘closeness’ of its argument to the target string. A mutate function that given a string and a mutation rate returns a copy of the string, with some characters probably mutated. While the parent is not yet the target: copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Assess the fitness of the parent and all the copies to the target and make the most fit string the new parent, discarding the others. repeat until the parent converges, (hopefully), to the target. See also   Wikipedia entry:   Weasel algorithm.   Wikipedia entry:   Evolutionary algorithm. Note: to aid comparison, try and ensure the variables and functions mentioned in the task description appear in solutions A cursory examination of a few of the solutions reveals that the instructions have not been followed rigorously in some solutions. Specifically, While the parent is not yet the target: copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Note that some of the the solutions given retain characters in the mutated string that are correct in the target string. However, the instruction above does not state to retain any of the characters while performing the mutation. Although some may believe to do so is implied from the use of "converges" (:* repeat until the parent converges, (hopefully), to the target. Strictly speaking, the new parent should be selected from the new pool of mutations, and then the new parent used to generate the next set of mutations with parent characters getting retained only by not being mutated. It then becomes possible that the new set of mutations has no member that is fitter than the parent! As illustration of this error, the code for 8th has the following remark. Create a new string based on the TOS, changing randomly any characters which don't already match the target: NOTE: this has been changed, the 8th version is completely random now Clearly, this algo will be applying the mutation function only to the parent characters that don't match to the target characters! To ensure that the new parent is never less fit than the prior parent, both the parent and all of the latest mutations are subjected to the fitness test to select the next parent.
#Seed7
Seed7
$ include "seed7_05.s7i";   const string: table is "ABCDEFGHIJKLMNOPQRSTUVWXYZ ";   const func integer: unfitness (in string: a, in string: b) is func result var integer: sum is 0; local var integer: index is 0; begin for index range 1 to length(a) do sum +:= ord(a[index] <> b[index]); end for; end func;   const proc: mutate (in string: a, inout string: b) is func local var integer: index is 0; begin b := a; for index range 1 to length(a) do if rand(1, 15) = 1 then b @:= [index] table[rand(1, 27)]; end if; end for; end func;   const proc: main is func local const string: target is "METHINKS IT IS LIKE A WEASEL"; const integer: OFFSPRING is 30; var integer: index is 0; var integer: unfit is 0; var integer: best is 0; var integer: bestIndex is 0; var integer: generation is 1; var string: parent is " " mult length(target); var array string: children is OFFSPRING times " " mult length(target); begin for index range 1 to length(target) do parent @:= [index] table[rand(1, 27)]; end for; repeat for index range 1 to OFFSPRING do mutate(parent, children[index]); end for; best := succ(length(parent)); bestIndex := 0; for index range 1 to OFFSPRING do unfit := unfitness(target, children[index]); if unfit < best then best := unfit; bestIndex := index; end if; end for; if bestIndex <> 0 then parent := children[bestIndex]; end if; writeln("generation " <& generation <& ": score " <& best <& ": " <& parent); incr(generation); until best = 0; end func;
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion). The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition: Fn = Fn+2 - Fn+1, if n<0 support for negative     n     in the solution is optional. Related tasks   Fibonacci n-step number sequences‎   Leonardo numbers References   Wikipedia, Fibonacci number   Wikipedia, Lucas number   MathWorld, Fibonacci Number   Some identities for r-Fibonacci numbers   OEIS Fibonacci numbers   OEIS Lucas numbers
#PL.2FI
PL/I
/* Form the n-th Fibonacci number, n > 1. 12 March 2022 */ Fib: procedure (n) returns (fixed binary (31)); declare (i, n, f1, f2, f3) fixed binary (31);   f1 = 0; f2 = 1; do i = 1 to n-2; f3 = f1 + f2; f1 = f2; f2 = f3; end; return (f3);   end Fib;  
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterative or recursive. Support for trapping negative   n   errors is optional. Related task   Primorial numbers
#Excel
Excel
  =fact(5)  
http://rosettacode.org/wiki/Execute_Brain****
Execute Brain****
Execute Brain**** is an implementation of Brainf***. Other implementations of Brainf***. RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages. Below are links to each of the versions of RCBF. An implementation need only properly implement the following instructions: Command Description > Move the pointer to the right < Move the pointer to the left + Increment the memory cell under the pointer - Decrement the memory cell under the pointer . Output the character signified by the cell at the pointer , Input a character and store it in the cell at the pointer [ Jump past the matching ] if the cell under the pointer is 0 ] Jump back to the matching [ if the cell under the pointer is nonzero Any cell size is allowed,   EOF   (End-O-File)   support is optional, as is whether you have bounded or unbounded memory.
#Scheme
Scheme
$ include "seed7_05.s7i";   const proc: brainF (in string: source, inout file: input, inout file: output) is func local var array char: memory is 100000 times '\0;'; var integer: dataPointer is 50000; var integer: instructionPointer is 1; var integer: nestingLevel is 0; begin while instructionPointer <= length(source) do case source[instructionPointer] of when {'>'}: incr(dataPointer); when {'<'}: decr(dataPointer); when {'+'}: incr(memory[dataPointer]); when {'-'}: decr(memory[dataPointer]); when {'.'}: write(output, memory[dataPointer]); when {','}: memory[dataPointer] := getc(input); when {'['}: # Forward if zero at dataPointer if memory[dataPointer] = '\0;' then nestingLevel := 1; repeat incr(instructionPointer); case source[instructionPointer] of when {'['}: incr(nestingLevel); when {']'}: decr(nestingLevel); end case; until nestingLevel = 0; end if; when {']'}: # Backward if non-zero at dataPointer if memory[dataPointer] <> '\0;' then nestingLevel := 1; repeat decr(instructionPointer); case source[instructionPointer] of when {'['}: decr(nestingLevel); when {']'}: incr(nestingLevel); end case; until nestingLevel = 0; end if; end case; incr(instructionPointer); end while; end func;   const proc: brainF (in string: source) is func begin brainF(source, IN, OUT); end func;   const proc: main is func begin brainF("++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>."); end func;
http://rosettacode.org/wiki/Evolutionary_algorithm
Evolutionary algorithm
Starting with: The target string: "METHINKS IT IS LIKE A WEASEL". An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). A fitness function that computes the ‘closeness’ of its argument to the target string. A mutate function that given a string and a mutation rate returns a copy of the string, with some characters probably mutated. While the parent is not yet the target: copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Assess the fitness of the parent and all the copies to the target and make the most fit string the new parent, discarding the others. repeat until the parent converges, (hopefully), to the target. See also   Wikipedia entry:   Weasel algorithm.   Wikipedia entry:   Evolutionary algorithm. Note: to aid comparison, try and ensure the variables and functions mentioned in the task description appear in solutions A cursory examination of a few of the solutions reveals that the instructions have not been followed rigorously in some solutions. Specifically, While the parent is not yet the target: copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Note that some of the the solutions given retain characters in the mutated string that are correct in the target string. However, the instruction above does not state to retain any of the characters while performing the mutation. Although some may believe to do so is implied from the use of "converges" (:* repeat until the parent converges, (hopefully), to the target. Strictly speaking, the new parent should be selected from the new pool of mutations, and then the new parent used to generate the next set of mutations with parent characters getting retained only by not being mutated. It then becomes possible that the new set of mutations has no member that is fitter than the parent! As illustration of this error, the code for 8th has the following remark. Create a new string based on the TOS, changing randomly any characters which don't already match the target: NOTE: this has been changed, the 8th version is completely random now Clearly, this algo will be applying the mutation function only to the parent characters that don't match to the target characters! To ensure that the new parent is never less fit than the prior parent, both the parent and all of the latest mutations are subjected to the fitness test to select the next parent.
#SequenceL
SequenceL
import <Utilities/Sequence.sl>;   AllowedChars := " ABCDEFGHIJKLMNOPQRSTUVWXYZ";   initializeParent(randChars(1)) := AllowedChars[randChars];   Fitness(target(1), current(1)) := let fit[i] := true when target[i] = current[i]; in size(fit);   Mutate(letter(0), rate(0), randRate(0), randChar(0)) := letter when randRate > rate else AllowedChars[randChar];   evolve(target(1), parent(1), C(0), P(0), rateRands(2), charRands(2)) := let mutations[i] := Mutate(parent, P, rateRands[i], charRands[i]) foreach i within 1 ... C; fitnesses := Fitness(target, mutations); in mutations[firstIndexOf(fitnesses, vectorMax(fitnesses))];
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion). The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition: Fn = Fn+2 - Fn+1, if n<0 support for negative     n     in the solution is optional. Related tasks   Fibonacci n-step number sequences‎   Leonardo numbers References   Wikipedia, Fibonacci number   Wikipedia, Lucas number   MathWorld, Fibonacci Number   Some identities for r-Fibonacci numbers   OEIS Fibonacci numbers   OEIS Lucas numbers
#PL.2FM
PL/M
100H: BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS; EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT; PRINT: PROCEDURE (S); DECLARE S ADDRESS; CALL BDOS(9,S); END PRINT;   PRINT$NUMBER: PROCEDURE (N); DECLARE S (6) BYTE INITIAL ('.....$'); DECLARE (N, P) ADDRESS, C BASED P BYTE; P = .S(5); DIGIT: P = P - 1; C = N MOD 10 + '0'; N = N / 10; IF N > 0 THEN GO TO DIGIT; CALL PRINT(P); END PRINT$NUMBER;   FIBONACCI: PROCEDURE (N) ADDRESS; DECLARE (N, A, B, C, I) ADDRESS; IF N<=1 THEN RETURN N; A = 0; B = 1; DO I=2 TO N; C = A; A = B; B = A + C; END; RETURN B; END FIBONACCI;   DECLARE I ADDRESS; DO I=0 TO 20; CALL PRINT$NUMBER(FIBONACCI(I)); CALL PRINT(.' $'); END; CALL EXIT; EOF
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterative or recursive. Support for trapping negative   n   errors is optional. Related task   Primorial numbers
#Ezhil
Ezhil
  நிரல்பாகம் fact ( n ) @( n == 0 ) ஆனால் பின்கொடு 1 இல்லை பின்கொடு n*fact( n - 1 ) முடி முடி   பதிப்பி fact ( 10 )  
http://rosettacode.org/wiki/Execute_Brain****
Execute Brain****
Execute Brain**** is an implementation of Brainf***. Other implementations of Brainf***. RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages. Below are links to each of the versions of RCBF. An implementation need only properly implement the following instructions: Command Description > Move the pointer to the right < Move the pointer to the left + Increment the memory cell under the pointer - Decrement the memory cell under the pointer . Output the character signified by the cell at the pointer , Input a character and store it in the cell at the pointer [ Jump past the matching ] if the cell under the pointer is 0 ] Jump back to the matching [ if the cell under the pointer is nonzero Any cell size is allowed,   EOF   (End-O-File)   support is optional, as is whether you have bounded or unbounded memory.
#Seed7
Seed7
$ include "seed7_05.s7i";   const proc: brainF (in string: source, inout file: input, inout file: output) is func local var array char: memory is 100000 times '\0;'; var integer: dataPointer is 50000; var integer: instructionPointer is 1; var integer: nestingLevel is 0; begin while instructionPointer <= length(source) do case source[instructionPointer] of when {'>'}: incr(dataPointer); when {'<'}: decr(dataPointer); when {'+'}: incr(memory[dataPointer]); when {'-'}: decr(memory[dataPointer]); when {'.'}: write(output, memory[dataPointer]); when {','}: memory[dataPointer] := getc(input); when {'['}: # Forward if zero at dataPointer if memory[dataPointer] = '\0;' then nestingLevel := 1; repeat incr(instructionPointer); case source[instructionPointer] of when {'['}: incr(nestingLevel); when {']'}: decr(nestingLevel); end case; until nestingLevel = 0; end if; when {']'}: # Backward if non-zero at dataPointer if memory[dataPointer] <> '\0;' then nestingLevel := 1; repeat decr(instructionPointer); case source[instructionPointer] of when {'['}: decr(nestingLevel); when {']'}: incr(nestingLevel); end case; until nestingLevel = 0; end if; end case; incr(instructionPointer); end while; end func;   const proc: brainF (in string: source) is func begin brainF(source, IN, OUT); end func;   const proc: main is func begin brainF("++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>."); end func;
http://rosettacode.org/wiki/Evolutionary_algorithm
Evolutionary algorithm
Starting with: The target string: "METHINKS IT IS LIKE A WEASEL". An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). A fitness function that computes the ‘closeness’ of its argument to the target string. A mutate function that given a string and a mutation rate returns a copy of the string, with some characters probably mutated. While the parent is not yet the target: copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Assess the fitness of the parent and all the copies to the target and make the most fit string the new parent, discarding the others. repeat until the parent converges, (hopefully), to the target. See also   Wikipedia entry:   Weasel algorithm.   Wikipedia entry:   Evolutionary algorithm. Note: to aid comparison, try and ensure the variables and functions mentioned in the task description appear in solutions A cursory examination of a few of the solutions reveals that the instructions have not been followed rigorously in some solutions. Specifically, While the parent is not yet the target: copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Note that some of the the solutions given retain characters in the mutated string that are correct in the target string. However, the instruction above does not state to retain any of the characters while performing the mutation. Although some may believe to do so is implied from the use of "converges" (:* repeat until the parent converges, (hopefully), to the target. Strictly speaking, the new parent should be selected from the new pool of mutations, and then the new parent used to generate the next set of mutations with parent characters getting retained only by not being mutated. It then becomes possible that the new set of mutations has no member that is fitter than the parent! As illustration of this error, the code for 8th has the following remark. Create a new string based on the TOS, changing randomly any characters which don't already match the target: NOTE: this has been changed, the 8th version is completely random now Clearly, this algo will be applying the mutation function only to the parent characters that don't match to the target characters! To ensure that the new parent is never less fit than the prior parent, both the parent and all of the latest mutations are subjected to the fitness test to select the next parent.
#Sidef
Sidef
define target = "METHINKS IT IS LIKE A WEASEL" define mutate_chance = 0.08 define alphabet = [('A'..'Z')..., ' '] define C = 100   func fitness(str) { str.chars ~Z== target.chars -> count(true) } func mutate(str) { str.gsub(/(.)/, {|s1| 1.rand < mutate_chance ? alphabet.pick : s1 }) }   for ( var (i, parent) = (0, alphabet.rand(target.len).join); parent != target; parent = C.of{ mutate(parent) }.max_by(fitness) ) { printf("%6d: '%s'\n", i++, parent) }
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion). The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition: Fn = Fn+2 - Fn+1, if n<0 support for negative     n     in the solution is optional. Related tasks   Fibonacci n-step number sequences‎   Leonardo numbers References   Wikipedia, Fibonacci number   Wikipedia, Lucas number   MathWorld, Fibonacci Number   Some identities for r-Fibonacci numbers   OEIS Fibonacci numbers   OEIS Lucas numbers
#PL.2FpgSQL
PL/pgSQL
CREATE OR REPLACE FUNCTION fib(n INTEGER) RETURNS INTEGER AS $$ BEGIN IF (n < 2) THEN RETURN n; END IF; RETURN fib(n - 1) + fib(n - 2); END; $$ LANGUAGE plpgsql;
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterative or recursive. Support for trapping negative   n   errors is optional. Related task   Primorial numbers
#F.23
F#
//val inline factorial : // ^a -> ^a // when ^a : (static member get_One : -> ^a) and // ^a : (static member ( + ) : ^a * ^a -> ^a) and // ^a : (static member ( * ) : ^a * ^a -> ^a) let inline factorial n = Seq.reduce (*) [ LanguagePrimitives.GenericOne .. n ]
http://rosettacode.org/wiki/Execute_Brain****
Execute Brain****
Execute Brain**** is an implementation of Brainf***. Other implementations of Brainf***. RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages. Below are links to each of the versions of RCBF. An implementation need only properly implement the following instructions: Command Description > Move the pointer to the right < Move the pointer to the left + Increment the memory cell under the pointer - Decrement the memory cell under the pointer . Output the character signified by the cell at the pointer , Input a character and store it in the cell at the pointer [ Jump past the matching ] if the cell under the pointer is 0 ] Jump back to the matching [ if the cell under the pointer is nonzero Any cell size is allowed,   EOF   (End-O-File)   support is optional, as is whether you have bounded or unbounded memory.
#Sidef
Sidef
define tape_length = 50_000; define eof_val = -1; define unbalanced_exit_code = 1;   var cmd = 0; var cell = 0; var code = []; var loops = []; var tape = tape_length.of(0);   func get_input { static input_buffer = []; input_buffer.len || (input_buffer = ((STDIN.readline \\ return eof_val).chomp.chars.map{.ord})); input_buffer.shift \\ eof_val; }   func jump { var depth = 0; while (depth >= 0) { ++cmd < code.len || Sys.exit(unbalanced_exit_code); if (code[cmd] == '[') { ++depth; } elsif (code[cmd] == ']') { --depth; } } }   var commands = Hash.new( '>' => { ++cell }, '<' => { --cell }, '+' => { ++tape[cell] }, '-' => { --tape[cell] }, '.' => { tape[cell].chr.print }, ',' => { tape[cell] = get_input() }, '[' => { tape[cell] ? loops.append(cmd) : jump() }, ']' => { cmd = (loops.pop - 1) }, );   STDOUT.autoflush(1); code = ARGF.slurp.chars.grep {|c| commands.exists(c)}; var code_len = code.len;   while (cmd < code_len) { commands{code[cmd]}.run; cmd++; }
http://rosettacode.org/wiki/Evolutionary_algorithm
Evolutionary algorithm
Starting with: The target string: "METHINKS IT IS LIKE A WEASEL". An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). A fitness function that computes the ‘closeness’ of its argument to the target string. A mutate function that given a string and a mutation rate returns a copy of the string, with some characters probably mutated. While the parent is not yet the target: copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Assess the fitness of the parent and all the copies to the target and make the most fit string the new parent, discarding the others. repeat until the parent converges, (hopefully), to the target. See also   Wikipedia entry:   Weasel algorithm.   Wikipedia entry:   Evolutionary algorithm. Note: to aid comparison, try and ensure the variables and functions mentioned in the task description appear in solutions A cursory examination of a few of the solutions reveals that the instructions have not been followed rigorously in some solutions. Specifically, While the parent is not yet the target: copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Note that some of the the solutions given retain characters in the mutated string that are correct in the target string. However, the instruction above does not state to retain any of the characters while performing the mutation. Although some may believe to do so is implied from the use of "converges" (:* repeat until the parent converges, (hopefully), to the target. Strictly speaking, the new parent should be selected from the new pool of mutations, and then the new parent used to generate the next set of mutations with parent characters getting retained only by not being mutated. It then becomes possible that the new set of mutations has no member that is fitter than the parent! As illustration of this error, the code for 8th has the following remark. Create a new string based on the TOS, changing randomly any characters which don't already match the target: NOTE: this has been changed, the 8th version is completely random now Clearly, this algo will be applying the mutation function only to the parent characters that don't match to the target characters! To ensure that the new parent is never less fit than the prior parent, both the parent and all of the latest mutations are subjected to the fitness test to select the next parent.
#Sinclair_ZX81_BASIC
Sinclair ZX81 BASIC
10 LET A$="ABCDEFGHIJKLMNOPQRSTUVWXYZ " 20 LET T$="METHINKS IT IS LIKE A WEASEL" 30 LET L=LEN T$ 40 LET C=10 50 LET M=0.05 60 LET G=0 70 DIM C$(C,L) 80 LET P$="" 90 FOR I=1 TO L 100 LET P$=P$+A$(INT (RND*LEN A$)+1) 110 NEXT I 120 PRINT AT 1,0;P$ 130 LET S$=P$ 140 GOSUB 390 150 LET N=R 160 PRINT AT 1,30;N 170 PRINT AT 0,4;G 180 IF P$=T$ THEN GOTO 440 190 FOR I=1 TO C 200 FOR J=1 TO L 210 LET C$(I,J)=P$(J) 220 IF RND<=M THEN LET C$(I,J)=A$(INT (RND*LEN A$)+1) 230 PRINT AT I+2,J-1;C$(I,J) 240 NEXT J 250 PRINT AT I+2,30;" " 260 NEXT I 270 LET F=0 280 FOR I=1 TO C 290 LET S$=C$(I) 300 GOSUB 390 310 PRINT AT I+2,30;R 320 IF R>N THEN LET F=I 330 IF R>N THEN LET N=R 340 NEXT I 350 IF F>0 THEN LET P$=C$(F) 360 LET G=G+1 370 PRINT AT 1,0;P$ 380 GOTO 160 390 LET R=0 400 FOR K=1 TO L 410 IF S$(K)=T$(K) THEN LET R=R+1 420 NEXT K 430 RETURN
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion). The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition: Fn = Fn+2 - Fn+1, if n<0 support for negative     n     in the solution is optional. Related tasks   Fibonacci n-step number sequences‎   Leonardo numbers References   Wikipedia, Fibonacci number   Wikipedia, Lucas number   MathWorld, Fibonacci Number   Some identities for r-Fibonacci numbers   OEIS Fibonacci numbers   OEIS Lucas numbers
#PL.2FSQL
PL/SQL
  CREATE OR REPLACE FUNCTION fnu_fibonacci(p_num INTEGER) RETURN INTEGER IS f INTEGER; p INTEGER; q INTEGER; BEGIN CASE WHEN p_num < 0 OR p_num != TRUNC(p_num) THEN raise_application_error(-20001, 'Invalid input: ' || p_num, TRUE); WHEN p_num IN (0, 1) THEN f := p_num; ELSE p := 0; q := 1; FOR i IN 2 .. p_num LOOP f := p + q; p := q; q := f; END LOOP; END CASE; RETURN(f); END fnu_fibonacci; /  
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterative or recursive. Support for trapping negative   n   errors is optional. Related task   Primorial numbers
#Factor
Factor
USING: math.ranges sequences ;   : factorial ( n -- n ) [1,b] product ;
http://rosettacode.org/wiki/Execute_Brain****
Execute Brain****
Execute Brain**** is an implementation of Brainf***. Other implementations of Brainf***. RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages. Below are links to each of the versions of RCBF. An implementation need only properly implement the following instructions: Command Description > Move the pointer to the right < Move the pointer to the left + Increment the memory cell under the pointer - Decrement the memory cell under the pointer . Output the character signified by the cell at the pointer , Input a character and store it in the cell at the pointer [ Jump past the matching ] if the cell under the pointer is 0 ] Jump back to the matching [ if the cell under the pointer is nonzero Any cell size is allowed,   EOF   (End-O-File)   support is optional, as is whether you have bounded or unbounded memory.
#Standard_ML
Standard ML
import Foundation   let valids = [">", "<", "+", "-", ".", ",", "[", "]"] as Set<Character> var ip = 0 var dp = 0 var data = [UInt8](count: 30_000, repeatedValue: 0)   let input = Process.arguments   if input.count != 2 { fatalError("Need one input file") }   let infile: String!   do { infile = try String(contentsOfFile: input[1], encoding: NSUTF8StringEncoding) ?? "" } catch let err { infile = "" }   var program = ""   // remove invalid chars for c in infile.characters { if valids.contains(c) { program += String(c) } }   let numChars = program.characters.count   if numChars == 0 { fatalError("Error reading file") }   func increaseInstructionPointer() { ip += 1 }   func executeInstruction(ins: Character) { switch ins { case ">": dp += 1 increaseInstructionPointer() case "<": dp -= 1 increaseInstructionPointer() case "+": data[dp] = data[dp] &+ 1 increaseInstructionPointer() case "-": data[dp] = data[dp] &- 1 increaseInstructionPointer() case ".": print(Character(UnicodeScalar(data[dp])), terminator: "") increaseInstructionPointer() case ",": handleIn() increaseInstructionPointer() case "[": handleOpenBracket() case "]": handleClosedBracket() default: fatalError("What") } }   func handleIn() { let input = NSFileHandle.fileHandleWithStandardInput() let bytes = input.availableData.bytes let buf = unsafeBitCast(UnsafeBufferPointer(start: bytes, count: 1), UnsafeBufferPointer<UInt8>.self)   data[dp] = buf[0] }   func handleOpenBracket() { if data[dp] == 0 { var i = 1   while i > 0 { ip += 1 let ins = program[program.startIndex.advancedBy(ip)]   if ins == "[" { i += 1 } else if ins == "]" { i -= 1 } } } else { increaseInstructionPointer() } }   func handleClosedBracket() { if data[dp] != 0 { var i = 1   while i > 0 { ip -= 1 let ins = program[program.startIndex.advancedBy(ip)]   if ins == "[" { i -= 1 } else if ins == "]" { i += 1 } } } else { increaseInstructionPointer() } }   func tick() { let ins = program[program.startIndex.advancedBy(ip)]   if valids.contains(ins) { executeInstruction(ins) } else { increaseInstructionPointer() } }   while ip != numChars { tick() }
http://rosettacode.org/wiki/Evolutionary_algorithm
Evolutionary algorithm
Starting with: The target string: "METHINKS IT IS LIKE A WEASEL". An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). A fitness function that computes the ‘closeness’ of its argument to the target string. A mutate function that given a string and a mutation rate returns a copy of the string, with some characters probably mutated. While the parent is not yet the target: copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Assess the fitness of the parent and all the copies to the target and make the most fit string the new parent, discarding the others. repeat until the parent converges, (hopefully), to the target. See also   Wikipedia entry:   Weasel algorithm.   Wikipedia entry:   Evolutionary algorithm. Note: to aid comparison, try and ensure the variables and functions mentioned in the task description appear in solutions A cursory examination of a few of the solutions reveals that the instructions have not been followed rigorously in some solutions. Specifically, While the parent is not yet the target: copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Note that some of the the solutions given retain characters in the mutated string that are correct in the target string. However, the instruction above does not state to retain any of the characters while performing the mutation. Although some may believe to do so is implied from the use of "converges" (:* repeat until the parent converges, (hopefully), to the target. Strictly speaking, the new parent should be selected from the new pool of mutations, and then the new parent used to generate the next set of mutations with parent characters getting retained only by not being mutated. It then becomes possible that the new set of mutations has no member that is fitter than the parent! As illustration of this error, the code for 8th has the following remark. Create a new string based on the TOS, changing randomly any characters which don't already match the target: NOTE: this has been changed, the 8th version is completely random now Clearly, this algo will be applying the mutation function only to the parent characters that don't match to the target characters! To ensure that the new parent is never less fit than the prior parent, both the parent and all of the latest mutations are subjected to the fitness test to select the next parent.
#Smalltalk
Smalltalk
String subclass: Mutant [ <shape: #character>   Target := Mutant from: 'METHINKS IT IS LIKE A WEASEL'. Letters := ' ABCDEFGHIJKLMNOPQRSTUVWXYZ'.   Mutant class >> run: c rate: p ["Run Evolutionary algorighm, using c copies and mutate rate p." | pool parent | parent := self newRandom. pool := Array new: c+1.   [parent displayNl. parent = Target] whileFalse: [1 to: c do: [:i | pool at: i put: (parent copy mutate: p)]. pool at: c+1 put: parent. parent := pool fold: [:winner :each | winner fittest: each]]]   Mutant class >> newRandom [^(self new: Target size) initializeToRandom; yourself]   initializeToRandom [self keys do: [:i | self at: i put: self randomLetter]]   mutate: p [self keys do: [:i | Random next <= p ifTrue: [self at: i put: self randomLetter]]]   fitness [| score | score := 0. self with: Target do: [:me :you | me = you ifTrue: [score := score + 1]]. ^score]   fittest: aMutant [^self fitness > aMutant fitness ifTrue: [self] ifFalse: [aMutant]]   randomLetter [^Letters at: (Random between: 1 and: Letters size)] ]
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion). The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition: Fn = Fn+2 - Fn+1, if n<0 support for negative     n     in the solution is optional. Related tasks   Fibonacci n-step number sequences‎   Leonardo numbers References   Wikipedia, Fibonacci number   Wikipedia, Lucas number   MathWorld, Fibonacci Number   Some identities for r-Fibonacci numbers   OEIS Fibonacci numbers   OEIS Lucas numbers
#Plain_English
Plain English
To find a fibonacci number given a count: Put 0 into a number. Put 1 into another number. Loop. If a counter is past the count, put the number into the fibonacci number; exit. Add the number to the other number. Swap the number with the other number. Repeat.
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterative or recursive. Support for trapping negative   n   errors is optional. Related task   Primorial numbers
#FALSE
FALSE
[1\[$][$@*\1-]#%]f: ^'0- f;!.
http://rosettacode.org/wiki/Execute_Brain****
Execute Brain****
Execute Brain**** is an implementation of Brainf***. Other implementations of Brainf***. RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages. Below are links to each of the versions of RCBF. An implementation need only properly implement the following instructions: Command Description > Move the pointer to the right < Move the pointer to the left + Increment the memory cell under the pointer - Decrement the memory cell under the pointer . Output the character signified by the cell at the pointer , Input a character and store it in the cell at the pointer [ Jump past the matching ] if the cell under the pointer is 0 ] Jump back to the matching [ if the cell under the pointer is nonzero Any cell size is allowed,   EOF   (End-O-File)   support is optional, as is whether you have bounded or unbounded memory.
#Swift
Swift
import Foundation   let valids = [">", "<", "+", "-", ".", ",", "[", "]"] as Set<Character> var ip = 0 var dp = 0 var data = [UInt8](count: 30_000, repeatedValue: 0)   let input = Process.arguments   if input.count != 2 { fatalError("Need one input file") }   let infile: String!   do { infile = try String(contentsOfFile: input[1], encoding: NSUTF8StringEncoding) ?? "" } catch let err { infile = "" }   var program = ""   // remove invalid chars for c in infile.characters { if valids.contains(c) { program += String(c) } }   let numChars = program.characters.count   if numChars == 0 { fatalError("Error reading file") }   func increaseInstructionPointer() { ip += 1 }   func executeInstruction(ins: Character) { switch ins { case ">": dp += 1 increaseInstructionPointer() case "<": dp -= 1 increaseInstructionPointer() case "+": data[dp] = data[dp] &+ 1 increaseInstructionPointer() case "-": data[dp] = data[dp] &- 1 increaseInstructionPointer() case ".": print(Character(UnicodeScalar(data[dp])), terminator: "") increaseInstructionPointer() case ",": handleIn() increaseInstructionPointer() case "[": handleOpenBracket() case "]": handleClosedBracket() default: fatalError("What") } }   func handleIn() { let input = NSFileHandle.fileHandleWithStandardInput() let bytes = input.availableData.bytes let buf = unsafeBitCast(UnsafeBufferPointer(start: bytes, count: 1), UnsafeBufferPointer<UInt8>.self)   data[dp] = buf[0] }   func handleOpenBracket() { if data[dp] == 0 { var i = 1   while i > 0 { ip += 1 let ins = program[program.startIndex.advancedBy(ip)]   if ins == "[" { i += 1 } else if ins == "]" { i -= 1 } } } else { increaseInstructionPointer() } }   func handleClosedBracket() { if data[dp] != 0 { var i = 1   while i > 0 { ip -= 1 let ins = program[program.startIndex.advancedBy(ip)]   if ins == "[" { i -= 1 } else if ins == "]" { i += 1 } } } else { increaseInstructionPointer() } }   func tick() { let ins = program[program.startIndex.advancedBy(ip)]   if valids.contains(ins) { executeInstruction(ins) } else { increaseInstructionPointer() } }   while ip != numChars { tick() }
http://rosettacode.org/wiki/Evolutionary_algorithm
Evolutionary algorithm
Starting with: The target string: "METHINKS IT IS LIKE A WEASEL". An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). A fitness function that computes the ‘closeness’ of its argument to the target string. A mutate function that given a string and a mutation rate returns a copy of the string, with some characters probably mutated. While the parent is not yet the target: copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Assess the fitness of the parent and all the copies to the target and make the most fit string the new parent, discarding the others. repeat until the parent converges, (hopefully), to the target. See also   Wikipedia entry:   Weasel algorithm.   Wikipedia entry:   Evolutionary algorithm. Note: to aid comparison, try and ensure the variables and functions mentioned in the task description appear in solutions A cursory examination of a few of the solutions reveals that the instructions have not been followed rigorously in some solutions. Specifically, While the parent is not yet the target: copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Note that some of the the solutions given retain characters in the mutated string that are correct in the target string. However, the instruction above does not state to retain any of the characters while performing the mutation. Although some may believe to do so is implied from the use of "converges" (:* repeat until the parent converges, (hopefully), to the target. Strictly speaking, the new parent should be selected from the new pool of mutations, and then the new parent used to generate the next set of mutations with parent characters getting retained only by not being mutated. It then becomes possible that the new set of mutations has no member that is fitter than the parent! As illustration of this error, the code for 8th has the following remark. Create a new string based on the TOS, changing randomly any characters which don't already match the target: NOTE: this has been changed, the 8th version is completely random now Clearly, this algo will be applying the mutation function only to the parent characters that don't match to the target characters! To ensure that the new parent is never less fit than the prior parent, both the parent and all of the latest mutations are subjected to the fitness test to select the next parent.
#Swift
Swift
func evolve( to target: String, parent: inout String, mutationRate: Int, copies: Int ) { var parentFitness: Int { return fitness(target: target, sentence: parent) }   var generation = 0   while parent != target { generation += 1   let bestOfGeneration = (0..<copies) .map({_ in mutate(sentence: parent, rate: mutationRate) }) .map({ (fitness(target: target, sentence: $0), $0) }) .sorted(by: { $0.0 < $1.0 }) .first!   if bestOfGeneration.0 < parentFitness { print("Gen \(generation) produced better fit. \(bestOfGeneration.1) with fitness \(bestOfGeneration.0)") parent = bestOfGeneration.1 } } }   func fitness(target: String, sentence: String) -> Int { return zip(target, sentence).filter(!=).count }   func mutate(sentence: String, rate: Int) -> String { return String( sentence.map({char in if Int.random(in: 1...100) - rate <= 0 { return "ABCDEFGHIJKLMNOPQRSTUVWXYZ ".randomElement()! } else { return char } }) ) }   let target = "METHINKS IT IS LIKE A WEASEL" let copies = 100 let mutationRate = 20   var start = mutate(sentence: target, rate: 100)   print("target: \(target)") print("Gen 0: \(start) with fitness \(fitness(target: target, sentence: start))")   evolve(to: target, parent: &start, mutationRate: mutationRate, copies: 100)
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion). The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition: Fn = Fn+2 - Fn+1, if n<0 support for negative     n     in the solution is optional. Related tasks   Fibonacci n-step number sequences‎   Leonardo numbers References   Wikipedia, Fibonacci number   Wikipedia, Lucas number   MathWorld, Fibonacci Number   Some identities for r-Fibonacci numbers   OEIS Fibonacci numbers   OEIS Lucas numbers
#Pop11
Pop11
define fib(x); lvars a , b; 1 -> a; 1 -> b; repeat x - 1 times (a + b, b) -> (b, a); endrepeat; a; enddefine;
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterative or recursive. Support for trapping negative   n   errors is optional. Related task   Primorial numbers
#Fancy
Fancy
def class Number { def factorial { 1 upto: self . product } }   # print first ten factorials 1 upto: 10 do_each: |i| { i to_s ++ "! = " ++ (i factorial) println }
http://rosettacode.org/wiki/Execute_Brain****
Execute Brain****
Execute Brain**** is an implementation of Brainf***. Other implementations of Brainf***. RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages. Below are links to each of the versions of RCBF. An implementation need only properly implement the following instructions: Command Description > Move the pointer to the right < Move the pointer to the left + Increment the memory cell under the pointer - Decrement the memory cell under the pointer . Output the character signified by the cell at the pointer , Input a character and store it in the cell at the pointer [ Jump past the matching ] if the cell under the pointer is 0 ] Jump back to the matching [ if the cell under the pointer is nonzero Any cell size is allowed,   EOF   (End-O-File)   support is optional, as is whether you have bounded or unbounded memory.
#Tcl
Tcl
#!/usr/bin/env bash # BrainF*** interpreter in bash if (( ! $# )); then printf >&2 'Usage: %s program-file\n' "$0" exit 1 fi   # load the program exec 3<"$1" program=() while IFS= read -r line <&3; do mapfile -t instr < <(tr -cd '[]<>.,+-' <<<"$line" | sed $'s/./&\\\n/g') program+=("${instr[@]}") done exec 3<&-   # parse loops loops=() matches=() for pc in "${!program[@]}"; do instr=${program[pc]} if [[ $instr == '[' ]]; then loops=("$pc" "${loops[@]}") elif [[ $instr == ']' ]]; then matches[$pc]=${loops[0]} matches[${loops[0]}]=$pc loops=(${loops[@]:1}) fi done   # execute program memory=(0) mp=0 pc=0 while (( pc < ${#program[@]} )); do instr=${program[pc]} (( pc+=1 )) mem=${memory[mp]} case "$instr" in '[') if (( ! mem )); then (( pc=${matches[pc-1]}+1 )); fi;; ']') if (( mem )); then (( pc=${matches[pc-1]}+1 )); fi;; +) memory[mp]=$(( (mem + 1) % 256 ));; -) memory[mp]=$(( (mem - 1) % 256 ));; '>') (( mp+=1 )); if (( mp >= ${#memory[@]} )); then memory+=(0); fi;; '<') (( mp-=1 )); if (( mp < 0 )); then memory=(0 "${memory[@]}"); mp=0; fi;; .) printf %b $(printf '\\%03o' "$mem");; ,) read -n1 c; memory[mp]=$(LC_CTYPE=C printf '%d' "'$c");; esac done
http://rosettacode.org/wiki/Evolutionary_algorithm
Evolutionary algorithm
Starting with: The target string: "METHINKS IT IS LIKE A WEASEL". An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). A fitness function that computes the ‘closeness’ of its argument to the target string. A mutate function that given a string and a mutation rate returns a copy of the string, with some characters probably mutated. While the parent is not yet the target: copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Assess the fitness of the parent and all the copies to the target and make the most fit string the new parent, discarding the others. repeat until the parent converges, (hopefully), to the target. See also   Wikipedia entry:   Weasel algorithm.   Wikipedia entry:   Evolutionary algorithm. Note: to aid comparison, try and ensure the variables and functions mentioned in the task description appear in solutions A cursory examination of a few of the solutions reveals that the instructions have not been followed rigorously in some solutions. Specifically, While the parent is not yet the target: copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Note that some of the the solutions given retain characters in the mutated string that are correct in the target string. However, the instruction above does not state to retain any of the characters while performing the mutation. Although some may believe to do so is implied from the use of "converges" (:* repeat until the parent converges, (hopefully), to the target. Strictly speaking, the new parent should be selected from the new pool of mutations, and then the new parent used to generate the next set of mutations with parent characters getting retained only by not being mutated. It then becomes possible that the new set of mutations has no member that is fitter than the parent! As illustration of this error, the code for 8th has the following remark. Create a new string based on the TOS, changing randomly any characters which don't already match the target: NOTE: this has been changed, the 8th version is completely random now Clearly, this algo will be applying the mutation function only to the parent characters that don't match to the target characters! To ensure that the new parent is never less fit than the prior parent, both the parent and all of the latest mutations are subjected to the fitness test to select the next parent.
#Tailspin
Tailspin
  def alphabet: [' ABCDEFGHIJKLMNOPQRSTUVWXYZ'...]; def target: ['METHINKS IT IS LIKE A WEASEL'...]; def generationSize: 100; def mutationPercent: 10;   source randomCharacter $alphabet::length -> SYS::randomInt -> $alphabet($+1)! end randomCharacter   templates countFitness @:0; $ -> \[i](when <=$target($i)> do @countFitness: $@countFitness + 1; \) -> !VOID { candidate: $, fitness: $@countFitness } ! end countFitness   sink evolve @: {generation: 0"1", parent: $}; [email protected] -> # when <{fitness: <=$target::length>}> do 'Target "$target...;" reached after [email protected]; generations' -> !OUT::write otherwise 'Fitness $.fitness; at generation [email protected];: "$.candidate...;"$#10;' -> !OUT::write @.generation: [email protected] + 1"1"; 1..$generationSize -> [[email protected]... -> \( when <?(100 -> SYS::randomInt <..~$mutationPercent>)> do $randomCharacter! otherwise $! \)] -> countFitness -> \(when <{fitness: <[email protected]..>}> do @evolve.parent: $;\) -> !VOID [email protected] -> # end evolve   [1..$target::length -> $randomCharacter] -> countFitness -> !evolve  
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion). The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition: Fn = Fn+2 - Fn+1, if n<0 support for negative     n     in the solution is optional. Related tasks   Fibonacci n-step number sequences‎   Leonardo numbers References   Wikipedia, Fibonacci number   Wikipedia, Lucas number   MathWorld, Fibonacci Number   Some identities for r-Fibonacci numbers   OEIS Fibonacci numbers   OEIS Lucas numbers
#PostScript
PostScript
%!PS   % We want the 'n'th fibonacci number /n 13 def   % Prepare output canvas: /Helvetica findfont 20 scalefont setfont 100 100 moveto   %define the function recursively: /fib { dup 3 lt { pop 1 } { dup 1 sub fib exch 2 sub fib add } ifelse } def   (Fib\() show n (....) cvs show (\)=) show n fib (.....) cvs show   showpage
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterative or recursive. Support for trapping negative   n   errors is optional. Related task   Primorial numbers
#Fantom
Fantom
class Main { static Int factorialRecursive (Int n) { if (n <= 1) return 1 else return n * (factorialRecursive (n - 1)) }   static Int factorialIterative (Int n) { Int product := 1 for (Int i := 2; i <=n ; ++i) { product *= i } return product }   static Int factorialFunctional (Int n) { (1..n).toList.reduce(1) |a,v| { v->mult(a) // use a dynamic invoke // alternatively, cast a: v * (Int)a } }   public static Void main () { echo (factorialRecursive(20)) echo (factorialIterative(20)) echo (factorialFunctional(20)) } }
http://rosettacode.org/wiki/Execute_Brain****
Execute Brain****
Execute Brain**** is an implementation of Brainf***. Other implementations of Brainf***. RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages. Below are links to each of the versions of RCBF. An implementation need only properly implement the following instructions: Command Description > Move the pointer to the right < Move the pointer to the left + Increment the memory cell under the pointer - Decrement the memory cell under the pointer . Output the character signified by the cell at the pointer , Input a character and store it in the cell at the pointer [ Jump past the matching ] if the cell under the pointer is 0 ] Jump back to the matching [ if the cell under the pointer is nonzero Any cell size is allowed,   EOF   (End-O-File)   support is optional, as is whether you have bounded or unbounded memory.
#TI-83_BASIC
TI-83 BASIC
#!/usr/bin/env bash # BrainF*** interpreter in bash if (( ! $# )); then printf >&2 'Usage: %s program-file\n' "$0" exit 1 fi   # load the program exec 3<"$1" program=() while IFS= read -r line <&3; do mapfile -t instr < <(tr -cd '[]<>.,+-' <<<"$line" | sed $'s/./&\\\n/g') program+=("${instr[@]}") done exec 3<&-   # parse loops loops=() matches=() for pc in "${!program[@]}"; do instr=${program[pc]} if [[ $instr == '[' ]]; then loops=("$pc" "${loops[@]}") elif [[ $instr == ']' ]]; then matches[$pc]=${loops[0]} matches[${loops[0]}]=$pc loops=(${loops[@]:1}) fi done   # execute program memory=(0) mp=0 pc=0 while (( pc < ${#program[@]} )); do instr=${program[pc]} (( pc+=1 )) mem=${memory[mp]} case "$instr" in '[') if (( ! mem )); then (( pc=${matches[pc-1]}+1 )); fi;; ']') if (( mem )); then (( pc=${matches[pc-1]}+1 )); fi;; +) memory[mp]=$(( (mem + 1) % 256 ));; -) memory[mp]=$(( (mem - 1) % 256 ));; '>') (( mp+=1 )); if (( mp >= ${#memory[@]} )); then memory+=(0); fi;; '<') (( mp-=1 )); if (( mp < 0 )); then memory=(0 "${memory[@]}"); mp=0; fi;; .) printf %b $(printf '\\%03o' "$mem");; ,) read -n1 c; memory[mp]=$(LC_CTYPE=C printf '%d' "'$c");; esac done
http://rosettacode.org/wiki/Evolutionary_algorithm
Evolutionary algorithm
Starting with: The target string: "METHINKS IT IS LIKE A WEASEL". An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). A fitness function that computes the ‘closeness’ of its argument to the target string. A mutate function that given a string and a mutation rate returns a copy of the string, with some characters probably mutated. While the parent is not yet the target: copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Assess the fitness of the parent and all the copies to the target and make the most fit string the new parent, discarding the others. repeat until the parent converges, (hopefully), to the target. See also   Wikipedia entry:   Weasel algorithm.   Wikipedia entry:   Evolutionary algorithm. Note: to aid comparison, try and ensure the variables and functions mentioned in the task description appear in solutions A cursory examination of a few of the solutions reveals that the instructions have not been followed rigorously in some solutions. Specifically, While the parent is not yet the target: copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Note that some of the the solutions given retain characters in the mutated string that are correct in the target string. However, the instruction above does not state to retain any of the characters while performing the mutation. Although some may believe to do so is implied from the use of "converges" (:* repeat until the parent converges, (hopefully), to the target. Strictly speaking, the new parent should be selected from the new pool of mutations, and then the new parent used to generate the next set of mutations with parent characters getting retained only by not being mutated. It then becomes possible that the new set of mutations has no member that is fitter than the parent! As illustration of this error, the code for 8th has the following remark. Create a new string based on the TOS, changing randomly any characters which don't already match the target: NOTE: this has been changed, the 8th version is completely random now Clearly, this algo will be applying the mutation function only to the parent characters that don't match to the target characters! To ensure that the new parent is never less fit than the prior parent, both the parent and all of the latest mutations are subjected to the fitness test to select the next parent.
#Tcl
Tcl
package require Tcl 8.5   # A function to select a random character from an argument string proc tcl::mathfunc::randchar s { string index $s [expr {int([string length $s]*rand())}] }   # Set up the initial variables set target "METHINKS IT IS LIKE A WEASEL" set charset "ABCDEFGHIJKLMNOPQRSTUVWXYZ " set parent [subst [regsub -all . $target {[expr {randchar($charset)}]}]] set MaxMutateRate 0.91 set C 100   # Work with parent and target as lists of characters so iteration is more efficient set target [split $target {}] set parent [split $parent {}]   # Generate the fitness *ratio* proc fitness s { global target set count 0 foreach c1 $s c2 $target { if {$c1 eq $c2} {incr count} } return [expr {$count/double([llength $target])}] } # This generates the converse of the Python version; logically saner naming proc mutateRate {parent} { expr {(1.0-[fitness $parent]) * $::MaxMutateRate} } proc mutate {rate} { global charset parent foreach c $parent { lappend result [expr {rand() <= $rate ? randchar($charset) : $c}] } return $result } proc que {} { global iterations parent puts [format "#%-4i, fitness %4.1f%%, '%s'" \ $iterations [expr {[fitness $parent]*100}] [join $parent {}]] }   while {$parent ne $target} { set rate [mutateRate $parent] if {!([incr iterations] % 100)} que set copies [list [list $parent [fitness $parent]]] for {set i 0} {$i < $C} {incr i} { lappend copies [list [set copy [mutate $rate]] [fitness $copy]] } set parent [lindex [lsort -real -decreasing -index 1 $copies] 0 0] } puts "" que
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion). The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition: Fn = Fn+2 - Fn+1, if n<0 support for negative     n     in the solution is optional. Related tasks   Fibonacci n-step number sequences‎   Leonardo numbers References   Wikipedia, Fibonacci number   Wikipedia, Lucas number   MathWorld, Fibonacci Number   Some identities for r-Fibonacci numbers   OEIS Fibonacci numbers   OEIS Lucas numbers
#Potion
Potion
recursive = (n): if (n <= 1): 1. else: recursive (n - 1) + recursive (n - 2)..   n = 40 ("fib(", n, ")= ", recursive (n), "\n") join print
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterative or recursive. Support for trapping negative   n   errors is optional. Related task   Primorial numbers
#Fermat
Fermat
666!
http://rosettacode.org/wiki/Execute_Brain****
Execute Brain****
Execute Brain**** is an implementation of Brainf***. Other implementations of Brainf***. RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages. Below are links to each of the versions of RCBF. An implementation need only properly implement the following instructions: Command Description > Move the pointer to the right < Move the pointer to the left + Increment the memory cell under the pointer - Decrement the memory cell under the pointer . Output the character signified by the cell at the pointer , Input a character and store it in the cell at the pointer [ Jump past the matching ] if the cell under the pointer is 0 ] Jump back to the matching [ if the cell under the pointer is nonzero Any cell size is allowed,   EOF   (End-O-File)   support is optional, as is whether you have bounded or unbounded memory.
#TI-89_BASIC
TI-89 BASIC
#!/usr/bin/env bash # BrainF*** interpreter in bash if (( ! $# )); then printf >&2 'Usage: %s program-file\n' "$0" exit 1 fi   # load the program exec 3<"$1" program=() while IFS= read -r line <&3; do mapfile -t instr < <(tr -cd '[]<>.,+-' <<<"$line" | sed $'s/./&\\\n/g') program+=("${instr[@]}") done exec 3<&-   # parse loops loops=() matches=() for pc in "${!program[@]}"; do instr=${program[pc]} if [[ $instr == '[' ]]; then loops=("$pc" "${loops[@]}") elif [[ $instr == ']' ]]; then matches[$pc]=${loops[0]} matches[${loops[0]}]=$pc loops=(${loops[@]:1}) fi done   # execute program memory=(0) mp=0 pc=0 while (( pc < ${#program[@]} )); do instr=${program[pc]} (( pc+=1 )) mem=${memory[mp]} case "$instr" in '[') if (( ! mem )); then (( pc=${matches[pc-1]}+1 )); fi;; ']') if (( mem )); then (( pc=${matches[pc-1]}+1 )); fi;; +) memory[mp]=$(( (mem + 1) % 256 ));; -) memory[mp]=$(( (mem - 1) % 256 ));; '>') (( mp+=1 )); if (( mp >= ${#memory[@]} )); then memory+=(0); fi;; '<') (( mp-=1 )); if (( mp < 0 )); then memory=(0 "${memory[@]}"); mp=0; fi;; .) printf %b $(printf '\\%03o' "$mem");; ,) read -n1 c; memory[mp]=$(LC_CTYPE=C printf '%d' "'$c");; esac done
http://rosettacode.org/wiki/Evolutionary_algorithm
Evolutionary algorithm
Starting with: The target string: "METHINKS IT IS LIKE A WEASEL". An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). A fitness function that computes the ‘closeness’ of its argument to the target string. A mutate function that given a string and a mutation rate returns a copy of the string, with some characters probably mutated. While the parent is not yet the target: copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Assess the fitness of the parent and all the copies to the target and make the most fit string the new parent, discarding the others. repeat until the parent converges, (hopefully), to the target. See also   Wikipedia entry:   Weasel algorithm.   Wikipedia entry:   Evolutionary algorithm. Note: to aid comparison, try and ensure the variables and functions mentioned in the task description appear in solutions A cursory examination of a few of the solutions reveals that the instructions have not been followed rigorously in some solutions. Specifically, While the parent is not yet the target: copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Note that some of the the solutions given retain characters in the mutated string that are correct in the target string. However, the instruction above does not state to retain any of the characters while performing the mutation. Although some may believe to do so is implied from the use of "converges" (:* repeat until the parent converges, (hopefully), to the target. Strictly speaking, the new parent should be selected from the new pool of mutations, and then the new parent used to generate the next set of mutations with parent characters getting retained only by not being mutated. It then becomes possible that the new set of mutations has no member that is fitter than the parent! As illustration of this error, the code for 8th has the following remark. Create a new string based on the TOS, changing randomly any characters which don't already match the target: NOTE: this has been changed, the 8th version is completely random now Clearly, this algo will be applying the mutation function only to the parent characters that don't match to the target characters! To ensure that the new parent is never less fit than the prior parent, both the parent and all of the latest mutations are subjected to the fitness test to select the next parent.
#uBasic.2F4tH
uBasic/4tH
T = 0 ' Address of target L = 28 ' Length of string P = T + L ' Address of parent R = 6 ' Mutation rate in percent C = 7 ' Number of children B = 0 ' Best rate so far   Proc _Initialize ' Initialize   Do ' Now start mutating I = 0 ' Nothing does it better so far   For x = 2 To C+1 ' Addresses of children Proc _MutateDNA (x, P, R) ' Now mutate their DNA F = FUNC(_Fitness (x, T)) ' Check for fitness If F > B Then B = F : I = x ' If fitness of child is better Next ' Make it the best score   If I Then ' If a better child was found Proc _MakeParent (P, I) ' Make the child the parent Proc _PrintParent (P) ' Print the new parent EndIf   Until B = L ' Until top score equals length Loop   End     _MutateDNA Param(3) ' Mutate an entire DNA Local(1)   For d@ = 0 to L-1 ' For the entire string If c@ > Rnd(100) Then ' If mutation rate is met @(a@*L+d@) = Ord("A") + Rnd(27) ' Mutate the gene Else @(a@*L+d@) = @(b@+d@) ' Otherwise copy it from the parent EndIf Next Return     _Fitness Param(2) ' Check for fitness Local(2)   c@ = 0 ' Fitness is zero For d@ = 0 to L-1 ' For the entire string If @(a@*L+d@) = @(b@+d@) Then c@ = c@ + 1 Next ' If string matches, increment score Return (c@) ' Return the fitness     _MakeParent Param(2) ' Make a child into a parent Local(1)   For c@ = 0 to L-1 ' For the entire string @(a@+c@) = @(b@*L+c@) ' Copy the DNA gene by gene Next Return     _PrintParent Param(1) ' Print the parent Local(1)   For b@ = 0 to L-1 ' For the entire string If (@(a@+b@)) > Ord ("Z") Then Print " "; ' Cater for the space Else Print CHR(@(a@+b@)); ' Print a gene EndIf Next   Print ' Issue a linefeed Return     _Initialize ' Initialize target and parent @(0)=Ord("M") ' Initialize target (long!) @(1)=Ord("E") ' Character by character @(2)=Ord("T") @(3)=Ord("H") @(4)=Ord("I") @(5)=Ord("N") @(6)=Ord("K") @(7)=Ord("S") @(8)=Ord("Z")+1 @(9)=Ord("I") @(10)=Ord("T") @(11)=Ord("Z")+1 @(12)=Ord("I") @(13)=Ord("S") @(14)=Ord("Z")+1 @(15)=Ord("L") @(16)=Ord("I") @(17)=Ord("K") @(18)=Ord("E") @(19)=Ord("Z")+1 @(20)=Ord("A") @(21)=Ord("Z")+1 @(22)=Ord("W") @(23)=Ord("E") @(24)=Ord("A") @(25)=Ord("S") @(26)=Ord("E") @(27)=Ord("L")   Proc _MutateDNA (P/L, P, 100) ' Now mutate the parent DNA Return
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion). The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition: Fn = Fn+2 - Fn+1, if n<0 support for negative     n     in the solution is optional. Related tasks   Fibonacci n-step number sequences‎   Leonardo numbers References   Wikipedia, Fibonacci number   Wikipedia, Lucas number   MathWorld, Fibonacci Number   Some identities for r-Fibonacci numbers   OEIS Fibonacci numbers   OEIS Lucas numbers
#PowerBASIC
PowerBASIC
actual: displayed: F(88) 1100087778366101931 1100087778366101930 F(89) 1779979416004714189 1779979416004714190 F(90) 2880067194370816120 2880067194370816120 F(91) 4660046610375530309 4660046610375530310 F(92) 7540113804746346429 7540113804746346430
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterative or recursive. Support for trapping negative   n   errors is optional. Related task   Primorial numbers
#FOCAL
FOCAL
1.1 F N=0,10; D 2 1.2 S N=-3; D 2 1.3 S N=100; D 2 1.4 S N=300; D 2 1.5 Q   2.1 I (N)3.1,4.1 2.2 S R=1 2.3 F I=1,N; S R=R*I 2.4 T "FACTORIAL OF ", %3.0, N, " IS ", %8.0, R, ! 2.9 R   3.1 T "N IS NEGATIVE" !; D 2.9   4.1 T "FACTORIAL OF 0 IS 1" !; D 2.9
http://rosettacode.org/wiki/Execute_Brain****
Execute Brain****
Execute Brain**** is an implementation of Brainf***. Other implementations of Brainf***. RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages. Below are links to each of the versions of RCBF. An implementation need only properly implement the following instructions: Command Description > Move the pointer to the right < Move the pointer to the left + Increment the memory cell under the pointer - Decrement the memory cell under the pointer . Output the character signified by the cell at the pointer , Input a character and store it in the cell at the pointer [ Jump past the matching ] if the cell under the pointer is 0 ] Jump back to the matching [ if the cell under the pointer is nonzero Any cell size is allowed,   EOF   (End-O-File)   support is optional, as is whether you have bounded or unbounded memory.
#UNIX_Shell
UNIX Shell
#!/usr/bin/env bash # BrainF*** interpreter in bash if (( ! $# )); then printf >&2 'Usage: %s program-file\n' "$0" exit 1 fi   # load the program exec 3<"$1" program=() while IFS= read -r line <&3; do mapfile -t instr < <(tr -cd '[]<>.,+-' <<<"$line" | sed $'s/./&\\\n/g') program+=("${instr[@]}") done exec 3<&-   # parse loops loops=() matches=() for pc in "${!program[@]}"; do instr=${program[pc]} if [[ $instr == '[' ]]; then loops=("$pc" "${loops[@]}") elif [[ $instr == ']' ]]; then matches[$pc]=${loops[0]} matches[${loops[0]}]=$pc loops=(${loops[@]:1}) fi done   # execute program memory=(0) mp=0 pc=0 while (( pc < ${#program[@]} )); do instr=${program[pc]} (( pc+=1 )) mem=${memory[mp]} case "$instr" in '[') if (( ! mem )); then (( pc=${matches[pc-1]}+1 )); fi;; ']') if (( mem )); then (( pc=${matches[pc-1]}+1 )); fi;; +) memory[mp]=$(( (mem + 1) % 256 ));; -) memory[mp]=$(( (mem - 1) % 256 ));; '>') (( mp+=1 )); if (( mp >= ${#memory[@]} )); then memory+=(0); fi;; '<') (( mp-=1 )); if (( mp < 0 )); then memory=(0 "${memory[@]}"); mp=0; fi;; .) printf %b $(printf '\\%03o' "$mem");; ,) read -n1 c; memory[mp]=$(LC_CTYPE=C printf '%d' "'$c");; esac done
http://rosettacode.org/wiki/Evolutionary_algorithm
Evolutionary algorithm
Starting with: The target string: "METHINKS IT IS LIKE A WEASEL". An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). A fitness function that computes the ‘closeness’ of its argument to the target string. A mutate function that given a string and a mutation rate returns a copy of the string, with some characters probably mutated. While the parent is not yet the target: copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Assess the fitness of the parent and all the copies to the target and make the most fit string the new parent, discarding the others. repeat until the parent converges, (hopefully), to the target. See also   Wikipedia entry:   Weasel algorithm.   Wikipedia entry:   Evolutionary algorithm. Note: to aid comparison, try and ensure the variables and functions mentioned in the task description appear in solutions A cursory examination of a few of the solutions reveals that the instructions have not been followed rigorously in some solutions. Specifically, While the parent is not yet the target: copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Note that some of the the solutions given retain characters in the mutated string that are correct in the target string. However, the instruction above does not state to retain any of the characters while performing the mutation. Although some may believe to do so is implied from the use of "converges" (:* repeat until the parent converges, (hopefully), to the target. Strictly speaking, the new parent should be selected from the new pool of mutations, and then the new parent used to generate the next set of mutations with parent characters getting retained only by not being mutated. It then becomes possible that the new set of mutations has no member that is fitter than the parent! As illustration of this error, the code for 8th has the following remark. Create a new string based on the TOS, changing randomly any characters which don't already match the target: NOTE: this has been changed, the 8th version is completely random now Clearly, this algo will be applying the mutation function only to the parent characters that don't match to the target characters! To ensure that the new parent is never less fit than the prior parent, both the parent and all of the latest mutations are subjected to the fitness test to select the next parent.
#Ursala
Ursala
#import std #import nat   rand_char = arc ' ABCDEFGHIJKLMNOPQRSTUVWXYZ'   target = 'METHINKS IT IS LIKE A WEASEL'   parent = rand_char* target   fitness = length+ (filter ~=)+ zip/target   mutate("string","rate") = "rate"%~?(rand_char,~&)* "string"   C = 32   evolve = @iiX ~&l->r @r -*iota(C); @lS nleq$-&l+ ^(fitness,~&)^*C/~&h mutate\*10   #cast %s   main = evolve parent
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion). The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition: Fn = Fn+2 - Fn+1, if n<0 support for negative     n     in the solution is optional. Related tasks   Fibonacci n-step number sequences‎   Leonardo numbers References   Wikipedia, Fibonacci number   Wikipedia, Lucas number   MathWorld, Fibonacci Number   Some identities for r-Fibonacci numbers   OEIS Fibonacci numbers   OEIS Lucas numbers
#PowerShell
PowerShell
  function FibonacciNumber ( $count ) { $answer = @(0,1) while ($answer.Length -le $count) { $answer += $answer[-1] + $answer[-2] } return $answer }  
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterative or recursive. Support for trapping negative   n   errors is optional. Related task   Primorial numbers
#Forth
Forth
: fac ( n -- n! ) 1 swap 1+ 1 ?do i * loop ;
http://rosettacode.org/wiki/Execute_Brain****
Execute Brain****
Execute Brain**** is an implementation of Brainf***. Other implementations of Brainf***. RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages. Below are links to each of the versions of RCBF. An implementation need only properly implement the following instructions: Command Description > Move the pointer to the right < Move the pointer to the left + Increment the memory cell under the pointer - Decrement the memory cell under the pointer . Output the character signified by the cell at the pointer , Input a character and store it in the cell at the pointer [ Jump past the matching ] if the cell under the pointer is 0 ] Jump back to the matching [ if the cell under the pointer is nonzero Any cell size is allowed,   EOF   (End-O-File)   support is optional, as is whether you have bounded or unbounded memory.
#VBScript
VBScript
'Execute BrainFuck 'VBScript Implementation 'The Main Interpreter Function BFInpt(s, sp, d, dp, i, ip, o) While sp < Len(s) Select Case Mid(s, sp + 1, 1) Case "+" newd = Asc(d(dp)) + 1 If newd > 255 Then newd = newd Mod 256 'To take account of values over 255 d(dp) = Chr(newd) Case "-" newd = Asc(d(dp)) - 1 If newd < 0 Then newd = (newd Mod 256) + 256 'To take account of negative values d(dp) = Chr(newd) Case ">" dp = dp + 1 If dp > UBound(d) Then ReDim Preserve d(UBound(d) + 1) d(dp) = Chr(0) End If Case "<" dp = dp - 1 Case "." o = o & d(dp) Case "," If ip = Len(i) Then d(dp) = Chr(0) Else ip = ip + 1 : d(dp) = Mid(i, ip, 1) Case "[" If Asc(d(dp)) = 0 Then bracket = 1 While bracket And sp < Len(s) sp = sp + 1 If Mid(s, sp + 1, 1) = "[" Then bracket = bracket + 1 ElseIf Mid(s, sp + 1, 1) = "]" Then bracket = bracket - 1 End If WEnd Else pos = sp - 1 sp = sp + 1 If BFInpt(s, sp, d, dp, i, ip, o) Then sp = pos End If Case "]" BFInpt = Asc(d(dp)) <> 0 Exit Function End Select sp = sp + 1 WEnd End Function   'This Prepares the Intepreter Function BFuck(source, input) Dim data() : ReDim data(0) data(0) = Chr(0) DataPtr = 0 SrcPtr = 0 InputPtr = 0 output = ""   BFInpt source , SrcPtr , _ data , DataPtr , _ input , InputPtr , _ output BFuck = output End Function     'Sample Run 'The input is a string. The first character will be scanned by the first comma 'in the code, the next character will be scanned by the next comma, and so on. code = ">++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.>" & _ ">+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++." inpstr = "" WScript.StdOut.Write BFuck(code, inpstr)
http://rosettacode.org/wiki/Evolutionary_algorithm
Evolutionary algorithm
Starting with: The target string: "METHINKS IT IS LIKE A WEASEL". An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). A fitness function that computes the ‘closeness’ of its argument to the target string. A mutate function that given a string and a mutation rate returns a copy of the string, with some characters probably mutated. While the parent is not yet the target: copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Assess the fitness of the parent and all the copies to the target and make the most fit string the new parent, discarding the others. repeat until the parent converges, (hopefully), to the target. See also   Wikipedia entry:   Weasel algorithm.   Wikipedia entry:   Evolutionary algorithm. Note: to aid comparison, try and ensure the variables and functions mentioned in the task description appear in solutions A cursory examination of a few of the solutions reveals that the instructions have not been followed rigorously in some solutions. Specifically, While the parent is not yet the target: copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Note that some of the the solutions given retain characters in the mutated string that are correct in the target string. However, the instruction above does not state to retain any of the characters while performing the mutation. Although some may believe to do so is implied from the use of "converges" (:* repeat until the parent converges, (hopefully), to the target. Strictly speaking, the new parent should be selected from the new pool of mutations, and then the new parent used to generate the next set of mutations with parent characters getting retained only by not being mutated. It then becomes possible that the new set of mutations has no member that is fitter than the parent! As illustration of this error, the code for 8th has the following remark. Create a new string based on the TOS, changing randomly any characters which don't already match the target: NOTE: this has been changed, the 8th version is completely random now Clearly, this algo will be applying the mutation function only to the parent characters that don't match to the target characters! To ensure that the new parent is never less fit than the prior parent, both the parent and all of the latest mutations are subjected to the fitness test to select the next parent.
#UTFool
UTFool
  ··· http://rosettacode.org/wiki/Evolutionary_algorithm ··· ■ Evolutionary § static target⦂ String: "METHINKS IT IS LIKE A WEASEL" letter⦂ char[]: "ABCDEFGHIJKLMNOPQRSTUVWXYZ ".toCharArray° parent⦂ String random⦂ java.util.Random° rate⦂ double: 0.5 C⦂ int: 1000   ▶ fittness⦂ int · computes the 'closeness' of its • argument⦂ String · to the target string closeness⦂ int: 0 ∀ i ∈ 0 … target.length° closeness◥ if target.charAt i = argument.charAt i return closeness   ▶ mutate⦂ String · returns a copy of the • given⦂ String · with some characters probably mutated • rate⦂ double copy⦂ char[]: given.toCharArray° ∀ i ∈ 0 … given.length° copy[i]: letter[random.nextInt letter.length] if rate > random.nextDouble° return String.valueOf copy   ▶ main • args⦂ String[] ancest⦂ StringBuilder° ∀ i ∈ 0 … target.length° ancest.append letter[random.nextInt letter.length] parent: ancest.toString° currentFittness⦂ int: fittness parent generation⦂ int: 0 🔁 until the parent ≈ target if fittness parent > currentFittness currentFittness: fittness parent System.out.println "Fittness of generation #⸨generation⸩ is ⸨currentFittness⸩" for each time from 1 to C mutation⦂ String: mutate parent, rate parent: mutation if fittness parent < fittness mutation generation◥ System.out.println "Target reached by generation #⸨generation⸩"  
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion). The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition: Fn = Fn+2 - Fn+1, if n<0 support for negative     n     in the solution is optional. Related tasks   Fibonacci n-step number sequences‎   Leonardo numbers References   Wikipedia, Fibonacci number   Wikipedia, Lucas number   MathWorld, Fibonacci Number   Some identities for r-Fibonacci numbers   OEIS Fibonacci numbers   OEIS Lucas numbers
#Processing
Processing
void setup() { size(400, 400); fill(255, 64); frameRate(2); } void draw() { int num = fibonacciNum(frameCount); println(frameCount, num); rect(0,0,num, num); if(frameCount==14) frameCount = -1; // restart } int fibonacciNum(int n) { return (n < 2) ? n : fibonacciNum(n - 1) + fibonacciNum(n - 2); }
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterative or recursive. Support for trapping negative   n   errors is optional. Related task   Primorial numbers
#Fortran
Fortran
nfactorial = PRODUCT((/(i, i=1,n)/))
http://rosettacode.org/wiki/Execute_Brain****
Execute Brain****
Execute Brain**** is an implementation of Brainf***. Other implementations of Brainf***. RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages. Below are links to each of the versions of RCBF. An implementation need only properly implement the following instructions: Command Description > Move the pointer to the right < Move the pointer to the left + Increment the memory cell under the pointer - Decrement the memory cell under the pointer . Output the character signified by the cell at the pointer , Input a character and store it in the cell at the pointer [ Jump past the matching ] if the cell under the pointer is 0 ] Jump back to the matching [ if the cell under the pointer is nonzero Any cell size is allowed,   EOF   (End-O-File)   support is optional, as is whether you have bounded or unbounded memory.
#Vlang
Vlang
fn main() { // example program is current Brain**** solution to // Hello world/Text task. only requires 10 bytes of data store! bf(10, '++++++++++[>+>+++>++++>+++++++>++++++++>+++++++++>++ ++++++++>+++++++++++>++++++++++++<<<<<<<<<-]>>>>+.>>> >+..<.<++++++++.>>>+.<<+.<<<<++++.<++.>>>+++++++.>>>.+++. <+++++++.--------.<<<<<+.<+++.---.') }   fn bf(d_len int, code string) { mut ds := []u8{len: d_len} // data store mut dp := 0 // data pointer for ip := 0; ip < code.len; ip++ { match code[ip] { `>` { dp++ } `<` { dp-- } `+` { ds[dp]++ } `-` { ds[dp]-- } `.` { print(ds[dp].ascii_str()) } `,` { //fmt.Scanf("%c", &ds[dp]) ds[dp] = -1 //TODO } `[` { if ds[dp] == 0 { for nc := 1; nc > 0; { ip++ if code[ip] == `[` { nc++ } else if code[ip] == `]` { nc-- } } } } `]` { if ds[dp] != 0 { for nc := 1; nc > 0; { ip-- if code[ip] == `]` { nc++ } else if code[ip] == `[` { nc-- } } } } else {} } } }
http://rosettacode.org/wiki/Evolutionary_algorithm
Evolutionary algorithm
Starting with: The target string: "METHINKS IT IS LIKE A WEASEL". An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). A fitness function that computes the ‘closeness’ of its argument to the target string. A mutate function that given a string and a mutation rate returns a copy of the string, with some characters probably mutated. While the parent is not yet the target: copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Assess the fitness of the parent and all the copies to the target and make the most fit string the new parent, discarding the others. repeat until the parent converges, (hopefully), to the target. See also   Wikipedia entry:   Weasel algorithm.   Wikipedia entry:   Evolutionary algorithm. Note: to aid comparison, try and ensure the variables and functions mentioned in the task description appear in solutions A cursory examination of a few of the solutions reveals that the instructions have not been followed rigorously in some solutions. Specifically, While the parent is not yet the target: copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Note that some of the the solutions given retain characters in the mutated string that are correct in the target string. However, the instruction above does not state to retain any of the characters while performing the mutation. Although some may believe to do so is implied from the use of "converges" (:* repeat until the parent converges, (hopefully), to the target. Strictly speaking, the new parent should be selected from the new pool of mutations, and then the new parent used to generate the next set of mutations with parent characters getting retained only by not being mutated. It then becomes possible that the new set of mutations has no member that is fitter than the parent! As illustration of this error, the code for 8th has the following remark. Create a new string based on the TOS, changing randomly any characters which don't already match the target: NOTE: this has been changed, the 8th version is completely random now Clearly, this algo will be applying the mutation function only to the parent characters that don't match to the target characters! To ensure that the new parent is never less fit than the prior parent, both the parent and all of the latest mutations are subjected to the fitness test to select the next parent.
#vbscript
vbscript
  'This is the string we want to "evolve" to. Any string of any length will 'do as long as it consists only of upper case letters and spaces.   Target = "METHINKS IT IS LIKE A WEASEL"   'This is the pool of letters that will be selected at random for a mutation   letters = " ABCDEFGHIJKLMNOPQRSTUVWXYZ"   'A mutation rate of 0.5 means that there is a 50% chance that one letter 'will be mutated at random in the next child   mutation_rate = 0.5   'Set for 10 children per generation   Dim child(10)   'Generate the first guess as random letters   Randomize Parent = ""   for i = 1 to len(Target) Parent = Parent & Mid(letters,Random(1,Len(letters)),1) next   gen = 0   Do bestfit = 0 bestind = 0   gen = gen + 1   'make n copies of the current string and find the one 'that best matches the target string   For i = 0 to ubound(child)   child(i) = Mutate(Parent, mutation_rate)   fit = Fitness(Target, child(i))   If fit > bestfit Then bestfit = fit bestind = i End If   Next   'Select the child that has the best fit with the target string   Parent = child(bestind) Wscript.Echo parent, "(fit=" & bestfit & ")"   Loop Until Parent = Target   Wscript.Echo vbcrlf & "Generations = " & gen   'apply a random mutation to a random character in a string   Function Mutate ( ByVal str , ByVal rate )   Dim pos 'a random position in the string' Dim ltr 'a new letter chosen at random '   If rate > Rnd(1) Then   ltr = Mid(letters,Random(1,len(letters)),1) pos = Random(1,len(str)) str = Left(str, pos - 1) & ltr & Mid(str, pos + 1)   End If   Mutate = str   End Function   'returns the number of letters in the two strings that match   Function Fitness (ByVal str , ByVal ref )   Dim i   Fitness = 0   For i = 1 To Len(str) If Mid(str, i, 1) = Mid(ref, i, 1) Then Fitness = Fitness + 1 Next   End Function   'Return a random integer in the range lower to upper (inclusive)   Private Function Random ( lower , upper ) Random = Int((upper - lower + 1) * Rnd + lower) End Function
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion). The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition: Fn = Fn+2 - Fn+1, if n<0 support for negative     n     in the solution is optional. Related tasks   Fibonacci n-step number sequences‎   Leonardo numbers References   Wikipedia, Fibonacci number   Wikipedia, Lucas number   MathWorld, Fibonacci Number   Some identities for r-Fibonacci numbers   OEIS Fibonacci numbers   OEIS Lucas numbers
#Prolog
Prolog
  fib(1, 1) :- !. fib(0, 0) :- !. fib(N, Value) :- A is N - 1, fib(A, A1), B is N - 2, fib(B, B1), Value is A1 + B1.  
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterative or recursive. Support for trapping negative   n   errors is optional. Related task   Primorial numbers
#FPr
FPr
fact==((1&),iota)\(1*2)&
http://rosettacode.org/wiki/Execute_Brain****
Execute Brain****
Execute Brain**** is an implementation of Brainf***. Other implementations of Brainf***. RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages. Below are links to each of the versions of RCBF. An implementation need only properly implement the following instructions: Command Description > Move the pointer to the right < Move the pointer to the left + Increment the memory cell under the pointer - Decrement the memory cell under the pointer . Output the character signified by the cell at the pointer , Input a character and store it in the cell at the pointer [ Jump past the matching ] if the cell under the pointer is 0 ] Jump back to the matching [ if the cell under the pointer is nonzero Any cell size is allowed,   EOF   (End-O-File)   support is optional, as is whether you have bounded or unbounded memory.
#Wren
Wren
import "io" for Stdin   class Brainf__k { construct new(prog, memSize) { _prog = prog _memSize = memSize _mem = List.filled(memSize, 0) _ip = 0 _dp = 0 }   memVal_ { (_dp >= 0 && _dp < _memSize) ? _mem[_dp] : 0 }   execute() { while (_ip < _prog.count) { var cmd = _prog[_ip] _ip = _ip + 1 if (cmd == ">") { _dp = _dp + 1 } else if (cmd == "<") { _dp = _dp - 1 } else if (cmd == "+") { _mem[_dp] = memVal_ + 1 } else if (cmd == "-") { _mem[_dp] = memVal_ - 1 } else if (cmd == ",") { _mem[_dp] = Stdin.readByte() } else if (cmd == ".") { System.write(String.fromByte(memVal_)) } else if (cmd == "[") { handleLoopStart_() } else if (cmd == "]") { handleLoopEnd_() } } }   handleLoopStart_() { if (memVal_ != 0) return var depth = 1 while (_ip < _prog.count) { var cmd = _prog[_ip] _ip = _ip + 1 if (cmd == "[") { depth = depth + 1 } else if (cmd == "]") { depth = depth - 1 if (depth == 0) return } } Fiber.abort("Could not find matching end bracket.") }   handleLoopEnd_() { var depth = 0 while (_ip >= 0) { _ip = _ip - 1 var cmd = _prog[_ip] if (cmd == "]") { depth = depth + 1 } else if (cmd == "[") { depth = depth - 1 if (depth == 0) return } } Fiber.abort("Could not find matching start bracket.") } }   var prog = "++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>." Brainf__k.new(prog, 10).execute()
http://rosettacode.org/wiki/Evolutionary_algorithm
Evolutionary algorithm
Starting with: The target string: "METHINKS IT IS LIKE A WEASEL". An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). A fitness function that computes the ‘closeness’ of its argument to the target string. A mutate function that given a string and a mutation rate returns a copy of the string, with some characters probably mutated. While the parent is not yet the target: copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Assess the fitness of the parent and all the copies to the target and make the most fit string the new parent, discarding the others. repeat until the parent converges, (hopefully), to the target. See also   Wikipedia entry:   Weasel algorithm.   Wikipedia entry:   Evolutionary algorithm. Note: to aid comparison, try and ensure the variables and functions mentioned in the task description appear in solutions A cursory examination of a few of the solutions reveals that the instructions have not been followed rigorously in some solutions. Specifically, While the parent is not yet the target: copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Note that some of the the solutions given retain characters in the mutated string that are correct in the target string. However, the instruction above does not state to retain any of the characters while performing the mutation. Although some may believe to do so is implied from the use of "converges" (:* repeat until the parent converges, (hopefully), to the target. Strictly speaking, the new parent should be selected from the new pool of mutations, and then the new parent used to generate the next set of mutations with parent characters getting retained only by not being mutated. It then becomes possible that the new set of mutations has no member that is fitter than the parent! As illustration of this error, the code for 8th has the following remark. Create a new string based on the TOS, changing randomly any characters which don't already match the target: NOTE: this has been changed, the 8th version is completely random now Clearly, this algo will be applying the mutation function only to the parent characters that don't match to the target characters! To ensure that the new parent is never less fit than the prior parent, both the parent and all of the latest mutations are subjected to the fitness test to select the next parent.
#Visual_Basic
Visual Basic
      Option Explicit   Private Sub Main() Dim Target Dim Parent Dim mutation_rate Dim children Dim bestfitness Dim bestindex Dim Index Dim fitness   Target = "METHINKS IT IS LIKE A WEASEL" Parent = "IU RFSGJABGOLYWF XSMFXNIABKT" mutation_rate = 0.5 children = 10 ReDim child(children)   Do bestfitness = 0 bestindex = 0 For Index = 1 To children child(Index) = FNmutate(Parent, mutation_rate, Target) fitness = FNfitness(Target, child(Index)) If fitness > bestfitness Then bestfitness = fitness bestindex = Index End If Next Index   Parent = child(bestindex) Debug.Print Parent Loop Until Parent = Target End     End Sub   Function FNmutate(Text, Rate, ref) Dim C As Integer Dim Aux As Integer   If Rate > Rnd(1) Then C = 63 + 27 * Rnd() + 1 If C = 64 Then C = 32 Aux = Len(Text) * Rnd() + 1 If Mid(Text, Aux, 1) <> Mid(ref, Aux, 1) Then Text = Left(Text, Aux - 1) & Chr(C) & Mid(Text, Aux + 1) End If   End If FNmutate = Text End Function Function FNfitness(Text, ref) Dim I, F For I = 1 To Len(Text) If Mid(Text, I, 1) = Mid(ref, I, 1) Then F = F + 1 Next FNfitness = F / Len(Text) End Function  
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion). The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition: Fn = Fn+2 - Fn+1, if n<0 support for negative     n     in the solution is optional. Related tasks   Fibonacci n-step number sequences‎   Leonardo numbers References   Wikipedia, Fibonacci number   Wikipedia, Lucas number   MathWorld, Fibonacci Number   Some identities for r-Fibonacci numbers   OEIS Fibonacci numbers   OEIS Lucas numbers
#Pure
Pure
fib n = loop 0 1 n with loop a b n = if n==0 then a else loop b (a+b) (n-1); end;
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterative or recursive. Support for trapping negative   n   errors is optional. Related task   Primorial numbers
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Function Factorial_Iterative(n As Integer) As Integer Var result = 1 For i As Integer = 2 To n result *= i Next Return result End Function   Function Factorial_Recursive(n As Integer) As Integer If n = 0 Then Return 1 Return n * Factorial_Recursive(n - 1) End Function   For i As Integer = 1 To 5 Print i; " =>"; Factorial_Iterative(i) Next   For i As Integer = 6 To 10 Print Using "##"; i; Print " =>"; Factorial_Recursive(i) Next   Print Print "Press any key to quit" Sleep
http://rosettacode.org/wiki/Execute_Brain****
Execute Brain****
Execute Brain**** is an implementation of Brainf***. Other implementations of Brainf***. RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages. Below are links to each of the versions of RCBF. An implementation need only properly implement the following instructions: Command Description > Move the pointer to the right < Move the pointer to the left + Increment the memory cell under the pointer - Decrement the memory cell under the pointer . Output the character signified by the cell at the pointer , Input a character and store it in the cell at the pointer [ Jump past the matching ] if the cell under the pointer is 0 ] Jump back to the matching [ if the cell under the pointer is nonzero Any cell size is allowed,   EOF   (End-O-File)   support is optional, as is whether you have bounded or unbounded memory.
#x86_Assembly
x86 Assembly
#> newsyntax @in:PE @token:bf @PE:"function(Stack){ this.TestNext(Stack,\"Paren\",\"TK_POPEN\"); this.Move(Stack,2); let Check = function(t,v){ return AST.IsPreciseToken(Stack.Token,t,v); } let Write = function(v){ AST.ChunkWrite(Stack,v); } this.OpenChunk(Stack); while(!this.IsPreciseToken(Stack.Token,\"Paren\",\"TK_PCLOSE\")){ if(Check(\"None\",\"TK_DOT\")){ Write(\"output\"); }else if(Check(\"None\",\"TK_COMMA\")){ Write(\"input\"); }else if(Check(\"Operator\",\"TK_ADD\")){ Write(\"inc\"); }else if(Check(\"Operator\",\"TK_SUB\")){ Write(\"deinc\"); }else if(Check(\"Compare\",\"TK_GT\")){ Write(\"meminc\"); }else if(Check(\"Compare\",\"TK_LT\")){ Write(\"memdeinc\"); }else if(Check(\"Brace\",\"TK_IOPEN\")){ this.OpenChunk(Stack); }else if(Check(\"Brace\",\"TK_ICLOSE\")){ this.CloseChunk(Stack); } this.Next(Stack); } this.CloseChunk(Stack); if(!this.CheckNext(Stack,\"None\",\"TK_LINEEND\")&&!this.CheckNext(Stack,\"None\",\"TK_COMMA\")){ this.Next(Stack); this.ChunkWrite(Stack,this.ParseExpression(Stack)); } }" @Interpret:"function(AST,Token){ let BF = Token[3]; let Chunk = BF[0]; let Input = BF[1]; if(Input){ Input=this.Parse(AST,Input); } let IPos=0; let Memory = [],MemPos=0; let UpdateMemory = function(){ if(Memory[MemPos]===undefined){ Memory[MemPos]=0; } } let Read = function(v){ if(v==\"output\"){ AST.LibGlobals.log(Memory[MemPos]); }else if(v==\"input\"){ Memory[MemPos]=Input.charCodeAt(IPos)||0; IPos++; }else if(v==\"inc\"){ UpdateMemory(); Memory[MemPos]++; }else if(v==\"deinc\"){ UpdateMemory(); Memory[MemPos]--; }else if(v==\"meminc\"){ MemPos++; UpdateMemory(); }else if(v==\"memdeinc\"){ MemPos--; UpdateMemory(); }else if(v instanceof Array){ UpdateMemory(); while(Memory[MemPos]!=0){ for(let vv of v){ Read(vv); } UpdateMemory(); } } } UpdateMemory(); for(let v of Chunk){ Read(v); } UpdateMemory(); return Memory[MemPos]; }" <#   set x = bf ( + + + > + + [ < + > - ] < ); log(x);
http://rosettacode.org/wiki/Evolutionary_algorithm
Evolutionary algorithm
Starting with: The target string: "METHINKS IT IS LIKE A WEASEL". An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). A fitness function that computes the ‘closeness’ of its argument to the target string. A mutate function that given a string and a mutation rate returns a copy of the string, with some characters probably mutated. While the parent is not yet the target: copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Assess the fitness of the parent and all the copies to the target and make the most fit string the new parent, discarding the others. repeat until the parent converges, (hopefully), to the target. See also   Wikipedia entry:   Weasel algorithm.   Wikipedia entry:   Evolutionary algorithm. Note: to aid comparison, try and ensure the variables and functions mentioned in the task description appear in solutions A cursory examination of a few of the solutions reveals that the instructions have not been followed rigorously in some solutions. Specifically, While the parent is not yet the target: copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Note that some of the the solutions given retain characters in the mutated string that are correct in the target string. However, the instruction above does not state to retain any of the characters while performing the mutation. Although some may believe to do so is implied from the use of "converges" (:* repeat until the parent converges, (hopefully), to the target. Strictly speaking, the new parent should be selected from the new pool of mutations, and then the new parent used to generate the next set of mutations with parent characters getting retained only by not being mutated. It then becomes possible that the new set of mutations has no member that is fitter than the parent! As illustration of this error, the code for 8th has the following remark. Create a new string based on the TOS, changing randomly any characters which don't already match the target: NOTE: this has been changed, the 8th version is completely random now Clearly, this algo will be applying the mutation function only to the parent characters that don't match to the target characters! To ensure that the new parent is never less fit than the prior parent, both the parent and all of the latest mutations are subjected to the fitness test to select the next parent.
#Vlang
Vlang
import rand import rand.seed const target = "METHINKS IT IS LIKE A WEASEL".bytes() const set = "ABCDEFGHIJKLMNOPQRSTUVWXYZ ".bytes()       fn initialize() []u8 { rand.seed(seed.time_seed_array(2)) mut parent := []u8{len: target.len} for i in 0..parent.len { parent[i] = set[rand.intn(set.len) or {0}] } return parent }   // fitness: 0 is perfect fit. greater numbers indicate worse fit. fn fitness(a []u8) int { mut h := 0 // (hamming distance) for i, tc in target { if a[i] != tc { h++ } } return h }   // set m to mutation of p, with each character of p mutated with probability r fn mutate(p []u8, mut m []u8, r f64) { for i, ch in p { if rand.f64() < r { m[i] = set[rand.intn(set.len) or {0}] } else { m[i] = ch } } }   fn main() { c := 20 // number of times to copy and mutate parent   mut parent := initialize() mut copies := [][]u8{len: c, init: []u8{len: parent.len}}   println(parent.bytestr()) for best := fitness(parent); best > 0; { for mut cp in copies { mutate(parent, mut cp, .05) } for cp in copies { fm := fitness(cp) if fm < best { best = fm parent = cp.clone() println(parent.bytestr()) } } } }
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion). The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition: Fn = Fn+2 - Fn+1, if n<0 support for negative     n     in the solution is optional. Related tasks   Fibonacci n-step number sequences‎   Leonardo numbers References   Wikipedia, Fibonacci number   Wikipedia, Lucas number   MathWorld, Fibonacci Number   Some identities for r-Fibonacci numbers   OEIS Fibonacci numbers   OEIS Lucas numbers
#PureBasic
PureBasic
Macro Fibonacci (n) Int((Pow(((1+Sqr(5))/2),n)-Pow(((1-Sqr(5))/2),n))/Sqr(5)) EndMacro
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterative or recursive. Support for trapping negative   n   errors is optional. Related task   Primorial numbers
#friendly_interactive_shell
friendly interactive shell
  function factorial set x $argv[1] set result 1 for i in (seq $x) set result (expr $i '*' $result) end echo $result end  
http://rosettacode.org/wiki/Execute_Brain****
Execute Brain****
Execute Brain**** is an implementation of Brainf***. Other implementations of Brainf***. RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages. Below are links to each of the versions of RCBF. An implementation need only properly implement the following instructions: Command Description > Move the pointer to the right < Move the pointer to the left + Increment the memory cell under the pointer - Decrement the memory cell under the pointer . Output the character signified by the cell at the pointer , Input a character and store it in the cell at the pointer [ Jump past the matching ] if the cell under the pointer is 0 ] Jump back to the matching [ if the cell under the pointer is nonzero Any cell size is allowed,   EOF   (End-O-File)   support is optional, as is whether you have bounded or unbounded memory.
#XBS
XBS
#> newsyntax @in:PE @token:bf @PE:"function(Stack){ this.TestNext(Stack,\"Paren\",\"TK_POPEN\"); this.Move(Stack,2); let Check = function(t,v){ return AST.IsPreciseToken(Stack.Token,t,v); } let Write = function(v){ AST.ChunkWrite(Stack,v); } this.OpenChunk(Stack); while(!this.IsPreciseToken(Stack.Token,\"Paren\",\"TK_PCLOSE\")){ if(Check(\"None\",\"TK_DOT\")){ Write(\"output\"); }else if(Check(\"None\",\"TK_COMMA\")){ Write(\"input\"); }else if(Check(\"Operator\",\"TK_ADD\")){ Write(\"inc\"); }else if(Check(\"Operator\",\"TK_SUB\")){ Write(\"deinc\"); }else if(Check(\"Compare\",\"TK_GT\")){ Write(\"meminc\"); }else if(Check(\"Compare\",\"TK_LT\")){ Write(\"memdeinc\"); }else if(Check(\"Brace\",\"TK_IOPEN\")){ this.OpenChunk(Stack); }else if(Check(\"Brace\",\"TK_ICLOSE\")){ this.CloseChunk(Stack); } this.Next(Stack); } this.CloseChunk(Stack); if(!this.CheckNext(Stack,\"None\",\"TK_LINEEND\")&&!this.CheckNext(Stack,\"None\",\"TK_COMMA\")){ this.Next(Stack); this.ChunkWrite(Stack,this.ParseExpression(Stack)); } }" @Interpret:"function(AST,Token){ let BF = Token[3]; let Chunk = BF[0]; let Input = BF[1]; if(Input){ Input=this.Parse(AST,Input); } let IPos=0; let Memory = [],MemPos=0; let UpdateMemory = function(){ if(Memory[MemPos]===undefined){ Memory[MemPos]=0; } } let Read = function(v){ if(v==\"output\"){ AST.LibGlobals.log(Memory[MemPos]); }else if(v==\"input\"){ Memory[MemPos]=Input.charCodeAt(IPos)||0; IPos++; }else if(v==\"inc\"){ UpdateMemory(); Memory[MemPos]++; }else if(v==\"deinc\"){ UpdateMemory(); Memory[MemPos]--; }else if(v==\"meminc\"){ MemPos++; UpdateMemory(); }else if(v==\"memdeinc\"){ MemPos--; UpdateMemory(); }else if(v instanceof Array){ UpdateMemory(); while(Memory[MemPos]!=0){ for(let vv of v){ Read(vv); } UpdateMemory(); } } } UpdateMemory(); for(let v of Chunk){ Read(v); } UpdateMemory(); return Memory[MemPos]; }" <#   set x = bf ( + + + > + + [ < + > - ] < ); log(x);
http://rosettacode.org/wiki/Evolutionary_algorithm
Evolutionary algorithm
Starting with: The target string: "METHINKS IT IS LIKE A WEASEL". An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). A fitness function that computes the ‘closeness’ of its argument to the target string. A mutate function that given a string and a mutation rate returns a copy of the string, with some characters probably mutated. While the parent is not yet the target: copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Assess the fitness of the parent and all the copies to the target and make the most fit string the new parent, discarding the others. repeat until the parent converges, (hopefully), to the target. See also   Wikipedia entry:   Weasel algorithm.   Wikipedia entry:   Evolutionary algorithm. Note: to aid comparison, try and ensure the variables and functions mentioned in the task description appear in solutions A cursory examination of a few of the solutions reveals that the instructions have not been followed rigorously in some solutions. Specifically, While the parent is not yet the target: copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Note that some of the the solutions given retain characters in the mutated string that are correct in the target string. However, the instruction above does not state to retain any of the characters while performing the mutation. Although some may believe to do so is implied from the use of "converges" (:* repeat until the parent converges, (hopefully), to the target. Strictly speaking, the new parent should be selected from the new pool of mutations, and then the new parent used to generate the next set of mutations with parent characters getting retained only by not being mutated. It then becomes possible that the new set of mutations has no member that is fitter than the parent! As illustration of this error, the code for 8th has the following remark. Create a new string based on the TOS, changing randomly any characters which don't already match the target: NOTE: this has been changed, the 8th version is completely random now Clearly, this algo will be applying the mutation function only to the parent characters that don't match to the target characters! To ensure that the new parent is never less fit than the prior parent, both the parent and all of the latest mutations are subjected to the fitness test to select the next parent.
#Wren
Wren
import "random" for Random   var target = "METHINKS IT IS LIKE A WEASEL" var set = "ABCDEFGHIJKLMNOPQRSTUVWXYZ " var rand = Random.new()   // fitness: 0 is perfect fit. greater numbers indicate worse fit. var fitness = Fn.new { |a| (0...target.count).count { |i| a[i] != target[i] } }   // set m to mutation of p, with each character of p mutated with probability r var mutate = Fn.new { |p, m, r| var i = 0 for (ch in p) { if (rand.float(1) < r) { m[i] = set[rand.int(set.count)] } else { m[i] = ch } i = i + 1 } }   var parent = List.filled(target.count, "") (0...parent.count).each { |i| parent[i] = set[rand.int(set.count)] } var c = 20 // number of times to copy and mutate parent var copies = List.filled(c, null) for (i in 0...c) copies[i] = List.filled(parent.count, 0) System.print(parent.join()) var best = fitness.call(parent) while (best > 0) { for (cp in copies) mutate.call(parent, cp, 0.05) for (cp in copies) { var fm = fitness.call(cp) if (fm < best) { best = fm parent = cp.toList System.print(parent.join()) } } }
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion). The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition: Fn = Fn+2 - Fn+1, if n<0 support for negative     n     in the solution is optional. Related tasks   Fibonacci n-step number sequences‎   Leonardo numbers References   Wikipedia, Fibonacci number   Wikipedia, Lucas number   MathWorld, Fibonacci Number   Some identities for r-Fibonacci numbers   OEIS Fibonacci numbers   OEIS Lucas numbers
#Purity
Purity
  data Fib1 = FoldNat < const (Cons One (Cons One Empty)), (uncurry Cons) . ((uncurry Add) . (Head, Head . Tail), id) >  
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterative or recursive. Support for trapping negative   n   errors is optional. Related task   Primorial numbers
#Frink
Frink
  // Calculate factorial with math operator x = 5 println[x!]   // Calculate factorial with built-in function println[factorial[x]]  
http://rosettacode.org/wiki/Execute_Brain****
Execute Brain****
Execute Brain**** is an implementation of Brainf***. Other implementations of Brainf***. RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages. Below are links to each of the versions of RCBF. An implementation need only properly implement the following instructions: Command Description > Move the pointer to the right < Move the pointer to the left + Increment the memory cell under the pointer - Decrement the memory cell under the pointer . Output the character signified by the cell at the pointer , Input a character and store it in the cell at the pointer [ Jump past the matching ] if the cell under the pointer is 0 ] Jump back to the matching [ if the cell under the pointer is nonzero Any cell size is allowed,   EOF   (End-O-File)   support is optional, as is whether you have bounded or unbounded memory.
#zkl
zkl
fcn bf(pgm,input=""){ pgm=pgm.text; // handle both String and Data const CELLS=0d30_000; if(Void==pgm.span("[","]")){ println("Mismatched brackets"); return(); } fcn(code,z,jmpTable){ // build jump table (for [ & ]) if(span:=code.span("[","]")){ a,b:=span; b+=a-1; jmpTable[a+z]=b+z; jmpTable[b+z]=a+z; self.fcn(code[a+1,b-a-1],z+a+1,jmpTable); self.fcn(code[b+1,*],z+b+1,jmpTable); } }(pgm,0,jmpTable:=Dictionary());   tape:=CELLS.pump(Data(CELLS,Int),0); ip:=dp:=0; input=input.walker(); try{ while(1){ switch(pgm[ip]){ case(">"){ dp+=1 } case("<"){ dp-=1 } case("+"){ tape[dp]=tape[dp]+1 } case("-"){ tape[dp]=tape[dp]-1 } case("."){ tape[dp].toChar().print() } case(","){ c:=input._next(); tape[dp]=(c and input.value or 0); } case("["){ if(0==tape[dp]){ ip=jmpTable[ip] }} case("]"){ if(tape[dp]) { ip=jmpTable[ip] }} } ip+=1; } // while }catch(IndexError){} // read past end of tape == end of program }
http://rosettacode.org/wiki/Evolutionary_algorithm
Evolutionary algorithm
Starting with: The target string: "METHINKS IT IS LIKE A WEASEL". An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). A fitness function that computes the ‘closeness’ of its argument to the target string. A mutate function that given a string and a mutation rate returns a copy of the string, with some characters probably mutated. While the parent is not yet the target: copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Assess the fitness of the parent and all the copies to the target and make the most fit string the new parent, discarding the others. repeat until the parent converges, (hopefully), to the target. See also   Wikipedia entry:   Weasel algorithm.   Wikipedia entry:   Evolutionary algorithm. Note: to aid comparison, try and ensure the variables and functions mentioned in the task description appear in solutions A cursory examination of a few of the solutions reveals that the instructions have not been followed rigorously in some solutions. Specifically, While the parent is not yet the target: copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Note that some of the the solutions given retain characters in the mutated string that are correct in the target string. However, the instruction above does not state to retain any of the characters while performing the mutation. Although some may believe to do so is implied from the use of "converges" (:* repeat until the parent converges, (hopefully), to the target. Strictly speaking, the new parent should be selected from the new pool of mutations, and then the new parent used to generate the next set of mutations with parent characters getting retained only by not being mutated. It then becomes possible that the new set of mutations has no member that is fitter than the parent! As illustration of this error, the code for 8th has the following remark. Create a new string based on the TOS, changing randomly any characters which don't already match the target: NOTE: this has been changed, the 8th version is completely random now Clearly, this algo will be applying the mutation function only to the parent characters that don't match to the target characters! To ensure that the new parent is never less fit than the prior parent, both the parent and all of the latest mutations are subjected to the fitness test to select the next parent.
#XPL0
XPL0
include c:\cxpl\codes; \intrinsic code declarations string 0; \use zero-terminated convention (instead of MSb)   def MutateRate = 15, \1 chance in 15 of a mutation Copies = 30; \number of mutated copies char Target, AlphaTbl; int SizeOfAlpha;     func StrLen(Str); \Return the number of characters in a string char Str; int I; for I:= 0 to -1>>1-1 do if Str(I) = 0 then return I;     func Unfitness(A, B); \Return number of characters different between A and B char A, B; int I, C; [C:= 0; for I:= 0 to StrLen(A)-1 do if A(I) # B(I) then C:= C+1; return C; ]; \Unfitness     proc Mutate(A, B); \Copy string A to B, but with each character of B having char A, B; \ a 1 in MutateRate chance of differing from A int I; [for I:= 0 to StrLen(A)-1 do B(I):= if Ran(MutateRate) then A(I) else AlphaTbl(Ran(SizeOfAlpha)); B(I):= 0; \terminate string ]; \Mutate     int I, BestI, Diffs, Best, Iter; def SizeOfTarget = 28; char Specimen(Copies, SizeOfTarget+1); int ISpecimen, Temp;   [Target:= "METHINKS IT IS LIKE A WEASEL"; AlphaTbl:= "ABCDEFGHIJKLMNOPQRSTUVWXYZ "; SizeOfAlpha:= StrLen(AlphaTbl); ISpecimen:= Specimen; \integer accesses pointers rather than bytes   \Initialize first Specimen, the parent, to a random string for I:= 0 to SizeOfTarget-1 do Specimen(0,I):= AlphaTbl(Ran(SizeOfAlpha)); Specimen(0,I):= 0; \terminate string   Iter:= 0; repeat for I:= 1 to Copies-1 do Mutate(ISpecimen(0), ISpecimen(I));   Best:= SizeOfTarget; \find best matching string for I:= 0 to Copies-1 do [Diffs:= Unfitness(Target, ISpecimen(I)); if Diffs < Best then [Best:= Diffs; BestI:= I]; ]; if BestI \#0\ then \swap best string with first string [Temp:= ISpecimen(0); ISpecimen(0):= ISpecimen(BestI); ISpecimen(BestI):= Temp; ]; Text(0, "Iter "); IntOut(0, Iter); Text(0, " Score "); IntOut(0, Best); Text(0, ": "); Text(0, ISpecimen(0)); CrLf(0); Iter:= Iter+1; until Best = 0; ]