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 thi... | #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 fi... |
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:... | #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 ; Ad... |
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.... | #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... |
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 ... | #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 |... | #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)
}
whe... |
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)
}
whe... |
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... | #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$s2a... |
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... | #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 :access... |
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... | #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) →
"... |
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... | #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();
... |
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 iterat... | #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 ov... | #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 (... |
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... | #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... |
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... | #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 [... |
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... | #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 {
... |
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... | #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'... |
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)
... | #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' ... |
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... | #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
... |
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:... | #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... |
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.... | #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 Char... |
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 ... | #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 |... | #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;
whil... |
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... | #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];
Mem... |
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... | #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 slZi... |
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... | #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... |
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... | #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()
}
els... |
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 iterat... | #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 ;
... |
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... | #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 Doub... |
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... | #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 Hailst... |
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... | #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)} [...] ... |
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... | #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 langua... | #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"... |
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)
... | #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 thi... | #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:... | #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... |
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.... | #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;
int... |
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 ... | #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 |... | #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;... |
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 |... | #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;
whil... |
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... | #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 sta... |
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... | #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))... |
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... | #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 b... |
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... | #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 'unexpecte... |
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
}
}
/// ... |
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 iterat... | #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 ov... | #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... |
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... | #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 {
... |
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... | #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 $h2... |
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... | #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("F... |
http://rosettacode.org/wiki/Extend_your_language | Extend your language | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. by using macros), other langua... | #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 non... |
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... | #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) {$bo... |
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)
... | #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"
* "... |
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... | #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[Prime... |
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:... | #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 ... |
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.... | #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 = "ABCDEFGHIJKLMNOPQRSTU... |
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 ... | #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 |... | #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... |
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... | #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|_... |
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... | #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 } =
[... |
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... | #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 ()
{
... |
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... | #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 = ... |
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 iterat... | #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 ov... | #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 ov... | #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 langua... | #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, ... |
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... | #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... |
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)
... | #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 noth... |
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... | #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:... | #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] ... |
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.... | #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)... |
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 ... | #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 |... | #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 |... | #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, wor... |
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> <wh... | #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 {
... |
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... | #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"
)
... |
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
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.