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/Extend_your_language | Extend your language | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. by using macros), other languages go much further. Most notably in the Forth and Lisp families, programming per se is done by extending the language without any formal distinction between built-in and user-defined elements.
If your language supports it, show how to introduce a new flow control mechanism. A practical and useful example is a four-way branch:
Occasionally, code must be written that depends on two conditions, resulting in up to four branches (depending on whether both, only the first, only the second, or none of the conditions are "true"). In a C-like language this could look like the following:
if (condition1isTrue) {
if (condition2isTrue)
bothConditionsAreTrue();
else
firstConditionIsTrue();
}
else if (condition2isTrue)
secondConditionIsTrue();
else
noConditionIsTrue();
Besides being rather cluttered, the statement(s) for 'condition2isTrue' must be written down twice. If 'condition2isTrue' were a lengthy and involved expression, it would be quite unreadable, and the code generated by the compiler might be unnecessarily large.
This can be improved by introducing a new keyword if2. It is similar to if, but takes two conditional statements instead of one, and up to three 'else' statements. One proposal (in pseudo-C syntax) might be:
if2 (condition1isTrue) (condition2isTrue)
bothConditionsAreTrue();
else1
firstConditionIsTrue();
else2
secondConditionIsTrue();
else
noConditionIsTrue();
Pick the syntax which suits your language. The keywords 'else1' and 'else2' are just examples. The new conditional expression should look, nest and behave analogously to the language's built-in 'if' statement.
| #UNIX_Shell | UNIX Shell | if2() {
if eval "$1"; then
if eval "$2"; then eval "$3"; else eval "$4"; fi
else
if eval "$2"; then eval "$5"; else eval "$6"; fi
fi
} |
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
| #Sidef | Sidef | { |i|
if (i %% 3) {
print "Fizz"
i %% 5 && print "Buzz"
print "\n"
}
elsif (i %% 5) { say "Buzz" }
else { say i }
} * 100 |
http://rosettacode.org/wiki/Extensible_prime_generator | Extensible prime generator | Task
Write a generator of prime numbers, in order, that will automatically adjust to accommodate the generation of any reasonably high prime.
The routine should demonstrably rely on either:
Being based on an open-ended counter set to count without upper limit other than system or programming language limits. In this case, explain where this counter is in the code.
Being based on a limit that is extended automatically. In this case, choose a small limit that ensures the limit will be passed when generating some of the values to be asked for below.
If other methods of creating an extensible prime generator are used, the algorithm's means of extensibility/lack of limits should be stated.
The routine should be used to:
Show the first twenty primes.
Show the primes between 100 and 150.
Show the number of primes between 7,700 and 8,000.
Show the 10,000th prime.
Show output on this page.
Note: You may reference code already on this site if it is written to be imported/included, then only the code necessary for import and the performance of this task need be shown. (It is also important to leave a forward link on the referenced tasks entry so that later editors know that the code is used for multiple tasks).
Note 2: If a languages in-built prime generator is extensible or is guaranteed to generate primes up to a system limit, (231 or memory overflow for example), then this may be used as long as an explanation of the limits of the prime generator is also given. (Which may include a link to/excerpt from, language documentation).
Note 3:The task is written so it may be useful in solving the task Emirp primes as well as others (depending on its efficiency).
Reference
Prime Numbers. Website with large count of primes.
| #Swift | Swift | import Foundation
func soeDictOdds() -> UnfoldSequence<Int, Int> {
var bp = 5; var q = 25
var bps: UnfoldSequence<Int, Int>.Iterator? = nil
var dict = [9: 6] // Dictionary<Int, Int>(9 => 6)
return sequence(state: 2, next: { n in
if n < 9 { if n < 3 { n = 3; return 2 }; defer {n += 2}; return n }
while n >= q || dict[n] != nil {
if n >= q {
let inc = bp + bp
dict[n + inc] = inc
if bps == nil {
bps = soeDictOdds().makeIterator()
bp = (bps?.next())!; bp = (bps?.next())!; bp = (bps?.next())! // skip 2/3/5...
}
bp = (bps?.next())!; q = bp * bp // guaranteed never nil
} else {
let inc = dict[n] ?? 0
dict[n] = nil
var next = n + inc
while dict[next] != nil { next += inc }
dict[next] = inc
}
n += 2
}
defer { n += 2 }; return n
})
}
print("The first 20 primes are: ", terminator: "")
soeDictOdds().lazy.prefix(20).forEach { print($0, "", terminator: "") }
print()
print("The primes between 100 and 150 are: ", terminator: "")
soeDictOdds().lazy.drop(while: { $0 < Prime(100) }).lazy.prefix(while: { $0 <= 150 })
.forEach { print($0, "", terminator: "") }
print()
print("The number of primes from 7700 to 8000 is :", terminator: "")
print(soeDictOdds().lazy.drop(while: { $0 < 7700 }).lazy.prefix(while: { $0 <= 8000 })
.lazy.reduce(0, { a, _ in a + 1 }))
print("The 10,000th prime is: ", terminator: "")
print((soeDictOdds().lazy.dropFirst(9999).first { $0 == $0 })!)
print("The sum of primes to 2 million is: ", terminator: "")
let start = NSDate()
let answr = soeDictOdds().lazy.prefix(while: { $0 <= 2000000 })
.reduce(0, { a, p in a + Int64(p) })
let elpsd = -start.timeIntervalSinceNow
print(answr)
print(String(format: "This test took %.3f milliseconds.", elpsd * 1000)) |
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.
| #Clojure | Clojure | (ns brainfuck)
(def ^:dynamic *input*)
(def ^:dynamic *output*)
(defrecord Data [ptr cells])
(defn inc-ptr [next-cmd]
(fn [data]
(next-cmd (update-in data [:ptr] inc))))
(defn dec-ptr [next-cmd]
(fn [data]
(next-cmd (update-in data [:ptr] dec))))
(defn inc-cell [next-cmd]
(fn [data]
(next-cmd (update-in data [:cells (:ptr data)] (fnil inc 0)))))
(defn dec-cell [next-cmd]
(fn [data]
(next-cmd (update-in data [:cells (:ptr data)] (fnil dec 0)))))
(defn output-cell [next-cmd]
(fn [data]
(set! *output* (conj *output* (get (:cells data) (:ptr data) 0)))
(next-cmd data)))
(defn input-cell [next-cmd]
(fn [data]
(let [[input & rest-input] *input*]
(set! *input* rest-input)
(next-cmd (update-in data [:cells (:ptr data)] input)))))
(defn if-loop [next-cmd loop-cmd]
(fn [data]
(next-cmd (loop [d data]
(if (zero? (get (:cells d) (:ptr d) 0))
d
(recur (loop-cmd d)))))))
(defn terminate [data] data)
(defn split-cmds [cmds]
(letfn [(split [[cmd & rest-cmds] loop-cmds]
(when (nil? cmd) (throw (Exception. "invalid commands: missing ]")))
(case cmd
\[ (let [[c l] (split-cmds rest-cmds)]
(recur c (str loop-cmds "[" l "]")))
\] [(apply str rest-cmds) loop-cmds]
(recur rest-cmds (str loop-cmds cmd))))]
(split cmds "")))
(defn compile-cmds [[cmd & rest-cmds]]
(if (nil? cmd)
terminate
(case cmd
\> (inc-ptr (compile-cmds rest-cmds))
\< (dec-ptr (compile-cmds rest-cmds))
\+ (inc-cell (compile-cmds rest-cmds))
\- (dec-cell (compile-cmds rest-cmds))
\. (output-cell (compile-cmds rest-cmds))
\, (input-cell (compile-cmds rest-cmds))
\[ (let [[cmds loop-cmds] (split-cmds rest-cmds)]
(if-loop (compile-cmds cmds) (compile-cmds loop-cmds)))
\] (throw (Exception. "invalid commands: missing ["))
(compile-cmds rest-cmds))))
(defn compile-and-run [cmds input]
(binding [*input* input *output* []]
(let [compiled-cmds (compile-cmds cmds)]
(println (compiled-cmds (Data. 0 {}))))
(println *output*)
(println (apply str (map char *output*)))))
|
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.
| #D | D | import std.stdio, std.random, std.algorithm, std.range, std.ascii;
enum target = "METHINKS IT IS LIKE A WEASEL"d;
enum C = 100; // Number of children in each generation.
enum P = 0.05; // Mutation probability.
enum fitness = (dchar[] s) => target.zip(s).count!q{ a[0] != a[1] };
dchar rnd() { return (uppercase ~ " ")[uniform(0, $)]; }
enum mut = (dchar[] s) => s.map!(a => uniform01 < P ? rnd : a).array;
void main() {
auto parent = generate!rnd.take(target.length).array;
for (auto gen = 1; parent != target; gen++) {
// parent = parent.repeat(C).map!mut.array.max!fitness;
parent = parent.repeat(C).map!mut.array
.minPos!((a, b) => a.fitness < b.fitness)[0];
writefln("Gen %2d, dist=%2d: %s", gen, parent.fitness, 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
| #LiveCode | LiveCode | -- Iterative, translation of the basic version.
function fibi n
put 0 into aa
put 1 into b
repeat with i = 1 to n
put aa + b into temp
put b into aa
put temp into b
end repeat
return aa
end fibi
-- Recursive
function fibr n
if n <= 1 then
return n
else
return fibr(n-1) + fibr(n-2)
end if
end fibr |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #Python | Python | $ "bottles.qky" loadfile ( if required, the source code for this can be found at
http://rosettacode.org/wiki/99_bottles_of_beer#Quackery )
[ stack ] is accumulator ( --> s )
[ stack ] is sourcecode ( --> s )
[ say "Hello, world!" cr ] is H.HQ9+ ( --> )
[ sourcecode share
echo$ cr ] is Q.HQ9+ ( --> )
[ 99 song echo$ ] is 9.HQ9+ ( --> )
[ 1 accumulator tally ] is +.HQ9+ ( --> )
[ dup sourcecode put
0 accumulator put
witheach
[ $ ".HQ9+" join
quackery ]
sourcecode release
cr say "Accumulator = "
accumulator take echo ] is HQ9+ ( $ --> )
$ "HH+QQQQ+" HQ9+ |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #Quackery | Quackery | $ "bottles.qky" loadfile ( if required, the source code for this can be found at
http://rosettacode.org/wiki/99_bottles_of_beer#Quackery )
[ stack ] is accumulator ( --> s )
[ stack ] is sourcecode ( --> s )
[ say "Hello, world!" cr ] is H.HQ9+ ( --> )
[ sourcecode share
echo$ cr ] is Q.HQ9+ ( --> )
[ 99 song echo$ ] is 9.HQ9+ ( --> )
[ 1 accumulator tally ] is +.HQ9+ ( --> )
[ dup sourcecode put
0 accumulator put
witheach
[ $ ".HQ9+" join
quackery ]
sourcecode release
cr say "Accumulator = "
accumulator take echo ] is HQ9+ ( $ --> )
$ "HH+QQQQ+" HQ9+ |
http://rosettacode.org/wiki/Execute_a_Markov_algorithm | Execute a Markov algorithm | Execute a Markov algorithm
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create an interpreter for a Markov Algorithm.
Rules have the syntax:
<ruleset> ::= ((<comment> | <rule>) <newline>+)*
<comment> ::= # {<any character>}
<rule> ::= <pattern> <whitespace> -> <whitespace> [.] <replacement>
<whitespace> ::= (<tab> | <space>) [<whitespace>]
There is one rule per line.
If there is a . (period) present before the <replacement>, then this is a terminating rule in which case the interpreter must halt execution.
A ruleset consists of a sequence of rules, with optional comments.
Rulesets
Use the following tests on entries:
Ruleset 1
# This rules file is extracted from Wikipedia:
# http://en.wikipedia.org/wiki/Markov_Algorithm
A -> apple
B -> bag
S -> shop
T -> the
the shop -> my brother
a never used -> .terminating rule
Sample text of:
I bought a B of As from T S.
Should generate the output:
I bought a bag of apples from my brother.
Ruleset 2
A test of the terminating rule
# Slightly modified from the rules on Wikipedia
A -> apple
B -> bag
S -> .shop
T -> the
the shop -> my brother
a never used -> .terminating rule
Sample text of:
I bought a B of As from T S.
Should generate:
I bought a bag of apples from T shop.
Ruleset 3
This tests for correct substitution order and may trap simple regexp based replacement routines if special regexp characters are not escaped.
# BNF Syntax testing rules
A -> apple
WWWW -> with
Bgage -> ->.*
B -> bag
->.* -> money
W -> WW
S -> .shop
T -> the
the shop -> my brother
a never used -> .terminating rule
Sample text of:
I bought a B of As W my Bgage from T S.
Should generate:
I bought a bag of apples with my money from T shop.
Ruleset 4
This tests for correct order of scanning of rules, and may trap replacement routines that scan in the wrong order. It implements a general unary multiplication engine. (Note that the input expression must be placed within underscores in this implementation.)
### Unary Multiplication Engine, for testing Markov Algorithm implementations
### By Donal Fellows.
# Unary addition engine
_+1 -> _1+
1+1 -> 11+
# Pass for converting from the splitting of multiplication into ordinary
# addition
1! -> !1
,! -> !+
_! -> _
# Unary multiplication by duplicating left side, right side times
1*1 -> x,@y
1x -> xX
X, -> 1,1
X1 -> 1X
_x -> _X
,x -> ,X
y1 -> 1y
y_ -> _
# Next phase of applying
1@1 -> x,@y
1@_ -> @_
,@_ -> !_
++ -> +
# Termination cleanup for addition
_1 -> 1
1+_ -> 1
_+_ ->
Sample text of:
_1111*11111_
should generate the output:
11111111111111111111
Ruleset 5
A simple Turing machine,
implementing a three-state busy beaver.
The tape consists of 0s and 1s, the states are A, B, C and H (for Halt), and the head position is indicated by writing the state letter before the character where the head is.
All parts of the initial tape the machine operates on have to be given in the input.
Besides demonstrating that the Markov algorithm is Turing-complete, it also made me catch a bug in the C++ implementation which wasn't caught by the first four rulesets.
# Turing machine: three-state busy beaver
#
# state A, symbol 0 => write 1, move right, new state B
A0 -> 1B
# state A, symbol 1 => write 1, move left, new state C
0A1 -> C01
1A1 -> C11
# state B, symbol 0 => write 1, move left, new state A
0B0 -> A01
1B0 -> A11
# state B, symbol 1 => write 1, move right, new state B
B1 -> 1B
# state C, symbol 0 => write 1, move left, new state B
0C0 -> B01
1C0 -> B11
# state C, symbol 1 => write 1, move left, halt
0C1 -> H01
1C1 -> H11
This ruleset should turn
000000A000000
into
00011H1111000
| #PureBasic | PureBasic | Structure mRule
pattern.s
replacement.s
isTerminal.i
EndStructure
Procedure parseRule(text.s, List rules.mRule())
#tab = 9: #space = 32: #whiteSpace$ = Chr(#space) + Chr(#tab)
Protected tLen, cPtr, nChar.c, pEnd, pLast, pattern.s
cPtr = 1
If FindString(#whiteSpace$, Left(text, cPtr), 1): ProcedureReturn 0: EndIf ;parse error
If Left(text, cPtr) = "#": ProcedureReturn 2: EndIf ;comment skipped
tLen = Len(text)
Repeat
cPtr + 1
If cPtr > tLen: ProcedureReturn 0: EndIf ;parse error
nChar = Asc(Mid(text, cPtr, 1))
Select nChar
Case #space, #tab
Select pEnd
Case 0 To 2
pEnd = 1
pLast = cPtr - 1
Case 3
pattern = Left(text, pLast)
EndSelect
Case '-'
If pEnd = 1: pEnd = 2: EndIf
Case '>'
If pEnd = 2: pEnd = 3: EndIf
EndSelect
Until pattern <> ""
Repeat
cPtr + 1
Until Not FindString(#whiteSpace$, Mid(text, cPtr, 1), 1)
Protected isTerminal
If Mid(text, cPtr, 1) = "."
isTerminal = #True: cPtr + 1
EndIf
LastElement(rules()): AddElement(rules())
rules()\pattern = pattern
rules()\replacement = Right(text, tLen - cPtr + 1)
rules()\isTerminal = isTerminal
ProcedureReturn 1 ;processed rule
EndProcedure
Procedure.s interpretMarkov(text.s, List rules.mRule())
Repeat
madeReplacement = #False
ForEach rules()
If FindString(text, rules()\pattern, 1)
text = ReplaceString(text, rules()\pattern, rules()\replacement)
madeReplacement = #True: isFinished = rules()\isTerminal
Break
EndIf
Next
Until Not madeReplacement Or isFinished
ProcedureReturn text
EndProcedure
Procedure addRule(text.s, List rules.mRule())
Protected result = parseRule(text, rules())
Select result
Case 0: AddGadgetItem(7, -1, "Invalid rule: " + #DQUOTE$ + text + #DQUOTE$)
Case 1: AddGadgetItem(7, -1, "Added: " + #DQUOTE$ + text + #DQUOTE$)
Case 2: AddGadgetItem(7, -1, "Comment: " + #DQUOTE$ + text + #DQUOTE$)
EndSelect
EndProcedure
OpenWindow(0, 0, 0, 350, 300, "Markov Algorithm Interpreter", #PB_Window_SystemMenu)
ButtonGadget(0, 45, 10, 75, 20, "Load Ruleset")
ButtonGadget(1, 163, 10, 65, 20, "Add Rule")
ButtonGadget(2, 280, 10, 65, 20, "Interpret")
TextGadget(3, 5, 40, 30, 20, "Input:")
StringGadget(4, 45, 40, 300, 20,"")
TextGadget(5, 5, 100, 35, 20, "Output:")
ButtonGadget(6, 160, 70, 70, 20, "Clear Output")
EditorGadget(7, 45, 100, 300, 195, #PB_Editor_ReadOnly)
NewList rules.mRule()
Define event, isDone, text.s, result, file.s
Repeat
event = WaitWindowEvent()
Select event
Case #PB_Event_Gadget
Select EventGadget()
Case 0
Define file.s, rule.s
file = OpenFileRequester("Select rule set", "*.txt", "Text (*.txt)|*.txt", 0)
If file
ClearList(rules())
ReadFile(0, file)
While Not(Eof(0))
addRule(ReadString(0), rules())
Wend
AddGadgetItem(7, -1, "Loaded " + Str(ListSize(rules())) + " rules."): AddGadgetItem(7, -1, "")
EndIf
Case 1
addRule(GetGadgetText(4), rules())
Case 2
text = GetGadgetText(4): AddGadgetItem(7, -1, "Interpret: " + #DQUOTE$ + text + #DQUOTE$)
AddGadgetItem(7, -1, "Result: " + #DQUOTE$ + interpretMarkov(text, rules()) + #DQUOTE$): AddGadgetItem(7, -1, "")
Case 6
ClearGadgetItems(7)
EndSelect
Case #PB_Event_CloseWindow
isDone = #True
EndSelect
Until isDone
|
http://rosettacode.org/wiki/Exceptions/Catch_an_exception_thrown_in_a_nested_call | Exceptions/Catch an exception thrown in a nested call | Show how to create a user-defined exception and show how to catch an exception raised from several nested calls away.
Create two user-defined exceptions, U0 and U1.
Have function foo call function bar twice.
Have function bar call function baz.
Arrange for function baz to raise, or throw exception U0 on its first call, then exception U1 on its second.
Function foo should catch only exception U0, not U1.
Show/describe what happens when the program is run.
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
const EXCEPTION: U0 is enumlit;
const EXCEPTION: U1 is enumlit;
const proc: baz (in integer: num) is func
begin
if num = 1 then
raise U0;
else
raise U1;
end if;
end func;
const proc: bar (in integer: num) is func
begin
baz(num);
end func;
const proc: foo is func
local
var integer: num is 0;
begin
for num range 1 to 2 do
block
bar(num);
exception
catch U0: writeln("U0 catched");
end block;
end for;
end func;
const proc: main is func
begin
foo;
end func; |
http://rosettacode.org/wiki/Exceptions/Catch_an_exception_thrown_in_a_nested_call | Exceptions/Catch an exception thrown in a nested call | Show how to create a user-defined exception and show how to catch an exception raised from several nested calls away.
Create two user-defined exceptions, U0 and U1.
Have function foo call function bar twice.
Have function bar call function baz.
Arrange for function baz to raise, or throw exception U0 on its first call, then exception U1 on its second.
Function foo should catch only exception U0, not U1.
Show/describe what happens when the program is run.
| #Sidef | Sidef | func baz(i) { die "U#{i}" };
func bar(i) { baz(i) };
func foo {
[0, 1].each { |i|
try { bar(i) }
catch { |_, msg|
msg ~~ /^U0/ ? say "Function foo() caught exception U0"
: die msg; # re-raise the exception
};
}
}
foo(); |
http://rosettacode.org/wiki/Exceptions/Catch_an_exception_thrown_in_a_nested_call | Exceptions/Catch an exception thrown in a nested call | Show how to create a user-defined exception and show how to catch an exception raised from several nested calls away.
Create two user-defined exceptions, U0 and U1.
Have function foo call function bar twice.
Have function bar call function baz.
Arrange for function baz to raise, or throw exception U0 on its first call, then exception U1 on its second.
Function foo should catch only exception U0, not U1.
Show/describe what happens when the program is run.
| #Smalltalk | Smalltalk |
Exception subclass: #U0.
Exception subclass: #U1.
Object subclass: Foo [
bazCount := 0.
foo
[2 timesRepeat:
[ "==>" [self bar] "<=="
on: U0
do:
[:sig |
'Call to bar was aborted by exception U0' printNl.
sig return]]]
bar
[self baz]
baz
[bazCount := bazCount + 1.
bazCount = 1 ifTrue: [U0 new signal].
bazCount = 2 ifTrue: [U1 new signal].
"Thirds time's a charm..."]
]
|
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
| #MATLAB | MATLAB | >> error 'Help'
??? Help |
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
| #Modula-3 | Modula-3 | EXCEPTION EndOfFile;
EXCEPTION Error(TEXT); |
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
| #Io | Io | System runCommand("ls") stdout println |
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
| #IS-BASIC | IS-BASIC | 100 EXT "dir" |
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
| #J | J | load'task'
NB. Execute a command and wait for it to complete
shell 'dir'
NB. Execute a command but don't wait for it to complete
fork 'notepad'
NB. Execute a command and capture its stdout
stdout =: shell 'dir'
NB. Execute a command, provide it with stdin,
NB. and capture its stdout
stdin =: 'blahblahblah'
stdout =: stdin spawn 'grep blah' |
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
| #Babel | Babel | ((main
{(0 1 2 3 4 5 6 7 8 9 10)
{fact ! %d nl <<}
each})
(fact
{({dup 0 =}{ zap 1 }
{dup 1 =}{ zap 1 }
{1 }{ <- 1 {iter 1 + *} -> 1 - times })
cond})) |
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
| #Pascal | Pascal | Program ExponentiationOperator(output);
function intexp (base, exponent: integer): longint;
var
i: integer;
begin
if (exponent < 0) then
if (base = 1) then
intexp := 1
else
intexp := 0
else
begin
intexp := 1;
for i := 1 to exponent do
intexp := intexp * base;
end;
end;
function realexp (base: real; exponent: integer): real;
var
i: integer;
begin
realexp := 1.0;
if (exponent < 0) then
for i := exponent to -1 do
realexp := realexp / base
else
for i := 1 to exponent do
realexp := realexp * base;
end;
begin
writeln('2^30: ', intexp(2, 30));
writeln('2.0^30: ', realexp(2.0, 30));
end. |
http://rosettacode.org/wiki/Extend_your_language | Extend your language | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. by using macros), other languages go much further. Most notably in the Forth and Lisp families, programming per se is done by extending the language without any formal distinction between built-in and user-defined elements.
If your language supports it, show how to introduce a new flow control mechanism. A practical and useful example is a four-way branch:
Occasionally, code must be written that depends on two conditions, resulting in up to four branches (depending on whether both, only the first, only the second, or none of the conditions are "true"). In a C-like language this could look like the following:
if (condition1isTrue) {
if (condition2isTrue)
bothConditionsAreTrue();
else
firstConditionIsTrue();
}
else if (condition2isTrue)
secondConditionIsTrue();
else
noConditionIsTrue();
Besides being rather cluttered, the statement(s) for 'condition2isTrue' must be written down twice. If 'condition2isTrue' were a lengthy and involved expression, it would be quite unreadable, and the code generated by the compiler might be unnecessarily large.
This can be improved by introducing a new keyword if2. It is similar to if, but takes two conditional statements instead of one, and up to three 'else' statements. One proposal (in pseudo-C syntax) might be:
if2 (condition1isTrue) (condition2isTrue)
bothConditionsAreTrue();
else1
firstConditionIsTrue();
else2
secondConditionIsTrue();
else
noConditionIsTrue();
Pick the syntax which suits your language. The keywords 'else1' and 'else2' are just examples. The new conditional expression should look, nest and behave analogously to the language's built-in 'if' statement.
| #Ursala | Ursala | iftwo("p","q") <"both","justp","justq","neither"> =
"p"?(
"q"?("both","justp"),
"q"?("justq","neither")) |
http://rosettacode.org/wiki/Extend_your_language | Extend your language | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. by using macros), other languages go much further. Most notably in the Forth and Lisp families, programming per se is done by extending the language without any formal distinction between built-in and user-defined elements.
If your language supports it, show how to introduce a new flow control mechanism. A practical and useful example is a four-way branch:
Occasionally, code must be written that depends on two conditions, resulting in up to four branches (depending on whether both, only the first, only the second, or none of the conditions are "true"). In a C-like language this could look like the following:
if (condition1isTrue) {
if (condition2isTrue)
bothConditionsAreTrue();
else
firstConditionIsTrue();
}
else if (condition2isTrue)
secondConditionIsTrue();
else
noConditionIsTrue();
Besides being rather cluttered, the statement(s) for 'condition2isTrue' must be written down twice. If 'condition2isTrue' were a lengthy and involved expression, it would be quite unreadable, and the code generated by the compiler might be unnecessarily large.
This can be improved by introducing a new keyword if2. It is similar to if, but takes two conditional statements instead of one, and up to three 'else' statements. One proposal (in pseudo-C syntax) might be:
if2 (condition1isTrue) (condition2isTrue)
bothConditionsAreTrue();
else1
firstConditionIsTrue();
else2
secondConditionIsTrue();
else
noConditionIsTrue();
Pick the syntax which suits your language. The keywords 'else1' and 'else2' are just examples. The new conditional expression should look, nest and behave analogously to the language's built-in 'if' statement.
| #Wren | Wren | class IfBoth {
construct new(cond1, cond2) {
_cond1 = cond1
_cond2 = cond2
}
elseFirst(func) {
if (_cond1 && !_cond2) func.call()
return this
}
elseSecond(func) {
if (_cond2 && !_cond1) func.call()
return this
}
elseNeither(func) {
if (!_cond1 && !_cond2) func.call()
return this // in case it's called out of order
}
}
var ifBoth = Fn.new { |cond1, cond2, func|
if (cond1 && cond2) func.call()
return IfBoth.new(cond1, cond2)
}
var a = 0
var b = 1
ifBoth.call(a == 1, b == 3) {
System.print("a == 1 and b == 3")
}.elseFirst {
System.print("a == 1 and b <> 3")
}.elseSecond {
System.print("a <> 1 and b = 3")
}.elseNeither {
System.print("a <> 1 and b <> 3")
}
// It's also possible to omit any (or all) of the 'else' clauses
// or to call them out of order.
a = 1
b = 0
ifBoth.call (a == 1, b == 3) {
System.print("a == 1 and b == 3")
}.elseNeither {
System.print("a <> 1 and b <> 3")
}.elseFirst {
System.print("a == 1 and b <> 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
| #Simula | Simula | begin
integer i;
for i := 1 step 1 until 100 do
begin
boolean fizzed;
fizzed := 0 = mod(i, 3);
if fizzed then
outtext("Fizz");
if mod(i, 5) = 0 then
outtext("Buzz")
else if not fizzed then
outint(i, 3);
outimage
end;
end |
http://rosettacode.org/wiki/Extensible_prime_generator | Extensible prime generator | Task
Write a generator of prime numbers, in order, that will automatically adjust to accommodate the generation of any reasonably high prime.
The routine should demonstrably rely on either:
Being based on an open-ended counter set to count without upper limit other than system or programming language limits. In this case, explain where this counter is in the code.
Being based on a limit that is extended automatically. In this case, choose a small limit that ensures the limit will be passed when generating some of the values to be asked for below.
If other methods of creating an extensible prime generator are used, the algorithm's means of extensibility/lack of limits should be stated.
The routine should be used to:
Show the first twenty primes.
Show the primes between 100 and 150.
Show the number of primes between 7,700 and 8,000.
Show the 10,000th prime.
Show output on this page.
Note: You may reference code already on this site if it is written to be imported/included, then only the code necessary for import and the performance of this task need be shown. (It is also important to leave a forward link on the referenced tasks entry so that later editors know that the code is used for multiple tasks).
Note 2: If a languages in-built prime generator is extensible or is guaranteed to generate primes up to a system limit, (231 or memory overflow for example), then this may be used as long as an explanation of the limits of the prime generator is also given. (Which may include a link to/excerpt from, language documentation).
Note 3:The task is written so it may be useful in solving the task Emirp primes as well as others (depending on its efficiency).
Reference
Prime Numbers. Website with large count of primes.
| #Tcl | Tcl | package require Tcl 8.6
# An iterative version of the Sieve of Eratosthenes.
# Effective limit is the size of memory.
coroutine primes apply {{} {
yield
while 1 {yield [coroutine primes_[incr p] apply {{} {
yield [info coroutine]
set plist {}
for {set n 2} true {incr n} {
set found 0
foreach p $plist {
if {$n%$p==0} {
set found 1
break
}
}
if {!$found} {
lappend plist $n
yield $n
}
}
}}]}
}}
set p [primes]
for {set primes {}} {[llength $primes] < 20} {} {
lappend primes [$p]
}
puts 1st20=[join $primes ,]
rename $p {}
set p [primes]
for {set primes {}} {[set n [$p]] <= 150} {} {
if {$n >= 100 && $n <= 150} {
lappend primes $n
}
}
puts 100-150=[join $primes ,]
rename $p {}
set p [primes]
for {set count 0} {[set n [$p]] <= 8000} {} {
incr count [expr {$n>=7700 && $n<=8000}]
}
puts count7700-8000=$count
rename $p {}
set p [primes]
for {set count 0} {$count < 10000} {incr count} {
set prime [$p]
}
puts prime10000=$prime
rename $p {} |
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.
| #CLU | CLU | tape = cluster is new, left, right, get_cell, set_cell
ac = array[char]
rep = record [
cells: ac,
index: int
]
new = proc () returns (cvt)
t: rep := rep${
cells: ac$predict(0, 30000),
index: 0
}
ac$addh(t.cells, '\000')
return(t)
end new
left = proc (t: cvt)
t.index := t.index - 1
if t.index < ac$low(t.cells) then ac$addl(t.cells, '\000') end
end left
right = proc (t: cvt)
t.index := t.index + 1
if t.index > ac$high(t.cells) then ac$addh(t.cells, '\000') end
end right
get_cell = proc (t: cvt) returns (int)
return (char$c2i(t.cells[t.index]) // 256)
end get_cell
set_cell = proc (t: cvt, i: int)
t.cells[t.index] := char$i2c(i // 256)
end set_cell
end tape
program = cluster is parse, fetch, jump
loop_jump = struct[from, to: int]
alj = array[loop_jump]
slj = sequence[loop_jump]
rep = struct [
loops: slj,
code: string
]
parse = proc (s: string) returns (cvt) signals (bad_loops)
ac = array[char]
prog: ac := ac$predict(1, string$size(s))
loops: alj := alj$[]
loop_stack: array[int] := array[int]$[]
for c: char in string$chars(s) do
if string$indexc(c, "+-<>,.[]") = 0 then continue end
ac$addh(prog, c)
if c = '[' then
array[int]$addh(loop_stack, ac$high(prog))
elseif c = ']' then
here: int := ac$high(prog)
there: int := array[int]$remh(loop_stack)
except when bounds: signal bad_loops end
alj$addh(loops, loop_jump${from: here, to: there})
alj$addh(loops, loop_jump${from: there, to: here})
end
end
if ~array[int]$empty(loop_stack) then signal bad_loops end
return (rep${loops: slj$a2s(loops), code: string$ac2s(prog)})
end parse
fetch = proc (p: cvt, i: int) returns (char) signals (bounds)
return (p.code[i]) resignal bounds
end fetch
jump = proc (p: cvt, i: int) returns (int) signals (not_found)
for j: loop_jump in slj$elements(p.loops) do
if j.from = i then return (j.to) end
end
signal not_found
end jump
end program
brainf = cluster is make, run
rep = struct [
prog: program,
mem: tape,
inp, out: stream
]
make = proc (p: program, i, o: stream) returns (cvt)
return (rep${
prog: p,
inp: i,
out: o,
mem: tape$new()
})
end make
read = proc (p: rep) returns (int)
return (char$c2i(stream$getc(p.inp)))
except when end_of_file:
return (0)
end
end read
write = proc (p: rep, c: int)
stream$putc(p.out, char$i2c(c))
end write
run = proc (p: cvt)
ip: int := 1
while true do
op: char := p.prog[ip] except when bounds: break end
if op = '+' then p.mem.cell := p.mem.cell + 1
elseif op = '-' then p.mem.cell := p.mem.cell - 1
elseif op = '>' then tape$right(p.mem)
elseif op = '<' then tape$left(p.mem)
elseif op = ',' then p.mem.cell := read(p)
elseif op = '.' then write(p, p.mem.cell)
elseif op = '[' cand p.mem.cell = 0 then
ip := program$jump(p.prog, ip)
elseif op = ']' cand p.mem.cell ~= 0 then
ip := program$jump(p.prog, ip)
end
ip := ip + 1
end
end run
end brainf
read_whole_stream = proc (s: stream) returns (string)
chars: array[char] := array[char]$predict(1, 4096)
while true do
array[char]$addh(chars, stream$getc(s))
except when end_of_file: break end
end
return (string$ac2s(chars))
end read_whole_stream
start_up = proc ()
pi: stream := stream$primary_input()
po: stream := stream$primary_output()
stream$puts(po, "Filename? ")
fname: file_name := file_name$parse(stream$getl(pi))
file: stream := stream$open(fname, "read")
code: string := read_whole_stream(file)
stream$close(file)
prog: program := program$parse(code)
interp: brainf := brainf$make(prog, pi, po)
brainf$run(interp)
end start_up |
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.
| #Delphi | Delphi | pragma.syntax("0.9")
pragma.enable("accumulator")
def target := "METHINKS IT IS LIKE A WEASEL"
def alphabet := "ABCDEFGHIJKLMNOPQRSTUVWXYZ "
def C := 100
def RATE := 0.05
def randomCharString() {
return E.toString(alphabet[entropy.nextInt(alphabet.size())])
}
def fitness(string) {
return accum 0 for i => ch in string {
_ + (ch == target[i]).pick(1, 0)
}
}
def mutate(string, rate) {
return accum "" for i => ch in string {
_ + (entropy.nextDouble() < rate).pick(randomCharString(), E.toString(ch))
}
}
def weasel() {
var parent := accum "" for _ in 1..(target.size()) { _ + randomCharString() }
var generation := 0
while (parent != target) {
println(`$generation $parent`)
def copies := accum [] for _ in 1..C { _.with(mutate(parent, RATE)) }
var best := parent
for c in copies {
if (fitness(c) > fitness(best)) {
best := c
}
}
parent := best
generation += 1
}
println(`$generation $parent`)
}
weasel() |
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
| #LLVM | LLVM | ; This is not strictly LLVM, as it uses the C library function "printf".
; LLVM does not provide a way to print values, so the alternative would be
; to just load the string into memory, and that would be boring.
; Additional comments have been inserted, as well as changes made from the output produced by clang such as putting more meaningful labels for the jumps
$"PRINT_LONG" = comdat any
@"PRINT_LONG" = linkonce_odr unnamed_addr constant [5 x i8] c"%ld\0A\00", comdat, align 1
;--- The declaration for the external C printf function.
declare i32 @printf(i8*, ...)
;--------------------------------------------------------------------
;-- Function for calculating the nth fibonacci numbers
;--------------------------------------------------------------------
define i32 @fibonacci(i32) {
%2 = alloca i32, align 4 ;-- allocate local copy of n
%3 = alloca i32, align 4 ;-- allocate a
%4 = alloca i32, align 4 ;-- allocate b
store i32 %0, i32* %2, align 4 ;-- store copy of n
store i32 0, i32* %3, align 4 ;-- a := 0
store i32 1, i32* %4, align 4 ;-- b := 1
br label %loop
loop:
%5 = load i32, i32* %2, align 4 ;-- load n
%6 = icmp sgt i32 %5, 0 ;-- n > 0
br i1 %6, label %loop_body, label %exit
loop_body:
%7 = load i32, i32* %3, align 4 ;-- load a
%8 = load i32, i32* %4, align 4 ;-- load b
%9 = add nsw i32 %7, %8 ;-- t = a + b
store i32 %8, i32* %3, align 4 ;-- store a = b
store i32 %9, i32* %4, align 4 ;-- store b = t
%10 = load i32, i32* %2, align 4 ;-- load n
%11 = add nsw i32 %10, -1 ;-- decrement n
store i32 %11, i32* %2, align 4 ;-- store n
br label %loop
exit:
%12 = load i32, i32* %3, align 4 ;-- load a
ret i32 %12 ;-- return a
}
;--------------------------------------------------------------------
;-- Main function for printing successive fibonacci numbers
;--------------------------------------------------------------------
define i32 @main() {
%1 = alloca i32, align 4 ;-- allocate index
store i32 0, i32* %1, align 4 ;-- index := 0
br label %loop
loop:
%2 = load i32, i32* %1, align 4 ;-- load index
%3 = icmp sle i32 %2, 12 ;-- index <= 12
br i1 %3, label %loop_body, label %exit
loop_body:
%4 = load i32, i32* %1, align 4 ;-- load index
%5 = call i32 @fibonacci(i32 %4)
%6 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([5 x i8], [5 x i8]* @"PRINT_LONG", i32 0, i32 0), i32 %5)
%7 = load i32, i32* %1, align 4 ;-- load index
%8 = add nsw i32 %7, 1 ;-- increment index
store i32 %8, i32* %1, align 4 ;-- store index
br label %loop
exit:
ret i32 0 ;-- return EXIT_SUCCESS
} |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #Racket | Racket | #lang racket
; if we `for` over the port, we won't have the program in memory for 'Q'
(define (parse-HQ9+ the-program)
(define oTW " on the wall")
(and ; ensures the accumulator is never seen!
(for/fold ((A 0))
((token (in-string the-program)))
(case token
((#\H) (display "hello, world") A)
((#\Q) (display the-program) A)
;; official esolang version of 99-BoB at:
;; http://esolangs.org/wiki/99_bottles_of_beer
((#\9)
(displayln
(let ((BoB (lambda (n)
(string-append
(case n ((1) "1 bottle") ((0) "No bottles")
(else (format "~a bottles" n)))
" of beer"))))
(string-join
(for/list ((btls (in-range 99 0 -1)))
(string-append (BoB btls)oTW",\n"(BoB btls)
".\nTake one down, pass it around,\n"
(BoB (sub1 btls))oTW"."))
"\n\n"))) A)
((#\+) (add1 A))
((#\newline) ; language extension, makes getting standard in easier
(eprintf "warning: HQ9+: language extension ~s" token)
A)
(else (error "syntax error: HQ9+: unrecognised token ~s" token))))
(void)))
(module+ main (parse-HQ9+ (port->string)))
(module+ test
(require rackunit)
(check-equal? (with-output-to-string (lambda () (parse-HQ9+ ""))) "")
(check-equal? (with-output-to-string (lambda () (parse-HQ9+ "H"))) "hello, world")
(check-equal? (with-output-to-string (lambda () (parse-HQ9+ "Q"))) "Q")
(check-equal? (with-output-to-string (lambda () (parse-HQ9+ "QQ"))) "QQQQ")
(check-equal? (with-output-to-string (lambda () (parse-HQ9+ "+"))) "")
(check-equal? (with-output-to-string (lambda () (parse-HQ9+ "+"))) "")
(check-equal? (with-output-to-string (lambda () (parse-HQ9+ "++"))) "")
(check-equal? (with-output-to-string (lambda () (parse-HQ9+ "+++"))) "")
(check-equal? (with-output-to-string (lambda () (parse-HQ9+ "+++++++++++++++++"))) "")
(check-equal? (with-output-to-string (lambda () (parse-HQ9+ (make-string 10000 #\+)))) "")
;;; you can jolly well read (and sing along to) the output of '9'
) |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #Raku | Raku | class HQ9Interpreter {
has @!code;
has $!accumulator;
has $!pointer;
method run ($code) {
@!code = $code.comb;
$!accumulator = 0;
$!pointer = 0;
while $!pointer < @!code {
given @!code[$!pointer].lc {
when 'h' { say 'Hello world!' }
when 'q' { say @!code }
when '9' { bob(99) }
when '+' { $!accumulator++ }
default { note "Syntax error: Unknown command \"{@!code[$!pointer]}\"" }
}
$!pointer++;
}
}
sub bob ($beer is copy) {
sub what { "{$beer??$beer!!'No more'} bottle{$beer-1??'s'!!''} of beer" };
sub where { 'on the wall' };
sub drink { $beer--; "Take one down, pass it around," }
while $beer {
.say for "&what() &where(),", "&what()!",
"&drink()", "&what() &where()!", ''
}
}
}
# Feed it a command string:
my $hq9 = HQ9Interpreter.new;
$hq9.run("hHq+++Qq");
say '';
$hq9.run("Jhq.k+hQ"); |
http://rosettacode.org/wiki/Execute_a_Markov_algorithm | Execute a Markov algorithm | Execute a Markov algorithm
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create an interpreter for a Markov Algorithm.
Rules have the syntax:
<ruleset> ::= ((<comment> | <rule>) <newline>+)*
<comment> ::= # {<any character>}
<rule> ::= <pattern> <whitespace> -> <whitespace> [.] <replacement>
<whitespace> ::= (<tab> | <space>) [<whitespace>]
There is one rule per line.
If there is a . (period) present before the <replacement>, then this is a terminating rule in which case the interpreter must halt execution.
A ruleset consists of a sequence of rules, with optional comments.
Rulesets
Use the following tests on entries:
Ruleset 1
# This rules file is extracted from Wikipedia:
# http://en.wikipedia.org/wiki/Markov_Algorithm
A -> apple
B -> bag
S -> shop
T -> the
the shop -> my brother
a never used -> .terminating rule
Sample text of:
I bought a B of As from T S.
Should generate the output:
I bought a bag of apples from my brother.
Ruleset 2
A test of the terminating rule
# Slightly modified from the rules on Wikipedia
A -> apple
B -> bag
S -> .shop
T -> the
the shop -> my brother
a never used -> .terminating rule
Sample text of:
I bought a B of As from T S.
Should generate:
I bought a bag of apples from T shop.
Ruleset 3
This tests for correct substitution order and may trap simple regexp based replacement routines if special regexp characters are not escaped.
# BNF Syntax testing rules
A -> apple
WWWW -> with
Bgage -> ->.*
B -> bag
->.* -> money
W -> WW
S -> .shop
T -> the
the shop -> my brother
a never used -> .terminating rule
Sample text of:
I bought a B of As W my Bgage from T S.
Should generate:
I bought a bag of apples with my money from T shop.
Ruleset 4
This tests for correct order of scanning of rules, and may trap replacement routines that scan in the wrong order. It implements a general unary multiplication engine. (Note that the input expression must be placed within underscores in this implementation.)
### Unary Multiplication Engine, for testing Markov Algorithm implementations
### By Donal Fellows.
# Unary addition engine
_+1 -> _1+
1+1 -> 11+
# Pass for converting from the splitting of multiplication into ordinary
# addition
1! -> !1
,! -> !+
_! -> _
# Unary multiplication by duplicating left side, right side times
1*1 -> x,@y
1x -> xX
X, -> 1,1
X1 -> 1X
_x -> _X
,x -> ,X
y1 -> 1y
y_ -> _
# Next phase of applying
1@1 -> x,@y
1@_ -> @_
,@_ -> !_
++ -> +
# Termination cleanup for addition
_1 -> 1
1+_ -> 1
_+_ ->
Sample text of:
_1111*11111_
should generate the output:
11111111111111111111
Ruleset 5
A simple Turing machine,
implementing a three-state busy beaver.
The tape consists of 0s and 1s, the states are A, B, C and H (for Halt), and the head position is indicated by writing the state letter before the character where the head is.
All parts of the initial tape the machine operates on have to be given in the input.
Besides demonstrating that the Markov algorithm is Turing-complete, it also made me catch a bug in the C++ implementation which wasn't caught by the first four rulesets.
# Turing machine: three-state busy beaver
#
# state A, symbol 0 => write 1, move right, new state B
A0 -> 1B
# state A, symbol 1 => write 1, move left, new state C
0A1 -> C01
1A1 -> C11
# state B, symbol 0 => write 1, move left, new state A
0B0 -> A01
1B0 -> A11
# state B, symbol 1 => write 1, move right, new state B
B1 -> 1B
# state C, symbol 0 => write 1, move left, new state B
0C0 -> B01
1C0 -> B11
# state C, symbol 1 => write 1, move left, halt
0C1 -> H01
1C1 -> H11
This ruleset should turn
000000A000000
into
00011H1111000
| #Python | Python | import re
def extractreplacements(grammar):
return [ (matchobj.group('pat'), matchobj.group('repl'), bool(matchobj.group('term')))
for matchobj in re.finditer(syntaxre, grammar)
if matchobj.group('rule')]
def replace(text, replacements):
while True:
for pat, repl, term in replacements:
if pat in text:
text = text.replace(pat, repl, 1)
if term:
return text
break
else:
return text
syntaxre = r"""(?mx)
^(?:
(?: (?P<comment> \# .* ) ) |
(?: (?P<blank> \s* ) (?: \n | $ ) ) |
(?: (?P<rule> (?P<pat> .+? ) \s+ -> \s+ (?P<term> \.)? (?P<repl> .+) ) )
)$
"""
grammar1 = """\
# This rules file is extracted from Wikipedia:
# http://en.wikipedia.org/wiki/Markov_Algorithm
A -> apple
B -> bag
S -> shop
T -> the
the shop -> my brother
a never used -> .terminating rule
"""
grammar2 = '''\
# Slightly modified from the rules on Wikipedia
A -> apple
B -> bag
S -> .shop
T -> the
the shop -> my brother
a never used -> .terminating rule
'''
grammar3 = '''\
# BNF Syntax testing rules
A -> apple
WWWW -> with
Bgage -> ->.*
B -> bag
->.* -> money
W -> WW
S -> .shop
T -> the
the shop -> my brother
a never used -> .terminating rule
'''
grammar4 = '''\
### Unary Multiplication Engine, for testing Markov Algorithm implementations
### By Donal Fellows.
# Unary addition engine
_+1 -> _1+
1+1 -> 11+
# Pass for converting from the splitting of multiplication into ordinary
# addition
1! -> !1
,! -> !+
_! -> _
# Unary multiplication by duplicating left side, right side times
1*1 -> x,@y
1x -> xX
X, -> 1,1
X1 -> 1X
_x -> _X
,x -> ,X
y1 -> 1y
y_ -> _
# Next phase of applying
1@1 -> x,@y
1@_ -> @_
,@_ -> !_
++ -> +
# Termination cleanup for addition
_1 -> 1
1+_ -> 1
_+_ ->
'''
grammar5 = '''\
# Turing machine: three-state busy beaver
#
# state A, symbol 0 => write 1, move right, new state B
A0 -> 1B
# state A, symbol 1 => write 1, move left, new state C
0A1 -> C01
1A1 -> C11
# state B, symbol 0 => write 1, move left, new state A
0B0 -> A01
1B0 -> A11
# state B, symbol 1 => write 1, move right, new state B
B1 -> 1B
# state C, symbol 0 => write 1, move left, new state B
0C0 -> B01
1C0 -> B11
# state C, symbol 1 => write 1, move left, halt
0C1 -> H01
1C1 -> H11
'''
text1 = "I bought a B of As from T S."
text2 = "I bought a B of As W my Bgage from T S."
text3 = '_1111*11111_'
text4 = '000000A000000'
if __name__ == '__main__':
assert replace(text1, extractreplacements(grammar1)) \
== 'I bought a bag of apples from my brother.'
assert replace(text1, extractreplacements(grammar2)) \
== 'I bought a bag of apples from T shop.'
# Stretch goals
assert replace(text2, extractreplacements(grammar3)) \
== 'I bought a bag of apples with my money from T shop.'
assert replace(text3, extractreplacements(grammar4)) \
== '11111111111111111111'
assert replace(text4, extractreplacements(grammar5)) \
== '00011H1111000' |
http://rosettacode.org/wiki/Exceptions/Catch_an_exception_thrown_in_a_nested_call | Exceptions/Catch an exception thrown in a nested call | Show how to create a user-defined exception and show how to catch an exception raised from several nested calls away.
Create two user-defined exceptions, U0 and U1.
Have function foo call function bar twice.
Have function bar call function baz.
Arrange for function baz to raise, or throw exception U0 on its first call, then exception U1 on its second.
Function foo should catch only exception U0, not U1.
Show/describe what happens when the program is run.
| #Swift | Swift | enum MyException : ErrorType {
case U0
case U1
}
func foo() throws {
for i in 0 ... 1 {
do {
try bar(i)
} catch MyException.U0 {
print("Function foo caught exception U0")
}
}
}
func bar(i: Int) throws {
try baz(i) // Nest those calls
}
func baz(i: Int) throws {
if i == 0 {
throw MyException.U0
} else {
throw MyException.U1
}
}
try foo() |
http://rosettacode.org/wiki/Exceptions/Catch_an_exception_thrown_in_a_nested_call | Exceptions/Catch an exception thrown in a nested call | Show how to create a user-defined exception and show how to catch an exception raised from several nested calls away.
Create two user-defined exceptions, U0 and U1.
Have function foo call function bar twice.
Have function bar call function baz.
Arrange for function baz to raise, or throw exception U0 on its first call, then exception U1 on its second.
Function foo should catch only exception U0, not U1.
Show/describe what happens when the program is run.
| #Tcl | Tcl | package require Tcl 8.5
proc foo {} {
set code [catch {bar} ex options]
if {$code == 1} {
switch -exact -- $ex {
U0 {puts "caught exception U0"}
default {return -options $options $ex ;# re-raise exception}
}
}
}
proc bar {} {baz}
# create an alias to pass the initial exception U0 to the baz proc
interp alias {} baz {} _baz U0
proc _baz {exception} {
# re-set the alias so subsequent invocations will use exception U1
interp alias {} baz {} _baz U1
# throw
return -code error $exception
}
foo
foo |
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
| #MOO | MOO | raise(E_PERM); |
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
| #Nanoquery | Nanoquery | try
invalid "this statement will fail"
catch e
println "caught an exception"
println e
end try |
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
| #Java | Java | import java.util.Scanner;
import java.io.*;
public class Program {
public static void main(String[] args) {
try {
Process p = Runtime.getRuntime().exec("cmd /C dir");//Windows command, use "ls -oa" for UNIX
Scanner sc = new Scanner(p.getInputStream());
while (sc.hasNext()) System.out.println(sc.nextLine());
}
catch (IOException e) {
System.out.println(e.getMessage());
}
}
} |
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
| #JavaScript | JavaScript | var shell = new ActiveXObject("WScript.Shell");
shell.run("cmd /c dir & pause"); |
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
| #BaCon | BaCon | ' Factorial
FUNCTION factorial(NUMBER n) TYPE NUMBER
IF n <= 1 THEN
RETURN 1
ELSE
RETURN n * factorial(n - 1)
ENDIF
END FUNCTION
n = VAL(TOKEN$(ARGUMENT$, 2))
PRINT n, factorial(n) FORMAT "%ld! = %ld\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
| #Perl | Perl | #!/usr/bin/perl -w
use strict ;
sub expon {
my ( $base , $expo ) = @_ ;
if ( $expo == 0 ) {
return 1 ;
}
elsif ( $expo == 1 ) {
return $base ;
}
elsif ( $expo > 1 ) {
my $prod = 1 ;
foreach my $n ( 0..($expo - 1) ) {
$prod *= $base ;
}
return $prod ;
}
elsif ( $expo < 0 ) {
return 1 / ( expon ( $base , -$expo ) ) ;
}
}
print "3 to the power of 10 as a function is " . expon( 3 , 10 ) . " !\n" ;
print "3 to the power of 10 as a builtin is " . 3**10 . " !\n" ;
print "5.5 to the power of -3 as a function is " . expon( 5.5 , -3 ) . " !\n" ;
print "5.5 to the power of -3 as a builtin is " . 5.5**-3 . " !\n" ;
|
http://rosettacode.org/wiki/Extend_your_language | Extend your language | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. by using macros), other languages go much further. Most notably in the Forth and Lisp families, programming per se is done by extending the language without any formal distinction between built-in and user-defined elements.
If your language supports it, show how to introduce a new flow control mechanism. A practical and useful example is a four-way branch:
Occasionally, code must be written that depends on two conditions, resulting in up to four branches (depending on whether both, only the first, only the second, or none of the conditions are "true"). In a C-like language this could look like the following:
if (condition1isTrue) {
if (condition2isTrue)
bothConditionsAreTrue();
else
firstConditionIsTrue();
}
else if (condition2isTrue)
secondConditionIsTrue();
else
noConditionIsTrue();
Besides being rather cluttered, the statement(s) for 'condition2isTrue' must be written down twice. If 'condition2isTrue' were a lengthy and involved expression, it would be quite unreadable, and the code generated by the compiler might be unnecessarily large.
This can be improved by introducing a new keyword if2. It is similar to if, but takes two conditional statements instead of one, and up to three 'else' statements. One proposal (in pseudo-C syntax) might be:
if2 (condition1isTrue) (condition2isTrue)
bothConditionsAreTrue();
else1
firstConditionIsTrue();
else2
secondConditionIsTrue();
else
noConditionIsTrue();
Pick the syntax which suits your language. The keywords 'else1' and 'else2' are just examples. The new conditional expression should look, nest and behave analogously to the language's built-in 'if' statement.
| #XBS | XBS | #>
newsyntax
@in:CH
@token:does
@CH:"function(Stack){
this.Next(Stack);
this.ChunkWrite(Stack,this.ParseExpression(Stack));
this.TestNext(Stack,\"Bracket\",\"TK_BOPEN\");
this.Move(Stack,2);
this.CodeBlock(Stack);
this.JumpBack(Stack);
this.OpenChunk(Stack);
while(this.CheckNext(Stack,\"Identifier\",\"otherwise\")||this.CheckNext(Stack,\"Identifier\",\"or\")){
if(this.CheckNext(Stack,\"Identifier\",\"otherwise\")){
this.OpenChunk(Stack);
this.ChunkWrite(Stack,\"else\");
this.Next(Stack);
this.TestNext(Stack,\"Bracket\",\"TK_BOPEN\");
this.Move(Stack,2);
this.CodeBlock(Stack);
this.JumpBack(Stack);
this.CloseChunk(Stack);
break;
}else{
this.OpenChunk(Stack);
this.ChunkWrite(Stack,\"elif\");
this.Move(Stack,2);
this.ChunkWrite(Stack,this.ParseExpression(Stack));
this.TestNext(Stack,\"Bracket\",\"TK_BOPEN\");
this.Move(Stack,2);
this.CodeBlock(Stack);
this.JumpBack(Stack);
this.CloseChunk(Stack);
}
}
this.CloseChunk(Stack);
}"
@Interpret:"function(AST,Token){
let Condition = this.Parse(AST,Token[3]);
if(Condition){
this.CondState(AST,Token[4]);
} else {
let Conds = Token[5];
if(Conds.length<1){return}
let DidCond = false;
let ElseCond = undefined;
for(let v of Conds){
if(DidCond){break}
if(v[0]==\"else\"){
ElseCond=v;
break;
}else if(v[0]==\"elif\"){
let Exp = this.Parse(AST,v[1]);
if(Exp){
DidCond=true;
this.CondState(AST,v[2]);
break;
}
}
}
if(!DidCond&&ElseCond){
this.CondState(AST,ElseCond[1]);
}
}
}"
<#
func equalsOneOrTwo(a){
does a == 1 {
log(`Yep! {a} == 1`);
} or a == 2 {
log(`Yes, {a} == 2`);
} otherwise {
does a <= 0 {
log(`Sorry, your number {a} must be greater than 0!`);
} otherwise {
log(`Nope. {a} != 1 or 2`);
}
}
}
equalsOneOrTwo(1);
equalsOneOrTwo(2);
equalsOneOrTwo(3);
equalsOneOrTwo(0); |
http://rosettacode.org/wiki/Extend_your_language | Extend your language | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. by using macros), other languages go much further. Most notably in the Forth and Lisp families, programming per se is done by extending the language without any formal distinction between built-in and user-defined elements.
If your language supports it, show how to introduce a new flow control mechanism. A practical and useful example is a four-way branch:
Occasionally, code must be written that depends on two conditions, resulting in up to four branches (depending on whether both, only the first, only the second, or none of the conditions are "true"). In a C-like language this could look like the following:
if (condition1isTrue) {
if (condition2isTrue)
bothConditionsAreTrue();
else
firstConditionIsTrue();
}
else if (condition2isTrue)
secondConditionIsTrue();
else
noConditionIsTrue();
Besides being rather cluttered, the statement(s) for 'condition2isTrue' must be written down twice. If 'condition2isTrue' were a lengthy and involved expression, it would be quite unreadable, and the code generated by the compiler might be unnecessarily large.
This can be improved by introducing a new keyword if2. It is similar to if, but takes two conditional statements instead of one, and up to three 'else' statements. One proposal (in pseudo-C syntax) might be:
if2 (condition1isTrue) (condition2isTrue)
bothConditionsAreTrue();
else1
firstConditionIsTrue();
else2
secondConditionIsTrue();
else
noConditionIsTrue();
Pick the syntax which suits your language. The keywords 'else1' and 'else2' are just examples. The new conditional expression should look, nest and behave analogously to the language's built-in 'if' statement.
| #Z80_Assembly | Z80 Assembly | cp b
jr nz,B_False
cp c
jr z,doubleTrue
;B true, C false
;your code goes here
jp done
B_False:
cp c
jr nz,doubleFalse
;B false, C true
;your code goes here
jp done
doubleTrue:
;your code goes here
jp done
doubleFalse:
;your code goes here
jp done
done:
;rest of program |
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
| #SkookumScript | SkookumScript |
1.to 100
[
println(
if idx.mod(15) = 0 ["FizzBuzz"]
idx.mod(3) = 0 ["Fizz"]
idx.mod(5) = 0 ["Buzz"]
else [idx])
]
|
http://rosettacode.org/wiki/Extensible_prime_generator | Extensible prime generator | Task
Write a generator of prime numbers, in order, that will automatically adjust to accommodate the generation of any reasonably high prime.
The routine should demonstrably rely on either:
Being based on an open-ended counter set to count without upper limit other than system or programming language limits. In this case, explain where this counter is in the code.
Being based on a limit that is extended automatically. In this case, choose a small limit that ensures the limit will be passed when generating some of the values to be asked for below.
If other methods of creating an extensible prime generator are used, the algorithm's means of extensibility/lack of limits should be stated.
The routine should be used to:
Show the first twenty primes.
Show the primes between 100 and 150.
Show the number of primes between 7,700 and 8,000.
Show the 10,000th prime.
Show output on this page.
Note: You may reference code already on this site if it is written to be imported/included, then only the code necessary for import and the performance of this task need be shown. (It is also important to leave a forward link on the referenced tasks entry so that later editors know that the code is used for multiple tasks).
Note 2: If a languages in-built prime generator is extensible or is guaranteed to generate primes up to a system limit, (231 or memory overflow for example), then this may be used as long as an explanation of the limits of the prime generator is also given. (Which may include a link to/excerpt from, language documentation).
Note 3:The task is written so it may be useful in solving the task Emirp primes as well as others (depending on its efficiency).
Reference
Prime Numbers. Website with large count of primes.
| #VBA | VBA | Option Explicit
Sub Main()
Dim Primes() As Long, n As Long, temp$
Dim t As Single
t = Timer
n = 133218295 'limit for an Array of Longs with VBA on my computer
Primes = ListPrimes(n)
Debug.Print "For N = " & Format(n, "#,##0") & ", execution time : " & _
Format(Timer - t, "0.000 s") & ", " & _
Format(UBound(Primes) + 1, "#,##0") & " primes numbers."
'First twenty primes
For n = 0 To 19
temp = temp & ", " & Primes(n)
Next
Debug.Print "First twenty primes : "; Mid(temp, 3)
'Primes between 100 and 150
n = 0: temp = vbNullString
Do While Primes(n) < 100
n = n + 1
Loop
Do While Primes(n) < 150
temp = temp & ", " & Primes(n)
n = n + 1
Loop
Debug.Print "Primes between 100 and 150 : " & Mid(temp, 3)
'Number of primes between 7,700 and 8,000
Dim ccount As Long
n = 0
Do While Primes(n) < 7700
n = n + 1
Loop
Do While Primes(n) < 8000
ccount = ccount + 1
n = n + 1
Loop
Debug.Print "Number of primes between 7,700 and 8,000 : " & ccount
'The 10 x Xth prime
n = 1
Do While n <= 100000
n = n * 10
Debug.Print "The " & n & "th prime: "; Format(Primes(n - 1), "#,##0")
Loop
Debug.Print "VBA has a limit in array's dim"
Debug.Print "With my computer, the limit for an array of Long is : 133 218 295"
Debug.Print "The last prime I could find is the : " & _
Format(UBound(Primes), "#,##0") & "th, Value : " & _
Format(Primes(UBound(Primes)), "#,##0")
End Sub
Function ListPrimes(MAX As Long) As Long()
Dim t() As Boolean, L() As Long, c As Long, s As Long, i As Long, j As Long
ReDim t(2 To MAX)
ReDim L(MAX \ 2)
s = Sqr(MAX)
For i = 3 To s Step 2
If t(i) = False Then
For j = i * i To MAX Step i
t(j) = True
Next
End If
Next i
L(0) = 2
For i = 3 To MAX Step 2
If t(i) = False Then
c = c + 1
L(c) = i
End If
Next i
ReDim Preserve L(c)
ListPrimes = L
End Function |
http://rosettacode.org/wiki/Execute_Brain**** | Execute Brain**** | Execute Brain**** is an implementation of Brainf***.
Other implementations of Brainf***.
RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages.
Below are links to each of the versions of RCBF.
An implementation need only properly implement the following instructions:
Command
Description
>
Move the pointer to the right
<
Move the pointer to the left
+
Increment the memory cell under the pointer
-
Decrement the memory cell under the pointer
.
Output the character signified by the cell at the pointer
,
Input a character and store it in the cell at the pointer
[
Jump past the matching ] if the cell under the pointer is 0
]
Jump back to the matching [ if the cell under the pointer is nonzero
Any cell size is allowed, EOF (End-O-File) support is optional, as is whether you have bounded or unbounded memory.
| #COBOL | COBOL | pointer_alpha = 1/0
pointer_numeric = 1/0
tape_behind = ''
tape_ahead = 1/0
tape_pos = 0 # only for debugging
array_behind = 1/0
array_ahead = ''
set_tape_ahead = array_ahead
array_ahead = 1/0
#
shift
comefrom if array_ahead is array_ahead
cdr = 1/0
cdr = array_ahead
shift_tail = cdr
new_cell
comefrom shift if shift_tail is ''
itoa = 0
shift_tail = itoa
car = 1/0
car = array_ahead
array_behind = car array_behind
done = shift_tail
array_ahead = shift_tail
comefrom shift if array_ahead is done
set_pointer_alpha = 1/0
set_pointer_alpha
comefrom if set_pointer_alpha
atoi = set_pointer_alpha
cdr = tape_ahead
set_tape_ahead = set_pointer_alpha cdr
set_pointer_alpha = 1/0
set_tape_ahead = 1/0
set_pointer_vals
comefrom if set_tape_ahead
tape_ahead = set_tape_ahead
car = tape_ahead
pointer_alpha = car
atoi = pointer_alpha
pointer_numeric = atoi
set_tape_ahead = 1/0
pointer_change = 1/0
change_pointer_val
comefrom if pointer_change
car = tape_ahead
cdr = tape_ahead
itoa = pointer_numeric + pointer_change
set_tape_ahead = itoa cdr
pointer_change = 1/0
file = 0 # initialize to something other than undefined so jump from file works when read fails
read_path = argv
error_reading_program
comefrom file if file + 0 is 0
'Error: cannot read Brainfuck program at "' read_path '"'
''
program_loaded
comefrom file if file is file
program_behind = ''
program_ahead = file
run
comefrom program_loaded
opcode = 1/0
opcode_numeric = 1/0
in_buffer = '' # cf0x10 stdin is line-buffered
jumping = 0
moving = 1
comefrom run
comefrom execute if opcode_numeric is 0
''
execute
comefrom run if moving
# can be useful for debugging:
#program_ahead moving ':' jumping '@' tape_pos ':' pointer_numeric
car = program_ahead
atoi = car
opcode_numeric = atoi
opcode = car
opcode = 1/0
#
program_forward
comefrom execute if moving > 0
array_behind = program_behind
array_ahead = 1/0
array_ahead = program_ahead
program_behind = array_behind
program_ahead = array_ahead
forward_jump
comefrom execute if opcode is '['
jump
comefrom forward_jump if pointer_numeric is 0
jumping = jumping + 1
moving = 1
match_brace
comefrom forward_jump if jumping < 0
jumping = jumping + 1
stop_jump
comefrom match_brace if jumping is 0
moving = 1
program_backward
comefrom execute if moving < 0
array_behind = program_ahead
array_ahead = 1/0
array_ahead = program_behind
program_behind = array_ahead
program_ahead = array_behind
backward_jump
comefrom execute if opcode is ']'
jump
comefrom backward_jump if pointer_numeric > 0
jumping = jumping - 1
moving = -1
match_brace
comefrom backward_jump if jumping > 0
jumping = jumping - 1
stop_jump
comefrom match_brace if jumping is 0
moving = 1
op
comefrom execute if opcode
moving = 1
do_op = opcode
comefrom op if jumping
#
forward
comefrom op if do_op is '>'
tape_pos = tape_pos + 1
array_ahead = 1/0
array_behind = tape_behind
array_ahead = tape_ahead
tape_behind = array_behind
set_tape_ahead = array_ahead
backward
comefrom op if do_op is '<'
tape_pos = tape_pos - 1
array_ahead = 1/0
array_behind = tape_ahead
array_ahead = tape_behind
tape_behind = array_ahead
set_tape_ahead = array_behind
increment
comefrom op if do_op is '+'
pointer_change = 1
decrement
comefrom op if do_op is '-'
pointer_change = -1
print
comefrom op if do_op is '.'
pointer_alpha...
read
comefrom op if do_op is ','
#
cdr = 1/0
cdr = in_buffer
car = in_buffer
set_pointer_alpha = car
cdr = in_buffer
in_buffer = cdr
comefrom stdin if stdin + 0 is 0
#
block_for_input
comefrom read if cdr is ''
stdin = ''
in_buffer = stdin
cdr = in_buffer
comefrom stdin if stdin + 0 is 0 |
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.
| #E | E | pragma.syntax("0.9")
pragma.enable("accumulator")
def target := "METHINKS IT IS LIKE A WEASEL"
def alphabet := "ABCDEFGHIJKLMNOPQRSTUVWXYZ "
def C := 100
def RATE := 0.05
def randomCharString() {
return E.toString(alphabet[entropy.nextInt(alphabet.size())])
}
def fitness(string) {
return accum 0 for i => ch in string {
_ + (ch == target[i]).pick(1, 0)
}
}
def mutate(string, rate) {
return accum "" for i => ch in string {
_ + (entropy.nextDouble() < rate).pick(randomCharString(), E.toString(ch))
}
}
def weasel() {
var parent := accum "" for _ in 1..(target.size()) { _ + randomCharString() }
var generation := 0
while (parent != target) {
println(`$generation $parent`)
def copies := accum [] for _ in 1..C { _.with(mutate(parent, RATE)) }
var best := parent
for c in copies {
if (fitness(c) > fitness(best)) {
best := c
}
}
parent := best
generation += 1
}
println(`$generation $parent`)
}
weasel() |
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
| #Logo | Logo | to fib :n [:a 0] [:b 1]
if :n < 1 [output :a]
output (fib :n-1 :b :a+:b)
end |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #REXX | REXX | /*REXX program implements the HQ9+ language. ───────────────────────────────────────*/
arg pgm . /*obtain optional argument.*/
accumulator=0 /*assign default to accum. */
do instructions=1 for length(pgm); ?=substr(pgm, instructions, 1)
select
when ?=='H' then say "Hello, world!" /*text varies on definition*/
when ?=='Q' then do j=1 for sourceline(); say sourceline(j); end /*j*/
when ?== 9 then call 99
when ?=='+' then accumulator=accumulator+1
otherwise say 'invalid HQ9+ instruction:' ?
end /*select*/
end /*instructions*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
99: do j=99 by -1 to 1
say j 'bottle's(j) "of beer the wall,"
say j 'bottle's(j) "of beer."
say 'Take one down, pass it around,'
n=j-1
if n==0 then n='no' /*cheating to use 0. */
say n 'bottle's(j-1) "of beer the wall."
say
end /*j*/
say 'No more bottles of beer on the wall,' /*finally, last verse.*/
say 'no more bottles of beer.'
say 'Go to the store and buy some more,'
say '99 bottles of beer on the wall.'
return
/*──────────────────────────────────────────────────────────────────────────────────────*/
s: if arg(1)==1 then return ''; return "s" /*a simple pluralizer.*/ |
http://rosettacode.org/wiki/Execute_a_Markov_algorithm | Execute a Markov algorithm | Execute a Markov algorithm
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create an interpreter for a Markov Algorithm.
Rules have the syntax:
<ruleset> ::= ((<comment> | <rule>) <newline>+)*
<comment> ::= # {<any character>}
<rule> ::= <pattern> <whitespace> -> <whitespace> [.] <replacement>
<whitespace> ::= (<tab> | <space>) [<whitespace>]
There is one rule per line.
If there is a . (period) present before the <replacement>, then this is a terminating rule in which case the interpreter must halt execution.
A ruleset consists of a sequence of rules, with optional comments.
Rulesets
Use the following tests on entries:
Ruleset 1
# This rules file is extracted from Wikipedia:
# http://en.wikipedia.org/wiki/Markov_Algorithm
A -> apple
B -> bag
S -> shop
T -> the
the shop -> my brother
a never used -> .terminating rule
Sample text of:
I bought a B of As from T S.
Should generate the output:
I bought a bag of apples from my brother.
Ruleset 2
A test of the terminating rule
# Slightly modified from the rules on Wikipedia
A -> apple
B -> bag
S -> .shop
T -> the
the shop -> my brother
a never used -> .terminating rule
Sample text of:
I bought a B of As from T S.
Should generate:
I bought a bag of apples from T shop.
Ruleset 3
This tests for correct substitution order and may trap simple regexp based replacement routines if special regexp characters are not escaped.
# BNF Syntax testing rules
A -> apple
WWWW -> with
Bgage -> ->.*
B -> bag
->.* -> money
W -> WW
S -> .shop
T -> the
the shop -> my brother
a never used -> .terminating rule
Sample text of:
I bought a B of As W my Bgage from T S.
Should generate:
I bought a bag of apples with my money from T shop.
Ruleset 4
This tests for correct order of scanning of rules, and may trap replacement routines that scan in the wrong order. It implements a general unary multiplication engine. (Note that the input expression must be placed within underscores in this implementation.)
### Unary Multiplication Engine, for testing Markov Algorithm implementations
### By Donal Fellows.
# Unary addition engine
_+1 -> _1+
1+1 -> 11+
# Pass for converting from the splitting of multiplication into ordinary
# addition
1! -> !1
,! -> !+
_! -> _
# Unary multiplication by duplicating left side, right side times
1*1 -> x,@y
1x -> xX
X, -> 1,1
X1 -> 1X
_x -> _X
,x -> ,X
y1 -> 1y
y_ -> _
# Next phase of applying
1@1 -> x,@y
1@_ -> @_
,@_ -> !_
++ -> +
# Termination cleanup for addition
_1 -> 1
1+_ -> 1
_+_ ->
Sample text of:
_1111*11111_
should generate the output:
11111111111111111111
Ruleset 5
A simple Turing machine,
implementing a three-state busy beaver.
The tape consists of 0s and 1s, the states are A, B, C and H (for Halt), and the head position is indicated by writing the state letter before the character where the head is.
All parts of the initial tape the machine operates on have to be given in the input.
Besides demonstrating that the Markov algorithm is Turing-complete, it also made me catch a bug in the C++ implementation which wasn't caught by the first four rulesets.
# Turing machine: three-state busy beaver
#
# state A, symbol 0 => write 1, move right, new state B
A0 -> 1B
# state A, symbol 1 => write 1, move left, new state C
0A1 -> C01
1A1 -> C11
# state B, symbol 0 => write 1, move left, new state A
0B0 -> A01
1B0 -> A11
# state B, symbol 1 => write 1, move right, new state B
B1 -> 1B
# state C, symbol 0 => write 1, move left, new state B
0C0 -> B01
1C0 -> B11
# state C, symbol 1 => write 1, move left, halt
0C1 -> H01
1C1 -> H11
This ruleset should turn
000000A000000
into
00011H1111000
| #Racket | Racket |
#lang racket
(struct -> (A B))
(struct ->. (A B))
(define ((Markov-algorithm . rules) initial-string)
(let/cc stop
; rewriting rules
(define (rewrite rule str)
(match rule
[(-> a b) (cond [(replace a str b) => apply-rules]
[else str])]
[(->. a b) (cond [(replace a str b) => stop]
[else str])]))
; the cycle through rewriting rules
(define (apply-rules s) (foldl rewrite s rules))
; the result is a fixed point of rewriting procedure
(fixed-point apply-rules initial-string)))
;; replaces the first substring A to B in a string s
(define (replace A s B)
(and (regexp-match? (regexp-quote A) s)
(regexp-replace (regexp-quote A) s B)))
;; Finds the least fixed-point of a function
(define (fixed-point f x0)
(let loop ([x x0] [fx (f x0)])
(if (equal? x fx) fx (loop fx (f fx)))))
|
http://rosettacode.org/wiki/Execute_a_Markov_algorithm | Execute a Markov algorithm | Execute a Markov algorithm
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create an interpreter for a Markov Algorithm.
Rules have the syntax:
<ruleset> ::= ((<comment> | <rule>) <newline>+)*
<comment> ::= # {<any character>}
<rule> ::= <pattern> <whitespace> -> <whitespace> [.] <replacement>
<whitespace> ::= (<tab> | <space>) [<whitespace>]
There is one rule per line.
If there is a . (period) present before the <replacement>, then this is a terminating rule in which case the interpreter must halt execution.
A ruleset consists of a sequence of rules, with optional comments.
Rulesets
Use the following tests on entries:
Ruleset 1
# This rules file is extracted from Wikipedia:
# http://en.wikipedia.org/wiki/Markov_Algorithm
A -> apple
B -> bag
S -> shop
T -> the
the shop -> my brother
a never used -> .terminating rule
Sample text of:
I bought a B of As from T S.
Should generate the output:
I bought a bag of apples from my brother.
Ruleset 2
A test of the terminating rule
# Slightly modified from the rules on Wikipedia
A -> apple
B -> bag
S -> .shop
T -> the
the shop -> my brother
a never used -> .terminating rule
Sample text of:
I bought a B of As from T S.
Should generate:
I bought a bag of apples from T shop.
Ruleset 3
This tests for correct substitution order and may trap simple regexp based replacement routines if special regexp characters are not escaped.
# BNF Syntax testing rules
A -> apple
WWWW -> with
Bgage -> ->.*
B -> bag
->.* -> money
W -> WW
S -> .shop
T -> the
the shop -> my brother
a never used -> .terminating rule
Sample text of:
I bought a B of As W my Bgage from T S.
Should generate:
I bought a bag of apples with my money from T shop.
Ruleset 4
This tests for correct order of scanning of rules, and may trap replacement routines that scan in the wrong order. It implements a general unary multiplication engine. (Note that the input expression must be placed within underscores in this implementation.)
### Unary Multiplication Engine, for testing Markov Algorithm implementations
### By Donal Fellows.
# Unary addition engine
_+1 -> _1+
1+1 -> 11+
# Pass for converting from the splitting of multiplication into ordinary
# addition
1! -> !1
,! -> !+
_! -> _
# Unary multiplication by duplicating left side, right side times
1*1 -> x,@y
1x -> xX
X, -> 1,1
X1 -> 1X
_x -> _X
,x -> ,X
y1 -> 1y
y_ -> _
# Next phase of applying
1@1 -> x,@y
1@_ -> @_
,@_ -> !_
++ -> +
# Termination cleanup for addition
_1 -> 1
1+_ -> 1
_+_ ->
Sample text of:
_1111*11111_
should generate the output:
11111111111111111111
Ruleset 5
A simple Turing machine,
implementing a three-state busy beaver.
The tape consists of 0s and 1s, the states are A, B, C and H (for Halt), and the head position is indicated by writing the state letter before the character where the head is.
All parts of the initial tape the machine operates on have to be given in the input.
Besides demonstrating that the Markov algorithm is Turing-complete, it also made me catch a bug in the C++ implementation which wasn't caught by the first four rulesets.
# Turing machine: three-state busy beaver
#
# state A, symbol 0 => write 1, move right, new state B
A0 -> 1B
# state A, symbol 1 => write 1, move left, new state C
0A1 -> C01
1A1 -> C11
# state B, symbol 0 => write 1, move left, new state A
0B0 -> A01
1B0 -> A11
# state B, symbol 1 => write 1, move right, new state B
B1 -> 1B
# state C, symbol 0 => write 1, move left, new state B
0C0 -> B01
1C0 -> B11
# state C, symbol 1 => write 1, move left, halt
0C1 -> H01
1C1 -> H11
This ruleset should turn
000000A000000
into
00011H1111000
| #Raku | Raku | grammar Markov {
token TOP {
^ [^^ [<rule> | <comment>] $$ [\n|$]]* $
{ make $<rule>>>.ast }
}
token comment {
<before ^^> '#' \N*
{ make Nil }
}
token ws {
[' '|\t]*
}
rule rule {
<before ^^>$<pattern>=[\N+?] '->'
$<terminal>=[\.]?$<replacement>=[\N*]
{ make {:pattern($<pattern>.Str),
:replacement($<replacement>.Str),
:terminal($<terminal>.Str eq ".")} }
}
}
sub run(:$ruleset, :$start_value, :$verbose?) {
my $value = $start_value;
my @rules = Markov.parse($ruleset).ast.list;
loop {
my $beginning = $value;
for @rules {
my $prev = $value;
$value = $value.subst(.<pattern>, .<replacement>);
say $value if $verbose && $value ne $prev;
return $value if .<terminal>;
last if $value ne $prev;
}
last if $value eq $beginning;
}
return $value;
}
multi sub MAIN(Bool :$verbose?) {
my @rulefiles = dir.grep(/rules.+/).sort;
for @rulefiles -> $rulefile {
my $testfile = $rulefile.subst("rules", "test");
my $start_value = (try slurp($testfile).trim-trailing)
// prompt("please give a start value: ");
my $ruleset = slurp($rulefile);
say $start_value;
say run(:$ruleset, :$start_value, :$verbose);
say '';
}
}
multi sub MAIN(Str $rulefile where *.IO.f, Str $input where *.IO.f, Bool :$verbose?) {
my $ruleset = slurp($rulefile);
my $start_value = slurp($input).trim-trailing;
say "starting with: $start_value";
say run(:$ruleset, :$start_value, :$verbose);
}
multi sub MAIN(Str $rulefile where *.IO.f, *@pieces, Bool :$verbose?) {
my $ruleset = slurp($rulefile);
my $start_value = @pieces.join(" ");
say "starting with: $start_value";
say run(:$ruleset, :$start_value, :$verbose);
} |
http://rosettacode.org/wiki/Exceptions/Catch_an_exception_thrown_in_a_nested_call | Exceptions/Catch an exception thrown in a nested call | Show how to create a user-defined exception and show how to catch an exception raised from several nested calls away.
Create two user-defined exceptions, U0 and U1.
Have function foo call function bar twice.
Have function bar call function baz.
Arrange for function baz to raise, or throw exception U0 on its first call, then exception U1 on its second.
Function foo should catch only exception U0, not U1.
Show/describe what happens when the program is run.
| #TXR | TXR | @(defex u0)
@(defex u1)
@(define baz (x))
@ (cases)
@ (bind x "0")
@ (throw u0 "text0")
@ (or)
@ (bind x "1")
@ (throw u1 "text1")
@ (end)
@(end)
@(define bar (x))
@ (baz x)
@(end)
@(define foo ())
@ (next :list @'("0" "1"))
@ (collect)
@num
@ (try)
@ (bar num)
@ (catch u0 (arg))
@ (output)
caught u0: @arg
@ (end)
@ (end)
@ (end)
@(end)
@(foo) |
http://rosettacode.org/wiki/Exceptions/Catch_an_exception_thrown_in_a_nested_call | Exceptions/Catch an exception thrown in a nested call | Show how to create a user-defined exception and show how to catch an exception raised from several nested calls away.
Create two user-defined exceptions, U0 and U1.
Have function foo call function bar twice.
Have function bar call function baz.
Arrange for function baz to raise, or throw exception U0 on its first call, then exception U1 on its second.
Function foo should catch only exception U0, not U1.
Show/describe what happens when the program is run.
| #Ursala | Ursala | #import std
baz =
~&?(
~&h?(
:/'baz succeeded with this input:',
<'baz threw a user-defined empty string exception','U1'>!%),
<'baz threw a user-defined empty file exception','U0'>!%)
bar = :/'bar received this result from normal termination of baz:'+ baz
#executable&
foo =
guard(
:/'foo received this result from normal termination of bar:'+ bar,
'U0'?=z/~& :/'foo caught an exception with this error message:') |
http://rosettacode.org/wiki/Exceptions/Catch_an_exception_thrown_in_a_nested_call | Exceptions/Catch an exception thrown in a nested call | Show how to create a user-defined exception and show how to catch an exception raised from several nested calls away.
Create two user-defined exceptions, U0 and U1.
Have function foo call function bar twice.
Have function bar call function baz.
Arrange for function baz to raise, or throw exception U0 on its first call, then exception U1 on its second.
Function foo should catch only exception U0, not U1.
Show/describe what happens when the program is run.
| #Visual_Basic_.NET | Visual Basic .NET | Class U0
Inherits Exception
End Class
Class U1
Inherits Exception
End Class
Module Program
Sub Main()
Foo()
End Sub
Sub Foo()
Try
Bar()
Bar()
Catch ex As U0
Console.WriteLine(ex.GetType.Name & " caught.")
End Try
End Sub
Sub Bar()
Baz()
End Sub
Sub Baz()
' Static local variable is persisted between calls of the method and is initialized only once.
Static firstCall As Boolean = True
If firstCall Then
firstCall = False
Throw New U0()
Else
Throw New U1()
End If
End Sub
End Module |
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
| #Nemerle | Nemerle | // define a new exception
class MyException : Exception
{
...
}
// throw an exception
Foo() : void
{
throw MyException();
}
// catching exceptions
try {
Foo();
}
catch { // catch block uses pattern matching syntax
|e is MyException => ... // handle exception
|_ => throw e // rethrow unhandled exception
}
finally {
... // code executes whether or not exception was thrown
} |
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
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols nobinary
-- =============================================================================
class RExceptions public
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method test() public signals RExceptions.TakeException
if (1 == 1) then signal RExceptions.TakeException()
return
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method main(args = String[]) public static
do
RExceptions().test()
catch ex = Exception
say ex.toString()
end
return;
-- =============================================================================
class RExceptions.TakeException public extends Exception
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method TakeException() public
super('I resent that!')
return
|
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
| #Joy | Joy | "ls" system. |
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
| #Julia | Julia | run(`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
| #K | K | \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
| #bash | bash | factorial()
{
if [ $1 -le 1 ]
then
echo 1
else
result=$(factorial $[$1-1])
echo $((result*$1))
fi
}
|
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
| #Phix | Phix | with javascript_semantics
function powir(atom b, integer i)
atom res = 1
if i<0 then {b,i} = {1/b,abs(i)} end if
while i do
if and_bits(i,1) then res *= b end if
b *= b
i = floor(i/2)
end while
return res
end function
?powir(-3,-5)
?power(-3,-5)
|
http://rosettacode.org/wiki/Extend_your_language | Extend your language | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. by using macros), other languages go much further. Most notably in the Forth and Lisp families, programming per se is done by extending the language without any formal distinction between built-in and user-defined elements.
If your language supports it, show how to introduce a new flow control mechanism. A practical and useful example is a four-way branch:
Occasionally, code must be written that depends on two conditions, resulting in up to four branches (depending on whether both, only the first, only the second, or none of the conditions are "true"). In a C-like language this could look like the following:
if (condition1isTrue) {
if (condition2isTrue)
bothConditionsAreTrue();
else
firstConditionIsTrue();
}
else if (condition2isTrue)
secondConditionIsTrue();
else
noConditionIsTrue();
Besides being rather cluttered, the statement(s) for 'condition2isTrue' must be written down twice. If 'condition2isTrue' were a lengthy and involved expression, it would be quite unreadable, and the code generated by the compiler might be unnecessarily large.
This can be improved by introducing a new keyword if2. It is similar to if, but takes two conditional statements instead of one, and up to three 'else' statements. One proposal (in pseudo-C syntax) might be:
if2 (condition1isTrue) (condition2isTrue)
bothConditionsAreTrue();
else1
firstConditionIsTrue();
else2
secondConditionIsTrue();
else
noConditionIsTrue();
Pick the syntax which suits your language. The keywords 'else1' and 'else2' are just examples. The new conditional expression should look, nest and behave analogously to the language's built-in 'if' statement.
| #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 DEF FN i()=((NOT (a OR b))+2*(a AND NOT b)+3*(b AND NOT a)+4*(a AND b)): REM the function can be placed anywhere in the program, but it gets executed faster if it's at the top
20 FOR x=1 TO 20
30 LET a=(x/2)=INT (x/2): REM comparison 1
40 LET b=(x/3)=INT (x/3): REM comparison 2
50 GO TO 50+10*FN i(): REM cases
60 PRINT x;" is not divisible by 2 or 3": GO TO 100
70 PRINT x;" is divisible by 2": GO TO 100
80 PRINT x;" is divisible by 3": GO TO 100
90 PRINT x;" is divisible by 2 and 3"
100 NEXT x |
http://rosettacode.org/wiki/FizzBuzz | FizzBuzz | Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
| #Slate | Slate | n@(Integer traits) fizzbuzz
[
output ::= ((n \\ 3) isZero ifTrue: ['Fizz'] ifFalse: ['']) ; ((n \\ 5) isZero ifTrue: ['Buzz'] ifFalse: ['']).
output isEmpty ifTrue: [n printString] ifFalse: [output]
].
1 to: 100 do: [| :i | inform: i fizzbuzz] |
http://rosettacode.org/wiki/Extensible_prime_generator | Extensible prime generator | Task
Write a generator of prime numbers, in order, that will automatically adjust to accommodate the generation of any reasonably high prime.
The routine should demonstrably rely on either:
Being based on an open-ended counter set to count without upper limit other than system or programming language limits. In this case, explain where this counter is in the code.
Being based on a limit that is extended automatically. In this case, choose a small limit that ensures the limit will be passed when generating some of the values to be asked for below.
If other methods of creating an extensible prime generator are used, the algorithm's means of extensibility/lack of limits should be stated.
The routine should be used to:
Show the first twenty primes.
Show the primes between 100 and 150.
Show the number of primes between 7,700 and 8,000.
Show the 10,000th prime.
Show output on this page.
Note: You may reference code already on this site if it is written to be imported/included, then only the code necessary for import and the performance of this task need be shown. (It is also important to leave a forward link on the referenced tasks entry so that later editors know that the code is used for multiple tasks).
Note 2: If a languages in-built prime generator is extensible or is guaranteed to generate primes up to a system limit, (231 or memory overflow for example), then this may be used as long as an explanation of the limits of the prime generator is also given. (Which may include a link to/excerpt from, language documentation).
Note 3:The task is written so it may be useful in solving the task Emirp primes as well as others (depending on its efficiency).
Reference
Prime Numbers. Website with large count of primes.
| #Wren | Wren | import "/fmt" for Fmt
var primeSieve = Fn.new { |limit|
if (limit < 2) return []
var c = [false] * (limit + 1) // composite = true
c[0] = true
c[1] = true
// no need to process the even numbers > 2
var k = 9
while (k <= limit) {
c[k] = true
k = k + 6
}
k = 25
while (k <= limit) {
c[k] = true
k = k + 10
}
k = 49
while (k <= limit) {
c[k] = true
k = k + 14
}
var p = 11
var p2 = 121
var inc = [2,4,2,4,6,2,6,4,2,4,6,6,2,6,4,2,6,4,6,8,4,2,4,2,
4,8,6,4,6,2,4,6,2,6,6,4,2,4,6,2,6,4,2,4,2,10,2,10]
var w = 0
while (p2 <= limit) {
var i = p2
while (i <= limit) {
c[i] = true
i = i + 2*p
}
var ok = true
while (ok) {
p = p + inc[w]
w = (w + 1) % 48
ok = c[p]
}
p2 = p * p
}
var primes = [2]
var i = 3
while (i <= limit) {
if (!c[i]) primes.add(i)
i = i + 2
}
return primes
}
var primes = primeSieve.call(1e8 * 2)
System.print("The first 20 primes are: ")
System.print(primes.take(20).toList)
System.print("\nThe primes between 100 and 150 are:")
System.print(primes.where { |p| p > 100 && p < 150 }.toList)
System.write("\nThe number of primes between 7,700 and 8,000 is: ")
Fmt.print("$,d", primes.count{ |p| p > 7700 && p < 8000 })
Fmt.print("\nThe 10,000th prime is: $,d", primes[9999])
Fmt.print("\nThe 100,000th prime is: $,d", primes[99999])
Fmt.print("\nThe 1,000,000th prime is: $,d", primes[999999]) |
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.
| #Comefrom0x10 | Comefrom0x10 | pointer_alpha = 1/0
pointer_numeric = 1/0
tape_behind = ''
tape_ahead = 1/0
tape_pos = 0 # only for debugging
array_behind = 1/0
array_ahead = ''
set_tape_ahead = array_ahead
array_ahead = 1/0
#
shift
comefrom if array_ahead is array_ahead
cdr = 1/0
cdr = array_ahead
shift_tail = cdr
new_cell
comefrom shift if shift_tail is ''
itoa = 0
shift_tail = itoa
car = 1/0
car = array_ahead
array_behind = car array_behind
done = shift_tail
array_ahead = shift_tail
comefrom shift if array_ahead is done
set_pointer_alpha = 1/0
set_pointer_alpha
comefrom if set_pointer_alpha
atoi = set_pointer_alpha
cdr = tape_ahead
set_tape_ahead = set_pointer_alpha cdr
set_pointer_alpha = 1/0
set_tape_ahead = 1/0
set_pointer_vals
comefrom if set_tape_ahead
tape_ahead = set_tape_ahead
car = tape_ahead
pointer_alpha = car
atoi = pointer_alpha
pointer_numeric = atoi
set_tape_ahead = 1/0
pointer_change = 1/0
change_pointer_val
comefrom if pointer_change
car = tape_ahead
cdr = tape_ahead
itoa = pointer_numeric + pointer_change
set_tape_ahead = itoa cdr
pointer_change = 1/0
file = 0 # initialize to something other than undefined so jump from file works when read fails
read_path = argv
error_reading_program
comefrom file if file + 0 is 0
'Error: cannot read Brainfuck program at "' read_path '"'
''
program_loaded
comefrom file if file is file
program_behind = ''
program_ahead = file
run
comefrom program_loaded
opcode = 1/0
opcode_numeric = 1/0
in_buffer = '' # cf0x10 stdin is line-buffered
jumping = 0
moving = 1
comefrom run
comefrom execute if opcode_numeric is 0
''
execute
comefrom run if moving
# can be useful for debugging:
#program_ahead moving ':' jumping '@' tape_pos ':' pointer_numeric
car = program_ahead
atoi = car
opcode_numeric = atoi
opcode = car
opcode = 1/0
#
program_forward
comefrom execute if moving > 0
array_behind = program_behind
array_ahead = 1/0
array_ahead = program_ahead
program_behind = array_behind
program_ahead = array_ahead
forward_jump
comefrom execute if opcode is '['
jump
comefrom forward_jump if pointer_numeric is 0
jumping = jumping + 1
moving = 1
match_brace
comefrom forward_jump if jumping < 0
jumping = jumping + 1
stop_jump
comefrom match_brace if jumping is 0
moving = 1
program_backward
comefrom execute if moving < 0
array_behind = program_ahead
array_ahead = 1/0
array_ahead = program_behind
program_behind = array_ahead
program_ahead = array_behind
backward_jump
comefrom execute if opcode is ']'
jump
comefrom backward_jump if pointer_numeric > 0
jumping = jumping - 1
moving = -1
match_brace
comefrom backward_jump if jumping > 0
jumping = jumping - 1
stop_jump
comefrom match_brace if jumping is 0
moving = 1
op
comefrom execute if opcode
moving = 1
do_op = opcode
comefrom op if jumping
#
forward
comefrom op if do_op is '>'
tape_pos = tape_pos + 1
array_ahead = 1/0
array_behind = tape_behind
array_ahead = tape_ahead
tape_behind = array_behind
set_tape_ahead = array_ahead
backward
comefrom op if do_op is '<'
tape_pos = tape_pos - 1
array_ahead = 1/0
array_behind = tape_ahead
array_ahead = tape_behind
tape_behind = array_ahead
set_tape_ahead = array_behind
increment
comefrom op if do_op is '+'
pointer_change = 1
decrement
comefrom op if do_op is '-'
pointer_change = -1
print
comefrom op if do_op is '.'
pointer_alpha...
read
comefrom op if do_op is ','
#
cdr = 1/0
cdr = in_buffer
car = in_buffer
set_pointer_alpha = car
cdr = in_buffer
in_buffer = cdr
comefrom stdin if stdin + 0 is 0
#
block_for_input
comefrom read if cdr is ''
stdin = ''
in_buffer = stdin
cdr = in_buffer
comefrom stdin if stdin + 0 is 0 |
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.
| #EchoLisp | EchoLisp |
(require 'sequences)
(define ALPHABET (list->vector ["A" .. "Z"] ))
(vector-push ALPHABET " ")
(define (fitness source target) ;; score >=0, best is 0
(for/sum [(s source)(t target)]
(if (= s t) 0 1)))
(define (mutate source rate)
(for/string [(s source)]
(if (< (random) rate) [ALPHABET (random 27)] s)))
(define (select parent target rate copies (copy) (score))
(define best (fitness parent target))
(define selected parent)
(for [(i copies)]
(set! copy (mutate parent rate))
(set! score (fitness copy target))
(when (< score best)
(set! selected copy)
(set! best score)))
selected )
(define MUTATION_RATE 0.05) ;; 5% chances to change
(define COPIES 100)
(define TARGET "METHINKS IT IS LIKE A WEASEL")
(define (task (rate MUTATION_RATE) (copies COPIES) (target TARGET) (score))
(define parent ;; random source
(for/string
[(i (string-length target))] [ALPHABET (random 27)]))
(for [(i (in-naturals))]
(set! score (fitness parent target))
(writeln i parent 'score score)
#:break (zero? score)
(set! parent (select parent target rate copies))
))
|
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
| #LOLCODE | LOLCODE |
HAI 1.2
HOW DUZ I fibonacci YR N
EITHER OF BOTH SAEM N AN 1 AN BOTH SAEM N AN 0
O RLY?
YA RLY, FOUND YR 1
NO WAI
I HAS A N1
I HAS A N2
N1 R DIFF OF N AN 1
N2 R DIFF OF N AN 2
N1 R fibonacci N1
N2 R fibonacci N2
FOUND YR SUM OF N1 AN N2
OIC
IF U SAY SO
KTHXBYE
|
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #Ring | Ring |
# Project : Execute HQ9
bottle("hq9+HqQ+Qq")
func bottle(code)
accumulator = 0
for i = 1 to len(code)
switch code[i]
on "h"
see "Hello, world!" + nl
on "H"
see "hello, world!" + nl
on "q"
see code + nl
on "Q"
see code + nl
on "9"
bottles = 99
while bottles > 0
see "" + bottles + " bottles of beer on the wall, "
see "" + bottles + " bottles of beer," + nl
bottles = bottles - 1
see "take one down, pass it around, "
see "" + bottles + " bottles of beer on the wall." + nl
end
on "+"
accumulator = accumulator + 1
off
next
|
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #Ruby | Ruby | use std::env;
// HQ9+ requires that '+' increments an accumulator, but it's inaccessible (and thus, unused).
#[allow(unused_variables)]
fn execute(code: &str) {
let mut accumulator = 0;
for c in code.chars() {
match c {
'Q' => println!("{}", code),
'H' => println!("Hello, World!"),
'9' => {
for n in (1..100).rev() {
println!("{} bottles of beer on the wall", n);
println!("{} bottles of beer", n);
println!("Take one down, pass it around");
if (n - 1) > 1 {
println!("{} bottles of beer on the wall\n", n - 1);
} else {
println!("1 bottle of beer on the wall\n");
}
}
}
'+' => accumulator += 1,
_ => panic!("Invalid character '{}' found in source.", c),
}
}
}
fn main() {
execute(&env::args().nth(1).unwrap());
} |
http://rosettacode.org/wiki/Execute_a_Markov_algorithm | Execute a Markov algorithm | Execute a Markov algorithm
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create an interpreter for a Markov Algorithm.
Rules have the syntax:
<ruleset> ::= ((<comment> | <rule>) <newline>+)*
<comment> ::= # {<any character>}
<rule> ::= <pattern> <whitespace> -> <whitespace> [.] <replacement>
<whitespace> ::= (<tab> | <space>) [<whitespace>]
There is one rule per line.
If there is a . (period) present before the <replacement>, then this is a terminating rule in which case the interpreter must halt execution.
A ruleset consists of a sequence of rules, with optional comments.
Rulesets
Use the following tests on entries:
Ruleset 1
# This rules file is extracted from Wikipedia:
# http://en.wikipedia.org/wiki/Markov_Algorithm
A -> apple
B -> bag
S -> shop
T -> the
the shop -> my brother
a never used -> .terminating rule
Sample text of:
I bought a B of As from T S.
Should generate the output:
I bought a bag of apples from my brother.
Ruleset 2
A test of the terminating rule
# Slightly modified from the rules on Wikipedia
A -> apple
B -> bag
S -> .shop
T -> the
the shop -> my brother
a never used -> .terminating rule
Sample text of:
I bought a B of As from T S.
Should generate:
I bought a bag of apples from T shop.
Ruleset 3
This tests for correct substitution order and may trap simple regexp based replacement routines if special regexp characters are not escaped.
# BNF Syntax testing rules
A -> apple
WWWW -> with
Bgage -> ->.*
B -> bag
->.* -> money
W -> WW
S -> .shop
T -> the
the shop -> my brother
a never used -> .terminating rule
Sample text of:
I bought a B of As W my Bgage from T S.
Should generate:
I bought a bag of apples with my money from T shop.
Ruleset 4
This tests for correct order of scanning of rules, and may trap replacement routines that scan in the wrong order. It implements a general unary multiplication engine. (Note that the input expression must be placed within underscores in this implementation.)
### Unary Multiplication Engine, for testing Markov Algorithm implementations
### By Donal Fellows.
# Unary addition engine
_+1 -> _1+
1+1 -> 11+
# Pass for converting from the splitting of multiplication into ordinary
# addition
1! -> !1
,! -> !+
_! -> _
# Unary multiplication by duplicating left side, right side times
1*1 -> x,@y
1x -> xX
X, -> 1,1
X1 -> 1X
_x -> _X
,x -> ,X
y1 -> 1y
y_ -> _
# Next phase of applying
1@1 -> x,@y
1@_ -> @_
,@_ -> !_
++ -> +
# Termination cleanup for addition
_1 -> 1
1+_ -> 1
_+_ ->
Sample text of:
_1111*11111_
should generate the output:
11111111111111111111
Ruleset 5
A simple Turing machine,
implementing a three-state busy beaver.
The tape consists of 0s and 1s, the states are A, B, C and H (for Halt), and the head position is indicated by writing the state letter before the character where the head is.
All parts of the initial tape the machine operates on have to be given in the input.
Besides demonstrating that the Markov algorithm is Turing-complete, it also made me catch a bug in the C++ implementation which wasn't caught by the first four rulesets.
# Turing machine: three-state busy beaver
#
# state A, symbol 0 => write 1, move right, new state B
A0 -> 1B
# state A, symbol 1 => write 1, move left, new state C
0A1 -> C01
1A1 -> C11
# state B, symbol 0 => write 1, move left, new state A
0B0 -> A01
1B0 -> A11
# state B, symbol 1 => write 1, move right, new state B
B1 -> 1B
# state C, symbol 0 => write 1, move left, new state B
0C0 -> B01
1C0 -> B11
# state C, symbol 1 => write 1, move left, halt
0C1 -> H01
1C1 -> H11
This ruleset should turn
000000A000000
into
00011H1111000
| #REXX | REXX | /*REXX program executes a Markov algorithm(s) against specified entries. */
parse arg low high . /*allows which ruleset to process. */
if low=='' | low=="," then low=1 /*Not specified? Then use the default.*/
if high=='' | high=="," then high=6 /* " " " " " " */
tellE= low<0; tellR= high<0 /*flags: used to display file contents.*/
call readEntry
do j=abs(low) to abs(high) /*process each of these rulesets. */
call readRules j /*read a particular ruleset. */
call execRules j /*execute " " " */
say 'result for ruleset' j "───►" !.j
end /*j*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
execRules: parse arg q .; if tellE | tellR then say /*show a blank line?*/
do f=1
do k=1 while @.k\==''; if left(@.k, 1)=='#' | @.k='' then iterate
parse var @.k a ' ->' b /*obtain the A & B parts from rule.*/
a=strip(a); b=strip(b) /*strip leading and/or trailing blanks.*/
fullstop= left(b, 1)==. /*is this a "fullstop" rule? 1≡yes */
if fullstop then b=substr(b, 2) /*purify the B part of the rule. */
old=!.q /*remember the value before the change.*/
!.q=changestr(a, !.q, b) /*implement the ruleset change. */
if fullstop then if old\==!.q then return /*should we stop? */
if old\==!.q then iterate f /*Has Entry changed? Then start over.*/
end /*k*/
return
end /*f*/
return
/*──────────────────────────────────────────────────────────────────────────────────────*/
readEntry: eFID= 'MARKOV.ENT'; if tellE then say /*show a blank line?*/
!.= /*placeholder for all the test entries.*/
do e=1 while lines(eFID)\==0 /*read the input file until End-Of-File*/
!.e=linein(eFID); if tellE then say 'test entry' e "───►" !.e
end /*e*/ /* [↑] read and maybe echo the entry. */
return
/*──────────────────────────────────────────────────────────────────────────────────────*/
readRules: parse arg ? .; rFID= 'MARKOV_R.'?; if tellR then say /*show a blank line?*/
@.= /*placeholder for all the Markov rules.*/
do r=1 while lines(rFID)\==0 /*read the input file until End-Of-File*/
@.r=linein(rFID); if tellR then say 'ruleSet' ?"."left(r,4) '───►' @.r
end /*r*/ /* [↑] read and maybe echo the rule. */
return |
http://rosettacode.org/wiki/Exceptions/Catch_an_exception_thrown_in_a_nested_call | Exceptions/Catch an exception thrown in a nested call | Show how to create a user-defined exception and show how to catch an exception raised from several nested calls away.
Create two user-defined exceptions, U0 and U1.
Have function foo call function bar twice.
Have function bar call function baz.
Arrange for function baz to raise, or throw exception U0 on its first call, then exception U1 on its second.
Function foo should catch only exception U0, not U1.
Show/describe what happens when the program is run.
| #Wren | Wren | var U0 = "U0"
var U1 = "U1"
var bazCalled = 0
var baz = Fn.new {
bazCalled = bazCalled + 1
Fiber.abort( (bazCalled == 1) ? U0 : U1 )
}
var bar = Fn.new {
baz.call()
}
var foo = Fn.new {
for (i in 1..2) {
var f = Fiber.new { bar.call() }
f.try()
var err = f.error
if (err == U0) {
System.print("Caught exception %(err)")
} else if (err == U1) {
Fiber.abort("Uncaught exception %(err) rethrown") // re-throw
}
}
}
foo.call() |
http://rosettacode.org/wiki/Exceptions/Catch_an_exception_thrown_in_a_nested_call | Exceptions/Catch an exception thrown in a nested call | Show how to create a user-defined exception and show how to catch an exception raised from several nested calls away.
Create two user-defined exceptions, U0 and U1.
Have function foo call function bar twice.
Have function bar call function baz.
Arrange for function baz to raise, or throw exception U0 on its first call, then exception U1 on its second.
Function foo should catch only exception U0, not U1.
Show/describe what happens when the program is run.
| #zkl | zkl | class U0(Exception.Exception){fcn init{Exception.init("U0")}}
class U1(Exception.Exception){fcn init{Exception.init("U1")}}
fcn foo{try{bar(U0)}catch(U0){} bar(U1)}
fcn bar(e){baz(e)}
fcn baz(e){throw(e)}
foo() |
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
| #Nim | Nim | type SillyError = object of Exception |
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
| #Objective-C | Objective-C | @interface MyException : NSException {
//Put specific info in here
}
@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
| #Kotlin | Kotlin | // version 1.0.6
import java.util.Scanner
fun main(args: Array<String>) {
val proc = Runtime.getRuntime().exec("cmd /C dir") // testing on Windows 10
Scanner(proc.inputStream).use {
while (it.hasNextLine()) println(it.nextLine())
}
} |
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
| #Lang5 | Lang5 | 'ls system |
http://rosettacode.org/wiki/Factorial | Factorial | Definitions
The factorial of 0 (zero) is defined as being 1 (unity).
The Factorial Function of a positive integer, n, is defined as the product of the sequence:
n, n-1, n-2, ... 1
Task
Write a function to return the factorial of a number.
Solutions can be iterative or recursive.
Support for trapping negative n errors is optional.
Related task
Primorial numbers
| #BASIC | BASIC | FUNCTION factorial (n AS Integer) AS Integer
DIM f AS Integer, i AS Integer
f = 1
FOR i = 2 TO n
f = f*i
NEXT i
factorial = f
END FUNCTION |
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
| #PicoLisp | PicoLisp | (de ** (X N) # N th power of X
(if (ge0 N)
(let Y 1
(loop
(when (bit? 1 N)
(setq Y (* Y X)) )
(T (=0 (setq N (>> 1 N)))
Y )
(setq X (* X X)) ) )
0 ) ) |
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
| #PL.2FI | PL/I | declare exp generic
(iexp when (fixed, fixed),
fexp when (float, fixed) );
iexp: procedure (m, n) returns (fixed binary (31));
declare (m, n) fixed binary (31) nonassignable;
declare exp fixed binary (31) initial (m), i fixed binary;
if m = 0 & n = 0 then signal error;
if n = 0 then return (1);
do i = 2 to n;
exp = exp * m;
end;
return (exp);
end iexp;
fexp: procedure (a, n) returns (float (15));
declare (a float, n fixed binary (31)) nonassignable;
declare exp float initial (a), i fixed binary;
if a = 0 & n = 0 then signal error;
if n = 0 then return (1);
do i = 2 to n;
exp = exp * a;
end;
return (exp);
end fexp; |
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
| #Small | Small | Integer extend [
fizzbuzz [
| fb |
fb := '%<Fizz|>1%<Buzz|>2' % {
self \\ 3 == 0. self \\ 5 == 0 }.
^fb isEmpty ifTrue: [ self ] ifFalse: [ fb ]
]
]
1 to: 100 do: [ :i | i fizzbuzz displayNl ] |
http://rosettacode.org/wiki/Extensible_prime_generator | Extensible prime generator | Task
Write a generator of prime numbers, in order, that will automatically adjust to accommodate the generation of any reasonably high prime.
The routine should demonstrably rely on either:
Being based on an open-ended counter set to count without upper limit other than system or programming language limits. In this case, explain where this counter is in the code.
Being based on a limit that is extended automatically. In this case, choose a small limit that ensures the limit will be passed when generating some of the values to be asked for below.
If other methods of creating an extensible prime generator are used, the algorithm's means of extensibility/lack of limits should be stated.
The routine should be used to:
Show the first twenty primes.
Show the primes between 100 and 150.
Show the number of primes between 7,700 and 8,000.
Show the 10,000th prime.
Show output on this page.
Note: You may reference code already on this site if it is written to be imported/included, then only the code necessary for import and the performance of this task need be shown. (It is also important to leave a forward link on the referenced tasks entry so that later editors know that the code is used for multiple tasks).
Note 2: If a languages in-built prime generator is extensible or is guaranteed to generate primes up to a system limit, (231 or memory overflow for example), then this may be used as long as an explanation of the limits of the prime generator is also given. (Which may include a link to/excerpt from, language documentation).
Note 3:The task is written so it may be useful in solving the task Emirp primes as well as others (depending on its efficiency).
Reference
Prime Numbers. Website with large count of primes.
| #Zig | Zig |
const std = @import("std");
const builtin = std.builtin;
const heap = std.heap;
const mem = std.mem;
const meta = std.meta;
fn assertInt(comptime T: type) builtin.TypeInfo.Int {
if (@typeInfo(T) != .Int)
@compileError("data type must be an integer.");
const int = @typeInfo(T).Int;
if (int.is_signed == true or int.bits % 2 == 1 or int.bits < 4)
@compileError("type must be an unsigned integer with even bit size (of at least 4 bits).");
return int;
}
fn sqrtType(comptime T: type) type {
const t = assertInt(T);
return meta.Int(.unsigned, t.bits / 2);
}
// given an upper bound, max, return the most restrictive sieving data type.
pub fn autoSieveType(comptime max: u64) type {
if (max == 0)
@compileError("The maximum sieving size must be non-zero.");
var bit_len = 64 - @clz(u64, max);
if (max & (max - 1) == 0) // power of two
bit_len -= 1;
if (bit_len % 2 == 1)
bit_len += 1;
if (bit_len < 4)
bit_len = 4;
return meta.Int(.unsigned, bit_len);
}
test "type meta functions" {
const expect = std.testing.expect;
expect(sqrtType(u20) == u10);
expect(autoSieveType(8000) == u14);
expect(autoSieveType(9000) == u14);
expect(autoSieveType(16384) == u14);
expect(autoSieveType(16385) == u16);
expect(autoSieveType(32768) == u16);
expect(autoSieveType(1000) == u10);
expect(autoSieveType(10) == u4);
expect(autoSieveType(4) == u4);
expect(autoSieveType(std.math.maxInt(u32)) == u32);
}
const wheel2357 = [48]u8{
10, 2, 4, 2, 4, 6, 2, 6,
4, 2, 4, 6, 6, 2, 6, 4,
2, 6, 4, 6, 8, 4, 2, 4,
2, 4, 8, 6, 4, 6, 2, 4,
6, 2, 6, 6, 4, 2, 4, 6,
2, 6, 4, 2, 4, 2, 10, 2,
};
fn Wheel2357Multiple(comptime Int: type) type {
_ = assertInt(Int);
return struct {
multiple: Int,
base_prime: Int,
offset: u6,
fn less(self: Wheel2357Multiple(Int), other: Wheel2357Multiple(Int)) bool {
return self.multiple < other.multiple;
}
};
}
pub fn PrimeGen(comptime Int: type) type {
_ = assertInt(Int);
return struct {
const Self = @This();
initial_primes: u16,
offset: u6,
candidate: Int,
multiples: std.PriorityQueue(Wheel2357Multiple(Int)),
allocator: *mem.Allocator,
count: u32,
pub fn init(alloc: *mem.Allocator) Self {
return Self{
.initial_primes = 0xAC, // primes 2, 3, 5, 7 in a bitmask
.offset = 0,
.candidate = 1,
.count = 0,
.allocator = alloc,
.multiples = std.PriorityQueue(Wheel2357Multiple(Int)).init(alloc, Wheel2357Multiple(Int).less),
};
}
pub fn deinit(self: *PrimeGen(Int)) void {
self.multiples.deinit();
}
pub fn next(self: *PrimeGen(Int)) !?Int {
if (self.initial_primes != 0) { // use the bitmask up first
const p = @as(Int, @ctz(u16, self.initial_primes));
self.initial_primes &= self.initial_primes - 1;
self.count += 1;
return p;
} else {
while (true) {
// advance to the next prime candidate.
if (@addWithOverflow(Int, self.candidate, wheel2357[self.offset], &self.candidate))
return null;
self.offset = (self.offset + 1) % @as(u6, wheel2357.len);
// See if the composite number on top of the heap matches
// the candidate.
//
var top = self.multiples.peek();
if (top == null or self.candidate < top.?.multiple) {
// prime found, add the square and it's position on the wheel
// to the heap.
//
if (self.candidate <= std.math.maxInt(sqrtType(Int)))
try self.multiples.add(Wheel2357Multiple(Int){
.multiple = self.candidate * self.candidate,
.base_prime = self.candidate,
.offset = self.offset,
});
self.count += 1;
return self.candidate;
} else {
while (true) {
// advance the top of heap to the next prime multiple
// that is not a multiple of 2, 3, 5, 7.
//
var mult = self.multiples.remove();
// If the multiple becomes too big (greater than the the maximum
// sieve size), then there's no reason to add it back to the queue.
//
var tmp: Int = undefined;
if (!@mulWithOverflow(Int, mult.base_prime, wheel2357[mult.offset], &tmp) and
!@addWithOverflow(Int, tmp, mult.multiple, &mult.multiple))
{
mult.offset = (mult.offset + 1) % @as(u6, wheel2357.len);
try self.multiples.add(mult);
}
top = self.multiples.peek();
if (top == null or self.candidate != top.?.multiple)
break;
}
}
}
}
}
};
}
|
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.
| #Common_Lisp | Common Lisp |
program Execute_Brain;
{$APPTYPE CONSOLE}
uses
Winapi.Windows,
System.SysUtils;
const
DataSize = 1024; // Size of Data segment
MaxNest = 1000; // Maximum nesting depth of []
function Readkey: Char;
var
InputRec: TInputRecord;
NumRead: Cardinal;
KeyMode: DWORD;
StdIn: THandle;
begin
StdIn := GetStdHandle(STD_INPUT_HANDLE);
GetConsoleMode(StdIn, KeyMode);
SetConsoleMode(StdIn, 0);
repeat
ReadConsoleInput(StdIn, InputRec, 1, NumRead);
if (InputRec.EventType and KEY_EVENT <> 0) and InputRec.Event.KeyEvent.bKeyDown then
begin
if InputRec.Event.KeyEvent.AsciiChar <> #0 then
begin
Result := InputRec.Event.KeyEvent.UnicodeChar;
Break;
end;
end;
until FALSE;
SetConsoleMode(StdIn, KeyMode);
end;
procedure ExecuteBF(Source: string);
var
Dp: pByte; // Used as the Data Pointer
DataSeg: Pointer; // Start of the DataSegment (Cell 0)
Ip: pChar; // Used as instruction Pointer
LastIp: Pointer; // Last adr of code.
JmpStack: array[0..MaxNest - 1] of pChar; // Stack to Keep track of active "[" locations
JmpPnt: Integer; // Stack pointer ^^
JmpCnt: Word; // Used to count brackets when skipping forward.
begin
// Set up then data segment
getmem(DataSeg, dataSize);
Dp := DataSeg;
// fillbyte(dp^,dataSize,0);
FillChar(Dp^, DataSize, 0);
// Set up the JmpStack
JmpPnt := -1;
// Set up Instruction Pointer
Ip := @Source[1];
LastIp := @Source[length(Source)];
if Ip = nil then
exit;
// Main Execution loop
repeat { until Ip > LastIp }
case Ip^ of
'<':
dec(Dp);
'>':
inc(Dp);
'+':
inc(Dp^);
'-':
dec(Dp^);
'.':
write(chr(Dp^));
',':
Dp^ := ord(ReadKey);
'[':
if Dp^ = 0 then
begin
// skip forward until matching bracket;
JmpCnt := 1;
while (JmpCnt > 0) and (Ip <= LastIp) do
begin
inc(Ip);
case Ip^ of
'[':
inc(JmpCnt);
']':
dec(JmpCnt);
#0:
begin
Writeln('Error brackets don''t match');
halt;
end;
end;
end;
end
else
begin
// Add location to Jump stack
inc(JmpPnt);
JmpStack[JmpPnt] := Ip;
end;
']':
if Dp^ > 0 then
// Jump Back to matching [
Ip := JmpStack[JmpPnt]
else // Remove Jump from stack
dec(JmpPnt);
end;
inc(Ip);
until Ip > LastIp;
freemem(DataSeg, dataSize);
end;
const
HelloWorldWiki = '++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>' +
'---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.';
pressESCtoCont = '>[-]+++++++[<++++++++++>-]<->>[-]+++++++[<+++++++++++' +
'+>-]<->>[-]++++[<++++++++>-]+>[-]++++++++++[<++++++++' +
'++>-]>[-]++++++++[<++++++++++++++>-]<.++.+<.>..<<.<<.' +
'-->.<.>>.>>+.-----.<<.[<<+>>-]<<.>>>>.-.++++++.<++++.' +
'+++++.>+.<<<<++.>+[>+<--]>++++...';
waitForEsc = '[-]>[-]++++[<+++++++>-]<->[-]>+[[-]<<[>+>+<<-]' + '>>[<' +
'<+>>-],<[->-<]>]';
begin
// Execute "Hello World" example from Wikipedia
ExecuteBF(HelloWorldWiki);
// Print text "press ESC to continue....." and wait for ESC to be pressed
ExecuteBF(pressESCtoCont + waitForEsc);
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.
| #Elena | Elena | import system'routines;
import extensions;
import extensions'text;
const string Target = "METHINKS IT IS LIKE A WEASEL";
const string AllowedCharacters = " ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const int C = 100;
const real P = 0.05r;
rnd = randomGenerator;
randomChar
= AllowedCharacters[rnd.nextInt(AllowedCharacters.Length)];
extension evoHelper
{
randomString()
= 0.repeatTill(self).selectBy:(x => randomChar).summarize(new StringWriter());
fitnessOf(s)
= self.zipBy(s, (a,b => a==b ? 1 : 0)).summarize(new Integer()).toInt();
mutate(p)
= self.selectBy:(ch => rnd.nextReal() <= p ? randomChar : ch).summarize(new StringWriter());
}
class EvoAlgorithm : Enumerator
{
object theTarget;
object theCurrent;
object theVariantCount;
constructor new(s,count)
{
theTarget := s;
theVariantCount := count.toInt();
}
get() = theCurrent;
bool next()
{
if (nil == theCurrent)
{ theCurrent := theTarget.Length.randomString(); ^ true };
if (theTarget == theCurrent)
{ ^ false };
auto variants := Array.allocate(theVariantCount).populate:(x => theCurrent.mutate:P );
theCurrent := variants.sort:(a,b => a.fitnessOf:Target > b.fitnessOf:Target ).at:0;
^ true
}
reset()
{
theCurrent := nil
}
enumerable() => theTarget;
}
public program()
{
var attempt := new Integer();
EvoAlgorithm.new(Target,C).forEach:(current)
{
console
.printPaddingLeft(10,"#",attempt.append(1))
.printLine(" ",current," fitness: ",current.fitnessOf(Target))
};
console.readChar()
} |
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
| #LSL | LSL | integer Fibonacci(integer n) {
if(n<2) {
return n;
} else {
return Fibonacci(n-1)+Fibonacci(n-2);
}
}
default {
state_entry() {
integer x = 0;
for(x=0 ; x<35 ; x++) {
llOwnerSay("Fibonacci("+(string)x+")="+(string)Fibonacci(x));
}
}
} |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #Rust | Rust | use std::env;
// HQ9+ requires that '+' increments an accumulator, but it's inaccessible (and thus, unused).
#[allow(unused_variables)]
fn execute(code: &str) {
let mut accumulator = 0;
for c in code.chars() {
match c {
'Q' => println!("{}", code),
'H' => println!("Hello, World!"),
'9' => {
for n in (1..100).rev() {
println!("{} bottles of beer on the wall", n);
println!("{} bottles of beer", n);
println!("Take one down, pass it around");
if (n - 1) > 1 {
println!("{} bottles of beer on the wall\n", n - 1);
} else {
println!("1 bottle of beer on the wall\n");
}
}
}
'+' => accumulator += 1,
_ => panic!("Invalid character '{}' found in source.", c),
}
}
}
fn main() {
execute(&env::args().nth(1).unwrap());
} |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #Scala | Scala | def hq9plus(code: String) : String = {
var out = ""
var acc = 0
def bottle(num: Int) : Unit = {
if (num > 1) {
out += num + " bottles of beer on the wall, " + num + " bottles of beer.\n"
out += "Take one down and pass it around, " + (num - 1) + " bottle"
if (num > 2) out += "s"
out += " of beer.\n\n"
bottle(num - 1)
}
else {
out += "1 bottle of beer on the wall, 1 bottle of beer.\n" +
"Take one down and pass it around, no more bottles of beer on the wall.\n\n" +
"No more bottles of beer on the wall, no more bottles of beer.\n" +
"Go to the store and buy some more, 99 bottles of beer on the wall.\n"
}
}
def handle(char: Char) = char match {
case 'H' => out += "Hello world!\n"
case 'Q' => out += code + "\n"
case '+' => acc += 1
case '9' => bottle(99)
}
code.toList foreach handle
out
}
println(hq9plus("HQ9+"))
|
http://rosettacode.org/wiki/Execute_a_Markov_algorithm | Execute a Markov algorithm | Execute a Markov algorithm
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create an interpreter for a Markov Algorithm.
Rules have the syntax:
<ruleset> ::= ((<comment> | <rule>) <newline>+)*
<comment> ::= # {<any character>}
<rule> ::= <pattern> <whitespace> -> <whitespace> [.] <replacement>
<whitespace> ::= (<tab> | <space>) [<whitespace>]
There is one rule per line.
If there is a . (period) present before the <replacement>, then this is a terminating rule in which case the interpreter must halt execution.
A ruleset consists of a sequence of rules, with optional comments.
Rulesets
Use the following tests on entries:
Ruleset 1
# This rules file is extracted from Wikipedia:
# http://en.wikipedia.org/wiki/Markov_Algorithm
A -> apple
B -> bag
S -> shop
T -> the
the shop -> my brother
a never used -> .terminating rule
Sample text of:
I bought a B of As from T S.
Should generate the output:
I bought a bag of apples from my brother.
Ruleset 2
A test of the terminating rule
# Slightly modified from the rules on Wikipedia
A -> apple
B -> bag
S -> .shop
T -> the
the shop -> my brother
a never used -> .terminating rule
Sample text of:
I bought a B of As from T S.
Should generate:
I bought a bag of apples from T shop.
Ruleset 3
This tests for correct substitution order and may trap simple regexp based replacement routines if special regexp characters are not escaped.
# BNF Syntax testing rules
A -> apple
WWWW -> with
Bgage -> ->.*
B -> bag
->.* -> money
W -> WW
S -> .shop
T -> the
the shop -> my brother
a never used -> .terminating rule
Sample text of:
I bought a B of As W my Bgage from T S.
Should generate:
I bought a bag of apples with my money from T shop.
Ruleset 4
This tests for correct order of scanning of rules, and may trap replacement routines that scan in the wrong order. It implements a general unary multiplication engine. (Note that the input expression must be placed within underscores in this implementation.)
### Unary Multiplication Engine, for testing Markov Algorithm implementations
### By Donal Fellows.
# Unary addition engine
_+1 -> _1+
1+1 -> 11+
# Pass for converting from the splitting of multiplication into ordinary
# addition
1! -> !1
,! -> !+
_! -> _
# Unary multiplication by duplicating left side, right side times
1*1 -> x,@y
1x -> xX
X, -> 1,1
X1 -> 1X
_x -> _X
,x -> ,X
y1 -> 1y
y_ -> _
# Next phase of applying
1@1 -> x,@y
1@_ -> @_
,@_ -> !_
++ -> +
# Termination cleanup for addition
_1 -> 1
1+_ -> 1
_+_ ->
Sample text of:
_1111*11111_
should generate the output:
11111111111111111111
Ruleset 5
A simple Turing machine,
implementing a three-state busy beaver.
The tape consists of 0s and 1s, the states are A, B, C and H (for Halt), and the head position is indicated by writing the state letter before the character where the head is.
All parts of the initial tape the machine operates on have to be given in the input.
Besides demonstrating that the Markov algorithm is Turing-complete, it also made me catch a bug in the C++ implementation which wasn't caught by the first four rulesets.
# Turing machine: three-state busy beaver
#
# state A, symbol 0 => write 1, move right, new state B
A0 -> 1B
# state A, symbol 1 => write 1, move left, new state C
0A1 -> C01
1A1 -> C11
# state B, symbol 0 => write 1, move left, new state A
0B0 -> A01
1B0 -> A11
# state B, symbol 1 => write 1, move right, new state B
B1 -> 1B
# state C, symbol 0 => write 1, move left, new state B
0C0 -> B01
1C0 -> B11
# state C, symbol 1 => write 1, move left, halt
0C1 -> H01
1C1 -> H11
This ruleset should turn
000000A000000
into
00011H1111000
| #Ruby | Ruby | def setup(ruleset)
ruleset.each_line.inject([]) do |rules, line|
if line =~ /^\s*#/
rules
elsif line =~ /^(.+)\s+->\s+(\.?)(.*)$/
rules << [$1, $3, $2 != ""]
else
raise "Syntax error: #{line}"
end
end
end
def morcov(ruleset, input_data)
rules = setup(ruleset)
while (matched = rules.find { |match, replace, term|
input_data[match] and input_data.sub!(match, replace)
}) and !matched[2]
end
input_data
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
| #OCaml | OCaml | exception My_Exception;;
exception Another_Exception of string;; |
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
| #Oforth | Oforth | : iwillThrowAnException "A new exception" Exception throw ;
: iwillCatch
| e |
try: e [ iwillThrowAnException ] when: [ "Exception catched :" . e .cr ]
try: e [ 1 2 over last ] when: [ "Exception catched :" . e .cr ]
"Done" println ; |
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
| #Lasso | Lasso | local(
path = file_forceroot,
ls = sys_process('/bin/ls', (:'-l', #path)),
lswait = #ls -> wait
)
'<pre>'
#ls -> read
'</pre>' |
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
| #LFE | LFE |
> (os:cmd "ls -alrt")
|
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
| #BASIC256 | BASIC256 | print "enter a number, n = ";
input n
print string(n) + "! = " + string(factorial(n))
function factorial(n)
factorial = 1
if n > 0 then
for p = 1 to n
factorial *= p
next p
end if
end function |
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
| #PowerShell | PowerShell | function pow($a, [int]$b) {
if ($b -eq -1) { return 1/$a }
if ($b -eq 0) { return 1 }
if ($b -eq 1) { return $a }
if ($b -lt 0) {
$rec = $true # reciprocal needed
$b = -$b
}
$result = $a
2..$b | ForEach-Object {
$result *= $a
}
if ($rec) {
return 1/$result
} else {
return $result
}
} |
http://rosettacode.org/wiki/FizzBuzz | FizzBuzz | Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
| #Smalltalk | Smalltalk | Integer extend [
fizzbuzz [
| fb |
fb := '%<Fizz|>1%<Buzz|>2' % {
self \\ 3 == 0. self \\ 5 == 0 }.
^fb isEmpty ifTrue: [ self ] ifFalse: [ fb ]
]
]
1 to: 100 do: [ :i | i fizzbuzz displayNl ] |
http://rosettacode.org/wiki/Extensible_prime_generator | Extensible prime generator | Task
Write a generator of prime numbers, in order, that will automatically adjust to accommodate the generation of any reasonably high prime.
The routine should demonstrably rely on either:
Being based on an open-ended counter set to count without upper limit other than system or programming language limits. In this case, explain where this counter is in the code.
Being based on a limit that is extended automatically. In this case, choose a small limit that ensures the limit will be passed when generating some of the values to be asked for below.
If other methods of creating an extensible prime generator are used, the algorithm's means of extensibility/lack of limits should be stated.
The routine should be used to:
Show the first twenty primes.
Show the primes between 100 and 150.
Show the number of primes between 7,700 and 8,000.
Show the 10,000th prime.
Show output on this page.
Note: You may reference code already on this site if it is written to be imported/included, then only the code necessary for import and the performance of this task need be shown. (It is also important to leave a forward link on the referenced tasks entry so that later editors know that the code is used for multiple tasks).
Note 2: If a languages in-built prime generator is extensible or is guaranteed to generate primes up to a system limit, (231 or memory overflow for example), then this may be used as long as an explanation of the limits of the prime generator is also given. (Which may include a link to/excerpt from, language documentation).
Note 3:The task is written so it may be useful in solving the task Emirp primes as well as others (depending on its efficiency).
Reference
Prime Numbers. Website with large count of primes.
| #zkl | zkl | // http://stackoverflow.com/revisions/10733621/4
fcn postponed_sieve(){ # postponed sieve, by Will Ness
vm.yield(2); vm.yield(3); # original code David Eppstein,
vm.yield(5); vm.yield(7); # ActiveState Recipe 2002
D:=Dictionary();
ps:=Utils.Generator(postponed_sieve); # a separate Primes Supply:
p:=ps.pump(2,Void); # (3) a Prime to add to dict
q:=p*p; # (9) when its sQuare is
c:=9; # the next Candidate
while(1){
if (not D.holds(c)){ # not a multiple of any prime seen so far:
if (c < q) vm.yield(c); # a prime, or
else{ # (c==q): # the next prime's square:
add(D,c + 2*p,2*p); # (9+6,6 : 15,21,27,33,...)
p=ps.next(); # (5)
q=p*p; # (25)
}
}else{ # 'c' is a composite:
s := D.pop(c); # step of increment
add(D,c + s,s); # next multiple, same step
}
c += 2; # next odd candidate
}
}
fcn add(D,x,s){ # make no multiple keys in Dict
while(D.holds(x)){ x += s } # increment by the given step
D[x] = s;
} |
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.
| #D | D |
program Execute_Brain;
{$APPTYPE CONSOLE}
uses
Winapi.Windows,
System.SysUtils;
const
DataSize = 1024; // Size of Data segment
MaxNest = 1000; // Maximum nesting depth of []
function Readkey: Char;
var
InputRec: TInputRecord;
NumRead: Cardinal;
KeyMode: DWORD;
StdIn: THandle;
begin
StdIn := GetStdHandle(STD_INPUT_HANDLE);
GetConsoleMode(StdIn, KeyMode);
SetConsoleMode(StdIn, 0);
repeat
ReadConsoleInput(StdIn, InputRec, 1, NumRead);
if (InputRec.EventType and KEY_EVENT <> 0) and InputRec.Event.KeyEvent.bKeyDown then
begin
if InputRec.Event.KeyEvent.AsciiChar <> #0 then
begin
Result := InputRec.Event.KeyEvent.UnicodeChar;
Break;
end;
end;
until FALSE;
SetConsoleMode(StdIn, KeyMode);
end;
procedure ExecuteBF(Source: string);
var
Dp: pByte; // Used as the Data Pointer
DataSeg: Pointer; // Start of the DataSegment (Cell 0)
Ip: pChar; // Used as instruction Pointer
LastIp: Pointer; // Last adr of code.
JmpStack: array[0..MaxNest - 1] of pChar; // Stack to Keep track of active "[" locations
JmpPnt: Integer; // Stack pointer ^^
JmpCnt: Word; // Used to count brackets when skipping forward.
begin
// Set up then data segment
getmem(DataSeg, dataSize);
Dp := DataSeg;
// fillbyte(dp^,dataSize,0);
FillChar(Dp^, DataSize, 0);
// Set up the JmpStack
JmpPnt := -1;
// Set up Instruction Pointer
Ip := @Source[1];
LastIp := @Source[length(Source)];
if Ip = nil then
exit;
// Main Execution loop
repeat { until Ip > LastIp }
case Ip^ of
'<':
dec(Dp);
'>':
inc(Dp);
'+':
inc(Dp^);
'-':
dec(Dp^);
'.':
write(chr(Dp^));
',':
Dp^ := ord(ReadKey);
'[':
if Dp^ = 0 then
begin
// skip forward until matching bracket;
JmpCnt := 1;
while (JmpCnt > 0) and (Ip <= LastIp) do
begin
inc(Ip);
case Ip^ of
'[':
inc(JmpCnt);
']':
dec(JmpCnt);
#0:
begin
Writeln('Error brackets don''t match');
halt;
end;
end;
end;
end
else
begin
// Add location to Jump stack
inc(JmpPnt);
JmpStack[JmpPnt] := Ip;
end;
']':
if Dp^ > 0 then
// Jump Back to matching [
Ip := JmpStack[JmpPnt]
else // Remove Jump from stack
dec(JmpPnt);
end;
inc(Ip);
until Ip > LastIp;
freemem(DataSeg, dataSize);
end;
const
HelloWorldWiki = '++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>' +
'---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.';
pressESCtoCont = '>[-]+++++++[<++++++++++>-]<->>[-]+++++++[<+++++++++++' +
'+>-]<->>[-]++++[<++++++++>-]+>[-]++++++++++[<++++++++' +
'++>-]>[-]++++++++[<++++++++++++++>-]<.++.+<.>..<<.<<.' +
'-->.<.>>.>>+.-----.<<.[<<+>>-]<<.>>>>.-.++++++.<++++.' +
'+++++.>+.<<<<++.>+[>+<--]>++++...';
waitForEsc = '[-]>[-]++++[<+++++++>-]<->[-]>+[[-]<<[>+>+<<-]' + '>>[<' +
'<+>>-],<[->-<]>]';
begin
// Execute "Hello World" example from Wikipedia
ExecuteBF(HelloWorldWiki);
// Print text "press ESC to continue....." and wait for ESC to be pressed
ExecuteBF(pressESCtoCont + waitForEsc);
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.
| #Elixir | Elixir | defmodule Log do
def show(offspring,i) do
IO.puts "Generation: #{i}, Offspring: #{offspring}"
end
def found({target,i}) do
IO.puts "#{target} found in #{i} iterations"
end
end
defmodule Evolution do
# char list from A to Z; 32 is the ord value for space.
@chars [32 | Enum.to_list(?A..?Z)]
def select(target) do
(1..String.length(target)) # Creates parent for generation 0.
|> Enum.map(fn _-> Enum.random(@chars) end)
|> mutate(to_charlist(target),0)
|> Log.found
end
# w is used to denote fitness in population genetics.
defp mutate(parent,target,i) when target == parent, do: {parent,i}
defp mutate(parent,target,i) do
w = fitness(parent,target)
prev = reproduce(target,parent,mu_rate(w))
# Check if the most fit member of the new gen has a greater fitness than the parent.
if w < fitness(prev,target) do
Log.show(prev,i)
mutate(prev,target,i+1)
else
mutate(parent,target,i+1)
end
end
# Generate 100 offspring and select the one with the greatest fitness.
defp reproduce(target,parent,rate) do
[parent | (for _ <- 1..100, do: mutation(parent,rate))]
|> Enum.max_by(fn n -> fitness(n,target) end)
end
# Calculate fitness by checking difference between parent and offspring chars.
defp fitness(t,r) do
Enum.zip(t,r)
|> Enum.reduce(0, fn {tn,rn},sum -> abs(tn - rn) + sum end)
|> calc
end
# Generate offspring based on parent.
defp mutation(p,r) do
# Copy the parent chars, then check each val against the random mutation rate
Enum.map(p, fn n -> if :rand.uniform <= r, do: Enum.random(@chars), else: n end)
end
defp calc(sum), do: 100 * :math.exp(sum/-10)
defp mu_rate(n), do: 1 - :math.exp(-(100-n)/400)
end
Evolution.select("METHINKS IT IS LIKE A WEASEL") |
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
| #Lua | Lua |
--calculates the nth fibonacci number. Breaks for negative or non-integer n.
function fibs(n)
return n < 2 and n or fibs(n - 1) + fibs(n - 2)
end
|
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
const proc: runCode (in string: code) is func
local
var char: ch is ' ';
var integer: bottles is 0;
var integer: accumulator is 0;
begin
for ch range code do
case ch of
when {'H'}: writeln("Hello, world!");
when {'Q'}: writeln(code);
when {'9'}: bottles := 99;
repeat
writeln(bottles <& " bottles of beer on the wall");
writeln(bottles <& " bottles of beer");
writeln("Take one down, pass it around");
decr(bottles);
writeln(bottles <& " bottles of beer on the wall");
writeln;
until bottles = 0;
when {'+'}: incr(accumulator);
end case;
end for;
end func;
const proc: main is func
begin
if length(argv(PROGRAM)) >= 1 then
runCode(argv(PROGRAM)[1]);
end if;
end func; |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #Sidef | Sidef | class HQ9Interpreter {
has pointer;
has accumulator;
func bob (beer) {
func what { "#{beer ? beer : 'No more'} bottle#{beer-1 ? 's' : ''} of beer" }
func where { 'on the wall' }
func drink { beer--; "Take one down, pass it around," }
while (beer.is_pos) {
[[what(), where()], [what()],
[drink()], [what(), where()], []].each{.join(' ').say}
}
}
method run (code) {
var chars = code.chars;
accumulator = 0;
pointer = 0;
while (pointer < chars.len) {
given (chars[pointer].lc) {
when ('h') { say 'Hello world!' }
when ('q') { say code }
when ('9') { bob(99) }
when ('+') { accumulator++ }
default { warn %Q(Syntax error: Unknown command "#{chars[pointer]}") }
}
pointer++;
}
}
} |
http://rosettacode.org/wiki/Execute_a_Markov_algorithm | Execute a Markov algorithm | Execute a Markov algorithm
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create an interpreter for a Markov Algorithm.
Rules have the syntax:
<ruleset> ::= ((<comment> | <rule>) <newline>+)*
<comment> ::= # {<any character>}
<rule> ::= <pattern> <whitespace> -> <whitespace> [.] <replacement>
<whitespace> ::= (<tab> | <space>) [<whitespace>]
There is one rule per line.
If there is a . (period) present before the <replacement>, then this is a terminating rule in which case the interpreter must halt execution.
A ruleset consists of a sequence of rules, with optional comments.
Rulesets
Use the following tests on entries:
Ruleset 1
# This rules file is extracted from Wikipedia:
# http://en.wikipedia.org/wiki/Markov_Algorithm
A -> apple
B -> bag
S -> shop
T -> the
the shop -> my brother
a never used -> .terminating rule
Sample text of:
I bought a B of As from T S.
Should generate the output:
I bought a bag of apples from my brother.
Ruleset 2
A test of the terminating rule
# Slightly modified from the rules on Wikipedia
A -> apple
B -> bag
S -> .shop
T -> the
the shop -> my brother
a never used -> .terminating rule
Sample text of:
I bought a B of As from T S.
Should generate:
I bought a bag of apples from T shop.
Ruleset 3
This tests for correct substitution order and may trap simple regexp based replacement routines if special regexp characters are not escaped.
# BNF Syntax testing rules
A -> apple
WWWW -> with
Bgage -> ->.*
B -> bag
->.* -> money
W -> WW
S -> .shop
T -> the
the shop -> my brother
a never used -> .terminating rule
Sample text of:
I bought a B of As W my Bgage from T S.
Should generate:
I bought a bag of apples with my money from T shop.
Ruleset 4
This tests for correct order of scanning of rules, and may trap replacement routines that scan in the wrong order. It implements a general unary multiplication engine. (Note that the input expression must be placed within underscores in this implementation.)
### Unary Multiplication Engine, for testing Markov Algorithm implementations
### By Donal Fellows.
# Unary addition engine
_+1 -> _1+
1+1 -> 11+
# Pass for converting from the splitting of multiplication into ordinary
# addition
1! -> !1
,! -> !+
_! -> _
# Unary multiplication by duplicating left side, right side times
1*1 -> x,@y
1x -> xX
X, -> 1,1
X1 -> 1X
_x -> _X
,x -> ,X
y1 -> 1y
y_ -> _
# Next phase of applying
1@1 -> x,@y
1@_ -> @_
,@_ -> !_
++ -> +
# Termination cleanup for addition
_1 -> 1
1+_ -> 1
_+_ ->
Sample text of:
_1111*11111_
should generate the output:
11111111111111111111
Ruleset 5
A simple Turing machine,
implementing a three-state busy beaver.
The tape consists of 0s and 1s, the states are A, B, C and H (for Halt), and the head position is indicated by writing the state letter before the character where the head is.
All parts of the initial tape the machine operates on have to be given in the input.
Besides demonstrating that the Markov algorithm is Turing-complete, it also made me catch a bug in the C++ implementation which wasn't caught by the first four rulesets.
# Turing machine: three-state busy beaver
#
# state A, symbol 0 => write 1, move right, new state B
A0 -> 1B
# state A, symbol 1 => write 1, move left, new state C
0A1 -> C01
1A1 -> C11
# state B, symbol 0 => write 1, move left, new state A
0B0 -> A01
1B0 -> A11
# state B, symbol 1 => write 1, move right, new state B
B1 -> 1B
# state C, symbol 0 => write 1, move left, new state B
0C0 -> B01
1C0 -> B11
# state C, symbol 1 => write 1, move left, halt
0C1 -> H01
1C1 -> H11
This ruleset should turn
000000A000000
into
00011H1111000
| #Rust | Rust | use std::str::FromStr;
#[derive(Clone, Debug)]
pub struct Rule {
pub pat: String,
pub rep: String,
pub terminal: bool,
}
impl Rule {
pub fn new(pat: String, rep: String, terminal: bool) -> Self {
Self { pat, rep, terminal }
}
pub fn applicable_range(&self, input: impl AsRef<str>) -> Option<std::ops::Range<usize>> {
input
.as_ref()
.match_indices(&self.pat)
.next()
.map(|(start, slice)| start..start + slice.len())
}
pub fn apply(&self, s: &mut String) -> bool {
self.applicable_range(s.as_str()).map_or(false, |range| {
s.replace_range(range, &self.rep);
true
})
}
}
impl FromStr for Rule {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut split = s.splitn(2, " -> ");
let pat = split.next().ok_or_else(|| s.to_string())?;
let rep = split.next().ok_or_else(|| s.to_string())?;
let pat = pat.to_string();
if rep.starts_with('.') {
Ok(Self::new(pat, rep[1..].to_string(), true))
} else {
Ok(Self::new(pat, rep.to_string(), false))
}
}
}
#[derive(Clone, Debug)]
pub struct Rules {
rules: Vec<Rule>,
}
impl Rules {
pub fn new(rules: Vec<Rule>) -> Self {
Self { rules }
}
pub fn apply(&self, s: &mut String) -> Option<&Rule> {
self.rules
.iter()
.find(|rule| rule.apply(s))
}
pub fn execute(&self, mut buffer: String) -> String {
while let Some(rule) = self.apply(&mut buffer) {
if rule.terminal {
break;
}
}
buffer
}
}
impl FromStr for Rules {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut rules = Vec::new();
for line in s.lines().filter(|line| !line.starts_with('#')) {
rules.push(line.parse::<Rule>()?);
}
Ok(Rules::new(rules))
}
}
#[cfg(test)]
mod tests {
use super::Rules;
#[test]
fn case_01() -> Result<(), String> {
let input = "I bought a B of As from T S.";
let rules = "\
# This rules file is extracted from Wikipedia:
# http://en.wikipedia.org/wiki/Markov_Algorithm
A -> apple
B -> bag
S -> shop
T -> the
the shop -> my brother
a never used -> .terminating rule";
assert_eq!(
rules.parse::<Rules>()?.execute(input.to_string()),
"I bought a bag of apples from my brother."
);
Ok(())
}
#[test]
fn case_02() -> Result<(), String> {
let input = "I bought a B of As from T S.";
let rules = "\
# Slightly modified from the rules on Wikipedia
A -> apple
B -> bag
S -> .shop
T -> the
the shop -> my brother
a never used -> .terminating rule";
assert_eq!(
rules.parse::<Rules>()?.execute(input.to_string()),
"I bought a bag of apples from T shop."
);
Ok(())
}
#[test]
fn case_03() -> Result<(), String> {
let input = "I bought a B of As W my Bgage from T S.";
let rules = "\
# BNF Syntax testing rules
A -> apple
WWWW -> with
Bgage -> ->.*
B -> bag
->.* -> money
W -> WW
S -> .shop
T -> the
the shop -> my brother
a never used -> .terminating rule";
assert_eq!(
rules.parse::<Rules>()?.execute(input.to_string()),
"I bought a bag of apples with my money from T shop."
);
Ok(())
}
#[test]
fn case_04() -> Result<(), String> {
let input = "_1111*11111_";
let rules = "\
### Unary Multiplication Engine, for testing Markov Algorithm implementations
### By Donal Fellows.
# Unary addition engine
_+1 -> _1+
1+1 -> 11+
# Pass for converting from the splitting of multiplication into ordinary
# addition
1! -> !1
,! -> !+
_! -> _
# Unary multiplication by duplicating left side, right side times
1*1 -> x,@y
1x -> xX
X, -> 1,1
X1 -> 1X
_x -> _X
,x -> ,X
y1 -> 1y
y_ -> _
# Next phase of applying
1@1 -> x,@y
1@_ -> @_
,@_ -> !_
++ -> +
# Termination cleanup for addition
_1 -> 1
1+_ -> 1
_+_ -> ";
assert_eq!(
rules.parse::<Rules>()?.execute(input.to_string()),
"11111111111111111111"
);
Ok(())
}
#[test]
fn case_05() -> Result<(), String> {
let input = "000000A000000";
let rules = "\
# Turing machine: three-state busy beaver
#
# state A, symbol 0 => write 1, move right, new state B
A0 -> 1B
# state A, symbol 1 => write 1, move left, new state C
0A1 -> C01
1A1 -> C11
# state B, symbol 0 => write 1, move left, new state A
0B0 -> A01
1B0 -> A11
# state B, symbol 1 => write 1, move right, new state B
B1 -> 1B
# state C, symbol 0 => write 1, move left, new state B
0C0 -> B01
1C0 -> B11
# state C, symbol 1 => write 1, move left, halt
0C1 -> H01
1C1 -> H11";
assert_eq!(
rules.parse::<Rules>()?.execute(input.to_string()),
"00011H1111000"
);
Ok(())
}
}
|
http://rosettacode.org/wiki/Execute_a_Markov_algorithm | Execute a Markov algorithm | Execute a Markov algorithm
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create an interpreter for a Markov Algorithm.
Rules have the syntax:
<ruleset> ::= ((<comment> | <rule>) <newline>+)*
<comment> ::= # {<any character>}
<rule> ::= <pattern> <whitespace> -> <whitespace> [.] <replacement>
<whitespace> ::= (<tab> | <space>) [<whitespace>]
There is one rule per line.
If there is a . (period) present before the <replacement>, then this is a terminating rule in which case the interpreter must halt execution.
A ruleset consists of a sequence of rules, with optional comments.
Rulesets
Use the following tests on entries:
Ruleset 1
# This rules file is extracted from Wikipedia:
# http://en.wikipedia.org/wiki/Markov_Algorithm
A -> apple
B -> bag
S -> shop
T -> the
the shop -> my brother
a never used -> .terminating rule
Sample text of:
I bought a B of As from T S.
Should generate the output:
I bought a bag of apples from my brother.
Ruleset 2
A test of the terminating rule
# Slightly modified from the rules on Wikipedia
A -> apple
B -> bag
S -> .shop
T -> the
the shop -> my brother
a never used -> .terminating rule
Sample text of:
I bought a B of As from T S.
Should generate:
I bought a bag of apples from T shop.
Ruleset 3
This tests for correct substitution order and may trap simple regexp based replacement routines if special regexp characters are not escaped.
# BNF Syntax testing rules
A -> apple
WWWW -> with
Bgage -> ->.*
B -> bag
->.* -> money
W -> WW
S -> .shop
T -> the
the shop -> my brother
a never used -> .terminating rule
Sample text of:
I bought a B of As W my Bgage from T S.
Should generate:
I bought a bag of apples with my money from T shop.
Ruleset 4
This tests for correct order of scanning of rules, and may trap replacement routines that scan in the wrong order. It implements a general unary multiplication engine. (Note that the input expression must be placed within underscores in this implementation.)
### Unary Multiplication Engine, for testing Markov Algorithm implementations
### By Donal Fellows.
# Unary addition engine
_+1 -> _1+
1+1 -> 11+
# Pass for converting from the splitting of multiplication into ordinary
# addition
1! -> !1
,! -> !+
_! -> _
# Unary multiplication by duplicating left side, right side times
1*1 -> x,@y
1x -> xX
X, -> 1,1
X1 -> 1X
_x -> _X
,x -> ,X
y1 -> 1y
y_ -> _
# Next phase of applying
1@1 -> x,@y
1@_ -> @_
,@_ -> !_
++ -> +
# Termination cleanup for addition
_1 -> 1
1+_ -> 1
_+_ ->
Sample text of:
_1111*11111_
should generate the output:
11111111111111111111
Ruleset 5
A simple Turing machine,
implementing a three-state busy beaver.
The tape consists of 0s and 1s, the states are A, B, C and H (for Halt), and the head position is indicated by writing the state letter before the character where the head is.
All parts of the initial tape the machine operates on have to be given in the input.
Besides demonstrating that the Markov algorithm is Turing-complete, it also made me catch a bug in the C++ implementation which wasn't caught by the first four rulesets.
# Turing machine: three-state busy beaver
#
# state A, symbol 0 => write 1, move right, new state B
A0 -> 1B
# state A, symbol 1 => write 1, move left, new state C
0A1 -> C01
1A1 -> C11
# state B, symbol 0 => write 1, move left, new state A
0B0 -> A01
1B0 -> A11
# state B, symbol 1 => write 1, move right, new state B
B1 -> 1B
# state C, symbol 0 => write 1, move left, new state B
0C0 -> B01
1C0 -> B11
# state C, symbol 1 => write 1, move left, halt
0C1 -> H01
1C1 -> H11
This ruleset should turn
000000A000000
into
00011H1111000
| #Scala | Scala | import scala.io.Source
object MarkovAlgorithm {
val RulePattern = """(.*?)\s+->\s+(\.?)(.*)""".r
val CommentPattern = """#.*|\s*""".r
def rule(line: String) = line match {
case CommentPattern() => None
case RulePattern(pattern, terminal, replacement) => Some(pattern, replacement, terminal == ".")
case _ => error("Syntax error on line "+line)
}
def main(args: Array[String]) {
if (args.size != 2 ) {
println("Syntax: MarkovAlgorithm inputFile inputPattern")
exit(1)
}
val rules = (Source fromPath args(0) getLines () map rule).toList.flatten
def algorithm(input: String): String = rules find (input contains _._1) match {
case Some((pattern, replacement, true)) => input replaceFirst ("\\Q"+pattern+"\\E", replacement)
case Some((pattern, replacement, false)) => algorithm(input replaceFirst ("\\Q"+pattern+"\\E", replacement))
case None => input
}
println(args(1))
println(algorithm(args(1)))
}
} |
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
| #Oz | Oz | raise sillyError end
raise slightlyLessSilly(data:42 reason:outOfMemory) 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
| #PARI.2FGP | PARI/GP | trap(/* specific error can be given here, or leave blank to catch all */,
"caught"
,
error("bad stuff")
) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.