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/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
| #Symsyn | Symsyn |
| FizzBuzz
1 I
if I LE 100
mod I 3 X
mod I 5 Y
if X EQ 0
'FIZZ' $S
if Y EQ 0
+ 'BUZZ' $S
endif
else
if Y EQ 0
'BUZZ' $S
else
~ I $S
endif
endif
$S []
+ I
goif
endif
|
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.
| #Forth | Forth | MODULE BRAIN !It will suffer.
INTEGER MSG,KBD
CONTAINS !A twisted interpreter.
SUBROUTINE RUN(PROG,STORE) !Code and data are separate!
CHARACTER*(*) PROG !So, this is the code.
CHARACTER*(1) STORE(:) !And this a work area.
CHARACTER*1 C !The code of the moment.
INTEGER I,D !Fingers to an instruction, and to data.
D = 1 !First element of the store.
I = 1 !First element of the prog.
DO WHILE(I.LE.LEN(PROG)) !Off the end yet?
C = PROG(I:I) !Load the opcode fingered by I.
I = I + 1 !Advance one. The classic.
SELECT CASE(C) !Now decode the instruction.
CASE(">"); D = D + 1 !Move the data finger one place right.
CASE("<"); D = D - 1 !Move the data finger one place left.
CASE("+"); STORE(D) = CHAR(ICHAR(STORE(D)) + 1) !Add one to the fingered datum.
CASE("-"); STORE(D) = CHAR(ICHAR(STORE(D)) - 1) !Subtract one.
CASE("."); WRITE (MSG,1) STORE(D) !Write a character.
CASE(","); READ (KBD,1) STORE(D) !Read a character.
CASE("["); IF (ICHAR(STORE(D)).EQ.0) CALL SEEK(+1) !Conditionally, surge forward.
CASE("]"); IF (ICHAR(STORE(D)).NE.0) CALL SEEK(-1) !Conditionally, retreat.
CASE DEFAULT !For all others,
!Do nothing.
END SELECT !That was simple.
END DO !See what comes next.
1 FORMAT (A1,$) !One character, no advance to the next line.
CONTAINS !Now for an assistant.
SUBROUTINE SEEK(WAY) !Look for the BA that matches the AB.
INTEGER WAY !Which direction: ±1.
CHARACTER*1 AB,BA !The dancers.
INTEGER INDEEP !Nested brackets are allowed.
INDEEP = 0 !None have been counted.
I = I - 1 !Back to where C came from PROG.
AB = PROG(I:I) !The starter.
BA = "[ ]"(WAY + 2:WAY + 2) !The stopper.
1 IF (I.GT.LEN(PROG)) STOP "Out of code!" !Perhaps not!
IF (PROG(I:I).EQ.AB) THEN !A starter? (Even if backwards)
INDEEP = INDEEP + 1 !Yep.
ELSE IF (PROG(I:I).EQ.BA) THEN !A stopper?
INDEEP = INDEEP - 1 !Yep.
END IF !A case statement requires constants.
IF (INDEEP.GT.0) THEN !Are we out of it yet?
I = I + WAY !No. Move.
IF (I.GT.0) GO TO 1 !And try again.
STOP "Back to 0!" !Perhaps not.
END IF !But if we are out of the nest,
I = I + 1 !Advance to the following instruction, either WAY.
END SUBROUTINE SEEK !Seek, and one shall surely find.
END SUBROUTINE RUN !So much for that.
END MODULE BRAIN !Simple in itself.
PROGRAM POKE !A tester.
USE BRAIN !In a rather bad way.
CHARACTER*1 STORE(30000) !Probably rather more than is needed.
CHARACTER*(*) HELLOWORLD !Believe it or not...
PARAMETER (HELLOWORLD = "++++++++[>++++[>++>+++>+++>+<<<<-]"
1 //" >+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------"
2 //".--------.>>+.>++.")
KBD = 5 !Standard input.
MSG = 6 !Standard output.
STORE = CHAR(0) !Scrub.
CALL RUN(HELLOWORLD,STORE) !Have a go.
END !Enough. |
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.
| #FreeBASIC | FreeBASIC | ' version 01-07-2018
' compile with: fbc -s console
Randomize Timer
Const As UInteger children = 100
Const As Double mutate_rate = 0.05
Function fitness(target As String, tmp As String) As UInteger
Dim As UInteger x, f
For x = 0 To Len(tmp) -1
If tmp[x] = target[x] Then f += 1
Next
Return f
End Function
Sub mutate(tmp As String, chars As String, mute_rate As Double)
If Rnd <= mute_rate Then
tmp[Int(Rnd * Len(tmp))] = chars[Int(Rnd * Len(chars))]
End If
End Sub
' ------=< MAIN >=------
Dim As String target = "METHINKS IT IS LIKE A WEASEL"
Dim As String chars = " ABCDEFGHIJKLMNOPQRSTUVWXYZ"
Dim As String parent, mutation()
Dim As UInteger x, iter, f, fit(), best_fit, parent_fit
For x = 1 To Len(target)
parent += Chr(chars[Int(Rnd * Len(chars))])
Next
f = fitness(target, parent)
parent_fit = f
best_fit = f
Print "iteration best fit Parent"
Print "========= ======== ============================"
Print Using " #### #### ";iter; best_fit;
Print parent
Do
iter += 1
ReDim mutation(1 To children),fit(1 To children)
For x = 1 To children
mutation(x) = parent
mutate(mutation(x), chars, mutate_rate)
Next
For x = 1 To children
If mutation(x) <> parent Then
f = fitness(target, mutation(x))
If best_fit < f Then
best_fit = f
fit(x) = f
Else
fit(x) = parent_fit
End If
End If
Next
If best_fit > parent_fit Then
For x = 1 To children
If fit(x) = best_fit Then
parent = mutation(x)
Print Using " #### #### ";iter; best_fit;
Print parent
End If
Next
End If
Loop Until parent = target
' empty keyboard buffer
While InKey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
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
| #MATLAB | MATLAB | function f = fib(n)
f = [1 1 ; 1 0]^(n-1);
f = f(1,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
| #R | R |
e <- simpleError("This is a simpleError")
|
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
| #Racket | Racket |
#lang racket
;; define a new exception type
(struct exn:my-exception exn ())
;; handler that prints the message ("Hi!")
(define (handler exn)
(displayln (exn-message exn)))
;; install exception handlers
(with-handlers ([exn:my-exception? handler])
;; raise the exception
(raise (exn:my-exception "Hi!" (current-continuation-marks))))
|
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
| #NewLISP | NewLISP | (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
| #Nim | Nim | import osproc
let exitCode = execCmd "ls"
let (output, exitCode2) = execCmdEx "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
| #Objective-C | Objective-C | void runls()
{
[[NSTask launchedTaskWithLaunchPath:@"/bin/ls"
arguments:@[]] waitUntilExit];
} |
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
| #Brainf.2A.2A.2A | Brainf*** | >++++++++++>>>+>+[>>>+[-[<<<<<[+<<<<<]>>[[-]>[<<+>+>-]<[>+<-]<[>+<-[>+<-[>
+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>[-]>>>>+>+<<<<<<-[>+<-]]]]]]]]]]]>[<+>-
]+>>>>>]<<<<<[<<<<<]>>>>>>>[>>>>>]++[-<<<<<]>>>>>>-]+>>>>>]<[>++<-]<<<<[<[
>+<-]<<<<]>>[->[-]++++++[<++++++++>-]>>>>]<<<<<[<[>+>+<<-]>.<<<<<]>.>>>>] |
http://rosettacode.org/wiki/Exponentiation_operator | Exponentiation operator | Most programming languages have a built-in implementation of exponentiation.
Task
Re-implement integer exponentiation for both intint and floatint as both a procedure, and an operator (if your language supports operator definition).
If the language supports operator (or procedure) overloading, then an overloaded form should be provided for both intint and floatint variants.
Related tasks
Exponentiation order
arbitrary-precision integers (included)
Exponentiation with infix operators in (or operating on) the base
| #Scheme | Scheme | (define (^ base exponent)
(define (*^ exponent acc)
(if (= exponent 0)
acc
(*^ (- exponent 1) (* acc base))))
(*^ exponent 1))
(display (^ 2 3))
(newline)
(display (^ (/ 1 2) 3))
(newline)
(display (^ 0.5 3))
(newline)
(display (^ 2+i 3))
(newline) |
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
| #Tailspin | Tailspin |
templates fizz
$ mod 3 -> #
when <=0> do 'Fizz' !
end fizz
templates buzz
$ mod 5 -> #
when <=0> do 'Buzz' !
end buzz
[ 1..100 -> '$->fizz;$->buzz;' ] -> \[i](when <=''> do $i ! otherwise $ !\)... -> '$;
' -> !OUT::write
|
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.
| #Fortran | Fortran | MODULE BRAIN !It will suffer.
INTEGER MSG,KBD
CONTAINS !A twisted interpreter.
SUBROUTINE RUN(PROG,STORE) !Code and data are separate!
CHARACTER*(*) PROG !So, this is the code.
CHARACTER*(1) STORE(:) !And this a work area.
CHARACTER*1 C !The code of the moment.
INTEGER I,D !Fingers to an instruction, and to data.
D = 1 !First element of the store.
I = 1 !First element of the prog.
DO WHILE(I.LE.LEN(PROG)) !Off the end yet?
C = PROG(I:I) !Load the opcode fingered by I.
I = I + 1 !Advance one. The classic.
SELECT CASE(C) !Now decode the instruction.
CASE(">"); D = D + 1 !Move the data finger one place right.
CASE("<"); D = D - 1 !Move the data finger one place left.
CASE("+"); STORE(D) = CHAR(ICHAR(STORE(D)) + 1) !Add one to the fingered datum.
CASE("-"); STORE(D) = CHAR(ICHAR(STORE(D)) - 1) !Subtract one.
CASE("."); WRITE (MSG,1) STORE(D) !Write a character.
CASE(","); READ (KBD,1) STORE(D) !Read a character.
CASE("["); IF (ICHAR(STORE(D)).EQ.0) CALL SEEK(+1) !Conditionally, surge forward.
CASE("]"); IF (ICHAR(STORE(D)).NE.0) CALL SEEK(-1) !Conditionally, retreat.
CASE DEFAULT !For all others,
!Do nothing.
END SELECT !That was simple.
END DO !See what comes next.
1 FORMAT (A1,$) !One character, no advance to the next line.
CONTAINS !Now for an assistant.
SUBROUTINE SEEK(WAY) !Look for the BA that matches the AB.
INTEGER WAY !Which direction: ±1.
CHARACTER*1 AB,BA !The dancers.
INTEGER INDEEP !Nested brackets are allowed.
INDEEP = 0 !None have been counted.
I = I - 1 !Back to where C came from PROG.
AB = PROG(I:I) !The starter.
BA = "[ ]"(WAY + 2:WAY + 2) !The stopper.
1 IF (I.GT.LEN(PROG)) STOP "Out of code!" !Perhaps not!
IF (PROG(I:I).EQ.AB) THEN !A starter? (Even if backwards)
INDEEP = INDEEP + 1 !Yep.
ELSE IF (PROG(I:I).EQ.BA) THEN !A stopper?
INDEEP = INDEEP - 1 !Yep.
END IF !A case statement requires constants.
IF (INDEEP.GT.0) THEN !Are we out of it yet?
I = I + WAY !No. Move.
IF (I.GT.0) GO TO 1 !And try again.
STOP "Back to 0!" !Perhaps not.
END IF !But if we are out of the nest,
I = I + 1 !Advance to the following instruction, either WAY.
END SUBROUTINE SEEK !Seek, and one shall surely find.
END SUBROUTINE RUN !So much for that.
END MODULE BRAIN !Simple in itself.
PROGRAM POKE !A tester.
USE BRAIN !In a rather bad way.
CHARACTER*1 STORE(30000) !Probably rather more than is needed.
CHARACTER*(*) HELLOWORLD !Believe it or not...
PARAMETER (HELLOWORLD = "++++++++[>++++[>++>+++>+++>+<<<<-]"
1 //" >+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------"
2 //".--------.>>+.>++.")
KBD = 5 !Standard input.
MSG = 6 !Standard output.
STORE = CHAR(0) !Scrub.
CALL RUN(HELLOWORLD,STORE) !Have a go.
END !Enough. |
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.
| #F.C5.8Drmul.C3.A6 | Fōrmulæ | package main
import (
"fmt"
"math/rand"
"time"
)
var target = []byte("METHINKS IT IS LIKE A WEASEL")
var set = []byte("ABCDEFGHIJKLMNOPQRSTUVWXYZ ")
var parent []byte
func init() {
rand.Seed(time.Now().UnixNano())
parent = make([]byte, len(target))
for i := range parent {
parent[i] = set[rand.Intn(len(set))]
}
}
// fitness: 0 is perfect fit. greater numbers indicate worse fit.
func fitness(a []byte) (h int) {
// (hamming distance)
for i, tc := range target {
if a[i] != tc {
h++
}
}
return
}
// set m to mutation of p, with each character of p mutated with probability r
func mutate(p, m []byte, r float64) {
for i, ch := range p {
if rand.Float64() < r {
m[i] = set[rand.Intn(len(set))]
} else {
m[i] = ch
}
}
}
func main() {
const c = 20 // number of times to copy and mutate parent
copies := make([][]byte, c)
for i := range copies {
copies[i] = make([]byte, len(parent))
}
fmt.Println(string(parent))
for best := fitness(parent); best > 0; {
for _, cp := range copies {
mutate(parent, cp, .05)
}
for _, cp := range copies {
fm := fitness(cp)
if fm < best {
best = fm
copy(parent, cp)
fmt.Println(string(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
| #Maxima | Maxima | /* fib(n) is built-in; here is an implementation */
fib2(n) := (matrix([0, 1], [1, 1])^^n)[1, 2]$
fib2(100)-fib(100);
0
fib2(-10);
-55 |
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
| #Raku | Raku | try {
die "Help I'm dieing!";
CATCH {
when X::AdHoc { note .Str.uc; say "Cough, Cough, Aiee!!" }
default { note "Unexpected exception, $_!" }
}
}
say "Yay. I'm alive.";
die "I'm dead.";
say "Arrgh.";
CATCH {
default { note "No you're not."; say $_.Str; }
} |
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
| #Raven | Raven | 42 as custom_error
define foo
custom_error throw
try
foo
catch
custom_error =
if 'oops' print |
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
| #OCaml | OCaml | Sys.command "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
| #Octave | Octave | 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
| #Brat | Brat | factorial = { x |
true? x == 0 1 { x * factorial(x - 1)}
} |
http://rosettacode.org/wiki/Exponentiation_operator | Exponentiation operator | Most programming languages have a built-in implementation of exponentiation.
Task
Re-implement integer exponentiation for both intint and floatint as both a procedure, and an operator (if your language supports operator definition).
If the language supports operator (or procedure) overloading, then an overloaded form should be provided for both intint and floatint variants.
Related tasks
Exponentiation order
arbitrary-precision integers (included)
Exponentiation with infix operators in (or operating on) the base
| #Seed7 | Seed7 | const func integer: intPow (in var integer: base, in var integer: exponent) is func
result
var integer: result is 0;
begin
if exponent < 0 then
raise(NUMERIC_ERROR);
else
if odd(exponent) then
result := base;
else
result := 1;
end if;
exponent := exponent div 2;
while exponent <> 0 do
base *:= base;
if odd(exponent) then
result *:= base;
end if;
exponent := exponent div 2;
end while;
end if;
end func; |
http://rosettacode.org/wiki/Exponentiation_operator | Exponentiation operator | Most programming languages have a built-in implementation of exponentiation.
Task
Re-implement integer exponentiation for both intint and floatint as both a procedure, and an operator (if your language supports operator definition).
If the language supports operator (or procedure) overloading, then an overloaded form should be provided for both intint and floatint variants.
Related tasks
Exponentiation order
arbitrary-precision integers (included)
Exponentiation with infix operators in (or operating on) the base
| #Sidef | Sidef | func expon(_, {.is_zero}) { 1 }
func expon(base, exp {.is_neg}) {
expon(1/base, -exp)
}
func expon(base, exp {.is_int}) {
var c = 1
while (exp > 1) {
c *= base if exp.is_odd
base *= base
exp >>= 1
}
return (base * c)
}
say expon(3, 10)
say expon(5.5, -3) |
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
| #Tcl | Tcl | proc fizzbuzz {n {m1 3} {m2 5}} {
for {set i 1} {$i <= $n} {incr i} {
set ans ""
if {$i % $m1 == 0} {append ans Fizz}
if {$i % $m2 == 0} {append ans Buzz}
puts [expr {$ans eq "" ? $i : $ans}]
}
}
fizzbuzz 100 |
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.
| #FreeBASIC | FreeBASIC |
' Intérprete de brainfuck
' FB 1.05.0 Win64
'
Const BF_error_memoria_saturada As Integer = 2
Const BF_error_memoria_insuficiente As Integer = 4
Const BF_error_codigo_saturado As Integer = 8
Const BF_error_desbordamiento_codigo As Integer = 16
Dim BFcodigo As String = ">++++++++++[>+++>+++++++>++++++++++>+++++++++++>++++++++++++>++++++++++++++++[<]>-]>>>>>>+.<<<<++.>>+.---.<---.<<++.>>>+.>---.<+.<+++.>+.<<<+."
Dim codigo_error As Integer
Function EjecutarBF (BFcodigo As String, tammem As Uinteger) As Integer
Dim As String memoria = String(tammem, 0)
Dim As Uinteger puntero_instrucciones, puntero_datos
Dim As Integer nivel_de_alcance
For puntero_instrucciones = 0 To Len(BFcodigo)
Select Case Chr(BFcodigo[puntero_instrucciones])
Case ">"
puntero_datos += 1
If (puntero_datos > tammem - 1) Then Return BF_error_memoria_saturada
Case "<"
puntero_datos -= 1
If (puntero_datos > tammem - 1) Then Return BF_error_memoria_insuficiente
Case "+"
memoria[puntero_datos] += 1
Case "-"
memoria[puntero_datos] -= 1
Case "."
Print Chr(memoria[puntero_datos]);
Case ","
memoria[puntero_datos] = Asc(Input(1))
Case "["
If (memoria[puntero_datos] = 0) Then
Dim nivel_antiguo As Uinteger = nivel_de_alcance
nivel_de_alcance += 1
Do Until (nivel_de_alcance = nivel_antiguo)
puntero_instrucciones += 1
If (puntero_instrucciones > Len(BFcodigo) - 1) Then Return BF_error_codigo_saturado
Select Case Chr(BFcodigo[puntero_instrucciones])
Case "["
nivel_de_alcance += 1
Case "]"
nivel_de_alcance -= 1
End Select
Loop
Else
nivel_de_alcance += 1
End If
Continue For
Case "]"
If (memoria[puntero_datos] = 0) Then
nivel_de_alcance -= 1
Continue For
Else
Dim nivel_antiguo As Integer = nivel_de_alcance
nivel_de_alcance -= 1
Do Until (nivel_de_alcance = nivel_antiguo)
puntero_instrucciones -= 1
If (puntero_instrucciones > Len(BFcodigo) - 1) Then Return BF_error_desbordamiento_codigo
Select Case Chr(BFcodigo[puntero_instrucciones])
Case "["
nivel_de_alcance += 1
Case "]"
nivel_de_alcance -= 1
End Select
Loop
End If
Continue For
Case Else
Continue For
End Select
Next puntero_instrucciones
Return -1
End Function
Cls
codigo_error = EjecutarBF(BFcodigo, 1024)
If codigo_error Then
Sleep
Else
Print "codigo de error: " & codigo_error
End If
End
|
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.
| #Go | Go | package main
import (
"fmt"
"math/rand"
"time"
)
var target = []byte("METHINKS IT IS LIKE A WEASEL")
var set = []byte("ABCDEFGHIJKLMNOPQRSTUVWXYZ ")
var parent []byte
func init() {
rand.Seed(time.Now().UnixNano())
parent = make([]byte, len(target))
for i := range parent {
parent[i] = set[rand.Intn(len(set))]
}
}
// fitness: 0 is perfect fit. greater numbers indicate worse fit.
func fitness(a []byte) (h int) {
// (hamming distance)
for i, tc := range target {
if a[i] != tc {
h++
}
}
return
}
// set m to mutation of p, with each character of p mutated with probability r
func mutate(p, m []byte, r float64) {
for i, ch := range p {
if rand.Float64() < r {
m[i] = set[rand.Intn(len(set))]
} else {
m[i] = ch
}
}
}
func main() {
const c = 20 // number of times to copy and mutate parent
copies := make([][]byte, c)
for i := range copies {
copies[i] = make([]byte, len(parent))
}
fmt.Println(string(parent))
for best := fitness(parent); best > 0; {
for _, cp := range copies {
mutate(parent, cp, .05)
}
for _, cp := range copies {
fm := fitness(cp)
if fm < best {
best = fm
copy(parent, cp)
fmt.Println(string(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
| #MAXScript | MAXScript | fn fibIter n =
(
if n < 2 then
(
n
)
else
(
fib = 1
fibPrev = 1
for num in 3 to n do
(
temp = fib
fib += fibPrev
fibPrev = temp
)
fib
)
) |
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
| #REXX | REXX | /*REXX program demonstrates handling an exception (negative #); catching is via a label.*/
do j=9 by -5
say 'the square root of ' j " is " sqrt(j)
end /*j*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); h=d+6; m.=9
numeric digits; numeric form; if x<0 then signal .sqrtNeg
parse value format(x, 2, 1, , 0) 'E0' with g 'E' _ .; g=g * .5'e'_ % 2
do j=0 while h>9; m.j=h; h=h%2 + 1; end /*j*/
do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g) * .5; end /*k*/
numeric digits d; return g/1
.sqrtNeg: say 'illegal SQRT argument (argument is negative):' x; exit 13 |
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
| #Ring | Ring |
Try
see 1/0
Catch
raise("Sorry we can't divide 1/0 + nl)
Done
|
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
| #Oforth | Oforth | System cmd("pause") |
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
| #Oz | Oz | {OS.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
| #PARI.2FGP | PARI/GP | 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
| #Burlesque | Burlesque |
blsq ) 6?!
720
|
http://rosettacode.org/wiki/Exponentiation_operator | Exponentiation operator | Most programming languages have a built-in implementation of exponentiation.
Task
Re-implement integer exponentiation for both intint and floatint as both a procedure, and an operator (if your language supports operator definition).
If the language supports operator (or procedure) overloading, then an overloaded form should be provided for both intint and floatint variants.
Related tasks
Exponentiation order
arbitrary-precision integers (included)
Exponentiation with infix operators in (or operating on) the base
| #Slate | Slate | x@(Number traits) raisedTo: y@(Integer traits)
[
y isZero ifTrue: [^ x unit].
x isZero \/ [y = 1] ifTrue: [^ x].
y isPositive
ifTrue:
"(x * x raisedTo: y // 2) * (x raisedTo: y \\ 2)"
[| count result |
count: 1.
[(count: (count bitShift: 1)) < y] whileTrue.
result: x unit.
[count isPositive]
whileTrue:
[result: result squared.
(y bitAnd: count) isZero ifFalse: [result: result * x].
count: (count bitShift: -1)].
result]
ifFalse: [(x raisedTo: y negated) reciprocal]
]. |
http://rosettacode.org/wiki/Exponentiation_operator | Exponentiation operator | Most programming languages have a built-in implementation of exponentiation.
Task
Re-implement integer exponentiation for both intint and floatint as both a procedure, and an operator (if your language supports operator definition).
If the language supports operator (or procedure) overloading, then an overloaded form should be provided for both intint and floatint variants.
Related tasks
Exponentiation order
arbitrary-precision integers (included)
Exponentiation with infix operators in (or operating on) the base
| #Smalltalk | Smalltalk | Number extend [
** anInt [
| r |
( anInt isInteger )
ifFalse:
[ '** works fine only for integer powers'
displayOn: stderr . Character nl displayOn: stderr ].
r := 1.
1 to: anInt do: [ :i | r := ( r * self ) ].
^r
]
].
( 2.5 ** 3 ) displayNl.
( 2 ** 10 ) displayNl.
( 3/7 ** 3 ) displayNl. |
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
| #TI-83_BASIC | TI-83 BASIC | : FIZZBUZZ
101 1 DO
I 15 MOD 0 = IF
PRINT " FIZZBUZZ "
ELSE I 3 MOD 0 = IF
PRINT " FIZZ "
ELSE I 5 MOD 0 = IF
PRINT " BUZZ "
ELSE I . THEN THEN THEN
CR LOOP ; |
http://rosettacode.org/wiki/Execute_Brain**** | Execute Brain**** | Execute Brain**** is an implementation of Brainf***.
Other implementations of Brainf***.
RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages.
Below are links to each of the versions of RCBF.
An implementation need only properly implement the following instructions:
Command
Description
>
Move the pointer to the right
<
Move the pointer to the left
+
Increment the memory cell under the pointer
-
Decrement the memory cell under the pointer
.
Output the character signified by the cell at the pointer
,
Input a character and store it in the cell at the pointer
[
Jump past the matching ] if the cell under the pointer is 0
]
Jump back to the matching [ if the cell under the pointer is nonzero
Any cell size is allowed, EOF (End-O-File) support is optional, as is whether you have bounded or unbounded memory.
| #Furor | Furor |
argc 3 < { ."Usage: furor brainfuck.upu brainfuckpgmfile\n" }{
2 argv getfile // dup #s print free
sto bfpgm
100000 mem dup maximize sto bfmem // Memóriaallokáció a brainfuck memóriaterület számára
tick sto startingtick
sbr §brainfuck
NL
tick @startingtick #g - ."Time = " print ." tick\n"
@bfmem free // A lefoglalt munkamemória felszabadítása
}
end
// ===================================================
brainfuck:
#g @bfpgm~ !{ rts } // Ha nulla a brainfuck progi hossza, semmit se kell csinálni.
zero p zero m // Indexregiszterek lenullázása (inicializálás)
((( @p @bfpgm~ < )
§jumpingtable "+-<>[].,"
@[]bfpgm @p // Az épp aktuális brainfuck utasítás kódja
switch // Ugrás a megfelelő brainfuck funkció rutinjára
____: inc p (<) // default action
_3c_: @m !{ rts } dec m goto §____ // <
_3e_: @m @bfmem~ >= { rts } inc m goto §____ // >
_2b_: #c @[++]bfmem @m #g goto §____ // +
_2d_: #c @[--]bfmem @m #g goto §____ // -
_2c_: @bfmem @m getchar [^] goto §____
_2e_: @[]bfmem @m printchar goto §____
_5b_: @[]bfmem @m then §____
zero d @p ++ @bfpgm~ {||
{} []@bfpgm '[ == { inc d {<} }
{} []@bfpgm '] == { @d !{ {+} sto p {>} } dec d }
|} (<)
_5d_: zero d 1 @p {|| {-} []@bfpgm '] == { inc d {<} }
{-} []@bfpgm '[ == { @d !{ {} !sum p {>} } dec d }
|} (<)
)) rts
// ===================================================
{ „startingtick” }
{ „bfpgm” }
{ „bfmem” }
{ „p” /* index az épp végrehajtandó brainfuck mnemonikra */ }
{ „m” /* index a brainfuck memóriaterületre */ }
{ „d” /* munkaváltozó */ }
// ========================================
jumpingtable:
// + - < > [ ] . ,
§_2b_ §_2d_ §_3c_ §_3e_ §_5b_ §_5d_ §_2e_ §_2c_
|
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.
| #Haskell | Haskell | import System.Random
import Control.Monad
import Data.List
import Data.Ord
import Data.Array
showNum :: (Num a, Show a) => Int -> a -> String
showNum w = until ((>w-1).length) (' ':) . show
replace :: Int -> a -> [a] -> [a]
replace n c ls = take (n-1) ls ++ [c] ++ drop n ls
target = "METHINKS IT IS LIKE A WEASEL"
pfit = length target
mutateRate = 20
popsize = 100
charSet = listArray (0,26) $ ' ': ['A'..'Z'] :: Array Int Char
fitness = length . filter id . zipWith (==) target
printRes i g = putStrLn $
"gen:" ++ showNum 4 i ++ " "
++ "fitn:" ++ showNum 4 (round $ 100 * fromIntegral s / fromIntegral pfit ) ++ "% "
++ show g
where s = fitness g
mutate :: [Char] -> Int -> IO [Char]
mutate g mr = do
let r = length g
chances <- replicateM r $ randomRIO (1,mr)
let pos = elemIndices 1 chances
chrs <- replicateM (length pos) $ randomRIO (bounds charSet)
let nchrs = map (charSet!) chrs
return $ foldl (\ng (p,c) -> replace (p+1) c ng) g (zip pos nchrs)
evolve :: [Char] -> Int -> Int -> IO ()
evolve parent gen mr = do
when ((gen-1) `mod` 20 == 0) $ printRes (gen-1) parent
children <- replicateM popsize (mutate parent mr)
let child = maximumBy (comparing fitness) (parent:children)
if fitness child == pfit then printRes gen child
else evolve child (succ gen) mr
main = do
let r = length target
genes <- replicateM r $ randomRIO (bounds charSet)
let parent = map (charSet!) genes
evolve parent 1 mutateRate |
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
| #Mercury | Mercury |
% The following code is derived from the Mercury Tutorial by Ralph Becket.
% http://www.mercury.csse.unimelb.edu.au/information/papers/book.pdf
:- module fib.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
:- import_module int.
:- pred fib(int::in, int::out) is det.
fib(N, X) :-
( if N =< 2
then X = 1
else fib(N - 1, A), fib(N - 2, B), X = A + B ).
:- func fib(int) = int is det.
fib(N) = X :- fib(N, X).
main(!IO) :-
fib(40, X),
write_string("fib(40, ", !IO),
write_int(X, !IO),
write_string(")\n", !IO),
write_string("fib(40) = ", !IO),
write_int(fib(40), !IO),
write_string("\n", !IO).
|
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
| #Ruby | Ruby | # define an exception
class SillyError < Exception
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
| #Rust | Rust | // IO error is used here just as an example of an already existing
// Error
use std::io::{Error, ErrorKind};
// Rust technically doesn't have exception, but different
// types of error handling. Here are two examples of results.
fn valid_function() -> Result<usize, Error> {
Ok(100)
}
fn errored_function() -> Result<usize, Error> {
Err(Error::new(ErrorKind::Other, "Something wrong happened."))
}
// This should happen only when an unrecoverable error happened
fn panicking_function() {
panic!("Unrecoverable state reached");
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_valid_function() {
let result = match valid_function() {
Ok(number) => number,
Err(_) => panic!("This is not going to happen"),
};
assert_eq!(result, 100);
}
#[test]
fn test_errored_function() {
let result = match errored_function() {
Ok(_) => panic!("This is not going to happen"),
Err(e) => {
assert_eq!(e.to_string(), "Something wrong happened.");
0
}
};
assert_eq!(result, 0);
}
#[test]
#[should_panic]
fn test_panicking_function() {
panicking_function();
}
} |
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
| #Pascal | Pascal | Program ExecuteSystemCommand;
uses
SysUtils;
begin
ExecuteProcess('/bin/ls', '-alh');
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
| #PDP-11_Assembly | PDP-11 Assembly | ; Execute a file - the equivalent of system() in stdio
;
; On entry, r1=>nul-terminated command string
; On exit, VS=Couldn't fork
; VC=Forked successfully, r0=return value
;
.CLIsystem
trap 2 ; fork()
br CLIchild ; Child process returns here
bcc CLIparent ; Parent process returns here
mov (sp)+,r1
tst (sp)+
sev ; Couldn't fork, set V
rts pc
.CLIparent
mov r0,-(sp) ; Save child's PID
.CLIwait
trap 7 ; wait()
cmp r0,(sp)
beq CLIfinished
cmp r0,#&FFFF
bne CLIwait ; Loop until child finished
.CLIfinished
tst (sp)+ ; Drop child's PID
mov r1,r0 ; R0=return value
mov (sp)+,r1 ; Restore R1
tst (sp)+ ; Drop original R0
swab r0 ; Move return value to bottom byte
rts pc
; CLI child process
; -----------------
.CLIchild
clr -(sp) ; end of string array
mov r1,-(sp) ; => command string
mov #UXsh3,-(sp) ; => "-c"
mov #UXsh2,-(sp) ; => "sh"
mov #&890B,TRAP_BUF ; exec
mov #UXsh1,TRAP_BUF+2 ; => "/bin/sh"
mov sp,TRAP_BUF+4 ; => pointers to command strings
;mov SV_ENVPTR,TRAP_BUF+6 ; => "PATH=etc"
trap 0 ; indir()
EQUW TRAP_BUF ; exec(shell, parameters)
add #8,sp ; If we get back, we didn't fork, we spawned
mov (sp)+,r1 ; So, restore registers
clr (sp)+ ; and return exit value in R0
rts pc
.UXsh1 EQUS "/bin/sh",0
.UXsh2 EQUS "sh",0
.UXsh3 EQUS "-c",0
ALIGN
.TRAP_BUF
EQUW 0
EQUW 0
EQUW 0
EQUW 0 |
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
| #C | C | int factorial(int n) {
int result = 1;
for (int i = 1; i <= n; ++i)
result *= i;
return result;
}
|
http://rosettacode.org/wiki/Exponentiation_operator | Exponentiation operator | Most programming languages have a built-in implementation of exponentiation.
Task
Re-implement integer exponentiation for both intint and floatint as both a procedure, and an operator (if your language supports operator definition).
If the language supports operator (or procedure) overloading, then an overloaded form should be provided for both intint and floatint variants.
Related tasks
Exponentiation order
arbitrary-precision integers (included)
Exponentiation with infix operators in (or operating on) the base
| #Standard_ML | Standard ML | fun expt_int (a, b) = let
fun aux (x, i) =
if i = b then x
else aux (x * a, i + 1)
in
aux (1, 0)
end
fun expt_real (a, b) = let
fun aux (x, i) =
if i = b then x
else aux (x * a, i + 1)
in
aux (1.0, 0)
end
val op ** = expt_int
infix 6 **
val op *** = expt_real
infix 6 *** |
http://rosettacode.org/wiki/Exponentiation_operator | Exponentiation operator | Most programming languages have a built-in implementation of exponentiation.
Task
Re-implement integer exponentiation for both intint and floatint as both a procedure, and an operator (if your language supports operator definition).
If the language supports operator (or procedure) overloading, then an overloaded form should be provided for both intint and floatint variants.
Related tasks
Exponentiation order
arbitrary-precision integers (included)
Exponentiation with infix operators in (or operating on) the base
| #Stata | Stata | mata
function pow(a, n) {
x = a
for(p=1; n>0; n=floor(n/2)) {
if(mod(n,2)==1) p = p*x
x = x*x
}
return(p)
}
end |
http://rosettacode.org/wiki/FizzBuzz | FizzBuzz | Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
| #TI-83_Hex_Assembly | TI-83 Hex Assembly | : FIZZBUZZ
101 1 DO
I 15 MOD 0 = IF
PRINT " FIZZBUZZ "
ELSE I 3 MOD 0 = IF
PRINT " FIZZ "
ELSE I 5 MOD 0 = IF
PRINT " BUZZ "
ELSE I . THEN THEN THEN
CR LOOP ; |
http://rosettacode.org/wiki/Execute_Brain**** | Execute Brain**** | Execute Brain**** is an implementation of Brainf***.
Other implementations of Brainf***.
RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages.
Below are links to each of the versions of RCBF.
An implementation need only properly implement the following instructions:
Command
Description
>
Move the pointer to the right
<
Move the pointer to the left
+
Increment the memory cell under the pointer
-
Decrement the memory cell under the pointer
.
Output the character signified by the cell at the pointer
,
Input a character and store it in the cell at the pointer
[
Jump past the matching ] if the cell under the pointer is 0
]
Jump back to the matching [ if the cell under the pointer is nonzero
Any cell size is allowed, EOF (End-O-File) support is optional, as is whether you have bounded or unbounded memory.
| #GAP | GAP | # Here . and , print and read an integer, not a character
Brainfuck := function(prog)
local pointer, stack, leftcells, rightcells, instr, stackptr, len,
output, input, jump, i, j, set, get;
input := InputTextUser();
output := OutputTextUser();
instr := 1;
pointer := 0;
leftcells := [ ];
rightcells := [ ];
stack := [ ];
stackptr := 0;
len := Length(prog);
jump := [ ];
get := function()
local p;
if pointer >= 0 then
p := pointer + 1;
if IsBound(rightcells[p]) then
return rightcells[p];
else
return 0;
fi;
else
p := -pointer;
if IsBound(leftcells[p]) then
return leftcells[p];
else
return 0;
fi;
fi;
end;
set := function(value)
local p;
if pointer >= 0 then
p := pointer + 1;
if value = 0 then
Unbind(rightcells[p]);
else
rightcells[p] := value;
fi;
else
p := -pointer;
if value = 0 then
Unbind(leftcells[p]);
else
leftcells[p] := value;
fi;
fi;
end;
# find jumps for faster execution
for i in [1 .. len] do
if prog[i] = '[' then
stackptr := stackptr + 1;
stack[stackptr] := i;
elif prog[i] = ']' then
j := stack[stackptr];
stackptr := stackptr - 1;
jump[i] := j;
jump[j] := i;
fi;
od;
while instr <= len do
c := prog[instr];
if c = '<' then
pointer := pointer - 1;
elif c = '>' then
pointer := pointer + 1;
elif c = '+' then
set(get() + 1);
elif c = '-' then
set(get() - 1);
elif c = '.' then
WriteLine(output, String(get()));
elif c = ',' then
set(Int(Chomp(ReadLine(input))));
elif c = '[' then
if get() = 0 then
instr := jump[instr];
fi;
elif c = ']' then
if get() <> 0 then
instr := jump[instr];
fi;
fi;
instr := instr + 1;
od;
CloseStream(input);
CloseStream(output);
# for debugging purposes, return last state
return [leftcells, rightcells, pointer];
end;
# An addition
Brainfuck("+++.<+++++.[->+<]>.");
# 3
# 5
# 8 |
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.
| #Icon_and_Unicon | Icon and Unicon | global target, chars, parent, C, M, current_fitness
procedure fitness(s)
fit := 0
#Increment the fitness for every position in the string s that matches the target
every i := 1 to *target & s[i] == target[i] do fit +:= 1
return fit
end
procedure mutate(s)
#If a random number between 0 and 1 is inside the bounds of mutation randomly alter a character in the string
if (?0 <= M) then ?s := ?chars
return s
end
procedure generation()
population := [ ]
next_parent := ""
next_fitness := -1
#Create the next population
every 1 to C do push(population, mutate(parent))
#Find the member of the population with highest fitness, or use the last one inspected
every x := !population & (xf := fitness(x)) > next_fitness do {
next_parent := x
next_fitness := xf
}
parent := next_parent
return next_fitness
end
procedure main()
target := "METHINKS IT IS LIKE A WEASEL" #Our target string
chars := &ucase ++ " " #Set of usable characters
parent := "" & every 1 to *target do parent ||:= ?chars #The universal common ancestor!
current_fitness := fitness(parent) #The best fitness we have so far
C := 50 #Population size in each generation
M := 0.5 #Mutation rate per individual in a generation
gen := 1
#Until current fitness reaches a score of perfect match with the target string keep generating new populations
until ((current_fitness := generation()) = *target) do {
write(gen || " " || current_fitness || " " || parent)
gen +:= 1
}
write("At generation " || gen || " we found a string with perfect fitness at " || current_fitness || " reading: " || parent)
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
| #Metafont | Metafont | vardef fibo(expr n) =
if n=0: 0
elseif n=1: 1
else:
fibo(n-1) + fibo(n-2)
fi
enddef;
for i=0 upto 10: show fibo(i); endfor
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
| #Scala | Scala | //Defining exceptions
class AccountBlockException extends Exception
class InsufficientFundsException(val amount: Double) extends Exception
class CheckingAccount(number: Int, var blocked: Boolean = false, var balance: Double = 0.0) {
def deposit(amount: Double) { // Throwing an exception 1
if (blocked) throw new AccountBlockException
balance += amount
}
def withdraw(amount: Double) { // Throwing an exception 2
if (blocked) throw new AccountBlockException
if (amount <= balance) balance -= amount
else throw new InsufficientFundsException(amount - balance)
}
}
object CheckingAccount extends App {
class ExampleException1 extends Exception
val c = new CheckingAccount(101)
println("Depositing $500...")
try {
c.deposit(500.00)
println("\nWithdrawing $100...")
c.withdraw(100.00)
println("\nWithdrawing $600...")
c.withdraw(600.00)
} catch { // Exception handler
case ac: InsufficientFundsException => println(s"Sorry, but you are short ${'$'} ${ac.amount}")
case ac: AccountBlockException => println("Account blocked.")
///////////////////////////// An example of multiple exception handler ////////////////////////
case e@(_: ExampleException1 |
_: InterruptedException) => println(s"Out of memory or something else.")
case e: Exception => e.printStackTrace()
case _: Throwable => // Exception cached without any action
} finally println("Have a nice day")
}
object CheckingBlockingAccount extends App {
val c = new CheckingAccount(102, true)
println("Depositing $500...")
try {
c.deposit(500.00)
println("\nWithdrawing $100...")
c.withdraw(100.00)
println("\nWithdrawing $600...")
c.withdraw(600.00)
} catch { // Exception handler
case ac: InsufficientFundsException => println(s"Sorry, but you are short ${'$'} ${ac.amount}")
case ac: AccountBlockException => println("Account blocked.")
case e: Exception => e.printStackTrace()
case _: Throwable =>
} finally println("Have a nice day")
}
object NotImplementedErrorTest extends App {
??? // Throws scala.NotImplementedError: an implementation is missing
} |
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
| #Perl | Perl | my @results = qx(ls); # run command and return STDOUT as a string
my @results = `ls`; # same, alternative syntax
system "ls"; # run command and return exit status; STDOUT of command goes program STDOUT
print `ls`; # same, but with back quotes
exec "ls"; # replace 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
| #Phix | Phix | without js
string cmd = iff(platform()=WINDOWS?"dir":"ls")
system(cmd)
integer res = system_exec("pause",4)
|
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
| #C.23 | C# | using System;
class Program
{
static int Factorial(int number)
{
if(number < 0)
throw new ArgumentOutOfRangeException(nameof(number), number, "Must be zero or a positive number.");
var accumulator = 1;
for (var factor = 1; factor <= number; factor++)
{
accumulator *= factor;
}
return accumulator;
}
static void Main()
{
Console.WriteLine(Factorial(10));
}
} |
http://rosettacode.org/wiki/Exponentiation_operator | Exponentiation operator | Most programming languages have a built-in implementation of exponentiation.
Task
Re-implement integer exponentiation for both intint and floatint as both a procedure, and an operator (if your language supports operator definition).
If the language supports operator (or procedure) overloading, then an overloaded form should be provided for both intint and floatint variants.
Related tasks
Exponentiation order
arbitrary-precision integers (included)
Exponentiation with infix operators in (or operating on) the base
| #Swift | Swift | func raise<T: Numeric>(_ base: T, to exponent: Int) -> T {
precondition(exponent >= 0, "Exponent has to be nonnegative")
return Array(repeating: base, count: exponent).reduce(1, *)
}
infix operator **: MultiplicationPrecedence
func **<T: Numeric>(lhs: T, rhs: Int) -> T {
return raise(lhs, to: rhs)
}
let someFloat: Float = 2
let someInt: Int = 10
assert(raise(someFloat, to: someInt) == 1024)
assert(someFloat ** someInt == 1024)
assert(raise(someInt, to: someInt) == 10000000000)
assert(someInt ** someInt == 10000000000) |
http://rosettacode.org/wiki/Exponentiation_operator | Exponentiation operator | Most programming languages have a built-in implementation of exponentiation.
Task
Re-implement integer exponentiation for both intint and floatint as both a procedure, and an operator (if your language supports operator definition).
If the language supports operator (or procedure) overloading, then an overloaded form should be provided for both intint and floatint variants.
Related tasks
Exponentiation order
arbitrary-precision integers (included)
Exponentiation with infix operators in (or operating on) the base
| #Tcl | Tcl | package require Tcl 8.5
proc tcl::mathfunc::mypow {a b} {
if { ! [string is int -strict $b]} {error "exponent must be an integer"}
set res 1
for {set i 1} {$i <= $b} {incr i} {set res [expr {$res * $a}]}
return $res
}
expr {mypow(3, 3)} ;# ==> 27
expr {mypow(3.5, 3)} ;# ==> 42.875
expr {mypow(3.5, 3.2)} ;# ==> exponent must be an integer |
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
| #TransFORTH | TransFORTH | : FIZZBUZZ
101 1 DO
I 15 MOD 0 = IF
PRINT " FIZZBUZZ "
ELSE I 3 MOD 0 = IF
PRINT " FIZZ "
ELSE I 5 MOD 0 = IF
PRINT " BUZZ "
ELSE I . THEN THEN THEN
CR LOOP ; |
http://rosettacode.org/wiki/Execute_Brain**** | Execute Brain**** | Execute Brain**** is an implementation of Brainf***.
Other implementations of Brainf***.
RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages.
Below are links to each of the versions of RCBF.
An implementation need only properly implement the following instructions:
Command
Description
>
Move the pointer to the right
<
Move the pointer to the left
+
Increment the memory cell under the pointer
-
Decrement the memory cell under the pointer
.
Output the character signified by the cell at the pointer
,
Input a character and store it in the cell at the pointer
[
Jump past the matching ] if the cell under the pointer is 0
]
Jump back to the matching [ if the cell under the pointer is nonzero
Any cell size is allowed, EOF (End-O-File) support is optional, as is whether you have bounded or unbounded memory.
| #Go | Go | package main
import "fmt"
func main() {
// example program is current Brain**** solution to
// Hello world/Text task. only requires 10 bytes of data store!
bf(10, `++++++++++[>+>+++>++++>+++++++>++++++++>+++++++++>++
++++++++>+++++++++++>++++++++++++<<<<<<<<<-]>>>>+.>>>
>+..<.<++++++++.>>>+.<<+.<<<<++++.<++.>>>+++++++.>>>.+++.
<+++++++.--------.<<<<<+.<+++.---.`)
}
func bf(dLen int, is string) {
ds := make([]byte, dLen) // data store
var dp int // data pointer
for ip := 0; ip < len(is); ip++ {
switch is[ip] {
case '>':
dp++
case '<':
dp--
case '+':
ds[dp]++
case '-':
ds[dp]--
case '.':
fmt.Printf("%c", ds[dp])
case ',':
fmt.Scanf("%c", &ds[dp])
case '[':
if ds[dp] == 0 {
for nc := 1; nc > 0; {
ip++
if is[ip] == '[' {
nc++
} else if is[ip] == ']' {
nc--
}
}
}
case ']':
if ds[dp] != 0 {
for nc := 1; nc > 0; {
ip--
if is[ip] == ']' {
nc++
} else if is[ip] == '[' {
nc--
}
}
}
}
}
} |
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.
| #J | J | CHARSET=: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ '
NPROG=: 100 NB. number of progeny (C)
MRATE=: 0.05 NB. mutation rate
create =: (?@$&$ { ])&CHARSET NB. creates random list from charset of same shape as y
fitness =: +/@:~:"1
copy =: # ,:
mutate =: &(>: $ ?@$ 0:)(`(,: create))} NB. adverb
select =: ] {~ (i. <./)@:fitness NB. select fittest member of population
nextgen =: select ] , [: MRATE mutate NPROG copy ]
while =: conjunction def '(] , (u {:))^:(v {:)^:_ ,:'
evolve=: nextgen while (0 < fitness) create |
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
| #Microsoft_Small_Basic | Microsoft Small Basic | ' Fibonacci sequence - 31/07/2018
n = 139
f1 = 0
f2 = 1
TextWindow.WriteLine("fibo(0)="+f1)
TextWindow.WriteLine("fibo(1)="+f2)
For i = 2 To n
f3 = f1 + f2
TextWindow.WriteLine("fibo("+i+")="+f3)
f1 = f2
f2 = f3
EndFor |
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
| #Scheme | Scheme | (define (me-errors xx exception)
(if (even? xx)
xx
(exception)))
;example that does nothing special on exception
(call/cc
(lambda (exception)
(me-errors 222 exception)
(display "I guess everything is alright")))
;example that laments oddness on exception
(call/cc
(lambda (all-ok) ;used to "jump" over exception handling
(call/cc
(lambda (exception-handle)
(me-errors 333 exception-handle)
(display "I guess everything is alright")
(all-ok)))
(display "oh my god it is ODD!"))) |
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
| #Seed7 | Seed7 | const proc: foo is func
begin
raise RANGE_ERROR;
end func; |
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
| #PHP | PHP | @exec($command,$output);
echo nl2br($output); |
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
| #PicoLisp | PicoLisp | (call "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
| #C.2B.2B | C++ | #include <boost/iterator/counting_iterator.hpp>
#include <algorithm>
int factorial(int n)
{
// last is one-past-end
return std::accumulate(boost::counting_iterator<int>(1), boost::counting_iterator<int>(n+1), 1, std::multiplies<int>());
} |
http://rosettacode.org/wiki/Exponentiation_operator | Exponentiation operator | Most programming languages have a built-in implementation of exponentiation.
Task
Re-implement integer exponentiation for both intint and floatint as both a procedure, and an operator (if your language supports operator definition).
If the language supports operator (or procedure) overloading, then an overloaded form should be provided for both intint and floatint variants.
Related tasks
Exponentiation order
arbitrary-precision integers (included)
Exponentiation with infix operators in (or operating on) the base
| #Ursa | Ursa | # these implementations ignore negative exponents
def intpow (int m, int n)
if (< n 1)
return 1
end if
decl int ret
set ret 1
for () (> n 0) (dec n)
set ret (* ret m)
end for
return ret
end intpow
def floatpow (double m, int n)
if (or (< n 1) (and (= m 0) (= n 0)))
return 1
end if
decl int ret
set ret 1
for () (> n 0) (dec n)
set ret (* ret m)
end for
return ret
end floatpow |
http://rosettacode.org/wiki/Exponentiation_operator | Exponentiation operator | Most programming languages have a built-in implementation of exponentiation.
Task
Re-implement integer exponentiation for both intint and floatint as both a procedure, and an operator (if your language supports operator definition).
If the language supports operator (or procedure) overloading, then an overloaded form should be provided for both intint and floatint variants.
Related tasks
Exponentiation order
arbitrary-precision integers (included)
Exponentiation with infix operators in (or operating on) the base
| #VBA | VBA | Public Function exp(ByVal base As Variant, ByVal exponent As Long) As Variant
Dim result As Variant
If TypeName(base) = "Integer" Or TypeName(base) = "Long" Then
'integer exponentiation
result = 1
If exponent < 0 Then
result = IIf(Abs(base) <> 1, CVErr(2019), IIf(exponent Mod 2 = -1, base, 1))
End If
Do While exponent > 0
If exponent Mod 2 = 1 Then result = result * base
base = base * base
exponent = exponent \ 2
Loop
Else
Debug.Assert IsNumeric(base)
'float exponentiation
If base = 0 Then
If exponent < 0 Then result = CVErr(11)
Else
If exponent < 0 Then
base = 1# / base
exponent = -exponent
End If
result = 1
Do While exponent > 0
If exponent Mod 2 = 1 Then result = result * base
base = base * base
exponent = exponent \ 2
Loop
End If
End If
exp = result
End Function
Public Sub main()
Debug.Print "Integer exponentiation"
Debug.Print "10^7=", exp(10, 7)
Debug.Print "10^4=", exp(10, 4)
Debug.Print "(-3)^3=", exp(-3, 3)
Debug.Print "(-1)^(-5)=", exp(-1, -5)
Debug.Print "10^(-1)=", exp(10, -1)
Debug.Print "0^2=", exp(0, 2)
Debug.Print "Float exponentiation"
Debug.Print "10.0^(-3)=", exp(10#, -3)
Debug.Print "10.0^(-4)=", exp(10#, -4)
Debug.Print "(-3.0)^(-5)=", exp(-3#, -5)
Debug.Print "(-3.0)^(-4)=", exp(-3#, -4)
Debug.Print "0.0^(-4)=", exp(0#, -4)
End Sub |
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
| #True_BASIC | True BASIC | for i : 1 .. 100
if i mod 15 = 0 then
put "Fizzbuzz"
elsif i mod 5 = 0 then
put "Buzz"
elsif i mod 3 = 0 then
put "Fizz"
else
put i
end if
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.
| #Groovy | Groovy | class BrainfuckProgram {
def program = '', memory = [:]
def instructionPointer = 0, dataPointer = 0
def execute() {
while (instructionPointer < program.size())
switch(program[instructionPointer++]) {
case '>': dataPointer++; break;
case '<': dataPointer--; break;
case '+': memory[dataPointer] = memoryValue + 1; break
case '-': memory[dataPointer] = memoryValue - 1; break
case ',': memory[dataPointer] = System.in.read(); break
case '.': print String.valueOf(Character.toChars(memoryValue)); break
case '[': handleLoopStart(); break
case ']': handleLoopEnd(); break
}
}
private getMemoryValue() { memory[dataPointer] ?: 0 }
private handleLoopStart() {
if (memoryValue) return
int depth = 1
while (instructionPointer < program.size())
switch(program[instructionPointer++]) {
case '[': depth++; break
case ']': if (!(--depth)) return
}
throw new IllegalStateException('Could not find matching end bracket')
}
private handleLoopEnd() {
int depth = 0
while (instructionPointer >= 0) {
switch(program[--instructionPointer]) {
case ']': depth++; break
case '[': if (!(--depth)) return; break
}
}
throw new IllegalStateException('Could not find matching start bracket')
}
} |
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.
| #Java | Java |
import java.util.Random;
public class EvoAlgo {
static final String target = "METHINKS IT IS LIKE A WEASEL";
static final char[] possibilities = "ABCDEFGHIJKLMNOPQRSTUVWXYZ ".toCharArray();
static int C = 100; //number of spawn per generation
static double minMutateRate = 0.09;
static int perfectFitness = target.length();
private static String parent;
static Random rand = new Random();
private static int fitness(String trial){
int retVal = 0;
for(int i = 0;i < trial.length(); i++){
if (trial.charAt(i) == target.charAt(i)) retVal++;
}
return retVal;
}
private static double newMutateRate(){
return (((double)perfectFitness - fitness(parent)) / perfectFitness * (1 - minMutateRate));
}
private static String mutate(String parent, double rate){
String retVal = "";
for(int i = 0;i < parent.length(); i++){
retVal += (rand.nextDouble() <= rate) ?
possibilities[rand.nextInt(possibilities.length)]:
parent.charAt(i);
}
return retVal;
}
public static void main(String[] args){
parent = mutate(target, 1);
int iter = 0;
while(!target.equals(parent)){
double rate = newMutateRate();
iter++;
if(iter % 100 == 0){
System.out.println(iter +": "+parent+ ", fitness: "+fitness(parent)+", rate: "+rate);
}
String bestSpawn = null;
int bestFit = 0;
for(int i = 0; i < C; i++){
String spawn = mutate(parent, rate);
int fitness = fitness(spawn);
if(fitness > bestFit){
bestSpawn = spawn;
bestFit = fitness;
}
}
parent = bestFit > fitness(parent) ? bestSpawn : parent;
}
System.out.println(parent+", "+iter);
}
} |
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
| #min | min | (
(2 <)
((0 1 (dup rollup +)) dip pred times nip)
unless
) :fib |
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
| #Sidef | Sidef | try {
die "I'm dead!"; # throws an exception of type 'error'
}
catch { |type, msg|
say "type: #{type}"; # type: error
say "msg: #{msg}"; # msg: I'm dead! at test.sf line 2.
};
say "I'm alive...";
die "Now I'm dead!"; # this line terminates the program
say "Or am I?"; # Yes, you are! |
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
| #Slate | Slate | se@(SceneElement traits) doWithRestart: block
[
block handlingCases: {Abort -> [| :_ | ^ Nil]}
]. |
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
| #Smalltalk | Smalltalk | "exec" "gst" "-f" "$0" "$0" "$*"
"exit"
Transcript show: 'Throwing yawp'; cr.
self error: 'Yawp!'. |
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
| #Pike | Pike | int main(){
// Process.run was added in Pike 7.8 as a wrapper to simplify the use of Process.create_process()
mapping response = Process.run("ls -l");
// response is now a map containing 3 fields
// stderr, stdout, and exitcode. We want stdout.
write(response["stdout"] + "\n");
// with older versions of pike it's a bit more complicated:
Stdio.File stdout = Stdio.File();
Process.create_process(({"ls", "-l"}), ([ "stdout" : stdout->pipe() ]) );
write(stdout->read() + "\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
| #Pop11 | Pop11 | sysobey('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
| #C3 | C3 | fn int factorial(int n)
{
int result = 1;
for (int i = 1; i <= n; ++i)
{
result *= i;
}
return result;
}
|
http://rosettacode.org/wiki/Exponentiation_operator | Exponentiation operator | Most programming languages have a built-in implementation of exponentiation.
Task
Re-implement integer exponentiation for both intint and floatint as both a procedure, and an operator (if your language supports operator definition).
If the language supports operator (or procedure) overloading, then an overloaded form should be provided for both intint and floatint variants.
Related tasks
Exponentiation order
arbitrary-precision integers (included)
Exponentiation with infix operators in (or operating on) the base
| #VBScript | VBScript |
Function pow(x,y)
pow = 1
If y < 0 Then
For i = 1 To Abs(y)
pow = pow * (1/x)
Next
Else
For i = 1 To y
pow = pow * x
Next
End If
End Function
WScript.StdOut.Write "2 ^ 0 = " & pow(2,0)
WScript.StdOut.WriteLine
WScript.StdOut.Write "7 ^ 6 = " & pow(7,6)
WScript.StdOut.WriteLine
WScript.StdOut.Write "3.14159265359 ^ 9 = " & pow(3.14159265359,9)
WScript.StdOut.WriteLine
WScript.StdOut.Write "4 ^ -6 = " & pow(4,-6)
WScript.StdOut.WriteLine
WScript.StdOut.Write "-3 ^ 5 = " & pow(-3,5)
WScript.StdOut.WriteLine
|
http://rosettacode.org/wiki/Exponentiation_operator | Exponentiation operator | Most programming languages have a built-in implementation of exponentiation.
Task
Re-implement integer exponentiation for both intint and floatint as both a procedure, and an operator (if your language supports operator definition).
If the language supports operator (or procedure) overloading, then an overloaded form should be provided for both intint and floatint variants.
Related tasks
Exponentiation order
arbitrary-precision integers (included)
Exponentiation with infix operators in (or operating on) the base
| #XPL0 | XPL0 | include c:\cxpl\codes; \intrinsic 'code' declarations
func real Power(X, Y); \X raised to the Y power; (X > 0.0)
real X; int Y;
return Exp(float(Y) * Ln(X));
func IPower(X, Y); \X raised to the Y power
int X, Y;
int P;
[P:= 1;
while Y do
[if Y&1 then P:= P*X;
X:= X*X;
Y:= Y>>1;
];
return P;
];
int X, Y;
[Format(9, 0);
for X:= 1 to 10 do
[for Y:= 0 to 7 do
RlOut(0, Power(float(X), Y));
CrLf(0);
];
CrLf(0);
for X:= 1 to 10 do
[for Y:= 0 to 7 do
[ChOut(0, 9); IntOut(0, IPower(X, Y))];
CrLf(0);
];
] |
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
| #Turing | Turing | for i : 1 .. 100
if i mod 15 = 0 then
put "Fizzbuzz"
elsif i mod 5 = 0 then
put "Buzz"
elsif i mod 3 = 0 then
put "Fizz"
else
put i
end if
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.
| #GW-BASIC | GW-BASIC | 10 REM BRAINFK INTERPRETER FOR GW-BASIC
20 INPUT "File to open? ",INFILE$
30 DIM TAPE(10000): REM memory is 10000 long
40 DIM PRG$(5000): REM programs can be 5000 symbols long
50 PRG$ = ""
60 OPEN(INFILE$) FOR INPUT AS #1
70 S = 0 : REM instruction pointer
80 WHILE NOT EOF(1)
90 LINE INPUT #1, LIN$
100 FOR P = 1 TO LEN(LIN$)
110 C$=MID$(LIN$,P,1)
120 IF C$="+" OR C$="-" OR C$="." OR C$="," OR C$ = "<" OR C$=">" OR C$="[" OR C$="]" THEN S=S+1:PRG$(S)=C$
130 NEXT P
140 WEND
150 PRLEN = S
160 REM ok, the program has been read in. now set up the variables
170 P = 0 : REM tape pointer
180 S = 1 : REM instruction pointer
190 K = 0 : REM bracket counter
200 WHILE S<=PRLEN: REM as long as there are still instructions to come
210 IF INKEY$="Q" THEN END
220 IF PRG$(S) = "+" THEN GOSUB 320
230 IF PRG$(S) = "-" THEN GOSUB 350
240 IF PRG$(S) = ">" THEN GOSUB 380
250 IF PRG$(S) = "<" THEN GOSUB 420
260 IF PRG$(S) = "." THEN GOSUB 460
270 IF PRG$(S) = "," THEN GOSUB 490
280 IF PRG$(S) = "[" THEN GOSUB 650 ELSE IF PRG$(S) = "]" THEN GOSUB 550
290 S = S + 1
300 WEND
310 END
320 REM the + instruction
330 TAPE(P) = TAPE(P) + 1
340 RETURN
350 REM the - instruction
360 TAPE(P) = TAPE(P)-1
370 RETURN
380 REM the > instruction
390 P = P + 1
400 IF P > 10000 THEN P = P - 10000 : REM circular tape, because why not?
410 RETURN
420 REM the < instruction
430 P = P - 1
440 IF P < 0 THEN P = P + 10000
450 RETURN
460 REM the . instruction
470 PRINT CHR$(TAPE(P));
480 RETURN
490 REM the , instruction
500 BEEP : REM use the beep as a signal that input is expected
510 G$ = INKEY$
520 IF G$ = "" THEN GOTO 510
530 TAPE(P) = ASC(G$)
540 RETURN
550 REM the ] instruction
560 IF TAPE(P)=0 THEN RETURN : REM do nothing
570 K = 1 : REM otherwise it's some bracket counting
580 WHILE K > 0
590 S = S - 1
600 IF S = 0 THEN PRINT "Backtrack beyond start of program!" : END
610 IF PRG$(S) = "]" THEN K = K + 1
620 IF PRG$(S) = "[" THEN K = K - 1
630 WEND
640 RETURN
650 REM the [ instruction
660 IF TAPE(P)<> 0 THEN RETURN
670 K = 1
680 WHILE K>0
690 S = S + 1
700 IF S>PRLEN THEN PRINT "Advance beyond end of program!" : END
710 IF PRG$(S) = "]" THEN K = K - 1
720 IF PRG$(S) = "[" THEN K = K + 1
730 WEND
740 RETURN |
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.
| #JavaScript | JavaScript | // ------------------------------------- Cross-browser Compatibility -------------------------------------
/* Compatibility code to reduce an array
* Source: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/Reduce
*/
if (!Array.prototype.reduce) {
Array.prototype.reduce = function (fun /*, initialValue */ ) {
"use strict";
if (this === void 0 || this === null) throw new TypeError();
var t = Object(this);
var len = t.length >>> 0;
if (typeof fun !== "function") throw new TypeError();
// no value to return if no initial value and an empty array
if (len == 0 && arguments.length == 1) throw new TypeError();
var k = 0;
var accumulator;
if (arguments.length >= 2) {
accumulator = arguments[1];
} else {
do {
if (k in t) {
accumulator = t[k++];
break;
}
// if array contains no values, no initial value to return
if (++k >= len) throw new TypeError();
}
while (true);
}
while (k < len) {
if (k in t) accumulator = fun.call(undefined, accumulator, t[k], k, t);
k++;
}
return accumulator;
};
}
/* Compatibility code to map an array
* Source: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/Map
*/
if (!Array.prototype.map) {
Array.prototype.map = function (fun /*, thisp */ ) {
"use strict";
if (this === void 0 || this === null) throw new TypeError();
var t = Object(this);
var len = t.length >>> 0;
if (typeof fun !== "function") throw new TypeError();
var res = new Array(len);
var thisp = arguments[1];
for (var i = 0; i < len; i++) {
if (i in t) res[i] = fun.call(thisp, t[i], i, t);
}
return res;
};
}
/* ------------------------------------- Generator -------------------------------------
* Generates a fixed length gene sequence via a gene strategy object.
* The gene strategy object must have two functions:
* - "create": returns create a new gene
* - "mutate(existingGene)": returns mutation of an existing gene
*/
function Generator(length, mutationRate, geneStrategy) {
this.size = length;
this.mutationRate = mutationRate;
this.geneStrategy = geneStrategy;
}
Generator.prototype.spawn = function () {
var genes = [],
x;
for (x = 0; x < this.size; x += 1) {
genes.push(this.geneStrategy.create());
}
return genes;
};
Generator.prototype.mutate = function (parent) {
return parent.map(function (char) {
if (Math.random() > this.mutationRate) {
return char;
}
return this.geneStrategy.mutate(char);
}, this);
};
/* ------------------------------------- Population -------------------------------------
* Helper class that holds and spawns a new population.
*/
function Population(size, generator) {
this.size = size;
this.generator = generator;
this.population = [];
// Build initial popuation;
for (var x = 0; x < this.size; x += 1) {
this.population.push(this.generator.spawn());
}
}
Population.prototype.spawn = function (parent) {
this.population = [];
for (var x = 0; x < this.size; x += 1) {
this.population.push(this.generator.mutate(parent));
}
};
/* ------------------------------------- Evolver -------------------------------------
* Attempts to converge a population based a fitness strategy object.
* The fitness strategy object must have three function
* - "score(individual)": returns a score for an individual.
* - "compare(scoreA, scoreB)": return true if scoreA is better (ie more fit) then scoreB
* - "done( score )": return true if score is acceptable (ie we have successfully converged).
*/
function Evolver(size, generator, fitness) {
this.done = false;
this.fitness = fitness;
this.population = new Population(size, generator);
}
Evolver.prototype.getFittest = function () {
return this.population.population.reduce(function (best, individual) {
var currentScore = this.fitness.score(individual);
if (best === null || this.fitness.compare(currentScore, best.score)) {
return {
score: currentScore,
individual: individual
};
} else {
return best;
}
}, null);
};
Evolver.prototype.doGeneration = function () {
this.fittest = this.getFittest();
this.done = this.fitness.done(this.fittest.score);
if (!this.done) {
this.population.spawn(this.fittest.individual);
}
};
Evolver.prototype.run = function (onCheckpoint, checkPointFrequency) {
checkPointFrequency = checkPointFrequency || 10; // Default to Checkpoints every 10 generations
var generation = 0;
while (!this.done) {
this.doGeneration();
if (generation % checkPointFrequency === 0) {
onCheckpoint(generation, this.fittest);
}
generation += 1;
}
onCheckpoint(generation, this.fittest);
return this.fittest;
};
// ------------------------------------- Exports -------------------------------------
window.Generator = Generator;
window.Evolver = Evolver;
// helper utitlity to combine elements of two arrays.
Array.prototype.zip = function (b, func) {
var result = [],
max = Math.max(this.length, b.length),
x;
for (x = 0; x < max; x += 1) {
result.push(func(this[x], b[x]));
}
return result;
};
var target = "METHINKS IT IS LIKE A WEASEL", geneStrategy, fitness, target, generator, evolver, result;
geneStrategy = {
// The allowed character set (as an array)
characterSet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ ".split(""),
/*
Pick a random character from the characterSet
*/
create: function getRandomGene() {
var randomNumber = Math.floor(Math.random() * this.characterSet.length);
return this.characterSet[randomNumber];
}
};
geneStrategy.mutate = geneStrategy.create; // Our mutation stragtegy is to simply get a random gene
fitness = {
// The target (as an array of characters)
target: target.split(""),
equal: function (geneA, geneB) {
return (geneA === geneB ? 0 : 1);
},
sum: function (runningTotal, value) {
return runningTotal + value;
},
/*
We give one point to for each corect letter
*/
score: function (genes) {
var diff = genes.zip(this.target, this.equal); // create an array of ones and zeros
return diff.reduce(this.sum, 0); // Sum the array values together.
},
compare: function (scoreA, scoreB) {
return scoreA <= scoreB; // Lower scores are better
},
done: function (score) {
return score === 0; // We have matched the target string.
}
};
generator = new Generator(target.length, 0.05, geneStrategy);
evolver = new Evolver(100, generator, fitness);
function showProgress(generation, fittest) {
document.write("Generation: " + generation + ", Best: " + fittest.individual.join("") + ", fitness:" + fittest.score + "<br>");
}
result = evolver.run(showProgress); |
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
| #MiniScript | MiniScript | fibonacci = function(n)
if n < 2 then return n
n1 = 0
n2 = 1
for i in range(n-1, 1)
ans = n1 + n2
n1 = n2
n2 = ans
end for
return ans
end function
print fibonacci(6) |
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
| #SQL_PL | SQL PL |
--#SET TERMINATOR @
BEGIN
DECLARE numerator INTEGER DEFAULT 12;
DECLARE denominator INTEGER DEFAULT 0;
DECLARE RESULT INTEGER;
DECLARE overflow CONDITION FOR SQLSTATE '22003' ;
DECLARE CONTINUE HANDLER FOR overflow
RESIGNAL SQLSTATE '22375'
SET MESSAGE_TEXT = 'Zero division';
IF denominator = 0 THEN
SIGNAL overflow;
ELSE
SET RESULT = numerator / denominator;
END IF;
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
| #PowerShell | PowerShell | dir
ls
Get-ChildItem |
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
| #Prolog | Prolog | shell('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
| #Cat | Cat | define rec_fac
{ dup 1 <= [pop 1] [dec rec_fac *] if } |
http://rosettacode.org/wiki/Exponentiation_operator | Exponentiation operator | Most programming languages have a built-in implementation of exponentiation.
Task
Re-implement integer exponentiation for both intint and floatint as both a procedure, and an operator (if your language supports operator definition).
If the language supports operator (or procedure) overloading, then an overloaded form should be provided for both intint and floatint variants.
Related tasks
Exponentiation order
arbitrary-precision integers (included)
Exponentiation with infix operators in (or operating on) the base
| #Wren | Wren | class Num2 {
static ipow(i, exp) {
if (!i.isInteger) Fiber.abort("ipow method must have an integer receiver")
if (!exp.isInteger) Fiber.abort("ipow method must have an integer exponent")
if (i == 1 || exp == 0) return 1
if (i == -1) return (exp%2 == 0) ? 1 : -1
if (exp < 0) Fiber.abort("ipow method cannot have a negative exponent")
var ans = 1
var base = i
var e = exp
while (e > 1) {
if (e%2 == 1) ans = ans * base
e = (e/2).floor
base = base * base
}
return ans * base
}
static fpow(f, exp) {
if (!exp.isInteger) Fiber.abort("fpow method must have an integer exponent")
var ans = 1.0
var e = exp
var base = (e < 0) ? 1/f : f
if (e < 0) e = -e
while (e > 0) {
if (e%2 == 1) ans = ans * base
e = (e/2).floor
base = base * base
}
return ans
}
construct new(n) { _n = n }
^(exp) {
if (_n.isInteger && (exp >= 0 || _n.abs == 1)) return Num2.ipow(_n, exp)
return Num2.fpow(_n, exp)
}
}
System.print("Using static methods:")
System.print(" 2 ^ 3 = %(Num2.ipow(2, 3))")
System.print(" 1 ^ -10 = %(Num2.ipow(1, -10))")
System.print(" -1 ^ -3 = %(Num2.ipow(-1, -3))")
System.print()
System.print(" 2.0 ^ -3 = %(Num2.fpow(2.0, -3))")
System.print(" 1.5 ^ 0 = %(Num2.fpow(1.5, 0))")
System.print(" 4.5 ^ 2 = %(Num2.fpow(4.5, 2))")
System.print("\nUsing the ^ operator:")
System.print(" 2 ^ 3 = %(Num2.new(2) ^ 3)")
System.print(" 1 ^ -10 = %(Num2.new(1) ^ -10)")
System.print(" -1 ^ -3 = %(Num2.new(-1) ^ -3)")
System.print()
System.print(" 2.0 ^ -3 = %(Num2.new(2.0) ^ -3)")
System.print(" 1.5 ^ 0 = %(Num2.new(1.5) ^ 0)")
System.print(" 4.5 ^ 2 = %(Num2.new(4.5) ^ 2)") |
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
| #TUSCRIPT | TUSCRIPT | $$ MODE TUSCRIPT
LOOP n=1,100
mod=MOD (n,15)
SELECT mod
CASE 0
PRINT n," FizzBuzz"
CASE 3,6,9,12
PRINT n," Fizz"
CASE 5,10
PRINT n," Buzz"
DEFAULT
PRINT n
ENDSELECT
ENDLOOP |
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.
| #Haskell | Haskell | 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.
| #Julia | Julia | fitness(a::AbstractString, b::AbstractString) = count(l == t for (l, t) in zip(a, b))
function mutate(str::AbstractString, rate::Float64)
L = collect(Char, " ABCDEFGHIJKLMNOPQRSTUVWXYZ")
return map(str) do c
if rand() < rate rand(L) else c end
end
end
function evolve(parent::String, target::String, mutrate::Float64, nchild::Int)
println("Initial parent is $parent, its fitness is $(fitness(parent, target))")
gens = 0
while parent != target
children = collect(mutate(parent, mutrate) for i in 1:nchild)
bestfit, best = findmax(fitness.(children, target))
parent = children[best]
gens += 1
if gens % 10 == 0
println("After $gens generations, the new parent is $parent and its fitness is $(fitness(parent, target))")
end
end
println("After $gens generations, the parent evolved into the target $target")
end
evolve("IU RFSGJABGOLYWF XSMFXNIABKT", "METHINKS IT IS LIKE A WEASEL", 0.08998, 100) |
http://rosettacode.org/wiki/Fibonacci_sequence | Fibonacci sequence | The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion).
The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition:
Fn = Fn+2 - Fn+1, if n<0
support for negative n in the solution is optional.
Related tasks
Fibonacci n-step number sequences
Leonardo numbers
References
Wikipedia, Fibonacci number
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #MiniZinc | MiniZinc | function var int: fibonacci(int: n) =
let {
array[0..n] of var int: fibonacci;
constraint forall(a in 0..n)(
fibonacci[a] = if (a == 0 \/ a == 1) then
a
else
fibonacci[a-1]+fibonacci[a-2]
endif
)
} in fibonacci[n];
var int: fib = fibonacci(6);
solve satisfy;
output [show(fib),"\n"]; |
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
| #Standard_ML | Standard ML | exception MyException;
exception MyDataException of int; (* can be any first-class type, not just int *) |
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
| #Stata | Stata | capture confirm file titanium.dta
if _rc {
if _rc==601 {
display "the file does not exist"
}
else {
* all other cases
display "there was an error with return code " _rc
}
} |
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
| #PureBasic | PureBasic | ImportC "msvcrt.lib"
system(str.p-ascii)
EndImport
If OpenConsole()
system("dir & pause")
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit")
Input()
CloseConsole()
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
| #Python | Python | import os
exit_code = os.system('ls') # Just execute the command, return a success/fail code
output = os.popen('ls').read() # If you want to get the output data. Deprecated. |
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
| #Ceylon | Ceylon | shared void run() {
Integer? recursiveFactorial(Integer n) =>
switch(n <=> 0)
case(smaller) null
case(equal) 1
case(larger) if(exists f = recursiveFactorial(n - 1)) then n * f else null;
Integer? iterativeFactorial(Integer n) =>
switch(n <=> 0)
case(smaller) null
case(equal) 1
case(larger) (1:n).reduce(times);
for(Integer i in 0..10) {
print("the iterative factorial of ``i`` is ``iterativeFactorial(i) else "negative"``
and the recursive factorial of ``i`` is ``recursiveFactorial(i) else "negative"``\n");
}
}
|
http://rosettacode.org/wiki/Exponentiation_operator | Exponentiation operator | Most programming languages have a built-in implementation of exponentiation.
Task
Re-implement integer exponentiation for both intint and floatint as both a procedure, and an operator (if your language supports operator definition).
If the language supports operator (or procedure) overloading, then an overloaded form should be provided for both intint and floatint variants.
Related tasks
Exponentiation order
arbitrary-precision integers (included)
Exponentiation with infix operators in (or operating on) the base
| #zkl | zkl | fcn pow(n,exp){
reg v;
if(n.isType(1)){ // Int
if (exp<0) return(if(n*n!=1) 0 else (if(exp.isOdd) n else 1));
v=1;
}else{
if(exp<0){ n=1.0/n; exp=-exp; }
v=1.0;
}
while(exp>0){
if(exp.isOdd) v*=n;
n*=n;
exp/=2;
}
v
} |
http://rosettacode.org/wiki/Exponentiation_operator | Exponentiation operator | Most programming languages have a built-in implementation of exponentiation.
Task
Re-implement integer exponentiation for both intint and floatint as both a procedure, and an operator (if your language supports operator definition).
If the language supports operator (or procedure) overloading, then an overloaded form should be provided for both intint and floatint variants.
Related tasks
Exponentiation order
arbitrary-precision integers (included)
Exponentiation with infix operators in (or operating on) the base
| #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 PRINT e(3,2): REM 3 ^ 2
20 PRINT e(1.5,2.7): REM 1.5 ^ 2.7
30 STOP
9950 DEF FN e(a,b)=a^b |
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
| #TXR | TXR | $ txr -p "(mapcar (op if @1 @1 @2) (repeat '(nil nil fizz nil buzz fizz nil nil fizz buzz nil fizz nil nil fizzbuzz)) (range 1 100))" |
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.
| #Icon_and_Unicon | Icon and Unicon | 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(">++++++++[-<+++++++++>]<.>>+>-[+]++>++>+++[>[->+++<<+++>]<<]>-----.>->+++..+++.>-.<<+[>[+>+]>>]<--------------.>>.+++.------.--------.>+.>+.");
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.