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/Execute_SNUSP | Execute SNUSP | Execute SNUSP is an implementation of SNUSP.
Other implementations of SNUSP.
RCSNUSP
SNUSP
An implementation need only properly implement the Core SNUSP instructions ('$', '\', '/', '+', '-', '<', '>', ',', '.', '!', and '?'). Modular SNUSP ('#', '@') and Bloated SNUSP (':', ';', '%', and '&') are also allowed, but not required. Any extra characters that you implement should be noted in the description of your implementation. Any cell size is allowed, EOF support is optional, as is whether you have bounded or unbounded memory.
| #Racket | Racket | class SNUSP {
has @!inst-pointer;
has @!call-stack;
has @!direction;
has @!memory;
has $!mem-pointer;
method run ($code) {
init();
my @code = pad( |$code.lines );
for @code.kv -> $r, @l {
my $index = @l.grep( /'$'/, :k );
if $index {
@!inst-pointer = $r, $index;
last
}
}
loop {
my $instruction = @code[@!inst-pointer[0]; @!inst-pointer[1]];
given $instruction {
when '>' { $!mem-pointer++ }
when '<' { $!mem-pointer-- }
when '+' { @!memory[$!mem-pointer]++ }
when '-' { @!memory[$!mem-pointer]-- }
when '.' { print @!memory[$!mem-pointer].chr }
when ',' { @!memory[$!mem-pointer] = $*IN.getc.ord }
when '/' { @!direction = @!direction.reverse «*» -1 }
when '\\' { @!direction = @!direction.reverse }
when '!' { nexti() }
when '?' { nexti() unless @!memory[$!mem-pointer] }
when '@' { @!call-stack.push: @!inst-pointer.Array }
when '#' {
last unless +@!call-stack;
@!inst-pointer = |@!call-stack.pop;
nexti();
}
}
nexti();
last if @!inst-pointer[0] > +@code or
@!inst-pointer[1] > +@code[0];
}
sub init () {
@!inst-pointer = 0, 0;
@!direction = 0, 1;
$!mem-pointer = 0;
@!memory = ()
}
sub nexti () { @!inst-pointer Z+= @!direction }
sub pad ( *@lines ) {
my $max = max @lines».chars;
my @pad = @lines.map: $max - *.chars;
map -> $i { flat @lines[$i].comb, ' ' xx @pad[$i] }, ^@lines;
}
}
}
# TESTING
my $hw = q:to/END/;
/++++!/===========?\>++.>+.+++++++..+++\
\+++\ | /+>+++++++>/ /++++++++++<<.++>./
$+++/ | \+++++++++>\ \+++++.>.+++.-----\
\==-<<<<+>+++/ /=.>.+>.--------.-/
END
my $snusp = SNUSP.new;
$snusp.run($hw) |
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.
| #J | J | if2=: 2 :0
'`b1 b2'=. n
m@.(b1 + 2 * b2) f.
) |
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.
| #Java | Java |
public class If2 {
public static void if2(boolean firstCondition, boolean secondCondition,
Runnable bothTrue, Runnable firstTrue, Runnable secondTrue, Runnable noneTrue) {
if (firstCondition)
if (secondCondition)
bothTrue.run();
else firstTrue.run();
else if (secondCondition)
secondTrue.run();
else noneTrue.run();
}
}
|
http://rosettacode.org/wiki/Exponentiation_order | Exponentiation order | This task will demonstrate the order of exponentiation (xy) when there are multiple exponents.
(Many programming languages, especially those with extended─precision integer arithmetic, usually support one of **, ^, ↑ or some such for exponentiation.)
Task requirements
Show the result of a language's evaluation of multiple exponentiation (either as an integer or floating point).
If your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it.
Using whatever operator or syntax your language supports (if any), show the results in three lines (with identification):
5**3**2
(5**3)**2
5**(3**2)
If there are other methods (or formats) of multiple exponentiations, show them as well.
See also
MathWorld entry: exponentiation
Related tasks
exponentiation operator
arbitrary-precision integers (included)
Exponentiation with infix operators in (or operating on) the base
| #Wren | Wren | import "/fmt" for Fmt
var ops = [ "5**3**2", "(5**3)**2", "5**(3**2)" ]
var results = [ 5.pow(3).pow(2), (5.pow(3)).pow(2), 5.pow(3.pow(2)) ]
for (i in 0...ops.count) {
System.print("%(Fmt.s(-9, ops[i])) -> %(results[i])")
} |
http://rosettacode.org/wiki/Exponentiation_order | Exponentiation order | This task will demonstrate the order of exponentiation (xy) when there are multiple exponents.
(Many programming languages, especially those with extended─precision integer arithmetic, usually support one of **, ^, ↑ or some such for exponentiation.)
Task requirements
Show the result of a language's evaluation of multiple exponentiation (either as an integer or floating point).
If your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it.
Using whatever operator or syntax your language supports (if any), show the results in three lines (with identification):
5**3**2
(5**3)**2
5**(3**2)
If there are other methods (or formats) of multiple exponentiations, show them as well.
See also
MathWorld entry: exponentiation
Related tasks
exponentiation operator
arbitrary-precision integers (included)
Exponentiation with infix operators in (or operating on) the base
| #zkl | zkl | println("5 ^ 3 ^ 2 = %,d".fmt((5.0).pow((3.0).pow(2))));
println("(5 ^ 3) ^ 2 = %,d".fmt((5.0).pow(3).pow(2)));
println("5 ^ (3 ^ 2) = %,d".fmt((5.0).pow((3.0).pow(2)))); |
http://rosettacode.org/wiki/FizzBuzz | FizzBuzz | Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
| #REALbasic | REALbasic |
let fizzbuzz i =>
switch (i mod 3, i mod 5) {
| (0, 0) => "FizzBuzz"
| (0, _) => "Fizz"
| (_, 0) => "Buzz"
| _ => string_of_int i
};
for i in 1 to 100 {
print_endline (fizzbuzz i)
};
|
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.
| #jq | jq | # Recent versions of jq include the following definition:
# until/2 loops until cond is satisfied,
# and emits the value satisfying the condition:
def until(cond; next):
def _until:
if cond then . else (next|_until) end;
_until;
def count(cond): reduce .[] as $x (0; if $x|cond then .+1 else . end); |
http://rosettacode.org/wiki/Fibonacci_sequence | Fibonacci sequence | The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion).
The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition:
Fn = Fn+2 - Fn+1, if n<0
support for negative n in the solution is optional.
Related tasks
Fibonacci n-step number sequences
Leonardo numbers
References
Wikipedia, Fibonacci number
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #IDL | IDL | function fib,n
if n lt 3 then return,1L else return, fib(n-1)+fib(n-2)
end |
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
| #Ring | Ring |
nArray = list(100)
n = 45
j = 0
for i = 1 to n
if n % i = 0 j = j + 1 nArray[j] = i ok
next
see "Factors of " + n + " = "
for i = 1 to j
see "" + nArray[i] + " "
next
|
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #E | E | open unsafe.console char unsafe.cell imperative
eval src = eval' src
where eval' [] = ()
eval' (x::xs) | be 'H' = h() `seq` eval' xs
| be 'Q' = q() `seq` eval' xs
| be '9' = n() `seq` eval' xs
| be '+' = p() `seq` eval' xs
| else = fail ("Unrecognized " ++ x)
where r = ref 0
be c = char.upper x == c
h () = writen "Hello, world!"
q () = writen src
p () = r.+
n () = bottles [99,98..1]
where bottles [] = ()
bottles (x::xs) = rec write
(show x) " bottles of beer of the wall\r\n"
(show x) " bottles of beer\r\n"
"Take one down, pass it around\r\n"
`seq` bottles xs |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #Ela | Ela | open unsafe.console char unsafe.cell imperative
eval src = eval' src
where eval' [] = ()
eval' (x::xs) | be 'H' = h() `seq` eval' xs
| be 'Q' = q() `seq` eval' xs
| be '9' = n() `seq` eval' xs
| be '+' = p() `seq` eval' xs
| else = fail ("Unrecognized " ++ x)
where r = ref 0
be c = char.upper x == c
h () = writen "Hello, world!"
q () = writen src
p () = r.+
n () = bottles [99,98..1]
where bottles [] = ()
bottles (x::xs) = rec write
(show x) " bottles of beer of the wall\r\n"
(show x) " bottles of beer\r\n"
"Take one down, pass it around\r\n"
`seq` bottles xs |
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
| #APL | APL | markov←{
trim←{(~(∧\∨⌽∘(∧\)∘⌽)⍵∊⎕UCS 9 32)/⍵}
rules←(~rules∊⎕UCS 10 13)⊆rules←80 ¯1 ⎕MAP ⍺
rules←('#'≠⊃¨rules)/rules
rules←{
norm←' '@(9=⎕UCS)⊢⍵
spos←⍸' -> '⍷norm
pat←trim spos↑⍵
repl←trim(spos+2)↓⍵
term←'.'=⊃repl
term pat(term↓repl)
}¨rules
apply←{
0=⍴rule←⍸∨/¨(2⊃¨⍺)⍷¨⊂⍵:⍵
term pat repl←⊃⍺[⊃rule]
idx←(⊃⍸pat⍷⍵)-1
⍺ ∇⍣(~term)⊢(idx↑⍵),repl,(idx+≢pat)↓⍵
}
rules apply ⍵
} |
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
| #AutoHotkey | AutoHotkey | ;---------------------------------------------------------------------------
; Markov Algorithm.ahk
; by wolf_II
;---------------------------------------------------------------------------
; interpreter for a Markov Algorithm
;---------------------------------------------------------------------------
;---------------------------------------------------------------------------
AutoExecute: ; auto-execute section of the script
;---------------------------------------------------------------------------
#SingleInstance, Force ; only one instance allowed
#NoEnv ; don't check empty variables
StartupDir := A_WorkingDir ; remember startup directory
SetWorkingDir, %A_ScriptDir% ; change directoy
StringCaseSense, On ; case sensitive comparisons
;-----------------------------------------------------------------------
AppName := "Markov Algorithm"
Gosub, GuiCreate
Gui, Show,, %AppName%
Return
;---------------------------------------------------------------------------
GuiCreate: ; create the GUI
;---------------------------------------------------------------------------
; GUI options
Gui, -MinimizeBox
Gui, Add, Edit, y0 h0 ; catch the focus
; Ruleset
Gui, Add, GroupBox, w445 h145 Section, Ruleset
Gui, Add, Edit, xs+15 ys+20 w300 r8 vRuleset
Gui, Add, Button, x+15 w100, Load Ruleset
Gui, Add, Button, wp, Save Ruleset
Gui, Add, Button, w30, 1
Gui, Add, Button, x+5 wp, 2
Gui, Add, Button, x+5 wp, 3
Gui, Add, Button, xs+330 y+6 wp, 4
Gui, Add, Button, x+5 wp, 5
; String
Gui, Add, GroupBox, xs w445 h75 Section, String
Gui, Add, Edit, xs+15 ys+20 w300 vString
Gui, Add, Button, x+15 w100, Apply Ruleset
Gui, Add, Button, xp wp Hidden, Stop
Gui, Add, CheckBox, xs+15 yp+30 vSingleStepping, Single Stepping?
; Output
Gui, Add, GroupBox, xs w445 h235 Section, Output
Gui, Add, Edit, xs+15 ys+20 w415 r15 ReadOnly vOutput HwndhOut
Return
;---------------------------------------------------------------------------
GuiClose:
;---------------------------------------------------------------------------
ExitApp
Return
;---------------------------------------------------------------------------
ButtonLoadRuleset: ; load ruleset from file
;---------------------------------------------------------------------------
Gui, +OwnDialogs
FileSelectFile, RulesetFile,,, Load Ruleset, *.markov
If Not SubStr(RulesetFile, -6) = ".markov"
RulesetFile .= ".markov"
If FileExist(RulesetFile) {
FileRead, Ruleset, %RulesetFile%
GuiControl,, Ruleset, %Ruleset%
} Else
MsgBox, 16, Error - %AppName%, File not found:`n`n"%RulesetFile%"
Return
;---------------------------------------------------------------------------
ButtonSaveRuleset: ; save ruleset to file
;---------------------------------------------------------------------------
Gui, +OwnDialogs
Gui, Submit, NoHide
FileSelectFile, RulesetFile, S16,, Save Ruleset, *.markov
If Not SubStr(RulesetFile, -6) = ".markov"
RulesetFile .= ".markov"
FileDelete, %RulesetFile%
FileAppend, %Ruleset%, %RulesetFile%
Gui, Show
Return
_
;---------------------------------------------------------------------------
Button1: ; http://rosettacode.org/wiki/Execute_a_Markov_algorithm#Ruleset_1
;---------------------------------------------------------------------------
GuiControl,, Output ; clear output
GuiControl,, String, I bought a B of As from T S.
GuiControl,, Ruleset,
(LTrim
# 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
)
Return
;---------------------------------------------------------------------------
Button2: ; http://rosettacode.org/wiki/Execute_a_Markov_algorithm#Ruleset_2
;---------------------------------------------------------------------------
GuiControl,, Output ; clear output
GuiControl,, String, I bought a B of As from T S.
GuiControl,, Ruleset,
(LTrim
# Slightly modified from the rules on Wikipedia
A -> apple
B -> bag
S -> .shop
T -> the
the shop -> my brother
a never used -> .terminating rule
)
Return
;---------------------------------------------------------------------------
Button3: ; http://rosettacode.org/wiki/Execute_a_Markov_algorithm#Ruleset_3
;---------------------------------------------------------------------------
GuiControl,, Output ; clear output
GuiControl,, String, I bought a B of As W my Bgage from T S.
GuiControl,, Ruleset,
(LTrim
# 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
)
Return
;---------------------------------------------------------------------------
Button4: ; http://rosettacode.org/wiki/Execute_a_Markov_algorithm#Ruleset_4
;---------------------------------------------------------------------------
GuiControl,, Output ; clear output
GuiControl,, String, _1111*11111_
GuiControl,, Ruleset,
(LTrim
### 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
_+_ ->
)
Return
;---------------------------------------------------------------------------
Button5: ; http://rosettacode.org/wiki/Execute_a_Markov_algorithm#Ruleset_5
;---------------------------------------------------------------------------
GuiControl,, Output ; clear output
GuiControl,, String, 000000A000000
GuiControl,, Ruleset,
(LTrim
# 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
)
Return
;---------------------------------------------------------------------------
ButtonApplyRuleset: ; flow control for Algorithm
;---------------------------------------------------------------------------
; prepare
Gui, Submit, NoHide
GuiControl,, Output ; clear
Controls(False) ; disable
Count := 0
Subst := True
Stop := False
; keep substituting for as long as necessary
While, Subst {
Subst := False ; reset control variable
IfEqual, Stop, 1, Break
Gosub, Algorithm
}
; clean up
Output("Substitution count: " Count)
Controls(True) ; re-enable
Return
;---------------------------------------------------------------------------
ButtonStop: ; this button is initially hidden
;---------------------------------------------------------------------------
Stop := True
Return
;---------------------------------------------------------------------------
Algorithm: ; http://rosettacode.org/wiki/Execute_a_Markov_algorithm
;---------------------------------------------------------------------------
; Parse the ruleset and apply each rule to the string. Whenever a rule
; has changed the string goto first rule. Continue until a encountering
; a terminating rule, or until no further changes to the strings are
; made.
;-----------------------------------------------------------------------
Loop, Parse, Ruleset, `n, `r ; always start from the beginning
{
; check for comment
If SubStr(A_LoopField, 1, 1) = "#"
Continue ; get next line
; split a rule into $Search, $Terminator and $Replace
LookFor := "(?P<Search>.+) -> (?P<Terminator>\.?)(?P<Replace>.+)"
RegExMatch(A_LoopField, LookFor, $)
; single stepping through possible substitutions
If SingleStepping
MsgBox,, %AppName%, % ""
. "Rule = """ A_LoopField """`n`n"
. "Search`t= """ $Search """`n"
. "Replace`t= """ $Replace """`n"
. "Termintor`t= """ ($Terminator ? "True" : "False") """`n"
; try to substitute
StringReplace, String, String, %$Search%, %$Replace%, UseErrorLevel
; any success?
If ErrorLevel { ; yes, substitution done
Count++ ; keep count
Subst := True ; set control variable
Output(String) ; write new string to output
}
; terminate?
If $Terminator { ; yes, terminate
Stop := True ; set control variable
Break ; back to flow control
}
; we are not yet terminated ...
If Subst ; but we just did a substitution
Break ; back to flow control
}
Return
;---------------------------------------------------------------------------
Controls(Bool) { ; [en|dis]able controls
;---------------------------------------------------------------------------
Enable := Bool ? "+" : "-"
Disable := Bool ? "-" : "+"
Loop, 2
GuiControl, %Disable%ReadOnly, % "Edit" A_Index + 1
Loop, 7
GuiControl, %Disable%Disabled, % "Button" A_Index + 1
GuiControl, %Disable%Disabled, Edit4
GuiControl, %Disable%Hidden, Button10
GuiControl, %Enable%Hidden, Button11
GuiControl, %Disable%Disabled, Button12
}
;---------------------------------------------------------------------------
Output(Text) { ; append text to output
;---------------------------------------------------------------------------
static EM_REPLACESEL = 0xC2
global hOut
Sleep, 100
Text .= "`r`n"
SendMessage, EM_REPLACESEL,, &Text,, ahk_id %hOut%
}
;---------- end of file ---------------------------------------------------- |
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.
| #Clojure | Clojure | (def U0 (ex-info "U0" {}))
(def U1 (ex-info "U1" {}))
(defn baz [x] (if (= x 0) (throw U0) (throw U1)))
(defn bar [x] (baz x))
(defn foo []
(dotimes [x 2]
(try
(bar x)
(catch clojure.lang.ExceptionInfo e
(if (= e U0)
(println "foo caught U0")
(throw e))))))
(defn -main [& args]
(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.
| #Common_Lisp | Common Lisp | (define-condition user-condition-1 (error) ())
(define-condition user-condition-2 (error) ())
(defun foo ()
(dolist (type '(user-condition-1 user-condition-2))
(handler-case
(bar type)
(user-condition-1 (c)
(format t "~&foo: Caught: ~A~%" c)))))
(defun bar (type)
(baz type))
(defun baz (type)
(error type)) ; shortcut for (error (make-condition type))
(trace foo bar baz)
(foo) |
http://rosettacode.org/wiki/Exceptions | Exceptions | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
This task is to give an example of an exception handling routine
and to "throw" a new exception.
Related task
Exceptions Through Nested Calls
| #ALGOL_68 | ALGOL 68 | COMMENT
Define an general event handling mechanism on MODE OBJ:
* try to parallel pythons exception handling flexibility
END COMMENT
COMMENT
REQUIRES:
MODE OBJ # These can be a UNION of REF types #
OP OBJIS
PROVIDES:
OP ON, RAISE, RESET
PROC obj on, obj raise, obj reset
END COMMENT
# define object related to OBJ EVENTS #
MODE
RAISEOBJ = PROC(OBJ)VOID, RAWMENDOBJ = PROC(OBJ)BOOL,
MENDOBJ = UNION(RAWMENDOBJ, PROC VOID), # Generalise: Allow PROC VOID (a GOTO) as a short hand #
NEWSCOPEOBJ = STRUCT(REF NEWSCOPEOBJ up, FLEXOBJ obj flex, FLEXEVENTOBJ event flex, MENDOBJ mended),
SCOPEOBJ = REF NEWSCOPEOBJ;
MODE FLEXOBJ=FLEX[0]OBJ;
# Provide an INIT to convert a GO TO to a MEND ... useful for direct aborts #
OP INITMENDOBJ = (PROC VOID go to)MENDOBJ: (go to; SKIP);
SCOPEOBJ obj scope end = NIL;
SCOPEOBJ obj scope begin := obj scope end; # INITialise stack #
OBJ obj any = EMPTY;
EVENTOBJ obj event any = NIL;
# Some crude Singly Linked-List manipulations of the scopes, aka stack ... #
# An event/mended can be shared for all OBJ of the same type: #
PRIO INITAB = 1, +=: = 1;
OP INITAB = (SCOPEOBJ lhs, MENDOBJ obj mend)SCOPEOBJ:
lhs := (obj scope end, obj any, obj event any, obj mend);
OP INITSCOPE = (MENDOBJ obj mend)SCOPEOBJ: HEAP NEWSCOPEOBJ INITAB obj mend;
OP +=: = (SCOPEOBJ item, REF SCOPEOBJ rhs)SCOPEOBJ: ( up OF item := rhs; rhs := item );
OP +=: = (MENDOBJ mend, REF SCOPEOBJ rhs)SCOPEOBJ: INITSCOPE mend +=: rhs;
#OP -=: = (REF SCOPEOBJ scope)SCOPEOBJ: scope := up OF scope;#
COMMENT Restore the prio event scope: ~ END COMMENT
PROC obj reset = (SCOPEOBJ up scope)VOID: obj scope begin := up scope;
MENDOBJ obj unmendable = (OBJ obj)BOOL: FALSE;
MODE NEWEVENTOBJ = STRUCT( # the is simple a typed place holder #
SCOPEOBJ scope,
STRING description,
PROC (OBJ #obj#, MENDOBJ #obj mend#)SCOPEOBJ on,
PROC (OBJ #obj#, STRING #msg#)VOID raise
), EVENTOBJ = REF NEWEVENTOBJ;
MODE FLEXEVENTOBJ = FLEX[0]EVENTOBJ;
COMMENT Define how to catch an event:
obj - IF obj IS NIL then mend event on all OBJects
obj mend - PROC to call to repair the object
return the prior event scope
END COMMENT
PROC obj on = (FLEXOBJ obj flex, FLEXEVENTOBJ event flex, MENDOBJ mend)SCOPEOBJ: (
mend +=: obj scope begin;
IF obj any ISNTIN obj flex THEN obj flex OF obj scope begin := obj flex FI;
IF obj event any ISNTIN event flex THEN event flex OF obj scope begin := event flex FI;
up OF obj scope begin
);
PRIO OBJIS = 4, OBJISNT = 4; # pick the same PRIOrity as EQ and NE #
OP OBJISNT = (OBJ a,b)BOOL: NOT(a OBJIS b);
PRIO ISIN = 4, ISNTIN = 4;
OP ISNTIN = (OBJ obj, FLEXOBJ obj flex)BOOL: (
BOOL isnt in := FALSE;
FOR i TO UPB obj flex WHILE isnt in := obj OBJISNT obj flex[i] DO SKIP OD;
isnt in
);
OP ISIN = (OBJ obj, FLEXOBJ obj flex)BOOL: NOT(obj ISNTIN obj flex);
OP ISNTIN = (EVENTOBJ event, FLEXEVENTOBJ event flex)BOOL: (
BOOL isnt in := TRUE;
FOR i TO UPB event flex WHILE isnt in := event ISNT event flex[i] DO SKIP OD;
isnt in
);
OP ISIN = (EVENTOBJ event, FLEXEVENTOBJ event flex)BOOL: NOT(event ISNTIN event flex);
COMMENT Define how to raise an event, once it is raised try and mend it:
if all else fails produce an error message and stop
END COMMENT
PROC obj raise = (OBJ obj, EVENTOBJ event, STRING msg)VOID:(
SCOPEOBJ this scope := obj scope begin;
# until mended this event should cascade through scope event handlers/members #
FOR i WHILE this scope ISNT SCOPEOBJ(obj scope end) DO
IF (obj any ISIN obj flex OF this scope OR obj ISIN obj flex OF this scope ) AND
(obj event any ISIN event flex OF this scope OR event ISIN event flex OF this scope)
THEN
CASE mended OF this scope IN
(RAWMENDOBJ mend):IF mend(obj) THEN break mended FI,
(PROC VOID go to): (go to; stop)
OUT put(stand error, "undefined: raise stop"); stop
ESAC
FI;
this scope := up OF this scope
OD;
put(stand error, ("OBJ event: ",msg)); stop; FALSE
EXIT
break mended: TRUE
);
CO define ON and some useful(?) RAISE OPs CO
PRIO ON = 1, RAISE = 1;
OP ON = (MENDOBJ mend, EVENTOBJ event)SCOPEOBJ: obj on(obj any, event, mend),
RAISE = (OBJ obj, EVENTOBJ event)VOID: obj raise(obj, event, "unnamed event"),
RAISE = (OBJ obj, MENDOBJ mend)VOID: ( mend ON obj event any; obj RAISE obj event any),
RAISE = (EVENTOBJ event)VOID: obj raise(obj any, event, "unnamed event"),
RAISE = (MENDOBJ mend)VOID: ( mend ON obj event any; RAISE obj event any),
RAISE = (STRING msg, EVENTOBJ event)VOID: obj raise(obj any, event, msg);
OP (SCOPEOBJ #up scope#)VOID RESET = obj reset;
SKIP |
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
| #AppleScript | AppleScript | do shell script "ls" without altering line endings |
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
| #Applesoft_BASIC | Applesoft BASIC | ? CHR$(4)"CATALOG" |
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
| #Ada | Ada | function Factorial (N : Positive) return Positive is
Result : Positive := N;
Counter : Natural := N - 1;
begin
for I in reverse 1..Counter loop
Result := Result * I;
end loop;
return Result;
end Factorial; |
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
| #Ela | Ela | open number
_ ^ 0 = 1
x ^ n | n > 0 = f x (n - 1) x
|else = fail "Negative exponent"
where f _ 0 y = y
f a d y = g a d
where g b i | even i = g (b * b) (i `quot` 2)
| else = f b (i - 1) (b * y)
(12 ^ 4, 12 ** 4) |
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
| #Elixir | Elixir | defmodule My do
def exp(x,y) when is_integer(x) and is_integer(y) and y>=0 do
IO.write("int> ") # debug test
exp_int(x,y)
end
def exp(x,y) when is_integer(y) do
IO.write("float> ") # debug test
exp_float(x,y)
end
def exp(x,y), do: (IO.write(" "); :math.pow(x,y))
defp exp_int(_,0), do: 1
defp exp_int(x,y), do: Enum.reduce(1..y, 1, fn _,acc -> x * acc end)
defp exp_float(_,y) when y==0, do: 1.0
defp exp_float(x,y) when y<0, do: 1/exp_float(x,-y)
defp exp_float(x,y), do: Enum.reduce(1..y, 1, fn _,acc -> x * acc end)
end
list = [{2,0}, {2,3}, {2,-2},
{2.0,0}, {2.0,3}, {2.0,-2},
{0.5,0}, {0.5,3}, {0.5,-2},
{-2,2}, {-2,3}, {-2.0,2}, {-2.0,3},
]
IO.puts " ___My.exp___ __:math.pow_"
Enum.each(list, fn {x,y} ->
sxy = "#{x} ** #{y}"
sexp = inspect My.exp(x,y)
spow = inspect :math.pow(x,y) # For the comparison
:io.fwrite("~10s = ~12s, ~12s~n", [sxy, sexp, spow])
end) |
http://rosettacode.org/wiki/Executable_library | Executable library | The general idea behind an executable library is to create a library
that when used as a library does one thing;
but has the ability to be run directly via command line.
Thus the API comes with a CLI in the very same source code file.
Task detail
Create a library/module/dll/shared object/... for a programming language that contains a function/method called hailstone that is a function taking a positive integer and returns the Hailstone sequence for that number.
The library, when executed directly should satisfy the remaining requirements of the Hailstone sequence task:
2. Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
3. Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.
Create a second executable to calculate the following:
Use the library's hailstone function, in the standard manner, (or document how this use deviates from standard use of a library), together with extra code in this executable, to find the hailstone length returned most often for 1 ≤ n < 100,000.
Explain any extra setup/run steps needed to complete the task.
Notes:
It is assumed that for a language that overwhelmingly ships in a compiled form, such as C, the library must also be an executable and the compiled user of that library is to do so without changing the compiled library. I.e. the compile tool-chain is assumed not to be present in the runtime environment.
Interpreters are present in the runtime environment. | #Nim | Nim | proc hailstone*(n: int): auto =
result = @[n]
var n = n
while n > 1:
if (n and 1) == 1:
n = 3 * n + 1
else:
n = n div 2
result.add n
when isMainModule:
let h = hailstone 27
assert h.len == 112 and h[0..3] == @[27,82,41,124] and h[h.high-3..h.high] == @[8,4,2,1]
var m, mi = 0
for i in 1 ..< 100_000:
let n = hailstone(i).len
if n > m:
m = n
mi = i
echo "Maximum length ", m, " was found for hailstone(", mi, ") for numbers <100,000" |
http://rosettacode.org/wiki/Executable_library | Executable library | The general idea behind an executable library is to create a library
that when used as a library does one thing;
but has the ability to be run directly via command line.
Thus the API comes with a CLI in the very same source code file.
Task detail
Create a library/module/dll/shared object/... for a programming language that contains a function/method called hailstone that is a function taking a positive integer and returns the Hailstone sequence for that number.
The library, when executed directly should satisfy the remaining requirements of the Hailstone sequence task:
2. Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
3. Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.
Create a second executable to calculate the following:
Use the library's hailstone function, in the standard manner, (or document how this use deviates from standard use of a library), together with extra code in this executable, to find the hailstone length returned most often for 1 ≤ n < 100,000.
Explain any extra setup/run steps needed to complete the task.
Notes:
It is assumed that for a language that overwhelmingly ships in a compiled form, such as C, the library must also be an executable and the compiled user of that library is to do so without changing the compiled library. I.e. the compile tool-chain is assumed not to be present in the runtime environment.
Interpreters are present in the runtime environment. | #PARI.2FGP | PARI/GP | #include <pari/pari.h>
#define HAILSTONE1 "n=1;print1(%d,\": \");apply(x->while(x!=1,if(x/2==x\\2,x/=2,x=x*3+1);n++;print1(x,\", \")),%d);print(\"(\",n,\")\n\")"
#define HAILSTONE2 "m=n=0;for(i=2,%d,h=1;apply(x->while(x!=1,if(x/2==x\\2,x/=2,x=x*3+1);h++),i);if(m<h,m=h;n=i));print(n,\": \",m)"
void hailstone1(int x)
{
char buf[1024];
snprintf(buf, sizeof(buf), HAILSTONE1, x, x);
pari_init(1000000, 2);
geval(strtoGENstr(buf));
pari_close();
}
void hailstone2(int range)
{
char buf[1024];
snprintf(buf, sizeof(buf), HAILSTONE2, range);
pari_init(1000000, 2);
geval(strtoGENstr(buf));
pari_close();
}
#if __i386__
const char _hail[] __attribute__((section(".interp"))) = "/lib/ld-linux.so.2";
#else // __x86_64__
const char _hail[] __attribute__((section(".interp"))) = "/lib64/ld-linux-x86-64.so.2";
#endif
int main(void)
{
hailstone1(27);
hailstone2(100000);
exit(0);
} |
http://rosettacode.org/wiki/Extreme_floating_point_values | Extreme floating point values | The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity.
The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe other), extreme floating point values in your language and assign them to variables.
Print the values of these variables if possible; and show some arithmetic with these values and variables.
If your language can directly enter these extreme floating point values then show it.
See also
What Every Computer Scientist Should Know About Floating-Point Arithmetic
Related tasks
Infinity
Detect division by zero
Literals/Floating point
| #Smalltalk | Smalltalk | FloatE nan
FloatD nan
FloatE infinity
FloatD infinity
FloatE negativeInfinity
FloatD negativeInfinity
Float zero -> 0.0
Float negativeZero -> -0.0
0.0 negated -> -0.0
0.0 negated = 0.0 -> true. "they have the same value"
0.0 negated < 0.0 -> false
0.0 negated > 0.0 -> false
1.0 isFinite -> true
FloatE infinity isFinite -> false
(FloatE infinity = FloatD infinity) -> true
FloatE infinity > 1e200 -> true
FloatE infinity > FloatE negativeInfinity -> true
FloatE infinity > Number negativeInfinity -> true
(FloatE infinity negated = FloatE negativeInfinity) -> true
(1.0 / 0.0) -> ZeroDivision exception
[ 1.0 / 0.0 ] on:ZeroDivide do:[:ex | ex proceed ] -> infinity
(0.0 / 0.0) -> ZeroDivision exception
[ 0.0 / 0.0 ] on:ZeroDivide do:[:ex | ex proceed ] -> nan
(1.0 / Float infinity) -> 0.0
(1.0 / Float negativeInfinity) -> -0.0
-4 sqrt -> ImaginaryResultError exception
Number trapImaginary:[ -4 sqrt ] -> (0+2.0i) (works in Smalltalk/X)
[ -4 sqrt ] on:DomainError do:[:ex | ex proceed] -> nan
-1 log10 -> DomainError exception
[ -1 log10 ] on:DomainError do:[:ex | ex proceed] -> nan
|
http://rosettacode.org/wiki/Execute_SNUSP | Execute SNUSP | Execute SNUSP is an implementation of SNUSP.
Other implementations of SNUSP.
RCSNUSP
SNUSP
An implementation need only properly implement the Core SNUSP instructions ('$', '\', '/', '+', '-', '<', '>', ',', '.', '!', and '?'). Modular SNUSP ('#', '@') and Bloated SNUSP (':', ';', '%', and '&') are also allowed, but not required. Any extra characters that you implement should be noted in the description of your implementation. Any cell size is allowed, EOF support is optional, as is whether you have bounded or unbounded memory.
| #Raku | Raku | class SNUSP {
has @!inst-pointer;
has @!call-stack;
has @!direction;
has @!memory;
has $!mem-pointer;
method run ($code) {
init();
my @code = pad( |$code.lines );
for @code.kv -> $r, @l {
my $index = @l.grep( /'$'/, :k );
if $index {
@!inst-pointer = $r, $index;
last
}
}
loop {
my $instruction = @code[@!inst-pointer[0]; @!inst-pointer[1]];
given $instruction {
when '>' { $!mem-pointer++ }
when '<' { $!mem-pointer-- }
when '+' { @!memory[$!mem-pointer]++ }
when '-' { @!memory[$!mem-pointer]-- }
when '.' { print @!memory[$!mem-pointer].chr }
when ',' { @!memory[$!mem-pointer] = $*IN.getc.ord }
when '/' { @!direction = @!direction.reverse «*» -1 }
when '\\' { @!direction = @!direction.reverse }
when '!' { nexti() }
when '?' { nexti() unless @!memory[$!mem-pointer] }
when '@' { @!call-stack.push: @!inst-pointer.Array }
when '#' {
last unless +@!call-stack;
@!inst-pointer = |@!call-stack.pop;
nexti();
}
}
nexti();
last if @!inst-pointer[0] > +@code or
@!inst-pointer[1] > +@code[0];
}
sub init () {
@!inst-pointer = 0, 0;
@!direction = 0, 1;
$!mem-pointer = 0;
@!memory = ()
}
sub nexti () { @!inst-pointer Z+= @!direction }
sub pad ( *@lines ) {
my $max = max @lines».chars;
my @pad = @lines.map: $max - *.chars;
map -> $i { flat @lines[$i].comb, ' ' xx @pad[$i] }, ^@lines;
}
}
}
# TESTING
my $hw = q:to/END/;
/++++!/===========?\>++.>+.+++++++..+++\
\+++\ | /+>+++++++>/ /++++++++++<<.++>./
$+++/ | \+++++++++>\ \+++++.>.+++.-----\
\==-<<<<+>+++/ /=.>.+>.--------.-/
END
my $snusp = SNUSP.new;
$snusp.run($hw) |
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.
| #Julia | Julia |
const CSTACK1 = Array{Bool,1}()
const CSTACK2 = Array{Bool,1}()
const CSTACK3 = Array{Bool,1}()
macro if2(condition1, condition2, alltrue)
if !(length(CSTACK1) == length(CSTACK2) == length(CSTACK3))
throw("prior if2 statement error: must have if2, elseif1, elseif2, and elseifneither")
end
ifcond1 = eval(condition1)
ifcond2 = eval(condition2)
if ifcond1 && ifcond2
eval(alltrue)
push!(CSTACK1, false)
push!(CSTACK2, false)
push!(CSTACK3, false)
elseif ifcond1
push!(CSTACK1, true)
push!(CSTACK2, false)
push!(CSTACK3, false)
elseif ifcond2
push!(CSTACK1, false)
push!(CSTACK2, true)
push!(CSTACK3, false)
else
push!(CSTACK1, false)
push!(CSTACK2, false)
push!(CSTACK3, true)
end
end
macro elseif1(block)
quote
if pop!(CSTACK1)
$block
end
end
end
macro elseif2(block)
quote
if pop!(CSTACK2)
$block
end
end
end
macro elseifneither(block)
quote
if pop!(CSTACK3)
$block
end
end
end
# Testing of code starts here
@if2(2 != 4, 3 != 7, begin x = "all"; println(x) end)
@elseif1(begin println("one") end)
@elseif2(begin println("two") end)
@elseifneither(begin println("neither") end)
@if2(2 != 4, 3 == 7, println("all"))
@elseif1(begin println("one") end)
@elseif2(begin println("two") end)
@elseifneither(begin println("neither") end)
@if2(2 == 4, 3 != 7, begin x = "all"; println(x) end)
@elseif1(begin println("one") end)
@elseif2(begin println("two") end)
@elseifneither(begin println("neither") end)
@if2(2 == 4, 3 == 7, println("last all") end)
@elseif1(begin println("one") end)
@elseif2(begin println("two") end)
@elseifneither(begin println("neither") 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.
| #Kotlin | Kotlin | // version 1.0.6
data class IfBoth(val cond1: Boolean, val cond2: Boolean) {
fun elseFirst(func: () -> Unit): IfBoth {
if (cond1 && !cond2) func()
return this
}
fun elseSecond(func: () -> Unit): IfBoth {
if (cond2 && !cond1) func()
return this
}
fun elseNeither(func: () -> Unit): IfBoth {
if (!cond1 && !cond2) func()
return this // in case it's called out of order
}
}
fun ifBoth(cond1: Boolean, cond2: Boolean, func: () -> Unit): IfBoth {
if (cond1 && cond2) func()
return IfBoth(cond1, cond2)
}
fun main(args: Array<String>) {
var a = 0
var b = 1
ifBoth (a == 1, b == 3) {
println("a = 1 and b = 3")
}
.elseFirst {
println("a = 1 and b <> 3")
}
.elseSecond {
println("a <> 1 and b = 3")
}
.elseNeither {
println("a <> 1 and b <> 3")
}
// It's also possible to omit any (or all) of the 'else' clauses or to call them out of order
a = 1
b = 0
ifBoth (a == 1, b == 3) {
println("a = 1 and b = 3")
}
.elseNeither {
println("a <> 1 and b <> 3")
}
.elseFirst {
println("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
| #ReasonML | ReasonML |
let fizzbuzz i =>
switch (i mod 3, i mod 5) {
| (0, 0) => "FizzBuzz"
| (0, _) => "Fizz"
| (_, 0) => "Buzz"
| _ => string_of_int i
};
for i in 1 to 100 {
print_endline (fizzbuzz i)
};
|
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.
| #Julia | Julia | using Primes
sum = 2
currentprime = 2
for i in 2:100000
currentprime = nextprime(currentprime + 1)
sum += currentprime
end
println("The sum of the first 100,000 primes is $sum")
curprime = 1
arr = zeros(Int, 20)
for i in 1:20
curprime = nextprime(curprime + 1)
arr[i] = curprime
end
println("The first 20 primes are ", arr)
println("the primes between 100 and 150 are ", primes(100,150))
println("The number of primes between 7,700 and 8,000 is ", length(primes(7700, 8000)))
println("The 10,000th prime is ", prime(10000)) |
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.
| #11l | 11l | F bf(source)
V tape = DefaultDict[Int, Int]()
V cell = 0
V ptr = 0
L ptr < source.len
S source[ptr]
‘>’
cell++
‘<’
cell--
‘+’
tape[cell]++
‘-’
tape[cell]--
‘.’
:stdout.write(Char(code' tape[cell]))
‘,’
tape[cell] = :stdin.read(1).code
‘[’
I tape[cell] == 0
V nesting_level = 0
L
S source[ptr]
‘[’
nesting_level++
‘]’
I --nesting_level == 0
L.break
ptr++
‘]’
I tape[cell] != 0
V nesting_level = 0
L
S source[ptr]
‘[’
I --nesting_level == 0
L.break
‘]’
nesting_level++
ptr--
ptr++
bf(‘++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.’) |
http://rosettacode.org/wiki/Evolutionary_algorithm | Evolutionary algorithm | Starting with:
The target string: "METHINKS IT IS LIKE A WEASEL".
An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent).
A fitness function that computes the ‘closeness’ of its argument to the target string.
A mutate function that given a string and a mutation rate returns a copy of the string, with some characters probably mutated.
While the parent is not yet the target:
copy the parent C times, each time allowing some random probability that another character might be substituted using mutate.
Assess the fitness of the parent and all the copies to the target and make the most fit string the new parent, discarding the others.
repeat until the parent converges, (hopefully), to the target.
See also
Wikipedia entry: Weasel algorithm.
Wikipedia entry: Evolutionary algorithm.
Note: to aid comparison, try and ensure the variables and functions mentioned in the task description appear in solutions
A cursory examination of a few of the solutions reveals that the instructions have not been followed rigorously in some solutions. Specifically,
While the parent is not yet the target:
copy the parent C times, each time allowing some random probability that another character might be substituted using mutate.
Note that some of the the solutions given retain characters in the mutated string that are correct in the target string. However, the instruction above does not state to retain any of the characters while performing the mutation. Although some may believe to do so is implied from the use of "converges"
(:* repeat until the parent converges, (hopefully), to the target.
Strictly speaking, the new parent should be selected from the new pool of mutations, and then the new parent used to generate the next set of mutations with parent characters getting retained only by not being mutated. It then becomes possible that the new set of mutations has no member that is fitter than the parent!
As illustration of this error, the code for 8th has the following remark.
Create a new string based on the TOS, changing randomly any characters which
don't already match the target:
NOTE: this has been changed, the 8th version is completely random now
Clearly, this algo will be applying the mutation function only to the parent characters that don't match to the target characters!
To ensure that the new parent is never less fit than the prior parent, both the parent and all of the latest mutations are subjected to the fitness test to select the next parent.
| #11l | 11l | V target = Array(‘METHINKS IT IS LIKE A WEASEL’)
V alphabet = ‘ ABCDEFGHIJLKLMNOPQRSTUVWXYZ’
V p = 0.05
V c = 100
F neg_fitness(trial)
R sum(zip(trial, :target).map((t, h) -> Int(t != h)))
F mutate(parent)
R parent.map(ch -> (I random:() < :p {random:choice(:alphabet)} E ch))
V parent = (0 .< target.len).map(_ -> random:choice(:alphabet))
V i = 0
print((‘#3’.format(i))‘ ’parent.join(‘’))
L parent != target
V copies = ((0 .< c).map(_ -> mutate(:parent)))
parent = min(copies, key' x -> neg_fitness(x))
print((‘#3’.format(i))‘ ’parent.join(‘’))
i++ |
http://rosettacode.org/wiki/Fibonacci_sequence | Fibonacci sequence | The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion).
The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition:
Fn = Fn+2 - Fn+1, if n<0
support for negative n in the solution is optional.
Related tasks
Fibonacci n-step number sequences
Leonardo numbers
References
Wikipedia, Fibonacci number
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #Idris | Idris | fibAnalytic : Nat -> Double
fibAnalytic n =
floor $ ((pow goldenRatio n) - (pow (-1.0/goldenRatio) n)) / sqrt(5)
where goldenRatio : Double
goldenRatio = (1.0 + sqrt(5)) / 2.0 |
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
| #Ruby | Ruby | class Integer
def factors() (1..self).select { |n| (self % n).zero? } end
end
p 45.factors |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #Erlang | Erlang | % hq9+ Erlang implementation (JWL)
% http://www.erlang.org/
-module(hq9p).
-export([main/1]).
%% bottle helper routine
bottle(0) ->
io:format("No more bottles of beer ");
bottle(1) ->
io:format("1 bottle of beer ");
bottle(N) when N > 0 ->
io:format("~w bottles of beer ", [N]).
%% Implementation of instructions
beer(0) ->
bottle(0), io:format("on the wall~n"),
bottle(0), io:format("on the wall~nGo to the store and buy some more~n"),
io:format("99 bottles of beer on the wall.~n");
beer(N) ->
bottle(N), io:format("on the wall~n"),
bottle(N), io:format("~nTake one down and pass it around~n"),
bottle(N-1), io:format("on the wall~n~n"),
beer(N-1).
hello() ->
io:format("Hello world!~n", []).
prog(Prog) ->
io:format("~s~n", [Prog]).
inc(Acc) ->
Acc+1.
%% Interpreter
execute(Instruction, Prog, Acc) ->
case Instruction of
$H -> hello(), Acc;
$Q -> prog(Prog), Acc;
$9 -> beer(99), Acc;
$+ -> inc(Acc);
_ -> io:format("Invalid instruction: ~c~n", [Instruction]), Acc
end.
main([], _Prog, Acc) ->
Acc;
main([Instruction | Rest], Prog, Acc) ->
NewAcc = execute(Instruction, Prog, Acc),
main(Rest, Prog, NewAcc).
main(Prog) ->
Compiled = string:to_upper(Prog),
main(Compiled, Prog, 0).
|
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
| #BBC_BASIC | BBC BASIC | PRINT FNmarkov("ruleset1.txt", "I bought a B of As from T S.")
PRINT FNmarkov("ruleset2.txt", "I bought a B of As from T S.")
PRINT FNmarkov("ruleset3.txt", "I bought a B of As W my Bgage from T S.")
PRINT FNmarkov("ruleset4.txt", "_1111*11111_")
PRINT FNmarkov("ruleset5.txt", "000000A000000")
END
DEF FNmarkov(rulefile$, text$)
LOCAL i%, done%, rules%, rule$, old$, new$
rules% = OPENIN(rulefile$)
IF rules%=0 ERROR 100, "Cannot open rules file"
REPEAT
rule$ = GET$#rules%
IF ASC(rule$)<>35 THEN
REPEAT
i% = INSTR(rule$, CHR$(9))
IF i% MID$(rule$,i%,1) = " "
UNTIL i%=0
i% = INSTR(rule$, " -> ")
IF i% THEN
old$ = LEFT$(rule$,i%-1)
WHILE RIGHT$(old$)=" " old$ = LEFT$(old$) : ENDWHILE
new$ = MID$(rule$,i%+4)
WHILE ASC(new$)=32 new$ = MID$(new$,2) : ENDWHILE
IF ASC(new$)=46 new$ = MID$(new$,2) : done% = TRUE
i% = INSTR(text$,old$)
IF i% THEN
text$ = LEFT$(text$,i%-1) + new$ + MID$(text$,i%+LEN(old$))
PTR#rules% = 0
ENDIF
ENDIF
ENDIF
UNTIL EOF#rules% OR done%
CLOSE #rules%
= text$ |
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
| #Bracmat | Bracmat |
markov=
{
First the patterns that describe the rules syntax.
This is a naive and not very efficient way to parse the rules, but it closely
matches the problem description, which is nice.
}
( ruleset
= >%@" " ? { Added: assume that a rule cannot start with whitespace.
The %@ say that the thing to match must be exactly one
byte. % means 'one or more'. @ means 'zero or one'.
}
: ((!comment|!rule) !newlines) !ruleset
| { Recursion terminates here: match empty string. }
)
& (comment="#" ?com)
& ( rule
= %?pattern
!whitespace
"->"
!whitespace
( "." %?replacement&stop:?stop
| %?replacement
)
)
& ( whitespace
= (\t|" ") (!whitespace|)
)
& ( newlines
= ( (\n|\r)
& ( :!pattern:!replacement {Do nothing. We matched an empty line.}
| (!pattern.!replacement.!stop) !rules:?rules
{
Add pattern, replacement and the stop (empty string or "stop")
to a list of triplets. This list will contain the rules in
reverse order.
Then, reset these variables, so they are not added once more
if an empty line follows.
}
& :?stop:?pattern:?replacement
)
)
(!newlines|)
)
{
Compile the textual rules to a single Bracmat pattern.
}
& ( compileRules
= stop pattern replacement rules,pat rep stp
. :?stop:?pattern:?replacement:?rules
{
Important! Initialise these variables.
}
& @(!arg:!ruleset)
{
That's all. The textual rules are parsed and converted to a
list of triplets. The rules in the list are in reversed order.
}
& !rules:(?pat.?rep.?stp) ?rules
{
The head of the list is the last rule. Use it to initialise
the pattern "ruleSetAsPattern".
The single quote introduces a macro substition. All symbols
preceded with a $ are substituted.
}
&
' ( ?A ()$pat ?Z
& $stp:?stop
& $rep:?replacement
)
: (=?ruleSetAsPattern)
{
Add all remaining rules as new subpatterns to
"ruleSetAsPattern". Separate with the OR symbol.
}
& whl
' ( !rules:(?pat.?rep.?stp) ?rules
&
' ( ?A ()$pat ?Z
& $stp:?stop
& $rep:?replacement
| $ruleSetAsPattern
)
: (=?ruleSetAsPattern)
)
& '$ruleSetAsPattern
)
{
Function that takes two arguments: a rule set (as text)
and a subject string.
The function returns the transformed string.
}
& ( applyRules
= rulesSetAsText subject ruleSetAsPattern
, A Z replacement stop
. !arg:(?rulesSetAsText.?subject)
& compileRules$!rulesSetAsText:(=?ruleSetAsPattern)
{
Apply rule until no match
or until variable "stop" has been set to the value "stop".
}
& whl
' ( @(!subject:!ruleSetAsPattern)
& str$(!A !replacement !Z):?subject
& !stop:~stop
)
& !subject
)
{
Tests:
}
& out
$ ( applyRules
$ ( "# 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
"
. "I bought a B of As from T S."
)
)
& out
$ ( applyRules
$ ( "# Slightly modified from the rules on Wikipedia
A -> apple
B -> bag
S -> .shop
T -> the
the shop -> my brother
a never used -> .terminating rule
"
. "I bought a B of As from T S."
)
)
& out
$ ( applyRules
$ ( "# 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
"
. "I bought a B of As W my Bgage from T S."
)
)
& out
$ ( applyRules
$ ( "### 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
_+_ ->
"
. "_1111*11111_"
)
)
& out
$ ( applyRules
$ ( "# 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
"
. 000000A000000
)
)
& ok
| failure;
|
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.
| #Crystal | Crystal | class U0 < Exception
end
class U1 < Exception
end
def foo
2.times do |i|
begin
bar(i)
rescue e : U0
puts "rescued #{e}"
end
end
end
def bar(i : Int32)
baz(i)
end
def baz(i : Int32)
raise U0.new("this is u0") if i == 0
raise U1.new("this is u1") if i == 1
end
foo |
http://rosettacode.org/wiki/Exceptions/Catch_an_exception_thrown_in_a_nested_call | Exceptions/Catch an exception thrown in a nested call | Show how to create a user-defined exception and show how to catch an exception raised from several nested calls away.
Create two user-defined exceptions, U0 and U1.
Have function foo call function bar twice.
Have function bar call function baz.
Arrange for function baz to raise, or throw exception U0 on its first call, then exception U1 on its second.
Function foo should catch only exception U0, not U1.
Show/describe what happens when the program is run.
| #D | D | class U0 : Exception {
this() @safe pure nothrow { super("U0 error message"); }
}
class U1 : Exception {
this() @safe pure nothrow { super("U1 error message"); }
}
void foo() {
import std.stdio;
foreach (immutable i; 0 .. 2) {
try {
i.bar;
} catch (U0) {
"Function foo caught exception U0".writeln;
}
}
}
void bar(in int i) @safe pure {
i.baz;
}
void baz(in int i) @safe pure {
throw i ? new U1 : new U0;
}
void main() {
foo;
} |
http://rosettacode.org/wiki/Exceptions | Exceptions | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
This task is to give an example of an exception handling routine
and to "throw" a new exception.
Related task
Exceptions Through Nested Calls
| #AppleScript | AppleScript | try
set num to 1 / 0
--do something that might throw an error
end try |
http://rosettacode.org/wiki/Exceptions | Exceptions | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
This task is to give an example of an exception handling routine
and to "throw" a new exception.
Related task
Exceptions Through Nested Calls
| #AutoHotkey | AutoHotkey | try
BadlyCodedFunc()
catch e
MsgBox % "Error in " e.What ", which was called at line " e.Line
BadlyCodedFunc() {
throw Exception("Fail", -1)
} |
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
| #Arturo | Arturo | print execute "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
| #AutoHotkey | AutoHotkey | Run, %comspec% /k dir & pause |
http://rosettacode.org/wiki/Factorial | Factorial | Definitions
The factorial of 0 (zero) is defined as being 1 (unity).
The Factorial Function of a positive integer, n, is defined as the product of the sequence:
n, n-1, n-2, ... 1
Task
Write a function to return the factorial of a number.
Solutions can be iterative or recursive.
Support for trapping negative n errors is optional.
Related task
Primorial numbers
| #Agda | Agda | factorial : ℕ → ℕ
factorial zero = 1
factorial (suc n) = suc n * factorial n |
http://rosettacode.org/wiki/Exponentiation_operator | Exponentiation operator | Most programming languages have a built-in implementation of exponentiation.
Task
Re-implement integer exponentiation for both intint and floatint as both a procedure, and an operator (if your language supports operator definition).
If the language supports operator (or procedure) overloading, then an overloaded form should be provided for both intint and floatint variants.
Related tasks
Exponentiation order
arbitrary-precision integers (included)
Exponentiation with infix operators in (or operating on) the base
| #Erlang | Erlang |
pow(X, Y) when Y < 0 ->
1/pow(X, -Y);
pow(X, Y) when is_integer(Y) ->
pow(X, Y, 1).
pow(_, 0, B) ->
B;
pow(X, Y, B) ->
B2 = if Y rem 2 =:= 0 -> B; true -> X * B end,
pow(X * X, Y div 2, B2).
|
http://rosettacode.org/wiki/Executable_library | Executable library | The general idea behind an executable library is to create a library
that when used as a library does one thing;
but has the ability to be run directly via command line.
Thus the API comes with a CLI in the very same source code file.
Task detail
Create a library/module/dll/shared object/... for a programming language that contains a function/method called hailstone that is a function taking a positive integer and returns the Hailstone sequence for that number.
The library, when executed directly should satisfy the remaining requirements of the Hailstone sequence task:
2. Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
3. Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.
Create a second executable to calculate the following:
Use the library's hailstone function, in the standard manner, (or document how this use deviates from standard use of a library), together with extra code in this executable, to find the hailstone length returned most often for 1 ≤ n < 100,000.
Explain any extra setup/run steps needed to complete the task.
Notes:
It is assumed that for a language that overwhelmingly ships in a compiled form, such as C, the library must also be an executable and the compiled user of that library is to do so without changing the compiled library. I.e. the compile tool-chain is assumed not to be present in the runtime environment.
Interpreters are present in the runtime environment. | #Perl | Perl | package Hailstone;
sub seq {
my $x = shift;
$x == 1 ? (1) : ($x & 1)? ($x, seq($x * 3 + 1))
: ($x, seq($x / 2))
}
my %cache = (1 => 1);
sub len {
my $x = shift;
$cache{$x} //= 1 + (
$x & 1 ? len($x * 3 + 1)
: len($x / 2))
}
unless (caller) {
for (1 .. 100_000) {
my $l = len($_);
($m, $len) = ($_, $l) if $l > $len;
}
print "seq of 27 - $cache{27} elements: @{[seq(27)]}\n";
print "Longest sequence is for $m: $len\n";
}
1; |
http://rosettacode.org/wiki/Executable_library | Executable library | The general idea behind an executable library is to create a library
that when used as a library does one thing;
but has the ability to be run directly via command line.
Thus the API comes with a CLI in the very same source code file.
Task detail
Create a library/module/dll/shared object/... for a programming language that contains a function/method called hailstone that is a function taking a positive integer and returns the Hailstone sequence for that number.
The library, when executed directly should satisfy the remaining requirements of the Hailstone sequence task:
2. Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
3. Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.
Create a second executable to calculate the following:
Use the library's hailstone function, in the standard manner, (or document how this use deviates from standard use of a library), together with extra code in this executable, to find the hailstone length returned most often for 1 ≤ n < 100,000.
Explain any extra setup/run steps needed to complete the task.
Notes:
It is assumed that for a language that overwhelmingly ships in a compiled form, such as C, the library must also be an executable and the compiled user of that library is to do so without changing the compiled library. I.e. the compile tool-chain is assumed not to be present in the runtime environment.
Interpreters are present in the runtime environment. | #Phix | Phix | --global (if you want to be able to call this from test.exw)
function hailstone(atom n)
sequence s = {n}
while n!=1 do
if remainder(n,2)=0 then
n /= 2
else
n = 3*n+1
end if
s &= n
end while
return s
end function
global function hailstone_count(atom n)
integer count = 1
while n!=1 do
if remainder(n,2)=0 then
n /= 2
else
n = 3*n+1
end if
count += 1
end while
return count
end function
if include_file()==1 then
sequence s = hailstone(27)
integer ls = length(s)
s[5..-5] = {".."}
puts(1,"hailstone(27) = ")
? s
printf(1,"length = %d\n\n",ls)
integer hmax = 1, imax = 1,count
for i=2 to 1e5-1 do
count = hailstone_count(i)
if count>hmax then
hmax = count
imax = i
end if
end for
printf(1,"The longest hailstone sequence under 100,000 is %d with %d elements.\n",{imax,hmax})
end if |
http://rosettacode.org/wiki/Extreme_floating_point_values | Extreme floating point values | The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity.
The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe other), extreme floating point values in your language and assign them to variables.
Print the values of these variables if possible; and show some arithmetic with these values and variables.
If your language can directly enter these extreme floating point values then show it.
See also
What Every Computer Scientist Should Know About Floating-Point Arithmetic
Related tasks
Infinity
Detect division by zero
Literals/Floating point
| #Stata | Stata | . display %21x .
+1.0000000000000X+3ff
. display %21x .a
+1.0010000000000X+3ff
. display %21x .z
+1.01a0000000000X+3ff
. display %21x c(maxdouble)
+1.fffffffffffffX+3fe |
http://rosettacode.org/wiki/Extreme_floating_point_values | Extreme floating point values | The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity.
The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe other), extreme floating point values in your language and assign them to variables.
Print the values of these variables if possible; and show some arithmetic with these values and variables.
If your language can directly enter these extreme floating point values then show it.
See also
What Every Computer Scientist Should Know About Floating-Point Arithmetic
Related tasks
Infinity
Detect division by zero
Literals/Floating point
| #Swift | Swift | let negInf = -1.0 / 0.0
let inf = 1.0 / 0.0 //also Double.infinity
let nan = 0.0 / 0.0 //also Double.NaN
let negZero = -2.0 / inf
println("Negative inf: \(negInf)")
println("Positive inf: \(inf)")
println("NaN: \(nan)")
println("Negative 0: \(negZero)")
println("inf + -inf: \(inf + negInf)")
println("0 * NaN: \(0 * nan)")
println("NaN == NaN: \(nan == nan)") |
http://rosettacode.org/wiki/Execute_SNUSP | Execute SNUSP | Execute SNUSP is an implementation of SNUSP.
Other implementations of SNUSP.
RCSNUSP
SNUSP
An implementation need only properly implement the Core SNUSP instructions ('$', '\', '/', '+', '-', '<', '>', ',', '.', '!', and '?'). Modular SNUSP ('#', '@') and Bloated SNUSP (':', ';', '%', and '&') are also allowed, but not required. Any extra characters that you implement should be noted in the description of your implementation. Any cell size is allowed, EOF support is optional, as is whether you have bounded or unbounded memory.
| #Ruby | Ruby | $ include "seed7_05.s7i";
const proc: snusp (in string: sourceCode, in integer: memSize, inout file: input, inout file: output) is func
local
var array string: instructions is 0 times "";
var array char: memory is 0 times ' ';
var integer: dataPointer is 1;
var integer: instrPtrRow is 0;
var integer: instrPtrColumn is 0;
var integer: rowDir is 0;
var integer: columnDir is 1;
var integer: helpDir is 0;
var integer: row is 0;
begin
instructions := split(sourceCode, "\n");
memory := memSize times '\0;';
for key row range instructions do
if pos(instructions[row], '$') <> 0 then
instrPtrRow := row;
instrPtrColumn := pos(instructions[row], '$');
end if;
end for;
while instrPtrRow >= 1 and instrPtrRow <= length(instructions) and
instrPtrColumn >= 1 and instrPtrColumn <= length(instructions[instrPtrRow]) do
case instructions[instrPtrRow][instrPtrColumn] of
when {'>'}: incr(dataPointer);
when {'<'}: decr(dataPointer);
when {'+'}: incr(memory[dataPointer]);
when {'-'}: decr(memory[dataPointer]);
when {'.'}: write(output, memory[dataPointer]);
when {','}: memory[dataPointer] := getc(input);
when {'/'}: helpDir := rowDir;
rowDir := -columnDir;
columnDir := -helpDir;
when {'\\'}: helpDir := rowDir;
rowDir := columnDir;
columnDir := helpDir;
when {'!'}: instrPtrRow +:= rowDir;
instrPtrColumn +:= columnDir;
when {'?'}: if memory[dataPointer] = '\0;' then
instrPtrRow +:= rowDir;
instrPtrColumn +:= columnDir;
end if;
end case;
instrPtrRow +:= rowDir;
instrPtrColumn +:= columnDir;
end while;
end func;
# SNUSP implementation of Hello World.
const string: helloWorld is "/++++!/===========?\\>++.>+.+++++++..+++\\\n\
\\\+++\\ | /+>+++++++>/ /++++++++++<<.++>./\n\
\$+++/ | \\+++++++++>\\ \\+++++.>.+++.-----\\\n\
\ \\==-<<<<+>+++/ /=.>.+>.--------.-/";
const proc: main is func
begin
snusp(helloWorld, 5, IN, OUT);
end func; |
http://rosettacode.org/wiki/Execute_SNUSP | Execute SNUSP | Execute SNUSP is an implementation of SNUSP.
Other implementations of SNUSP.
RCSNUSP
SNUSP
An implementation need only properly implement the Core SNUSP instructions ('$', '\', '/', '+', '-', '<', '>', ',', '.', '!', and '?'). Modular SNUSP ('#', '@') and Bloated SNUSP (':', ';', '%', and '&') are also allowed, but not required. Any extra characters that you implement should be noted in the description of your implementation. Any cell size is allowed, EOF support is optional, as is whether you have bounded or unbounded memory.
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
const proc: snusp (in string: sourceCode, in integer: memSize, inout file: input, inout file: output) is func
local
var array string: instructions is 0 times "";
var array char: memory is 0 times ' ';
var integer: dataPointer is 1;
var integer: instrPtrRow is 0;
var integer: instrPtrColumn is 0;
var integer: rowDir is 0;
var integer: columnDir is 1;
var integer: helpDir is 0;
var integer: row is 0;
begin
instructions := split(sourceCode, "\n");
memory := memSize times '\0;';
for key row range instructions do
if pos(instructions[row], '$') <> 0 then
instrPtrRow := row;
instrPtrColumn := pos(instructions[row], '$');
end if;
end for;
while instrPtrRow >= 1 and instrPtrRow <= length(instructions) and
instrPtrColumn >= 1 and instrPtrColumn <= length(instructions[instrPtrRow]) do
case instructions[instrPtrRow][instrPtrColumn] of
when {'>'}: incr(dataPointer);
when {'<'}: decr(dataPointer);
when {'+'}: incr(memory[dataPointer]);
when {'-'}: decr(memory[dataPointer]);
when {'.'}: write(output, memory[dataPointer]);
when {','}: memory[dataPointer] := getc(input);
when {'/'}: helpDir := rowDir;
rowDir := -columnDir;
columnDir := -helpDir;
when {'\\'}: helpDir := rowDir;
rowDir := columnDir;
columnDir := helpDir;
when {'!'}: instrPtrRow +:= rowDir;
instrPtrColumn +:= columnDir;
when {'?'}: if memory[dataPointer] = '\0;' then
instrPtrRow +:= rowDir;
instrPtrColumn +:= columnDir;
end if;
end case;
instrPtrRow +:= rowDir;
instrPtrColumn +:= columnDir;
end while;
end func;
# SNUSP implementation of Hello World.
const string: helloWorld is "/++++!/===========?\\>++.>+.+++++++..+++\\\n\
\\\+++\\ | /+>+++++++>/ /++++++++++<<.++>./\n\
\$+++/ | \\+++++++++>\\ \\+++++.>.+++.-----\\\n\
\ \\==-<<<<+>+++/ /=.>.+>.--------.-/";
const proc: main is func
begin
snusp(helloWorld, 5, IN, OUT);
end func; |
http://rosettacode.org/wiki/Execute_SNUSP | Execute SNUSP | Execute SNUSP is an implementation of SNUSP.
Other implementations of SNUSP.
RCSNUSP
SNUSP
An implementation need only properly implement the Core SNUSP instructions ('$', '\', '/', '+', '-', '<', '>', ',', '.', '!', and '?'). Modular SNUSP ('#', '@') and Bloated SNUSP (':', ';', '%', and '&') are also allowed, but not required. Any extra characters that you implement should be noted in the description of your implementation. Any cell size is allowed, EOF support is optional, as is whether you have bounded or unbounded memory.
| #Tcl | Tcl | import "io" for Stdin
// 'raw' is a multi-line string
var snusp = Fn.new { |dlen, raw|
var ds = List.filled(dlen, 0) // data store
var dp = 0 // data pointer
// remove leading \n if it's there
if (raw[0] == "\n") raw = raw[1..-1]
// make 2 dimensional instruction store & declare instruction pointers
var s = raw.split("\n")
var ipr = 0
var ipc = 0
// look for starting instruction
for (r in 0...s.count) {
var row = s[r]
var outer = false
for (c in 0...row.count) {
var i = row[c]
if (i == "$") {
ipr = r
ipc = c
outer = true
break
}
}
if (outer) break
}
var id = 0
var step = Fn.new {
if (id&1 == 0) {
ipc = ipc + 1 - (id&2)
} else {
ipr = ipr + 1 - (id&2)
}
}
// execute
while (ipr >= 0 && ipr < s.count && ipc >= 0 && ipc < s[ipr].count) {
var c = s[ipr][ipc]
if (c == ">") {
dp = dp + 1
} else if (c == "<") {
dp = dp - 1
} else if (c == "+") {
ds[dp] = ds[dp] + 1
} else if (c == "-") {
ds[dp] = ds[dp] - 1
} else if (c == ".") {
System.write(String.fromByte(ds[dp]))
} else if (c == ",") {
ds[dp] = Stdin.readByte()
} else if (c == "/") {
id = ~id
} else if (c == "\\") {
id = id ^ 1
} else if (c == "!") {
step.call()
} else if (c == "?") {
if (ds[dp] == 0) step.call()
}
step.call()
}
}
var hw =
"/++++!/===========?\\>++.>+.+++++++..+++\\\n" +
"\\+++\\ | /+>+++++++>/ /++++++++++<<.++>./\n" +
"$+++/ | \\+++++++++>\\ \\+++++.>.+++.-----\\\n" +
" \\==-<<<<+>+++/ /=.>.+>.--------.-/"
snusp.call(5, hw) |
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.
| #Lua | Lua | -- Extend your language, in Lua, 6/17/2020 db
-- not to be taken seriously, ridiculous, impractical, esoteric, obscure, arcane ... but it works
-------------------
-- IMPLEMENTATION:
-------------------
function if2(cond1, cond2)
return function(code)
code = code:gsub("then2", "[3]=load[[")
code = code:gsub("else1", "]],[2]=load[[")
code = code:gsub("else2", "]],[1]=load[[")
code = code:gsub("neither", "]],[0]=load[[")
code = "return {" .. code .. "]]}"
local block, err = load(code)
if (err) then error("syntax error in if2 statement: "..err) end
local tab = block()
tab[(cond1 and 2 or 0) + (cond2 and 1 or 0)]()
end
end
----------
-- TESTS:
----------
for i = 1, 2 do
for j = 1, 2 do
print("i="..i.." j="..j)
if2 ( i==1, j==1 )[[ then2
print("both conditions are true")
else1
print("first is true, second is false")
else2
print("first is false, second is true")
neither
print("both conditions are false")
]]
end
end |
http://rosettacode.org/wiki/FizzBuzz | FizzBuzz | Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
| #REBOL | REBOL | rebol [
Title: "FizzBuzz"
URL: http://rosettacode.org/wiki/FizzBuzz
]
; Concatenative. Note use of 'case/all' construct to evaluate all
; conditions. I use 'copy' to allocate a new string each time through
; the loop -- otherwise 'x' would get very long...
repeat i 100 [
x: copy ""
case/all [
0 = mod i 3 [append x "Fizz"]
0 = mod i 5 [append x "Buzz"]
"" = x [x: mold i]
]
print x
] |
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.
| #Kotlin | Kotlin | fun isPrime(n: Int) : Boolean {
if (n < 2) return false
if (n % 2 == 0) return n == 2
if (n % 3 == 0) return n == 3
var d : Int = 5
while (d * d <= n) {
if (n % d == 0) return false
d += 2
if (n % d == 0) return false
d += 4
}
return true
}
fun generatePrimes() = sequence {
yield(2)
var p = 3
while (p <= Int.MAX_VALUE) {
if (isPrime(p)) yield(p)
p += 2
}
}
fun main(args: Array<String>) {
val primes = generatePrimes().take(10000) // generate first 10,000 primes
println("First 20 primes : ${primes.take(20).toList()}")
println("Primes between 100 and 150 : ${primes.filter { it in 100..150 }.toList()}")
println("Number of primes between 7700 and 8000 = ${primes.filter { it in 7700..8000 }.count()}")
println("10,000th prime = ${primes.last()}")
} |
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.
| #68000_Assembly | 68000 Assembly | ;
; Brainfuck interpreter by Thorham
;
; 68000+ AmigaOs2+
;
; Cell size is a byte
;
incdir "asminc:"
include "dos/dosextens.i"
include "lvo/lvos.i"
execBase equ 4
start
; parse command line parameter
move.l a0,fileName
move.b (a0)+,d0
beq exit ; no parameter
cmp.b #'"',d0 ; filter out double quotes
bne .loop
addq.l #1,fileName
.loop
move.b (a0)+,d0
cmp.b #'"',d0 ; filter out double quotes
beq .done
cmp.b #32,d0
bge .loop
.done
clr.b -(a0) ; end of string
; open dos library
move.l execBase,a6
lea dosName,a1
moveq #36,d0
jsr _LVOOpenLibrary(a6)
move.l d0,dosBase
beq exit
; get stdin and stdout handles
move.l dosBase,a6
jsr _LVOInput(a6)
move.l d0,stdIn
beq exit
jsr _LVOOutput(a6)
move.l d0,stdOut
beq exit
move.l stdIn,d1
jsr _LVOFlush(a6)
; open file
move.l fileName,d1
move.l #MODE_OLDFILE,d2
jsr _LVOOpen(a6)
move.l d0,fileHandle
beq exit
; examine file
lea fileInfoBlock,a4
move.l fileHandle,d1
move.l a4,d2
jsr _LVOExamineFH(a6)
tst.w d0
beq exit
; exit if the file is a folder
tst.l fib_DirEntryType(a4)
bge exit
; allocate file memory
move.l execBase,a6
move.l fib_Size(a4),d0
beq exit ; exit if file is empty
clr.l d1
jsr _LVOAllocVec(a6)
move.l d0,program
beq exit
; read file
move.l dosBase,a6
move.l fileHandle,d1
move.l program,d2
move.l fib_Size(a4),d3
jsr _LVORead(a6)
tst d0
ble exit ; exit if read didn't succeed
; close file
move.l fileHandle,d1
jsr _LVOClose(a6)
clr.l fileHandle
; clear tape (bss section is allocated by os but not cleared)
lea tape,a0
lea tapeEnd,a1
.loopClear
clr.b (a0)+
cmp.l a0,a1
bne .loopClear
; interpreter
move.l program,a2
lea tape,a3
clr.l d2
move.l a2,d6 ; start of program
move.l a2,d7 ; end of program
add.l fib_Size(a4),d7
loop
move.b (a2)+,d2
cmp.b #">",d2
beq .incPtr
cmp.b #"<",d2
beq .decPtr
cmp.b #"+",d2
beq .incMem
cmp.b #"-",d2
beq .decMem
cmp.b #".",d2
beq .outMem
cmp.b #",",d2
beq .inMem
cmp.b #"[",d2
beq .jmpForward
cmp.b #"]",d2
beq .jmpBack
; next command
.next
cmp.l d7,a2 ; test end of program
blt loop
; end of program reached
bra exit
; command implementations
.incPtr
addq.l #1,a3
cmp.l #tapeEnd,a3 ; test end of tape
bge exit
bra .next
.decPtr
subq.l #1,a3
cmp.l #tape,a3 ; test start of tape
blt exit
bra .next
.incMem
addq.b #1,(a3)
bra .next
.decMem
subq.b #1,(a3)
bra .next
.outMem
move.l stdOut,d1
move.b (a3),d2
jsr _LVOFPutC(a6)
bra .next
.inMem
move.l stdIn,d1
jsr _LVOFGetC(a6)
cmp.b #27,d0 ; convert escape to 0
bne .notEscape
moveq #0,d0
.notEscape
move.b d0,(a3)
bra .next
.jmpForward
tst.b (a3)
bne .next
move.l a2,a4
clr.l d3
.loopf
cmp.l d7,a4 ; test end of program
bge exit
move.b (a4)+,d2
cmp.b #"[",d2
bne .lf
addq.l #1,d3
bra .loopf
.lf
cmp.b #"]",d2
bne .loopf
subq.l #1,d3
bge .loopf
move.l a4,a2
bra .next
.jmpBack
tst.b (a3)
beq .next
move.l a2,a4
clr.l d3
.loopb
move.b -(a4),d2
cmp.l d6,a4 ; test start of program
blt exit
cmp.b #"]",d2
bne .lb
addq.l #1,d3
bra .loopb
.lb
cmp.b #"[",d2
bne .loopb
subq.l #1,d3
bgt .loopb
move.l a4,a2
bra .next
; cleanup and exit
exit
move.l dosBase,a6
move.l fileHandle,d1
beq .noFile
jsr _LVOClose(a6)
.noFile
move.l execBase,a6
move.l program,a1
tst.l a1
beq .noMem
jsr _LVOFreeVec(a6)
.noMem
move.l dosBase,a1
tst.l a1
beq .noLib
jsr _LVOCloseLibrary(a6)
.noLib
rts
; data
section data,data_p
dosBase
dc.l 0
fileName
dc.l 0
fileHandle
dc.l 0
fileInfoBlock
dcb.b fib_SIZEOF
stdIn
dc.l 0
stdOut
dc.l 0
program
dc.l 0
dosName
dc.b "dos.library",0
; tape memory
section mem,bss_p
tape
ds.b 1024*64
tapeEnd
|
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.
| #8080_Assembly | 8080 Assembly | MRATE: equ 26 ; Chance of mutation (MRATE/256)
COPIES: equ 100 ; Amount of copies to make
fname1: equ 5Dh ; First filename on command line (used for RNG seed)
fname2: equ 6Dh ; Second filename (also used for RNG seed)
org 100h
;;; Make random seed from the two CP/M 'filenames'
lxi b,rnddat
lxi h,fname1
xra a
call seed ; First four bytes from fn1 make X
call seed ; Second four bytes from fn1 make A
mvi l,fname2
call seed ; First four bytes from fn2 make B
call seed ; Second four bytes from fn2 make C
;;; Create the first parent (random string)
lxi h,parent
mvi e,tgtsz-1
genchr: call rndchr ; Get random character
mov m,a ; Store it
inx h
dcr e
jnz genchr
mvi m,'$' ; CP/M string terminator
;;; Main loop
loop: lxi d,parent
push d
call puts ; Print current parent
pop h ; Calculate fitness
call fitnes
xra a ; If it is 0, all characters match,
ora d
rz ; So we stop.
lxi h,kids ; Otherwise, set HL to start of children,
mvi a,0FFh ; Initialize maximum fitness value
sta maxfit
mvi a,COPIES ; Initialize copy counter
sta copies
;;; Make copies
copy: push h ; Store the place where the copy will go
call mutcpy ; Make a mutated copy of the parent
pop h ; Get the place where the copy went
push h ; But keep it on the stack
call fitnes ; Calculate the fitness of that copy
pop h ; Get place where copy went
lda maxfit ; Get current best fitness
cmp d ; Compare to fitness of current copy
jc next ; If it wasn't better, next copy
shld maxptr ; If it was better, store pointer
mov a,d
sta maxfit ; And new max fitness
next: lxi b,tgtsz ; Get place for next copy
dad b
xchg ; Keep in DE
lxi h,copies
dcr m ; Any copies left to make?
xchg
jnz copy ; Then make another copy
lhld maxptr ; Otherwise, get location of copy with best fitness
lxi b,parent ; Make that the new parent
pcopy: mov a,m ; Get character from copy
inx h
stax b ; Store into location of parent
inx b
cpi '$' ; Check for string terminator
jnz pcopy ; If it isn't, copy next character
jmp loop ; Otherwise, mutate new parent
;;; Make a copy of the parent, mutate it, and store it at [HL].
mutcpy: lxi b,parent
mcloop: ldax b ; Get current character
inx b
mov m,a ; Write it to new location
inx h
cpi '$' ; Was it the string terminator?
rz ; Then stop
call rand ; Otherwise, get random value
cpi MRATE ; Should we mutate this character?
jnc mcloop ; If not, just copy next character
call rndchr ; Otherwise, get a random character
dcx h ; And store it instead of the character we had
mov m,a
inx h
jmp mcloop
;;; Calculate fitness of candidate under [HL], fitness is
;;; returned in D. Fitness is "inverted", i.e. a fitness of 0
;;; means everything matches.
fitnes: lxi b,target
lxi d,tgtsz ; E=counter, D=fitness
floop: dcr e ; Done yet?
rz ; If so, return.
ldax b ; Get target character
inx b
cmp m ; Compare to current character
inx h
jz floop ; If they match, don't do anything
inr d ; If they don't match, count this
jmp floop
;;; Generate a random uppercase letter, or a space
;;; Return in A, other registers preserved
rndchr: call rand ; Get a random value
ani 31 ; from 0 to 31
cpi 28 ; If 28 or higher,
jnc rndchr ; get another value
adi 'A' ; Make uppercase letter
cpi 'Z'+1 ; If the result is 'Z' or lower,
rc ; then return it,
mvi a,' ' ; otherwise return a space
ret
;;; Load 4 bytes from [HL] and use them, plus A, as part of seed
;;; in [BC]
seed: mvi e,4 ; 4 bytes
sloop: xra m
inx h
dcr e
jnz sloop
stax b
inx b
ret
;;; Random number generator using XABC algorithm
rand: push h
lxi h,rnddat
inr m ; X++
mov a,m ; X
inx h
xra m ; ^ C
inx h
xra m ; ^ A
mov m,a ; -> A
inx h
add m ; + B
mov m,a ; -> B
rar ; >>1 (ish)
dcx h
xra m ; ^ A
dcx h
add m ; + C
mov m,a ; -> C
pop h
ret
;;; Print string to console using CP/M, saving all registers
puts: push h
push d
push b
push psw
mvi c,9 ; CP/M print string
call 5
lxi d,nl ; Print a newline as well
mvi c,9
call 5
pop b
pop d
pop h
pop psw
ret
nl: db 13,10,'$'
target: db 'METHINKS IT IS LIKE A WEASEL$'
tgtsz: equ $-target
rnddat: ds 4 ; RNG state
copies: ds 1 ; Copies left to make
maxfit: ds 1 ; Best fitness seen
maxptr: ds 2 ; Pointer to copy with best fitness
parent: equ $ ; Store current parent here
kids: equ $+tgtsz ; Store mutated copies here |
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
| #J | J | fibN=: (-&2 +&$: -&1)^:(1&<) M."0 |
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
| #Run_BASIC | Run BASIC | PRINT "Factors of 45 are ";factorlist$(45)
PRINT "Factors of 12345 are "; factorlist$(12345)
END
function factorlist$(f)
DIM L(100)
FOR i = 1 TO SQR(f)
IF (f MOD i) = 0 THEN
L(c) = i
c = c + 1
IF (f <> i^2) THEN
L(c) = (f / i)
c = c + 1
END IF
END IF
NEXT i
s = 1
while s = 1
s = 0
for i = 0 to c-1
if L(i) > L(i+1) and L(i+1) <> 0 then
t = L(i)
L(i) = L(i+1)
L(i+1) = t
s = 1
end if
next i
wend
FOR i = 0 TO c-1
factorlist$ = factorlist$ + STR$(L(i)) + ", "
NEXT
end function |
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
| #Rust | Rust | fn main() {
assert_eq!(vec![1, 2, 4, 5, 10, 10, 20, 25, 50, 100], factor(100)); // asserts that two expressions are equal to each other
assert_eq!(vec![1, 101], factor(101));
}
fn factor(num: i32) -> Vec<i32> {
let mut factors: Vec<i32> = Vec::new(); // creates a new vector for the factors of the number
for i in 1..((num as f32).sqrt() as i32 + 1) {
if num % i == 0 {
factors.push(i); // pushes smallest factor to factors
factors.push(num/i); // pushes largest factor to factors
}
}
factors.sort(); // sorts the factors into numerical order for viewing purposes
factors // returns the factors
} |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #Factor | Factor | USING: combinators command-line formatting interpolate io kernel
math math.ranges multiline namespaces sequences ;
IN: rosetta-code.hq9+
STRING: verse
${3} bottle${1} of beer on the wall
${3} bottle${1} of beer
Take one down, pass it around
${2} bottle${0} of beer on the wall
;
: bottles ( -- )
99 1 [a,b]
[ dup 1 - 2dup [ 1 = "" "s" ? ] bi@ verse interpolate nl ]
each ;
SYMBOL: accumulator
CONSTANT: commands
{
{ CHAR: H [ drop "Hello, world!" print ] }
{ CHAR: Q [ print ] }
{ CHAR: 9 [ drop bottles ] }
{ CHAR: + [ drop accumulator inc ] }
[ nip "Invalid command: %c" sprintf throw ]
}
: interpret-HQ9+ ( str -- )
dup [ commands case ] with each accumulator off ;
: main ( -- ) command-line get first interpret-HQ9+ ;
MAIN: main |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #Forth | Forth | variable accumulator
: H cr ." Hello, world!" ;
: Q cr 2dup type ;
: 9 99 verses ; \ http://rosettacode.org/wiki/99_Bottles_of_Beer#Forth
: + 1 accumulator +! ;
: hq9+ ( "code" -- )
parse-word 2dup bounds ?do
i 1 [ get-current literal ] search-wordlist
if execute else true abort" invalid HQ9+ instruction"
then loop 2drop ; |
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
| #C | C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <ctype.h>
typedef struct { char * s; size_t alloc_len; } string;
typedef struct {
char *pat, *repl;
int terminate;
} rule_t;
typedef struct {
int n;
rule_t *rules;
char *buf;
} ruleset_t;
void ruleset_del(ruleset_t *r)
{
if (r->rules) free(r->rules);
if (r->buf) free(r->buf);
free(r);
}
string * str_new(const char *s)
{
int l = strlen(s);
string *str = malloc(sizeof(string));
str->s = malloc(l + 1);
strcpy(str->s, s);
str->alloc_len = l + 1;
return str;
}
void str_append(string *str, const char *s, int len)
{
int l = strlen(str->s);
if (len == -1) len = strlen(s);
if (str->alloc_len < l + len + 1) {
str->alloc_len = l + len + 1;
str->s = realloc(str->s, str->alloc_len);
}
memcpy(str->s + l, s, len);
str->s[l + len] = '\0';
}
/* swap content of dest and src, and truncate src string */
void str_transfer(string *dest, string *src)
{
size_t tlen = dest->alloc_len;
dest->alloc_len = src->alloc_len;
src->alloc_len = tlen;
char *ts = dest->s;
dest->s = src->s;
src->s = ts;
src->s[0] = '\0';
}
void str_del(string *s)
{
if (s->s) free(s->s);
free(s);
}
void str_markov(string *str, ruleset_t *r)
{
int i, j, sl, pl;
int changed = 0, done = 0;
string *tmp = str_new("");
while (!done) {
changed = 0;
for (i = 0; !done && !changed && i < r->n; i++) {
pl = strlen(r->rules[i].pat);
sl = strlen(str->s);
for (j = 0; j < sl; j++) {
if (strncmp(str->s + j, r->rules[i].pat, pl))
continue;
str_append(tmp, str->s, j);
str_append(tmp, r->rules[i].repl, -1);
str_append(tmp, str->s + j + pl, -1);
str_transfer(str, tmp);
changed = 1;
if (r->rules[i].terminate)
done = 1;
break;
}
}
if (!changed) break;
}
str_del(tmp);
return;
}
ruleset_t* read_rules(const char *name)
{
struct stat s;
char *buf;
size_t i, j, k, tmp;
rule_t *rules = 0;
int n = 0; /* number of rules */
int fd = open(name, O_RDONLY);
if (fd == -1) return 0;
fstat(fd, &s);
buf = malloc(s.st_size + 2);
read(fd, buf, s.st_size);
buf[s.st_size] = '\n';
buf[s.st_size + 1] = '\0';
close(fd);
for (i = j = 0; buf[i] != '\0'; i++) {
if (buf[i] != '\n') continue;
/* skip comments */
if (buf[j] == '#' || i == j) {
j = i + 1;
continue;
}
/* find the '->' */
for (k = j + 1; k < i - 3; k++)
if (isspace(buf[k]) && !strncmp(buf + k + 1, "->", 2))
break;
if (k >= i - 3) {
printf("parse error: no -> in %.*s\n", i - j, buf + j);
break;
}
/* left side: backtrack through whitespaces */
for (tmp = k; tmp > j && isspace(buf[--tmp]); );
if (tmp < j) {
printf("left side blank? %.*s\n", i - j, buf + j);
break;
}
buf[++tmp] = '\0';
/* right side */
for (k += 3; k < i && isspace(buf[++k]););
buf[i] = '\0';
rules = realloc(rules, sizeof(rule_t) * (1 + n));
rules[n].pat = buf + j;
if (buf[k] == '.') {
rules[n].terminate = 1;
rules[n].repl = buf + k + 1;
} else {
rules[n].terminate = 0;
rules[n].repl = buf + k;
}
n++;
j = i + 1;
}
ruleset_t *r = malloc(sizeof(ruleset_t));
r->buf = buf;
r->rules = rules;
r->n = n;
return r;
}
int test_rules(const char *s, const char *file)
{
ruleset_t * r = read_rules(file);
if (!r) return 0;
printf("Rules from '%s' ok\n", file);
string *ss = str_new(s);
printf("text: %s\n", ss->s);
str_markov(ss, r);
printf("markoved: %s\n", ss->s);
str_del(ss);
ruleset_del(r);
return printf("\n");
}
int main()
{
/* rule 1-5 are files containing rules from page top */
test_rules("I bought a B of As from T S.", "rule1");
test_rules("I bought a B of As from T S.", "rule2");
test_rules("I bought a B of As W my Bgage from T S.", "rule3");
test_rules("_1111*11111_", "rule4");
test_rules("000000A000000", "rule5");
return 0;
} |
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.
| #Delphi | Delphi | program ExceptionsInNestedCall;
{$APPTYPE CONSOLE}
uses SysUtils;
type
U0 = class(Exception)
end;
U1 = class(Exception)
end;
procedure Baz(i: Integer);
begin
if i = 0 then
raise U0.Create('U0 Error message')
else
raise U1.Create('U1 Error message');
end;
procedure Bar(i: Integer);
begin
Baz(i);
end;
procedure Foo;
var
i: Integer;
begin
for i := 0 to 1 do
begin
try
Bar(i);
except
on E: U0 do
Writeln('Exception ' + E.ClassName + ' caught');
end;
end;
end;
begin
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
| #BBC_BASIC | BBC BASIC | ON ERROR PROCerror(ERR, REPORT$) : END
ERROR 100, "User-generated exception"
END
DEF PROCerror(er%, rpt$)
PRINT "Exception occurred"
PRINT "Error number was " ; er%
PRINT "Error string was " rpt$
ENDPROC |
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
| #blz | blz |
try
1 / 0 # Throw an exception
print("unreachable code")
catch
print("An error occured!")
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
| #AutoIt | AutoIt | Run(@ComSpec & " /c " & 'pause', "", @SW_HIDE) |
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
| #AWK | AWK | BEGIN {
system("ls") # Unix
#system("dir") # DOS/MS-Windows
} |
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
| #Aime | Aime | integer
factorial(integer n)
{
integer i, result;
result = 1;
i = 1;
while (i < n) {
i += 1;
result *= i;
}
return result;
} |
http://rosettacode.org/wiki/Exponentiation_operator | Exponentiation operator | Most programming languages have a built-in implementation of exponentiation.
Task
Re-implement integer exponentiation for both intint and floatint as both a procedure, and an operator (if your language supports operator definition).
If the language supports operator (or procedure) overloading, then an overloaded form should be provided for both intint and floatint variants.
Related tasks
Exponentiation order
arbitrary-precision integers (included)
Exponentiation with infix operators in (or operating on) the base
| #ERRE | ERRE | PROGRAM POWER
PROCEDURE POWER(A,B->POW) ! this routine handles only *INTEGER* powers
LOCAL FLAG%
IF B<0 THEN B=-B FLAG%=TRUE
POW=1
FOR X=1 TO B DO
POW=POW*A
END FOR
IF FLAG% THEN POW=1/POW
END PROCEDURE
BEGIN
POWER(11,-2->POW) PRINT(POW)
POWER(π,3->POW) PRINT(POW)
END PROGRAM |
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
| #F.23 | F# |
//Integer Exponentiation, more interesting anyway than repeated multiplication. Nigel Galloway, October 12th., 2018
let rec myExp n g=match g with
|0 ->1
|g when g%2=1 ->n*(myExp n (g-1))
|_ ->let p=myExp n (g/2) in p*p
printfn "%d" (myExp 3 15)
|
http://rosettacode.org/wiki/Executable_library | Executable library | The general idea behind an executable library is to create a library
that when used as a library does one thing;
but has the ability to be run directly via command line.
Thus the API comes with a CLI in the very same source code file.
Task detail
Create a library/module/dll/shared object/... for a programming language that contains a function/method called hailstone that is a function taking a positive integer and returns the Hailstone sequence for that number.
The library, when executed directly should satisfy the remaining requirements of the Hailstone sequence task:
2. Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
3. Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.
Create a second executable to calculate the following:
Use the library's hailstone function, in the standard manner, (or document how this use deviates from standard use of a library), together with extra code in this executable, to find the hailstone length returned most often for 1 ≤ n < 100,000.
Explain any extra setup/run steps needed to complete the task.
Notes:
It is assumed that for a language that overwhelmingly ships in a compiled form, such as C, the library must also be an executable and the compiled user of that library is to do so without changing the compiled library. I.e. the compile tool-chain is assumed not to be present in the runtime environment.
Interpreters are present in the runtime environment. | #PicoLisp | PicoLisp | #!/usr/bin/picolisp /usr/lib/picolisp/lib.l
(de hailstone (N)
(make
(until (= 1 (link N))
(setq N
(if (bit? 1 N)
(inc (* N 3))
(/ N 2) ) ) ) ) )
(de hailtest ()
(let L (hailstone 27)
(test 112 (length L))
(test (27 82 41 124) (head 4 L))
(test (8 4 2 1) (tail 4 L)) )
(let N (maxi '((N) (length (hailstone N))) (range 1 100000))
(test 77031 N)
(test 351 (length (hailstone N))) )
(println 'OK)
(bye) ) |
http://rosettacode.org/wiki/Executable_library | Executable library | The general idea behind an executable library is to create a library
that when used as a library does one thing;
but has the ability to be run directly via command line.
Thus the API comes with a CLI in the very same source code file.
Task detail
Create a library/module/dll/shared object/... for a programming language that contains a function/method called hailstone that is a function taking a positive integer and returns the Hailstone sequence for that number.
The library, when executed directly should satisfy the remaining requirements of the Hailstone sequence task:
2. Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
3. Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.
Create a second executable to calculate the following:
Use the library's hailstone function, in the standard manner, (or document how this use deviates from standard use of a library), together with extra code in this executable, to find the hailstone length returned most often for 1 ≤ n < 100,000.
Explain any extra setup/run steps needed to complete the task.
Notes:
It is assumed that for a language that overwhelmingly ships in a compiled form, such as C, the library must also be an executable and the compiled user of that library is to do so without changing the compiled library. I.e. the compile tool-chain is assumed not to be present in the runtime environment.
Interpreters are present in the runtime environment. | #Pike | Pike | #!/usr/bin/env pike
int next(int n)
{
if (n==1)
return 0;
if (n%2)
return 3*n+1;
else
return n/2;
}
array(int) hailstone(int n)
{
array seq = ({ n });
while (n=next(n))
seq += ({ n });
return seq;
}
void main()
{
array(int) two = hailstone(27);
if (equal(two[0..3], ({ 27, 82, 41, 124 })) && equal(two[<3..], ({ 8,4,2,1 })))
write("sizeof(({ %{%d, %}, ... %{%d, %} }) == %d\n", two[0..3], two[<3..], sizeof(two));
mapping longest = ([ "length":0, "start":0 ]);
foreach(allocate(100000); int start; )
{
int length = sizeof(hailstone(start));
if (length > longest->length)
{
longest->length = length;
longest->start = start;
}
}
write("longest sequence starting at %d has %d elements\n", longest->start, longest->length);
} |
http://rosettacode.org/wiki/Extreme_floating_point_values | Extreme floating point values | The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity.
The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe other), extreme floating point values in your language and assign them to variables.
Print the values of these variables if possible; and show some arithmetic with these values and variables.
If your language can directly enter these extreme floating point values then show it.
See also
What Every Computer Scientist Should Know About Floating-Point Arithmetic
Related tasks
Infinity
Detect division by zero
Literals/Floating point
| #Tcl | Tcl | % package require Tcl 8.5
8.5.2
% expr inf+1
Inf
% set inf_val [expr {1.0 / 0.0}]
Inf
% set neginf_val [expr {-1.0 / 0.0}]
-Inf
% set negzero_val [expr {1.0 / $neginf_val}]
-0.0
% expr {0.0 / 0.0}
domain error: argument not in valid range
% expr nan
domain error: argument not in valid range
% expr {1/-inf}
-0.0 |
http://rosettacode.org/wiki/Extreme_floating_point_values | Extreme floating point values | The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity.
The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe other), extreme floating point values in your language and assign them to variables.
Print the values of these variables if possible; and show some arithmetic with these values and variables.
If your language can directly enter these extreme floating point values then show it.
See also
What Every Computer Scientist Should Know About Floating-Point Arithmetic
Related tasks
Infinity
Detect division by zero
Literals/Floating point
| #Wren | Wren | var inf = 1/0
var negInf = -1/0
var nan = 0/0
var negZero = -0
System.print([inf, negInf, nan, negZero])
System.print([inf + inf, negInf + inf, nan * nan, negZero == 0])
System.print([inf/inf, negInf/2, nan + inf, negZero/0])
|
http://rosettacode.org/wiki/Execute_SNUSP | Execute SNUSP | Execute SNUSP is an implementation of SNUSP.
Other implementations of SNUSP.
RCSNUSP
SNUSP
An implementation need only properly implement the Core SNUSP instructions ('$', '\', '/', '+', '-', '<', '>', ',', '.', '!', and '?'). Modular SNUSP ('#', '@') and Bloated SNUSP (':', ';', '%', and '&') are also allowed, but not required. Any extra characters that you implement should be noted in the description of your implementation. Any cell size is allowed, EOF support is optional, as is whether you have bounded or unbounded memory.
| #Wren | Wren | import "io" for Stdin
// 'raw' is a multi-line string
var snusp = Fn.new { |dlen, raw|
var ds = List.filled(dlen, 0) // data store
var dp = 0 // data pointer
// remove leading \n if it's there
if (raw[0] == "\n") raw = raw[1..-1]
// make 2 dimensional instruction store & declare instruction pointers
var s = raw.split("\n")
var ipr = 0
var ipc = 0
// look for starting instruction
for (r in 0...s.count) {
var row = s[r]
var outer = false
for (c in 0...row.count) {
var i = row[c]
if (i == "$") {
ipr = r
ipc = c
outer = true
break
}
}
if (outer) break
}
var id = 0
var step = Fn.new {
if (id&1 == 0) {
ipc = ipc + 1 - (id&2)
} else {
ipr = ipr + 1 - (id&2)
}
}
// execute
while (ipr >= 0 && ipr < s.count && ipc >= 0 && ipc < s[ipr].count) {
var c = s[ipr][ipc]
if (c == ">") {
dp = dp + 1
} else if (c == "<") {
dp = dp - 1
} else if (c == "+") {
ds[dp] = ds[dp] + 1
} else if (c == "-") {
ds[dp] = ds[dp] - 1
} else if (c == ".") {
System.write(String.fromByte(ds[dp]))
} else if (c == ",") {
ds[dp] = Stdin.readByte()
} else if (c == "/") {
id = ~id
} else if (c == "\\") {
id = id ^ 1
} else if (c == "!") {
step.call()
} else if (c == "?") {
if (ds[dp] == 0) step.call()
}
step.call()
}
}
var hw =
"/++++!/===========?\\>++.>+.+++++++..+++\\\n" +
"\\+++\\ | /+>+++++++>/ /++++++++++<<.++>./\n" +
"$+++/ | \\+++++++++>\\ \\+++++.>.+++.-----\\\n" +
" \\==-<<<<+>+++/ /=.>.+>.--------.-/"
snusp.call(5, hw) |
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.
| #Lambdatalk | Lambdatalk |
{macro \{if2 (true|false|\{[^{}]*\}) (true|false|\{[^{}]*\})\}
to {if {and $1 $2}
then both are true
else {if {and $1 {not $2}}
then the first is true
else {if {and {not $1} $2}
then the second is true
else neither are true}}}}
{if2 true true} -> both are true
{if2 true false} -> the first is true
{if2 false true} -> the second is true
{if2 false false} -> neither are true
{if2 {< 1 2} {< 3 4}} -> both are true
{if2 {< 1 2} {> 3 4}} -> the first is true
{if2 {> 1 2} {< 3 4}} -> the second is true
{if2 {> 1 2} {> 3 4}} -> neither are 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
| #Red | Red | Red ["FizzBuzz"]
repeat i 100 [
print case [
i % 15 = 0 ["FizzBuzz"]
i % 5 = 0 ["Buzz"]
i % 3 = 0 ["Fizz"]
true [i]
]
] |
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.
| #Lua | Lua | local primegen = {
count_limit = 2,
value_limit = 3,
primelist = { 2, 3 },
nextgenvalue = 5,
nextgendelta = 2,
tbd = function(n)
if n < 2 then return false end
if n % 2 == 0 then return n==2 end
if n % 3 == 0 then return n==3 end
local limit = math.sqrt(n)
for f = 5, limit, 6 do
if n % f == 0 or n % (f+2) == 0 then return false end
end
return true
end,
needmore = function(self)
return (self.count_limit ~= nil and #self.primelist < self.count_limit)
or (self.value_limit ~= nil and self.nextgenvalue < self.value_limit)
end,
generate = function(self, count_limit, value_limit)
self.count_limit = count_limit
self.value_limit = value_limit
while self:needmore() do
if (self.tbd(self.nextgenvalue)) then
self.primelist[#self.primelist+1] = self.nextgenvalue
end
self.nextgenvalue = self.nextgenvalue + self.nextgendelta
self.nextgendelta = 6 - self.nextgendelta
end
end,
filter = function(self, f)
local list = {}
for k,v in ipairs(self.primelist) do
if (f(v)) then list[#list+1] = v end
end
return list
end,
}
primegen:generate(20, nil)
print("First 20 primes: " .. table.concat(primegen.primelist, ", "))
primegen:generate(nil, 150)
print("Primes between 100 and 150: " .. table.concat(primegen:filter(function(v) return v>=100 and v<=150 end), ", "))
primegen:generate(nil, 8000)
print("Number of primes between 7700 and 8000: " .. #primegen:filter(function(v) return v>=7700 and v<=8000 end))
primegen:generate(10000, nil)
print("The 10,000th prime: " .. primegen.primelist[#primegen.primelist])
primegen:generate(100000, nil)
print("The 100,000th prime: " .. primegen.primelist[#primegen.primelist]) |
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.
| #8080_Assembly | 8080 Assembly | ;;; CP/M Brainfuck compiler/interpreter, with a few optimizations
getch: equ 1 ; Read character from console
putch: equ 2 ; Print character to console
puts: equ 9 ; Print string to console
fopen: equ 15 ; Open file
fread: equ 20 ; Read from file
dmaoff: equ 26 ; Set DMA address
fcb: equ 5Ch ; FCB for first command line argument
EOFCH: equ -1 ; Value stored on the tape on EOF
org 100h
jmp start
;;; Print the character on the tape, saving HL (tape location),
;;; and including CR/LF translation.
bfout: push h ; Keep tape location
mov a,m ; What are we printing?
cpi 10 ; Newline?
jnz outch ; If not, just print the character.
mvi e,13 ; Otherwise, print a carriage return first.
mvi c,putch
call 5
pop h ; Then get the tape back
push h
outch: mov e,m ; Print the character in A.
mvi c,putch
call 5
pop h ; Restore tape location.
ret
;;; Read a character and store it on the tape, including CR/LF
;;; translation; ^Z is EOF.
bfin: push h ; Keep tape location
lda bfeoff ; Have we seen EOF yet?
ana a
jnz bfeof ; If so, return EOF.
mvi c,getch ; Otherwise, read character
call 5
cpi 26 ; Was it EOF?
jz bfeof ; Then handle EOF.
cpi 13 ; Was it CR? (Pressing 'Enter' only gives CR.)
jnz bfin_s ; If not, just store the character.
mvi c,putch ; Otherwise, output a LF (only CR is echoed as well)
mvi e,10
call 5
mvi a,10 ; And then store a LF instead of the CR.
bfin_s: pop h ; Restore tape location
mov m,a ; Store the character
ret
bfeof: sta bfeoff ; Set the EOF flag (A is nonzero here)
pop h ; Restore tape location
mvi m,EOFCH ; Store EOF return value.
ret
bfeoff: db 0 ; EOF flag, EOF seen if nonzero.
;;; Print mismatched brackets error
brkerr: lxi d,ebrk
;;; Print error message under DE and quit
err: mvi c,puts ; Print string
call 5
rst 0 ; Then quit
;;; Error messages.
efile: db 'Cannot read file.$'
ebrk: db 'Mismatched brackets.$'
;;; BF characters
bfchr: db '+-<>,.[]',26
;;; Main program
start: lhld 6 ; Set stack pointer to highest available address
sphl
mvi c,fopen ; Try to open the file given on the command line
lxi d,fcb
call 5
inr a ; A=FF on error,
lxi d,efile ; so if we couldn't open the file, say so, and stop
jz err
;;; Read file into memory in its entirety
lxi d,pgm ; Start of input
block: mvi c,dmaoff
push d ; Keep current address on stack
call 5 ; Set DMA to location of current block
mvi c,fread ; Read 128-byte block to that address
lxi d,fcb
call 5
dcr a ; A=1 = end of file
jz fdone
inr a ; Otherwise, A<>0 = error
lxi d,efile
jnz err
pop h ; Retrieve DMA address
lxi d,128 ; Add 128 (advance to next block)
dad d
xchg ; Put in DE
jmp block ; Go get next block.
fdone: pop h ; When done, find next address
mvi m,26 ; Write EOF, so file always ends with EOF.
;;; Filter out all the non-BF characters
lxi h,pgm ; Output pointer
push h ; On stack
lxi b,pgm ; Input pointer
filter: ldax b ; Get current character
inx b ; Look at next char next time
lxi h,bfchr ; Test against 9 brainfuck characters (8 + EOF)
mvi e,9
filchk: cmp m ; Is it a match?
jz filfnd ; Then we found it
inx h
dcr e
jnz filchk
jmp filter ; Otherwise, try next character
filfnd: pop h ; Get pointer from stack
mov m,a ; Store current character
inx h ; Move pointer
push h ; Store pointer back on stack
cpi 26 ; Reached the end?
jnz filter ; If not, keep going.
;;; Move the program as high up into memory as possible.
lxi h,-1024 ; Keep 1K stack space (allowing 512 levels of nested
dad sp ; loops)
pop d ; Source pointer in DE (destination in HL)
move: ldax d ; Copy backwards
dcx d
mov m,a
dcx h
ana a ; Until zero is reached
jnz move
inx h ; Move pointer to byte after zero
inx h
;;; Compile the Brainfuck code into 8080 machine code
lxi b,0 ; Push zero on stack (as boundary marker)
push b
lxi d,pgm ; DE = start of binary area (HL at start of source)
compil: mov a,m ; Get source byte
cpi '+' ; Plus or minus - change the tape value
jz tapval
cpi '-'
jz tapval
cpi '<' ; Left or right - move the tape
jz tapmov
cpi '>'
jz tapmov
cpi '.' ; Input and output
jz chout
cpi ','
jz chin
cpi '[' ; Start of loop
jz loops
cpi ']' ; End of loop
jz loope
cpi 26 ; EOF?
jz cdone
inx h ; Anything else is ignored
jmp compil
;;; Write code for '+' or '-' (change cell value)
tapval: mvi c,0 ; C = change in value necessary
tapv_s: mov a,m ; Get current byte
cpi '+' ; If plus,
jz tapinc ; Then we need to increment
cpi '-' ; If minus,
jz tapdec ; Then we need to decrement
;;; The effect of the last instructions should be to
;;; change the cell at the tape head by C.
;;; If -3 <= B <= 3, INR M/DCR M are most efficient.
;;; Otherwise, MVI A,NN / ADD M / MOV M,A is most efficient.
mov a,c
ana a ; Zero?
jz compil ; Then we do nothing.
cpi 4 ; Larger than 3?
jc tapinr ; If not, 'INR M' * C
cpi -3 ; Smaller than -3?
jnc tapdcr ; Then, 'DCR M' * -C
xchg ; Otherwise, use an ADD instruction
mvi m,3Eh ; 'MVI A,'
inx h
mov m,c ; C (all math is mod 256)
inx h
mvi m,86h ; 'ADD M'
inx h
mvi m,77h ; 'MOV M,A'
inx h
xchg
jmp compil
tapinc: inr c ; '+' means one more
inx h ; Check next byte
jmp tapv_s
tapdec: dcr c ; '-' means one less
inx h ; Check next byte
jmp tapv_s
tapinr: mvi a,34h ; INR M (increment cell)
jmp wrbyte
tapdcr: mvi a,35h ; DCR M (decrement cell)
jmp wrnegc
;;; Write code for '<' or '>' (move tape head)
tapmov: lxi b,0 ; BC = change in value necessary
tapm_s: mov a,m ; Get current byte
cpi '>' ; If right,
jz taprgt ; Then we need to move the tape right
cpi '<' ; If left,
jz taplft ; Then we need to move the tape left
;;; Move the tape by BC.
;;; If -4 <= BC <= 4, INX H/DCX H are most efficient.
;;; Otherwise, LXI B,NNNN / DAD B is most efficient.
mov a,b ; Is the displacement zero?
ora c
jz compil ; Then do nothing
mov a,b ; Otherwise, is the high byte 0?
ana a
jnz tbchi ; If not, it might be FF, but
mov a,c ; if so, is low byte <= 4?
cpi 5
jc tapinx ; Then we need to write 'INX H' C times
xra a ; Otherwise, do it the long way
tbchi: inr a ; Is the high byte FF?
jnz tapwbc ; If not, we'll have to do it the long way
mov a,c ; But if so, is low byte >= -4?
cpi -4
jnc tapdcx ; Then we can write 'DCX H' -C times
tapwbc: xchg ; Otherwise, use a DAD instruction
mvi m,1h ; 'LXI B,'
inx h
mov m,c ; Low byte
inx h
mov m,b ; High byte
inx h
mvi m,9h ; 'DAD B'
inx h
xchg
jmp compil
taprgt: inx b ; '>' is one to the right
inx h ; Check next byte
jmp tapm_s
taplft: dcx b ; '<' is one to the left
inx h ; Check next byte
jmp tapm_s
tapinx: mvi a,23h ; INX H (move tape right)
jmp wrbyte
tapdcx: mvi a,2Bh ; DCX H (move tape left)
jmp wrnegc
;;; Write the byte in A, -C times, to [DE++]
wrnegc: mov b,a ; Keep A
mov a,c ; Negate C
cma
inr a
mov c,a
mov a,b
;;; Write the byte in A, C times, to [DE++]
wrbyte: stax d
inx d
dcr c
jnz wrbyte
jmp compil
;;; Write code to print the current tape value
chout: inx h ; We know the cmd is '.', so skip it
lxi b,bfout ; Call the output routine
jmp wrcall
;;; Write code to read a character and store it on the tape
chin: inx h ; We know the cmd is ',', so skip it
lxi b,bfin
;;; Write code to CALL the routine with address BC
wrcall: xchg
mvi m,0CDh ; CALL
inx h
mov m,c ; Low byte
inx h
mov m,b ; High byte
inx h
xchg
jmp compil
;;; Write code to start a loop
loops: inx h ; We know the first cmd is '['
mov b,h ; Check for '-]'
mov c,l
ldax b
cpi '-'
jnz loopsw ; If not '-', it's a real loop
inx b
ldax b
cpi ']'
jz lzero ; If ']', we just need to set the cell to 0
;;; Code for loop: MOV A,M / ANA A / JZ cmd-past-loop
loopsw: xchg ; Destination pointer in HL
mvi m,7Eh ; MOV A,M
inx h
mvi m,0A7h ; ANA A
inx h
mvi m,0CAh ; JZ
inx h
inx h ; Advance past where the destination will go
inx h ; (End of loop will fill it in)
push h ; Store the address to jump back to on the stack
xchg
jmp compil
;;; Code to set a cell to zero in one go: MVI M,0
lzero: inx h ; Move past '-]'
inx h
xchg ; Destination pointer in HL
mvi m,36h ; MVI M,
inx h
mvi m,0 ; 0
inx h
xchg
jmp compil
;;; Write code to end a loop: MOV A,M / ANA A / JNZ loop-start
loope: inx h ; We know the first cmd is ']'
xchg ; Destination pointer in HL
mvi m,7Eh ; MOV A,M
inx h
mvi m,0A7h ; ANA A
inx h
mvi m,0C2h ; JNZ
inx h
pop b ; Get loop-start from the stack
mov a,b ; If it is 0, we've hit the sentinel, which means
ora c ; mismatched brackets
jz brkerr
mov m,c ; Store loop-start, low byte first,
inx h
mov m,b ; then high byte.
inx h
dcx b ; The two bytes before loop-start must be filled in
mov a,h ; with the address of the cmd past the loop, high
stax b ; byte last,
dcx b
mov a,l ; then low byte
stax b
xchg
jmp compil
;;; Done: finish the code with a RST 0 to end the program
cdone: xchg
mvi m,0C7h
pop b ; If the brackets are all matched, there should be
mov a,b ; a zero on the stack.
ora c
jnz brkerr
;;; Initialize the tape. The fastest way to fill up memory on the
;;; 8080 is to push values to the stack, so we will fill it up
;;; with zeroes, and position the tape there.
;;; HL contains the top of the program.
lxi d,32 ; The Brainfuck program doesn't use the stack, so
dad d ; reserving 16 levels for CP/M is more than enough.
mov a,l ; Complement the value (almost negation, but low bit
cma ; doesn't really matter here)
mov l,a
mov a,h
cma
mov h,a
dad sp ; Add the current stack pointer, giving bytes to fill
ana a ; Zero carry
mov a,h ; Divide value by two (we push words)
rar
mov h,a
mov a,l
rar
mov l,a
lxi d,0
ztape: push d ; Zero out the tape (on the stack)
dcx h
mov a,h
ora l
jnz ztape
dad sp ; HL is now 0, add SP to get tape bottom
;;; The compiled program is stored after this point, so we just
;;; fall through into it.
nop ; No-op (sentinel value)
pgm: equ $ ; Compiled BF program stored here. |
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.
| #8086_Assembly | 8086 Assembly | bits 16
cpu 8086
MRATE: equ 26 ; Mutation rate (MRATE/256)
COPIES: equ 100 ; Amount of copies to make
gettim: equ 02Ch ; MS-DOS get time function
pstr: equ 9 ; MS-DOS print string
section .text
org 100h
;;; Use MS-DOS time to set random seed
mov ah,gettim
int 21h
mov [rnddat],cx
mov [rnddat+2],dx
;;; Make first parent (random characters)
mov di,parent
mov cx,target.size-1
getchr: call rndchr ; Get random character
stosb ; Store in parent
loop getchr
mov al,'$' ; Write string terminator
stosb
;;; Main loop.
loop: mov bx,parent ; Print current parent
mov dx,bx
call puts
call fitnes ; Check fitness
test cl,cl ; If zero, we're done
jnz nxmut ; If not, do another mutation
ret ; Quit to DOS
nxmut: mov dl,0FFh ; DL = best fitness yet
mov di,kids ; Set DI to start of memory for children
mov ch,COPIES ; CH = amount of copies to make
xor bp,bp
;;; Make copy, mutate, and test fitness
copy: mov bx,di ; Let BX = where next copy will go
call mutcpy ; Make the copy (and adjust DI)
call fitnes ; Check fitness
cmp cl,dl ; Is it better than the previous best one?
ja next ; If not, just do the next one,
mov dl,cl ; Otherwise, this is now the best one
lea bp,[di-target.size] ; Store a pointer to it in BP
next: dec ch ; One copy less
jnz copy ; Make another copy if we need to
mov si,bp ; We're done, the best child becomes
mov di,parent ; the parent for the next generation
mov cx,target.size
rep movsb
jmp loop ; Next generation
;;; Make copy of parent, mutating as we go, and store at [DI]
mutcpy: mov si,parent
.loop: lodsb ; Get byte from parent
stosb ; Store in copy
cmp al,'$' ; Is it '$'?
je .out ; Then we're done
call rand ; Otherwise, should we mutate?
cmp al,MRATE
ja .loop ; If not, do next character
call rndchr ; But if so, get random character,
mov [di-1],al ; and overwrite the current character.
jmp .loop ; Then do the next character.
.out: ret
;;; Get fitness of character in [BX]
fitnes: mov si,target
xor cl,cl ; Fitness
.loop: lodsb ; Get target character
cmp al,'$' ; Done?
je .out ; Then stop
cmp al,[bx] ; Equal to character under [BX]?
lahf ; Keep flags
inc bx ; Increment BX
sahf ; Restore flags (was al=[bx]?)
je .loop ; If equal, do next character
inc cx ; Otherwise, count this as a mismatch
jmp .loop
.out: ret
;;; Generate random character, [A-Z] or space.
rndchr: call rand ; Get random number
and al,31 ; Lower five bits
cmp al,27 ; One of 27 characters?
jae rndchr ; If not, get new random number
add al,'A' ; Make uppercase letter
cmp al,'Z' ; More than 'Z'?
jbe .out ; If not, it's OK
mov al,' ' ; Otherwise, give a space
.out: ret
;;; Random number generator using XABC algorithm
;;; Returns random byte in AL
rand: push cx
push dx
mov cx,[rnddat] ; CH=X CL=A
mov dx,[rnddat+2] ; DH=B DL=C
inc ch ; X++
xor cl,ch ; A ^= X
xor cl,dl ; A ^= C
add dh,cl ; B += A
mov al,dh ; C' = B
shr al,1 ; C' >>= 1
xor al,cl ; C' ^= A
add al,dl ; C' += C
mov dl,al ; C = C'
mov [rnddat],cx
mov [rnddat+2],dx
pop dx
pop cx
ret
;;; Print string in DX, plus a newline, saving registers
puts: push ax
push dx
mov ah,pstr
int 21h
mov dx,nl
int 21h
pop dx
pop ax
ret
section .data
nl: db 13,10,'$'
target: db 'METHINKS IT IS LIKE A WEASEL$'
.size: equ $-target
section .bss
rnddat: resb 4 ; RNG state
parent: resb target.size ; Place to store current parent
kids: resb COPIES*target.size ; Place to store children |
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
| #Java | Java | public static long itFibN(int n)
{
if (n < 2)
return n;
long ans = 0;
long n1 = 0;
long n2 = 1;
for(n--; n > 0; n--)
{
ans = n1 + n2;
n1 = n2;
n2 = ans;
}
return ans;
} |
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
| #Sather | Sather | class MAIN is
factors!(n :INT):INT is
yield 1;
loop i ::= 2.upto!( n.flt.sqrt.int );
if n%i = 0 then
yield i;
if (i*i) /= n then
yield n / i;
end;
end;
end;
yield n;
end;
main is
a :ARRAY{INT} := |3135, 45, 64, 53, 45, 81|;
loop l ::= a.elt!;
#OUT + "factors of " + l + ": ";
loop ri ::= factors!(l);
#OUT + ri + " ";
end;
#OUT + "\n";
end;
end;
end;
|
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #Fortran | Fortran | "bottle" // IF (B.NE.1) THEN "s" FI // " of beer" |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #FreeBASIC | FreeBASIC |
' Intérprete de HQ9+
' FB 1.05.0 Win64
'
Dim Shared codigo As String: codigo = ""
Function HQ9plus(codigo As String) As String
Dim As Byte botellas, cont
Dim acumulador As Uinteger = 0
Dim HQ9plus1 As String
For cont = 1 To Len(codigo)
Select Case Ucase(Mid(codigo, cont, 1))
Case "H"
HQ9plus1 = HQ9plus1 + "Hello, world!"
Case "Q"
HQ9plus1 = HQ9plus1 + codigo
Case "9"
For botellas = 99 To 1 Step -1
HQ9plus1 = HQ9plus1 + Str(botellas) + " bottle"
If (botellas > 1) Then HQ9plus1 = HQ9plus1 + "s"
HQ9plus1 = HQ9plus1 + " of beer on the wall, " + Str(botellas) + " bottle"
If (botellas > 1) Then HQ9plus1 = HQ9plus1 + "s"
HQ9plus1 = HQ9plus1 + " of beer," + Chr(13) + Chr(10) +_
"Take one down, pass it around, " + Str(botellas - 1) + " bottle"
If (botellas > 2) Then HQ9plus1 = HQ9plus1 + "s"
HQ9plus1 = HQ9plus1 + " of beer on the wall." + Chr(13) + Chr(10) + Chr(10)
Next botellas
HQ9plus1 = HQ9plus1 + "No more bottles of beer on the wall, no more bottles of beer." +_
Chr(13) + Chr(10) + "Go to the store and buy some more, 99 bottles of beer on the wall."
Case "+"
acumulador = (acumulador + 1)
Case "E"
End
Case Else
'no es una instrucción válida
End Select
If Mid(codigo, cont, 1) <> "+" Then
HQ9plus1 = HQ9plus1 + Chr(13) + Chr(10)
End If
Next cont
HQ9plus = Left(HQ9plus1, (Len(HQ9plus1) - 2))
End Function
Cls
Do
Input codigo
Print HQ9plus(codigo): Print
Loop While Inkey <> Chr(27)
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
| #C.2B.2B | C++ |
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
struct rule
{
std::string pattern;
std::string replacement;
bool terminal;
rule(std::string pat, std::string rep, bool term):
pattern(pat),
replacement(rep),
terminal(term)
{
}
};
std::string const whitespace = " \t";
std::string::size_type const npos = std::string::npos;
bool is_whitespace(char c)
{
return whitespace.find(c) != npos;
}
std::vector<rule> read_rules(std::ifstream& rulefile)
{
std::vector<rule> rules;
std::string line;
while (std::getline(rulefile, line))
{
std::string::size_type pos;
// remove comments
pos = line.find('#');
if (pos != npos)
line.resize(pos);
// ignore lines consisting only of whitespace
if (line.find_first_not_of(whitespace) == npos)
continue;
// find "->" surrounded by whitespace
pos = line.find("->");
while (pos != npos && (pos == 0 || !is_whitespace(line[pos-1])))
pos = line.find("->", pos+1);
if (pos == npos || line.length() < pos+3 || !is_whitespace(line[pos+2]))
{
std::cerr << "invalid rule: " << line << "\n";
std::exit(EXIT_FAILURE);
}
std::string pattern = line.substr(0, pos-1);
std::string replacement = line.substr(pos+3);
// remove additional separating whitespace
pattern.erase(pattern.find_last_not_of(whitespace)+1);
replacement.erase(0, replacement.find_first_not_of(whitespace));
// test for terminal rule
bool terminal = !replacement.empty() && replacement[0] == '.';
if (terminal)
replacement.erase(0,1);
rules.push_back(rule(pattern, replacement, terminal));
}
return rules;
}
std::string markov(std::vector<rule> rules, std::string input)
{
std::string& output = input;
std::vector<rule>::iterator iter = rules.begin();
// Loop through each rule, transforming our current version
// with each rule.
while (iter != rules.end())
{
std::string::size_type pos = output.find(iter->pattern);
if (pos != npos)
{
output.replace(pos, iter->pattern.length(), iter->replacement);
if (iter->terminal)
break;
iter = rules.begin();
}
else
++iter;
}
return output;
}
int main(int argc, char* argv[])
{
if (argc != 3)
{
std::cout << "usage:\n " << argv[0] << " rulefile text\n";
return EXIT_FAILURE;
}
std::ifstream rulefile(argv[1]);
std::vector<rule> rules = read_rules(rulefile);
std::string input(argv[2]);
std::string output = markov(rules, input);
std::cout << output << "\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.
| #DWScript | DWScript | type Exception1 = class (Exception) end;
type Exception2 = class (Exception) end;
procedure Baz(i : Integer);
begin
if i=0 then
raise new Exception1('Error message 1')
else raise new Exception2('Error message 2');
end;
procedure Bar(i : Integer);
begin
Baz(i);
end;
procedure Foo;
var
i : Integer;
begin
for i:=0 to 2 do begin
try
Bar(i);
except
on E : Exception1 do
PrintLn(E.ClassName+' caught');
end;
end;
end;
Foo; |
http://rosettacode.org/wiki/Exceptions/Catch_an_exception_thrown_in_a_nested_call | Exceptions/Catch an exception thrown in a nested call | Show how to create a user-defined exception and show how to catch an exception raised from several nested calls away.
Create two user-defined exceptions, U0 and U1.
Have function foo call function bar twice.
Have function bar call function baz.
Arrange for function baz to raise, or throw exception U0 on its first call, then exception U1 on its second.
Function foo should catch only exception U0, not U1.
Show/describe what happens when the program is run.
| #Dyalect | Dyalect | var bazCallCount = 0
func baz() {
bazCallCount += 1
if bazCallCount == 1 {
throw @BazCall1()
} else if bazCallCount == 2 {
throw @BazCall2()
}
}
func bar() {
baz()
}
func foo() {
var calls = 2
while calls > 0 {
try {
bar()
} catch {
@BazCall1() => print("BazzCall1 caught.")
}
calls -= 1
}
}
foo() |
http://rosettacode.org/wiki/Exceptions | Exceptions | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
This task is to give an example of an exception handling routine
and to "throw" a new exception.
Related task
Exceptions Through Nested Calls
| #Bracmat | Bracmat | ( ( MyFunction
= someText XMLstuff
. ( get$!arg:?someText
& get$("CorporateData.xml",X,ML):?XMLstuff
| out
$ ( str
$ ( "Something went wrong when reading your file \""
!arg
"\". Or was it the Corporate Data? Hard to say. Anyhow, now I throw you out."
)
)
& ~
)
& contemplate$(!someText,!XMLstuff)
)
& MyFunction$"Tralula.txt"
); |
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
| #C | C | #include <setjmp.h>
enum { MY_EXCEPTION = 1 }; /* any non-zero number */
jmp_buf env;
void foo()
{
longjmp(env, MY_EXCEPTION); /* throw MY_EXCEPTION */
}
void call_foo()
{
switch (setjmp(env)) {
case 0: /* try */
foo();
break;
case MY_EXCEPTION: /* catch MY_EXCEPTION */
/* handle exceptions of type MY_EXCEPTION */
break;
default:
/* handle any type of exception not handled by above catches */
/* note: if this "default" section is not included, that would be equivalent to a blank "default" section */
/* i.e. any exception not caught above would be caught and ignored */
/* there is no way to "let the exception through" */
}
} |
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
| #BASIC | BASIC | SHELL "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
| #BASIC256 | BASIC256 | system "dir" |
http://rosettacode.org/wiki/Factorial | Factorial | Definitions
The factorial of 0 (zero) is defined as being 1 (unity).
The Factorial Function of a positive integer, n, is defined as the product of the sequence:
n, n-1, n-2, ... 1
Task
Write a function to return the factorial of a number.
Solutions can be iterative or recursive.
Support for trapping negative n errors is optional.
Related task
Primorial numbers
| #ALGOL_60 | ALGOL 60 | begin
comment factorial - algol 60;
integer procedure factorial(n); integer n;
begin
integer i,fact;
fact:=1;
for i:=2 step 1 until n do
fact:=fact*i;
factorial:=fact
end;
integer i;
for i:=1 step 1 until 10 do outinteger(1,factorial(i));
outstring(1,"\n")
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
| #Factor | Factor | : pow ( f n -- f' )
dup 0 < [ abs pow recip ]
[ [ 1 ] 2dip swap [ * ] curry times ] if ; |
http://rosettacode.org/wiki/Exponentiation_operator | Exponentiation operator | Most programming languages have a built-in implementation of exponentiation.
Task
Re-implement integer exponentiation for both intint and floatint as both a procedure, and an operator (if your language supports operator definition).
If the language supports operator (or procedure) overloading, then an overloaded form should be provided for both intint and floatint variants.
Related tasks
Exponentiation order
arbitrary-precision integers (included)
Exponentiation with infix operators in (or operating on) the base
| #Forth | Forth | : ** ( n m -- n^m )
1 swap 0 ?do over * loop nip ; |
http://rosettacode.org/wiki/Executable_library | Executable library | The general idea behind an executable library is to create a library
that when used as a library does one thing;
but has the ability to be run directly via command line.
Thus the API comes with a CLI in the very same source code file.
Task detail
Create a library/module/dll/shared object/... for a programming language that contains a function/method called hailstone that is a function taking a positive integer and returns the Hailstone sequence for that number.
The library, when executed directly should satisfy the remaining requirements of the Hailstone sequence task:
2. Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
3. Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.
Create a second executable to calculate the following:
Use the library's hailstone function, in the standard manner, (or document how this use deviates from standard use of a library), together with extra code in this executable, to find the hailstone length returned most often for 1 ≤ n < 100,000.
Explain any extra setup/run steps needed to complete the task.
Notes:
It is assumed that for a language that overwhelmingly ships in a compiled form, such as C, the library must also be an executable and the compiled user of that library is to do so without changing the compiled library. I.e. the compile tool-chain is assumed not to be present in the runtime environment.
Interpreters are present in the runtime environment. | #Python | Python | def hailstone(n):
seq = [n]
while n>1:
n = 3*n + 1 if n & 1 else n//2
seq.append(n)
return seq
if __name__ == '__main__':
h = hailstone(27)
assert len(h)==112 and h[:4]==[27, 82, 41, 124] and h[-4:]==[8, 4, 2, 1]
print("Maximum length %i was found for hailstone(%i) for numbers <100,000" %
max((len(hailstone(i)), i) for i in range(1,100000))) |
http://rosettacode.org/wiki/Executable_library | Executable library | The general idea behind an executable library is to create a library
that when used as a library does one thing;
but has the ability to be run directly via command line.
Thus the API comes with a CLI in the very same source code file.
Task detail
Create a library/module/dll/shared object/... for a programming language that contains a function/method called hailstone that is a function taking a positive integer and returns the Hailstone sequence for that number.
The library, when executed directly should satisfy the remaining requirements of the Hailstone sequence task:
2. Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
3. Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.
Create a second executable to calculate the following:
Use the library's hailstone function, in the standard manner, (or document how this use deviates from standard use of a library), together with extra code in this executable, to find the hailstone length returned most often for 1 ≤ n < 100,000.
Explain any extra setup/run steps needed to complete the task.
Notes:
It is assumed that for a language that overwhelmingly ships in a compiled form, such as C, the library must also be an executable and the compiled user of that library is to do so without changing the compiled library. I.e. the compile tool-chain is assumed not to be present in the runtime environment.
Interpreters are present in the runtime environment. | #Racket | Racket |
#lang racket
(provide hailstone)
(define hailstone
(let ([t (make-hasheq)])
(hash-set! t 1 '(1))
(λ(n) (hash-ref! t n
(λ() (cons n (hailstone (if (even? n) (/ n 2) (+ (* 3 n) 1)))))))))
(module+ main
(define h27 (hailstone 27))
(printf "h(27) = ~s, ~s items\n"
`(,@(take h27 4) ... ,@(take-right h27 4))
(length h27))
(define N 100000)
(define longest
(for/fold ([m #f]) ([i (in-range 1 (add1 N))])
(define h (hailstone i))
(if (and m (> (cdr m) (length h))) m (cons i (length h)))))
(printf "for x<=~s, ~s has the longest sequence with ~s items\n"
N (car longest) (cdr longest)))
|
http://rosettacode.org/wiki/Executable_library | Executable library | The general idea behind an executable library is to create a library
that when used as a library does one thing;
but has the ability to be run directly via command line.
Thus the API comes with a CLI in the very same source code file.
Task detail
Create a library/module/dll/shared object/... for a programming language that contains a function/method called hailstone that is a function taking a positive integer and returns the Hailstone sequence for that number.
The library, when executed directly should satisfy the remaining requirements of the Hailstone sequence task:
2. Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
3. Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.
Create a second executable to calculate the following:
Use the library's hailstone function, in the standard manner, (or document how this use deviates from standard use of a library), together with extra code in this executable, to find the hailstone length returned most often for 1 ≤ n < 100,000.
Explain any extra setup/run steps needed to complete the task.
Notes:
It is assumed that for a language that overwhelmingly ships in a compiled form, such as C, the library must also be an executable and the compiled user of that library is to do so without changing the compiled library. I.e. the compile tool-chain is assumed not to be present in the runtime environment.
Interpreters are present in the runtime environment. | #Raku | Raku | module Hailstone {
our sub hailstone($n) is export {
$n, { $_ %% 2 ?? $_ div 2 !! $_ * 3 + 1 } ... 1
}
}
sub MAIN {
say "hailstone(27) = {.[^4]} [...] {.[*-4 .. *-1]}" given Hailstone::hailstone 27;
} |
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.
| #langur | langur | given .x nxor, .y nxor {
case true: ... # both true
case true, false: ... # first true, second false
case false, true: ... # first false, second true
default: ... # both false
} |
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.
| #Lasso | Lasso | // Create a type to handle the captures
define if2 => type {
data private a, private b
public oncreate(a,b) => {
.a = #a
.b = #b
thread_var_push(.type,self)
handle => { thread_var_pop(.type)}
return givenblock()
}
public ifboth => .a && .b ? givenblock()
public else1 => .a && !.b ? givenblock()
public else2 => !.a && .b ? givenblock()
public else => !.a && !.b ? givenblock()
}
// Define methods to consider givenblocks
define ifboth => thread_var_get(::if2)->ifboth => givenblock
define else1 => thread_var_get(::if2)->else1 => givenblock
define else2 => thread_var_get(::if2)->else2 => givenblock
define else => thread_var_get(::if2)->else => givenblock |
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
| #Retro | Retro | : fizz? ( s-f ) 3 mod 0 = ;
: buzz? ( s-f ) 5 mod 0 = ;
: num? ( s-f ) dup fizz? swap buzz? or 0 = ;
: ?fizz ( s- ) fizz? [ "Fizz" puts ] ifTrue ;
: ?buzz ( s- ) buzz? [ "Buzz" puts ] ifTrue ;
: ?num ( s- ) num? &putn &drop if ;
: fizzbuzz ( s- ) dup ?fizz dup ?buzz dup ?num space ;
: all ( - ) 100 [ 1+ fizzbuzz ] iter ; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.