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.
| #Kotlin | Kotlin | import java.util.*
val target = "METHINKS IT IS LIKE A WEASEL"
val validChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ "
val random = Random()
fun randomChar() = validChars[random.nextInt(validChars.length)]
fun hammingDistance(s1: String, s2: String) =
s1.zip(s2).map { if (it.first == it.second) 0 else 1 }.sum()
fun fitness(s1: String) = target.length - hammingDistance(s1, target)
fun mutate(s1: String, mutationRate: Double) =
s1.map { if (random.nextDouble() > mutationRate) it else randomChar() }
.joinToString(separator = "")
fun main(args: Array<String>) {
val initialString = (0 until target.length).map { randomChar() }.joinToString(separator = "")
println(initialString)
println(mutate(initialString, 0.2))
val mutationRate = 0.05
val childrenPerGen = 50
var i = 0
var currVal = initialString
while (currVal != target) {
i += 1
currVal = (0..childrenPerGen).map { mutate(currVal, mutationRate) }.maxBy { fitness(it) }!!
}
println("Evolution found target after $i generations")
} |
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
| #MIPS_Assembly | MIPS Assembly |
.text
main: li $v0, 5 # read integer from input. The read integer will be stroed in $v0
syscall
beq $v0, 0, is1
beq $v0, 1, is1
li $s4, 1 # the counter which has to equal to $v0
li $s0, 1
li $s1, 1
loop: add $s2, $s0, $s1
addi $s4, $s4, 1
beq $v0, $s4, iss2
add $s0, $s1, $s2
addi $s4, $s4, 1
beq $v0, $s4, iss0
add $s1, $s2, $s0
addi $s4, $s4, 1
beq $v0, $s4, iss1
b loop
iss0: move $a0, $s0
b print
iss1: move $a0, $s1
b print
iss2: move $a0, $s2
b print
is1: li $a0, 1
b print
print: li $v0, 1
syscall
li $v0, 10
syscall
|
http://rosettacode.org/wiki/Exceptions | Exceptions | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
This task is to give an example of an exception handling routine
and to "throw" a new exception.
Related task
Exceptions Through Nested Calls
| #Swift | Swift | enum MyException : ErrorType {
case TerribleException
} |
http://rosettacode.org/wiki/Exceptions | Exceptions | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
This task is to give an example of an exception handling routine
and to "throw" a new exception.
Related task
Exceptions Through Nested Calls
| #Tcl | Tcl | package require Tcl 8.5
# Throw
proc e {args} {
error "error message" "error message for stack trace" {errorCode list}
}
# Catch and rethrow
proc f {} {
if {[catch {e 1 2 3 4} errMsg options] != 0} {
return -options $options $errMsg
}
}
f |
http://rosettacode.org/wiki/Execute_a_system_command | Execute a system command | Task
Run either the ls system command (dir on Windows), or the pause system command.
Related task
Get system command output
| #Quackery | Quackery | $ \
import os
exit_code = os.system('ls')
\ python |
http://rosettacode.org/wiki/Execute_a_system_command | Execute a system command | Task
Run either the ls system command (dir on Windows), or the pause system command.
Related task
Get system command output
| #R | R | system("ls")
output=system("ls",intern=TRUE) |
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
| #Chapel | Chapel | proc fac(n) {
var r = 1;
for i in 1..n do
r *= i;
return r;
} |
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
| #UNIX_Shell | UNIX Shell | i=1
while expr $i '<=' 100 >/dev/null; do
w=false
expr $i % 3 = 0 >/dev/null && { printf Fizz; w=true; }
expr $i % 5 = 0 >/dev/null && { printf Buzz; w=true; }
if $w; then echo; else echo $i; fi
i=`expr $i + 1`
done |
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.
| #J | J | import java.io.IOException;
public class Interpreter {
public final static int MEMORY_SIZE = 65536;
private final char[] memory = new char[MEMORY_SIZE];
private int dp;
private int ip;
private int border;
private void reset() {
for (int i = 0; i < MEMORY_SIZE; i++) {
memory[i] = 0;
}
ip = 0;
dp = 0;
}
private void load(String program) {
if (program.length() > MEMORY_SIZE - 2) {
throw new RuntimeException("Not enough memory.");
}
reset();
for (; dp < program.length(); dp++) {
memory[dp] = program.charAt(dp);
}
// memory[border] = 0 marks the end of instructions. dp (data pointer) cannot move lower than the
// border into the program area.
border = dp;
dp += 1;
}
public void execute(String program) {
load(program);
char instruction = memory[ip];
while (instruction != 0) {
switch (instruction) {
case '>':
dp++;
if (dp == MEMORY_SIZE) {
throw new RuntimeException("Out of memory.");
}
break;
case '<':
dp--;
if (dp == border) {
throw new RuntimeException("Invalid data pointer.");
}
break;
case '+':
memory[dp]++;
break;
case '-':
memory[dp]--;
break;
case '.':
System.out.print(memory[dp]);
break;
case ',':
try {
// Only works for one byte characters.
memory[dp] = (char) System.in.read();
} catch (IOException e) {
throw new RuntimeException(e);
}
break;
case '[':
if (memory[dp] == 0) {
skipLoop();
}
break;
case ']':
if (memory[dp] != 0) {
loop();
}
break;
default:
throw new RuntimeException("Unknown instruction.");
}
instruction = memory[++ip];
}
}
private void skipLoop() {
int loopCount = 0;
while (memory[ip] != 0) {
if (memory[ip] == '[') {
loopCount++;
} else if (memory[ip] == ']') {
loopCount--;
if (loopCount == 0) {
return;
}
}
ip++;
}
if (memory[ip] == 0) {
throw new RuntimeException("Unable to find a matching ']'.");
}
}
private void loop() {
int loopCount = 0;
while (ip >= 0) {
if (memory[ip] == ']') {
loopCount++;
} else if (memory[ip] == '[') {
loopCount--;
if (loopCount == 0) {
return;
}
}
ip--;
}
if (ip == -1) {
throw new RuntimeException("Unable to find a matching '['.");
}
}
public static void main(String[] args) {
Interpreter interpreter = new Interpreter();
interpreter.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.
| #Liberty_BASIC | Liberty BASIC | C = 10
'mutaterate has to be greater than 1 or it will not mutate
mutaterate = 2
mutationstaken = 0
generations = 0
Dim parentcopies$((C - 1))
Global targetString$ : targetString$ = "METHINKS IT IS LIKE A WEASEL"
Global allowableCharacters$ : allowableCharacters$ = " ABCDEFGHIJKLMNOPQRSTUVWXYZ"
currentminFitness = Len(targetString$)
For i = 1 To Len(targetString$)
parent$ = parent$ + Mid$(allowableCharacters$, Int(Rnd(1) + 1 * Len(allowableCharacters$)), 1) 'corrected line
Next i
Print "Parent = " + parent$
While parent$ <> targetString$
generations = (generations + 1)
For i = 0 To (C - 1)
parentcopies$(i) = mutate$(parent$, mutaterate)
mutationstaken = (mutationstaken + 1)
Next i
For i = 0 To (C - 1)
currentFitness = Fitness(targetString$, parentcopies$(i))
If currentFitness = 0 Then
parent$ = parentcopies$(i)
Exit For
Else
If currentFitness < currentminFitness Then
currentminFitness = currentFitness
parent$ = parentcopies$(i)
End If
End If
Next i
CLS
Print "Generation - " + str$(generations)
Print "Parent - " + parent$
Scan
Wend
Print
Print "Congratulations to me; I finished!"
Print "Final Mutation: " + parent$
'The ((i + 1) - (C)) reduces the total number of mutations that it took by one generation
'minus the perfect child mutation since any after that would not have been required.
Print "Total Mutations Taken - " + str$(mutationstaken - ((i + 1) - (C)))
Print "Total Generations Taken - " + str$(generations)
Print "Child Number " + str$(i) + " has perfect similarities to your target."
End
Function mutate$(mutate$, mutaterate)
If (Rnd(1) * mutaterate) > 1 Then
'The mutatingcharater randomizer needs 1 more than the length of the string
'otherwise it will likely take forever to get exactly that as a random number
mutatingcharacter = Int(Rnd(1) * (Len(targetString$) + 1))
mutate$ = Left$(mutate$, (mutatingcharacter - 1)) + Mid$(allowableCharacters$, Int(Rnd(1) * Len(allowableCharacters$)), 1) _
+ Mid$(mutate$, (mutatingcharacter + 1))
End If
End Function
Function Fitness(parent$, offspring$)
For i = 1 To Len(targetString$)
If Mid$(parent$, i, 1) <> Mid$(offspring$, i, 1) Then
Fitness = (Fitness + 1)
End If
Next i
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
| #Mirah | Mirah | def fibonacci(n:int)
return n if n < 2
fibPrev = 1
fib = 1
3.upto(Math.abs(n)) do
oldFib = fib
fib = fib + fibPrev
fibPrev = oldFib
end
fib * (n<0 ? int(Math.pow(n+1, -1)) : 1)
end
puts fibonacci 1
puts fibonacci 2
puts fibonacci 3
puts fibonacci 4
puts fibonacci 5
puts fibonacci 6
puts fibonacci 7
|
http://rosettacode.org/wiki/Exceptions | Exceptions | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
This task is to give an example of an exception handling routine
and to "throw" a new exception.
Related task
Exceptions Through Nested Calls
| #Transd | Transd | #lang transd
mainModule : {
func2: (lambda i Int()
(if (!= i 13)
(textout "OK " i "\n")
(throw "fail\n"))),
func1: (lambda
(textout "before try\n")
(try
(textout "before while\n")
(with n 10
(while (< n 15) (+= n 1)
(func2 n)
)
)
(textout "after while\n")
(catch (report e))
)
(textout "after try\n")
),
_start: (lambda (func1))
}
|
http://rosettacode.org/wiki/Exceptions | Exceptions | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
This task is to give an example of an exception handling routine
and to "throw" a new exception.
Related task
Exceptions Through Nested Calls
| #TXR | TXR | {monkey | gorilla | human} <name> |
http://rosettacode.org/wiki/Execute_a_system_command | Execute a system command | Task
Run either the ls system command (dir on Windows), or the pause system command.
Related task
Get system command output
| #Racket | Racket |
#lang racket
;; simple execution of a shell command
(system "ls")
;; capture output
(string-split (with-output-to-string (λ() (system "ls"))) "\n")
;; Warning: passing random string to be run in a shell is a bad idea!
;; much safer: avoids shell parsing, arguments passed separately
(system* "/bin/ls" "-l")
;; avoid specifying the executable path
(system* (find-executable-path "/bin/ls") "-l")
|
http://rosettacode.org/wiki/Execute_a_system_command | Execute a system command | Task
Run either the ls system command (dir on Windows), or the pause system command.
Related task
Get system command output
| #Raku | Raku | run "ls" orelse .die; # output to stdout
my @ls = qx/ls/; # output to variable
my $cmd = 'ls';
@ls = qqx/$cmd/; # same thing with interpolation |
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
| #Chef | Chef | Caramel Factorials.
Only reads one value.
Ingredients.
1 g Caramel
2 g Factorials
Method.
Take Factorials from refrigerator.
Put Caramel into 1st mixing bowl.
Verb the Factorials.
Combine Factorials into 1st mixing bowl.
Verb Factorials until verbed.
Pour contents of the 1st mixing bowl into the 1st baking dish.
Serves 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
| #Ursa | Ursa | #
# fizzbuzz
#
decl int i
for (set i 1) (< i 101) (inc i)
if (= (mod i 3) 0)
out "fizz" console
end if
if (= (mod i 5) 0)
out "buzz" console
end if
if (not (or (= (mod i 3) 0) (= (mod i 5) 0)))
out i console
end if
out endl console
end for |
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.
| #Janet | Janet | import java.io.IOException;
public class Interpreter {
public final static int MEMORY_SIZE = 65536;
private final char[] memory = new char[MEMORY_SIZE];
private int dp;
private int ip;
private int border;
private void reset() {
for (int i = 0; i < MEMORY_SIZE; i++) {
memory[i] = 0;
}
ip = 0;
dp = 0;
}
private void load(String program) {
if (program.length() > MEMORY_SIZE - 2) {
throw new RuntimeException("Not enough memory.");
}
reset();
for (; dp < program.length(); dp++) {
memory[dp] = program.charAt(dp);
}
// memory[border] = 0 marks the end of instructions. dp (data pointer) cannot move lower than the
// border into the program area.
border = dp;
dp += 1;
}
public void execute(String program) {
load(program);
char instruction = memory[ip];
while (instruction != 0) {
switch (instruction) {
case '>':
dp++;
if (dp == MEMORY_SIZE) {
throw new RuntimeException("Out of memory.");
}
break;
case '<':
dp--;
if (dp == border) {
throw new RuntimeException("Invalid data pointer.");
}
break;
case '+':
memory[dp]++;
break;
case '-':
memory[dp]--;
break;
case '.':
System.out.print(memory[dp]);
break;
case ',':
try {
// Only works for one byte characters.
memory[dp] = (char) System.in.read();
} catch (IOException e) {
throw new RuntimeException(e);
}
break;
case '[':
if (memory[dp] == 0) {
skipLoop();
}
break;
case ']':
if (memory[dp] != 0) {
loop();
}
break;
default:
throw new RuntimeException("Unknown instruction.");
}
instruction = memory[++ip];
}
}
private void skipLoop() {
int loopCount = 0;
while (memory[ip] != 0) {
if (memory[ip] == '[') {
loopCount++;
} else if (memory[ip] == ']') {
loopCount--;
if (loopCount == 0) {
return;
}
}
ip++;
}
if (memory[ip] == 0) {
throw new RuntimeException("Unable to find a matching ']'.");
}
}
private void loop() {
int loopCount = 0;
while (ip >= 0) {
if (memory[ip] == ']') {
loopCount++;
} else if (memory[ip] == '[') {
loopCount--;
if (loopCount == 0) {
return;
}
}
ip--;
}
if (ip == -1) {
throw new RuntimeException("Unable to find a matching '['.");
}
}
public static void main(String[] args) {
Interpreter interpreter = new Interpreter();
interpreter.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.
| #Logo | Logo | make "target "|METHINKS IT IS LIKE A WEASEL|
to distance :w
output reduce "sum (map.se [ifelse equal? ?1 ?2 [0][1]] :w :target)
end
to random.letter
output pick "| ABCDEFGHIJKLMNOPQRSTUVWXYZ|
end
to mutate :parent :rate
output map [ifelse random 100 < :rate [random.letter] [?]] :parent
end
make "C 100
make "mutate.rate 10 ; percent
to breed :parent
make "parent.distance distance :parent
localmake "best.child :parent
repeat :C [
localmake "child mutate :parent :mutate.rate
localmake "child.distance distance :child
if greater? :parent.distance :child.distance [
make "parent.distance :child.distance
make "best.child :child
]
]
output :best.child
end
to progress
output (sentence :trials :parent "distance: :parent.distance)
end
to evolve
make "parent cascade count :target [lput random.letter ?] "||
make "trials 0
while [not equal? :parent :target] [
make "parent breed :parent
print progress
make "trials :trials + 1
]
end |
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
| #.D0.9C.D0.9A-61.2F52 | МК-61/52 | П0 1 lg Вx <-> + L0 03 С/П БП
03 |
http://rosettacode.org/wiki/Exceptions | Exceptions | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
This task is to give an example of an exception handling routine
and to "throw" a new exception.
Related task
Exceptions Through Nested Calls
| #Ursa | Ursa | try
invalid "this statement will fail"
catch syntaxerror
# console.err is optional here
out "caught an exception" endl console.err
end try |
http://rosettacode.org/wiki/Exceptions | Exceptions | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
This task is to give an example of an exception handling routine
and to "throw" a new exception.
Related task
Exceptions Through Nested Calls
| #Ursala | Ursala | #import std
thrower = ~&?/'success'! -[epic fail]-!%
catcher = guard(thrower,---[someone failed]-) |
http://rosettacode.org/wiki/Exceptions | Exceptions | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
This task is to give an example of an exception handling routine
and to "throw" a new exception.
Related task
Exceptions Through Nested Calls
| #V | V | [myproc
['new error' 1 2 3] throw
'should not come here' puts
]. |
http://rosettacode.org/wiki/Execute_a_system_command | Execute a system command | Task
Run either the ls system command (dir on Windows), or the pause system command.
Related task
Get system command output
| #Raven | Raven | `ls -la` as listing |
http://rosettacode.org/wiki/Execute_a_system_command | Execute a system command | Task
Run either the ls system command (dir on Windows), or the pause system command.
Related task
Get system command output
| #REBOL | REBOL | ; Capture output to string variable:
x: "" call/output "dir" x
print x
; The 'console' refinement displays the command output on the REBOL command line.
call/console "dir *.r"
call/console "ls *.r"
call/console "pause"
; The 'shell' refinement may be necessary to launch some programs.
call/shell "notepad.exe" |
http://rosettacode.org/wiki/Execute_a_system_command | Execute a system command | Task
Run either the ls system command (dir on Windows), or the pause system command.
Related task
Get system command output
| #Red | Red |
call/show %pause ;The /show refinement forces the display of system's shell window (Windows only).
call/show %dir
call/show %notepad.exe |
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
| #ChucK | ChucK |
0 => int total;
fun int factorial(int i)
{
if (i == 0) return 1;
else
{
i * factorial(i - 1) => total;
}
return total;
}
// == another way
fun int factorial(int x)
{
if (x <= 1 ) return 1;
else return x * factorial (x - 1);
}
// call
factorial (5) => int answer;
// test
if ( answer == 120 ) <<<"success">>>;
|
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
| #Ursala | Ursala | #import std
#import nat
fizzbuzz = ^T(&&'Fizz'! not remainder\3,&&'Buzz'! not remainder\5)|| ~&h+ %nP
#show+
main = fizzbuzz*t iota 101 |
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.
| #Java | Java | import java.io.IOException;
public class Interpreter {
public final static int MEMORY_SIZE = 65536;
private final char[] memory = new char[MEMORY_SIZE];
private int dp;
private int ip;
private int border;
private void reset() {
for (int i = 0; i < MEMORY_SIZE; i++) {
memory[i] = 0;
}
ip = 0;
dp = 0;
}
private void load(String program) {
if (program.length() > MEMORY_SIZE - 2) {
throw new RuntimeException("Not enough memory.");
}
reset();
for (; dp < program.length(); dp++) {
memory[dp] = program.charAt(dp);
}
// memory[border] = 0 marks the end of instructions. dp (data pointer) cannot move lower than the
// border into the program area.
border = dp;
dp += 1;
}
public void execute(String program) {
load(program);
char instruction = memory[ip];
while (instruction != 0) {
switch (instruction) {
case '>':
dp++;
if (dp == MEMORY_SIZE) {
throw new RuntimeException("Out of memory.");
}
break;
case '<':
dp--;
if (dp == border) {
throw new RuntimeException("Invalid data pointer.");
}
break;
case '+':
memory[dp]++;
break;
case '-':
memory[dp]--;
break;
case '.':
System.out.print(memory[dp]);
break;
case ',':
try {
// Only works for one byte characters.
memory[dp] = (char) System.in.read();
} catch (IOException e) {
throw new RuntimeException(e);
}
break;
case '[':
if (memory[dp] == 0) {
skipLoop();
}
break;
case ']':
if (memory[dp] != 0) {
loop();
}
break;
default:
throw new RuntimeException("Unknown instruction.");
}
instruction = memory[++ip];
}
}
private void skipLoop() {
int loopCount = 0;
while (memory[ip] != 0) {
if (memory[ip] == '[') {
loopCount++;
} else if (memory[ip] == ']') {
loopCount--;
if (loopCount == 0) {
return;
}
}
ip++;
}
if (memory[ip] == 0) {
throw new RuntimeException("Unable to find a matching ']'.");
}
}
private void loop() {
int loopCount = 0;
while (ip >= 0) {
if (memory[ip] == ']') {
loopCount++;
} else if (memory[ip] == '[') {
loopCount--;
if (loopCount == 0) {
return;
}
}
ip--;
}
if (ip == -1) {
throw new RuntimeException("Unable to find a matching '['.");
}
}
public static void main(String[] args) {
Interpreter interpreter = new Interpreter();
interpreter.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.
| #Lua | Lua | local target = "METHINKS IT IS LIKE A WEASEL"
local alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ "
local c, p = 100, 0.06
local function fitness(s)
local score = #target
for i = 1,#target do
if s:sub(i,i) == target:sub(i,i) then score = score - 1 end
end
return score
end
local function mutate(s, rate)
local result, idx = ""
for i = 1,#s do
if math.random() < rate then
idx = math.random(#alphabet)
result = result .. alphabet:sub(idx,idx)
else
result = result .. s:sub(i,i)
end
end
return result, fitness(result)
end
local function randomString(len)
local result, idx = ""
for i = 1,len do
idx = math.random(#alphabet)
result = result .. alphabet:sub(idx,idx)
end
return result
end
local function printStep(step, s, fit)
print(string.format("%04d: ", step) .. s .. " [" .. fit .."]")
end
math.randomseed(os.time())
local parent = randomString(#target)
printStep(0, parent, fitness(parent))
local step = 0
while parent ~= target do
local bestFitness, bestChild, child, fitness = #target + 1
for i = 1,c do
child, fitness = mutate(parent, p)
if fitness < bestFitness then bestFitness, bestChild = fitness, child end
end
parent, step = bestChild, step + 1
printStep(step, parent, bestFitness)
end |
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
| #ML | ML | fun fib n =
let
fun fib' (0,a,b) = a
| fib' (n,a,b) = fib' (n-1,a+b,a)
in
fib' (n,0,1)
end |
http://rosettacode.org/wiki/Exceptions | Exceptions | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
This task is to give an example of an exception handling routine
and to "throw" a new exception.
Related task
Exceptions Through Nested Calls
| #VBA | VBA | Sub foo1()
err.raise(vbObjectError + 1050)
End Sub
Sub foo2()
Error vbObjectError + 1051
End Sub
|
http://rosettacode.org/wiki/Exceptions | Exceptions | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
This task is to give an example of an exception handling routine
and to "throw" a new exception.
Related task
Exceptions Through Nested Calls
| #Visual_Basic_.NET | Visual Basic .NET | Class MyException
Inherits Exception
'data with info about exception
End Class |
http://rosettacode.org/wiki/Execute_a_system_command | Execute a system command | Task
Run either the ls system command (dir on Windows), or the pause system command.
Related task
Get system command output
| #REXX | REXX | "dir /a:d" |
http://rosettacode.org/wiki/Execute_a_system_command | Execute a system command | Task
Run either the ls system command (dir on Windows), or the pause system command.
Related task
Get system command output
| #Ring | Ring |
system("dir")
|
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
| #Clay | Clay | factorialRec(n) {
if (n == 0) return 1;
return n * factorialRec(n - 1);
}
factorialIter(n) {
for (i in range(1, n))
n *= i;
return n;
}
factorialFold(n) {
return reduce(multiply, 1, range(1, 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
| #V | V | [fizzbuzz
1 [>=] [
[[15 % zero?] ['fizzbuzz' puts]
[5 % zero?] ['buzz' puts]
[3 % zero?] ['fizz' puts]
[true] [dup puts]
] when succ
] while].
|100 fizzbuzz |
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.
| #JavaScript | JavaScript | /*
* javascript bf interpreter
* by [email protected]
*/
function execute(code)
{
var mem = new Array(30000);
var sp = 10000;
var opcode = new String(code);
var oplen = opcode.length;
var ip = 0;
var loopstack = new Array();
var output = "";
for (var i = 0; i < 30000; ++i) mem[i] = 0;
while (ip < oplen) {
switch(opcode[ip]) {
case '+':
mem[sp]++;
break;
case '-':
mem[sp]--;
break;
case '>':
sp++;
break;
case '<':
sp--;
break;
case '.':
if (mem[sp] != 10 && mem[sp] != 13) {
output = output + Util.fromCharCode(mem[sp]);
} else {
puts(output);
output = "";
}
break;
case ',':
var s = console.input();
if (!s) exit(0);
mem[sp] = s.charCodeAt(0);
break;
case '[':
if (mem[sp]) {
loopstack.push(ip);
} else {
for (var k = ip, j = 0; k < oplen; k++) {
opcode[k] == '[' && j++;
opcode[k] == ']' && j--;
if (j == 0) break;
}
if (j == 0) ip = k;
else {
puts("Unmatched loop");
return false;
}
}
break;
case ']':
ip = loopstack.pop() - 1;
break;
default:
break;
}
ip++;
}
return true;
};
if (Interp.conf('unitTest') > 0) 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.
| #M2000_Interpreter | M2000 Interpreter |
Module WeaselAlgorithm {
Print "Evolutionary Algorithm"
\\ Weasel Algorithm
\\ Using dynamic array, which expand if no fitness change,
\\ and reduce to minimum when fitness changed
\\ Abandon strings when fitness change
\\ Also lambda function Mutate$ change when topscore=10, to change only one character
l$="ABCDEFGHIJKLMNOPQRSTUVWXYZ "
randomstring$=lambda$ l$ ->{
res$=""
For i=1 to 28: res$+=Mid$(L$,Random(1,27),1):next i
=res$
}
m$="METHINKS IT IS LIKE A WEASEL"
lm=len(m$)
fitness=lambda m$, lm (this$)-> {
score=0 : For i=1 to lm {score+=If(mid$(m$,i,1)=mid$(this$, i, 1)->1,0)} : =score
}
Mutate$=lambda$ l$ (w$)-> {
a=random(1,28) : insert a, 1 w$=mid$(l$, random(1,27),1)
If random(3)=1 Then b=a:while b=a {b=random(1,28)} : insert b, 1 w$=mid$(l$, random(1,27),1)
=w$
}
Mutate1$=lambda$ l$ (w$)-> {
insert random(1,28), 1 w$=mid$(l$, random(1,27),1) : =w$
}
f$=randomstring$()
topscore=0
last=0
Pen 11 {Print "Fitness |Target:", @(16),m$, @(47),"|Total Strings"}
Print Over $(3,8), str$(topscore/28,"##0.0%"),"",$(0),f$, 0
count=0
gen=30
mut=0
{
last=0
Dim a$(1 to gen)<<mutate$(f$)
mut+=gen
oldscore=topscore
For i=1 to gen {
topscore=max.data(topscore, fitness(a$(i)))
If oldscore<topscore Then last=i:Exit
}
If last>0 Then {
f$=a$(last) : gen=30 : If topscore=10 Then mutate$=mutate1$
} Else gen+=50
Print Over $(3,8), str$(topscore/28,"##0.0%"), "",$(0),f$, mut : refresh
count+=min(gen,i)
If topscore<28 Then loop
}
Print
Print "Results"
Print "I found this:"; a$(i)
Print "Total strings which evalute fitness:"; count
Print "Done"
}
WeaselAlgorithm
|
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
| #ML.2FI | ML/I | MCSKIP "WITH" NL
"" Fibonacci - recursive
MCSKIP MT,<>
MCINS %.
MCDEF FIB WITHS ()
AS <MCSET T1=%A1.
MCGO L1 UNLESS 2 GR T1
%T1.<>MCGO L0
%L1.%FIB(%T1.-1)+FIB(%T1.-2).>
fib(0) is FIB(0)
fib(1) is FIB(1)
fib(2) is FIB(2)
fib(3) is FIB(3)
fib(4) is FIB(4)
fib(5) is FIB(5) |
http://rosettacode.org/wiki/Exceptions | Exceptions | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
This task is to give an example of an exception handling routine
and to "throw" a new exception.
Related task
Exceptions Through Nested Calls
| #Wren | Wren | var intDiv = Fn.new { |a, b|
if (!(a is Num && a.isInteger) || !(b is Num && b.isInteger)) Fiber.abort("Invalid argument(s).")
if (b == 0) Fiber.abort("Division by zero error.")
if (a == 0) a = a.badMethod()
return (a/b).truncate
}
var a = [ [6, 2], [6, 0], [10, 5], [true, false], [0, 2] ]
for (e in a) {
var d
var f = Fiber.new { d = intDiv.call(e[0], e[1]) }
f.try()
if (f.error) {
System.print("Caught %(f.error)")
} else {
System.print("%(e[0]) / %(e[1]) = %(d)")
}
} |
http://rosettacode.org/wiki/Execute_a_system_command | Execute a system command | Task
Run either the ls system command (dir on Windows), or the pause system command.
Related task
Get system command output
| #Ruby | Ruby | string = `ls`
# runs command and returns its STDOUT as a string
string = %x{ls}
# ditto, alternative syntax
system "ls"
# runs command and returns its exit status; its STDOUT gets output to our STDOUT
print `ls`
#The same, but with back quotes
exec "ls"
# replace current process with another
# call system command and read output asynchronously
io = IO.popen('ls')
# ... later
io.each {|line| puts line} |
http://rosettacode.org/wiki/Execute_a_system_command | Execute a system command | Task
Run either the ls system command (dir on Windows), or the pause system command.
Related task
Get system command output
| #Run_BASIC | Run BASIC | print shell$("ls") ' prints the returned data from the OS
a$ = shell$("ls") ' holds returned data in a$ |
http://rosettacode.org/wiki/Execute_a_system_command | Execute a system command | Task
Run either the ls system command (dir on Windows), or the pause system command.
Related task
Get system command output
| #Rust | Rust | use std::process::Command;
fn main() {
let output = Command::new("ls").output().unwrap_or_else(|e| {
panic!("failed to execute process: {}", e)
});
println!("{}", String::from_utf8_lossy(&output.stdout));
}
|
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
| #Clio | Clio |
fn factorial n:
if n <= 1: n
else:
n * (n - 1 -> factorial)
10 -> factorial -> print
|
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
| #Vala | Vala | int main() {
for (int i = 1; i <= 100; i++) {
if (i % 3 == 0) stdout.printf("Fizz\n");
if (i % 5 == 0) stdout.printf("Buzz\n");
if (i % 15 == 0) stdout.printf("FizzBuzz\n");
if (i % 3 != 0 && i % 5 != 0) stdout.printf("%d\n", i);
}
return 0;;
} |
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.
| #Jsish | Jsish | /*
* javascript bf interpreter
* by [email protected]
*/
function execute(code)
{
var mem = new Array(30000);
var sp = 10000;
var opcode = new String(code);
var oplen = opcode.length;
var ip = 0;
var loopstack = new Array();
var output = "";
for (var i = 0; i < 30000; ++i) mem[i] = 0;
while (ip < oplen) {
switch(opcode[ip]) {
case '+':
mem[sp]++;
break;
case '-':
mem[sp]--;
break;
case '>':
sp++;
break;
case '<':
sp--;
break;
case '.':
if (mem[sp] != 10 && mem[sp] != 13) {
output = output + Util.fromCharCode(mem[sp]);
} else {
puts(output);
output = "";
}
break;
case ',':
var s = console.input();
if (!s) exit(0);
mem[sp] = s.charCodeAt(0);
break;
case '[':
if (mem[sp]) {
loopstack.push(ip);
} else {
for (var k = ip, j = 0; k < oplen; k++) {
opcode[k] == '[' && j++;
opcode[k] == ']' && j--;
if (j == 0) break;
}
if (j == 0) ip = k;
else {
puts("Unmatched loop");
return false;
}
}
break;
case ']':
ip = loopstack.pop() - 1;
break;
default:
break;
}
ip++;
}
return true;
};
if (Interp.conf('unitTest') > 0) 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.
| #m4 | m4 | divert(-1)
# Get a random number from 0 to one less than $1.
# (Note that this is not a very good RNG. Also it writes a file.)
#
# Usage: randnum(N) (Produces a random integer in 0..N-1)
#
define(`randnum',
`syscmd(`echo $RANDOM > __random_number__')eval(include(__random_number__) % ( $1 ))')
# The *target* specified in the Rosetta Code task.
define(`target',`METHINKS IT IS LIKE A WEASEL')
define(`alphabet',`ABCDEFGHIJKLMNOPQRSTUVWXYZ ')
define(`random_letter',`substr(alphabet,randnum(len(alphabet)),1)')
define(`create_primogenitor',`_$0(`')')
define(`_create_primogenitor',`ifelse(len(`$1'),len(target),`$1',
`$0(`$1'random_letter)')')
# The *parent* specified in the Rosetta Code task.
define(`parent',`'create_primogenitor)
#
# Usage: mutate_letter(STRING,INDEX)
#
define(`mutate_letter',
`substr(`$1',0,`$2')`'random_letter`'substr(`$1',incr(`$2'))')
#
# Usage: mutate_letter_at_rate(STRING,INDEX,MUTATION_RATE)
#
define(`mutate_letter_at_rate',
`ifelse(eval(randnum(100) < ($3)),1,`mutate_letter(`$1',`$2')',`$1')')
# The *mutate* procedure specified in the Rosetta Code task. The
# mutation rate is given in percents.
#
# Usage: mutate(STRING,MUTATION_RATE)
#
define(`mutate',`_$0(`$1',`$2',len(`$1'))')
define(`_mutate',
`ifelse($3,0,`$1',
`$0(mutate_letter_at_rate(`$1',decr($3),`$2'),`$2',decr($3))')')
# The *fitness* procedure specified in the Rosetta Code
# task. "Fitness" here is simply how many letters match.
#
# Usage: fitness(STRING)
#
define(`fitness',`_$0(`$1',target,0)')
define(`_fitness',
`ifelse(`$1',`',$3,
`ifelse(`'substr(`$1',0,1),`'substr(`$2',0,1),
`$0(`'substr(`$1',1),`'substr(`$2',1),incr($3))',
`$0(`'substr(`$1',1),`'substr(`$2',1),$3)')')')
#
# Usage: have_child(PARENT,MUTATION_RATE)
#
# The result is either the parent or the child: whichever has the
# greater fitness. If they are equally fit, one is chosen arbitrarily.
# (Note that, in the current implementation, fitnesses are not
# memoized.)
#
define(`have_child',
`pushdef(`_child_',mutate(`$1',`$2'))`'dnl
ifelse(eval(fitness(`'_child_) < fitness(`$1')),1,`$1',`_child_')`'dnl
popdef(`_child_')')
#
# Usage: next_parent(PARENT,NUM_CHILDREN,MUTATION_RATE)
#
# Note that a string is discarded as soon as it is known it will not
# be in the next generation. If some strings have the same highest
# fitness, one of them is chosen arbitrarily.
#
define(`next_parent',`_$0(`$1',`$2',`$3',`$1')')
define(`_next_parent',
`ifelse(`$2',0,`$1',
`$0(`'have_child(`$4',`$3'),decr(`$2'),`$3',`$4')')')
define(`repeat_until_equal',
`ifelse(`$1',`'target,`[$1]',
`pushdef(`_the_horta_',`'next_parent(`$1',`$2',`$3'))`'dnl
[_the_horta_]
$0(`'_the_horta_,`$2',`$3')`'dnl
popdef(`_the_horta_')')')
divert`'dnl
[parent]
repeat_until_equal(parent,10,10) |
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
| #Modula-2 | Modula-2 | MODULE Fibonacci;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
PROCEDURE Fibonacci(n : LONGINT) : LONGINT;
VAR
a,b,c : LONGINT;
BEGIN
IF n<0 THEN RETURN 0 END;
a:=1;
b:=1;
WHILE n>0 DO
c := a + b;
a := b;
b := c;
DEC(n)
END;
RETURN a
END Fibonacci;
VAR
buf : ARRAY[0..63] OF CHAR;
i : INTEGER;
r : LONGINT;
BEGIN
FOR i:=0 TO 10 DO
r := Fibonacci(i);
FormatString("%l\n", buf, r);
WriteString(buf);
END;
ReadChar
END Fibonacci. |
http://rosettacode.org/wiki/Exceptions | Exceptions | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
This task is to give an example of an exception handling routine
and to "throw" a new exception.
Related task
Exceptions Through Nested Calls
| #zkl | zkl | try{ throw(Exception.BadDay) }
catch { println(__exception," was thrown") }
fallthrough { println("No exception was thrown") }
println("OK"); |
http://rosettacode.org/wiki/Exceptions | Exceptions | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
This task is to give an example of an exception handling routine
and to "throw" a new exception.
Related task
Exceptions Through Nested Calls
| #Zig | Zig | const std = @import("std");
// To replace exceptions, Zig has error enums to handle error states.
pub fn main() !void {
// writing to stdout as file descriptor might fail,
// if we are a child process and the parent process has closed it
const stdout_wr = std.io.getStdOut().writer();
try stdout_wr.writeAll("a");
// Above code is identical to
stdout_wr.writeAll("a") catch |err| return err;
stdout_wr.writeAll("a") catch |err| {
// usually std streams are leaked and the Kernel cleans them up
var stdin = std.io.getStdIn();
var stderr = std.io.getStdErr();
stdin.close();
stderr.close();
return err;
};
} |
http://rosettacode.org/wiki/Execute_a_system_command | Execute a system command | Task
Run either the ls system command (dir on Windows), or the pause system command.
Related task
Get system command output
| #Scala | Scala | import scala.sys.process.Process
Process("ls", Seq("-oa"))! |
http://rosettacode.org/wiki/Execute_a_system_command | Execute a system command | Task
Run either the ls system command (dir on Windows), or the pause system command.
Related task
Get system command output
| #Scheme | Scheme | (system "ls") |
http://rosettacode.org/wiki/Execute_a_system_command | Execute a system command | Task
Run either the ls system command (dir on Windows), or the pause system command.
Related task
Get system command output
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "shell.s7i";
const proc: main is func
begin
cmd_sh("ls");
end func; |
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
| #CLIPS | CLIPS | (deffunction factorial (?a)
(if (or (not (integerp ?a)) (< ?a 0)) then
(printout t "Factorial Error!" crlf)
else
(if (= ?a 0) then
1
else
(* ?a (factorial (- ?a 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
| #VAX_Assembly | VAX Assembly | 00000008 0000 1 len =8
00000008 0000 2 msg: .blkb len ;output buffer
0000000C 0008 3 desc: .blkl 1 ;descriptor lenght field
00000000' 000C 4 .address msg ;pointer to buffer
00000012 0010 5 outlen: .blkw 1
4C 55 21 0000001A'010E0000' 0012 6 ctr: .ascid "!UL"
001D 7
0000 001D 8 .entry start,0
52 7C 001F 9 clrq r2 ;r2+r3 64bit
52 D6 0021 10 incl r2 ;start index 1
0023 11 loop:
E2 AF B4 0023 12 clrw desc ;assume not fizz and or buzz
55 D7 AF 9E 0026 13 movab msg, r5 ;pointer to message buffer
54 50 52 03 7B 002A 14 ediv #3,r2,r0,r4 ;divr.rl,divd.rq,quo.wl,rem.wl
54 D5 002F 15 tstl r4 ;remainder
0B 12 0031 16 bneq not_fizz ;not equal zero
0033 17
85 7A7A6966 8F D0 0033 18 movl #^a"fizz", (r5)+ ;add to message
CA AF 04 A0 003A 19 addw2 #4, desc ;and update length
003E 20 not_fizz:
54 50 52 05 7B 003E 21 ediv #5,r2,r0,r4
54 D5 0043 22 tstl r4
0B 12 0045 23 bneq not_buzz
0047 24
85 7A7A7562 8F D0 0047 25 movl #^a"buzz", (r5)+
B6 AF 04 A0 004E 26 addw2 #4, desc
0052 27 not_buzz:
B3 AF B5 0052 28 tstw desc ;fizz and or buzz?
1B 12 0055 29 bneq show_buffer ;neq - yes
0057 30
AD AF 08 B0 0057 31 movw #len, desc ;fao length limit
005B 32 $fao_s - ;eql -no
005B 33 ctrstr = ctr, - ;show number
005B 34 outlen = outlen, -
005B 35 outbuf = desc, -
005B 36 p1 = r2
96 AF A0 AF B0 006D 37 movw outlen, desc ;characters filled by fao
0072 38 show_buffer:
93 AF 7F 0072 39 pushaq desc
00000000'GF 01 FB 0075 40 calls #1, g^lib$put_output
9F 52 00000064 8F F3 007C 41 AOBLEQ #100,r2,loop ;limit.rl, index.ml
04 0084 42 ret
0085 43 .end start |
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.
| #Julia | Julia | using DataStructures
function execute(src)
pointers = Dict{Int,Int}()
stack = Int[]
for (ptr, opcode) in enumerate(src)
if opcode == '[' push!(stack, ptr) end
if opcode == ']'
if isempty(stack)
src = src[1:ptr]
break
end
sptr = pop!(stack)
pointers[ptr], pointers[sptr] = sptr, ptr
end
end
if ! isempty(stack) error("unclosed loops at $stack") end
tape = DefaultDict{Int,Int}(0)
cell, ptr = 0, 1
while ptr ≤ length(src)
opcode = src[ptr]
if opcode == '>' cell += 1
elseif opcode == '<' cell -= 1
elseif opcode == '+' tape[cell] += 1
elseif opcode == '-' tape[cell] -= 1
elseif opcode == ',' tape[cell] = Int(read(STDIN, 1))
elseif opcode == '.' print(STDOUT, Char(tape[cell]))
elseif (opcode == '[' && tape[cell] == 0) ||
(opcode == ']' && tape[cell] != 0) ptr = pointers[ptr]
end
ptr += 1
end
end
const src = """\
>++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.>
>+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++."""
execute(src) |
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.
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | target = "METHINKS IT IS LIKE A WEASEL";
alphabet = Append[CharacterRange["A", "Z"], " "];
fitness = HammingDistance[target, #] &;
mutate[str_String, rate_ : 0.01] := StringReplace[
str,
_ /; RandomReal[] < rate :> RandomChoice[alphabet]
]
mutationRate = 0.02; c = 100;
NestWhileList[
First@MinimalBy[
Thread[mutate[ConstantArray[#, c], mutationRate]],
fitness
] &,
mutate[target, 1],
fitness@# > 0 &
] // ListAnimate |
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
| #Modula-3 | Modula-3 | PROCEDURE Fib(n: INTEGER): INTEGER =
BEGIN
IF n < 2 THEN
RETURN n;
ELSE
RETURN Fib(n-1) + Fib(n-2);
END;
END Fib; |
http://rosettacode.org/wiki/Execute_a_system_command | Execute a system command | Task
Run either the ls system command (dir on Windows), or the pause system command.
Related task
Get system command output
| #SETL | SETL | system("ls"); |
http://rosettacode.org/wiki/Execute_a_system_command | Execute a system command | Task
Run either the ls system command (dir on Windows), or the pause system command.
Related task
Get system command output
| #Sidef | Sidef | # Pipe in read-only mode
%p(ls).open_r.each { |line|
print line;
};
var str1 = `ls`; # backtick: returns a string
var str2 = %x(ls); # ditto, alternative syntax
Sys.system('ls'); # system: executes a command and prints the result
Sys.exec('ls'); # replaces current process with another |
http://rosettacode.org/wiki/Execute_a_system_command | Execute a system command | Task
Run either the ls system command (dir on Windows), or the pause system command.
Related task
Get system command output
| #Slate | Slate | Platform run: 'ls'. |
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
| #Clojure | Clojure | (defn factorial [x]
(apply * (range 2 (inc x)))) |
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
| #VBA | VBA |
Option Explicit
Sub FizzBuzz()
Dim Tb(1 To 100) As Variant
Dim i As Integer
For i = 1 To 100
'Tb(i) = i ' move to Else
If i Mod 15 = 0 Then
Tb(i) = "FizzBuzz"
ElseIf i Mod 5 = 0 Then
Tb(i) = "Buzz"
ElseIf i Mod 3 = 0 Then
Tb(i) = "Fizz"
Else
Tb(i) = i
End If
Next
Debug.Print Join(Tb, vbCrLf)
End Sub |
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.
| #Kotlin | Kotlin | // version 1.1.2
class Brainf__k(val prog: String, memSize: Int) {
private val mem = IntArray(memSize)
private var ip = 0
private var dp = 0
private val memVal get() = mem.getOrElse(dp) { 0 }
fun execute() {
while (ip < prog.length) {
when (prog[ip++]) {
'>' -> dp++
'<' -> dp--
'+' -> mem[dp] = memVal + 1
'-' -> mem[dp] = memVal - 1
',' -> mem[dp] = System.`in`.read()
'.' -> print(memVal.toChar())
'[' -> handleLoopStart()
']' -> handleLoopEnd()
}
}
}
private fun handleLoopStart() {
if (memVal != 0) return
var depth = 1
while (ip < prog.length) {
when (prog[ip++]) {
'[' -> depth++
']' -> if (--depth == 0) return
}
}
throw IllegalStateException("Could not find matching end bracket")
}
private fun handleLoopEnd() {
var depth = 0
while (ip >= 0) {
when (prog[--ip]) {
']' -> depth++
'[' -> if (--depth == 0) return
}
}
throw IllegalStateException("Could not find matching start bracket")
}
}
fun main(args: Array<String>) {
val prog = "++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>."
Brainf__k(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.
| #MATLAB | MATLAB | %This class impliments a string that mutates to a target
classdef EvolutionaryAlgorithm
properties
target;
parent;
children = {};
validAlphabet;
%Constants
numChildrenPerIteration;
maxIterations;
mutationRate;
end
methods
%Class constructor
function family = EvolutionaryAlgorithm(target,mutationRate,numChildren,maxIterations)
family.validAlphabet = char([32 (65:90)]); %Space char and A-Z
family.target = target;
family.children = cell(numChildren,1);
family.numChildrenPerIteration = numChildren;
family.maxIterations = maxIterations;
family.mutationRate = mutationRate;
initialize(family);
end %class constructor
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Helper functions and class get/set functions
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%setAlphabet() - sets the valid alphabet for the current instance
%of the EvolutionaryAlgorithm class.
function setAlphabet(family,alphabet)
if(ischar(alphabet))
family.validAlphabet = alphabet;
%Makes change permanent
assignin('caller',inputname(1),family);
else
error 'New alphabet must be a string or character array';
end
end
%setTarget() - sets the target for the current instance
%of the EvolutionaryAlgorithm class.
function setTarget(family,target)
if(ischar(target))
family.target = target;
%Makes change permanent
assignin('caller',inputname(1),family);
else
error 'New target must be a string or character array';
end
end
%setMutationRate() - sets the mutation rate for the current instance
%of the EvolutionaryAlgorithm class.
function setMutationRate(family,mutationRate)
if(isnumeric(mutationRate))
family.mutationRate = mutationRate;
%Makes change permanent
assignin('caller',inputname(1),family);
else
error 'New mutation rate must be a double precision number';
end
end
%setMaxIterations() - sets the maximum number of iterations during
%evolution for the current instance of the EvolutionaryAlgorithm class.
function setMaxIterations(family,maxIterations)
if(isnumeric(maxIterations))
family.maxIterations = maxIterations;
%Makes change permanent
assignin('caller',inputname(1),family);
else
error 'New maximum amount of iterations must be a double precision number';
end
end
%display() - overrides the built-in MATLAB display() function, to
%display the important class variables
function display(family)
disp([sprintf('Target: %s\n',family.target)...
sprintf('Parent: %s\n',family.parent)...
sprintf('Valid Alphabet: %s\n',family.validAlphabet)...
sprintf('Number of Children: %d\n',family.numChildrenPerIteration)...
sprintf('Mutation Rate [0,1]: %d\n',family.mutationRate)...
sprintf('Maximum Iterations: %d\n',family.maxIterations)]);
end
%disp() - overrides the built-in MATLAB disp() function, to
%display the important class variables
function disp(family)
display(family);
end
%randAlphabetElement() - Generates a random character from the
%valid alphabet for the current instance of the class.
function elements = randAlphabetElements(family,numChars)
%Sample the valid alphabet randomly from the uniform
%distribution
N = length(family.validAlphabet);
choices = ceil(N*rand(1,numChars));
elements = family.validAlphabet(choices);
end
%initialize() - Sets the parent to a random string of length equal
%to the length of the target
function parent = initialize(family)
family.parent = randAlphabetElements(family,length(family.target));
parent = family.parent;
%Makes changes to the instance of EvolutionaryAlgorithm permanent
assignin('caller',inputname(1),family);
end %initialize
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Functions required by task specification
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%mutate() - generates children from the parent and mutates them
function mutate(family)
sizeParent = length(family.parent);
%Generate mutatant children sequentially
for child = (1:family.numChildrenPerIteration)
parentCopy = family.parent;
for charIndex = (1:sizeParent)
if (rand(1) < family.mutationRate)
parentCopy(charIndex) = randAlphabetElements(family,1);
end
end
family.children{child} = parentCopy;
end
%Makes changes to the instance of EvolutionaryAlgorithm permanent
assignin('caller',inputname(1),family);
end %mutate
%fitness() - Computes the Hamming distance between the target
%string and the string input as the familyMember argument
function theFitness = fitness(family,familyMember)
if not(ischar(familyMember))
error 'The second argument must be a string';
end
theFitness = sum(family.target == familyMember);
end
%evolve() - evolves the family until the target is reached or it
%exceeds the maximum amount of iterations
function [iteration,mostFitFitness] = evolve(family)
iteration = 0;
mostFitFitness = 0;
targetFitness = fitness(family,family.target);
disp(['Target fitness is ' num2str(targetFitness)]);
while (mostFitFitness < targetFitness) && (iteration < family.maxIterations)
iteration = iteration + 1;
mutate(family);
parentFitness = fitness(family,family.parent);
mostFit = family.parent;
mostFitFitness = parentFitness;
for child = (1:family.numChildrenPerIteration)
childFitness = fitness(family,family.children{child});
if childFitness > mostFitFitness
mostFit = family.children{child};
mostFitFitness = childFitness;
end
end
family.parent = mostFit;
disp([num2str(iteration) ': ' mostFit ' - Fitness: ' num2str(mostFitFitness)]);
end
%Makes changes to the instance of EvolutionaryAlgorithm permanent
assignin('caller',inputname(1),family);
end %evolve
end %methods
end %classdef |
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
| #Monicelli | Monicelli |
# Main
Lei ha clacsonato
voglio un nonnulla, Necchi mi porga un nonnulla
il nonnulla come se fosse brematurata la supercazzola bonaccia con il nonnulla o scherziamo?
un nonnulla a posterdati
# Fibonacci function 'bonaccia'
blinda la supercazzola Necchi bonaccia con antani Necchi o scherziamo? che cos'è l'antani?
minore di 3: vaffanzum 1! o tarapia tapioco: voglio unchiamo, Necchi come se fosse brematurata
la supercazzola bonaccia con antani meno 1 o scherziamo? voglio duechiamo,
Necchi come se fosse brematurata la supercazzola bonaccia con antani meno 2 o scherziamo? vaffanzum
unchiamo più duechiamo! e velocità di esecuzione
|
http://rosettacode.org/wiki/Execute_a_system_command | Execute a system command | Task
Run either the ls system command (dir on Windows), or the pause system command.
Related task
Get system command output
| #Smalltalk | Smalltalk | Smalltalk system: 'ls'. |
http://rosettacode.org/wiki/Execute_a_system_command | Execute a system command | Task
Run either the ls system command (dir on Windows), or the pause system command.
Related task
Get system command output
| #SQL_PL | SQL PL |
!ls
|
http://rosettacode.org/wiki/Execute_a_system_command | Execute a system command | Task
Run either the ls system command (dir on Windows), or the pause system command.
Related task
Get system command output
| #Standard_ML | Standard ML | OS.Process.system "ls" |
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
| #CLU | CLU | factorial = proc (n: int) returns (int) signals (negative)
if n<0 then signal negative
elseif n=0 then return(1)
else return(n * factorial(n-1))
end
end factorial
start_up = proc ()
po: stream := stream$primary_output()
for i: int in int$from_to(0, 10) do
fac: int := factorial(i)
stream$putl(po, int$unparse(i) || "! = " || int$unparse(fac))
end
end start_up |
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
| #VBScript | VBScript | For i = 1 To 100
If i Mod 15 = 0 Then
WScript.Echo "FizzBuzz"
ElseIf i Mod 5 = 0 Then
WScript.Echo "Buzz"
ElseIf i Mod 3 = 0 Then
WScript.Echo "Fizz"
Else
WScript.Echo i
End If
Next |
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.
| #Limbo | Limbo | implement Bf;
include "sys.m"; sys: Sys;
include "draw.m";
Bf: module {
init: fn(nil: ref Draw->Context, args: list of string);
ARENASZ: con 1024 * 1024;
EXIT, INC, DEC, JZ, JNZ, INCP, DECP, READ, WRITE: con iota;
};
init(nil: ref Draw->Context, args: list of string)
{
sys = load Sys Sys->PATH;
args = tl args;
if(args == nil || len args != 1) {
sys->fprint(sys->fildes(2), "usage: bf program");
raise "fail:usage";
}
code := compile(hd args);
execute(code, array[ARENASZ] of { * => byte 0 });
}
compile(p: string): array of int
{
marks: list of int = nil;
code := array[len p * 2 + 1] of { * => EXIT };
pc := 0;
for(i := 0; i < len p; i++) {
case p[i] {
'-' => code[pc++] = DEC;
'+' => code[pc++] = INC;
'<' => code[pc++] = DECP;
'>' => code[pc++] = INCP;
',' => code[pc++] = READ;
'.' => code[pc++] = WRITE;
'[' =>
code[pc++] = JZ;
marks = pc++ :: marks;
']' =>
if(marks == nil) {
sys->fprint(sys->fildes(2), "bf: unmatched ']' at character %d.", pc);
raise "fail:errors";
}
c := hd marks;
marks = tl marks;
code[pc++] = JNZ;
code[c] = pc;
code[pc++] = c;
}
}
if(marks != nil) {
sys->fprint(sys->fildes(2), "bf: unmatched '['.");
raise "fail:errors";
}
return code;
}
execute(code: array of int, arena: array of byte)
{
pc := 0;
p := 0;
buf := array[1] of byte;
stopreading := 0;
for(;;) {
case code[pc] {
DEC => arena[p]--;
INC => arena[p]++;
DECP =>
p--;
if(p < 0)
p = len arena - 1;
INCP =>
p = (p + 1) % len arena;
READ =>
if(!stopreading) {
n := sys->read(sys->fildes(0), buf, 1);
if(n < 1) {
arena[p] = byte 0;
stopreading = 1;
} else {
arena[p] = buf[0];
}
}
WRITE =>
buf[0] = arena[p];
sys->write(sys->fildes(1), buf, 1);
JNZ =>
if(arena[p] != byte 0)
pc = code[pc + 1];
else
pc++;
JZ =>
if(arena[p] == byte 0)
pc = code[pc + 1];
else
pc++;
EXIT => return;
}
pc++;
}
}
|
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.
| #Nanoquery | Nanoquery | import Nanoquery.Util
target = "METHINKS IT IS LIKE A WEASEL"
tbl = "ABCDEFGHIJKLMNOPQRSTUVWXYZ "
copies = 30
chance = 0.09
rand = new(Random)
// returns a random string of the specified length
def rand_string(length)
global tbl
global rand
ret = ""
for i in range(1, length)
ret += tbl[rand.getInt(len(tbl))]
end
return ret
end
// gets the fitness of a given string
def fitness(string)
global target
fit = 0
for i in range(0, len(string) - 1)
if string[i] != target[i]
fit -= 1
end
end
return fit
end
// mutates the specified string with a chance of 0.09 by default
def mutate(string)
global chance
global rand
global tbl
mutated = string
for i in range(0, len(mutated) - 1)
if rand.getFloat() <= chance
mutated[i] = tbl[rand.getInt(len(tbl))]
end
end
return mutated
end
// a function to find the index of the string with the best fitness
def most_fit(strlist)
global target
best_score = -(len(target) + 1)
best_index = 0
for j in range(0, len(strlist) - 1)
fit = fitness(strlist[j])
if fit > best_score
best_index = j
best_score = fit
end
end
return {best_index, best_score}
end
parent = rand_string(len(target)); iter = 1
while parent != target
children = {}
for i in range(1, 30)
children.append(mutate(parent))
end
fit = most_fit(children)
parent = children[fit[0]]
print format("iter %d, score %d: %s\n", iter, fit[1], parent)
iter += 1
end |
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
| #MontiLang | MontiLang | 0 VAR a .
1 VAR b .
INPUT TOINT
FOR :
a b + VAR c .
a PRINT .
b VAR a .
c VAR b .
ENDFOR |
http://rosettacode.org/wiki/Execute_a_system_command | Execute a system command | Task
Run either the ls system command (dir on Windows), or the pause system command.
Related task
Get system command output
| #Stata | Stata | !dir
* print a message and wait
!echo Ars Longa Vita Brevis & pause
* load Excel from Stata
!start excel
* run a Python program (Python must be installed and accessible in the PATH environment variable)
!python preprocessing.py
* load Windows Notepad
winexec notepad |
http://rosettacode.org/wiki/Execute_a_system_command | Execute a system command | Task
Run either the ls system command (dir on Windows), or the pause system command.
Related task
Get system command output
| #Tcl | Tcl | puts [exec ls] |
http://rosettacode.org/wiki/Execute_a_system_command | Execute a system command | Task
Run either the ls system command (dir on Windows), or the pause system command.
Related task
Get system command output
| #Toka | Toka | needs shell
" ls" system |
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
| #CMake | CMake | function(factorial var n)
set(product 1)
foreach(i RANGE 2 ${n})
math(EXPR product "${product} * ${i}")
endforeach(i)
set(${var} ${product} PARENT_SCOPE)
endfunction(factorial)
factorial(f 12)
message("12! = ${f}") |
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
| #Verbexx | Verbexx | @LOOP init:{@VAR t3 t5; @VAR i = 1} while:(i <= 100) next:{i++}
{
t3 = (i % 3 == 0);
t5 = (i % 5 == 0);
@SAY ( @CASE when:(t3 && t5) { 'FizzBuzz }
when: t3 { 'Fizz }
when: t5 { 'Buzz }
else: { i }
);
}; |
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.
| #Lua | Lua | local funs = {
['>'] = 'ptr = ptr + 1; ',
['<'] = 'ptr = ptr - 1; ',
['+'] = 'mem[ptr] = mem[ptr] + 1; ',
['-'] = 'mem[ptr] = mem[ptr] - 1; ',
['['] = 'while mem[ptr] ~= 0 do ',
[']'] = 'end; ',
['.'] = 'io.write(string.char(mem[ptr])); ',
[','] = 'mem[ptr] = (io.read(1) or "\\0"):byte(); ',
}
local prog = [[
local mem = setmetatable({}, { __index = function() return 0 end})
local ptr = 1
]]
local source = io.read('*all')
for p = 1, #source do
local snippet = funs[source:sub(p,p)]
if snippet then prog = prog .. snippet end
end
load(prog)() |
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.
| #Nim | Nim | import random
const
Target = "METHINKS IT IS LIKE A WEASEL"
Alphabet = " ABCDEFGHIJLKLMNOPQRSTUVWXYZ"
P = 0.05
C = 100
proc negFitness(trial: string): int =
for i in 0 .. trial.high:
if Target[i] != trial[i]:
inc result
proc mutate(parent: string): string =
for c in parent:
result.add (if rand(1.0) < P: sample(Alphabet) else: c)
randomize()
var parent = ""
for _ in 1..Target.len:
parent.add sample(Alphabet)
var i = 0
while parent != Target:
var copies = newSeq[string](C)
for i in 0 .. copies.high:
copies[i] = parent.mutate()
var best = copies[0]
for i in 1 .. copies.high:
if negFitness(copies[i]) < negFitness(best):
best = copies[i]
parent = best
echo i, " ", parent
inc i |
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
| #MUMPS | MUMPS | FIBOITER(N)
;Iterative version to get the Nth Fibonacci number
;N must be a positive integer
;F is the tree containing the values
;I is a loop variable.
QUIT:(N\1'=N)!(N<0) "Error: "_N_" is not a positive integer."
NEW F,I
SET F(0)=0,F(1)=1
QUIT:N<2 F(N)
FOR I=2:1:N SET F(I)=F(I-1)+F(I-2)
QUIT F(N) |
http://rosettacode.org/wiki/Execute_a_system_command | Execute a system command | Task
Run either the ls system command (dir on Windows), or the pause system command.
Related task
Get system command output
| #TUSCRIPT | TUSCRIPT |
$$ MODE TUSCRIPT
system=SYSTEM ()
IF (system=="WIN") THEN
EXECUTE "dir"
ELSEIF (system.sw."LIN") THEN
EXECUTE "ls -l"
ENDIF
|
http://rosettacode.org/wiki/Execute_a_system_command | Execute a system command | Task
Run either the ls system command (dir on Windows), or the pause system command.
Related task
Get system command output
| #UNIX_Shell | UNIX Shell | ls |
http://rosettacode.org/wiki/Execute_a_system_command | Execute a system command | Task
Run either the ls system command (dir on Windows), or the pause system command.
Related task
Get system command output
| #Ursa | Ursa | decl string<> arg
decl string<> output
decl iodevice iod
append "ls" arg
set iod (ursa.util.process.start arg)
set output (iod.readlines)
for (decl int i) (< i (size output)) (inc i)
out output<i> endl console
end for |
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
| #COBOL | COBOL | MOVE FUNCTION FACTORIAL(num) TO result |
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
| #Verilog | Verilog |
module main;
integer number;
initial begin
for(number = 1; number < 100; number = number + 1) begin
if (number % 15 == 0) $display("FizzBuzz");
else begin
if(number % 3 == 0) $display("Fizz");
else begin
if(number % 5 == 0) $display("Buzz");
else $display(number);
end
end
end
$finish;
end
endmodule
|
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.
| #M2000_Interpreter | M2000 Interpreter |
Module Checkit {
\\ Brain**** Compiler
Escape Off
\\ no Esc function so we can use Ctrl+Z when input characters to terminate BF
\\ ctrl+c open dialog for exit - by default in console mode
Const skipmonitor as boolean=true, output as boolean=True
Const ob$="{",cb$="}"
Gosub CallOne
\\ We use a group object with events.
Group WithEvents BF=BrainF()
Function BF_monitor {
\\ Event functions have same scope as the module where belong
If skipmonitor Then exit
Read New pc, mem
Print pc, mem
Print "Press space bar": While Key$<>" " {}
}
Function BF_newline {
If not skipmonitor then Print "newline" : exit
if output then Print
}
Function BF_print {
Read New c$
If not skipmonitor then Print "character:";c$ : exit
if output then Print c$;
}
Program$ = {++++++[>++++++++++++<-]>.
>++++++++++[>++++++++++<-]>+.
+++++++..+++.>++++[>+++++++++++<-]>.
<+++[>----<-]>.<<<<<+++[>+++++<-]>.
>>.+++.------.--------.>>+.
}
Report Program$
ExecBF(Program$)
End
Sub ExecBF(Code$)
ClearMem()
code$=filter$(code$, " "+chr$(10)+chr$(13))
code$<=replace$(".","@", code$)
code$<=replace$("-","-.D()", code$)
code$<=replace$("+","-.A()", code$)
code$<=replace$("<","-.L()", code$)
code$<=replace$(">","-.R()", code$)
code$<=replace$("@","-.P()", code$)
code$<=replace$("[","-.S("+ob$,code$)
code$<=replace$("]",cb$+")",code$)
code$<=replace$(",","-.K()", code$)
Rem : Print code$
BF.Eval code$
Print
End Sub
Sub ClearMem()
Dim cMem(1 to 30000)=0
For BF {
.Pc=1
.Zero=True
.Mem()=cMem()
}
End Sub
CallOne:
Class BrainF {
events "monitor", "newline", "print"
Dim Mem()
Pc=1, Zero as Boolean=True
Module UpdateZero {
.Zero<=.Mem(.Pc)=0
call event "monitor", .pc, .Mem(.pc)
}
Function A { \\ +
.Mem(.Pc)++
.UpdateZero
}
Function D { \\ -
.Mem(.Pc)--
.UpdateZero
}
Function R { \\ >
If .Pc=30000 Then Error "Upper Bound Error"
.Pc++
.UpdateZero
}
Function L { \\ <
If .Pc=1 Then Error "Lower Bound Error"
.Pc--
.UpdateZero
}
Function P { \\ .
Select Case .Mem(.Pc)
Case >31
Call Event "print", Chr$(.Mem(.Pc))
Case 10
Call Event "newline"
End Select
}
Function K { \\ ,
.Mem(.Pc)=Asc(Key$)
\\ ctrl+z for exit
If .Mem(.Pc)=26 Then Error "Finished"
.UpdateZero
}
Function S { \\ [
If .Zero then =0: exit
Read newEval$
Do {ret=Eval(newEval$)} until .Zero
}
Module Eval {
ret=eval(Letter$)
}
}
Return
}
Checkit
|
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.
| #Objeck | Objeck | bundle Default {
class Evolutionary {
target : static : String;
possibilities : static : Char[];
C : static : Int;
minMutateRate : static : Float;
perfectFitness : static : Int;
parent : static : String ;
rand : static : Float;
function : Init() ~ Nil {
target := "METHINKS IT IS LIKE A WEASEL";
possibilities := "ABCDEFGHIJKLMNOPQRSTUVWXYZ "->ToCharArray();
C := 100;
minMutateRate := 0.09;
perfectFitness := target->Size();
}
function : fitness(trial : String) ~ Int {
retVal := 0;
each(i : trial) {
if(trial->Get(i) = target->Get(i)) {
retVal += 1;
};
};
return retVal;
}
function : newMutateRate() ~ Float {
x : Float := perfectFitness - fitness(parent);
y : Float := perfectFitness->As(Float) * (1.01 - minMutateRate);
return x / y;
}
function : mutate(parent : String, rate : Float) ~ String {
retVal := "";
each(i : parent) {
rand := Float->Random();
if(rand <= rate) {
rand *= 1000.0;
intRand := rand->As(Int);
index : Int := intRand % possibilities->Size();
retVal->Append(possibilities[index]);
}
else {
retVal->Append(parent->Get(i));
};
};
return retVal;
}
function : Main(args : String[]) ~ Nil {
Init();
parent := mutate(target, 1.0);
iter := 0;
while(target->Equals(parent) <> true) {
rate := newMutateRate();
iter += 1;
if(iter % 100 = 0){
IO.Console->Instance()->Print(iter)->Print(": ")->PrintLine(parent);
};
bestSpawn : String;
bestFit := 0;
for(i := 0; i < C; i += 1;) {
spawn := mutate(parent, rate);
fitness := fitness(spawn);
if(fitness > bestFit) {
bestSpawn := spawn;
bestFit := fitness;
};
};
if(bestFit > fitness(parent)) {
parent := bestSpawn;
};
};
parent->PrintLine();
}
}
}
} |
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
| #Nanoquery | Nanoquery | def fibIter(n)
if (n < 2)
return n
end if
$fib = 1
$fibPrev = 1
for num in range(2, n - 1)
fib += fibPrev
fibPrev = fib - fibPrev
end for
return fib
end |
http://rosettacode.org/wiki/Execute_a_system_command | Execute a system command | Task
Run either the ls system command (dir on Windows), or the pause system command.
Related task
Get system command output
| #Ursala | Ursala | #import std
#import cli
#executable ('parameterized','')
myls = <.file$[contents: --<''>]>@hm+ (ask bash)/0+ -[ls --color=no]-! |
http://rosettacode.org/wiki/Execute_a_system_command | Execute a system command | Task
Run either the ls system command (dir on Windows), or the pause system command.
Related task
Get system command output
| #VBScript | VBScript |
Set objShell = CreateObject("WScript.Shell")
objShell.Run "%comspec% /K dir",3,True
|
http://rosettacode.org/wiki/Execute_a_system_command | Execute a system command | Task
Run either the ls system command (dir on Windows), or the pause system command.
Related task
Get system command output
| #Vedit_macro_language | Vedit macro language | system("dir", DOS) |
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
| #CoffeeScript | CoffeeScript | fac = (n) ->
if n <= 1
1
else
n * fac 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
| #VHDL | VHDL | entity fizzbuzz is
end entity fizzbuzz;
architecture beh of fizzbuzz is
procedure fizzbuzz(num : natural) is
begin
if num mod 15 = 0 then
report "FIZZBUZZ";
elsif num mod 3 = 0 then
report "FIZZ";
elsif num mod 5 = 0 then
report "BUZZ";
else
report to_string(num);
end if;
end procedure fizzbuzz;
begin
p_fizz : process is
begin
for i in 1 to 100 loop
fizzbuzz(i);
end loop;
wait for 200 us;
end process p_fizz;
end architecture beh; |
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.
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | bf[program_, input_] :=
Module[{p = Characters[program], pp = 0, m, mp = 0, bc = 0,
instr = StringToStream[input]},
m[_] = 0;
While[pp < Length@p,
pp++;
Switch[p[[pp]],
">", mp++,
"<", mp--,
"+", m[mp]++,
"-", m[mp]--,
".", BinaryWrite["stdout", m[mp]],
",", m[mp] = BinaryRead[instr],
"[", If[m[mp] == 0,
bc = 1;
While[bc > 0, pp++; Switch[p[[pp]], "[", bc++, "]", bc--]]],
"]", If[m[mp] != 0,
bc = -1;
While[bc < 0, pp--; Switch[p[[pp]], "[", bc++, "]", bc--]]]]];
Close[instr];];
bf[program_] := bf[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.
| #OCaml | OCaml | let target = "METHINKS IT IS LIKE A WEASEL"
let charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ "
let tlen = String.length target
let clen = String.length charset
let () = Random.self_init()
let parent =
let s = String.create tlen in
for i = 0 to tlen-1 do
s.[i] <- charset.[Random.int clen]
done;
s
let fitness ~trial =
let rec aux i d =
if i >= tlen then d else
aux (i+1) (if target.[i] = trial.[i] then d+1 else d) in
aux 0 0
let mutate parent rate =
let s = String.copy parent in
for i = 0 to tlen-1 do
if Random.float 1.0 > rate then
s.[i] <- charset.[Random.int clen]
done;
s, fitness s
let () =
let i = ref 0 in
while parent <> target do
let pfit = fitness parent in
let rate = float pfit /. float tlen in
let tries = Array.init 200 (fun _ -> mutate parent rate) in
let min_by (a, fa) (b, fb) = if fa > fb then a, fa else b, fb in
let best, f = Array.fold_left min_by (parent, pfit) tries in
if !i mod 100 = 0 then
Printf.printf "%5d - '%s' (fitness:%2d)\n%!" !i best f;
String.blit best 0 parent 0 tlen;
incr i
done;
Printf.printf "%5d - '%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
| #Nemerle | Nemerle | using System;
using System.Console;
module Fibonacci
{
Fibonacci(x : long) : long
{
|x when x < 2 => x
|_ => Fibonacci(x - 1) + Fibonacci(x - 2)
}
Main() : void
{
def num = Int64.Parse(ReadLine());
foreach (n in $[0 .. num])
WriteLine("{0}: {1}", n, Fibonacci(n));
}
} |
http://rosettacode.org/wiki/Execute_a_system_command | Execute a system command | Task
Run either the ls system command (dir on Windows), or the pause system command.
Related task
Get system command output
| #Visual_Basic | Visual Basic | Attribute VB_Name = "mdlShellAndWait"
Option Explicit
Private Declare Function OpenProcess Lib "kernel32" _
(ByVal dwDesiredAccess As Long, ByVal bInheritHandle As Long, _
ByVal dwProcessId As Long) As Long
Private Declare Function GetExitCodeProcess Lib "kernel32" _
(ByVal hProcess As Long, lpExitCode As Long) As Long
Private Const STATUS_PENDING = &H103&
Private Const PROCESS_QUERY_INFORMATION = &H400
'
' Little function go get exit code given processId
'
Function ProcessIsRunning( processId as Long ) as Boolean
Dim exitCode as Long
Call GetExitCodeProcess(lProcessId, exitCode)
ProcessIsRunning = (exitCode = STATUS_PENDING)
End Function
' Spawn subprocess and wait for it to complete.
' I believe that the command in the command line must be an exe or a bat file.
' Maybe, however, it can reference any file the system knows how to "Open"
'
' commandLine is an executable.
' expectedDuration - is for poping up a dialog for whatever
' infoText - text for progressDialog dialog
Public Function ShellAndWait( commandLine As String, _
expectedDuration As Integer ) As Boolean
Dim inst As Long
Dim startTime As Long
Dim expirationTime As Long
Dim pid As Long
Dim expiresSameDay As Boolean
On Error GoTo HandleError
'Deal with timeout being reset at Midnight ($hitForBrains VB folks)
startTime = CLng(Timer)
expirationTime = startTime + expectedDuration
expiresSameDay = expirationTime < 86400
If Not expiresSameDay Then
expirationTime = expirationTime - 86400
End If
inst = Shell(commandLine, vbMinimizedNoFocus)
If inst <> 0 Then
pid = OpenProcess(PROCESS_QUERY_INFORMATION, False, inst)
Do While ProcessIsRunning( pid)
DoEvents
If Timer > expirationTime And (expiresSameDay Or Timer < startTime) Then
Exit Do
End If
Loop
ShellAndWait = True
Else
MsgBox ("Couldn't execute command: " & commandLine)
ShellAndWait = False
End If
Exit Function
HandleError:
MsgBox ("Couldn't execute command: " & commandLine)
ShellAndWait = False
End Function
Sub SpawnDir()
ShellAndWait("dir", 10)
End Sub |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.