task_url stringlengths 30 116 | task_name stringlengths 2 86 | task_description stringlengths 0 14.4k | language_url stringlengths 2 53 | language_name stringlengths 1 52 | code stringlengths 0 61.9k |
|---|---|---|---|---|---|
http://rosettacode.org/wiki/Execute_SNUSP | Execute SNUSP | Execute SNUSP is an implementation of SNUSP.
Other implementations of SNUSP.
RCSNUSP
SNUSP
An implementation need only properly implement the Core SNUSP instructions ('$', '\', '/', '+', '-', '<', '>', ',', '.', '!', and '?'). Modular SNUSP ('#', '@') and Bloated SNUSP (':', ';', '%', and '&') are also allowed, but not... | #Lua | Lua | import strutils
# Requires 5 bytes of data store.
const Hw = r"""
/++++!/===========?\>++.>+.+++++++..+++\
\+++\ | /+>+++++++>/ /++++++++++<<.++>./
$+++/ | \+++++++++>\ \+++++.>.+++.-----\
\==-<<<<+>+++/ /=.>.+>.--------.-/"""
#----------------------------------------------------------------------------------... |
http://rosettacode.org/wiki/Execute_SNUSP | Execute SNUSP | Execute SNUSP is an implementation of SNUSP.
Other implementations of SNUSP.
RCSNUSP
SNUSP
An implementation need only properly implement the Core SNUSP instructions ('$', '\', '/', '+', '-', '<', '>', ',', '.', '!', and '?'). Modular SNUSP ('#', '@') and Bloated SNUSP (':', ';', '%', and '&') are also allowed, but not... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | import strutils
# Requires 5 bytes of data store.
const Hw = r"""
/++++!/===========?\>++.>+.+++++++..+++\
\+++\ | /+>+++++++>/ /++++++++++<<.++>./
$+++/ | \+++++++++>\ \+++++.>.+++.-----\
\==-<<<<+>+++/ /=.>.+>.--------.-/"""
#----------------------------------------------------------------------------------... |
http://rosettacode.org/wiki/Execute_SNUSP | Execute SNUSP | Execute SNUSP is an implementation of SNUSP.
Other implementations of SNUSP.
RCSNUSP
SNUSP
An implementation need only properly implement the Core SNUSP instructions ('$', '\', '/', '+', '-', '<', '>', ',', '.', '!', and '?'). Modular SNUSP ('#', '@') and Bloated SNUSP (':', ';', '%', and '&') are also allowed, but not... | #Nim | Nim | import strutils
# Requires 5 bytes of data store.
const Hw = r"""
/++++!/===========?\>++.>+.+++++++..+++\
\+++\ | /+>+++++++>/ /++++++++++<<.++>./
$+++/ | \+++++++++>\ \+++++.>.+++.-----\
\==-<<<<+>+++/ /=.>.+>.--------.-/"""
#----------------------------------------------------------------------------------... |
http://rosettacode.org/wiki/Execute_SNUSP | Execute SNUSP | Execute SNUSP is an implementation of SNUSP.
Other implementations of SNUSP.
RCSNUSP
SNUSP
An implementation need only properly implement the Core SNUSP instructions ('$', '\', '/', '+', '-', '<', '>', ',', '.', '!', and '?'). Modular SNUSP ('#', '@') and Bloated SNUSP (':', ';', '%', and '&') are also allowed, but not... | #OCaml | OCaml | with javascript_semantics
integer id = 0, ipr = 1, ipc = 1
procedure step()
if and_bits(id,1) == 0 then
ipc += 1 - and_bits(id,2)
else
ipr += 1 - and_bits(id,2)
end if
end procedure
procedure snusp(integer dlen, string s)
sequence ds = repeat(0,dlen) -- data store
integer dp = ... |
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 langua... | #Go | Go | package main
import "fmt"
type F func()
type If2 struct {cond1, cond2 bool}
func (i If2) else1(f F) If2 {
if i.cond1 && !i.cond2 {
f()
}
return i
}
func (i If2) else2(f F) If2 {
if i.cond2 && !i.cond1 {
f()
}
return i
}
func (i If2) else0(f F) If2 {
if !i.cond1 &&... |
http://rosettacode.org/wiki/Exponentiation_order | Exponentiation order | This task will demonstrate the order of exponentiation (xy) when there are multiple exponents.
(Many programming languages, especially those with extended─precision integer arithmetic, usually support one of **, ^, ↑ or some such for exponentiation.)
Task requirements
Show the result of a language's eval... | #REXX | REXX | /*REXX program demonstrates various ways of multiple exponentiations. */
/*┌────────────────────────────────────────────────────────────────────┐
│ The REXX language uses ** for exponentiation. │
│ Also, * * can be used. │
| and even ... |
http://rosettacode.org/wiki/Exponentiation_order | Exponentiation order | This task will demonstrate the order of exponentiation (xy) when there are multiple exponents.
(Many programming languages, especially those with extended─precision integer arithmetic, usually support one of **, ^, ↑ or some such for exponentiation.)
Task requirements
Show the result of a language's eval... | #Ring | Ring |
see "(5^3)^2 =>" + pow(pow(5,3),2) + nl
see "5^(3^2) =>" + pow(5,pow(3,2)) + nl
|
http://rosettacode.org/wiki/Exponentiation_order | Exponentiation order | This task will demonstrate the order of exponentiation (xy) when there are multiple exponents.
(Many programming languages, especially those with extended─precision integer arithmetic, usually support one of **, ^, ↑ or some such for exponentiation.)
Task requirements
Show the result of a language's eval... | #Ruby | Ruby | ar = ["5**3**2", "(5**3)**2", "5**(3**2)", "[5,3,2].inject(:**)"]
ar.each{|exp| puts "#{exp}:\t#{eval exp}"}
|
http://rosettacode.org/wiki/Filter | Filter | Task
Select certain elements from an Array into a new Array in a generic way.
To demonstrate, select all even numbers from an Array.
As an option, give a second solution which filters destructively,
by modifying the original Array rather than creating a new Array.
| #zkl | zkl | T(1,4,9,16,25,36,"37",49,64,81,100, True,self)
.filter(fcn(n){(0).isType(n) and n.isOdd})
//-->L(1,9,25,49,81) |
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)
... | #Raku | Raku | for 1 .. 100 {
when $_ %% (3 & 5) { say 'FizzBuzz'; }
when $_ %% 3 { say 'Fizz'; }
when $_ %% 5 { say 'Buzz'; }
default { .say; }
} |
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 thi... | #Icon_and_Unicon | Icon and Unicon | ![2,3,5,7] | (nc := 11) | (nc +:= |wheel2345) |
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 ... | #Hoon | Hoon | |= n=@ud
=/ a=@ud 0
=/ b=@ud 1
|-
?: =(n 0) a
$(a b, b (add a b), n (dec n)) |
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 |... | #Raku | Raku | sub factors (Int $n) { (1..$n).grep($n %% *) } |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #Common_Lisp | Common Lisp | import std.stdio, std.string;
void main(in string[] args) {
if (args.length != 2 ||
args[1].length != args[1].countchars("hHqQ9+")) {
writeln("Not valid HQ9+ code.");
return;
}
ulong accumulator;
foreach (immutable c; args[1]) {
final switch(c) {
case 'Q',... |
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 rais... | #ALGOL_68 | ALGOL 68 | MODE OBJ = STRUCT(
INT value,
STRUCT(
STRING message,
FLEX[0]STRING args,
PROC(REF OBJ)BOOL u0, u1
) exception
);
PROC on u0 = (REF OBJ self, PROC (REF OBJ) BOOL mended)VOID:
u0 OF exception OF self := mended;
PROC on u1 = (REF OBJ self, PROC (REF OBJ) BOOL mended)VOID:
u1 OF exception OF self... |
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
| #ABAP | ABAP | *&---------------------------------------------------------------------*
*& Report ZEXEC_SYS_CMD
*&
*&---------------------------------------------------------------------*
*&
*&
*&---------------------------------------------------------------------*
REPORT zexec_sys_cmd.
DATA: lv_opsys TYPE syst-o... |
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 iterat... | #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program factorial64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesAR... |
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 ov... | #Chef | Chef | (defn ** [x n] (reduce * (repeat n x))) |
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 ov... | #Clojure | Clojure | (defn ** [x n] (reduce * (repeat n x))) |
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 langua... | #Io | Io | HailStone := Object clone
HailStone sequence := method(n,
if(n < 1, Exception raise("hailstone: expect n >= 1 not #{n}" interpolate))
n = n floor // make sure integer value
stones := list(n)
while (n != 1,
n = if(n isEven, n/2, 3*n + 1)
stones append(n)
)
stones
)
if( ... |
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 langua... | #J | J | hailseq=: -:`(1 3&p.)@.(2&|) ^:(1 ~: ]) ^:a:"0
9!:29]1
9!:27'main 0'
main=:3 :0
smoutput 'Hailstone sequence for the number 27'
smoutput hailseq 27
smoutput ''
smoutput 'Finding number with longest hailstone sequence which is'
smoutput 'less than 100000 (and finding that sequence length):'
smoutput (I.@(= >... |
http://rosettacode.org/wiki/Extreme_floating_point_values | Extreme floating point values | The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity.
The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe ... | #Ruby | Ruby | inf = 1.0 / 0.0 # or Float::INFINITY
nan = 0.0 / 0.0 # or Float::NAN
expression = [
"1.0 / 0.0", "-1.0 / 0.0", "0.0 / 0.0", "- 0.0",
"inf + 1", "5 - inf", "inf * 5", "inf / 5", "inf * 0",
"1.0 / inf", "-1.0 / inf", "inf + inf", "inf - inf",
"inf * inf", "inf / inf", "inf * 0.0", " 0 < inf", "... |
http://rosettacode.org/wiki/Execute_SNUSP | Execute SNUSP | Execute SNUSP is an implementation of SNUSP.
Other implementations of SNUSP.
RCSNUSP
SNUSP
An implementation need only properly implement the Core SNUSP instructions ('$', '\', '/', '+', '-', '<', '>', ',', '.', '!', and '?'). Modular SNUSP ('#', '@') and Bloated SNUSP (':', ';', '%', and '&') are also allowed, but not... | #Perl | Perl | with javascript_semantics
integer id = 0, ipr = 1, ipc = 1
procedure step()
if and_bits(id,1) == 0 then
ipc += 1 - and_bits(id,2)
else
ipr += 1 - and_bits(id,2)
end if
end procedure
procedure snusp(integer dlen, string s)
sequence ds = repeat(0,dlen) -- data store
integer dp = ... |
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 langua... | #Haskell | Haskell | if2 :: Bool -> Bool -> a -> a -> a -> a -> a
if2 p1 p2 e12 e1 e2 e =
if p1 then
if p2 then e12 else e1
else if p2 then e2 else e
main = print $ if2 True False (error "TT") "TF" (error "FT") (error "FF")
|
http://rosettacode.org/wiki/Exponentiation_order | Exponentiation order | This task will demonstrate the order of exponentiation (xy) when there are multiple exponents.
(Many programming languages, especially those with extended─precision integer arithmetic, usually support one of **, ^, ↑ or some such for exponentiation.)
Task requirements
Show the result of a language's eval... | #Rust | Rust | fn main() {
println!("5**3**2 = {:7}", 5u32.pow(3).pow(2));
println!("(5**3)**2 = {:7}", (5u32.pow(3)).pow(2));
println!("5**(3**2) = {:7}", 5u32.pow(3u32.pow(2)));
} |
http://rosettacode.org/wiki/Exponentiation_order | Exponentiation order | This task will demonstrate the order of exponentiation (xy) when there are multiple exponents.
(Many programming languages, especially those with extended─precision integer arithmetic, usually support one of **, ^, ↑ or some such for exponentiation.)
Task requirements
Show the result of a language's eval... | #Scala | Scala | $ include "seed7_05.s7i";
const proc: main is func
begin
writeln("5**3**2 = " <& 5**3**2);
writeln("(5**3)**2 = " <& (5**3)**2);
writeln("5**(3**2) = " <& 5**(3**2));
end func; |
http://rosettacode.org/wiki/Exponentiation_order | Exponentiation order | This task will demonstrate the order of exponentiation (xy) when there are multiple exponents.
(Many programming languages, especially those with extended─precision integer arithmetic, usually support one of **, ^, ↑ or some such for exponentiation.)
Task requirements
Show the result of a language's eval... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
const proc: main is func
begin
writeln("5**3**2 = " <& 5**3**2);
writeln("(5**3)**2 = " <& (5**3)**2);
writeln("5**(3**2) = " <& 5**(3**2));
end func; |
http://rosettacode.org/wiki/Exponentiation_order | Exponentiation order | This task will demonstrate the order of exponentiation (xy) when there are multiple exponents.
(Many programming languages, especially those with extended─precision integer arithmetic, usually support one of **, ^, ↑ or some such for exponentiation.)
Task requirements
Show the result of a language's eval... | #Sidef | Sidef | var a = [
'5**3**2',
'(5**3)**2',
'5**(3**2)',
'5 ** 3 ** 2',
'5 ** 3**2',
'5**3 ** 2',
'[5,3,2]«**»',
]
a.each {|e|
"%-12s == %s\n".printf(e, eval(e))
} |
http://rosettacode.org/wiki/Filter | Filter | Task
Select certain elements from an Array into a new Array in a generic way.
To demonstrate, select all even numbers from an Array.
As an option, give a second solution which filters destructively,
by modifying the original Array rather than creating a new Array.
| #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 LET items=100: LET filtered=0
20 DIM a(items)
30 FOR i=1 TO items
40 LET a(i)=INT (RND*items)
50 NEXT i
60 FOR i=1 TO items
70 IF FN m(a(i),2)=0 THEN LET filtered=filtered+1: LET a(filtered)=a(i)
80 NEXT i
90 DIM b(filtered)
100 FOR i=1 TO filtered
110 LET b(i)=a(i): PRINT b(i);" ";
120 NEXT i
130 DIM a(1): REM To f... |
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)
... | #RapidQ | RapidQ | FOR i=1 TO 100
t$ = IIF(i MOD 3 = 0, "Fizz", "") + IIF(i MOD 5 = 0, "Buzz", "")
PRINT IIF(LEN(t$), t$, i)
NEXT i |
http://rosettacode.org/wiki/Extensible_prime_generator | Extensible prime generator | Task
Write a generator of prime numbers, in order, that will automatically adjust to accommodate the generation of any reasonably high prime.
The routine should demonstrably rely on either:
Being based on an open-ended counter set to count without upper limit other than system or programming language limits. In thi... | #J | J | p:i.20
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71
(#~ >:&100)i.&.(p:inv) 150
101 103 107 109 113 127 131 137 139 149
#(#~ >:&7700)i.&.(p:inv) 8000
30
p:10000-1
104729 |
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 ... | #Hope | Hope | dec f : num -> num;
--- f 0 <= 0;
--- f 1 <= 1;
--- f(n+2) <= f n + f(n+1); |
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 |... | #REALbasic | REALbasic | Function factors(num As UInt64) As UInt64()
'This function accepts an unsigned 64 bit integer as input and returns an array of unsigned 64 bit integers
Dim result() As UInt64
Dim iFactor As UInt64 = 1
While iFactor <= num/2 'Since a factor will never be larger than half of the number
If num Mod iFactor = 0 ... |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #D | D | import std.stdio, std.string;
void main(in string[] args) {
if (args.length != 2 ||
args[1].length != args[1].countchars("hHqQ9+")) {
writeln("Not valid HQ9+ code.");
return;
}
ulong accumulator;
foreach (immutable c; args[1]) {
final switch(c) {
case 'Q',... |
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 rais... | #APL | APL | :Namespace Traps
⍝ Traps (exceptions) are just numbers
⍝ 500-999 are reserved for the user
U0 U1←900 901
⍝ Catch
∇foo;i
:For i :In ⍳2
:Trap U0
bar i
:Else
⎕←'foo caught U0'
:EndTrap
:EndFor
... |
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 rais... | #AutoHotkey | AutoHotkey | global U0 := Exception("First Exception")
global U1 := Exception("Second Exception")
foo()
foo(){
try
bar()
catch e
MsgBox % "An exception was raised: " e.Message
bar()
}
bar(){
baz()
}
baz(){
static calls := 0
if ( ++calls = 1 )
throw U0
else if ( calls = 2 )
throw U1
} |
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
| #11l | 11l | T SillyError
String message
F (message)
.message = message
X.try
X SillyError(‘egg’)
X.catch SillyError se
print(se.message) |
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
| #Ada | Ada | with POSIX.Unsafe_Process_Primitives;
procedure Execute_A_System_Command is
Arguments : POSIX.POSIX_String_List;
begin
POSIX.Append (Arguments, "ls");
POSIX.Unsafe_Process_Primitives.Exec_Search ("ls", Arguments);
end Execute_A_System_Command; |
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
| #Aikido | Aikido |
var lines = system ("ls")
foreach line lines {
println (line)
}
|
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 iterat... | #ABAP | ABAP | form factorial using iv_val type i.
data: lv_res type i value 1.
do iv_val times.
multiply lv_res by sy-index.
enddo.
iv_val = lv_res.
endform. |
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 ov... | #Common_Lisp | Common Lisp | (defun my-expt-do (a b)
(do ((x 1 (* x a))
(y 0 (+ y 1)))
((= y b) x))) |
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 ov... | #D | D | import std.stdio, std.conv;
struct Number(T) {
T x; // base
alias x this;
string toString() const { return text(x); }
Number opBinary(string op)(in int exponent)
const pure nothrow @nogc if (op == "^^") in {
if (exponent < 0)
assert (x != 0, "Division by zero");
} body {
... |
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 langua... | #Java | Java |
import java.util.ArrayList;
import java.util.List;
// task 1
public class HailstoneSequence {
public static void main(String[] args) {
// task 2
int n = 27;
List<Long> sequence27 = hailstoneSequence(n);
System.out.printf("Hailstone sequence for %d has a length of %d:%nhailsto... |
http://rosettacode.org/wiki/Extreme_floating_point_values | Extreme floating point values | The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity.
The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe ... | #Rust | Rust | fn main() {
let inf: f64 = 1. / 0.; // or std::f64::INFINITY
let minus_inf: f64 = -1. / 0.; // or std::f64::NEG_INFINITY
let minus_zero: f64 = -1. / inf; // or -0.0
let nan: f64 = 0. / 0.; // or std::f64::NAN
// or std::f32 for the above
print... |
http://rosettacode.org/wiki/Extreme_floating_point_values | Extreme floating point values | The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity.
The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe ... | #S-lang | S-lang | foreach $1 ([{-0.0}, {_Inf, "1.0/0"}, {-_Inf, "-1.0/0"}, {_NaN}]) {
() = printf("%S", $1[0]);
if (length($1) > 1) () = printf("\t%S\n", eval($1[1]));
else () = printf("\n");
} |
http://rosettacode.org/wiki/Execute_SNUSP | Execute SNUSP | Execute SNUSP is an implementation of SNUSP.
Other implementations of SNUSP.
RCSNUSP
SNUSP
An implementation need only properly implement the Core SNUSP instructions ('$', '\', '/', '+', '-', '<', '>', ',', '.', '!', and '?'). Modular SNUSP ('#', '@') and Bloated SNUSP (':', ';', '%', and '&') are also allowed, but not... | #Phix | Phix | with javascript_semantics
integer id = 0, ipr = 1, ipc = 1
procedure step()
if and_bits(id,1) == 0 then
ipc += 1 - and_bits(id,2)
else
ipr += 1 - and_bits(id,2)
end if
end procedure
procedure snusp(integer dlen, string s)
sequence ds = repeat(0,dlen) -- data store
integer dp = ... |
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 langua... | #Icon_and_Unicon | Icon and Unicon | procedure main(A)
if2 { (A[1] = A[2]), (A[3] = A[4]), # Use PDCO with all three else clauses
write("1: both true"),
write("1: only first true"),
write("1: only second true"),
write("1: neither true")
}
if2 { (A[1] = A[2]), (A[3] = A[4]), # Use same PDCO with ... |
http://rosettacode.org/wiki/Exponentiation_order | Exponentiation order | This task will demonstrate the order of exponentiation (xy) when there are multiple exponents.
(Many programming languages, especially those with extended─precision integer arithmetic, usually support one of **, ^, ↑ or some such for exponentiation.)
Task requirements
Show the result of a language's eval... | #Simula | Simula | OutText("5** 3 **2: "); OutInt(5** 3 **2, 0); Outimage;
OutText("(5**3)**2: "); OutInt((5**3)**2, 0); Outimage;
OutText("5**(3**2): "); OutInt(5**(3**2), 0); Outimage |
http://rosettacode.org/wiki/Exponentiation_order | Exponentiation order | This task will demonstrate the order of exponentiation (xy) when there are multiple exponents.
(Many programming languages, especially those with extended─precision integer arithmetic, usually support one of **, ^, ↑ or some such for exponentiation.)
Task requirements
Show the result of a language's eval... | #Smalltalk | Smalltalk | Transcript show:'5**3**2 => '; showCR: 5**3**2.
Transcript show:'(5**3)**2 => '; showCR: (5**3)**2.
Transcript show:'5**(3**2) => '; showCR: 5**(3**2). |
http://rosettacode.org/wiki/Exponentiation_order | Exponentiation order | This task will demonstrate the order of exponentiation (xy) when there are multiple exponents.
(Many programming languages, especially those with extended─precision integer arithmetic, usually support one of **, ^, ↑ or some such for exponentiation.)
Task requirements
Show the result of a language's eval... | #Stata | Stata | . di (5^3^2)
15625
. di ((5^3)^2)
15625
. di (5^(3^2))
1953125 |
http://rosettacode.org/wiki/Exponentiation_order | Exponentiation order | This task will demonstrate the order of exponentiation (xy) when there are multiple exponents.
(Many programming languages, especially those with extended─precision integer arithmetic, usually support one of **, ^, ↑ or some such for exponentiation.)
Task requirements
Show the result of a language's eval... | #Swift | Swift | precedencegroup ExponentiationPrecedence {
associativity: left
higherThan: MultiplicationPrecedence
}
infix operator ** : ExponentiationPrecedence
@inlinable
public func ** <T: BinaryInteger>(lhs: T, rhs: T) -> T {
guard lhs != 0 else {
return 1
}
var x = lhs
var n = rhs
var y = T(1)
while n... |
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)
... | #Rascal | Rascal | import IO;
public void fizzbuzz() {
for(int n <- [1 .. 100]){
fb = ((n % 3 == 0) ? "Fizz" : "") + ((n % 5 == 0) ? "Buzz" : "");
println((fb == "") ?"<n>" : fb);
}
} |
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 thi... | #Java | Java | import java.util.*;
public class PrimeGenerator {
private int limit_;
private int index_ = 0;
private int increment_;
private int count_ = 0;
private List<Integer> primes_ = new ArrayList<>();
private BitSet sieve_ = new BitSet();
private int sieveLimit_ = 0;
public PrimeGenerator(in... |
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 ... | #Hy | Hy | (defn fib [n]
(if (< n 2)
n
(+ (fib (- n 2)) (fib (- n 1))))) |
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 |... | #Red | Red | Red []
factors: function [n [integer!]] [
n: absolute n
collect [
repeat i (sq: sqrt n) - 1 [
if n % i = 0 [
keep i
keep n / i
]
]
if sq = sq: to-integer sq [keep sq]
]
]
foreach num [
24
-64 ; negative
64 ... |
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 |... | #Relation | Relation |
program factors(num)
relation fact
insert 1
set i = 2
while i < num / 2
if num / i = floor(num/i)
insert i
end if
set i = i + 1
end while
insert num
print
end program
|
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #Delphi | Delphi |
uses
System.SysUtils;
procedure runCode(code: string);
var
c_len, i, bottles: Integer;
accumulator: Cardinal;
begin
c_len := Length(code);
accumulator := 0;
for i := 1 to c_len do
begin
case code[i] of
'Q':
writeln(code);
'H':
Writeln('Hello, world!');
'9':
... |
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> <wh... | #11l | 11l | T Rule
String pattern
String replacement
Bool terminating
F (pattern, replacement, terminating)
.pattern = pattern
.replacement = replacement
.terminating = terminating
F parse(rules)
[Rule] result
L(line) rules.split("\n")
I line.starts_with(‘#’)
L.continue
I ... |
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 rais... | #BBC_BASIC | BBC BASIC | REM Allocate error numbers:
U0& = 123
U1& = 124
PROCfoo
END
DEF PROCfoo
ON ERROR LOCAL IF ERR = U0& THEN PRINT "Exception U0 caught in foo" ELSE \
\ RESTORE ERROR : ERROR ERR, REPORT$
PROCbar
PROCbar
ENDPROC
DEF PROCbar
PRO... |
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 rais... | #C | C | #include <stdio.h>
#include <stdlib.h>
typedef struct exception {
int extype;
char what[128];
} exception;
typedef struct exception_ctx {
exception * exs;
int size;
int pos;
} exception_ctx;
exception_ctx * Create_Ex_Ctx(int length) {
const int safety = 8; // alignm... |
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
| #8086_Assembly | 8086 Assembly | ;syscall for creating a new file.
mov dx,offset filename
mov cx,0
mov ah,5Bh
int 21h
;if error occurs, will return carry set and error code in ax
;Error code 03h = path not found
;Error code 04h = Too many open files
;Error code 05h = Access denied
;Error code 50h = File already exists
jnc noError ... |
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
| #Ada | Ada | Foo_Error : 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
| #Aime | Aime | sshell ss;
ss.argv.insert("ls");
o_(ss.link);
|
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
| #ALGOL_68 | ALGOL 68 | system("ls") |
http://rosettacode.org/wiki/Factorial | Factorial | Definitions
The factorial of 0 (zero) is defined as being 1 (unity).
The Factorial Function of a positive integer, n, is defined as the product of the sequence:
n, n-1, n-2, ... 1
Task
Write a function to return the factorial of a number.
Solutions can be iterat... | #Action.21 | Action! | CARD FUNC Factorial(INT n BYTE POINTER err)
CARD i,res
IF n<0 THEN
err^=1 RETURN (0)
ELSEIF n>8 THEN
err^=2 RETURN (0)
FI
res=1
FOR i=2 TO n
DO
res=res*i
OD
err^=0
RETURN (res)
PROC Main()
INT i,f
BYTE err
FOR i=-2 TO 10
DO
f=Factorial(i,@err)
IF err=0 THEN
... |
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 ov... | #Delphi | Delphi |
program Exponentiation_operator;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
type
TDouble = record
Value: Double;
class operator Implicit(a: TDouble): Double;
class operator Implicit(a: Double): TDouble;
class operator Implicit(a: TDouble): string;
class operator LogicalXor(a: TDouble; b: I... |
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 langua... | #Julia | Julia |
############### in file hailstone.jl ###############
module Hailstone
function hailstone(n)
ret = [n]
while n > 1
if n & 1 > 0
n = 3n + 1
else
n = Int(n//2)
end
append!(ret, n)
end
return ret
end
export hailstone
end
if PROGRAM_FILE == "... |
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 langua... | #Limbo | Limbo | implement Execlib;
include "sys.m"; sys: Sys;
include "draw.m";
Execlib: module {
init: fn(ctxt: ref Draw->Context, args: list of string);
hailstone: fn(i: big): list of big;
};
init(nil: ref Draw->Context, nil: list of string)
{
sys = load Sys Sys->PATH;
seq := hailstone(big 27);
l := len seq;
sys->pri... |
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 langua... | #Lua | Lua | #!/usr/bin/env luajit
bit32=bit32 or bit
local lib={
hailstone=function(n)
local seq={n}
while n>1 do
n=bit32.band(n,1)==1 and 3*n+1 or n/2
seq[#seq+1]=n
end
return seq
end
}
if arg[0] and arg[0]:match("hailstone.lua") then
local function printf(fmt, ...) io.write(string.format(fmt, ...)) end
local... |
http://rosettacode.org/wiki/Extreme_floating_point_values | Extreme floating point values | The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity.
The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe ... | #Scala | Scala | object ExtremeFloatingPoint extends App {
val negInf = -1.0 / 0.0 //also Double.NegativeInfinity
val inf = 1.0 / 0.0 // //also Double.PositiveInfinity
val nan = 0.0 / 0.0 // //also Double.NaN
val negZero = -2.0 / inf
println("Value: Result: Infinity? Whole?")
println(f"Negative inf: ${negIn... |
http://rosettacode.org/wiki/Extreme_floating_point_values | Extreme floating point values | The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity.
The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe ... | #Scheme | Scheme | (define infinity (/ 1.0 0.0))
(define minus-infinity (- infinity))
(define zero 0.0)
(define minus-zero (- zero))
(define not-a-number (/ 0.0 0.0))
(equal? (list infinity minus-infinity zero minus-zero not-a-number)
(list +inf.0 -inf.0 0.0 -0.0 +nan.0))
; #t
|
http://rosettacode.org/wiki/Execute_SNUSP | Execute SNUSP | Execute SNUSP is an implementation of SNUSP.
Other implementations of SNUSP.
RCSNUSP
SNUSP
An implementation need only properly implement the Core SNUSP instructions ('$', '\', '/', '+', '-', '<', '>', ',', '.', '!', and '?'). Modular SNUSP ('#', '@') and Bloated SNUSP (':', ';', '%', and '&') are also allowed, but not... | #PicoLisp | PicoLisp | #!/usr/bin/env python3
HW = r'''
/++++!/===========?\>++.>+.+++++++..+++\
\+++\ | /+>+++++++>/ /++++++++++<<.++>./
$+++/ | \+++++++++>\ \+++++.>.+++.-----\
\==-<<<<+>+++/ /=.>.+>.--------.-/'''
def snusp(store, code):
ds = bytearray(store) # data store
dp = 0 # data pointer
cs = c... |
http://rosettacode.org/wiki/Execute_SNUSP | Execute SNUSP | Execute SNUSP is an implementation of SNUSP.
Other implementations of SNUSP.
RCSNUSP
SNUSP
An implementation need only properly implement the Core SNUSP instructions ('$', '\', '/', '+', '-', '<', '>', ',', '.', '!', and '?'). Modular SNUSP ('#', '@') and Bloated SNUSP (':', ';', '%', and '&') are also allowed, but not... | #Python | Python | #!/usr/bin/env python3
HW = r'''
/++++!/===========?\>++.>+.+++++++..+++\
\+++\ | /+>+++++++>/ /++++++++++<<.++>./
$+++/ | \+++++++++>\ \+++++.>.+++.-----\
\==-<<<<+>+++/ /=.>.+>.--------.-/'''
def snusp(store, code):
ds = bytearray(store) # data store
dp = 0 # data pointer
cs = c... |
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 langua... | #Idris | Idris | if2 : Bool -> Bool -> Lazy a -> Lazy a -> Lazy a -> Lazy a -> a
if2 True True v _ _ _ = v
if2 True False _ v _ _ = v
if2 False True _ _ v _ = v
if2 _ _ _ _ _ v = v |
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 langua... | #Inform_7 | Inform 7 | To if2 (c1 - condition) and-or (c2 - condition) begin -- end: (- switch (({c1})*2 + ({c2})) { 3: do -).
To else1 -- in if2: (- } until (1); 2: do { -).
To else2 -- in if2: (- } until (1); 1: do { -).
To else0 -- in if2: (- } until (1); 0: -). |
http://rosettacode.org/wiki/Exponentiation_order | Exponentiation order | This task will demonstrate the order of exponentiation (xy) when there are multiple exponents.
(Many programming languages, especially those with extended─precision integer arithmetic, usually support one of **, ^, ↑ or some such for exponentiation.)
Task requirements
Show the result of a language's eval... | #Tcl | Tcl | foreach expression {5**3**2 (5**3)**2 5**(3**2)} {
puts "${expression}:\t[expr $expression]"
} |
http://rosettacode.org/wiki/Exponentiation_order | Exponentiation order | This task will demonstrate the order of exponentiation (xy) when there are multiple exponents.
(Many programming languages, especially those with extended─precision integer arithmetic, usually support one of **, ^, ↑ or some such for exponentiation.)
Task requirements
Show the result of a language's eval... | #VBA | VBA | Public Sub exp()
Debug.Print "5^3^2", 5 ^ 3 ^ 2
Debug.Print "(5^3)^2", (5 ^ 3) ^ 2
Debug.Print "5^(3^2)", 5 ^ (3 ^ 2)
End Sub |
http://rosettacode.org/wiki/Exponentiation_order | Exponentiation order | This task will demonstrate the order of exponentiation (xy) when there are multiple exponents.
(Many programming languages, especially those with extended─precision integer arithmetic, usually support one of **, ^, ↑ or some such for exponentiation.)
Task requirements
Show the result of a language's eval... | #VBScript | VBScript |
WScript.StdOut.WriteLine "5^3^2 => " & 5^3^2
WScript.StdOut.WriteLine "(5^3)^2 => " & (5^3)^2
WScript.StdOut.WriteLine "5^(3^2) => " & 5^(3^2)
|
http://rosettacode.org/wiki/Exponentiation_order | Exponentiation order | This task will demonstrate the order of exponentiation (xy) when there are multiple exponents.
(Many programming languages, especially those with extended─precision integer arithmetic, usually support one of **, ^, ↑ or some such for exponentiation.)
Task requirements
Show the result of a language's eval... | #Verbexx | Verbexx | // Exponentiation order example:
@SAY "5**3**2 = " ( 5**3**2 );
@SAY "(5**3)**2 = " ( (5**3)**2 );
@SAY "5**(3**2) = " ( 5**(3**2) );
/] Output:
5**3**2 = 1953125
(5**3)**2 = 15625
5**(3**2) = 1953125 |
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)
... | #Raven | Raven | 100 each 1 + as n
''
n 3 mod 0 = if 'Fizz' cat
n 5 mod 0 = if 'Buzz' cat
dup empty if drop n
say |
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 thi... | #JavaScript | JavaScript | function primeGenerator(num, showPrimes) {
var i,
arr = [];
function isPrime(num) {
// try primes <= 16
if (num <= 16) return (
num == 2 || num == 3 || num == 5 || num == 7 || num == 11 || num == 13
);
// cull multiples of 2, 3, 5 or 7
if (num % 2 == 0 || num % 3 == 0 || num % 5 ==... |
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 ... | #Icon_and_Unicon | Icon and Unicon | procedure main(args)
write(fib(integer(!args) | 1000)
end
procedure fib(n)
static fCache
initial {
fCache := table()
fCache[0] := 0
fCache[1] := 1
}
/fCache[n] := fib(n-1) + fib(n-2)
return fCache[n]
end |
http://rosettacode.org/wiki/Factors_of_an_integer | Factors of an integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |... | #REXX | REXX | /*REXX program displays divisors of any [negative/zero/positive] integer or a range.*/
parse arg LO HI inc . /*obtain the optional args*/
HI= word(HI LO 20, 1); LO= word(LO 1,1); inc= word(inc 1,1) /*define the range options*/
w= length(HI) + 2; numeric digits max(9, w-2... |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #DWScript | DWScript | procedure RunCode(code : String);
var
i : Integer;
accum, bottles : Integer;
begin
for i:=1 to Length(code) do begin
case code[i] of
'Q', 'q' : PrintLn(code);
'H', 'h' : PrintLn('Hello, world!');
'9' : begin
bottles:=99;
while bottles>1 do begin
... |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #Dyalect | Dyalect | func eval(code) {
var accumulator = 0
var opcodes = (
"h": () => print("Hello, World!"),
"q": () => print(code),
"9": () => {
var quantity = 99
while quantity > 1 {
print("\(quantity) bottles of beer on the wall, \(quantity) bottles of ... |
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> <wh... | #Ada | Ada | with Ada.Strings.Unbounded;
package Markov is
use Ada.Strings.Unbounded;
type Ruleset (Length : Natural) is private;
type String_Array is array (Positive range <>) of Unbounded_String;
function Parse (S : String_Array) return Ruleset;
function Apply (R : Ruleset; S : String) return String;
private
t... |
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 rais... | #C.23 | C# | using System; //Used for Exception and Console classes
class Exceptions
{
class U0 : Exception { }
class U1 : Exception { }
static int i;
static void foo()
{
for (i = 0; i < 2; i++)
try
{
bar();
}
catch (U0) {
Console.WriteLine("U0 Caught");
}
}
static voi... |
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 rais... | #C.2B.2B | C++ | #include <iostream>
class U0 {};
class U1 {};
void baz(int i)
{
if (!i) throw U0();
else throw U1();
}
void bar(int i) { baz(i); }
void foo()
{
for (int i = 0; i < 2; i++)
{
try {
bar(i);
} catch(U0 e) {
std::cout<< "Exception U0 caught\n";
}
}
}
int ma... |
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
| #Aikido | Aikido |
try {
var lines = readfile ("input.txt")
process (lines)
} catch (e) {
do_somthing(e)
}
|
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
| #Aime | Aime | void
throwing(void)
{
o_text("throwing...\n");
error("now!");
}
void
catching(void)
{
o_text("ready to catch\n");
if (trap(throwing)) {
o_text("caught!\n");
} else {
# nothing was thrown
}
}
integer
main(void)
{
catching();
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
| #Amazing_Hopper | Amazing Hopper |
#!/usr/bin/hopper
#include <hopper.h>
main:
/* execute "ls -lstar" with no result return (only displayed) */
{"ls -lstar"},execv
/* this form does not allow composition of the line with variables.
Save result in the variable "s", and then display it */
s=`ls -l | awk '{if($2=="2")print $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
| #APL | APL |
h ← ⎕fio['fork_daemon'] '/bin/ls /var'
backups games lib lock mail run tmp
cache gemini local log opt spool
⎕fio['fclose'] h
0
|
http://rosettacode.org/wiki/Factorial | Factorial | Definitions
The factorial of 0 (zero) is defined as being 1 (unity).
The Factorial Function of a positive integer, n, is defined as the product of the sequence:
n, n-1, n-2, ... 1
Task
Write a function to return the factorial of a number.
Solutions can be iterat... | #ActionScript | ActionScript | public static function factorial(n:int):int
{
if (n < 0)
return 0;
var fact:int = 1;
for (var i:int = 1; i <= n; i++)
fact *= i;
return fact;
} |
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 ov... | #E | E | def power(base, exponent :int) {
var r := base
if (exponent < 0) {
for _ in exponent..0 { r /= base }
} else if (exponent <=> 0) {
return 1
} else {
for _ in 2..exponent { r *= base }
}
return r
} |
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 ov... | #EchoLisp | EchoLisp |
;; this exponentiation function handles integer, rational or float x.
;; n is a positive or negative integer.
(define (** x n) (cond
((zero? n) 1)
((< n 0) (/ (** x (- n)))) ;; x**-n = 1 / x**n
((= n 1) x)
((= n 0) 1)
((odd? n) (* x (** x (1- n)))) ;; x**(2p+1) = x * x**2p
(else (let ((m... |
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 langua... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | hailstone[1] = {1};
hailstone[n_] :=
hailstone[n] = Prepend[hailstone[If[EvenQ[n], n/2, 3 n + 1]], n];
If[$ScriptCommandLine[[1]] == $Input,
val = hailstone[27];
Print["hailstone(27) starts with ", val[[;; 4]], ", ends with ",
val[[-4 ;;]], ", and has length ", Length[val], "."];
val = MaximalBy[Range[9999... |
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 langua... | #Nanoquery | Nanoquery | def hailstone(n)
seq = list()
while (n > 1)
append seq n
if (n % 2)=0
n = int(n / 2)
else
n = int((3 * n) + 1)
end
end
append seq n
return seq
end
if main
h = hailstone(27)
println "hailstone(27)"
println "total elements: " + len(hailstone(27))
print h[0] + ", " + h[1] + ", " + h[2] + ", "... |
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 langua... | #NetRexx | NetRexx | $ jar cvfe RHailstoneSequence.jar RHailstoneSequence RHailstoneSequence.class
added manifest
adding: RHailstoneSequence.class(in = 2921) (out= 1567)(deflated 46%) |
http://rosettacode.org/wiki/Extreme_floating_point_values | Extreme floating point values | The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity.
The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe ... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "float.s7i";
const proc: main is func
begin
writeln("positive infinity: " <& Infinity);
writeln("negative infinity: " <& -Infinity);
writeln("negative zero: " <& -0.0);
writeln("not a number: " <& NaN);
# some arithmetic
writeln("+Infinity + 2.0 = " <&... |
http://rosettacode.org/wiki/Extreme_floating_point_values | Extreme floating point values | The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity.
The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe ... | #Sidef | Sidef | var inf = 1/0 # same as: Inf
var nan = 0/0 # same as: NaN
var exprs = [
"1.0 / 0.0", "-1.0 / 0.0", "0.0 / 0.0", "- 0.0",
"inf + 1", "5 - inf", "inf * 5", "inf / 5", "inf * 0",
"1.0 / inf", "-1.0 / inf", "inf + inf", "inf - inf",
"inf * inf", "inf / inf", "inf * 0.0", " 0 < inf", "inf == inf",
"nan + 1... |
Subsets and Splits
Rosetta Code COBOL Python Hard Tasks
Identifies and retrieves challenging tasks that exist in both COBOL and Python, revealing cross-language programming patterns and difficulty levels for comparative analysis.
Rosetta Code Task Comparisons
Identifies tasks common to both COBOL and Python languages that are described as having difficulty levels, revealing cross-language task similarities and providing useful comparative programming examples.
SQL Code Examples from Training Data
Retrieves raw SQL code examples for the SQL language, which is basic data retrieval without meaningful analysis or patterns.
SQL Code Examples from Training Data
Retrieves raw SQL code examples for the SQL language, which is basic filtering that shows what data looks like but doesn't provide meaningful analysis or patterns.
Select Specific Languages Codes
Retrieves specific programming language names and codes from training data, providing basic filtering but limited analytical value beyond identifying these particular languages.