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/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.
| #Lingo | Lingo | -- parent script "sieve"
property _sieve
----------------------------------------
-- @constructor
----------------------------------------
on new (me)
me._sieve = []
me._primeSieve(100) -- arbitrary initial size of sieve
return me
end
----------------------------------------
-- Returns sorted list of first n primes p with p >= a (default: a=1)
----------------------------------------
on getNPrimes (me, n, a)
if voidP(a) then a = 1
i = a
res = []
repeat while TRUE
if i>me._sieve.count then me._primeSieve(2*i)
if me._sieve[i] then res.add(i)
if res.count=n then return res
i = i +1
end repeat
end
----------------------------------------
-- Returns sorted list of primes p with a <= p <= b
----------------------------------------
on getPrimesInRange (me, a, b)
if me._sieve.count<b then me._primeSieve(b)
primes = []
repeat with i = a to b
if me._sieve[i] then primes.add(i)
end repeat
return primes
end
----------------------------------------
-- Returns nth prime
----------------------------------------
on getNthPrime (me, n)
if me._sieve.count<2*n then me._primeSieve(2*n)
i = 0
found = 0
repeat while TRUE
i = i +1
if i>me._sieve.count then me._primeSieve(2*i)
if me._sieve[i] then found=found+1
if found=n then return i
end repeat
end
----------------------------------------
-- Sieve of Eratosthenes
----------------------------------------
on _primeSieve (me, limit)
if me._sieve.count>=limit then
return
else if me._sieve.count>0 then
return me._complementSieve(limit)
end if
me._sieve = [0]
repeat with i = 2 to limit
me._sieve[i] = 1
end repeat
c = sqrt(limit)
repeat with i = 2 to c
if (me._sieve[i]=0) then next repeat
j = i*i
repeat while (j<=limit)
me._sieve[j] = 0
j = j + i
end repeat
end repeat
end
----------------------------------------
-- Expands existing sieve to new limit
----------------------------------------
on _complementSieve (me, n)
n1 = me._sieve.count
repeat with i = n1+1 to n
me._sieve[i] = 1
end repeat
c1 = sqrt(n1)
repeat with i = 2 to c1
if (me._sieve[i]=0) then next repeat
j = n1 - (n1 mod i)
repeat while (j<=n)
me._sieve[j] = 0
j = j + i
end repeat
end repeat
c = sqrt(n)
repeat with i = c1+1 to c
if (me._sieve[i]=0) then next repeat
j = i*i
repeat while (j<=n)
me._sieve[j] = 0
j = j + i
end repeat
end repeat
end |
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.
| #8086_Assembly | 8086 Assembly | ;;; MS-DOS Brainf*** interpreter/compiler
cpu 8086
putch: equ 2h ; Print character
puts: equ 9h ; Print string
open: equ 3Dh ; Open file
read: equ 3Fh ; Read from file
exit: equ 4Ch ; Exit to DOS
flags: equ 33h ; Set break flags
CMDLEN: equ 80h ; Address of length of command line argument
CMDARG: equ 81h ; Address of text of command line argument
BRK: equ 1 ; Break flag
EOFCH: equ -1 ; Written to the tape on EOF
section .text
org 100h
;;; See if there is enough memory
mov sp,stack.top ; Move stack inward to free up memory
mov ax,cs ; Get allocated memory size from DOS
dec ax ; (It is at location 3 in the MCB, which
mov es,ax ; is located one paragraph above CS.)
mov ax,[es:3]
mov bx,sp ; The amount of memory the program itself
mov cl,4 ; needs is from CS:0 up to CS:SP in bytes,
shr bx,cl ; shifted right by 4 to give paragraphs;
inc bx ; making sure to round up.
mov bp,cs ; The paragraph right after this is used
add bp,bx ; as the segment base for BF's memory.
sub ax,bx ; Free mem = allocated mem - program mem
cmp ax,128*1024/16 ; We'll require at least 128k bytes
jae mem_ok ; (for two separate code and data segments)
mov dx,err.mem ; If we don't have enough,
jmp error ; give an error message.
;;; Stop on Ctrl+C
mem_ok: mov ax,flags<<8|BRK
mov dl,1
int 21h
;;; See if a command line argument was given
mov bl,[CMDLEN] ; Get length of argument
test bl,bl ; See if it's zero
jnz arg_ok
mov dx,err.usage ; Print usage string if no argument given
jmp error
arg_ok: xor bh,bh
mov [CMDARG+bx],bh ; Terminate the argument string with a zero
mov ax,open<<8 ; Try to open the file for reading
mov dx,CMDARG+1 ; Skip first item (always 1)
int 21h
jnc fileok
mov dx,err.file ; Print file error if it fails
jmp error
fileok: mov di,ax ; Keep file handle in DI
xor si,si ; Keep pointer in SI
mov ds,bp ; Start reading into the memory past our stack
block: mov ah,read ; Read from file
mov bx,di
mov cx,0FFFEh
mov dx,si ; To the place just beyond the last read
int 21h
jnc .rdok
mov dx,err.file ; Read error
jmp error
.rdok: test ax,ax ; If zero bytes read, we're done
jz .done
add si,ax ; Move pointer past read
jnc block ; If there's still room, do another read
mov dx,err.mem ; If we overshot, then give memory error
jmp error
.done: mov [si],byte 0 ; Zero-terminate the data
;;; Filter out all non-BF characters
push ds ; Set ES to DS
pop es
xor si,si ; Source and destination pointer to beginning
xor di,di
filter: lodsb ; Get byte from source
xor bx,bx ; See if byte is BF command
.test: cmp al,[cs:bx+bfchar] ; Test against current character
je .match ; If a match, we found it
inc bx ; If not, try next possible command
cmp bx,8
jbe .test
jmp filter ; If we didn't find it, ignore this character
.match: stosb ; We found it, keep it
test al,al ; If zero, we found the end,
jnz filter ; Otherwise, do next character
;;; Compile the BF source into 8086 machine code
add bp,65536/16 ; Set ES to point to the start of the second
mov es,bp ; 64k (4k paragraphs) that we allocated earlier
xor di,di ; Start at address zero,
push di ; Store a zero on the stack as boundary marker,
mov ax,stop ; At 0000, store a far pointer to the
stosw ; cleanup routine,
mov ax,cs
stosw
mov ax,bfout ; At 0004, store a far pointer to the
stosw ; output routine,
mov ax,cs
stosw
mov ax,bfin ; At 0008, store a far pointer to the
stosw ; input routine,
mov ax,cs
stosw ; Compiled BF code starts at 000C.
xor si,si ; Start at beginning of BF source code
compil: lodsb ; Get current command
.ch: cmp di,-16 ; See if we still have 16 bytes free
jb .fch ; (Loop is 11 bytes, +5 for INT 21h/4Ch at end)
mov dx,err.mem ; If not, we're out of memory
jmp error
.fch: cmp al,'+' ; + and - change the value of the current cell
je tapval
cmp al,'-'
je tapval
cmp al,'>' ; < and > move the tape
je tapmov
cmp al,'<'
je tapmov
cmp al,',' ; I/O
jne .tsout ; Conditional jumps are limited to 128-byte
jmp chin ; displacement
.tsout: cmp al,'.'
jne .tsls
jmp chout
.tsls: cmp al,'[' ; Loops
jne .tsle
jmp loops
.tsle: cmp al,']'
jne .tsend
jmp loope
.tsend: test al,al ; Reached zero?
jnz compil ; If not, next command
jmp cdone ; If so, we're done
;;; Compile a string of +s and -s into an 8086 instruction
tapval: xor cl,cl ; Count up contiguous +s and -s modulo 256
.ch: cmp al,'+'
je .inc
cmp al,'-'
je .dec
test cl,cl ; If zero,
jz compil.ch ; it's a no-op.
mov bl,al ; Otherwise, keep next character
cmp cl,-1 ; If -1, decrement cell
mov ax,0FFEh ; DEC BYTE [BX]
je .wword
cmp cl,1 ; If 1, increment cell
mov ax,07FEh ; INC BYTE [BX]
je .wword
mov ax,0780h ; ADD BYTE [BX],
stosw
mov al,cl ; change to cell
stosb
mov al,bl ; Move next character back into AL
jmp compil.ch ; Compile next command
.inc: inc cl ; Increment cell
lodsb
jmp .ch
.dec: dec cl ; Decrement cell
lodsb
jmp .ch
.wword: stosw ; Write instruction word
mov al,bl ; Move next character back into AL
jmp compil.ch ; Compile next command
;;; Compile a string of <s and >s into an 8086 instruction
tapmov: xor cx,cx ; Count up contiguous <s and >s modulo 65536
.ch: cmp al,'>'
je .right
cmp al,'<'
je .left
test cx,cx ; Is there any net movement at all?
jnz .move ; If so, generate a move instruction
jmp compil.ch ; But otherwise it's a no-op, ignore it
.move: mov bl,al ; Otherwise, keep next character
cmp cx,4 ; If CX<4, a series of INC BX are best
mov al,43h ; INC BX
jb .wbyte
neg cx
cmp cx,4 ; If -CX<4, a series of DEC BX are best
mov al,4Bh ; DEC BX
jb .wbyte
neg cx
mov ax,0C381h ; ADD BX,
stosw
mov ax,cx ; tape movement
stosw
mov al,bl ; Move next character back into AL
jmp compil.ch ; Compile next command
.left: dec cx ; Left: decrement pointer
lodsb
jmp .ch
.right: inc cx ; Right: increment pointer
lodsb
jmp .ch
.wbyte: rep stosb ; Write AL, CX times.
mov al,bl ; Move next character back into AL
jmp compil.ch ; Compile next command
;;; Compile BF input
chin: mov al,2Eh ; CS segment override
stosb
mov ax,1EFFh ; CALL FAR PTR
stosw
mov ax,8 ; Pointer to input routine at address 8
stosw
jmp compil ; Compile next command
;;; Compile BF output
chout: mov al,2Eh ; CS segment override
stosb
mov ax,1EFFh ; CALL FAR PTR
stosw
mov ax,4 ; Pointer to output routine at address 4
stosw
jmp compil
;;; Compile start of loop
loops: cmp word [si],5D2Dh ; Are the next two characters '-]'?
je .zero ; Then just set the cell to zero
mov ax,078Ah ; Otherwise, write out a real loop
stosw ; ^- MOV AL,[BX]
mov ax,0C084h ; TEST AL,AL
stosw
mov ax,0575h ; JNZ loop-body
stosw
mov al,0B8h ; MOV AX, (simulate absolute near jmp)
stosb
xor ax,ax ; loop-end (we don't know it yet so 0)
stosw
mov ax,0E0FFh ; JMP AX
stosw
push di ; Store addr of loop body on stack
jmp compil ; Compile next command
.zero: mov ax,07C6h ; MOV BYTE [BX],
stosw
xor al,al ; 0
stosb
inc si ; Move past -]
inc si
jmp compil ; Compile next command
;;; Compile end of loop
loope: pop bx ; Retrieve address of loop body from stack
test bx,bx ; If it is zero, we've hit the top of stack
jz .ebrkt ; so the brackets aren't balanced.
mov ax,078Ah ; MOV AL,[BX]
stosw
mov ax,0C084h ; TEST AL,AL
stosw
mov ax,0574h ; JZ loop-end
stosw
mov al,0B8h ; MOV AX, (simulate absolute near jmp)
stosb
mov ax,bx ; loop-start
stosw
mov ax,0E0FFh ; JMP AX
stosw
mov [es:bx-4],di ; Store loop-end in matching loop start code
jmp compil
.ebrkt: mov dx,err.brk
jmp error
;;; Compilation is done.
cdone: mov al,2Eh ; Code to jump to cleanup routine
stosb ; ^- CS segment override
mov ax,2EFFh ; JMP FAR PTR
stosw
pop ax ; Should be zero if all loops closed
stosw
test ax,ax ; Were all loops closed?
jz .lp_ok
mov dx,err.brk ; If not, print error
jmp error
.lp_ok: mov [cs:cp],word 12 ; Make far pointer to start of BF code
mov [cs:cp+2],bp ; (which starts at ES:0C = BP:0C)
mov ax,ds ; Set both DS and ES to BF tape segment
mov es,ax ; (also the initial source segment)
xor ax,ax ; Clear the tape (set all bytes to zero)
mov cx,32768
rep stosw
xor bx,bx ; Tape begins at address 0
xor cx,cx ; No EOF and char buffer is empty
jmp far [cs:cp] ; Jump into the BF code
;;; BF program jumps here to stop the program
stop: mov ax,exit<<8|0 ; Quit to DOS with return code 0
int 21h
;;; Print error message in CS:DX and quit with errorlevel 2
error: push cs ; Set DS to CS
pop ds
mov ah,puts ; Print DS:DX
int 21h
mov ax,exit<<8|2 ; Quit to DOS
int 21h
;;; Output subroutine called by the BF program (far call)
bfout: mov ah,putch ; Prepare to write character
mov dl,[bx] ; Get character from tape
cmp dl,10 ; Is it LF?
jne .wr ; If not, just write it
mov dl,13 ; Otherwise, print CR first,
int 21h
mov dl,10 ; then LF.
.wr: int 21h ; Write character
retf
;;; Input subroutine called by the BF program (far call)
;;; Buffered input with CR/LF translation
;;; Note: this keeps state in registers!
;;; CL = chars left in buffer, CH = set if EOF seen,
;;; SI = buffer pointer, ES = BF data segment
bfin: test ch,ch ; EOF seen?
jnz .r_eof
mov ax,cs ; Set DS to our segment
mov ds,ax
.getch: test cl,cl ; Characters left in buffer?
jnz .retch ; If so, return next character
mov bp,bx ; Keep BF tape pointer
mov ah,read ; Read
xor bx,bx ; From STDIN
mov cx,255 ; Max 255 characters
mov dx,ibuf ; Into the buffer
int 21h
mov bx,bp ; Restore tape pointer
jc .ioerr ; If carry set, I/O error
test ax,ax ; If nothing returned, EOF
jz .s_eof
mov cx,ax ; Otherwise, set character count,
mov si,ibuf ; set buffer pointer back to start,
jmp .getch ; and return first character from buffer.
.s_eof: inc ch ; We've seen EOF now
.r_eof: mov al,EOFCH ; Return EOF
jmp .ret
.retch: lodsb ; Get char from buffer
dec cl ; One fewer character left
cmp al,26 ; ^Z = EOF when reading from keyboard
je .s_eof
cmp al,10 ; If it is LF, ignore it and get another
je .getch
cmp al,13 ; If it is CR, return LF instead
jne .ret
mov al,10
.ret: mov dx,es ; Set DS back to BF's data segment
mov ds,dx
mov [bx],al ; Put character on tape
retf
.ioerr: mov dx,err.io ; Print I/O error and quit
jmp error
section .data
bfchar: db '+-<>,.[]',0
err: ;;; Error messages
.usage: db 'BRAINFK PGM.B',13,10,10,9,'Run the BF program in PGM.B$'
.file: db 'Cannot read file$'
.brk: db 'Mismatched brackets$'
.mem: db 'Out of memory$'
.io: db 'I/O Error$'
section .bss
cp: resw 2 ; Far pointer to start of BF code
ibuf: resb 256 ; 255 char input buffer
stack: resw 512 ; 512 words for the stack
.top: equ $ |
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.
| #8th | 8th |
\ RosettaCode challenge http://rosettacode.org/wiki/Evolutionary_algorithm
\ Responding to the criticism that the implementation was too directed, this
\ version does a completely random selection of chars to mutate
var gen
\ Convert a string of valid chars into an array of char-strings:
"ABCDEFGHIJKLMNOPQRSTUVWXYZ " null s:/ var, valid-chars
\ How many mutations each generation will handle; the larger, the slower each
\ generation but the fewer generations required:
300 var, #mutations
23 var, mutability
: get-random-char
valid-chars @
27 rand-pcg n:abs swap n:mod
a:@ nip ;
: mutate-string \ s -- s'
(
rand-pcg mutability @ n:mod not if
drop get-random-char
then
) s:map ;
: mutate \ s n -- a
\ iterate 'n' times over the initial string, mutating it each time
\ save the original string, as the best of the previous generation:
>r [] over a:push swap
(
tuck mutate-string
a:push swap
) r> times drop ;
\ compute Hamming distance of two strings:
: hamming \ s1 s2 -- n
0 >r
s:len n:1-
(
2 pick over s:@ nip
2 pick rot s:@ nip
n:- n:abs r> n:+ >r
) 0 rot loop
2drop r> ;
var best
: fitness-check \ s a -- s t
10000 >r
-1 best !
(
\ ix s ix s'
2 pick hamming
r@
over n:> if
rdrop >r
best !
else
2drop
then
)
a:each
rdrop best @ a:@ nip ;
: add-random-char \ s -- s'
get-random-char s:+ ;
\ take the target and make a random string of the same length
: initial-string \ s -- s
s:len "" swap
' add-random-char
swap times ;
: done? \ s1 s2 -- s1 s2 | bye
2dup s:= if
"Done in " . gen @ . " generations" . cr ;;;
then ;
: setup-random
rand rand rand-pcg-seed ;
: evolve
1 gen n:+!
\ create an array of #mutations strings mutated from the random string, drop the random
#mutations @ mutate
\ iterate over the array and pick the closest fit:
fitness-check
\ show this generation's best match:
dup . cr
\ check for end condition and continue if not done:
done? evolve ;
"METHINKS IT IS LIKE A WEASEL"
setup-random initial-string evolve bye |
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
| #JavaScript | JavaScript | function fib(n) {
return n<2?n:fib(n-1)+fib(n-2);
} |
http://rosettacode.org/wiki/Factors_of_an_integer | Factors of an integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Compute the factors of a positive integer.
These factors are the positive integers by which the number being factored can be divided to yield a positive integer result.
(Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty; this task does not require handling of either of these cases).
Note that every prime number has two factors: 1 and itself.
Related tasks
count in factors
prime decomposition
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
sequence: smallest number greater than previous term with exactly n divisors
| #Scala | Scala | def factors(num: Int) = {
(1 to num).filter { divisor =>
num % divisor == 0
}
} |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #Go | Go | module hq9plus
function main = |args| {
var accumulator = 0
let source = readln("please enter your source code: ")
foreach ch in source: chars() {
case {
when ch == 'h' or ch == 'H' {
println("Hello, world!")
}
when ch == 'q' or ch == 'Q' {
println(source)
}
when ch == '9' {
ninety9Bottles()
}
when ch == '+' {
accumulator = accumulator + 1
}
otherwise {
println("syntax error")
}
}
}
}
function bottles = |amount| -> match {
when amount == 1 then "One bottle"
when amount == 0 then "No bottles"
otherwise amount + " bottles"
}
function ninety9Bottles = {
foreach n in [99..0]: decrementBy(1) {
println(bottles(n) + " of beer on the wall,")
println(bottles(n) + " of beer!")
println("Take one down, pass it around,")
println(bottles(n - 1) + " of beer on the wall!")
}
}
|
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #Golo | Golo | module hq9plus
function main = |args| {
var accumulator = 0
let source = readln("please enter your source code: ")
foreach ch in source: chars() {
case {
when ch == 'h' or ch == 'H' {
println("Hello, world!")
}
when ch == 'q' or ch == 'Q' {
println(source)
}
when ch == '9' {
ninety9Bottles()
}
when ch == '+' {
accumulator = accumulator + 1
}
otherwise {
println("syntax error")
}
}
}
}
function bottles = |amount| -> match {
when amount == 1 then "One bottle"
when amount == 0 then "No bottles"
otherwise amount + " bottles"
}
function ninety9Bottles = {
foreach n in [99..0]: decrementBy(1) {
println(bottles(n) + " of beer on the wall,")
println(bottles(n) + " of beer!")
println("Take one down, pass it around,")
println(bottles(n - 1) + " of beer on the wall!")
}
}
|
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
| #CLU | CLU | markov = cluster is make, run
rule = struct[from, to: string, term: bool]
rep = array[rule]
% Remove leading and trailing whitespace from a string
trim = proc (s: string) returns (string)
ac = array[char]
sc = sequence[char]
own ws: string := "\n\t "
a: ac := string$s2ac(s)
while ~ac$empty(a) cand string$indexc(ac$bottom(a), ws) ~= 0 do
ac$reml(a)
end
while ~ac$empty(a) cand string$indexc(ac$top(a), ws) ~= 0 do
ac$remh(a)
end
return(string$sc2s(sc$a2s(a)))
end trim
% Parse a single Markov rule
parse = proc (s: string) returns (rule) signals (comment, invalid(string))
if string$empty(s) cor s[1]='#' then signal comment end
arrow: int := string$indexs(" -> ", s)
if arrow=0 then signal invalid(s) end
left: string := trim(string$substr(s, 1, arrow-1))
right: string := trim(string$rest(s, arrow+4))
if ~string$empty(right) cand right[1] = '.' then
right := string$rest(right, 2)
return(rule${from: left, to: right, term: true})
else
return(rule${from: left, to: right, term: false})
end
end parse
% Add a rule to the list
add_rule = proc (m: cvt, s: string) signals (invalid(string))
rep$addh(m, parse(s)) resignal invalid
except when comment: end
end add_rule
% Read rules in sequence from a stream
add_rules = proc (m: cvt, s: stream) signals (invalid(string))
while true do
add_rule(up(m), stream$getl(s)) resignal invalid
except when end_of_file: break end
end
end add_rules
make = proc (s: stream) returns (cvt) signals (invalid(string))
a: rep := rep$new()
add_rules(up(a), s)
return(a)
end make
% Apply a rule to a string
apply_rule = proc (r: rule, s: string) returns (string) signals (no_match)
match: int := string$indexs(r.from, s)
if match = 0 then signal no_match end
new: string := string$substr(s, 1, match-1)
|| r.to
|| string$rest(s, match+string$size(r.from))
return(new)
end apply_rule
% Apply all rules to a string repeatedly
run = proc (c: cvt, s: string) returns (string)
i: int := 1
while i <= rep$high(c) do
r: rule := c[i]
begin
s := apply_rule(r, s)
i := 1
if r.term then break end
end except when no_match:
i := i+1
end
end
return(s)
end run
end markov
start_up = proc ()
po: stream := stream$primary_output()
eo: stream := stream$error_output()
begin
args: sequence[string] := get_argv()
file: string := args[1]
input: string := args[2]
fs: stream := stream$open(file_name$parse(file), "read")
mkv: markov := markov$make(fs)
stream$close(fs)
stream$putl(po, markov$run(mkv, input))
end except
when bounds: stream$putl(eo, "Arguments: markov [filename] [string]")
when not_possible(s: string): stream$putl(eo, "File error: " || s)
when invalid(s: string): stream$putl(eo, "Parse error: " || s)
end
end start_up |
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
| #Common_Lisp | Common Lisp | ;;; Keeps track of all our rules
(defclass markov ()
((rules :initarg :rules :initform nil :accessor rules)))
;;; Definition of a rule
(defclass rule ()
((pattern :initarg :pattern :accessor pattern)
(replacement :initarg :replacement :accessor replacement)
(terminal :initform nil :initarg :terminal :accessor terminal)))
;;; Parse a rule with this regular expression
(defparameter *rex->* (compile-re "^(.+)(?: |\\t)->(?: |\\t)(\\.?)(.*)$"))
;;; Create a rule and add it to the markov object
(defmethod update-markov ((mkv markov) lhs terminating rhs)
(setf (rules mkv) (cons
(make-instance 'rule :pattern lhs :replacement rhs :terminal terminating)
(rules mkv))))
;;; Parse a line and add it to the markov object
(defmethod parse-line ((mkv markov) line)
(let ((trimmed (string-trim #(#\Space #\Tab) line)))
(if (not (or
(eql #\# (aref trimmed 0))
(equal "" trimmed)))
(let ((vals (multiple-value-list (match-re *rex->* line))))
(if (not (car vals))
(progn
(format t "syntax error in ~A" line)
(throw 'fail t)))
(update-markov mkv (nth 2 vals) (equal "." (nth 3 vals)) (nth 4 vals))))))
;;; Make a markov object from the string of rules
(defun make-markov (rules-text)
(catch 'fail
(let ((mkv (make-instance 'markov)))
(with-input-from-string (s rules-text)
(loop for line = (read-line s nil)
while line do
(parse-line mkv line)))
(setf (rules mkv) (reverse (rules mkv)))
mkv)))
;;; Given a rule and bounds where it applies, apply it to the input text
(defun adjust (rule-info text)
(let* ((rule (car rule-info))
(index-start (cadr rule-info))
(index-end (caddr rule-info))
(prefix (subseq text 0 index-start))
(suffix (subseq text index-end))
(replace (replacement rule)))
(concatenate 'string prefix replace suffix)))
;;; Get the next applicable rule or nil if none
(defmethod get-rule ((markov markov) text)
(dolist (rule (rules markov) nil)
(let ((index (search (pattern rule) text)))
(if index
(return (list rule index (+ index (length (pattern rule)))))))))
;;; Interpret text using a markov object
(defmethod interpret ((markov markov) text)
(let ((rule-info (get-rule markov text))
(ret text))
(loop (if (not rule-info) (return ret))
(setf ret (adjust rule-info ret))
(if (terminal (car rule-info)) (return ret))
(setf rule-info (get-rule markov ret))))) |
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.
| #EchoLisp | EchoLisp |
(define (foo)
(for ((i 2))
(try
(bar i)
(catch (id message)
(if (= id 'U0)
(writeln message 'catched)
(error id "not catched"))))))
(define (bar i)
(baz i))
(define (baz i)
(if (= i 0)
(throw 'U0 "U0 raised")
(throw 'U1 "U1 raised")))
(foo) →
"U0 raised" catched
👓 error: U1 not catched
|
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.
| #EGL | EGL | record U0 type Exception
end
record U1 type Exception
end
program Exceptions
function main()
foo();
end
function foo()
try
bar();
onException(ex U0)
SysLib.writeStdout("Caught a U0 with message: '" :: ex.message :: "'");
end
bar();
end
function bar()
baz();
end
firstBazCall boolean = true;
function baz()
if(firstBazCall)
firstBazCall = false;
throw new U0{message = "This is the U0 exception"};
else
throw new U1{message = "This is the U1 exception"};
end
end
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
| #C.23 | C# | public class MyException : Exception
{
// data with info about exception
}; |
http://rosettacode.org/wiki/Exceptions | Exceptions | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
This task is to give an example of an exception handling routine
and to "throw" a new exception.
Related task
Exceptions Through Nested Calls
| #C.2B.2B | C++ | struct MyException
{
// data with info about exception
}; |
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
| #Batch_File | Batch File | 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
| #BBC_BASIC | BBC BASIC | OSCLI "CAT" |
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_68 | ALGOL 68 | PROC factorial = (INT upb n)LONG LONG INT:(
LONG LONG INT z := 1;
FOR n TO upb n DO z *:= n OD;
z
); ~ |
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
| #Fortran | Fortran | MODULE Exp_Mod
IMPLICIT NONE
INTERFACE OPERATOR (.pow.) ! Using ** instead would overload the standard exponentiation operator
MODULE PROCEDURE Intexp, Realexp
END INTERFACE
CONTAINS
FUNCTION Intexp (base, exponent)
INTEGER :: Intexp
INTEGER, INTENT(IN) :: base, exponent
INTEGER :: i
IF (exponent < 0) THEN
IF (base == 1) THEN
Intexp = 1
ELSE
Intexp = 0
END IF
RETURN
END IF
Intexp = 1
DO i = 1, exponent
Intexp = Intexp * base
END DO
END FUNCTION IntExp
FUNCTION Realexp (base, exponent)
REAL :: Realexp
REAL, INTENT(IN) :: base
INTEGER, INTENT(IN) :: exponent
INTEGER :: i
Realexp = 1.0
IF (exponent < 0) THEN
DO i = exponent, -1
Realexp = Realexp / base
END DO
ELSE
DO i = 1, exponent
Realexp = Realexp * base
END DO
END IF
END FUNCTION RealExp
END MODULE Exp_Mod
PROGRAM EXAMPLE
USE Exp_Mod
WRITE(*,*) 2.pow.30, 2.0.pow.30
END PROGRAM EXAMPLE |
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. | #REXX | REXX | /*REXX program returns the hailstone (Collatz) sequence for any integer.*/
numeric digits 20 /*ensure enough digits for mult. */
parse arg n 1 s /*N & S assigned to the first arg*/
do while n\==1 /*loop while N isn't unity. */
if n//2 then n=n*3+1 /*if N is odd, calc: 3*n +1 */
else n=n%2 /* " " " even, perform fast ÷ */
s=s n /*build a sequence list (append).*/
end /*while*/
return s |
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. | #Ruby | Ruby | # hailstone.rb
module Hailstone
module_function
def hailstone n
seq = [n]
until n == 1
n = (n.even?) ? (n / 2) : (3 * n + 1)
seq << n
end
seq
end
end
if __FILE__ == $0
include Hailstone
# for n = 27, show sequence length and first and last 4 elements
hs27 = hailstone 27
p [hs27.length, hs27[0..3], hs27[-4..-1]]
# find the longest sequence among n less than 100,000
n, len = (1 ... 100_000) .collect {|n|
[n, hailstone(n).length]} .max_by {|n, len| len}
puts "#{n} has a hailstone sequence length of #{len}"
puts "the largest number in that sequence is #{hailstone(n).max}"
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.
| #M2000_Interpreter | M2000 Interpreter |
module if2 {
over 3 : read &c
c=not (stackitem() and stackitem(2))
}
module ifelse1 {
over 3 : read &c
c=not (stackitem() and not stackitem(2))
}
module ifelse2 {
over 3 : read &c
c=not (stackitem(2) and not stackitem())
}
module ifelse {
over 3 : read &c
c=stackitem() or stackitem(2)
}
module endif2 {
if not empty then drop 3
}
ctrl=true
for a=1 to 2
for b=1 to 2
Print "a=";a, "b=";b
if2 a=1, b=2, &ctrl : Part {
print "both", a, b
} as ctrl
ifelse1 : Part {
print "first", a
} as ctrl
ifelse2 : Part {
print "second", b
} as ctrl
ifelse : part {
print "no one"
} as ctrl
endif2
next b
next a
Print "ok"
|
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.
| #m4 | m4 | divert(-1)
#
# m4 is a macro language, so this is just a matter of defining a
# macro, using the built-in branching macro "ifelse".
#
# ifelse2(x1,x2,y1,y2,exprxy,exprx,expry,expr)
#
# Checks if x1 and x2 are equal strings and if y1 and y2 are equal
# strings.
#
define(`ifelse2',
`ifelse(`$1',`$2',`ifelse(`$3',`$4',`$5',`$6')',
`ifelse(`$3',`$4',`$7',`$8')')')
divert`'dnl
dnl
ifelse2(1,1,2,2,`exprxy',`exprx',`expry',`expr')
ifelse2(1,1,2,-2,`exprxy',`exprx',`expry',`expr')
ifelse2(1,-1,2,2,`exprxy',`exprx',`expry',`expr')
ifelse2(1,-1,2,-2,`exprxy',`exprx',`expry',`expr') |
http://rosettacode.org/wiki/FizzBuzz | FizzBuzz | Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
| #REXX | REXX | /*REXX program displays numbers 1 ──► 100 (some transformed) for the FizzBuzz problem.*/
/*╔═══════════════════════════════════╗*/
do j=1 to 100; z= j /*║ ║*/
if j//3 ==0 then z= 'Fizz' /*║ The divisors (//) of the IFs ║*/
if j//5 ==0 then z= 'Buzz' /*║ must be in ascending order. ║*/
if j//(3*5)==0 then z= 'FizzBuzz' /*║ ║*/
say right(z, 8) /*╚═══════════════════════════════════╝*/
end /*j*/ /*stick a fork in it, we're all done. */ |
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.
| #M2000_Interpreter | M2000 Interpreter |
Module CheckPrimes {
\\ Inventories are lists, Known and Known1 are pointers to Inventories
Inventory Known=1:=2@,2:=3@,3:=5@
Inventory Known1=2@, 3@, 5@
\\ In a lambda all closures are copies
\\ but Known and Know1 are copies of pointers
\\ so are closures like by reference
PrimeNth=lambda Known, Known1 (n as long) -> {
if n<1 then Error "Only >=1"
if exist(known, n) then =eval(known) : exit
if n>5 then {
i=len(known1)
x=eval(known1, i-1)+2
} else x=5 : i=2
{
if i=n then =known(n) : exit
ok=false
if frac(x) then 1000
if frac(x/2) else 1000
if frac(x/3) else 1000
x1=sqrt(x) : d=5@
Repeat
if frac(x/d ) else exit
d += 2: if d>x1 then ok=true : exit
if frac(x/d) else exit
d += 4: if d<= x1 else ok=true: exit
Always
1000 If ok then i++:Append Known, i:=x : if not exist(Known1, x) then Append Known1, x
x+=2 : Loop }
}
\\ IsPrime has same closure, Known1
IsPrime=lambda Known1 (x as decimal) -> {
if exist(Known1, x) then =true : exit
if Eval(Known1, len(Known1)-1)>x then exit
if frac(x/2) else exit
if frac(x/3) else exit
x1=sqrt(x):d = 5@
{if frac(x/d ) else exit
d += 2: if d>x1 then =true : exit
if frac(x/d) else exit
d += 4: if d<= x1 else =true: exit
loop
}
}
\\ fill Known1, PrimeNth is a closure here
IsPrime2=lambda Known1, PrimeNth (x as decimal) -> {
if exist(Known1, x) then =true : exit
i=len(Known1)
if Eval(Known1, i-1)>x then exit
{
z=PrimeNth(i)
if z<x then loop else.if z=x then =true :exit
i++
}
}
Print "First twenty primes"
n=PrimeNth(20)
For i=1 to 20 : Print Known(i),: Next i
Print
Print "Primes between 100 and 150:"
c=0
For i=100 to 150
If IsPrime2(i) Then print i, : c++
Next i
Print
Print "Count:", c
Print "Primes between 7700 and 8000:"
c=0
For i=7700 to 8000
If IsPrime(i) Then print i, : c++
Next i
Print
Print "Count:", c
Print "200th Prime:"
Print PrimeNth(200)
Print "List from 190th to 199th Prime:"
For i=190 to 199 : Print Known(i), : Next i
Print
Print "Wait"
Refresh ' because refresh happen on next Print, which take time
' using set fast! we get no respond from GUI/M2000 Console
' also Esc, Break and Ctrl+C not work
' we have to use Refresh each 500 primes to have one Refresh
Set fast !
for i=500 to 10000 step 50: m=PrimeNth(i): Print "."; :Refresh:Next i
Print
Print "10000th Prime:", PrimeNth(10000)
' reset speed to fast (there are three levels: slow/fast/fast!)
set fast
Print
Rem 1 : Print Known
Rem 2: Print Known1
}
CheckPrimes
|
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.
| #Ada | Ada | # Brain**** interpreter
# execute the Brain**** program in the code string
bf := proc( code :: string ) is
local address := 1; # current data address
local pc := 1; # current position in code
local data := []; # data - initially empty
local input := ""; # user input - initially empty
local bfOperations := # table of operations and their implemntations
[ ">" ~ proc() is inc address, 1 end
, "<" ~ proc() is dec address, 1 end
, "+" ~ proc() is inc data[ address ], 1 end
, "-" ~ proc() is dec data[ address ], 1 end
, "." ~ proc() is io.write( char( data[ address ] ) ) end
, "," ~ proc() is
# get next input character, converted to an integer
while input = ""
do
# no input left - get the next line
input := io.read()
od;
data[ address ] := abs( input[ 1 ] );
# remove the latest character from the input
if size input < 2
then
input := ""
else
input := input[ 2 to -1 ]
fi
end
, "[" ~ proc() is
if data[ address ] = 0
then
# skip to the end of the loop
local depth := 0;
do
inc pc, 1;
if code[ pc ] = "["
then
inc depth, 1
elif code[ pc ] = "]"
then
dec depth, 1
fi
until depth < 0
fi
end
, "]" ~ proc() is
if data[ address ] <> 0
then
# skip to the start of the loop
local depth := 0;
do
dec pc, 1;
if code[ pc ] = "["
then
dec depth, 1
elif code[ pc ] = "]"
then
inc depth, 1
fi
until depth < 0
fi
end
];
# execute the operations - ignore anything invalid
while pc <= size code
do
if data[ address ] = null
then
data[ address ] := 0
fi;
if bfOperations[ code[ pc ] ] <> null
then
bfOperations[ code[ pc ] ]()
fi;
inc pc, 1
od
end;
# prompt for Brain**** code and execute it, repeating until an empty code string is entered
scope
local code;
do
io.write( "BF> " );
code := io.read();
bf( code )
until code = ""
epocs; |
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.
| #Ada | Ada | with Ada.Text_IO;
with Ada.Numerics.Discrete_Random;
with Ada.Numerics.Float_Random;
with Ada.Strings.Fixed;
with Ada.Strings.Maps;
procedure Evolution is
-- only upper case characters allowed, and space, which uses '@' in
-- internal representation (allowing subtype of Character).
subtype DNA_Char is Character range '@' .. 'Z';
-- DNA string is as long as target string.
subtype DNA_String is String (1 .. 28);
-- target string translated to DNA_Char string
Target : constant DNA_String := "METHINKS@IT@IS@LIKE@A@WEASEL";
-- calculate the 'closeness' to the target DNA.
-- it returns a number >= 0 that describes how many chars are correct.
-- can be improved much to make evolution better, but keep simple for
-- this example.
function Fitness (DNA : DNA_String) return Natural is
Result : Natural := 0;
begin
for Position in DNA'Range loop
if DNA (Position) = Target (Position) then
Result := Result + 1;
end if;
end loop;
return Result;
end Fitness;
-- output the DNA using the mapping
procedure Output_DNA (DNA : DNA_String; Prefix : String := "") is
use Ada.Strings.Maps;
Output_Map : Character_Mapping;
begin
Output_Map := To_Mapping
(From => To_Sequence (To_Set (('@'))),
To => To_Sequence (To_Set ((' '))));
Ada.Text_IO.Put (Prefix);
Ada.Text_IO.Put (Ada.Strings.Fixed.Translate (DNA, Output_Map));
Ada.Text_IO.Put_Line (", fitness: " & Integer'Image (Fitness (DNA)));
end Output_DNA;
-- DNA_Char is a discrete type, use Ada RNG
package Random_Char is new Ada.Numerics.Discrete_Random (DNA_Char);
DNA_Generator : Random_Char.Generator;
-- need generator for floating type, too
Float_Generator : Ada.Numerics.Float_Random.Generator;
-- returns a mutated copy of the parent, applying the given mutation rate
function Mutate (Parent : DNA_String;
Mutation_Rate : Float)
return DNA_String
is
Result : DNA_String := Parent;
begin
for Position in Result'Range loop
if Ada.Numerics.Float_Random.Random (Float_Generator) <= Mutation_Rate
then
Result (Position) := Random_Char.Random (DNA_Generator);
end if;
end loop;
return Result;
end Mutate;
-- genetic algorithm to evolve the string
-- could be made a function returning the final string
procedure Evolve (Child_Count : Positive := 100;
Mutation_Rate : Float := 0.2)
is
type Child_Array is array (1 .. Child_Count) of DNA_String;
-- determine the fittest of the candidates
function Fittest (Candidates : Child_Array) return DNA_String is
The_Fittest : DNA_String := Candidates (1);
begin
for Candidate in Candidates'Range loop
if Fitness (Candidates (Candidate)) > Fitness (The_Fittest)
then
The_Fittest := Candidates (Candidate);
end if;
end loop;
return The_Fittest;
end Fittest;
Parent, Next_Parent : DNA_String;
Children : Child_Array;
Loop_Counter : Positive := 1;
begin
-- initialize Parent
for Position in Parent'Range loop
Parent (Position) := Random_Char.Random (DNA_Generator);
end loop;
Output_DNA (Parent, "First: ");
while Parent /= Target loop
-- mutation loop
for Child in Children'Range loop
Children (Child) := Mutate (Parent, Mutation_Rate);
end loop;
Next_Parent := Fittest (Children);
-- don't allow weaker children as the parent
if Fitness (Next_Parent) > Fitness (Parent) then
Parent := Next_Parent;
end if;
-- output every 20th generation
if Loop_Counter mod 20 = 0 then
Output_DNA (Parent, Integer'Image (Loop_Counter) & ": ");
end if;
Loop_Counter := Loop_Counter + 1;
end loop;
Output_DNA (Parent, "Final (" & Integer'Image (Loop_Counter) & "): ");
end Evolve;
begin
-- initialize the random number generators
Random_Char.Reset (DNA_Generator);
Ada.Numerics.Float_Random.Reset (Float_Generator);
-- evolve!
Evolve;
end Evolution; |
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
| #Joy | Joy | DEFINE fib == [small] [] [pred dup pred] [+] binrec. |
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
| #Scheme | Scheme | (define (factors n)
(define (*factors d)
(cond ((> d n) (list))
((= (modulo n d) 0) (cons d (*factors (+ d 1))))
(else (*factors (+ d 1)))))
(*factors 1))
(display (factors 1111111))
(newline) |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #Haskell | Haskell | // live demo: http://try.haxe.org/#2E7D4
static function hq9plus(code:String):String {
var out:String = "";
var acc:Int = 0;
for (position in 0 ... code.length) switch (code.charAt(position)) {
case "H", "h": out += "Hello, World!\n";
case "Q", "q": out += '$code\n';
case "9":
var quantity:Int = 99;
while (quantity > 1) {
out += '$quantity bottles of beer on the wall, $quantity bottles of beer.\n';
out += 'Take one down and pass it around, ${--quantity} bottles of beer.\n';
}
out += "1 bottle of beer on the wall, 1 bottle of beer.\n" +
"Take one down and pass it around, no more bottles of beer on the wall.\n\n" +
"No more bottles of beer on the wall, no more bottles of beer.\n" +
"Go to the store and buy some more, 99 bottles of beer on the wall.\n";
case "+": acc++;
}
return out;
} |
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
| #Cowgol | Cowgol | include "cowgol.coh";
include "strings.coh";
include "malloc.coh";
include "argv.coh";
include "file.coh";
record Rule is
pattern: [uint8];
replacement: [uint8];
next: [Rule];
terminates: uint8;
end record;
sub AllocRule(): (rule: [Rule]) is
rule := Alloc(@bytesof Rule) as [Rule];
MemZero(rule as [uint8], @bytesof Rule);
end sub;
sub ParseRule(text: [uint8]): (rule: [Rule]) is
sub ParseError() is
print("Failed to parse rule: ");
print(text);
print_nl();
ExitWithError();
end sub;
var cur := text;
sub SkipWs() is
while [cur] != 0 and [cur] <= ' ' loop cur := @next cur; end loop;
end sub;
sub AllocAndCopy(src: [uint8], length: intptr): (copy: [uint8]) is
copy := Alloc(length + 1);
MemCopy(src, length, copy);
[copy + length] := 0;
end sub;
SkipWs();
if [cur] == '#' or [cur] == 0 then # comment or empty line
rule := 0 as [Rule];
return;
end if;
var patternStart := cur;
# find the " ->"
while [cur] != 0
and ([cur] > ' ' or [cur+1] != '-' or [cur+2] != '>') loop
cur := @next cur;
end loop;
if [cur] == 0 then ParseError(); end if;
# find last char of pattern
var patternEnd := cur;
while patternStart < patternEnd and [patternEnd] <= ' ' loop
patternEnd := @prev patternEnd;
end loop;
cur := cur + 3; # whitespace + '->'
SkipWs();
var replacementStart := cur;
# find last char of replacement
while [cur] != 0 loop cur := @next cur; end loop;
while replacementStart < cur and [cur] <= ' ' loop
cur := @prev cur;
end loop;
# make rule object
rule := AllocRule();
rule.pattern := AllocAndCopy(patternStart, patternEnd-patternStart+1);
if [replacementStart] == '.' then
rule.terminates := 1;
replacementStart := @next replacementStart;
end if;
rule.replacement := AllocAndCopy(replacementStart, cur-replacementStart+1);
end sub;
sub FindMatch(needle: [uint8], haystack: [uint8]): (match: [uint8]) is
match := 0 as [uint8];
while [haystack] != 0 loop
var n := needle;
var h := haystack;
while [n] != 0 and [h] != 0 and [n] == [h] loop
n := @next n;
h := @next h;
end loop;
if [n] == 0 then
match := haystack;
return;
end if;
haystack := @next haystack;
end loop;
end sub;
const NO_MATCH := 0;
const HALT := 1;
const CONTINUE := 2;
sub ApplyRule(rule: [Rule], in: [uint8], out: [uint8]): (result: uint8) is
var match := FindMatch(rule.pattern, in);
if match == 0 as [uint8] then
result := NO_MATCH;
else
var len := StrLen(rule.replacement);
var patlen := StrLen(rule.pattern);
var rest := match + patlen;
MemCopy(in, match-in, out);
MemCopy(rule.replacement, len, out+(match-in));
CopyString(rest, out+(match-in)+len);
if rule.terminates != 0 then
result := HALT;
else
result := CONTINUE;
end if;
end if;
end sub;
sub ApplyRules(rules: [Rule], buffer: [uint8]): (r: [uint8]) is
var outbuf: uint8[256];
var rule := rules;
r := buffer;
while rule != 0 as [Rule] loop
case ApplyRule(rule, buffer, &outbuf[0]) is
when NO_MATCH:
rule := rule.next;
when HALT:
CopyString(&outbuf[0], buffer);
return;
when CONTINUE:
CopyString(&outbuf[0], buffer);
rule := rules;
end case;
end loop;
end sub;
sub ReadFile(filename: [uint8]): (rules: [Rule]) is
var linebuf: uint8[256];
var fcb: FCB;
var bufptr := &linebuf[0];
rules := 0 as [Rule];
var prevRule := 0 as [Rule];
if FCBOpenIn(&fcb, filename) != 0 then
print("Cannot open file: ");
print(filename);
print_nl();
ExitWithError();
end if;
var length := FCBExt(&fcb);
var ch: uint8 := 1;
while length != 0 and ch != 0 loop
ch := FCBGetChar(&fcb);
length := length - 1;
[bufptr] := ch;
bufptr := @next bufptr;
if ch == '\n' then
[bufptr] := 0;
bufptr := &linebuf[0];
var rule := ParseRule(&linebuf[0]);
if rule != 0 as [Rule] then
if rules == 0 as [Rule] then rules := rule; end if;
if prevRule != 0 as [Rule] then prevRule.next := rule; end if;
prevRule := rule;
end if;
end if;
end loop;
var dummy := FCBClose(&fcb);
end sub;
ArgvInit();
var fname := ArgvNext();
if fname == 0 as [uint8] then
print("usage: markov [pattern file] [pattern]\n");
ExitWithError();
end if;
var patbuf: uint8[256];
var patptr := &patbuf[0];
loop
var patpart := ArgvNext();
if patpart == 0 as [uint8] then
if patptr != &patbuf[0] then patptr := @prev patptr; end if;
[patptr] := 0;
break;
end if;
var partlen := StrLen(patpart);
MemCopy(patpart, partlen, patptr);
patptr := patptr + partlen + 1;
[@prev patptr] := ' ';
end loop;
print(ApplyRules(ReadFile(fname), &patbuf[0]));
print_nl(); |
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
| #D | D | void main() {
import std.stdio, std.file, std.regex, std.string, std.range,
std.functional;
const rules = "markov_rules.txt".readText.splitLines.split("");
auto tests = "markov_tests.txt".readText.splitLines;
auto re = ctRegex!(r"^([^#]*?)\s+->\s+(\.?)(.*)"); // 160 MB RAM.
alias slZip = curry!(zip, StoppingPolicy.requireSameLength);
foreach (test, const rule; slZip(tests, rules)) {
const origTest = test.dup;
string[][] capt;
foreach (const line; rule) {
auto m = line.match(re);
if (!m.empty) {
//capt.put(m.captures.dropOne);
capt ~= m.captures.dropOne.array;
}
}
REDO:
const copy = test;
foreach (const c; capt) {
test = test.replace(c[0], c[2]);
if (c[1] == ".")
break;
if (test != copy)
goto REDO;
}
writefln("%s\n%s\n", origTest, test);
}
} |
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.
| #Eiffel | Eiffel | class MAIN
inherit EXCEPTIONS
creation foo
feature {ANY}
baz_calls: INTEGER
feature foo is
do
Current.bar
rescue
if is_developer_exception_of_name("U0") then
baz_calls := 1
print("Caught U0 exception.%N")
retry
end
if is_developer_exception then
print("Won't catch ")
print(developer_exception_name)
print(" exception...%N")
end
end
feature bar is
do
Current.baz
end
feature baz is
do
if baz_calls = 0 then
raise("U0")
else
raise("U1")
end
end
end |
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.
| #Elena | Elena | import extensions;
class U0 : Exception
{
constructor new()
<= new();
}
class U1 : Exception
{
constructor new()
<= new();
}
singleton Exceptions
{
static int i;
bar()
<= baz();
baz()
{
if (i == 0)
{
U0.raise()
}
else
{
U1.raise()
}
}
foo()
{
for(i := 0, i < 2, i += 1)
{
try
{
self.bar()
}
catch(U0 e)
{
console.printLine("U0 Caught")
}
}
}
}
public program()
{
Exceptions.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
| #Clojure | Clojure | (try
(if (> (rand) 0.5)
(throw (RuntimeException. "oops!"))
(println "see this half the time")
(catch RuntimeException e
(println e)
(finally
(println "always see this")) |
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
| #ColdFusion | ColdFusion | try {
foo();
} catch (Any e) {
// handle exception e
} |
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
| #Befunge | Befunge | "sl"=@;pushes ls, = executes it, @ ends it; |
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
| #BQN | BQN | •SH ⟨"ls"⟩ |
http://rosettacode.org/wiki/Factorial | Factorial | Definitions
The factorial of 0 (zero) is defined as being 1 (unity).
The Factorial Function of a positive integer, n, is defined as the product of the sequence:
n, n-1, n-2, ... 1
Task
Write a function to return the factorial of a number.
Solutions can be iterative or recursive.
Support for trapping negative n errors is optional.
Related task
Primorial numbers
| #ALGOL_W | ALGOL W | begin
% computes factorial n iteratively %
integer procedure factorial( integer value n ) ;
if n < 2
then 1
else begin
integer f;
f := 2;
for i := 3 until n do f := f * i;
f
end factorial ;
for t := 0 until 10 do write( "factorial: ", t, factorial( t ) );
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
| #FreeBASIC | FreeBASIC | ' FB 1.05.0
' Note that 'base' is a keyword in FB, so we use 'base_' instead as a parameter
Function Pow Overload (base_ As Double, exponent As Integer) As Double
If exponent = 0.0 Then Return 1.0
If exponent = 1.0 Then Return base_
If exponent < 0.0 Then Return 1.0 / Pow(base_, -exponent)
Dim power As Double = base_
For i As Integer = 2 To exponent
power *= base_
Next
Return power
End Function
Function Pow Overload(base_ As Integer, exponent As Integer) As Double
Return Pow(CDbl(base_), exponent)
End Function
' check results of these functions using FB's built in '^' operator
Print "Pow(2, 2) = "; Pow(2, 2)
Print "Pow(2.5, 2) = "; Pow(2.5, 2)
Print "Pow(2, -3) = "; Pow(2, -3)
Print "Pow(1.78, 3) = "; Pow(1.78, 3)
Print
Print "2 ^ 2 = "; 2 ^ 2
Print "2.5 ^ 2 = "; 2.5 ^ 2
Print "2 ^ -3 = "; 2 ^ -3
Print "1.78 ^ 3 = "; 1.78 ^ 3
Print
Print "Press any key to quit"
Sleep |
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. | #Scala | Scala |
object HailstoneSequence extends App { // Show it all, default number is 27.
def hailstone(n: Int): LazyList[Int] =
n #:: (if (n == 1) LazyList.empty else hailstone(if (n % 2 == 0) n / 2 else n * 3 + 1))
Hailstone.details(args.headOption.map(_.toInt).getOrElse(27))
HailTest.main(Array())
}
object Hailstone extends App { // Compute a given or default number to Hailstone sequence
def details(nr: Int): Unit = {
val collatz = HailstoneSequence.hailstone(nr)
println(s"Use the routine to show that the hailstone sequence for the number: $nr.")
println(collatz.toList)
println(s"It has ${collatz.length} elements.")
}
details(args.headOption.map(_.toInt).getOrElse(27))
}
object HailTest extends App { // Compute only the < 100000 test
println(
"Compute the number < 100,000, which has the longest hailstone sequence with that sequence's length.")
val (n, len) = (1 until 100000).map(n => (n, HailstoneSequence.hailstone(n).length)).maxBy(_._2)
println(s"Longest hailstone sequence length= $len occurring with number $n.")
}
|
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. | #Sidef | Sidef | func hailstone(n) {
gather {
while (n > 1) {
take(n)
n = (n.is_even ? n/2 : (3*n + 1))
}
take(1)
}
}
if (__FILE__ == __MAIN__) { # true when not imported
var seq = hailstone(27)
say "hailstone(27) - #{seq.len} elements: #{seq.ft(0, 3)} [...] #{seq.ft(-4)}"
var n = 0
var max = 0
100_000.times { |i|
var seq = hailstone(i)
if (seq.len > max) {
max = seq.len
n = i
}
}
say "Longest sequence is for #{n}: #{max}"
} |
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.
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language |
If2[test1_, test2_, condBoth_, cond1_, cond2_, condNone_] := With[
{result1 = test1,
result2 = test2},
Which[
result1 && result2, condBoth,
result1, cond1,
result2, cond2,
True, condNone]];
SetAttributes[If2, HoldAll];
|
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.
| #min | min | (
:none :two :one :both -> :r2 -> :r1
(
((r1 r2 and)(both))
((r1)(one))
((r2)(two))
((true)(none))
) case
) :if2
(3 4 >) (0 0 ==)
("both are true")
("the first is true")
("the second is true")
("both are false")
if2 puts! ;the second is true
;compare to regular if
(4 even?)
("true")
("false")
if puts! ;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
| #Ring | Ring |
for n = 1 to 100
if n % 15 = 0 see "" + n + " = " + "FizzBuzz"+ nl
but n % 5 = 0 see "" + n + " = " + "Buzz" + nl
but n % 3 = 0 see "" + n + " = " + "Fizz" + nl
else see "" + n + " = " + n + nl ok
next
|
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.
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | Prime[Range[20]]
{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71}
Select[Range[100,150], PrimeQ]
{101, 103, 107, 109, 113, 127, 131, 137, 139, 149}
PrimePi[8000] - PrimePi[7700]
30
Prime[10000]
104729 |
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.
| #Agena | Agena | # Brain**** interpreter
# execute the Brain**** program in the code string
bf := proc( code :: string ) is
local address := 1; # current data address
local pc := 1; # current position in code
local data := []; # data - initially empty
local input := ""; # user input - initially empty
local bfOperations := # table of operations and their implemntations
[ ">" ~ proc() is inc address, 1 end
, "<" ~ proc() is dec address, 1 end
, "+" ~ proc() is inc data[ address ], 1 end
, "-" ~ proc() is dec data[ address ], 1 end
, "." ~ proc() is io.write( char( data[ address ] ) ) end
, "," ~ proc() is
# get next input character, converted to an integer
while input = ""
do
# no input left - get the next line
input := io.read()
od;
data[ address ] := abs( input[ 1 ] );
# remove the latest character from the input
if size input < 2
then
input := ""
else
input := input[ 2 to -1 ]
fi
end
, "[" ~ proc() is
if data[ address ] = 0
then
# skip to the end of the loop
local depth := 0;
do
inc pc, 1;
if code[ pc ] = "["
then
inc depth, 1
elif code[ pc ] = "]"
then
dec depth, 1
fi
until depth < 0
fi
end
, "]" ~ proc() is
if data[ address ] <> 0
then
# skip to the start of the loop
local depth := 0;
do
dec pc, 1;
if code[ pc ] = "["
then
dec depth, 1
elif code[ pc ] = "]"
then
inc depth, 1
fi
until depth < 0
fi
end
];
# execute the operations - ignore anything invalid
while pc <= size code
do
if data[ address ] = null
then
data[ address ] := 0
fi;
if bfOperations[ code[ pc ] ] <> null
then
bfOperations[ code[ pc ] ]()
fi;
inc pc, 1
od
end;
# prompt for Brain**** code and execute it, repeating until an empty code string is entered
scope
local code;
do
io.write( "BF> " );
code := io.read();
bf( code )
until code = ""
epocs; |
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.
| #Aime | Aime | integer
fitness(data t, data b)
{
integer c, f, i;
f = 0;
for (i, c in b) {
f += sign(t[i] ^ c);
}
f;
}
void
mutate(data e, data b, data u)
{
integer c;
for (, c in b) {
e.append(drand(15) ? c : u[drand(26)]);
}
}
integer
main(void)
{
data b, t, u;
integer f, i;
t = "METHINK IT IS LIKE A WEASEL";
u = "ABCDEFGHIJKLMNOPQRSTUVWXYZ ";
i = ~t;
while (i) {
i -= 1;
b.append(u[drand(26)]);
}
f = fitness(t, b);
while (f) {
data n;
integer a;
o_form("/lw4/~\n", f, b);
n = b;
i = 32;
while (i) {
data c;
i -= 1;
mutate(c, b, u);
a = fitness(t, c);
if (a < f) {
f = a;
n = c;
}
}
b = n;
}
o_form("/lw4/~\n", f, b);
return 0;
} |
http://rosettacode.org/wiki/Fibonacci_sequence | Fibonacci sequence | The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion).
The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition:
Fn = Fn+2 - Fn+1, if n<0
support for negative n in the solution is optional.
Related tasks
Fibonacci n-step number sequences
Leonardo numbers
References
Wikipedia, Fibonacci number
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #jq | jq |
nth_fib(pow(2;20)) | tostring | [length, .[:10], .[-10:]]
|
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
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
const proc: writeFactors (in integer: number) is func
local
var integer: testNum is 0;
begin
write("Factors of " <& number <& ": ");
for testNum range 1 to sqrt(number) do
if number rem testNum = 0 then
if testNum <> 1 then
write(", ");
end if;
write(testNum);
if testNum <> number div testNum then
write(", " <& number div testNum);
end if;
end if;
end for;
writeln;
end func;
const proc: main is func
local
const array integer: numsToFactor is [] (45, 53, 64);
var integer: number is 0;
begin
for number range numsToFactor do
writeFactors(number);
end for;
end func; |
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
| #SequenceL | SequenceL | Factors(num(0))[i] := i when num mod i = 0 foreach i within 1 ... num; |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #Haxe | Haxe | // live demo: http://try.haxe.org/#2E7D4
static function hq9plus(code:String):String {
var out:String = "";
var acc:Int = 0;
for (position in 0 ... code.length) switch (code.charAt(position)) {
case "H", "h": out += "Hello, World!\n";
case "Q", "q": out += '$code\n';
case "9":
var quantity:Int = 99;
while (quantity > 1) {
out += '$quantity bottles of beer on the wall, $quantity bottles of beer.\n';
out += 'Take one down and pass it around, ${--quantity} bottles of beer.\n';
}
out += "1 bottle of beer on the wall, 1 bottle of beer.\n" +
"Take one down and pass it around, no more bottles of beer on the wall.\n\n" +
"No more bottles of beer on the wall, no more bottles of beer.\n" +
"Go to the store and buy some more, 99 bottles of beer on the wall.\n";
case "+": acc++;
}
return out;
} |
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
| #D.C3.A9j.C3.A0_Vu | Déjà Vu | (remove-comments) text:
]
for line in text:
if and line not starts-with line "#":
line
[
(markov-parse) text:
]
for line in text:
local :index find line " -> "
local :pat slice line 0 index
local :rep slice line + index 4 len line
local :term starts-with rep "."
if term:
set :rep slice rep 1 len rep
& pat & term rep
[
markov-parse:
(markov-parse) (remove-comments) split !decode!utf-8 !read!stdin "\n"
(markov-tick) rules start:
for rule in copy rules:
local :pat &< rule
local :rep &> dup &> rule
local :term &<
local :index find start pat
if < -1 index:
)
slice start + index len pat len start
rep
slice start 0 index
concat(
return term
true start
markov rules:
true
while:
not (markov-tick) rules
!. markov markov-parse get-from !args 1 |
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
| #EchoLisp | EchoLisp |
;; rule := (pattern replacement [#t terminal])
(define-syntax-rule (pattern rule) (first rule))
(define-syntax-rule (repl sule) (second rule))
(define-syntax-rule (term? rule) (!empty? (cddr rule)))
;; (alpha .beta )--> (alpha beta #t)
(define (term-rule rule)
(if (string=? (string-first (repl rule)) ".")
(list (pattern rule) (string-rest (repl rule)) #t)
rule ))
;; returns list of rules
(define (parse-rules lines)
(map term-rule
(for/list [(line (string-split lines "\n"))]
#:continue (string=? (string-first line) "#")
(map string-trim
(string-split (string-replace line "/\\t/g" " ") " -> ")))))
;; markov machine
(define (markov i-string rules)
(while
(for/fold (run #f) ((rule rules))
#:when (string-index (pattern rule) i-string)
(set! i-string (string-replace i-string (pattern rule) (repl rule)))
;;(writeln rule i-string) ;; uncomment for trace
#:break (term? rule) => #f
#:break #t => #t ))
i-string)
(define (task i-string RS)
(markov i-string (parse-rules RS)))
|
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.
| #Elixir | Elixir | defmodule U0, do: defexception [:message]
defmodule U1, do: defexception [:message]
defmodule ExceptionsTest do
def foo do
Enum.each([0,1], fn i ->
try do
bar(i)
rescue
U0 -> IO.puts "U0 rescued"
end
end)
end
def bar(i), do: baz(i)
def baz(0), do: raise U0
def baz(1), do: raise U1
end
ExceptionsTest.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.
| #Erlang | Erlang |
-module( exceptions_catch ).
-export( [task/0] ).
task() -> [foo(X) || X<- lists:seq(1, 2)].
baz( 1 ) -> erlang:throw( u0 );
baz( 2 ) -> erlang:throw( u1 ).
foo( N ) ->
try
baz( N )
catch
_:u0 -> io:fwrite( "Catched ~p~n", [u0] )
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
| #Common_Lisp | Common Lisp | (define-condition unexpected-odd-number (error)
((number :reader number :initarg :number))
(:report (lambda (condition stream)
(format stream "Unexpected odd number: ~w."
(number condition)))))
(defun get-number (&aux (n (random 100)))
(if (not (oddp n)) n
(error 'unexpected-odd-number :number n)))
(defun get-even-number ()
(handler-case (get-number)
(unexpected-odd-number (condition)
(1+ (number condition))))) |
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
| #D | D | import std.stdio;
/// Throw Exceptions
/// Stack traces are generated compiling with the -g switch.
void test1() {
throw new Exception("Sample Exception");
}
/// Catch Exceptions
void test2() {
try {
test1();
} catch (Exception ex) {
writeln(ex);
throw ex; // rethrow
}
}
/// Ways to implement finally
void test3() {
try test2();
finally writeln("test3 finally");
}
/// Or also with scope guards
void test4() {
scope(exit) writeln("Test4 done");
scope(failure) writeln("Test4 exited by exception");
scope(success) writeln("Test4 exited by return or function end");
test2();
}
void main() {
test4();
} |
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
| #Bracmat | Bracmat | sys$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
| #Brat | Brat | include :subprocess
p subprocess.run :ls #Lists files in directory |
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
| #Brlcad | Brlcad |
exec ls
|
http://rosettacode.org/wiki/Factorial | Factorial | Definitions
The factorial of 0 (zero) is defined as being 1 (unity).
The Factorial Function of a positive integer, n, is defined as the product of the sequence:
n, n-1, n-2, ... 1
Task
Write a function to return the factorial of a number.
Solutions can be iterative or recursive.
Support for trapping negative n errors is optional.
Related task
Primorial numbers
| #ALGOL-M | ALGOL-M | INTEGER FUNCTION FACTORIAL( N ); INTEGER N;
BEGIN
INTEGER I, FACT;
FACT := 1;
FOR I := 2 STEP 1 UNTIL N DO
FACT := FACT * I;
FACTORIAL := FACT;
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
| #GAP | GAP | expon := function(a, n, one, mul)
local p;
p := one;
while n > 0 do
if IsOddInt(n) then
p := mul(a, p);
fi;
a := mul(a, a);
n := QuoInt(n, 2);
od;
return p;
end;
expon(2, 10, 1, \*);
# 1024
# a more creative use of exponentiation
List([0 .. 31], n -> (1 - expon(0, n, 1, \-))/2);
# [ 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
# 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1 ] |
http://rosettacode.org/wiki/Exponentiation_operator | Exponentiation operator | Most programming languages have a built-in implementation of exponentiation.
Task
Re-implement integer exponentiation for both intint and floatint as both a procedure, and an operator (if your language supports operator definition).
If the language supports operator (or procedure) overloading, then an overloaded form should be provided for both intint and floatint variants.
Related tasks
Exponentiation order
arbitrary-precision integers (included)
Exponentiation with infix operators in (or operating on) the base
| #Go | Go | package main
import (
"errors"
"fmt"
)
func expI(b, p int) (int, error) {
if p < 0 {
return 0, errors.New("negative power not allowed")
}
r := 1
for i := 1; i <= p; i++ {
r *= b
}
return r, nil
}
func expF(b float32, p int) float32 {
var neg bool
if p < 0 {
neg = true
p = -p
}
r := float32(1)
for pow := b; p > 0; pow *= pow {
if p&1 == 1 {
r *= pow
}
p >>= 1
}
if neg {
r = 1 / r
}
return r
}
func main() {
ti := func(b, p int) {
fmt.Printf("%d^%d: ", b, p)
e, err := expI(b, p)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(e)
}
}
fmt.Println("expI tests")
ti(2, 10)
ti(2, -10)
ti(-2, 10)
ti(-2, 11)
ti(11, 0)
fmt.Println("overflow undetected")
ti(10, 10)
tf := func(b float32, p int) {
fmt.Printf("%g^%d: %g\n", b, p, expF(b, p))
}
fmt.Println("\nexpF tests:")
tf(2, 10)
tf(2, -10)
tf(-2, 10)
tf(-2, 11)
tf(11, 0)
fmt.Println("disallowed in expI, allowed here")
tf(0, -1)
fmt.Println("other interesting cases for 32 bit float type")
tf(10, 39)
tf(10, -39)
tf(-10, 39)
} |
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. | #Tcl | Tcl | ### In the file hailstone.tcl ###
package provide hailstone 1.0
proc hailstone n {
while 1 {
lappend seq $n
if {$n == 1} {return $seq}
set n [expr {$n & 1 ? $n*3+1 : $n/2}]
}
}
# If directly executed, run demo code
if {[info script] eq $::argv0} {
set h27 [hailstone 27]
puts "h27 len=[llength $h27]"
puts "head4 = [lrange $h27 0 3]"
puts "tail4 = [lrange $h27 end-3 end]"
set maxlen [set max 0]
for {set i 1} {$i<100000} {incr i} {
set l [llength [hailstone $i]]
if {$l>$maxlen} {set maxlen $l;set max $i}
}
puts "max is $max, with length $maxlen"
} |
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. | #Wren | Wren | /* hailstone.wren */
var Hailstone = Fn.new { |n|
if (n < 1) Fiber.abort("Parameter must be a positive integer.")
var h = [n]
while (n != 1) {
n = (n%2 == 0) ? (n/2).floor : 3*n + 1
h.add(n)
}
return h
}
var libMain_ = Fn.new {
var h = Hailstone.call(27)
System.print("For the Hailstone sequence starting with n = 27:")
System.print(" Number of elements = %(h.count)")
System.print(" First four elements = %(h[0..3])")
System.print(" Final four elements = %(h[-4..-1])")
System.print("\nThe Hailstone sequence for n < 100,000 with the longest length is:")
var longest = 0
var longlen = 0
for (n in 1..99999) {
var h = Hailstone.call(n)
var c = h.count
if (c > longlen) {
longest = n
longlen = c
}
}
System.print(" Longest = %(longest)")
System.print(" Length = %(longlen)")
}
// Check if it's being used as a library or not.
import "os" for Process
if (Process.allArguments[1] == "hailstone.wren") { // if true, not a library
libMain_.call()
} |
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.
| #Morfa | Morfa |
import morfa.base;
// introduce 4 new operators to handle the if2 syntax
operator then { kind = infix, precedence = mul, associativity = right}
operator else1 { kind = infix, precedence = not, associativity = left }
operator else2 { kind = infix, precedence = not, associativity = left }
operator none { kind = infix, precedence = not, associativity = left }
// function which bounds the condition expression to the if2 "actions"
public func then(condition: IF2.Condition, actionHolder: IF2): void
{
actionHolder.actions[condition]();
}
// functions (bound to operators) used to "build" the if2 "statement"
public func else1(bothAction: func(): void, else1Action: func(): void): IF2
{
return IF2([IF2.Condition.both -> bothAction,
IF2.Condition.else1 -> else1Action]);
}
public func else2(actionHolder: IF2, action: func(): void): IF2
{
return checkAndAdd(actionHolder, action, IF2.Condition.else2);
}
public func none(actionHolder: IF2, action: func(): void): IF2
{
return checkAndAdd(actionHolder, action, IF2.Condition.none);
}
// finally, function which combines two conditions into a "trigger" for the if2 "statement"
public func if2(condition1: bool, condition2: bool): IF2.Condition
{
if (condition1 and condition2)
return IF2.Condition.both;
else if (condition1)
return IF2.Condition.else1;
else if (condition2)
return IF2.Condition.else2;
else
return IF2.Condition.none;
}
// private helper function to build the IF2 structure
func checkAndAdd(actionHolder: IF2, action: func(): void, actionName: IF2.Condition): IF2
{
if (actionHolder.actions.contains(actionName))
throw new Exception("action defined twice for one condition in if2");
else
actionHolder.actions[actionName] = action;
return actionHolder;
}
// helper structure to process the if2 "statement"
struct IF2
{
public enum Condition { both, else1, else2, none };
public var actions: Dict<Condition, func(): void>;
}
// usage
if2 (true, false) then func()
{
println("both true");
}
else1 func()
{
println("first true");
}
else2 func()
{
println("second true");
}
none func()
{
println("none true");
};
|
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.
| #Nemerle | Nemerle |
// point of interest: the when keyword and && operator inside the macro definition are macros themselves
macro if2 (cond1, cond2, bodyTT, bodyTF, bodyFT, bodyFF)
syntax ("if2", "(", cond1, ")", "(", cond2, ")", bodyTT, "elseTF", bodyTF, "elseFT", bodyFT, "else", bodyFF)
{
<[
when($cond1 && $cond2) {$bodyTT};
when($cond1 && !($cond2)) {$bodyTF};
when(!($cond1) && $cond2) {$bodyFT};
when(!($cond1) && !($cond2)) {$bodyFF};
]>
} |
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
| #Robotic | Robotic |
set "local1" to 1
: "loop"
wait for 10
if "('local1' % 15)" = 0 then "fizzbuzz"
if "('local1' % 3)" = 0 then "fizz"
if "('local1' % 5)" = 0 then "buzz"
* "&local1&"
: "inc"
inc "local1" by 1
if "local1" <= 100 then "loop"
goto "done"
: "fizzbuzz"
* "FizzBuzz"
goto "inc"
: "fizz"
* "Fizz"
goto "inc"
: "buzz"
* "Buzz"
goto "inc"
: "done"
end
|
http://rosettacode.org/wiki/Extensible_prime_generator | Extensible prime generator | Task
Write a generator of prime numbers, in order, that will automatically adjust to accommodate the generation of any reasonably high prime.
The routine should demonstrably rely on either:
Being based on an open-ended counter set to count without upper limit other than system or programming language limits. In this case, explain where this counter is in the code.
Being based on a limit that is extended automatically. In this case, choose a small limit that ensures the limit will be passed when generating some of the values to be asked for below.
If other methods of creating an extensible prime generator are used, the algorithm's means of extensibility/lack of limits should be stated.
The routine should be used to:
Show the first twenty primes.
Show the primes between 100 and 150.
Show the number of primes between 7,700 and 8,000.
Show the 10,000th prime.
Show output on this page.
Note: You may reference code already on this site if it is written to be imported/included, then only the code necessary for import and the performance of this task need be shown. (It is also important to leave a forward link on the referenced tasks entry so that later editors know that the code is used for multiple tasks).
Note 2: If a languages in-built prime generator is extensible or is guaranteed to generate primes up to a system limit, (231 or memory overflow for example), then this may be used as long as an explanation of the limits of the prime generator is also given. (Which may include a link to/excerpt from, language documentation).
Note 3:The task is written so it may be useful in solving the task Emirp primes as well as others (depending on its efficiency).
Reference
Prime Numbers. Website with large count of primes.
| #Nim | Nim | import tables
type PrimeType = int
proc primesHashTable(): iterator(): PrimeType {.closure.} =
iterator output(): PrimeType {.closure.} =
# some initial values to avoid race and reduce initializations...
yield 2.PrimeType; yield 3.PrimeType; yield 5.PrimeType; yield 7.PrimeType
var h = initTable[PrimeType,PrimeType]()
var n = 9.PrimeType
let bps = primesHashTable()
var bp = bps() # advance past 2
bp = bps(); var q = bp * bp # to initialize with 3
while true:
if n >= q:
let inc = bp + bp
h[n + inc] = inc
bp = bps(); q = bp * bp
elif h.hasKey(n):
var inc: PrimeType
discard h.take(n, inc)
var nxt = n + inc
while h.hasKey(nxt): nxt += inc # ensure no duplicates
h[nxt] = inc
else: yield n
n += 2.PrimeType
output
var num = 0
stdout.write "The first 20 primes are: "
var iter = primesHashTable()
for p in iter():
if num >= 20: break else: stdout.write(p, " "); num += 1
echo ""
stdout.write "The primes between 100 and 150 are: "
iter = primesHashTable()
for p in iter():
if p >= 150: break
if p >= 100: stdout.write(p, " ")
echo ""
num = 0
iter = primesHashTable()
for p in iter():
if p > 8000: break
if p >= 7700: num += 1
echo "The number of primes between 7700 and 8000 is: ", num
num = 1
iter = primesHashTable()
for p in iter():
if num >= 10000:
echo "The 10,000th prime is: ", p
break
num += 1
var sum = 0
iter = primesHashTable()
for p in iter():
if p >= 2_000_000:
echo "The sum of the primes to two million is: ", sum
break
sum += p |
http://rosettacode.org/wiki/Execute_Brain**** | Execute Brain**** | Execute Brain**** is an implementation of Brainf***.
Other implementations of Brainf***.
RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages.
Below are links to each of the versions of RCBF.
An implementation need only properly implement the following instructions:
Command
Description
>
Move the pointer to the right
<
Move the pointer to the left
+
Increment the memory cell under the pointer
-
Decrement the memory cell under the pointer
.
Output the character signified by the cell at the pointer
,
Input a character and store it in the cell at the pointer
[
Jump past the matching ] if the cell under the pointer is 0
]
Jump back to the matching [ if the cell under the pointer is nonzero
Any cell size is allowed, EOF (End-O-File) support is optional, as is whether you have bounded or unbounded memory.
| #ALGOL_68 | ALGOL 68 | BEGIN # Brain**** -> Algol 68 transpiler #
# a single line of Brain**** code is prompted for and read from #
# standard input, the generated code is written to standard output #
# the original code is included in the output as a comment #
# transpiles the Brain**** code in code list to Algol 68 #
PROC generate = ( STRING code list )VOID:
BEGIN
PROC emit = ( STRING code )VOID: print( ( code, newline ) );
PROC emit1 = ( STRING code )VOID:
print( ( IF need semicolon THEN ";" ELSE "" FI
, newline, indent, code
)
);
PROC next = CHAR: IF c pos > c max
THEN "$"
ELSE CHAR result = code list[ c pos ];
c pos +:= 1;
result
FI;
# address and data modes and the data space #
emit( "BEGIN" );
emit( " MODE DADDR = INT; # data address #" );
emit( " MODE DATA = INT;" );
emit( " DATA zero = 0;" );
emit( " [-255:255]DATA data; # finite data space #" );
emit( " FOR i FROM LWB data TO UPB data DO data[i] := zero OD;" );
emit( " DADDR addr := ( UPB data + LWB data ) OVER 2;" );
# actual code #
STRING indent := " ";
BOOL need semicolon := FALSE;
INT c pos := LWB code list;
INT c max = UPB code list;
CHAR c := next;
WHILE c /= "$" DO
IF c = "?"
THEN emit1( "SKIP" );
need semicolon := TRUE;
WHILE ( c := next ) = "?" DO SKIP OD
ELIF c = "<" OR c = ">"
THEN CHAR op code = c;
CHAR assign op = IF c = ">" THEN "+" ELSE "-" FI;
INT incr := 1;
WHILE ( c := next ) = op code DO incr +:= 1 OD;
emit1( "addr " + assign op + ":= " + whole( incr, 0 ) );
need semicolon := TRUE
ELIF c = "+" OR c = "-"
THEN CHAR op code = c;
INT incr := 1;
WHILE ( c := next ) = op code DO incr +:= 1 OD;
emit1( "data[ addr ] " + op code + ":= " + whole( incr, 0 ) );
need semicolon := TRUE
ELIF c = "."
THEN emit1( "print( ( REPR data[ addr ] ) )" );
need semicolon := TRUE;
c := next
ELIF c = ","
THEN emit1( "data[ addr ] := ABS read char" );
need semicolon := TRUE;
c := next
ELIF c = "["
THEN emit1( "WHILE data[ addr ] /= zero DO" );
indent +:= " ";
need semicolon := FALSE;
c := next
ELIF c = "]"
THEN need semicolon := FALSE;
indent := indent[ LWB indent + 2 : ];
emit1( "OD" );
need semicolon := TRUE;
c := next
ELSE
print( ( "Invalid op code: """, c, """", newline ) );
c := next
FI
OD;
emit( "" );
emit( "END" )
END # gen # ;
# get the code to transpile and output it as a comment at the start #
# of the code #
print( ( "CO BF> " ) );
STRING code list;
read( ( code list, newline ) );
print( ( newline, code list, newline, "CO", newline ) );
# transpile the code #
generate( code list )
END |
http://rosettacode.org/wiki/Evolutionary_algorithm | Evolutionary algorithm | Starting with:
The target string: "METHINKS IT IS LIKE A WEASEL".
An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent).
A fitness function that computes the ‘closeness’ of its argument to the target string.
A mutate function that given a string and a mutation rate returns a copy of the string, with some characters probably mutated.
While the parent is not yet the target:
copy the parent C times, each time allowing some random probability that another character might be substituted using mutate.
Assess the fitness of the parent and all the copies to the target and make the most fit string the new parent, discarding the others.
repeat until the parent converges, (hopefully), to the target.
See also
Wikipedia entry: Weasel algorithm.
Wikipedia entry: Evolutionary algorithm.
Note: to aid comparison, try and ensure the variables and functions mentioned in the task description appear in solutions
A cursory examination of a few of the solutions reveals that the instructions have not been followed rigorously in some solutions. Specifically,
While the parent is not yet the target:
copy the parent C times, each time allowing some random probability that another character might be substituted using mutate.
Note that some of the the solutions given retain characters in the mutated string that are correct in the target string. However, the instruction above does not state to retain any of the characters while performing the mutation. Although some may believe to do so is implied from the use of "converges"
(:* repeat until the parent converges, (hopefully), to the target.
Strictly speaking, the new parent should be selected from the new pool of mutations, and then the new parent used to generate the next set of mutations with parent characters getting retained only by not being mutated. It then becomes possible that the new set of mutations has no member that is fitter than the parent!
As illustration of this error, the code for 8th has the following remark.
Create a new string based on the TOS, changing randomly any characters which
don't already match the target:
NOTE: this has been changed, the 8th version is completely random now
Clearly, this algo will be applying the mutation function only to the parent characters that don't match to the target characters!
To ensure that the new parent is never less fit than the prior parent, both the parent and all of the latest mutations are subjected to the fitness test to select the next parent.
| #ALGOL_68 | ALGOL 68 | STRING target := "METHINKS IT IS LIKE A WEASEL";
PROC fitness = (STRING tstrg)REAL:
(
INT sum := 0;
FOR i FROM LWB tstrg TO UPB tstrg DO
sum +:= ABS(ABS target[i] - ABS tstrg[i])
OD;
# fitness := # 100.0*exp(-sum/10.0)
);
PROC rand char = CHAR:
(
#STATIC# []CHAR ucchars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ ";
# rand char := # ucchars[ENTIER (random*UPB ucchars)+1]
);
PROC mutate = (REF STRING kid, parent, REAL mutate rate)VOID:
(
FOR i FROM LWB parent TO UPB parent DO
kid[i] := IF random < mutate rate THEN rand char ELSE parent[i] FI
OD
);
PROC kewe = ( STRING parent, INT iters, REAL fits, REAL mrate)VOID:
(
printf(($"#"4d" fitness: "g(-6,2)"% "g(-6,4)" '"g"'"l$, iters, fits, mrate, parent))
);
PROC evolve = VOID:
(
FLEX[UPB target]CHAR parent;
REAL fits;
[100]FLEX[UPB target]CHAR kid;
INT iters := 0;
kid[LWB kid] := LOC[UPB target]CHAR;
REAL mutate rate;
# initialize #
FOR i FROM LWB parent TO UPB parent DO
parent[i] := rand char
OD;
fits := fitness(parent);
WHILE fits < 100.0 DO
INT j;
REAL kf;
mutate rate := 1.0 - exp(- (100.0 - fits)/400.0);
FOR j FROM LWB kid TO UPB kid DO
mutate(kid[j], parent, mutate rate)
OD;
FOR j FROM LWB kid TO UPB kid DO
kf := fitness(kid[j]);
IF fits < kf THEN
fits := kf;
parent := kid[j]
FI
OD;
IF iters MOD 100 = 0 THEN
kewe( parent, iters, fits, mutate rate )
FI;
iters+:=1
OD;
kewe( parent, iters, fits, mutate rate )
);
main:
(
evolve
) |
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
| #Julia | Julia | fib(n) = n < 2 ? n : fib(n-1) + fib(n-2) |
http://rosettacode.org/wiki/Factors_of_an_integer | Factors of an integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Compute the factors of a positive integer.
These factors are the positive integers by which the number being factored can be divided to yield a positive integer result.
(Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty; this task does not require handling of either of these cases).
Note that every prime number has two factors: 1 and itself.
Related tasks
count in factors
prime decomposition
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
sequence: smallest number greater than previous term with exactly n divisors
| #Sidef | Sidef | say divisors(97) #=> [1, 97]
say divisors(2695) #=> [1, 5, 7, 11, 35, 49, 55, 77, 245, 385, 539, 2695] |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #Icon_and_Unicon | Icon and Unicon | procedure main(A)
repeat writes("Enter HQ9+ code: ") & HQ9(get(A)|read()|break)
end
procedure HQ9(code)
static bnw,bcr
initial { # number matching words and line feeds for the b-th bottle
bnw := table(" bottles"); bnw[1] := " bottle"; bnw[0] := "No more bottles"
bcr := table("\n"); bcr[0]:=""
}
every c := map(!code) do # ignore case
case c of { # interpret
"h" : write("Hello, World!") # . hello
"q" : write(code) # . quine
"9" : { # . 99 bottles
every b := 99 to 1 by -1 do writes(
bcr[b],b,bnw[b]," of beer on the wall\n",
b,bnw[b]," of beer\nTake one down, pass it around\n",
1~=b|"",bnw[b-1]," of beer on the wall",bcr[b-1])
write(", ",map(bnw[b-1])," of beer.\nGo to the store ",
"and buy some more, 99 bottles of beer on the wall.")
}
"+" : { /acc := 0 ; acc +:=1 } # . yes it is weird
default: stop("Syntax error in ",code) # . error/exit
}
return
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
| #F.23 | F# | open System
open System.IO
open System.Text.RegularExpressions
type Rule = {
matches : Regex
replacement : string
terminate : bool
}
let (|RegexMatch|_|) regexStr input =
let m = Regex.Match(input, regexStr, RegexOptions.ExplicitCapture)
if m.Success then Some (m) else None
let (|RuleReplace|_|) rule input =
let replaced = rule.matches.Replace(input, rule.replacement, 1, 0)
if input = replaced then None
else Some (replaced, rule.terminate)
let parseRules line =
match line with
| RegexMatch "^#" _ -> None
| RegexMatch "(?<pattern>.*?)\s+->\s+(?<replacement>.*)$" m ->
let replacement = (m.Groups.Item "replacement").Value
let terminate = replacement.Length > 0 && replacement.Substring(0,1) = "."
let pattern = (m.Groups.Item "pattern").Value
Some {
matches = pattern |> Regex.Escape |> Regex;
replacement = if terminate then replacement.Substring(1) else replacement;
terminate = terminate
}
| _ -> failwith "illegal rule definition"
let rec applyRules input = function
| [] -> (input, true)
| rule::rules ->
match input with
| RuleReplace rule (withReplacement, terminate) ->
(withReplacement, terminate)
| _ -> applyRules input rules
[<EntryPoint>]
let main argv =
let rules = File.ReadAllLines argv.[0] |> Array.toList |> List.choose parseRules
let rec run input =
let output, terminate = applyRules input rules
if terminate then output
else run output
Console.ReadLine()
|> run
|> printfn "%s"
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.
| #Factor | Factor | USING: combinators.extras continuations eval formatting kernel ;
IN: rosetta-code.nested-exceptions
ERROR: U0 ;
ERROR: U1 ;
: baz ( -- )
"IN: rosetta-code.nested-exceptions : baz ( -- ) U1 ;"
( -- ) eval U0 ;
: bar ( -- ) baz ;
: foo ( -- )
[
[ bar ] [
dup T{ U0 } =
[ "%u recovered\n" printf ] [ rethrow ] if
] recover
] twice ;
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.
| #Fantom | Fantom |
const class U0 : Err
{
new make () : super ("U0") {}
}
const class U1 : Err
{
new make () : super ("U1") {}
}
class Main
{
Int bazCalls := 0
Void baz ()
{
bazCalls += 1
if (bazCalls == 1)
throw U0()
else
throw U1()
}
Void bar ()
{
baz ()
}
Void foo ()
{
2.times
{
try
{
bar ()
}
catch (U0 e)
{
echo ("Caught U0")
}
}
}
public static Void main ()
{
Main().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.
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Enum ErrorTypes
U0 = 1000
U1
End Enum
Function errorName(ex As ErrorTypes) As String
Select Case As Const ex
Case U0
Return "U0"
Case U1
Return "U1"
End Select
End Function
Sub catchError(ex As ErrorTypes)
Dim e As Integer = Err '' cache the error number
If e = ex Then
Print "Error "; errorName(ex); ", number"; ex; " caught"
End If
End Sub
Sub baz()
Static As Integer timesCalled = 0 '' persisted between procedure calls
timesCalled += 1
If timesCalled = 1 Then
err = U0
Else
err = U1
End if
End Sub
Sub bar()
baz
End Sub
Sub foo()
bar
catchError(U0) '' not interested in U1, assumed non-fatal
bar
catchError(U0)
End Sub
Foo
Print
Print "Press any key to quit"
Sleep |
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
| #Delphi | Delphi | procedure test;
begin
raise Exception.Create('Sample Exception');
end; |
http://rosettacode.org/wiki/Exceptions | Exceptions | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
This task is to give an example of an exception handling routine
and to "throw" a new exception.
Related task
Exceptions Through Nested Calls
| #Dyalect | Dyalect | func Integer.Add(x) {
throw @NegativesNotAllowed(x) when x < 0
this + x
}
try {
12.Add(-5)
} catch {
@NegativesNotAllowed(x) => print("Negative number: \(x)")
} |
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
| #C | C | #include <stdlib.h>
int main()
{
system("ls");
return 0;
} |
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
| #C.23 | C# | using System.Diagnostics;
namespace Execute
{
class Program
{
static void Main(string[] args)
{
Process.Start("cmd.exe", "/c 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
| #AmigaE | AmigaE | PROC fact(x) IS IF x>=2 THEN x*fact(x-1) ELSE 1
PROC main()
WriteF('5! = \d\n', fact(5))
ENDPROC |
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
| #Haskell | Haskell | (^) :: (Num a, Integral b) => a -> b -> a
_ ^ 0 = 1
x ^ n | n > 0 = f x (n-1) x where
f _ 0 y = y
f a d y = g a d where
g b i | even i = g (b*b) (i `quot` 2)
| otherwise = f b (i-1) (b*y)
_ ^ _ = error "Prelude.^: negative exponent" |
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
| #HicEst | HicEst | WRITE(Clipboard) pow(5, 3) ! 125
WRITE(ClipBoard) pow(5.5, 7) ! 152243.5234
FUNCTION pow(x, n)
pow = 1
DO i = 1, n
pow = pow * x
ENDDO
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. | #zkl | zkl | fcn collatz(n,z=L()){ z.append(n); if(n==1) return(z);
if(n.isEven) return(self.fcn(n/2,z)); return(self.fcn(n*3+1,z)) }
h27:=collatz(27);
println("Hailstone(27)-->",h27[0,4].concat(","),"...",
h27[-4,*].concat(",")," length ",h27.len());
[2..0d100_000].pump(Void, // loop n from 2 to 100,000
collatz, // generate Collatz sequence(n)
fcn(c,n){ // if new longest sequence, save length/C, return longest
if(c.len()>n[0]) n.clear(c.len(),c[0]); n}.fp1(L(0,0)))
.println(); |
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.
| #NewLISP | NewLISP | (context 'if2)
(define-macro (if2:if2 cond1 cond2 both-true first-true second-true neither)
(cond
((eval cond1)
(if (eval cond2)
(eval both-true)
(eval first-true)))
((eval cond2)
(eval second-true))
(true
(eval neither))))
(context MAIN)
> (if2 true true 'bothTrue 'firstTrue 'secondTrue 'else)
bothTrue
> (if2 true false 'bothTrue 'firstTrue 'secondTrue 'else)
firstTrue
> (if2 false true 'bothTrue 'firstTrue 'secondTrue 'else)
secondTrue
> (if2 false false 'bothTrue 'firstTrue 'secondTrue 'else)
else
|
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
| #Rockstar | Rockstar | Midnight takes your heart and your soul
While your heart is as high as your soul
Put your heart without your soul into your heart
Give back your heart
Desire is a lovestruck ladykiller
My world is nothing
Fire is ice
Hate is water
Until my world is Desire,
Build my world up
If Midnight taking my world, Fire is nothing and Midnight taking my world, Hate is nothing
Shout "FizzBuzz!"
Take it to the top
If Midnight taking my world, Fire is nothing
Shout "Fizz!"
Take it to the top
If Midnight taking my world, Hate is nothing
Say "Buzz!"
Take it to the top
Whisper my world
|
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.
| #PARI.2FGP | PARI/GP | void
showprimes(GEN lower, GEN upper)
{
forprime_t T;
if (!forprime_init(&T, a,b)) return;
while(forprime_next(&T))
{
pari_printf("%Ps\n", T.pp);
}
} |
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.
| #Amazing_Hopper | Amazing Hopper |
/*
BFC.COM
BrainF**k's Pseudo-compiler!
Mr_Dalien. NOV 26, 2021
*/
#include <hopper.h>
#proto checkMove(_S_,_OPE_,_CODE_,_BF_)
#proto check(_S_,_OPE_,_CODE_,_BF_)
#proto tabulation(_S_)
main:
total arg,minus(1) zero?
do {
{"\LR","Bad filename!\OFF\n"}print
{0}return
}
filename = [&2] // get filename parameter 2 (parameter 1 is "bfc.com")
sf="",{filename}exist?,not,
do{
{"File: \LR",filename,"\OFF"," don't exist!\n"}print
{0}return
}
{filename}load string(sf) // load file as string
--sf // "load string" load adding a newline at the EOS. "--sf" delete it!
// determine tape size:
rightMove=0,{">",sf}count at, mov(rightMove)
leftMove=0,{"<",sf}count at, mov(leftMove)
totalCells = 0
prec(0) // precision 0 decimals: all number are integers!
{0}{rightMove}minus(leftMove), cpy(totalCells),lt?
do{
{"In file \LR",filename,"\OFF",": program bad formed!\n"}print
{0}return
}
// start process!
nLen=0, {sf}len,mov(nLen)
i=1, // index
res={}, // new file "C"
space=5 // tab space
// header:
{"#include <stdio.h>","int main(){"," int ptr=0, i=0, cell["},{totalCells},xtostr,cat,{"];"}cat,push all(res)
{" for( i=0; i<",totalCells},xtostr,cat,{"; ++i) cell[i]=0;"}cat,push(res)
iwhile={},swOk=0,true(swOk)
cntMove=0
v=""
__PRINCIPAL__:
[i:i]get(sf),mov(v),
switch(v)
case(">")::do{
_checkMove(">","+","ptr",sf),
_tabulation(space),{"if(ptr>="}cat,{totalCells},xtostr,cat
{") perror(\"Program pointer overflow\");"}cat,push(res),
exit
}
case("<")::do{
_checkMove("<","-","ptr",sf),
_tabulation(space),{"if(ptr<0) perror(\"Program pointer underflow\");"}cat,push(res),
exit
}
case("+")::do{
_check("+","+","cell[ptr]",sf), exit
}
case("-")::do{
_check("-","-","cell[ptr]",sf), exit
}
case("[")::do{
{"]"}push(iwhile)
_tabulation(space),{"while(cell[ptr])"}cat,push(res),
_tabulation(space),{"{"}cat,push(res)
space += 5
exit
}
case("]")::do{
try
pop(iwhile),kill
space -= 5, _tabulation(space),{"}"}cat,push(res)
catch(e)
{"SIMBOL: ",v,", POS: ",i,": \LR","Symbol out of context \OFF"}println
false(swOk)
finish
exit
}
case(".")::do{
_tabulation(space),{"putchar(cell[ptr]);"}cat,push(res)
exit
}
case(",")::do{
_tabulation(space),{"cell[ptr] = getc(stdin);"}cat,push(res)
exit
}
// otherwise?
{"WARNING! SIMBOL(ASCII): ",v}asc,{", POS: ",i,": \LY","Invalid code, is ommited!\OFF\n"}print
end switch
{cntMove}neg? // exist more "<" than ">" ??
do {
{"SIMBOL: ",v,", POS: ",i,": \LR","Underflow detected!\OFF\n"}print
false(swOk)
}
++i,{nLen,i}le?,{swOk},and,jt(__PRINCIPAL__)
{swOk} do{
_tabulation(space),{"return 0;"}cat,push(res)
space -=5
{"}"}push(res)
name="", {"",".bf",filename},transform,mov(name), // bye bye ".bf"!
cname="", {name,".c"}cat,mov(cname), // hello <filename>.c!
{"\n"}tok sep // save array with newlines
{res,cname},save // save the array into the <filename>.c"
{" "}tok sep // "join" need this!
executable="", {"gcc ",cname," -o ",name} join(executable) // line to compile new filename
{executable}execv // do compile c program generated!
/* OPTIONAL: remove <filename>.c */
// {"rm ",cname}cat,execv
}
{"\LG","Compilation terminated "}
if({swOk}not)
{"\LR","with errors!\OFF\n"}
else
{"successfully!\OFF\n"}
end if
print
exit(0)
.locals
checkMove(simb,operator,code,bfprg)
c=1,
{cntMove},iif({operator}eqto("+"),1,-1),add,mov(cntMove)
__SUB_MOVE__:
++i,[i:i]get(sf),{simb}eq?
do{ ++c,
{cntMove},iif({operator}eqto("+"),1,-1),add,mov(cntMove)
jmp(__SUB_MOVE__)
}
_tabulation(space),{code}cat,{operator}cat,{"= "}cat,{c}xtostr,cat,{";"}cat
push(res)
--i
back
check(simb,operator,code,bfprg)
c=1,
__SUB__:
++i,[i:i]get(sf),{simb}eq? do{ ++c, jmp(__SUB__) }
_tabulation(space),{code}cat,{operator}cat,{"= "}cat,{c}xtostr,cat,{";"}cat
push(res)
--i
back
tabulation(space)
{" "}replyby(space)
back
|
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.
| #Amstrad_CPC_Locomotive_BASIC | Amstrad CPC Locomotive BASIC | 10 s$="METHINKS IT IS LIKE A WEASEL"
20 cc=100
30 prop=0.05
40 sl=len(s$)
50 dim c(cc,sl)
60 dim o(sl)
70 dim v(cc)
80 cp = 1
90 start=time
100 for i=1 to sl
110 o(i)=asc(mid$(s$,i,1))
120 if o(i)=32 then o(i)=64
130 next
140 for j=1 to sl:c(1,j)=int(64+27*rnd(1)):next
150 for i=2 to cc
160 for j=1 to sl:c(i,j)=c(cp,j):next
170 next
180 for i=1 to cc
190 for j=1 to sl
200 if rnd(1)>prop then goto 220
210 c(i,j)=int(64+27*rnd(1))
220 next j: next i
230 sc=0:bsi=1
240 for i=1 to cc
250 v(i)=0
260 for j=1 to sl
270 if c(i,j)=o(j) then v(i)=v(i)+1
280 next j
290 if v(i)>sc then sc=v(i):bsi=i
300 next i
310 print sc"@"bsi;:if bsi<10 then print " ";
320 for i=1 to sl:?chr$(c(bsi, i)+(c(bsi, i)=64)*32);:next:?
330 if sc=sl then print "We have a weasel!":? "Time: "(time-start)/300:end
340 cp=bsi
350 goto 150 |
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
| #K | K | {:[x<3;1;_f[x-1]+_f[x-2]]} |
http://rosettacode.org/wiki/Factors_of_an_integer | Factors of an integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Compute the factors of a positive integer.
These factors are the positive integers by which the number being factored can be divided to yield a positive integer result.
(Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty; this task does not require handling of either of these cases).
Note that every prime number has two factors: 1 and itself.
Related tasks
count in factors
prime decomposition
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
sequence: smallest number greater than previous term with exactly n divisors
| #Slate | Slate | n@(Integer traits) primeFactors
[
[| :result |
result nextPut: 1.
n primesDo: [| :prime | result nextPut: prime]] writingAs: {}
]. |
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
| #Smalltalk | Smalltalk | Integer>>factors
| a |
a := OrderedCollection new.
1 to: (self / 2) do: [ :i |
((self \\ i) = 0) ifTrue: [ a add: i ] ].
a add: self.
^a |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #Inform_7 | Inform 7 | HQ9+ is a room.
After reading a command:
interpret the player's command;
reject the player's command.
To interpret (code - indexed text):
let accumulator be 0;
repeat with N running from 1 to the number of characters in code:
let C be character number N in code in upper case;
if C is "H":
say "Hello, world!";
otherwise if C is "Q":
say "[code][line break]";
otherwise if C is "9":
repeat with iteration running from 1 to 99:
let M be 100 - iteration;
say "[M] bottle[s] of beer on the wall[line break]";
say "[M] bottle[s] of beer[line break]";
say "Take one down, pass it around[line break]";
say "[M - 1] bottle[s] of beer on the wall[paragraph break]";
otherwise if C is "+":
increase accumulator by 1. |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #J | J | bob =: ": , ' bottle' , (1 = ]) }. 's of beer'"_
bobw=: bob , ' on the wall'"_
beer=: bobw , ', ' , bob , '; take one down and pass it around, ' , bobw@<: |
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
| #Go | Go | package main
import (
"fmt"
"regexp"
"strings"
)
type testCase struct {
ruleSet, sample, output string
}
func main() {
fmt.Println("validating", len(testSet), "test cases")
var failures bool
for i, tc := range testSet {
if r, ok := interpret(tc.ruleSet, tc.sample); !ok {
fmt.Println("test", i+1, "invalid ruleset")
failures = true
} else if r != tc.output {
fmt.Printf("test %d: got %q, want %q\n", i+1, r, tc.output)
failures = true
}
}
if !failures {
fmt.Println("no failures")
}
}
func interpret(ruleset, input string) (string, bool) {
if rules, ok := parse(ruleset); ok {
return run(rules, input), true
}
return "", false
}
type rule struct {
pat string
rep string
term bool
}
var (
rxSet = regexp.MustCompile(ruleSet)
rxEle = regexp.MustCompile(ruleEle)
ruleSet = `(?m:^(?:` + ruleEle + `)*$)`
ruleEle = `(?:` + comment + `|` + ruleRe + `)\n+`
comment = `#.*`
ruleRe = `(.*)` + ws + `->` + ws + `([.])?(.*)`
ws = `[\t ]+`
)
func parse(rs string) ([]rule, bool) {
if !rxSet.MatchString(rs) {
return nil, false
}
x := rxEle.FindAllStringSubmatchIndex(rs, -1)
var rules []rule
for _, x := range x {
if x[2] > 0 {
rules = append(rules,
rule{pat: rs[x[2]:x[3]], term: x[4] > 0, rep: rs[x[6]:x[7]]})
}
}
return rules, true
}
func run(rules []rule, s string) string {
step1:
for _, r := range rules {
if f := strings.Index(s, r.pat); f >= 0 {
s = s[:f] + r.rep + s[f+len(r.pat):]
if r.term {
return s
}
goto step1
}
}
return s
}
// text all cut and paste from RC task page
var testSet = []testCase{
{`# 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.`,
`I bought a bag of apples from my brother.`,
},
{`# 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.`,
`I bought a bag of apples from T shop.`,
},
{`# 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.`,
`I bought a bag of apples with my money from T shop.`,
},
{`### 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_`,
`11111111111111111111`,
},
{`# 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`,
`00011H1111000`,
},
} |
http://rosettacode.org/wiki/Exceptions/Catch_an_exception_thrown_in_a_nested_call | Exceptions/Catch an exception thrown in a nested call | Show how to create a user-defined exception and show how to catch an exception raised from several nested calls away.
Create two user-defined exceptions, U0 and U1.
Have function foo call function bar twice.
Have function bar call function baz.
Arrange for function baz to raise, or throw exception U0 on its first call, then exception U1 on its second.
Function foo should catch only exception U0, not U1.
Show/describe what happens when the program is run.
| #Go | Go | // Outline for a try/catch-like exception mechanism in Go
//
// As all Go programmers should know, the Go authors are sharply critical of
// the try/catch idiom and consider it bad practice in general.
// See http://golang.org/doc/go_faq.html#exceptions
package main
import (
"fmt"
"runtime"
"strings"
)
// trace is for pretty output for the Rosetta Code task.
// It would have no place in a practical program.
func trace(s string) {
nc := runtime.Callers(2, cs)
f := runtime.FuncForPC(cs[0])
fmt.Print(strings.Repeat(" ", nc-3), f.Name()[5:], ": ", s, "\n")
}
var cs = make([]uintptr, 10)
type exception struct {
name string
handler func()
}
// try implents the try/catch-like exception mechanism. It takes a function
// to be called, and a list of exceptions to catch during the function call.
// Note that for this simple example, f has no parameters. In a practical
// program it might, of course. In this case, the signature of try would
// have to be modified to take these parameters and then supply them to f
// when it calls f.
func try(f func(), exs []exception) {
trace("start")
defer func() {
if pv := recover(); pv != nil {
trace("Panic mode!")
if px, ok := pv.(exception); ok {
for _, ex := range exs {
if ex.name == px.name {
trace("handling exception")
px.handler()
trace("panic over")
return
}
}
}
trace("can't recover this one!")
panic(pv)
}
}()
f()
trace("complete")
}
func main() {
trace("start")
foo()
trace("complete")
}
// u0, u1 declared at package level so they can be accessed by any function.
var u0, u1 exception
// foo. Note that function literals u0, u1 here in the lexical scope
// of foo serve the purpose of catch blocks of other languages.
// Passing u0 to try serves the purpose of the catch condition.
// While try(bar... reads much like the try statement of other languages,
// this try is an ordinary function. foo is passing bar into try,
// not calling it directly.
func foo() {
trace("start")
u0 = exception{"U0", func() { trace("U0 handled") }}
u1 = exception{"U1", func() { trace("U1 handled") }}
try(bar, []exception{u0})
try(bar, []exception{u0})
trace("complete")
}
func bar() {
trace("start")
baz()
trace("complete")
}
var bazCall int
func baz() {
trace("start")
bazCall++
switch bazCall {
case 1:
trace("panicking with execption U0")
panic(u0)
case 2:
trace("panicking with execption U1")
panic(u1)
}
trace("complete")
} |
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
| #DWScript | DWScript | procedure Test;
begin
raise Exception.Create('Sample Exception');
end; |
http://rosettacode.org/wiki/Exceptions | Exceptions | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
This task is to give an example of an exception handling routine
and to "throw" a new exception.
Related task
Exceptions Through Nested Calls
| #D.C3.A9j.C3.A0_Vu | Déjà Vu | stuff-going-wrong:
raise :value-error
try:
stuff-going-wrong
catch value-error:
!print "Whoops!" |
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
| #C.2B.2B | C++ | system("pause"); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.