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_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
#Clojure
Clojure
(.. Runtime getRuntime (exec "cmd /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...
#AntLang
AntLang
factorial:{1 */ 1+range[x]} /Call: factorial[1000]
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...
#Icon_and_Unicon
Icon and Unicon
procedure main() bases := [5,5.] numbers := [0,2,2.,-1,3] every write("expon(",b := !bases,", ",x := !numbers,")=",(expon(b,x) | "failed") \ 1) end   procedure expon(base,power) local op,res   base := numeric(base) | runerror(102,base) power := power = integer(power) | runerr(101,power)   if power = 0 then...
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...
#Nim
Nim
import macros   proc newIfElse(c, t, e: NimNode): NimNode {.compiletime.} = result = newIfStmt((c, t)) result.add(newNimNode(nnkElse).add(e))   macro if2(x, y: bool; z: untyped): untyped = var parts: array[4, NimNode] for i in parts.low .. parts.high: parts[i] = newNimNode(nnkDiscardStmt).add(NimNode(nil)) ...
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...
#OCaml
OCaml
(* Languages with pattern matching ALREADY HAVE THIS! *)   let myfunc pred1 pred2 = match (pred1, pred2) with | (true, true) -> print_endline ("(true, true)"); | (true, false) -> print_endline ("(true, false)"); | (false, true) -> print_endline ("(false, true)"); | (false, false) -> print_endline ("(false, fa...
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) ...
#Ruby
Ruby
1.upto(100) do |n| print "Fizz" if a = (n % 3).zero? print "Buzz" if b = (n % 5).zero? print n unless (a || b) puts end
http://rosettacode.org/wiki/Extensible_prime_generator
Extensible prime generator
Task Write a generator of prime numbers, in order, that will automatically adjust to accommodate the generation of any reasonably high prime. The routine should demonstrably rely on either: Being based on an open-ended counter set to count without upper limit other than system or programming language limits. In thi...
#Pascal
Pascal
http://www.primos.mat.br/Ate100G.html -> 75. de 16639648367 a 16875026921 76. de 16875026963 a 17110593779 77. de 17110593791 a 17346308407 ... my unit: 750000000 16875026921 760000000 17110593779 770000000 17346251243 <----Wrong
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:...
#AppleScript
AppleScript
  set codeString to text returned of (display dialog "Enter BF code:" buttons "OK" default answer "") set inputString to text returned of (display dialog "Enter input string" buttons "OK" default answer "") set codePointer to 1 set loopPosns to {} set tape to {} set tapePointer to 1 set output to {} set inputPointer to...
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....
#APL
APL
evolve←{ ⍺←0.1 target←'METHINKS IT IS LIKE A WEASEL' charset←27↑⎕A fitness←{target+.=⍵} mutate←⍺∘{ (⍺>?(⍴target)/0){ ⍺:(?⍴charset)⊃charset ⍵ }¨⍵ } ⍵{ target≡⎕←⍵:⍵ next←mutate¨⍺/⊂⍵ ⍺∇(⊃⍒fitness¨next)⊃next }charset[?(⍴target)/⍴charset...
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 ...
#Kabap
Kabap
  // Calculate the $n'th Fibonacci number   // Set this to how many in the sequence to generate $n = 10;   // These are what hold the current calculation $a = 0; $b = 1;   // This holds the complete sequence that is generated $sequence = "";   // Prepare a loop $i = 0; :calcnextnumber; $i = $i++;   // Do the calculat...
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 |...
#Standard_ML
Standard ML
fun printIntList ls = ( List.app (fn n => print(Int.toString n ^ " ")) ls; print "\n" );   fun factors n = let fun factors'(n, k) = if k > n then [] else if n mod k = 0 then k :: factors'(n, k+1) else factors'(n, k+1) in factors'(n,1) 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 |...
#Swift
Swift
func factors(n: Int) -> [Int] {   return filter(1...n) { n % $0 == 0 } }
http://rosettacode.org/wiki/Execute_HQ9%2B
Execute HQ9+
Task Implement a   HQ9+   interpreter or compiler.
#Java
Java
function hq9plus(code) { var out = ''; var acc = 0;   for (var i=0; i<code.length; i++) { switch (code.charAt(i)) { case 'H': out += "hello, world\n"; break; case 'Q': out += code + "\n"; break; case '9': for (var j=99; j>1; j--) { out += j + " bottles of beer on the wall, ...
http://rosettacode.org/wiki/Execute_a_Markov_algorithm
Execute a Markov algorithm
Execute a Markov algorithm You are encouraged to solve this task according to the task description, using any language you may know. Task Create an interpreter for a Markov Algorithm. Rules have the syntax: <ruleset> ::= ((<comment> | <rule>) <newline>+)* <comment> ::= # {<any character>} <rule> ::= <pattern> <wh...
#Groovy
Groovy
def markovInterpreterFor = { rules -> def ruleMap = [:] rules.eachLine { line -> (line =~ /\s*(.+)\s->\s([.]?)(.+)\s*/).each { text, key, terminating, value -> if (key.startsWith('#')) { return } ruleMap[key] = [text: value, terminating: terminating] } } [interpre...
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...
#Haskell
Haskell
import Control.Monad.Error import Control.Monad.Trans (lift)   -- Our "user-defined exception" tpe data MyError = U0 | U1 | Other deriving (Eq, Read, Show)   -- Required for any error type instance Error MyError where noMsg = Other strMsg _ = Other   -- Throwing and catching exceptions implies that we are workin...
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...
#Icon_and_Unicon
Icon and Unicon
import Exceptions   class U0 : Exception() method getMessage() return "U0: " || (\message | "unknown") end end   class U1 : Exception() method getMessage() return "U1: " || (\message | "unknown") end end   procedure main() # (Because Exceptions are not built into Unicon, uncaught ...
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
#E
E
def nameOf(arg :int) { if (arg == 43) { return "Bob" } else { throw("Who?") } }   def catching(arg) { try { return ["ok", nameOf(arg)] } catch exceptionObj { return ["notok", exceptionObj] } }
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
#Elena
Elena
class MyException : Exception { constructor new() <= new("MyException raised"); }
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
#CMake
CMake
execute_process(COMMAND ls)
http://rosettacode.org/wiki/Execute_a_system_command
Execute a system command
Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
#COBOL
COBOL
CALL "SYSTEM" USING BY CONTENT "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...
#Apex
Apex
public static long fact(final Integer n) { if (n < 0) { System.debug('No negative numbers'); return 0; } long ans = 1; for (Integer i = 1; i <= n; i++) { ans *= i; } return ans; }
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...
#J
J
exp =: */@:#~   10 exp 3 1000   10 exp 0 1
http://rosettacode.org/wiki/Exponentiation_operator
Exponentiation operator
Most programming languages have a built-in implementation of exponentiation. Task Re-implement integer exponentiation for both   intint   and   floatint   as both a procedure,   and an operator (if your language supports operator definition). If the language supports operator (or procedure) overloading, then an ov...
#Java
Java
public class Exp{ public static void main(String[] args){ System.out.println(pow(2,30)); System.out.println(pow(2.0,30)); //tests System.out.println(pow(2.0,-2)); }   public static double pow(double base, int exp){ if(exp < 0) return 1 / pow(base, -exp); double ans = 1.0; fo...
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...
#PARI.2FGP
PARI/GP
if2(c1,c2,tt,tf,ft,ff)={ if(c1, if(c2,tt,tf) , if(c2,ft,ff) ) };
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...
#Perl
Perl
  #!/usr/bin/perl use warnings; use strict; use v5.10;   =for starters   Syntax:   if2 condition1, condition2, then2 { # both conditions are true } else1 { # only condition1 is true } else2 { # only condition2 is true } orelse { # neither condition is 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) ...
#Ruby_with_RSpec
Ruby with RSpec
  require 'fizzbuzz'   describe 'FizzBuzz' do context 'knows that a number is divisible by' do it '3' do expect(is_divisible_by_three?(3)).to be_true end it '5' do expect(is_divisible_by_five?(5)).to be_true end it '15' do expect(is_divisible_by_fifteen?(15)).to be_true end ...
http://rosettacode.org/wiki/Extensible_prime_generator
Extensible prime generator
Task Write a generator of prime numbers, in order, that will automatically adjust to accommodate the generation of any reasonably high prime. The routine should demonstrably rely on either: Being based on an open-ended counter set to count without upper limit other than system or programming language limits. In thi...
#Perl
Perl
use Math::Prime::Util qw(nth_prime prime_count primes); # Direct solutions. # primes([start],end) returns an array reference with all primes in the range # prime_count([start],end) uses sieving or LMO to return fast prime counts # nth_prime(n) does just that. It runs quite fast for native size inputs. say "First 20: "...
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:...
#Arturo
Arturo
; ; Brainf*ck compiler ; In Arturo ;   Tape: [0] DataPointer: new 0 InstructionPointer: new 0   ; Look for jumps in Code an register them ; in the Jumps table   precomputeJumps: function [][ vstack: new [] jumphash: new #[] instrPointer: 0   while [instrPointer<CodeLength] [ command: get split C...
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....
#AutoHotkey
AutoHotkey
output := "" target := "METHINKS IT IS LIKE A WEASEL" targetLen := StrLen(target) Loop, 26 possibilities_%A_Index% := Chr(A_Index+64) ; A-Z possibilities_27 := " " C := 100   parent := "" Loop, %targetLen% { Random, randomNum, 1, 27 parent .= possibilities_%randomNum% }   Loop, { If (target = parent) Break If ...
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 ...
#Klingphix
Klingphix
:Fibonacci dup 0 less ( ["Invalid argument"] [1 1 rot 2 sub [drop over over add] for] ) if ;   30 Fibonacci pstack print nl   msec print nl "bertlham " input
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 |...
#Tailspin
Tailspin
  [1..351 -> \(when <?(351 mod $ <=0>)> do $! \)] -> !OUT::write  
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 |...
#Tcl
Tcl
proc factors {n} { set factors {} for {set i 1} {$i <= sqrt($n)} {incr i} { if {$n % $i == 0} { lappend factors $i [expr {$n / $i}] } } return [lsort -unique -integer $factors] } puts [factors 64] puts [factors 45] puts [factors 53]
http://rosettacode.org/wiki/Execute_HQ9%2B
Execute HQ9+
Task Implement a   HQ9+   interpreter or compiler.
#JavaScript
JavaScript
function hq9plus(code) { var out = ''; var acc = 0;   for (var i=0; i<code.length; i++) { switch (code.charAt(i)) { case 'H': out += "hello, world\n"; break; case 'Q': out += code + "\n"; break; case '9': for (var j=99; j>1; j--) { out += j + " bottles of beer on the wall, ...
http://rosettacode.org/wiki/Execute_a_Markov_algorithm
Execute a Markov algorithm
Execute a Markov algorithm You are encouraged to solve this task according to the task description, using any language you may know. Task Create an interpreter for a Markov Algorithm. Rules have the syntax: <ruleset> ::= ((<comment> | <rule>) <newline>+)* <comment> ::= # {<any character>} <rule> ::= <pattern> <wh...
#Haskell
Haskell
import Data.List (isPrefixOf) import Data.Maybe (catMaybes) import Control.Monad import Text.ParserCombinators.Parsec import System.IO import System.Environment (getArgs)   main = do args <- getArgs unless (length args == 1) $ fail "Please provide exactly one source file as an argument." let sourcePath ...
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...
#Io
Io
U0 := Exception clone U1 := Exception clone   foo := method( for(i,1,2, try( bar(i) )catch( U0, "foo caught U0" print )pass ) ) bar := method(n, baz(n) ) baz := method(n, if(n == 1,U0,U1) raise("baz with n = #{n}" interpolate) )   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...
#J
J
main=: monad define smoutput 'main' try. foo '' catcht. smoutput 'main caught ',type_jthrow_ end. )   foo=: monad define smoutput ' foo' for_i. 0 1 do. try. bar i catcht. if. type_jthrow_-:'U0' do. smoutput ' foo caught ',type_jthrow_ else. throw. end. end. end. )   bar=: baz [ smoutput bin...
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
#Erlang
Erlang
  -module( exceptions ).   -export( [task/0] ).   task() -> try erlang:throw( new_exception )   catch _:Exception -> io:fwrite( "Catched ~p~n", [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
#Factor
Factor
"Install Linux, Problem Solved" throw   TUPLE: velociraptor ; \ velociraptor new throw
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
#CoffeeScript
CoffeeScript
  { spawn } = require 'child_process'   ls = spawn 'ls'   ls.stdout.on 'data', ( data ) -> console.log "Output: #{ data }"   ls.stderr.on 'data', ( data ) -> console.error "Error: #{ data }"   ls.on 'close', -> console.log "'ls' has finished executing."  
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
#Common_Lisp
Common Lisp
(with-output-to-string (stream) (extensions:run-program "ls" nil :output stream))
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...
#APL
APL
 !6 720
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...
#JavaScript
JavaScript
function pow(base, exp) { if (exp != Math.floor(exp)) throw "exponent must be an integer"; if (exp < 0) return 1 / pow(base, -exp); var ans = 1; while (exp > 0) { ans *= base; exp--; } return ans; }
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...
#jq
jq
# 0^0 => 1 # NOTE: jq converts very large integers to floats. # This implementation uses reduce to avoid deep recursion def power_int(n): if n == 0 then 1 elif . == 0 then 0 elif n < 0 then 1/power_int(-n) elif ((n | floor) == n) then ( (n % 2) | if . == 0 then 1 else -1 end ) as $sign | if (. == ...
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...
#Phix
Phix
switch {condition1,condition2} do case {true,true}: case {true,false}: case {false,true}: case {false,false}: end switch
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...
#PHL
PHL
module stmts;   import phl::lang::io;   /* LinkedList --> Each element contains a condition */ struct @ConditionalChain { field @Boolean cond; field @ConditionalChain next;   @ConditionalChain init(@Boolean cond, @ConditionalChain next) [ this::cond = cond; this::next = next;   return this; ]   /* * If the...
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) ...
#Run_BASIC
Run BASIC
fn main() { for i in 1..=100 { match (i % 3, i % 5) { (0, 0) => println!("fizzbuzz"), (0, _) => println!("fizz"), (_, 0) => println!("buzz"), (_, _) => println!("{}", 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...
#Phix
Phix
with javascript_semantics if platform()!=JS then free_console() end if sequence primes = {2,3,5,7} atom sieved = 10 procedure add_block() integer N = min((sieved-1)*sieved,400000) sequence sieve = repeat(1,N) -- sieve[i] is really i+sieved for i=2 to length(primes) do -- (evens filtered on output) atom...
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:...
#AutoHotkey
AutoHotkey
; AutoFucck ; A AutoIt Brainfuck Interpreter ; by minx ; AutoIt Version: 3.3.8.x   ; Commands: ; - DEC ; + INC ; [ LOOP START ; ] LOOP END ; . Output cell value as ASCII Chr ; , Input a ASCII char (cell value = ASCII code) ; : Ouput cell value as integer ; ; Input a Integer ; _ Output a single whitespace ; / ...
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....
#AWK
AWK
  #!/bin/awk -f function randchar(){ return substr(charset,randint(length(charset)+1),1) } function mutate(gene,rate ,l,newgene){ newgene = "" for (l=1; l < 1+length(gene); l++){ if (rand() < rate) newgene = newgene randchar() else newgene = newgene substr(gene,l,1) } return newgene } function fitness(gene,tar...
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 ...
#Kotlin
Kotlin
enum class Fibonacci { ITERATIVE { override fun get(n: Int): Long = if (n < 2) { n.toLong() } else { var n1 = 0L var n2 = 1L repeat(n) { val sum = n1 + n2 n1 = n2 n2 = sum } n1 ...
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 |...
#UNIX_Shell
UNIX Shell
factor() { r=`echo "sqrt($1)" | bc` # or `echo $1 v p | dc` i=1 while [ $i -lt $r ]; do if [ `expr $1 % $i` -eq 0 ]; then echo $i expr $1 / $i fi i=`expr $i + 1` done | sort -nu }  
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 |...
#Ursa
Ursa
decl int n set n (int args<1>)   decl int i for (set i 1) (< i (+ (/ n 2) 1)) (inc i) if (= (mod n i) 0) out i " " console end if end for out n endl console
http://rosettacode.org/wiki/Execute_HQ9%2B
Execute HQ9+
Task Implement a   HQ9+   interpreter or compiler.
#Julia
Julia
hello() = println("Hello, world!") quine() = println(src) bottles() = for i = 99:-1:1 print("\n$i bottles of beer on the wall\n$i bottles of beer\nTake one down, pass it around\n$(i-1) bottles of beer on the wall\n") end acc = 0 incr() = global acc += 1   const dispatch = Dict( 'h' => hello, 'q' => quine, '9' =>...
http://rosettacode.org/wiki/Execute_HQ9%2B
Execute HQ9+
Task Implement a   HQ9+   interpreter or compiler.
#Kotlin
Kotlin
// version 1.1.3   fun hq9plus(code: String) { var acc = 0 val sb = StringBuilder() for (c in code) { sb.append( when (c) { 'h', 'H' -> "Hello, world!\n" 'q', 'Q' -> code + "\n" '9'-> { val sb2 = StringBuilder() ...
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...
#Icon_and_Unicon
Icon and Unicon
procedure main(A) rules := loadRules(open(A[1],"r")) every write(line := !&input, " -> ",apply(rules, line)) end   record rule(pat, term, rep)   procedure loadRules(f) rules := [] every !f ? if not ="#" then put(rules, rule(1(trim(tab(find("->"))),move(2),tab(many(' \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...
#Java
Java
class U0 extends Exception { } class U1 extends Exception { }   public class ExceptionsTest { public static void foo() throws U1 { for (int i = 0; i <= 1; i++) { try { bar(i); } catch (U0 e) { System.out.println("Function foo caught exception 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...
#JavaScript
JavaScript
function U() {} U.prototype.toString = function(){return this.className;}   function U0() { this.className = arguments.callee.name; } U0.prototype = new U();   function U1() { this.className = arguments.callee.name; } U1.prototype = new U();   function foo() { for (var i = 1; i <= 2; i++) { try {...
http://rosettacode.org/wiki/Exceptions
Exceptions
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops This task is to give an example of an exception handling routine and to "throw" a new exception. Related task   Exceptions Through Nested Calls
#Fancy
Fancy
# define custom exception class # StandardError is base class for all exception classes class MyError : StandardError { def initialize: message { # forward to StdError's initialize method super initialize: message } }   try { # raises/throws a new MyError exception within try-block MyError new: "my mess...
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
#Fantom
Fantom
  // Create a new error class by subclassing sys::Err const class SpecialErr : Err { // you must provide some message about the error // to the parent class, for reporting new make () : super ("special error") {} }   class Main { static Void fn () { throw SpecialErr () }   public static Void main ()...
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
#D
D
  import std.process, std.stdio; //these two alternatives wait for the process to return, and capture the output //each process function returns a Tuple of (int)"status" and (string)"output auto ls_string = executeShell("ls -l"); //takes single string writeln((ls_string.status == 0) ? ls_string.output : "command failed...
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
#dc
dc
! 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...
#AppleScript
AppleScript
on factorial(x) if x < 0 then return 0 set R to 1 repeat while x > 1 set {R, x} to {R * x, x - 1} end repeat return R 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...
#Julia
Julia
  function pow(base::Number, exp::Integer) r = one(base) for i = 1:exp r *= base end return r 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...
#Kotlin
Kotlin
// version 1.0.6   infix fun Int.ipow(exp: Int): Int = when { this == 1 -> 1 this == -1 -> if (exp and 1 == 0) 1 else -1 exp < 0 -> throw IllegalArgumentException("invalid exponent") exp == 0 -> 1 else -> { var ans = 1 var base = this ...
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...
#PicoLisp
PicoLisp
(undef 'if2) # Undefine the built-in 'if2'   (de if2 "P" (if (eval (pop '"P")) (eval ((if (eval (car "P")) cadr caddr) "P")) (if (eval (car "P")) (eval (cadddr "P")) (run (cddddr "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...
#Plain_TeX
Plain TeX
\def\iftwo#1#2#3#4#5\elsefirst#6\elsesecond#7\elseneither#8\owtfi {\if#1#2\if#3#4#5\else#6\fi\else\if#3#4#7\else#8\fi\fi}   \def\both{***both***} \def\first{***first***} \def\second{***second***} \def\neither{***neither***} \message{\iftwo{1}{1}{2}{2}\both\elsefirst\first\elsesecond\second\elseneither\neither\owtfi} \m...
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) ...
#Rust
Rust
fn main() { for i in 1..=100 { match (i % 3, i % 5) { (0, 0) => println!("fizzbuzz"), (0, _) => println!("fizz"), (_, 0) => println!("buzz"), (_, _) => println!("{}", 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...
#PicoLisp
PicoLisp
(de prime? (N Lst) (let S (sqrt N) (for D Lst (T (> D S) T) (T (=0 (% N D)) NIL) ) ) ) (de primeseq (A B) (let (I 1 R) (nth (make (link 2) (while (> A (inc 'I 2)) (and (prime? I (made)) (link I)) ) (setq R (length (made))) ...
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:...
#AutoIt
AutoIt
; AutoFucck ; A AutoIt Brainfuck Interpreter ; by minx ; AutoIt Version: 3.3.8.x   ; Commands: ; - DEC ; + INC ; [ LOOP START ; ] LOOP END ; . Output cell value as ASCII Chr ; , Input a ASCII char (cell value = ASCII code) ; : Ouput cell value as integer ; ; Input a Integer ; _ Output a single whitespace ; / ...
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....
#Batch_File
Batch File
  @echo off setlocal enabledelayedexpansion   set target=M E T H I N K S @ I T @ I S @ L I K E @ A @ W E A S E L set chars=A B C D E F G H I J K L M N O P Q R S T U V W X Y Z @   set tempcount=0 for %%i in (%target%) do ( set /a tempcount+=1 set target!tempcount!=%%i ) call:parent   echo %target% echo -----------...
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 ...
#L.2B.2B
L++
(defn int fib (int n) (return (? (< n 2) n (+ (fib (- n 1)) (fib (- n 2)))))) (main (prn (fib 30)))
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 |...
#Ursala
Ursala
#import std #import nat   factors "n" = (filter not remainder/"n") nrange(1,"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 |...
#VBA
VBA
Function Factors(x As Integer) As String Application.Volatile Dim i As Integer Dim cooresponding_factors As String Factors = 1 corresponding_factors = x For i = 2 To Sqr(x) If x Mod i = 0 Then Factors = Factors & ", " & i If i <> x / i Then corresponding_factors = x / i & ", " & corresponding_factors En...
http://rosettacode.org/wiki/Execute_HQ9%2B
Execute HQ9+
Task Implement a   HQ9+   interpreter or compiler.
#Liberty_BASIC
Liberty BASIC
'Try this hq9+ program - "hq9+HqQ+Qq" Prompt "Please input your hq9+ program."; code$ Print hq9plus$(code$) End   Function hq9plus$(code$) For i = 1 to Len(code$) Select Case Case Upper$(Mid$(code$, i, 1)) = "H" hq9plus$ = hq9plus$ + "Hello, world!" Case Upper$(Mid$(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...
#J
J
require'strings regex'   markovLexer =: verb define rules =. LF cut TAB&=`(,:&' ')}y rules =. a: -.~ (dltb@:{.~ i:&'#')&.> rules rules =. 0 _1 {"1 '\s+->\s+' (rxmatch rxcut ])S:0 rules (,. ] (}.&.>~ ,. ]) ('.'={.)&.>)/ |: rules )     replace =: dyad define 'index patternLength replacement'=. x 'he...
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...
#jq
jq
# n is assumed to be the number of times baz has been previously called: def baz(n): if n==0 then error("U0") elif n==1 then error("U1") else "Goodbye" end;   def bar(n): baz(n);   def foo: (try bar(0) catch if . == "U0" then "We caught U0" else error(.) end), (try bar(1) catch if . == "U0" then "We caught ...
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...
#Julia
Julia
struct U0 <: Exception end struct U1 <: Exception end   function foo() for i in 1:2 try bar() catch err if isa(err, U0) println("catched U0") else rethrow(err) end end end end   function bar() baz() end   function baz() if isdefined(:_called) &...
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...
#Kotlin
Kotlin
// version 1.0.6   class U0 : Throwable("U0 occurred") class U1 : Throwable("U1 occurred")   fun foo() { for (i in 1..2) { try { bar(i) } catch(e: U0) { println(e.message) } } }   fun bar(i: Int) { baz(i) }   fun baz(i: Int) { when (i) { 1 -> throw...
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
#Forth
Forth
: f ( -- ) 1 throw ." f " ; \ will throw a "1" : g ( -- ) 0 throw ." g " ; \ does not throw
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
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Enum ErrorType myError = 1000 End Enum   Sub foo() Err = 1000 ' raise a user-defined error End Sub   Sub callFoo() foo() Dim As Long errNo = Err ' cache Err in case it's reset by a different function Select Case errNo Case 0 ' No error (system defined) Case 1 To 17 ' S...
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
#DBL
DBL
XCALL SPAWN ("ls *.jpg > file.txt")  ;execute command and continue XCALL EXEC ("script.sh")  ;execute script or binary and exit STOP '@/bin/ls *.jpg > file.txt'  ;exit and execute command
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...
#Applesoft_BASIC
Applesoft BASIC
100 N = 4 : GOSUB 200"FACTORIAL 110 PRINT N 120 END   200 N = INT(N) 210 IF N > 1 THEN FOR I = N - 1 TO 2 STEP -1 : N = N * I : NEXT I 220 RETURN
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...
#Lambdatalk
Lambdatalk
  {def ^ {def *^ {lambda {:base :exponent :acc} {if {= :exponent 0} then :acc else {*^ :base {- :exponent 1} {* :acc :base}}}}} {lambda {:base :exponent} {*^ :base :exponent 1}}} -> ^   {^ 2 3} -> 8 {^ {/ 1 2} 3} -> 0.125 // No rational type as primitives {^ 0.5 3} -> 0.125  
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...
#Liberty_BASIC
Liberty BASIC
  print " 11^5 = ", floatPow( 11, 5 ) print " (-11)^5 = ", floatPow( -11, 5 ) print " 11^( -5) = ", floatPow( 11, -5 ) print " 3.1416^3 = ", floatPow( 3.1416, 3 ) print " 0^2 = ", floatPow( 0, 2 ) print " 2^0 = ", floatPow( 2, 0 ) print " -2^0 ...
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...
#PowerShell
PowerShell
  function When-Condition { [CmdletBinding()] Param ( [Parameter(Mandatory=$true, Position=0)] [bool] $Test1,   [Parameter(Mandatory=$true, Position=1)] [bool] $Test2,   [Parameter(Mandatory=$true, Position=2)] [scriptblock] $Both,   ...
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) ...
#Salmon
Salmon
iterate (x; [1...100]) ((x % 15 == 0) ? "FizzBuzz" : ((x % 3 == 0) ? "Fizz" : ((x % 5 == 0) ? "Buzz" : x)))!;
http://rosettacode.org/wiki/Extensible_prime_generator
Extensible prime generator
Task Write a generator of prime numbers, in order, that will automatically adjust to accommodate the generation of any reasonably high prime. The routine should demonstrably rely on either: Being based on an open-ended counter set to count without upper limit other than system or programming language limits. In thi...
#PureBasic
PureBasic
EnableExplicit DisableDebugger Define StartTime.i=ElapsedMilliseconds()   Procedure.b IsPrime(n.i) Define i.i=5 If n<2 : ProcedureReturn #False : EndIf If n%2=0 : ProcedureReturn Bool(n=2) : EndIf If n%3=0 : ProcedureReturn Bool(n=3) : EndIf While i*i<=n If n%i=0 : ProcedureReturn #False : EndIf i+2 ...
http://rosettacode.org/wiki/Execute_Brain****
Execute Brain****
Execute Brain**** is an implementation of Brainf***. Other implementations of Brainf***. RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages. Below are links to each of the versions of RCBF. An implementation need only properly implement the following instructions:...
#AWK
AWK
BEGIN { bf=ARGV[1]; ARGV[1] = "" compile(bf) execute() }   # Strips non-instructions, builds the jump table. function compile(s, i,j,k,f) { c = split(s, src, "") j = 0 for(i = 1; i <= c; i++) { if(src[i] ~ /[\-\+\[\]\<\>,\.]/) code[j++] = src[i]   if(src[i] == "[") { marks[j] = 1 } else if(src[i] ==...
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....
#BBC_BASIC
BBC BASIC
target$ = "METHINKS IT IS LIKE A WEASEL" parent$ = "IU RFSGJABGOLYWF XSMFXNIABKT" mutation_rate = 0.5 children% = 10   DIM child$(children%)   REPEAT bestfitness = 0 bestindex% = 0 FOR index% = 1 TO children% child$(index%) = FNmutate(parent$, mutati...
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 ...
#LabVIEW
LabVIEW
  1) basic version {def fib1 {lambda {:n} {if {< :n 3} then 1 else {+ {fib1 {- :n 1}} {fib1 {- :n 2}}} }}}   {fib1 16} -> 987 (CPU ~ 16ms) {fib1 30} = 832040 (CPU > 12000ms)   2) tail-recursive version {def fib2 {def fib2.r {lambda {:a :b :i} {if {< :i 1} then :a else {fib2.r :b {+ :a :b} ...
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 |...
#Verilog
Verilog
  module main; integer i, n;   initial begin n = 45;   $write(n, " =>"); for(i = 1; i <= n / 2; i = i + 1) if(n % i == 0) $write(i); $display(n); $finish ; end endmodule  
http://rosettacode.org/wiki/Execute_HQ9%2B
Execute HQ9+
Task Implement a   HQ9+   interpreter or compiler.
#Lua
Lua
  function runCode( code ) local acc, lc = 0 for i = 1, #code do lc = code:sub( i, i ):upper() if lc == "Q" then print( lc ) elseif lc == "H" then print( "Hello, World!" ) elseif lc == "+" then acc = acc + 1 elseif lc == "9" then for j = 99, 1, -1 do ...
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...
#Java
Java
import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern;   public class Markov {   public static void main(String[] args) throws IOE...
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...
#langur
langur
val .U0 = h{"msg": "U0"} val .U1 = h{"msg": "U1"}   val .baz = f(.i) throw if(.i==0: .U0; .U1) val .bar = f(.i) .baz(.i)   val .foo = f() { for .i in [0, 1] { .bar(.i) catch if _err["msg"] == .U0["msg"] { writeln "caught .U0 in .foo()" } else { throw } } }...
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...
#Lasso
Lasso
define try(exception) => { local( gb = givenblock, error ) handle => { // Only relay error if it's not the specified exception if(#error) => { if(#error->get(2) == #exception) => { stdoutnl('Handled exception: '+#error->get(2)) else ...
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...
#Lua
Lua
local baz_counter=1 function baz() if baz_counter==1 then baz_counter=baz_counter+1 error("U0",3)--3 sends it down the call stack. elseif baz_counter==2 then error("U1",3)--3 sends it down the call stack. end end   function bar() baz() end   function foo() function callbar() local no_err,resu...
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
#Gambas
Gambas
Public Sub Main() Dim iInteger As Integer   MakeError DivError   iInteger = "2.54"   Catch Print Error.Text   End '______________________ Public Sub DivError()   Print 10 / 0   Catch Print Error.Text   End '______________________ Public Sub MakeError()   Error.Raise("My Error")   Catch Print Error.Text   End
http://rosettacode.org/wiki/Execute_a_system_command
Execute a system command
Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
#DCL
DCL
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
#Delphi
Delphi
program ExecuteSystemCommand;   {$APPTYPE CONSOLE}   uses Windows, ShellApi;   begin ShellExecute(0, nil, 'cmd.exe', ' /c dir', nil, SW_HIDE); end.
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...
#Arendelle
Arendelle
< n > { @n = 0 , ( return , 1 ) , ( return , @n * !factorial( @n - ! ) ) }