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/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
| #Lingo | Lingo | -- As for built-in power() function:
-- base can be either integer or float; returns float.
on pow (base, exp)
if exp=0 then return 1.0
else if exp<0 then
exp = -exp
base = 1.0/base
end if
res = float(base)
repeat with i = 2 to exp
res = res*base
end repeat
return res
end |
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
| #Logo | Logo | to int_power :n :m
if equal? 0 :m [output 1]
if equal? 0 modulo :m 2 [output int_power :n*:n :m/2]
output :n * int_power :n :m-1
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.
| #Python | Python | a, b = 1, 0
if (c1 := a == 1) and (c2 := b == 3):
print('a = 1 and b = 3')
elif c1:
print('a = 1 and b <> 3')
elif c2:
print('a <> 1 and b = 3')
else:
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
| #SAS | SAS | data _null_;
do i=1 to 100;
if mod(i,15)=0 then put "FizzBuzz";
else if mod(i,5)=0 then put "Buzz";
else if mod(i,3)=0 then put "Fizz";
else put i;
end;
run; |
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.
| #Python | Python | islice(count(7), 0, None, 2) |
http://rosettacode.org/wiki/Execute_Brain**** | Execute Brain**** | Execute Brain**** is an implementation of Brainf***.
Other implementations of Brainf***.
RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages.
Below are links to each of the versions of RCBF.
An implementation need only properly implement the following instructions:
Command
Description
>
Move the pointer to the right
<
Move the pointer to the left
+
Increment the memory cell under the pointer
-
Decrement the memory cell under the pointer
.
Output the character signified by the cell at the pointer
,
Input a character and store it in the cell at the pointer
[
Jump past the matching ] if the cell under the pointer is 0
]
Jump back to the matching [ if the cell under the pointer is nonzero
Any cell size is allowed, EOF (End-O-File) support is optional, as is whether you have bounded or unbounded memory.
| #Axe | Axe | Lbl BF
r₁→P
r₂→I
L₁→D
Fill(D,768,0)
While {P}
{P}→C
If C='+'
{D}++
ElseIf C='-'
{D}--
ElseIf C='>'
D++
ElseIf C='<'
D--
ElseIf C='.'
Disp {D}▶Char
ElseIf C=','
{I}→{D}
I++
ElseIf C='['?{D}=0
NEXT(P)→P
ElseIf C=']'
PREV(P)→P
End
P++
End
Return
Lbl NEXT
r₁++
1→S
While S
If {r₁}='['
S++
ElseIf {r₁}=']'
S--
End
r₁++
End
r₁
Return
Lbl PREV
r₁--
1→S
While S
If {r₁}=']'
S++
ElseIf {r₁}='['
S--
End
r₁--
End
r₁
Return |
http://rosettacode.org/wiki/Evolutionary_algorithm | Evolutionary algorithm | Starting with:
The target string: "METHINKS IT IS LIKE A WEASEL".
An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent).
A fitness function that computes the ‘closeness’ of its argument to the target string.
A mutate function that given a string and a mutation rate returns a copy of the string, with some characters probably mutated.
While the parent is not yet the target:
copy the parent C times, each time allowing some random probability that another character might be substituted using mutate.
Assess the fitness of the parent and all the copies to the target and make the most fit string the new parent, discarding the others.
repeat until the parent converges, (hopefully), to the target.
See also
Wikipedia entry: Weasel algorithm.
Wikipedia entry: Evolutionary algorithm.
Note: to aid comparison, try and ensure the variables and functions mentioned in the task description appear in solutions
A cursory examination of a few of the solutions reveals that the instructions have not been followed rigorously in some solutions. Specifically,
While the parent is not yet the target:
copy the parent C times, each time allowing some random probability that another character might be substituted using mutate.
Note that some of the the solutions given retain characters in the mutated string that are correct in the target string. However, the instruction above does not state to retain any of the characters while performing the mutation. Although some may believe to do so is implied from the use of "converges"
(:* repeat until the parent converges, (hopefully), to the target.
Strictly speaking, the new parent should be selected from the new pool of mutations, and then the new parent used to generate the next set of mutations with parent characters getting retained only by not being mutated. It then becomes possible that the new set of mutations has no member that is fitter than the parent!
As illustration of this error, the code for 8th has the following remark.
Create a new string based on the TOS, changing randomly any characters which
don't already match the target:
NOTE: this has been changed, the 8th version is completely random now
Clearly, this algo will be applying the mutation function only to the parent characters that don't match to the target characters!
To ensure that the new parent is never less fit than the prior parent, both the parent and all of the latest mutations are subjected to the fitness test to select the next parent.
| #C | C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
const char target[] = "METHINKS IT IS LIKE A WEASEL";
const char tbl[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ ";
#define CHOICE (sizeof(tbl) - 1)
#define MUTATE 15
#define COPIES 30
/* returns random integer from 0 to n - 1 */
int irand(int n)
{
int r, rand_max = RAND_MAX - (RAND_MAX % n);
while((r = rand()) >= rand_max);
return r / (rand_max / n);
}
/* number of different chars between a and b */
int unfitness(const char *a, const char *b)
{
int i, sum = 0;
for (i = 0; a[i]; i++)
sum += (a[i] != b[i]);
return sum;
}
/* each char of b has 1/MUTATE chance of differing from a */
void mutate(const char *a, char *b)
{
int i;
for (i = 0; a[i]; i++)
b[i] = irand(MUTATE) ? a[i] : tbl[irand(CHOICE)];
b[i] = '\0';
}
int main()
{
int i, best_i, unfit, best, iters = 0;
char specimen[COPIES][sizeof(target) / sizeof(char)];
/* init rand string */
for (i = 0; target[i]; i++)
specimen[0][i] = tbl[irand(CHOICE)];
specimen[0][i] = 0;
do {
for (i = 1; i < COPIES; i++)
mutate(specimen[0], specimen[i]);
/* find best fitting string */
for (best_i = i = 0; i < COPIES; i++) {
unfit = unfitness(target, specimen[i]);
if(unfit < best || !i) {
best = unfit;
best_i = i;
}
}
if (best_i) strcpy(specimen[0], specimen[best_i]);
printf("iter %d, score %d: %s\n", iters++, best, specimen[0]);
} while (best);
return 0;
} |
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
| #lambdatalk | lambdatalk |
1) basic version
{def fib1
{lambda {:n}
{if {< :n 3}
then 1
else {+ {fib1 {- :n 1}} {fib1 {- :n 2}}} }}}
{fib1 16} -> 987 (CPU ~ 16ms)
{fib1 30} = 832040 (CPU > 12000ms)
2) tail-recursive version
{def fib2
{def fib2.r
{lambda {:a :b :i}
{if {< :i 1}
then :a
else {fib2.r :b {+ :a :b} {- :i 1}} }}}
{lambda {:n} {fib2.r 0 1 :n}}}
{fib2 16} -> 987 (CPU ~ 1ms)
{fib2 30} -> 832040 (CPU ~2ms)
{fib2 1000} -> 4.346655768693743e+208 (CPU ~ 22ms)
3) Dijkstra Algorithm
{def fib3
{def fib3.r
{lambda {:a :b :p :q :count}
{if {= :count 0}
then :b
else {if {= {% :count 2} 0}
then {fib3.r :a :b
{+ {* :p :p} {* :q :q}}
{+ {* :q :q} {* 2 :p :q}}
{/ :count 2}}
else {fib3.r {+ {* :b :q} {* :a :q} {* :a :p}}
{+ {* :b :p} {* :a :q}}
:p :q
{- :count 1}} }}}}
{lambda {:n}
{fib3.r 1 0 0 1 :n} }}
{fib3 16} -> 987 (CPU ~ 2ms)
{fib3 30} -> 832040 (CPU ~ 2ms)
{fib3 1000} -> 4.346655768693743e+208 (CPU ~ 3ms)
4) memoization
{def fib4
{def fib4.m {array.new}} // init an empty array
{def fib4.r {lambda {:n}
{if {< :n 2}
then {array.get {array.set! {fib4.m} :n 1} :n} // init with 1,1
else {if {equal? {array.get {fib4.m} :n} undefined} // if not exists
then {array.get {array.set! {fib4.m} :n
{+ {fib4.r {- :n 1}}
{fib4.r {- :n 2}}}} :n} // compute it
else {array.get {fib4.m} :n} }}}} // else get it
{lambda {:n}
{fib4.r :n}
{fib4.m} }} // display the number AND all its predecessors
-> fib4
{fib4 90}
-> 4660046610375530000
[1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181,6765,10946,17711,28657,46368,75025,121393,196418,
317811,514229,832040,1346269,2178309,3524578,5702887,9227465,14930352,24157817,39088169,63245986,102334155,
165580141,267914296,433494437,701408733,1134903170,1836311903,2971215073,4807526976,7778742049,12586269025,
20365011074,32951280099,53316291173,86267571272,139583862445,225851433717,365435296162,591286729879,956722026041,
1548008755920,2504730781961,4052739537881,6557470319842,10610209857723,17167680177565,27777890035288,44945570212853,
72723460248141,117669030460994,190392490709135,308061521170129,498454011879264,806515533049393,1304969544928657,
2111485077978050,3416454622906707,5527939700884757,8944394323791464,14472334024676220,23416728348467684,
37889062373143900,61305790721611580,99194853094755490,160500643816367070,259695496911122560,420196140727489660,
679891637638612200,1100087778366101900,1779979416004714000,2880067194370816000,4660046610375530000]
5) Binet's formula (non recursive)
{def fib5
{lambda {:n}
{let { {:n :n} {:sqrt5 {sqrt 5}} }
{round {/ {- {pow {/ {+ 1 :sqrt5} 2} :n}
{pow {/ {- 1 :sqrt5} 2} :n}} :sqrt5}}} }}
{fib5 16} -> 987 (CPU ~ 1ms)
{fib5 30} -> 832040 (CPU ~ 1ms)
{fib5 1000} -> 4.346655768693743e+208 (CPU ~ 1ms)
|
http://rosettacode.org/wiki/Factors_of_an_integer | Factors of an integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Compute the factors of a positive integer.
These factors are the positive integers by which the number being factored can be divided to yield a positive integer result.
(Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty; this task does not require handling of either of these cases).
Note that every prime number has two factors: 1 and itself.
Related tasks
count in factors
prime decomposition
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
sequence: smallest number greater than previous term with exactly n divisors
| #Wortel | Wortel | @let {
factors1 &n !-\%%n @to n
factors_tacit @(\\%% !- @to)
[[
!factors1 10
!factors_tacit 100
!factors1 720
]]
} |
http://rosettacode.org/wiki/Factors_of_an_integer | Factors of an integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Compute the factors of a positive integer.
These factors are the positive integers by which the number being factored can be divided to yield a positive integer result.
(Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty; this task does not require handling of either of these cases).
Note that every prime number has two factors: 1 and itself.
Related tasks
count in factors
prime decomposition
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
sequence: smallest number greater than previous term with exactly n divisors
| #Wren | Wren | import "/fmt" for Fmt
import "/math" for Int
var a = [11, 21, 32, 45, 67, 96, 159, 723, 1024, 5673, 12345, 32767, 123459, 999997]
System.print("The factors of the following numbers are:")
for (e in a) System.print("%(Fmt.d(6, e)) => %(Int.divisors(e))") |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | hq9plus[program_] :=
Module[{accumulator = 0, bottle},
bottle[n_] :=
ToString[n] <> If[n == 1, " bottle", " bottles"] <> " of beer";
Do[Switch[chr, "H", Print@"hello, world", "Q", Print@program, "9",
Print@StringJoin[
Table[bottle[n] <> " on the wall\n" <> bottle[n] <>
"\ntake one down, pass it around\n" <> bottle[n - 1] <>
" on the wall" <> If[n == 1, "", "\n\n"], {n, 99, 1, -1}]],
"+", accumulator++], {chr, Characters@program}]; accumulator] |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #MiniScript | MiniScript | code = input("Enter HQ9+ program: ")
sing = function()
for i in range(99,2)
print i + " bottles of beer on the wall, " + i + " bottles of beer"
print "Take one down, pass it around, " + (i-1) + " bottle" + "s"*(i>2) + " of beer on the wall"
end for
print "1 bottle of beer on the wall, 1 bottle of beer"
print "Take one down, pass it around, no bottles of beer on the wall!"
end function
accumulator = 0
for c in code
c = c.lower
if c == "h" then print "Hello World"
if c == "q" then print code
if c == "9" then sing
if c == "+" then accumulator = accumulator + 1
end for |
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
| #JavaScript | JavaScript | /**
* Take a ruleset and return a function which takes a string to which the rules
* should be applied.
* @param {string} ruleSet
* @returns {function(string): string}
*/
const markov = ruleSet => {
/**
* Split a string at an index
* @param {string} s The string to split
* @param {number} i The index number where to split.
* @returns {Array<string>}
*/
const splitAt = (s, i) => [s.slice(0, i), s.slice(i)];
/**
* Strip a leading number of chars from a string.
* @param {string} s The string to strip the chars from
* @param {string} strip A string who's length will determine the number of
* chars to strip.
* @returns {string}
*/
const stripLeading = (s, strip) => s.split('')
.filter((e, i) => i >= strip.length).join('');
/**
* Replace the substring in the string.
* @param {string} s The string to replace the substring in
* @param {string} find The sub-string to find
* @param {string} rep The replacement string
* @returns {string}
*/
const replace = (s, find, rep) => {
let result = s;
if (s.indexOf(find) >= 0) {
const a = splitAt(s, s.indexOf(find));
result = [a[0], rep, stripLeading(a[1], find)].join('');
}
return result;
};
/**
* Convert a ruleset string into a map
* @param {string} ruleset
* @returns {Map}
*/
const makeRuleMap = ruleset => ruleset.split('\n')
.filter(e => !e.startsWith('#'))
.map(e => e.split(' -> '))
.reduce((p,c) => p.set(c[0], c[1]), new Map());
/**
* Recursively apply the ruleset to the string.
* @param {Map} rules The rules to apply
* @param {string} s The string to apply the rules to
* @returns {string}
*/
const parse = (rules, s) => {
const o = s;
for (const [k, v] of rules.entries()) {
if (v.startsWith('.')) {
s = replace(s, k, stripLeading(v, '.'));
break;
} else {
s = replace(s, k, v);
if (s !== o) { break; }
}
}
return o === s ? s : parse(rules, s);
};
const ruleMap = makeRuleMap(ruleSet);
return str => parse(ruleMap, str)
};
const ruleset1 = `# 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`;
const ruleset2 = `# Slightly modified from the rules on Wikipedia
A -> apple
B -> bag
S -> .shop
T -> the
the shop -> my brother
a never used -> .terminating rule`;
const ruleset3 = `# 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`;
const ruleset4 = `### 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
_+_ -> `;
const ruleset5 = `# 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`;
console.log(markov(ruleset1)('I bought a B of As from T S.'));
console.log(markov(ruleset2)('I bought a B of As from T S.'));
console.log(markov(ruleset3)('I bought a B of As W my Bgage from T S.'));
console.log(markov(ruleset4)('_1111*11111_'));
console.log(markov(ruleset5)('000000A000000')); |
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.
| #Maple | Maple | num_times:=0:
baz := proc()
global num_times := num_times + 1;
error `if`(num_times <= 1, "U0", "U1");
end proc:
bar:=proc()
baz();
end proc;
foo:=proc()
local i;
for i from 0 to 1 do
bar();
end do;
end proc; |
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.
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | foo[] := Catch[ bar[1]; bar[2]; ]
bar[i_] := baz[i];
baz[i_] := Switch[i,
1, Throw["Exception U0 in baz"];,
2, Throw["Exception U1 in baz"];] |
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.
| #MATLAB_.2F_Octave | MATLAB / Octave | function exceptionsCatchNestedCall()
function foo()
try
bar(1);
bar(2);
catch
disp(lasterror);
rethrow(lasterror);
end
end
function bar(i)
baz(i);
end
function baz(i)
switch i
case 1
error('BAZ:U0','HAHAHAH');
case 2
error('BAZ:U1','AWWWW');
otherwise
disp 'I can''t do that Dave.';
end
end
foo();
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
| #Go | Go | package main
import "fmt"
func foo() int {
fmt.Println("let's foo...")
defer func() {
if e := recover(); e != nil {
fmt.Println("Recovered from", e)
}
}()
var a []int
a[12] = 0
fmt.Println("there's no point in going on.")
panic("never reached")
panic(fmt.Scan) // Can use any value, here a function!
}
func main() {
foo()
fmt.Println("glad that's over.")
} |
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
| #Haskell | Haskell | do {- ... -}
throwIO SomeException |
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
| #E | E | def ls := makeCommand("ls")
ls("-l")
def [results, _, _] := ls.exec(["-l"])
when (results) -> {
def [exitCode, out, err] := results
print(out)
} catch problem {
print(`failed to execute ls: $problem`)
} |
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
| #Emacs_Lisp | Emacs Lisp | (shell-command "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
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program factorial.s */
/* Constantes */
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessLargeNumber: .asciz "Number N to large. \n"
szMessNegNumber: .asciz "Number N is negative. \n"
szMessResult: .ascii "Resultat = " @ message result
sMessValeur: .fill 12, 1, ' '
.asciz "\n"
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
push {fp,lr} @ saves 2 registers
mov r0,#-5
bl factorial
mov r0,#10
bl factorial
mov r0,#20
bl factorial
100: @ standard end of the program
mov r0, #0 @ return code
pop {fp,lr} @restaur 2 registers
mov r7, #EXIT @ request to exit program
swi 0 @ perform the system call
/********************************************/
/* calculation */
/********************************************/
/* r0 contains number N */
factorial:
push {r1,r2,lr} @ save registres
cmp r0,#0
blt 99f
beq 100f
cmp r0,#1
beq 100f
bl calFactorial
cmp r0,#-1 @ overflow ?
beq 98f
ldr r1,iAdrsMessValeur
bl conversion10 @ call function with 2 parameter (r0,r1)
ldr r0,iAdrszMessResult
bl affichageMess @ display message
b 100f
98: @ display error message
ldr r0,iAdrszMessLargeNumber
bl affichageMess
b 100f
99: @ display error message
ldr r0,iAdrszMessNegNumber
bl affichageMess
100:
pop {r1,r2,lr} @ restaur registers
bx lr @ return
iAdrszMessNegNumber: .int szMessNegNumber
iAdrszMessLargeNumber: .int szMessLargeNumber
iAdrsMessValeur: .int sMessValeur
iAdrszMessResult: .int szMessResult
/******************************************************************/
/* calculation */
/******************************************************************/
/* r0 contains the number N */
calFactorial:
cmp r0,#1 @ N = 1 ?
bxeq lr @ yes -> return
push {fp,lr} @ save registers
sub sp,#4 @ 4 byte on the stack
mov fp,sp @ fp <- start address stack
str r0,[fp] @ fp contains N
sub r0,#1 @ call function with N - 1
bl calFactorial
cmp r0,#-1 @ error overflow ?
beq 100f @ yes -> return
ldr r1,[fp] @ load N
umull r0,r2,r1,r0 @ multiply result by N
cmp r2,#0 @ r2 is the hi rd if <> 0 overflow
movne r0,#-1 @ if overflow -1 -> r0
100:
add sp,#4 @ free 4 bytes on stack
pop {fp,lr} @ restau2 registers
bx lr @ return
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {fp,lr} /* save registres */
push {r0,r1,r2,r7} /* save others registers */
mov r2,#0 /* counter length */
1: /* loop length calculation */
ldrb r1,[r0,r2] /* read octet start position + index */
cmp r1,#0 /* if 0 its over */
addne r2,r2,#1 /* else add 1 in the length */
bne 1b /* and loop */
/* so here r2 contains the length of the message */
mov r1,r0 /* address message in r1 */
mov r0,#STDOUT /* code to write to the standard output Linux */
mov r7, #WRITE /* code call system "write" */
swi #0 /* call systeme */
pop {r0,r1,r2,r7} /* restaur others registers */
pop {fp,lr} /* restaur des 2 registres */
bx lr /* return */
/******************************************************************/
/* Converting a register to a decimal */
/******************************************************************/
/* r0 contains value and r1 address area */
conversion10:
push {r1-r4,lr} /* save registers */
mov r3,r1
mov r2,#10
1: @ start loop
bl divisionpar10 @ r0 <- dividende. quotient ->r0 reste -> r1
add r1,#48 @ digit
strb r1,[r3,r2] @ store digit on area
sub r2,#1 @ previous position
cmp r0,#0 @ stop if quotient = 0 */
bne 1b @ else loop
@ and move spaves in first on area
mov r1,#' ' @ space
2:
strb r1,[r3,r2] @ store space in area
subs r2,#1 @ @ previous position
bge 2b @ loop if r2 >= zéro
100:
pop {r1-r4,lr} @ restaur registres
bx lr @return
/***************************************************/
/* division par 10 signé */
/* Thanks to http://thinkingeek.com/arm-assembler-raspberry-pi/*
/* and http://www.hackersdelight.org/ */
/***************************************************/
/* r0 dividende */
/* r0 quotient */
/* r1 remainder */
divisionpar10:
/* r0 contains the argument to be divided by 10 */
push {r2-r4} /* save registers */
mov r4,r0
ldr r3, .Ls_magic_number_10 /* r1 <- magic_number */
smull r1, r2, r3, r0 /* r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0) */
mov r2, r2, ASR #2 /* r2 <- r2 >> 2 */
mov r1, r0, LSR #31 /* r1 <- r0 >> 31 */
add r0, r2, r1 /* r0 <- r2 + r1 */
add r2,r0,r0, lsl #2 /* r2 <- r0 * 5 */
sub r1,r4,r2, lsl #1 /* r1 <- r4 - (r2 * 2) = r4 - (r0 * 10) */
pop {r2-r4}
bx lr /* leave function */
.align 4
.Ls_magic_number_10: .word 0x66666667
|
http://rosettacode.org/wiki/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
| #Lua | Lua | number = {}
function number.pow( a, b )
local ret = 1
if b >= 0 then
for i = 1, b do
ret = ret * a.val
end
else
for i = b, -1 do
ret = ret / a.val
end
end
return ret
end
function number.New( v )
local num = { val = v }
local mt = { __pow = number.pow }
setmetatable( num, mt )
return num
end
x = number.New( 5 )
print( x^2 ) --> 25
print( number.pow( x, -4 ) ) --> 0.016 |
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.
| #Quackery | Quackery | ( --------------------- version #1 --------------------- )
[ not swap not 1 << |
]'[ swap peek do ] is if2.1 ( b b --> )
[ if2.1
[ [ say "true and true" ]
[ say "true and false" ]
[ say "false and true" ]
[ say "false and false" ] ]
cr ] is task.1 ( b b --> )
( --------------------- version #2 --------------------- )
[ not swap not 1 << |
dup 0 > iff ]else[ ]else[
1 - dup 0 > iff ]else[ ]else[
1 - 0 > iff ]else[ ]else[ ] is if2.2 ( b b --> )
[ if2.2 [ say "true and true" ]
else [ say "true and false" ]
else [ say "false and true" ]
else [ say "false and false" ]
cr ] is task.2 ( b b --> )
( ------------------------ demo ------------------------ )
true true task.1
true false task.1
false true task.1
false false task.1
cr
true true task.2
true false task.2
false true task.2
false false task.2
|
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.
| #R | R |
if2 <- function(condition1, condition2, both_true, first_true, second_true, both_false)
{
expr <- if(condition1)
{
if(condition2) both_true else first_true
} else if(condition2) second_true else both_false
eval(expr)
}
|
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
| #Sather | Sather | class MAIN is
main is
loop i ::= 1.upto!(100);
s:STR := "";
if i % 3 = 0 then s := "Fizz"; end;
if i % 5 = 0 then s := s + "Buzz"; end;
if s.length > 0 then
#OUT + s + "\n";
else
#OUT + i + "\n";
end;
end;
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.
| #Racket | Racket | #lang racket
;; Using the prime functions from:
(require math/number-theory)
(displayln "Show the first twenty primes.")
(next-primes 1 20)
(displayln "Show the primes between 100 and 150.")
;; Note that in each of the in-range filters I "add1" to the stop value, so that (in this case) 150 is
;; considered. I'm pretty sure it's not prime... but technology moves so fast nowadays that things
;; might have changed!
(for/list ((i (sequence-filter prime? (in-range 100 (add1 150))))) i)
(displayln "Show the number of primes between 7,700 and 8,000.")
;; (for/sum (...) 1) counts the values in a sequence
(for/sum ((i (sequence-filter prime? (in-range 7700 (add1 8000))))) 1)
(displayln "Show the 10,000th prime.")
(nth-prime (sub1 10000)) ; (nth-prime 0) => 2
;; If a languages in-built prime generator is extensible or is guaranteed to generate primes up to a
;; system limit, (2^31 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).
;;
;; Full details in:
;; [[http://docs.racket-lang.org/math/number-theory.html?q=prime%3F#%28part._primes%29]]
;; When reading the manual, note that "Integer" and "Natural" are unlimited (or bounded by whatever
;; big number representation there is (and the computational complexity of the work being asked).
(define 2^256 (expt 2 256))
2^256
(next-prime 2^256)
;; (Oh, and this is a 64-bit laptop, I left my 256-bit PC in the office.) |
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.
| #BASIC | BASIC | 0 ON NOT T GOTO 20 : FOR A = T TO L : B = PEEK(S + P) : ON C%(ASC(MID$(C$, A, T))) GOSUB 1, 2, 3, 4, 5, 8, 6, 7 : NEXT A : END
1 P = P + T : ON P < E GOTO 11 : O = 1E99
2 P = P - T : ON P > M GOTO 11 : O = 1E99
3 B = B + T : B = B - (B > U) * B : GOTO 9
4 B = B - T : B = B - (B < 0) * (B - U) : GOTO 9
5 PRINT CHR$(B); : RETURN
6 D = T : ON NOT B GOTO 10 : RETURN
7 D = M : ON NOT NOT B GOTO 10 : RETURN
8 GET B$ : B = LEN(B$) : IF B THEN B = ASC(B$)
9 POKE S + P, B : RETURN
10 FOR K = D TO 0 STEP 0 : A = A + D : K = K + D%(ASC(MID$(C$, A, T))) : NEXT K : RETURN
11 RETURN
20 HIMEM: 38401
21 LOMEM: 8185
22 DIM C%(14999) : CLEAR
23 POKE 105, PEEK(175)
24 POKE 106, PEEK(176)
25 POKE 107, PEEK(175)
26 POKE 108, PEEK(176)
27 POKE 109, PEEK(175)
28 POKE 110, PEEK(176)
29 HIMEM: 8192
30 T = 1
31 M = -1
32 S = 8192
33 E = 30000
34 U = 255
35 DIM C%(255), D%(255)
43 C%(ASC("+")) = 3
44 C%(ASC(",")) = 6
45 C%(ASC("-")) = 4
46 C%(ASC(".")) = 5
60 C%(ASC("<")) = 2
62 C%(ASC(">")) = 1
91 C%(ASC("[")) = 7
92 D%(ASC("[")) = 1
93 C%(ASC("]")) = 8
94 D%(ASC("]")) = -1
95 C$ = "++++++++[>++++[>++>+++>+++>+<<<<-]>+>->+>>+[<]<-]>>.>>---.+++++++..+++.>.<<-.>.+++.------.--------.>+.>++.+++."
98 L = LEN(C$)
99 GOTO |
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.
| #C.23 | C# | using System;
using System.Collections.Generic;
using System.Linq;
static class Program {
static Random Rng = new Random((int)DateTime.Now.Ticks);
static char NextCharacter(this Random self) {
const string AllowedChars = " ABCDEFGHIJKLMNOPQRSTUVWXYZ";
return AllowedChars[self.Next() % AllowedChars.Length];
}
static string NextString(this Random self, int length) {
return String.Join("", Enumerable.Repeat(' ', length)
.Select(c => Rng.NextCharacter()));
}
static int Fitness(string target, string current) {
return target.Zip(current, (a, b) => a == b ? 1 : 0).Sum();
}
static string Mutate(string current, double rate) {
return String.Join("", from c in current
select Rng.NextDouble() <= rate ? Rng.NextCharacter() : c);
}
static void Main(string[] args) {
const string target = "METHINKS IT IS LIKE A WEASEL";
const int C = 100;
const double P = 0.05;
// Start with a random string the same length as the target.
string parent = Rng.NextString(target.Length);
Console.WriteLine("START: {0,20} fitness: {1}",
parent, Fitness(target, parent));
int i = 0;
while (parent != target) {
// Create C mutated strings + the current parent.
var candidates = Enumerable.Range(0, C + 1)
.Select(n => n > 0 ? Mutate(parent, P) : parent);
// select the fittest
parent = candidates.OrderByDescending(c => Fitness(target, c)).First();
++i;
Console.WriteLine(" #{0,6} {1,20} fitness: {2}",
i, parent, Fitness(target, parent));
}
Console.WriteLine("END: #{0,6} {1,20}", i, parent);
}
} |
http://rosettacode.org/wiki/Fibonacci_sequence | Fibonacci sequence | The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion).
The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition:
Fn = Fn+2 - Fn+1, if n<0
support for negative n in the solution is optional.
Related tasks
Fibonacci n-step number sequences
Leonardo numbers
References
Wikipedia, Fibonacci number
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #Lang5 | Lang5 | [] '__A set : dip swap __A swap 2 compress collapse '__A set execute
__A -1 extract nip ; : nip swap drop ; : tuck swap over ;
: -rot rot rot ; : 0= 0 == ; : 1+ 1 + ; : 1- 1 - ; : sum '+ reduce ;
: bi 'keep dip execute ; : keep over 'execute dip ;
: fib dup 1 > if dup 1- fib swap 2 - fib + then ;
: fib dup 1 > if "1- fib" "2 - fib" bi + then ; |
http://rosettacode.org/wiki/Factors_of_an_integer | Factors of an integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Compute the factors of a positive integer.
These factors are the positive integers by which the number being factored can be divided to yield a positive integer result.
(Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty; this task does not require handling of either of these cases).
Note that every prime number has two factors: 1 and itself.
Related tasks
count in factors
prime decomposition
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
sequence: smallest number greater than previous term with exactly n divisors
| #X86_Assembly | X86 Assembly |
section .bss
factorArr resd 250 ;big buffer against seg fault
section .text
global _main
_main:
mov ebp, esp; for correct debugging
mov eax, 0x7ffffffe ;number of which we want to know the factors, max num this program works with
mov ebx, eax ;save eax
mov ecx, 1 ;n, factor we test for
mov [factorArr], dword 0
looping:
mov eax, ebx ;restore eax
xor edx, edx ;clear edx
div ecx
cmp edx, 0 ;test if our number % n == 0
jne next
mov edx, [factorArr] ;if yes, we increment the size of the array and append n
inc edx
mov [factorArr+edx*4], ecx ;appending n
mov [factorArr], edx ;storing the new size
next:
mov eax, ecx
cmp eax, ebx ;is n bigger then our number ?
jg end ;if yes we end
inc ecx
jmp looping
end:
mov ecx, factorArr ;pass arr address by ecx
xor eax, eax ;clear eax
mov esp, ebp ;garbage collecting
ret
|
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #Nanoquery | Nanoquery | import Nanoquery.IO
// a function to handle fatal errors
def fatal_error(errtext)
println "%" + errtext
println "usage: " + args[1] + " [filename.cp]"
exit(1)
end
// a function to perform '99 bottles of beer'
def bottles(n)
for bottles in range(n, 1, -1)
bottlestr = ""
if bottles = 1
bottlestr = "bottle"
else
bottlestr = "bottles"
end if
println (bottles + " " + bottlestr + " of beer on the wall")
println (bottles + " " + bottlestr + " of beer")
println "Take one down, pass it around."
if !(bottles = 2)
println (bottles - 1 + " bottles of beer on the wall.\n")
else
println "1 bottle of beer on the wall.\n"
end if
end for
end
// get a filename from the command line and read the file in
fname = null
source = null
try
fname = args[2]
source = new(Nanoquery.IO.File, fname).readAll()
catch
fatal_error("error while trying to read from specified file")
end
// define an int to be the accumulator
accum = 0
// interpreter the hq9+
for char in source
if char = "h"
println "hello world!"
else if char = "q"
println source
else if char = "9"
bottles(99)
else if char = "+"
accum += 1
end
end |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #NetRexx | NetRexx |
var program = "9hHqQ+"
var i = 0
proc bottle(n: int): string =
case n
of 0:
result = "No more bottles"
of 1:
result = "1 bottle"
else:
result = $n & " bottles"
proc ninetyNineBottles =
for n in countdown(99, 1):
echo bottle(n), " bottle of beer on the wall"
echo bottle(n), " bottle of beer"
echo "Take one down, pass it around"
echo bottle(n - 1), " of beer on the wall"
for token in items(program):
case token
of 'h', 'H':
echo("Hello, world!")
of 'q', 'Q':
echo(program)
of '9':
ninetyNineBottles()
of '+':
inc(i)
else:
echo("Unknown command: ", token)
|
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
| #jq | jq | jq -nrR --rawfile markov_rules markov_rules.txt -f program.jq markov_tests.txt
|
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
| #Julia | Julia | module MarkovAlgos
struct MarkovRule{F,T}
patt::F
repl::T
term::Bool
end
isterminating(r::MarkovRule) = r.term
Base.show(io::IO, rule::MarkovRule) =
print(io, rule.patt, " → ", isterminating(rule) ? "." : "", rule.repl)
function Base.convert(::Type{MarkovRule}, s::AbstractString)
rmatch = match(r"^(.+)\s+->\s*(\.)?(.*)?$", s)
if rmatch ≡ nothing || isempty(rmatch.captures)
throw(ParseError("not valid rule: " * s))
end
patt, term, repl = rmatch.captures
return MarkovRule(patt, repl ≢ nothing ? repl : "", term ≢ nothing)
end
function ruleset(file::Union{AbstractString,IO})
ruleset = Vector{MarkovRule}(0)
for line in eachline(file)
ismatch(r"(^#|^\s*$)", line) || push!(ruleset, MarkovRule(line))
end
return ruleset
end
apply(text::AbstractString, rule::MarkovRule) = replace(text, rule.patt, rule.repl)
function apply(file::Union{AbstractString,IO}, ruleset::AbstractVector{<:MarkovRule})
text = readstring(file)
redo = !isempty(text)
while redo
matchrule = false
for rule in ruleset
if contains(text, rule.patt)
matchrule = true
text = apply(text, rule)
redo = !isterminating(rule)
break
end
end
redo = redo && matchrule
end
return text
end
end # module MarkovAlgos |
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.
| #Nemerle | Nemerle | using System;
using System.Console;
namespace NestedExceptions
{
public class U0 : Exception
{
public this() {base()}
}
public class U1 : Exception
{
public this() {base()}
}
module NestedExceptions
{
Foo () : void
{
mutable call = 0;
repeat(2) {
try {
Bar(call);
}
catch {
|e is U0 => WriteLine("Exception U0 caught.")
}
finally {
call++;
}
}
}
Bar (call : int) : void
{
Baz(call)
}
Baz (call : int) : void // throw U0() on first call, U1() on second
{
unless (call > 0) throw U0();
when (call > 0) throw U1();
}
Main () : void
{
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.
| #Nim | Nim | type U0 = object of Exception
type U1 = object of Exception
proc baz(i) =
if i > 0: raise newException(U1, "Some error")
else: raise newException(U0, "Another error")
proc bar(i) =
baz(i)
proc foo() =
for i in 0..1:
try:
bar(i)
except U0:
echo "Function foo caught exception U0"
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.
| #Objective-C | Objective-C | @interface U0 : NSObject { }
@end
@interface U1 : NSObject { }
@end
@implementation U0
@end
@implementation U1
@end
void foo();
void bar(int i);
void baz(int i);
void foo() {
for (int i = 0; i <= 1; i++) {
@try {
bar(i);
} @catch (U0 *e) {
NSLog(@"Function foo caught exception U0");
}
}
}
void bar(int i) {
baz(i); // Nest those calls
}
void baz(int i) {
if (i == 0)
@throw [U0 new];
else
@throw [U1 new];
}
int main (int argc, const char * argv[]) {
@autoreleasepool {
foo();
}
return 0;
} |
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
| #HolyC | HolyC | try {
U8 *err = 'Error';
throw(err); // throw exception
} catch {
if (err == 'Error')
Print("Raised 'Error'");
PutExcept; // print the exception and stack trace
} |
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
| #Icon_and_Unicon | Icon and Unicon | import Exceptions
procedure main(A)
every i := !A do {
case Try().call{ write(g(i)) } of {
Try().catch(): {
x := Try().getException()
write(x.getMessage(), ":\n", x.getLocation())
}
}
}
end
procedure g(i)
if numeric(i) = 3 then Exception().throw("bad value of "||i)
return i
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
| #Erlang | Erlang | os:cmd("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
| #ERRE | ERRE | SHELL("DIR/W") |
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
| #Euphoria | Euphoria | -- system --
-- the simplest way --
-- system spawns a new shell so I/O redirection is possible --
system( "dir /w c:\temp\ " ) -- Microsoft --
system( "/bin/ls -l /tmp" ) -- Linux BSD OSX --
----
-- system_exec() --
-- system_exec does not spawn a new shell --
-- ( like bash or cmd.exe ) --
integer exit_code = 0
sequence ls_command = ""
ifdef UNIX or LINUX or OSX then
ls_command = "/bin/ls -l "
elsifdef WINDOWS then
ls_command = "dir /w "
end ifdef
exit_code = system_exec( ls_command )
if exit_code = -1 then
puts( STDERR, " could not execute " & ls_command & "\n" )
elsif exit_code = 0 then
puts( STDERR, ls_command & " succeeded\n")
else
printf( STDERR, "command %s failed with code %d\n", ls_command, exit_code)
end if |
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
| #ArnoldC | ArnoldC | LISTEN TO ME VERY CAREFULLY factorial
I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE n
GIVE THESE PEOPLE AIR
BECAUSE I'M GOING TO SAY PLEASE n
BULLS***
I'LL BE BACK 1
YOU HAVE NO RESPECT FOR LOGIC
HEY CHRISTMAS TREE product
YOU SET US UP @NO PROBLEMO
STICK AROUND n
GET TO THE CHOPPER product
HERE IS MY INVITATION product
YOU'RE FIRED n
ENOUGH TALK
GET TO THE CHOPPER n
HERE IS MY INVITATION n
GET DOWN @NO PROBLEMO
ENOUGH TALK
CHILL
I'LL BE BACK product
HASTA LA VISTA, BABY |
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
| #Lucid | Lucid | pow(n,x)
k = n fby k div 2;
p = x fby p*p;
y =1 fby if even(k) then y else y*p;
result y asa k eq 0;
end |
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
| #M2000_Interpreter | M2000 Interpreter |
Module Exponentiation {
\\ a variable can be any type except a string (no $ in name)
\\ variable b is long type.
\\ by default we pass by value arguments to a function
\\ to pass by reference we have to use & before name,
\\ in the signature and in the call
function pow(a, b as long) {
p=a-a ' make p same type as a
p++
if b>0 then for i=1& to b {p*=a}
=p
}
const fst$="{0::-32} {1}"
Document exp$
k= pow(11&, 5)
exp$=format$(fst$, k, type$(k)="Long")+{
}
l=pow(11, 5)
exp$=format$(fst$, l, type$(l)="Double")+{
}
m=pow(pi, 3)
exp$=format$(fst$, m, type$(m)="Decimal")+{
}
\\ send to clipboard
clipboard exp$
\\ send monospaced type text to console using cr char to change lines
Print #-2, exp$
Rem Report exp$ ' send to console using proportional spacing and justification
}
Exponentiation
|
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.
| #Racket | Racket |
#lang racket
;; define a new syntax
(define-syntax-rule
;; this is the new syntax we want, in sexpr syntax:
(if2 condition1isTrue condition2isTrue
bothConditionsAreTrue
firstConditionIsTrue
secondConditionIsTrue
noConditionIsTrue)
;; and this is the syntax that implements it:
(if condition1isTrue
(if condition2isTrue
bothConditionsAreTrue
firstConditionIsTrue)
(if condition2isTrue
secondConditionIsTrue
noConditionIsTrue)))
;; ... and that's all you need -- it now works:
(define (try x y)
(displayln (if2 (< x 10) (< y 10)
"Both small"
"First is small"
"Second is small"
"Neither is small")))
(try 1 1) ; Both small
(try 1 10) ; First is small
(try 10 1) ; Second is small
(try 10 10) ; Neither is small
|
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.
| #Raku | Raku | my &if2 = -> \a, \b, &x { my @*IF2 = ?a,?b; x }
my &if-both = -> &x { x if @*IF2 eq (True,True) }
my &if-first = -> &x { x if @*IF2 eq (True,False) }
my &if-second = -> &x { x if @*IF2 eq (False,True) }
my &if-neither = -> &x { x if @*IF2 eq (False,False)}
sub test ($a,$b) {
$_ = "G"; # Demo correct scoping of topic.
my $got = "o"; # Demo correct scoping of lexicals.
my $*got = "t"; # Demo correct scoping of dynamics.
if2 $a, $b, {
if-both { say "$_$got$*got both" }
if-first { say "$_$got$*got first" }
if-second { say "$_$got$*got second" }
if-neither { say "$_$got$*got neither" }
}
}
say test |$_ for 1,0 X 1,0; |
http://rosettacode.org/wiki/FizzBuzz | FizzBuzz | Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
| #Scala | Scala | object FizzBuzz extends App {
1 to 100 foreach { n =>
println((n % 3, n % 5) match {
case (0, 0) => "FizzBuzz"
case (0, _) => "Fizz"
case (_, 0) => "Buzz"
case _ => n
})
}
} |
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.
| #Raku | Raku | my @primes = lazy gather for 1 .. * { .take if .is-prime }
say "The first twenty primes:\n ", "[{@primes[^20].fmt("%d", ', ')}]";
say "The primes between 100 and 150:\n ", "[{@primes.&between(100, 150).fmt("%d", ', ')}]";
say "The number of primes between 7,700 and 8,000:\n ", +@primes.&between(7700, 8000);
say "The 10,000th prime:\n ", @primes[9999];
sub between (@p, $l, $u) {
gather for @p { .take if $l < $_ < $u; last if $_ >= $u }
} |
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.
| #BBC_BASIC | BBC BASIC | bf$ = "++++++++[>++++[>++>+++>+++>+<<<<-]>+>->+>>+[<]<-]>>.>" + \
\ ">---.+++++++..+++.>.<<-.>.+++.------.--------.>+.>++.+++."
PROCbrainfuck(bf$)
END
DEF PROCbrainfuck(b$)
LOCAL B%, K%, M%, P%
DIM M% LOCAL 65535
B% = 1 : REM pointer to string
K% = 0 : REM bracket counter
P% = 0 : REM pointer to memory
FOR B% = 1 TO LEN(b$)
CASE MID$(b$,B%,1) OF
WHEN "+": M%?P% += 1
WHEN "-": M%?P% -= 1
WHEN ">": P% += 1
WHEN "<": P% -= 1
WHEN ".": VDU M%?P%
WHEN ",": M%?P% = GET
WHEN "[":
IF M%?P% = 0 THEN
K% = 1
B% += 1
WHILE K%
IF MID$(b$,B%,1) = "[" THEN K% += 1
IF MID$(b$,B%,1) = "]" THEN K% -= 1
B% += 1
ENDWHILE
ENDIF
WHEN "]":
IF M%?P% <> 0 THEN
K% = -1
B% -= 1
WHILE K%
IF MID$(b$,B%,1) = "[" THEN K% += 1
IF MID$(b$,B%,1) = "]" THEN K% -= 1
B% -= 1
ENDWHILE
ENDIF
ENDCASE
NEXT
ENDPROC
|
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.
| #C.2B.2B | C++ | #include <string>
#include <cstdlib>
#include <iostream>
#include <cassert>
#include <algorithm>
#include <vector>
#include <ctime>
std::string allowed_chars = " ABCDEFGHIJKLMNOPQRSTUVWXYZ";
// class selection contains the fitness function, encapsulates the
// target string and allows access to it's length. The class is only
// there for access control, therefore everything is static. The
// string target isn't defined in the function because that way the
// length couldn't be accessed outside.
class selection
{
public:
// this function returns 0 for the destination string, and a
// negative fitness for a non-matching string. The fitness is
// calculated as the negated sum of the circular distances of the
// string letters with the destination letters.
static int fitness(std::string candidate)
{
assert(target.length() == candidate.length());
int fitness_so_far = 0;
for (int i = 0; i < target.length(); ++i)
{
int target_pos = allowed_chars.find(target[i]);
int candidate_pos = allowed_chars.find(candidate[i]);
int diff = std::abs(target_pos - candidate_pos);
fitness_so_far -= std::min(diff, int(allowed_chars.length()) - diff);
}
return fitness_so_far;
}
// get the target string length
static int target_length() { return target.length(); }
private:
static std::string target;
};
std::string selection::target = "METHINKS IT IS LIKE A WEASEL";
// helper function: cyclically move a character through allowed_chars
void move_char(char& c, int distance)
{
while (distance < 0)
distance += allowed_chars.length();
int char_pos = allowed_chars.find(c);
c = allowed_chars[(char_pos + distance) % allowed_chars.length()];
}
// mutate the string by moving the characters by a small random
// distance with the given probability
std::string mutate(std::string parent, double mutation_rate)
{
for (int i = 0; i < parent.length(); ++i)
if (std::rand()/(RAND_MAX + 1.0) < mutation_rate)
{
int distance = std::rand() % 3 + 1;
if(std::rand()%2 == 0)
move_char(parent[i], distance);
else
move_char(parent[i], -distance);
}
return parent;
}
// helper function: tell if the first argument is less fit than the
// second
bool less_fit(std::string const& s1, std::string const& s2)
{
return selection::fitness(s1) < selection::fitness(s2);
}
int main()
{
int const C = 100;
std::srand(time(0));
std::string parent;
for (int i = 0; i < selection::target_length(); ++i)
{
parent += allowed_chars[std::rand() % allowed_chars.length()];
}
int const initial_fitness = selection::fitness(parent);
for(int fitness = initial_fitness;
fitness < 0;
fitness = selection::fitness(parent))
{
std::cout << parent << ": " << fitness << "\n";
double const mutation_rate = 0.02 + (0.9*fitness)/initial_fitness;
std::vector<std::string> childs;
childs.reserve(C+1);
childs.push_back(parent);
for (int i = 0; i < C; ++i)
childs.push_back(mutate(parent, mutation_rate));
parent = *std::max_element(childs.begin(), childs.end(), less_fit);
}
std::cout << "final string: " << parent << "\n";
} |
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
| #langur | langur | val .fibonacci = f if(.x < 2: .x ; self(.x - 1) + self(.x - 2))
writeln map .fibonacci, series 2..20 |
http://rosettacode.org/wiki/Factors_of_an_integer | Factors of an integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Compute the factors of a positive integer.
These factors are the positive integers by which the number being factored can be divided to yield a positive integer result.
(Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty; this task does not require handling of either of these cases).
Note that every prime number has two factors: 1 and itself.
Related tasks
count in factors
prime decomposition
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
sequence: smallest number greater than previous term with exactly n divisors
| #XPL0 | XPL0 | include c:\cxpl\codes;
int N0, N, F;
[N0:= 1;
repeat IntOut(0, N0); Text(0, " = ");
F:= 2; N:= N0;
repeat if rem(N/F) = 0 then
[if N # N0 then Text(0, " * ");
IntOut(0, F);
N:= N/F;
]
else F:= F+1;
until F>N;
if N0=1 then IntOut(0, 1); \1 = 1
CrLf(0);
N0:= N0+1;
until KeyHit;
] |
http://rosettacode.org/wiki/Factors_of_an_integer | Factors of an integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Compute the factors of a positive integer.
These factors are the positive integers by which the number being factored can be divided to yield a positive integer result.
(Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty; this task does not require handling of either of these cases).
Note that every prime number has two factors: 1 and itself.
Related tasks
count in factors
prime decomposition
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
sequence: smallest number greater than previous term with exactly n divisors
| #Yabasic | Yabasic |
sub printFactors(n)
if n < 1 then return 0 : fi
print n, " =>",
for i = 1 to n / 2
if mod(n, i) = 0 then print i, " "; : fi
next i
print n
end sub
printFactors(11)
printFactors(21)
printFactors(32)
printFactors(45)
printFactors(67)
printFactors(96)
print
end
|
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #Nim | Nim |
var program = "9hHqQ+"
var i = 0
proc bottle(n: int): string =
case n
of 0:
result = "No more bottles"
of 1:
result = "1 bottle"
else:
result = $n & " bottles"
proc ninetyNineBottles =
for n in countdown(99, 1):
echo bottle(n), " bottle of beer on the wall"
echo bottle(n), " bottle of beer"
echo "Take one down, pass it around"
echo bottle(n - 1), " of beer on the wall"
for token in items(program):
case token
of 'h', 'H':
echo("Hello, world!")
of 'q', 'Q':
echo(program)
of '9':
ninetyNineBottles()
of '+':
inc(i)
else:
echo("Unknown command: ", token)
|
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #NS-HUBASIC | NS-HUBASIC | 10 INPUT "INPUT HQ9+ CODE: ",I$
20 B$="S"
30 W$=" ON THE WALL"
40 FOR I=1 TO LEN(I$)
50 C$=MID$(I$,I,1)
60 IF C$="H" THEN PRINT "HELLO, WORLD!"
70 IF C$="Q" THEN PRINT I$
80 A=A+(C$="+")
90 IF C$<>"9" GOTO 200
100 FOR B=99 TO 1 STEP -1
110 IF B=1 THEN B$=""
120 PRINT B " BOTTLE"B$" OF BEER" W$
130 PRINT B " BOTTLE"B$" OF BEER"
140 PRINT "TAKE ONE DOWN,"
150 PRINT "PASS IT AROUND"
160 IF B=2 THEN B$=""
170 IF B=1 THEN B$="S"
180 PRINT B-1 " BOTTLE"B$" OF BEER" W$
190 NEXT
200 NEXT |
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
| #Kotlin | Kotlin | // version 1.1.51
import java.io.File
import java.util.regex.Pattern
/* rulesets assumed to be separated by a blank line in file */
fun readRules(path: String): List<List<String>> {
val ls = System.lineSeparator()
return File(path).readText().split("$ls$ls").map { it.split(ls) }
}
/* tests assumed to be on consecutive lines */
fun readTests(path: String) = File(path).readLines()
fun main(args: Array<String>) {
val rules = readRules("markov_rules.txt")
val tests = readTests("markov_tests.txt")
val pattern = Pattern.compile("^([^#]*?)\\s+->\\s+(\\.?)(.*)")
for ((i, origTest) in tests.withIndex()) {
val captures = mutableListOf<List<String>>()
for (rule in rules[i]) {
val m = pattern.matcher(rule)
if (m.find()) {
val groups = List<String>(m.groupCount()) { m.group(it + 1) }
captures.add(groups)
}
}
var test = origTest
do {
val copy = test
var redo = false
for (c in captures) {
test = test.replace(c[0], c[2])
if (c[1] == ".") break
if (test != copy) { redo = true; break }
}
}
while (redo)
println("$origTest\n$test\n")
}
} |
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.
| #OCaml | OCaml | exception U0
exception U1
let baz i =
raise (if i = 0 then U0 else U1)
let bar i = baz i (* Nest those calls *)
let foo () =
for i = 0 to 1 do
try
bar i
with U0 ->
print_endline "Function foo caught exception U0"
done
let () = 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.
| #Oforth | Oforth | Exception Class new: U0
Exception Class new: U1
: baz ifZero: [ "First call" U0 throw ] else: [ "Second call" U1 throw ] ;
: bar baz ;
: foo
| e |
try: e [ 0 bar ] when: [ e isKindOf(U0) ifTrue: [ "Catched" .cr ] else: [ e throw ] ]
try: e [ 1 bar ] when: [ e isKindOf(U0) ifTrue: [ "Catched" .cr ] else: [ e throw ] ]
"Done" . ; |
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
| #J | J | pickyPicky =: verb define
if. y-:'bad argument' do.
throw.
else.
'thanks!'
end.
)
tryThis =: verb define
try.
pickyPicky y
catcht.
'Uh oh!'
end.
)
tryThis 'bad argument'
Uh oh! |
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
| #Java | Java | //Checked exception
public class MyException extends Exception {
//Put specific info in here
}
//Unchecked exception
public class MyRuntimeException extends RuntimeException {} |
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
| #F.23 | F# | System.Diagnostics.Process.Start("cmd", "/c 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
| #Factor | Factor | "ls" run-process wait-for-process |
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
| #Fantom | Fantom |
class Main
{
public static Void main ()
{
p := Process (["ls"])
p.run
}
}
|
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
| #Arturo | Arturo | factorial: $[n][
if? n>0 [n * factorial n-1]
else [1]
] |
http://rosettacode.org/wiki/Exponentiation_operator | Exponentiation operator | Most programming languages have a built-in implementation of exponentiation.
Task
Re-implement integer exponentiation for both intint and floatint as both a procedure, and an operator (if your language supports operator definition).
If the language supports operator (or procedure) overloading, then an overloaded form should be provided for both intint and floatint variants.
Related tasks
Exponentiation order
arbitrary-precision integers (included)
Exponentiation with infix operators in (or operating on) the base
| #M4 | M4 | define(`power',`ifelse($2,0,1,`eval($1*$0($1,decr($2)))')')
power(2,10) |
http://rosettacode.org/wiki/Exponentiation_operator | Exponentiation operator | Most programming languages have a built-in implementation of exponentiation.
Task
Re-implement integer exponentiation for both intint and floatint as both a procedure, and an operator (if your language supports operator definition).
If the language supports operator (or procedure) overloading, then an overloaded form should be provided for both intint and floatint variants.
Related tasks
Exponentiation order
arbitrary-precision integers (included)
Exponentiation with infix operators in (or operating on) the base
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | exponentiation[x_,y_Integer]:=Which[y>0,Times@@ConstantArray[x,y],y==0,1,y<0,1/exponentiation[x,-y]]
CirclePlus[x_,y_Integer]:=exponentiation[x,y] |
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.
| #REXX | REXX | if2( some-expression-that-results-in-a-boolean-value, some-other-expression-that-results-in-a-boolean-value)
/*this part is a REXX comment*/ /*could be a DO structure.*/
select /*↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓*/ /*↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓*/
when if.11 /*{condition 1 & 2 are true}*/ then perform-a-REXX-statement
when if.10 /*{condition 1 is true}*/ then " " " "
when if.01 /*{condition 2 is true}*/ then " " " "
when if.00 /*{no condition is true}*/ then " " " "
end
/*an example of a DO structure for the first clause: */
when if.11 /*{condition 1 & 2 are true}*/ then do; x=12; y=length(y); 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.
| #Ring | Ring |
# Project : Extend your language
see "a = 1, b = 1 => "
test(1, 1)
see "a = 1, b = 0 => "
test(1, 0)
see "a = 0, b = 1 => "
test(0, 1)
see "a = 0, b = 0 => "
test(0, 0)
see nl
func test(a,b)
if a > 0 and b > 0
see "both positive"
but a > 0
see "first positive"
but b > 0
see "second positive"
but a < 1 and b < 1
see "neither positive"
ok
see nl
|
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
| #Scheme | Scheme | (do ((i 1 (+ i 1)))
((> i 100))
(display
(cond ((= 0 (modulo i 15)) "FizzBuzz")
((= 0 (modulo i 3)) "Fizz")
((= 0 (modulo i 5)) "Buzz")
(else i)))
(newline)) |
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.
| #Red | Red |
Red [Description: "Prime checker/generator/counter"]
context [
poke noprime: make bitset! 3 1 true
top: 2
noprimes: function [n [integer!] /extern top][
either top < n [
n: n + 100
r: 2
while [r * r <= n][
repeat q n / r - 1 [poke noprime q + 1 * r true]
until [not pick noprime r: r + 1]
]
self/top: n
][top]
]
set 'prime? func [
"Check whether number is prime or return required prime"
n [integer!]
/next "Return next closest prime to given number"
/last "Return last closest prime to given number, or number itself if prime"
/Nth "Return Nth prime"
][
noprimes case [
Nth [to integer! n * 12 ]
next [n + 100]
true [n]
]
case [
next [until [not noprime/(n: n + 1)] n]
last [while [noprime/:n][n: n - 1] n]
Nth [
cnt: i: 0
while [cnt < n][
until [not noprime/(i: i + 1)]
cnt: cnt + 1
]
i
]
true [not noprime/:n]
]
]
set 'primes function [
"Return (number of) primes in given range"
n [integer!]
/from "Start considering primes from `start`"
start "Default 1"
/list "First argument is interpreted as number of primes to list"
/count "Count primes from `start`"
][
start: any [start 1]
either list [
noprimes start + (n * 12)
][
set [start n] sort reduce [n start]
noprimes start + n
]
case [
list [
start: start - 1
collect [
loop n [
until [not noprime/(start: start + 1)]
keep start
]
]
]
count [
cnt: 0
repeat i n - start + 1 [
j: i - 1
if not noprime/(j + start) [cnt: cnt + 1]
]
cnt
]
true [
collect [
repeat i n - start + 1 [
j: i - 1
if not noprime/(j: j + start) [keep j]
]
]
]
]
]
]
|
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.
| #BCPL | BCPL | get "libhdr"
manifest
$( bfeof = 0
$)
let reads(v) be
$( let ch = ?
v%0 := 0
ch := rdch()
until ch = '*N' do
$( v%0 := v%0 + 1
v%(v%0) := ch
ch := rdch()
$)
$)
let contains(str, ch) = valof
$( for i = 1 to str%0 do
if ch = str%i then resultis true
resultis false
$)
let readbf(file, v) = valof
$( let i, ch = 1, ?
let curin = input()
v%0 := 0
selectinput(file)
ch := rdch()
until ch = endstreamch do
$( if contains("+-<>.,[]", ch) then
$( v%i := ch
i := i + 1
$)
ch := rdch()
$)
v%i := 0
endread()
selectinput(curin)
resultis i + 1
$)
let bfout(ch) be wrch(ch=10 -> '*N', ch)
let bfin() = valof
$( let ch = rdch()
resultis ch = endstreamch -> bfeof, ch
$)
let scan(v, i, dir) = valof
$( let d = 1
until d = 0 do
$( i := i + dir
if v%i = 0 then
$( writes("Unbalanced brackets*N")
resultis 0
$)
if v%i = '[' then d := d + dir
if v%i = ']' then d := d - dir
$)
resultis i
$)
let run(v, m) be
$( let i = 1
until v%i = 0 do
$( switchon v%i into
$( case '+': v%m := v%m + 1 ; endcase
case '-': v%m := v%m - 1 ; endcase
case '>': m := m + 1 ; endcase
case '<': m := m - 1 ; endcase
case '.': bfout(v%m) ; endcase
case ',': v%m := bfin() ; endcase
case '[':
if v%m = 0 then i := scan(v, i, 1)
if i = 0 then return
endcase
case ']':
unless v%m = 0 do i := scan(v, i, -1)
if i = 0 then return
endcase
$)
i := i + 1
$)
$)
let start() be
$( let fname = vec 63
let file = ?
writes("Filename? ")
reads(fname)
file := findinput(fname)
test file = 0 then
writes("Cannot open file.*N")
else
$( let mvec = getvec(maxvec())
let m = readbf(file, mvec)
run(mvec, m)
freevec(mvec)
$)
$) |
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.
| #Ceylon | Ceylon | import ceylon.random {
DefaultRandom
}
shared void run() {
value mutationRate = 0.05;
value childrenPerGeneration = 100;
value target = "METHINKS IT IS LIKE A WEASEL";
value alphabet = {' ', *('A'..'Z')};
value random = DefaultRandom();
value randomLetter => random.nextElement(alphabet);
function fitness(String a, String b) =>
count {for([c1, c2] in zipPairs(a, b)) c1 == c2};
function mutate(String string) =>
String {
for(letter in string)
if(random.nextFloat() < mutationRate)
then randomLetter
else letter
};
function makeCopies(String string) =>
{for(i in 1..childrenPerGeneration) mutate(string)};
function chooseFittest(String+ children) =>
children
.map((String element) => element->fitness(element, target))
.max(increasingItem)
.key;
variable value parent = String {for(i in 1..target.size) randomLetter};
variable value generationCount = 0;
function display() => print("``generationCount``: ``parent``");
display();
while(parent != target) {
parent = chooseFittest(parent, *makeCopies(parent));
generationCount++;
display();
}
print("mutated into target in ``generationCount`` generations!");
} |
http://rosettacode.org/wiki/Fibonacci_sequence | Fibonacci sequence | The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion).
The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition:
Fn = Fn+2 - Fn+1, if n<0
support for negative n in the solution is optional.
Related tasks
Fibonacci n-step number sequences
Leonardo numbers
References
Wikipedia, Fibonacci number
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #Lasso | Lasso |
define fibonacci(n::integer) => {
#n < 1 ? return false
local(
swap = 0,
n1 = 0,
n2 = 1
)
loop(#n) => {
#swap = #n1 + #n2;
#n2 = #n1;
#n1 = #swap;
}
return #n1
}
fibonacci(0) //->output false
fibonacci(1) //->output 1
fibonacci(2) //->output 1
fibonacci(3) //->output 2
|
http://rosettacode.org/wiki/Factors_of_an_integer | Factors of an integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Compute the factors of a positive integer.
These factors are the positive integers by which the number being factored can be divided to yield a positive integer result.
(Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty; this task does not require handling of either of these cases).
Note that every prime number has two factors: 1 and itself.
Related tasks
count in factors
prime decomposition
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
sequence: smallest number greater than previous term with exactly n divisors
| #zkl | zkl | fcn f(n){ (1).pump(n.toFloat().sqrt(), List,
'wrap(m){((n % m)==0) and T(m,n/m) or Void.Skip}) }
fcn g(n){ [[(m); [1..n.toFloat().sqrt()],'{n%m==0}; '{T(m,n/m)} ]] } // list comprehension |
http://rosettacode.org/wiki/Factors_of_an_integer | Factors of an integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Compute the factors of a positive integer.
These factors are the positive integers by which the number being factored can be divided to yield a positive integer result.
(Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty; this task does not require handling of either of these cases).
Note that every prime number has two factors: 1 and itself.
Related tasks
count in factors
prime decomposition
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
sequence: smallest number greater than previous term with exactly n divisors
| #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 INPUT "Enter a number or 0 to exit: ";n
20 IF n=0 THEN STOP
30 PRINT "Factors of ";n;": ";
40 FOR i=1 TO n
50 IF FN m(n,i)=0 THEN PRINT i;" ";
60 NEXT i
70 DEF FN m(a,b)=a-INT (a/b)*b |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #OCaml | OCaml | let hq9p line =
let accumulator = ref 0 in
for i = 0 to (String.length line - 1) do
match line.[i] with
| 'h' | 'H' -> print_endline "Hello, world!"
| 'q' | 'Q' -> print_endline line
| '9' -> beer 99
| '+' -> incr accumulator
done |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #PARI.2FGP | PARI/GP | beer(n)={
if(n == 1,
print("1 bottle of beer on the wall");
print("1 bottle of beer");
print("Take one down and pass it around");
print("No bottles of beer on the wall")
,
print(n" bottles of beer on the wall");
print(n" bottles of beer");
print("Take one down and pass it around");
print(n-1," bottles of beer on the wall\n");
beer(n-1)
)
};
HQ9p(s)={
my(accum=0,v=Vec(s));
for(i=1,#s,
if(v[i] == "H" || v[i] == "h", print("Hello, world!"); next);
if(v[i] == "Q" || v[i] == "q", print(s); next);
if(v[i] == "9", beer(99); next);
if(v[i] == "+", accum++, error("Nasal demons"))
)
}; |
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
| #Lua | Lua | -- utility method to escape punctuation
function normalize(str)
local result = str:gsub("(%p)", "%%%1")
-- print(result)
return result
end
-- utility method to split string into lines
function get_lines(str)
local t = {}
for line in str:gmatch("([^\n\r]*)[\n\r]*") do
table.insert(t, line)
end
return t
end
local markov = {}
local MARKOV_RULE_PATTERN = "(.+)%s%-%>%s(%.?)(.*)"
function markov.rule(pattern,replacement,terminating)
return {
pattern = pattern,
replacement = replacement,
terminating = (terminating == ".")
}, normalize(pattern)
end
function markov.make_rules(sample)
local lines = get_lines(sample)
local rules = {}
local finders = {}
for i,line in ipairs(lines) do
if not line:find("^#") then
s,e,pat,term,rep = line:find(MARKOV_RULE_PATTERN)
if s then
r, p = markov.rule(pat,rep,term)
rules[p] = r
table.insert(finders, p)
end
end
end
return {
rules = rules,
finders = finders
}
end
function markov.execute(state, sample_input)
local rules, finders = state.rules, state.finders
local found = false -- did we find any rule?
local terminate = false
repeat
found = false
for i,v in ipairs(finders) do
local found_now = false -- did we find this rule?
if sample_input:find(v) then
found = true
found_now = true
end
sample_input = sample_input:gsub(v, rules[v].replacement, 1)
-- handle terminating rules
if found_now then
if rules[v].terminating then terminate = true end
break
end
end
until not found or terminate
return sample_input
end
------------------------------------------
------------------------------------------
local 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
]]
local 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
]]
local 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
]]
local 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
_+_ ->
]]
local 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
]]
local text1 = "I bought a B of As from T S."
local text2 = "I bought a B of As W my Bgage from T S."
local text3 = '_1111*11111_'
local text4 = '000000A000000'
------------------------------------------
------------------------------------------
function do_markov(rules, input, output)
local m = markov.make_rules(rules)
input = markov.execute(m, input)
assert(input == output)
print(input)
end
do_markov(grammar1, text1, 'I bought a bag of apples from my brother.')
do_markov(grammar2, text1, 'I bought a bag of apples from T shop.')
-- stretch goals
do_markov(grammar3, text2, 'I bought a bag of apples with my money from T shop.')
do_markov(grammar4, text3, '11111111111111111111')
do_markov(grammar5, text4, '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.
| #Oz | Oz | declare
proc {Foo}
for I in 1..2 do
try
{Bar I}
catch u0 then {System.showInfo "Procedure Foo caught exception u0"}
end
end
end
proc {Bar I} {Baz I} end
proc {Baz I}
if I == 1 then
raise u0 end
else
raise u1 end
end
end
in
{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.
| #PARI.2FGP | PARI/GP | call = 0;
U0() = error("x = ", 1, " should not happen!");
U1() = error("x = ", 2, " should not happen!");
baz(x) = if(x==1, U0(), x==2, U1());x;
bar() = baz(call++);
foo() = if(!call, iferr(bar(), E, printf("Caught exception, call=%d",call)), bar()) |
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
| #JavaScript | JavaScript | function doStuff() {
throw new Error('Not implemented!');
} |
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
| #jq | jq | try FILTER catch CATCHER |
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
| #Forth | Forth | s" 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
| #Fortran | Fortran |
program SystemTest
integer :: i
call execute_command_line ("ls", exitstat=i)
end program SystemTest
|
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
| #AsciiDots | AsciiDots |
/---------*--~-$#-&
| /--;---\| [!]-\
| *------++--*#1/
| | /1#\ ||
[*]*{-}-*~<+*?#-.
*-------+-</
\-#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
| #Maxima | Maxima | "^^^"(a, n) := block(
[p: 1],
while n > 0 do (
if oddp(n) then p: p * a,
a: a * a,
n: quotient(n, 2)
),
p
)$
infix("^^^")$
2 ^^^ 10;
1024
2.5 ^^^ 10;
9536.7431640625 |
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
| #.D0.9C.D0.9A-61.2F52 | МК-61/52 | С/П x^y С/П |
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.
| #Ruby | Ruby | # Define a class which always returns itself for everything
class HopelesslyEgocentric
def method_missing(what, *args) self end
end
def if2(cond1, cond2)
if cond1 and cond2
yield
HopelesslyEgocentric.new
elsif cond1
Class.new(HopelesslyEgocentric) do
def else1; yield; HopelesslyEgocentric.new end
end.new
elsif cond2
Class.new(HopelesslyEgocentric) do
def else2; yield; HopelesslyEgocentric.new end
end.new
else
Class.new(HopelesslyEgocentric) do
def neither; yield end
end.new
end
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.
| #Rust | Rust | #![allow(unused_variables)]
macro_rules! if2 {
($cond1: expr, $cond2: expr
=> $both:expr
=> $first: expr
=> $second:expr
=> $none:expr)
=> {
match ($cond1, $cond2) {
(true, true) => $both,
(true, _ ) => $first,
(_ , true) => $second,
_ => $none
}
}
}
fn main() {
let i = 1;
let j = 2;
if2!(i > j, i + j >= 3
=> {
// code blocks and statements can go here also
let k = i + j;
println!("both were true")
}
=> println!("the first was true")
=> println!("the second was true")
=> println!("neither were true")
)
} |
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
| #Sed | Sed | #n
# doesn't work if there's no input
# initialize counters (0 = empty) and value
s/.*/ 0/
: loop
# increment counters, set carry
s/^\(a*\) \(b*\) \([0-9][0-9]*\)/\1a \2b \3@/
# propagate carry
: carry
s/ @/ 1/
s/9@/@0/
s/8@/9/
s/7@/8/
s/6@/7/
s/5@/6/
s/4@/5/
s/3@/4/
s/2@/3/
s/1@/2/
s/0@/1/
/@/b carry
# save state
h
# handle factors
s/aaa/Fizz/
s/bbbbb/Buzz/
# strip value if any factor
/z/s/[0-9]//g
# strip counters and spaces
s/[ab ]//g
# output
p
# restore state
g
# roll over counters
s/aaa//
s/bbbbb//
# loop until value = 100
/100/q
b loop |
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.
| #REXX | REXX | /*REXX program calculates and displays primes using an extendible prime number generator*/
parse arg f .; if f=='' then f= 20 /*allow specifying number for 1 ──► F.*/
_i= ' (inclusive) '; _b= 'between '; _tnp= 'the number of primes' _b; _tn= 'the primes'
call primes f; do j=1 for f; $= $ @.j; end /*j*/
say 'the first ' f " primes are: " $
say
call primes -150; do j=100 to 150; if !.j==1 then $= $ j; end /*j*/
say _tn _b '100 to 150' _i "are: " $
say
call primes -8000; do j=7700 to 8000; if !.j==1 then $= $ j; end /*j*/
say _tnp '7,700 and 8,000' _i "is: " words($)
say
call primes 10000
say 'the 10,000th prime is: ' @.10000
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
primes: procedure expose !. @. $ #; parse arg H,,$; Hneg= H<0; H= abs(H)
if symbol('#')=="LIT" then call .primI /*1st time here? Then initialize stuff*/
if Hneg then if H<=@.# then return /*do we have a high enough P already?*/
else nop /*this is used to match the above THEN.*/
else if H<=# then return /*are there enough primes currently ? */
/* [↓] gen more primes within range. */
do j=@.#+2 by 2; parse var j '' -1 _ /*find primes until have H Primes. */
if _==5 then iterate /*is the right─most digit a 5 (five)? */
if j// 3==0 then iterate /*is J divisible by three? (& etc.)*/
if j// 7==0 then iterate; if j//11==0 then iterate; if j//13==0 then iterate
if j//17==0 then iterate; if j//19==0 then iterate; if j//23==0 then iterate
if j//29==0 then iterate; if j//31==0 then iterate; if j//37==0 then iterate
if j//41==0 then iterate; if j//43==0 then iterate; if j//47==0 then iterate
if j//53==0 then iterate; if j//59==0 then iterate; if j//61==0 then iterate
if j//67==0 then iterate; if j//71==0 then iterate; if j//73==0 then iterate
if j//79==0 then iterate; if j//83==0 then iterate; if j//89==0 then iterate
if j//97==0 then iterate; if j//101==0 then iterate; if j//103==0 then iterate
x= j; r= 0; q= 1; do while q<=x; q= q*4; end /*R: the sqrt(J).*/
do while q>1; q=q%4; _=x-r-q; r=r%2; if _>=0 then do;x=_;r=r+q; end; end
do [email protected] while @.k<=r /*÷ by the known odd primes (hardcoded)*/
if j//@.k==0 then iterate j /*J ÷ by a prime? Then not prime. ___*/
end /*k*/ /* [↑] divide by odd primes up to √ J */
#= # + 1 /*bump the number of primes found. */
@.#= j; !.j= 1 /*assign to sparse array; prime²; P#.*/
if Hneg then if H<=@.# then leave /*is this a high enough prime? */
else nop /*used to match the above THEN. */
else if H<=# then leave /*have enough primes been generated? */
end /*j*/ /* [↑] keep generating until enough. */
return /*return to invoker with more primes. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
.primI: !.=0; @.=0; /*!.x= a prime or not; @.n= Nth prime.*/
L= 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103
do #=1 for words(L); p= word(L, #); @.#= p; !.p=1; end /*#*/
#= # - 1; @.lowP= #; return /*#: # primes; @.lowP: start of ÷ */ |
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.
| #Brainf.2A.2A.2A | Brainf*** |
>>>,[->+>+<<]>>[-<<+>>]>++++[<++++++++>-]<+<[->>+>>+<<<<]>>>>[-<<<<+>>
>>]<<<[->>+>+<<<]>>>[-<<<+>>>]<<[>[->+<]<[-]]>[-]>[[-]<<<<->-<[->>+>>+
<<<<]>>>>[-<<<<+>>>>]<<<[->>+>+<<<]>>>[-<<<+>>>]<<[>[->+<]<[-]]>[-]>]<
<<<[->>+<<]>[->+<]>[[-]<<<[->+>+<<]>>[-<<+>>]>++++++[<+++++++>-]<+<[->
>>+>+<<<<]>>>>[-<<<<+>>>>]<<<[->+>>+<<<]>>>[-<<<+>>>]<[<[->>+<<]>[-]]<
[-]>>[[-]<<<<->-<[->>>+>+<<<<]>>>>[-<<<<+>>>>]<<<[->+>>+<<<]>>>[-<<<+>
>>]<[<[->>+<<]>[-]]<[-]>>]<<<<[->>>+<<<]>[->>+<<]>+>[<->[-]]<[<<<<+>>>
>[-]]<<<[->+>+<<]>>[-<<+>>]>+++++[<+++++++++>-]<<[->>>+>+<<<<]>>>>[-<<
<<+>>>>]<<<[->+>>+<<<]>>>[-<<<+>>>]<[<[->>+<<]>[-]]<[-]>>[[-]<<<<->-<[
->>>+>+<<<<]>>>>[-<<<<+>>>>]<<<[->+>>+<<<]>>>[-<<<+>>>]<[<[->>+<<]>[-]
]<[-]>>]<<<<[->>>+<<<]>[->>+<<]>+>[<->[-]]<[<<<<++>>>>[-]]<<<[->+>+<<]
>>[-<<+>>]>++++++[<++++++++++>-]<<[->>>+>+<<<<]>>>>[-<<<<+>>>>]<<<[->+
>>+<<<]>>>[-<<<+>>>]<[<[->>+<<]>[-]]<[-]>>[[-]<<<<->-<[->>>+>+<<<<]>>>
>[-<<<<+>>>>]<<<[->+>>+<<<]>>>[-<<<+>>>]<[<[->>+<<]>[-]]<[-]>>]<<<<[->
>>+<<<]>[->>+<<]>+>[<->[-]]<[<<<<+++>>>>[-]]<<<[->+>+<<]>>[-<<+>>]>+++
+++[<++++++++++>-]<++<[->>>+>+<<<<]>>>>[-<<<<+>>>>]<<<[->+>>+<<<]>>>[-
<<<+>>>]<[<[->>+<<]>[-]]<[-]>>[[-]<<<<->-<[->>>+>+<<<<]>>>>[-<<<<+>>>>
]<<<[->+>>+<<<]>>>[-<<<+>>>]<[<[->>+<<]>[-]]<[-]>>]<<<<[->>>+<<<]>[->>
+<<]>+>[<->[-]]<[<<<<++++>>>>[-]]<<<[->+>+<<]>>[-<<+>>]>+++++[<+++++++
++>-]<+<[->>>+>+<<<<]>>>>[-<<<<+>>>>]<<<[->+>>+<<<]>>>[-<<<+>>>]<[<[->
>+<<]>[-]]<[-]>>[[-]<<<<->-<[->>>+>+<<<<]>>>>[-<<<<+>>>>]<<<[->+>>+<<<
]>>>[-<<<+>>>]<[<[->>+<<]>[-]]<[-]>>]<<<<[->>>+<<<]>[->>+<<]>+>[<->[-]
]<[<<<<+++++>>>>[-]]<<<[->+>+<<]>>[-<<+>>]>++++[<+++++++++++>-]<<[->>>
+>+<<<<]>>>>[-<<<<+>>>>]<<<[->+>>+<<<]>>>[-<<<+>>>]<[<[->>+<<]>[-]]<[-
]>>[[-]<<<<->-<[->>>+>+<<<<]>>>>[-<<<<+>>>>]<<<[->+>>+<<<]>>>[-<<<+>>>
]<[<[->>+<<]>[-]]<[-]>>]<<<<[->>>+<<<]>[->>+<<]>+>[<->[-]]<[<<<<++++++
>>>>[-]]<<<[->+>+<<]>>[-<<+>>]>+++++++[<+++++++++++++>-]<<[->>>+>+<<<<
]>>>>[-<<<<+>>>>]<<<[->+>>+<<<]>>>[-<<<+>>>]<[<[->>+<<]>[-]]<[-]>>[[-]
<<<<->-<[->>>+>+<<<<]>>>>[-<<<<+>>>>]<<<[->+>>+<<<]>>>[-<<<+>>>]<[<[->
>+<<]>[-]]<[-]>>]<<<<[->>>+<<<]>[->>+<<]>+>[<->[-]]<[<<<<+++++++>>>>[-
]]<<<[->+>+<<]>>[-<<+>>]>+++++++[<+++++++++++++>-]<++<[->>>+>+<<<<]>>>
>[-<<<<+>>>>]<<<[->+>>+<<<]>>>[-<<<+>>>]<[<[->>+<<]>[-]]<[-]>>[[-]<<<<
->-<[->>>+>+<<<<]>>>>[-<<<<+>>>>]<<<[->+>>+<<<]>>>[-<<<+>>>]<[<[->>+<<
]>[-]]<[-]>>]<<<<[->>>+<<<]>[->>+<<]>+>[<->[-]]<[<<<<++++++++>>>>[-]]<
<<<[->>+>+<<<]>>>[-<<<+>>>]<[<<<[->>>>>>>>>+<+<<<<<<<<]>>>>>>>>[-<<<<<
<<<+>>>>>>>>]<<<<<<<[->>>>>>>>>+<<+<<<<<<<]>>>>>>>[-<<<<<<<+>>>>>>>]>[
<[->>>>>+<<<<<]>[->>>>>+<<<<<]>[->>>>>+<<<<<]>>>+>-]>>[-]<[->+<]<<[[-<
<<<<+>>>>>]<<<<<-]<<<<<<<<+>[-]>>[-]]<,[->+>+<<]>>[-<<+>>]>++++[<+++++
+++>-]<+<[->>+>>+<<<<]>>>>[-<<<<+>>>>]<<<[->>+>+<<<]>>>[-<<<+>>>]<<[>[
->+<]<[-]]>[-]>[[-]<<<<->-<[->>+>>+<<<<]>>>>[-<<<<+>>>>]<<<[->>+>+<<<]
>>>[-<<<+>>>]<<[>[->+<]<[-]]>[-]>]<<<<[->>+<<]>[->+<]>]<<<<<[-][->>>>>
>>>>+<<<<<<+<<<]>>>[-<<<+>>>]>>>>>>[<[->>>>>+<<<<<]>[->>>>>+<<<<<]>>>>
+>-]>>[[-<+<+>>]<<[->>+<<]>[-<+>[<->[-]]]<[[-]<[->+>+<<]>>[-<<+>>]<<[[
-<<<<<+>>>>>]>[-<<<<<+>>>>>]<<<<<<-]<<<<<<<<[-]>>>>>>>>>[-<<<<<<<<<+>>
>>>>>>>]<<<<<<<<<<[->>>>>>>>>>+<+<<<<<<<<<]>>>>>>>>>[-<<<<<<<<<+>>>>>>
>>>]>[<[->>>>>+<<<<<]>[->>>>>+<<<<<]>>>>+>-]>>>+<<<<[[-<<<<<+>>>>>]<<<
<<-]<<<<<<<<+[->>>>>>>>>+<<<<<<+<<<]>>>[-<<<+>>>]>>>>>>[<[->>>>>+<<<<<
]>[->>>>>+<<<<<]>>>>+>-][-]]>>[-<+<+>>]<<[->>+<<]>[-[-<+>[<->[-]]]]<[[
-]<[->+>+<<]>>[-<<+>>]<<[[-<<<<<+>>>>>]>[-<<<<<+>>>>>]<<<<<<-]<<<<<<<<
[-]>>>>>>>>>[-<<<<<<<<<+>>>>>>>>>]<<<<<<<<<<[->>>>>>>>>>+<+<<<<<<<<<]>
>>>>>>>>[-<<<<<<<<<+>>>>>>>>>]>[<[->>>>>+<<<<<]>[->>>>>+<<<<<]>>>>+>-]
>>>-<<<<[[-<<<<<+>>>>>]<<<<<-]<<<<<<<<+[->>>>>>>>>+<<<<<<+<<<]>>>[-<<<
+>>>]>>>>>>[<[->>>>>+<<<<<]>[->>>>>+<<<<<]>>>>+>-][-]]>>[-<+<+>>]<<[->
>+<<]>[-[-[-<+>[<->[-]]]]]<[[-]<[->+>+<<]>>[-<<+>>]<<[[-<<<<<+>>>>>]>[
-<<<<<+>>>>>]<<<<<<-]<<<<<<<<[-]>>>>>>>>>[-<<<<<<<<<+>>>>>>>>>]<<<<<<<
<<<->+[->>>>>>>>>+<<<<<<+<<<]>>>[-<<<+>>>]>>>>>>[<[->>>>>+<<<<<]>[->>>
>>+<<<<<]>>>>+>-][-]]>>[-<+<+>>]<<[->>+<<]>[-[-[-[-<+>[<->[-]]]]]]<[[-
]<[->+>+<<]>>[-<<+>>]<<[[-<<<<<+>>>>>]>[-<<<<<+>>>>>]<<<<<<-]<<<<<<<<[
-]>>>>>>>>>[-<<<<<<<<<+>>>>>>>>>]<<<<<<<<<<+>+[->>>>>>>>>+<<<<<<+<<<]>
>>[-<<<+>>>]>>>>>>[<[->>>>>+<<<<<]>[->>>>>+<<<<<]>>>>+>-][-]]>>[-<+<+>
>]<<[->>+<<]>[-[-[-[-[-<+>[<->[-]]]]]]]<[[-]<[->+>+<<]>>[-<<+>>]<<[[-<
<<<<+>>>>>]>[-<<<<<+>>>>>]<<<<<<-]<<<<<<<<[-]>>>>>>>>>[-<<<<<<<<<+>>>>
>>>>>]<<<<<<<<<<[->>>>>>>>>>+<+<<<<<<<<<]>>>>>>>>>[-<<<<<<<<<+>>>>>>>>
>]>[<[->>>>>+<<<<<]>[->>>>>+<<<<<]>>>>+>-]>>>.<<<<[[-<<<<<+>>>>>]<<<<<
-]<<<<<<<<+[->>>>>>>>>+<<<<<<+<<<]>>>[-<<<+>>>]>>>>>>[<[->>>>>+<<<<<]>
[->>>>>+<<<<<]>>>>+>-][-]]>>[-<+<+>>]<<[->>+<<]>[-[-[-[-[-[-<+>[<->[-]
]]]]]]]<[[-]<[->+>+<<]>>[-<<+>>]<<[[-<<<<<+>>>>>]>[-<<<<<+>>>>>]<<<<<<
-]<<<<<<<<[-]>>>>>>>>>[-<<<<<<<<<+>>>>>>>>>]<<<<<<<<<<[->>>>>>>>>>+<+<
<<<<<<<<]>>>>>>>>>[-<<<<<<<<<+>>>>>>>>>]>[<[->>>>>+<<<<<]>[->>>>>+<<<<
<]>>>>+>-]>>>,<<<<[[-<<<<<+>>>>>]<<<<<-]<<<<<<<<+[->>>>>>>>>+<<<<<<+<<
<]>>>[-<<<+>>>]>>>>>>[<[->>>>>+<<<<<]>[->>>>>+<<<<<]>>>>+>-][-]]>>[-<+
<+>>]<<[->>+<<]>[-[-[-[-[-[-[-<+>[<->[-]]]]]]]]]<[[-]<[->+>+<<]>>[-<<+
>>]<<[[-<<<<<+>>>>>]>[-<<<<<+>>>>>]<<<<<<-]<<<<<<<<[-]>>>>>>>>>[-<<<<<
<<<<+>>>>>>>>>]<<<<<<<<<<[->>>>>>>>>>+<+<<<<<<<<<]>>>>>>>>>[-<<<<<<<<<
+>>>>>>>>>]>[<[->>>>>+<<<<<]>[->>>>>+<<<<<]>>>>+>-]>>>[-<<<+>+>>]<<[->
>+<<]<<[[-<<<<<+>>>>>]>[-<<<<<+>>>>>]<<<<<<-]>[-<<<<<<+>>>>>>]>+<<<<<<
<[>>>>>>>-<<<<<<<[-]]<<<[->>>>>>>>>+<<<<<<+<<<]>>>[-<<<+>>>]>>>>>>[<[-
>>>>>+<<<<<]>[->>>>>+<<<<<]>[->>>>>+<<<<<]>>>+>-]>[[-]<+[<[->>>>>+<<<<
<]>[->>>>>+<<<<<]>>>>+>>>[->>+<<<+>]<[->+<]>>>[-[-[-[-[-[-[-<<<+>>>[<<
<->>>[-]]]]]]]]]<<<[<+>[-]]>[->>+<<<+>]<[->+<]>>>[-[-[-[-[-[-[-[-<<<+>
>>[<<<->>>[-]]]]]]]]]]<<<[<->[-]]<]>[-]]<<[->>>>>+<<<<<]>>>>>+>[-]]>>[
-<+<+>>]<<[->>+<<]>[-[-[-[-[-[-[-[-<+>[<->[-]]]]]]]]]]<[[-][-]<[->+>+<
<]>>[-<<+>>]<<[[-<<<<<+>>>>>]>[-<<<<<+>>>>>]<<<<<<-]<<<<<<<<[-]>>>>>>>
>>[-<<<<<<<<<+>>>>>>>>>]<<<<<<<<<<[->>>>>>>>>>+<+<<<<<<<<<]>>>>>>>>>[-
<<<<<<<<<+>>>>>>>>>]>[<[->>>>>+<<<<<]>[->>>>>+<<<<<]>>>>+>-]>>>[-<<<+>
+>>]<<[->>+<<]<<[[-<<<<<+>>>>>]>[-<<<<<+>>>>>]<<<<<<-]>[-<<<<<<+>>>>>>
]<<<<<<[->>>>>>>+<<<<<<<]<<<[->>>>>>>>>+<<<<<<+<<<]>>>[-<<<+>>>]>>>>>>
[<[->>>>>+<<<<<]>[->>>>>+<<<<<]>[->>>>>+<<<<<]>>>+>-]>[[-]<+[<[-<<<<<+
>>>>>]>[-<<<<<+>>>>>]<<<<<<->>>[->>+<<<+>]<[->+<]>>>[-[-[-[-[-[-[-<<<+
>>>[<<<->>>[-]]]]]]]]]<<<[<->[-]]>[->>+<<<+>]<[->+<]>>>[-[-[-[-[-[-[-[
-<<<+>>>[<<<->>>[-]]]]]]]]]]<<<[<+>[-]]<]>[-]]<<[->>>>>+<<<<<]>>>>>+>[
-]]>>]
|
http://rosettacode.org/wiki/Evolutionary_algorithm | Evolutionary algorithm | Starting with:
The target string: "METHINKS IT IS LIKE A WEASEL".
An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent).
A fitness function that computes the ‘closeness’ of its argument to the target string.
A mutate function that given a string and a mutation rate returns a copy of the string, with some characters probably mutated.
While the parent is not yet the target:
copy the parent C times, each time allowing some random probability that another character might be substituted using mutate.
Assess the fitness of the parent and all the copies to the target and make the most fit string the new parent, discarding the others.
repeat until the parent converges, (hopefully), to the target.
See also
Wikipedia entry: Weasel algorithm.
Wikipedia entry: Evolutionary algorithm.
Note: to aid comparison, try and ensure the variables and functions mentioned in the task description appear in solutions
A cursory examination of a few of the solutions reveals that the instructions have not been followed rigorously in some solutions. Specifically,
While the parent is not yet the target:
copy the parent C times, each time allowing some random probability that another character might be substituted using mutate.
Note that some of the the solutions given retain characters in the mutated string that are correct in the target string. However, the instruction above does not state to retain any of the characters while performing the mutation. Although some may believe to do so is implied from the use of "converges"
(:* repeat until the parent converges, (hopefully), to the target.
Strictly speaking, the new parent should be selected from the new pool of mutations, and then the new parent used to generate the next set of mutations with parent characters getting retained only by not being mutated. It then becomes possible that the new set of mutations has no member that is fitter than the parent!
As illustration of this error, the code for 8th has the following remark.
Create a new string based on the TOS, changing randomly any characters which
don't already match the target:
NOTE: this has been changed, the 8th version is completely random now
Clearly, this algo will be applying the mutation function only to the parent characters that don't match to the target characters!
To ensure that the new parent is never less fit than the prior parent, both the parent and all of the latest mutations are subjected to the fitness test to select the next parent.
| #Clojure | Clojure | (def c 100) ;number of children in each generation
(def p 0.05) ;mutation probability
(def target "METHINKS IT IS LIKE A WEASEL")
(def tsize (count target))
(def alphabet " ABCDEFGHIJLKLMNOPQRSTUVWXYZ") |
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
| #Latitude | Latitude | fibo := {
takes '[n].
if { n <= 1. } then {
n.
} else {
fibo (n - 1) + fibo (n - 2).
}.
}. |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #Pascal | Pascal | program HQ9;
procedure runCode(code: string);
var
c_len, i, bottles: Integer;
accumulator: Cardinal;
begin
c_len := Length(code);
accumulator := 0;
for i := 1 to c_len do
begin
case code[i] of
'Q','q':
writeln(code);
'H','h':
Writeln('Hello, world!');
'9':
begin
bottles := 99;
repeat
writeln(bottles,' bottles of beer on the wall');
writeln(bottles,' bottles of beer');
Writeln('Take one down, pass it around');
dec(bottles);
writeln(bottles,' bottles of beer on the wall',#13#10);
until (bottles <= 0);
end;
'+':
inc(accumulator);
end;
end;
end;
BEGIN
runCode('QqQh');
//runCode('HQ9+');// output to long
END. |
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
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | markov[ruleset_, text_] :=
Module[{terminating = False, output = text,
rules = StringCases[
ruleset, {StartOfLine ~~ pattern : Except["\n"] .. ~~
" " | "\t" .. ~~ "->" ~~ " " | "\t" .. ~~ dot : "" | "." ~~
replacement : Except["\n"] .. ~~ EndOfLine :> {pattern,
replacement, dot == "."}}]},
While[! terminating, terminating = True;
Do[If[! StringFreeQ[output, rule[[1]]],
output = StringReplace[output, rule[[1]] -> rule[[2]]];
If[! rule[[3]], terminating = False]; Break[]], {rule, rules}]];
output]; |
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
| #.D0.9C.D0.9A-61.2F52 | МК-61/52 | 9 П4
КИП4 [x] П7 Вx {x} П8
ИП8 ИПE * П8 {x} x=0 08
П5 ИП9 П1 lg [x] 10^x П3
ИП1 П2
Сx П6
ИП2 ИП7 - x=0 70
ИП9 ^ lg [x] 1 + ИП5 - 10^x / [x]
ИП6 ИП8 x#0 50 lg [x] 1 + + 10^x *
ИП9 ИП6 10^x П7 / {x} ИП7 * +
ИП8 ИП7 * + П9
С/П БП 00
x>=0 80
КИП6
ИП2 ИПE / [x] П2
x=0 26
КИП5
ИП1 ИП3 / {x} ИП3 * П1
ИП3 ИПE / [x] П3
x=0 22
ИП4 ИП0 - 9 - x=0 02 С/П |
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.
| #Pascal | Pascal | sub foo {
foreach (0..1) {
eval { bar($_) };
if ($@ =~ /U0/) { print "Function foo caught exception U0\n"; }
else { die; } # propagate the exception
}
}
sub bar {
baz(@_); # Nest those calls
}
sub baz {
my $i = shift;
die ($i ? "U1" : "U0");
}
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.
| #Perl | Perl | sub foo {
foreach (0..1) {
eval { bar($_) };
if ($@ =~ /U0/) { print "Function foo caught exception U0\n"; }
else { die; } # propagate the exception
}
}
sub bar {
baz(@_); # Nest those calls
}
sub baz {
my $i = shift;
die ($i ? "U1" : "U0");
}
foo(); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.