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/9_billion_names_of_God_the_integer
9 billion names of God the integer
This task is a variation of the short story by Arthur C. Clarke. (Solvers should be aware of the consequences of completing this task.) In detail, to specify what is meant by a   “name”: The integer 1 has 1 name     “1”. The integer 2 has 2 names   “1+1”,   and   “2”. The integer 3 has 3 names   “1+1+1”,   “2+1”,   ...
#Red
Red
  Red []   context [ sum-part: function [nums [block!] count [integer!]][ out: 0.0 loop count [ out: out + nums/1 if empty? nums: next nums [break] ] out ] nums: make map! [1 [1] 2 [1 1]] sums: make map! [1 1 2 2] set 'names function [row /sho...
http://rosettacode.org/wiki/A%2BB
A+B
A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separated by space(s): ( − 1000 ≤...
#BlooP
BlooP
  DEFINE PROCEDURE ''ADD'' [A, B]: BLOCK 0: BEGIN OUTPUT <= A + B; BLOCK 0: END.  
http://rosettacode.org/wiki/Ackermann_function
Ackermann function
The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree. The Ackermann function is usually defined as follows: A ( m , n ) = { n + 1 if  m = 0 A ( m ...
#SPAD
SPAD
  NNI ==> NonNegativeInteger   A:(NNI,NNI) -> NNI   A(m,n) == m=0 => n+1 m>0 and n=0 => A(m-1,1) m>0 and n>0 => A(m-1,A(m,n-1))   -- Example matrix [[A(i,j) for i in 0..3] for j in 0..3]  
http://rosettacode.org/wiki/ABC_problem
ABC problem
ABC problem You are encouraged to solve this task according to the task description, using any language you may know. You are given a collection of ABC blocks   (maybe like the ones you had when you were a kid). There are twenty blocks with two letters on each block. A complete alphabet is guaranteed amongst all sid...
#Dyalect
Dyalect
func blockable(str) { var blocks = [ "BO", "XK", "DQ", "CP", "NA", "GT", "RE", "TG", "QD", "FS", "JW", "HU", "VI", "AN", "OB", "ER", "FS", "LY", "PC", "ZM" ]   var strUp = str.Upper() var fin = ""   for c in strUp { for j in blocks.Indices() { if blocks[j].StartsWith(...
http://rosettacode.org/wiki/100_prisoners
100 prisoners
The Problem 100 prisoners are individually numbered 1 to 100 A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside. Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start. Prisoners start outside the room They can decid...
#BASIC256
BASIC256
  O = 50 N = 2*O iterations = 10000   REM From the numbers 0 to N-1 inclusive, pick O of them. function shuffle(N, O) dim array(N) for i = 0 to N-1 array[i] = i next i for i = 0 to O-1 swapindex = i + rand*(N-i) swapvalue = array[swapindex] array[swapindex] = array[i] array[i] = swapvalue next i return ...
http://rosettacode.org/wiki/Abundant_odd_numbers
Abundant odd numbers
An Abundant number is a number n for which the   sum of divisors   σ(n) > 2n, or,   equivalently,   the   sum of proper divisors   (or aliquot sum)       s(n) > n. E.G. 12   is abundant, it has the proper divisors     1,2,3,4 & 6     which sum to   16   ( > 12 or n);        or alternately,   has the sigma sum of ...
#R
R
# Abundant Odd Numbers   find_div_sum <- function(x){ # Finds sigma: the sum of the divisors (not including the number itself) of an odd number if (x < 16) return(0) root <- sqrt(x) vec <- as.vector(1) for (i in seq.int(3, root - 1, by = 2)){ if(x %% i == 0){ vec <- c(vec, i, x/i) } } if (ro...
http://rosettacode.org/wiki/21_game
21 game
21 game You are encouraged to solve this task according to the task description, using any language you may know. 21 is a two player game, the game is played by choosing a number (1, 2, or 3) to be added to the running total. The game is won by the player whose chosen number causes the running total to reach exactly ...
#Julia
Julia
  function trytowin(n) if 21 - n < 4 println("Computer chooses $(21 - n) and wins. GG!") exit(0) end end   function choosewisely(n) trytowin(n) targets = [1, 5, 9, 13, 17, 21] pos = findfirst(x -> x > n, targets) bestmove = targets[pos] - n if bestmove > 3 println("Lo...
http://rosettacode.org/wiki/24_game/Solve
24 game/Solve
task Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the 24 game. Show examples of solutions generated by the program. Related task   Arithmetic Evaluator
#CoffeeScript
CoffeeScript
  # This program tries to find some way to turn four digits into an arithmetic # expression that adds up to 24. # # Example solution for 5, 7, 8, 8: # (((8 + 7) * 8) / 5)     solve_24_game = (digits...) -> # Create an array of objects for our helper functions arr = for digit in digits { val: digit ...
http://rosettacode.org/wiki/4-rings_or_4-squares_puzzle
4-rings or 4-squares puzzle
4-rings or 4-squares puzzle You are encouraged to solve this task according to the task description, using any language you may know. Task Replace       a, b, c, d, e, f,   and   g       with the decimal digits   LOW   ───►   HIGH such that the sum of the letters inside of each of the four large squares add up to t...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
{low, high} = {1, 7}; SolveValues[{a + b == b + c + d == d + e + f == f + g, low <= a <= high, low <= b <= high, low <= c <= high, low <= d <= high, low <= e <= high, low <= f <= high, low <= g <= high, a != b != c != d != e != f != g}, {a, b, c, d, e, f, g}, Integers]   {low, high} = {3, 9}; SolveValues[{a + ...
http://rosettacode.org/wiki/99_bottles_of_beer
99 bottles of beer
Task Display the complete lyrics for the song:     99 Bottles of Beer on the Wall. The beer song The lyrics follow this form: 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of beer on the wall 98 bottles of beer Take one dow...
#Action.21
Action!
PROC Bottles(BYTE i) IF i=0 THEN Print("No more") ELSE PrintB(i) FI Print(" bottle") IF i#1 THEN Print("s") FI RETURN   PROC Main() BYTE i=[99]   WHILE i>0 DO Bottles(i) PrintE(" of beer on the wall,") Bottles(i) PrintE(" of beer,") Print("Take ") IF i>1 THEN Prin...
http://rosettacode.org/wiki/24_game
24 game
The 24 Game tests one's mental arithmetic. Task Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed. The program should prompt for the player to enter an arithmetic expression using just those, and all of those four digits, used exactly once each. T...
#C.23
C#
#include <random> #include <iostream> #include <stack> #include <set> #include <string> #include <functional> using namespace std;   class RPNParse { public: stack<double> stk; multiset<int> digits;   void op(function<double(double,double)> f) { if(stk.size() < 2) throw "Improperly written expression"...
http://rosettacode.org/wiki/9_billion_names_of_God_the_integer
9 billion names of God the integer
This task is a variation of the short story by Arthur C. Clarke. (Solvers should be aware of the consequences of completing this task.) In detail, to specify what is meant by a   “name”: The integer 1 has 1 name     “1”. The integer 2 has 2 names   “1+1”,   and   “2”. The integer 3 has 3 names   “1+1+1”,   “2+1”,   ...
#REXX
REXX
/*REXX program generates and displays a number triangle for partitions of a number. */ numeric digits 400 /*be able to handle larger numbers. */ parse arg N . /*obtain optional argument from the CL.*/ if N=='' then N= 25 ...
http://rosettacode.org/wiki/A%2BB
A+B
A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separated by space(s): ( − 1000 ≤...
#bootBASIC
bootBASIC
10 print "Number 1"; 20 input a 30 print "Number 2"; 40 input b 50 print a+b
http://rosettacode.org/wiki/Ackermann_function
Ackermann function
The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree. The Ackermann function is usually defined as follows: A ( m , n ) = { n + 1 if  m = 0 A ( m ...
#SQL_PL
SQL PL
  --#SET TERMINATOR @   SET SERVEROUTPUT ON@   CREATE OR REPLACE FUNCTION ACKERMANN( IN M SMALLINT, IN N BIGINT ) RETURNS BIGINT BEGIN DECLARE RET BIGINT; DECLARE STMT STATEMENT;   IF (M = 0) THEN SET RET = N + 1; ELSEIF (N = 0) THEN PREPARE STMT FROM 'SET ? = ACKERMANN(? - 1, 1)'; EXECUTE STMT I...
http://rosettacode.org/wiki/ABC_problem
ABC problem
ABC problem You are encouraged to solve this task according to the task description, using any language you may know. You are given a collection of ABC blocks   (maybe like the ones you had when you were a kid). There are twenty blocks with two letters on each block. A complete alphabet is guaranteed amongst all sid...
#EchoLisp
EchoLisp
  (lib 'list) ;; list-delete   (define BLOCKS '("BO" "XK" "DQ" "CP" "NA" "GT" "RE" "TG" "QD" "FS" "JW" "HU" "VI" "AN" "OB" "ER" "FS" "LY" "PC" "ZM" ))   (define WORDS '("A" "BARK" "BOOK" "TREAT" "COMMON" "SQUAD" "CONFUSE"))   (define (spell word blocks) (cond ((string-empty? word) #t) ((empty? blocks) #f) ...
http://rosettacode.org/wiki/100_prisoners
100 prisoners
The Problem 100 prisoners are individually numbered 1 to 100 A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside. Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start. Prisoners start outside the room They can decid...
#BCPL
BCPL
get "libhdr"   manifest $( seed = 12345 // for pseudorandom number generator size = 100 // amount of drawers and prisoners tries = 50 // amount of tries each prisoner may make simul = 2000 // amount of simulations to run $)   let randto(n) = valof $( static $( state = seed $) let mask ...
http://rosettacode.org/wiki/Abundant_odd_numbers
Abundant odd numbers
An Abundant number is a number n for which the   sum of divisors   σ(n) > 2n, or,   equivalently,   the   sum of proper divisors   (or aliquot sum)       s(n) > n. E.G. 12   is abundant, it has the proper divisors     1,2,3,4 & 6     which sum to   16   ( > 12 or n);        or alternately,   has the sigma sum of ...
#Racket
Racket
#lang racket   (require math/number-theory racket/generator)   (define (make-generator start) (in-generator (for ([n (in-naturals start)] #:when (odd? n)) (define divisor-sum (- (apply + (divisors n)) n)) (when (> divisor-sum n) (yield (list n divisor-sum))))))   (for/list ([i (in-range 25)] [x ...
http://rosettacode.org/wiki/21_game
21 game
21 game You are encouraged to solve this task according to the task description, using any language you may know. 21 is a two player game, the game is played by choosing a number (1, 2, or 3) to be added to the running total. The game is won by the player whose chosen number causes the running total to reach exactly ...
#Lua
Lua
  gamewon = false running_total = 0 player = 1 opponent = 2   while not gamewon do num = 0   if player == 1 then opponent = 2 repeat print("Enter a number between 1 and 3 (0 to quit):") num = io.read("*n") if num == 0 then os.exit() end until (num > 0) and (num <=3) e...
http://rosettacode.org/wiki/24_game/Solve
24 game/Solve
task Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the 24 game. Show examples of solutions generated by the program. Related task   Arithmetic Evaluator
#Common_Lisp
Common Lisp
(defconstant +ops+ '(* / + -))   (defun digits () (sort (loop repeat 4 collect (1+ (random 9))) #'<))   (defun expr-value (expr) (eval expr))   (defun divides-by-zero-p (expr) (when (consp expr) (destructuring-bind (op &rest args) expr (or (divides-by-zero-p (car args)) (and (eq op '/) ...
http://rosettacode.org/wiki/4-rings_or_4-squares_puzzle
4-rings or 4-squares puzzle
4-rings or 4-squares puzzle You are encouraged to solve this task according to the task description, using any language you may know. Task Replace       a, b, c, d, e, f,   and   g       with the decimal digits   LOW   ───►   HIGH such that the sum of the letters inside of each of the four large squares add up to t...
#Modula-2
Modula-2
MODULE FourSquare; FROM Conversions IMPORT IntToStr; FROM Terminal IMPORT *;   PROCEDURE WriteInt(num : INTEGER); VAR str : ARRAY[0..16] OF CHAR; BEGIN IntToStr(num,str); WriteString(str); END WriteInt;   PROCEDURE four_square(low, high : INTEGER; unique, print : BOOLEAN); VAR count : INTEGER; VAR a, b, c, d, e...
http://rosettacode.org/wiki/99_bottles_of_beer
99 bottles of beer
Task Display the complete lyrics for the song:     99 Bottles of Beer on the Wall. The beer song The lyrics follow this form: 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of beer on the wall 98 bottles of beer Take one dow...
#ActionScript
ActionScript
for(var numBottles:uint = 99; numBottles > 0; numBottles--) { trace(numBottles, " bottles of beer on the wall"); trace(numBottles, " bottles of beer"); trace("Take one down, pass it around"); trace(numBottles - 1, " bottles of beer on the wall\n"); }
http://rosettacode.org/wiki/24_game
24 game
The 24 Game tests one's mental arithmetic. Task Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed. The program should prompt for the player to enter an arithmetic expression using just those, and all of those four digits, used exactly once each. T...
#C.2B.2B
C++
#include <random> #include <iostream> #include <stack> #include <set> #include <string> #include <functional> using namespace std;   class RPNParse { public: stack<double> stk; multiset<int> digits;   void op(function<double(double,double)> f) { if(stk.size() < 2) throw "Improperly written expression"...
http://rosettacode.org/wiki/9_billion_names_of_God_the_integer
9 billion names of God the integer
This task is a variation of the short story by Arthur C. Clarke. (Solvers should be aware of the consequences of completing this task.) In detail, to specify what is meant by a   “name”: The integer 1 has 1 name     “1”. The integer 2 has 2 names   “1+1”,   and   “2”. The integer 3 has 3 names   “1+1+1”,   “2+1”,   ...
#Ruby
Ruby
  # Generate IPF triangle # Nigel_Galloway: May 1st., 2013. def g(n,g) return 1 unless 1 < g and g < n-1 (2..g).inject(1){|res,q| res + (q > n-g ? 0 : g(n-g,q))} end   (1..25).each {|n| puts (1..n).map {|g| "%4s" % g(n,g)}.join }  
http://rosettacode.org/wiki/A%2BB
A+B
A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separated by space(s): ( − 1000 ≤...
#BQN
BQN
#!/usr/bin/env bqn   # Cut 𝕩 at occurrences of 𝕨, removing separators and empty segments # (BQNcrate phrase). Split ← (¬-˜⊢×·+`»⊸>)∘≠⊔⊢   # Natural number from base-10 digits (BQNcrate phrase). Base10 ← 10⊸×⊸+˜´∘⌽   # Parse any number of space-separated numbers from string 𝕩. ParseNums ← {Base10¨ -⟜'0' ' ' Split 𝕩}...
http://rosettacode.org/wiki/Ackermann_function
Ackermann function
The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree. The Ackermann function is usually defined as follows: A ( m , n ) = { n + 1 if  m = 0 A ( m ...
#Standard_ML
Standard ML
fun a (0, n) = n+1 | a (m, 0) = a (m-1, 1) | a (m, n) = a (m-1, a (m, n-1))
http://rosettacode.org/wiki/ABC_problem
ABC problem
ABC problem You are encouraged to solve this task according to the task description, using any language you may know. You are given a collection of ABC blocks   (maybe like the ones you had when you were a kid). There are twenty blocks with two letters on each block. A complete alphabet is guaranteed amongst all sid...
#Ela
Ela
open list monad io char   :::IO   null = foldr (\_ _ -> false) true   mapM_ f = foldr ((>>-) << f) (return ())   abc _ [] = [[]] abc blocks (c::cs) = [b::ans \\ b <- blocks | c `elem` b, ans <- abc (delete b blocks) cs]   blocks = ["BO", "XK", "DQ", "CP", "NA", "GT", "RE", "TG", "QD", "FS", "JW", "HU", "VI...
http://rosettacode.org/wiki/100_prisoners
100 prisoners
The Problem 100 prisoners are individually numbered 1 to 100 A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside. Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start. Prisoners start outside the room They can decid...
#C
C
  #include<stdbool.h> #include<stdlib.h> #include<stdio.h> #include<time.h>   #define LIBERTY false #define DEATH true   typedef struct{ int cardNum; bool hasBeenOpened; }drawer;   drawer *drawerSet;   void initialize(int prisoners){ int i,j,card; bool unique;   drawerSet = ((drawer*)malloc(prisoners * sizeof(draw...
http://rosettacode.org/wiki/Abundant_odd_numbers
Abundant odd numbers
An Abundant number is a number n for which the   sum of divisors   σ(n) > 2n, or,   equivalently,   the   sum of proper divisors   (or aliquot sum)       s(n) > n. E.G. 12   is abundant, it has the proper divisors     1,2,3,4 & 6     which sum to   16   ( > 12 or n);        or alternately,   has the sigma sum of ...
#Raku
Raku
sub odd-abundant (\x) { my @l = x.is-prime ?? 1 !! flat 1, (3 .. x.sqrt.floor).map: -> \d { next unless d +& 1; my \y = x div d; next if y * d !== x; d !== y ?? (d, y) !! d }; @l.sum > x ?? @l.sort !! Empty; }   sub odd-abundants (Int :$start-at is copy) { $start-...
http://rosettacode.org/wiki/21_game
21 game
21 game You are encouraged to solve this task according to the task description, using any language you may know. 21 is a two player game, the game is played by choosing a number (1, 2, or 3) to be added to the running total. The game is won by the player whose chosen number causes the running total to reach exactly ...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
SeedRandom[1234]; ClearAll[ComputerChoose, HumanChoose] ComputerChoose[n_] := If[n < 18, RandomChoice[{1, 2, 3}], 21 - n] HumanChoose[] := ChoiceDialog["How many?", {1 -> 1, 2 -> 2, 3 -> 3, "Quit" -> -1}] runningtotal = 0; whofirst = ChoiceDialog["Who goes first?", {"You" -> 1, "Computer" -> 2}]; While[runningtotal < 2...
http://rosettacode.org/wiki/24_game/Solve
24 game/Solve
task Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the 24 game. Show examples of solutions generated by the program. Related task   Arithmetic Evaluator
#D
D
import std.stdio, std.algorithm, std.range, std.conv, std.string, std.concurrency, permutations2, arithmetic_rational;   string solve(in int target, in int[] problem) { static struct T { Rational r; string e; }   Generator!T computeAllOperations(in Rational[] L) { return new typeof(return)({ ...
http://rosettacode.org/wiki/4-rings_or_4-squares_puzzle
4-rings or 4-squares puzzle
4-rings or 4-squares puzzle You are encouraged to solve this task according to the task description, using any language you may know. Task Replace       a, b, c, d, e, f,   and   g       with the decimal digits   LOW   ───►   HIGH such that the sum of the letters inside of each of the four large squares add up to t...
#Nim
Nim
func isUnique(a, b, c, d, e, f, g: uint8): bool = a != b and a != c and a != d and a != e and a != f and a != g and b != c and b != d and b != e and b != f and b != g and c != d and c != e and c != f and c != g and d != e and d != f and d != f and e != f and e != g and f != g   func isSolution(a, ...
http://rosettacode.org/wiki/15_puzzle_solver
15 puzzle solver
Your task is to write a program that finds a solution in the fewest moves possible single moves to a random Fifteen Puzzle Game. For this task you will be using the following puzzle: 15 14 1 6 9 11 4 12 0 10 7 3 13 8 5 2 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0 The output must show the moves' dir...
#11l
11l
-V nr = [3, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3] nc = [3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2]   T Solver n = 0 np = 0 n0 = [0] * 100 n2 = [UInt64(0)] * 100 n3 = [Char("\0")] * 100 n4 = [0] * 100   F (values) .n0[0] = values.index(0)   UInt64 tmp = 0 L(val) v...
http://rosettacode.org/wiki/99_bottles_of_beer
99 bottles of beer
Task Display the complete lyrics for the song:     99 Bottles of Beer on the Wall. The beer song The lyrics follow this form: 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of beer on the wall 98 bottles of beer Take one dow...
#Ada
Ada
with Ada.Text_Io; use Ada.Text_Io;   procedure Bottles is begin for X in reverse 1..99 loop Put_Line(Integer'Image(X) & " bottles of beer on the wall"); Put_Line(Integer'Image(X) & " bottles of beer"); Put_Line("Take one down, pass it around"); Put_Line(Integer'Image(X - 1) & " bottles...
http://rosettacode.org/wiki/24_game
24 game
The 24 Game tests one's mental arithmetic. Task Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed. The program should prompt for the player to enter an arithmetic expression using just those, and all of those four digits, used exactly once each. T...
#Ceylon
Ceylon
import ceylon.random { DefaultRandom }   class Rational(shared Integer numerator, shared Integer denominator = 1) satisfies Numeric<Rational> {   assert (denominator != 0);   Integer gcd(Integer a, Integer b) => if (b == 0) then a else gcd(b, a % b);   shared Rational inverted => Rational(denominator, numerator);  ...
http://rosettacode.org/wiki/9_billion_names_of_God_the_integer
9 billion names of God the integer
This task is a variation of the short story by Arthur C. Clarke. (Solvers should be aware of the consequences of completing this task.) In detail, to specify what is meant by a   “name”: The integer 1 has 1 name     “1”. The integer 2 has 2 names   “1+1”,   and   “2”. The integer 3 has 3 names   “1+1+1”,   “2+1”,   ...
#Rust
Rust
extern crate num;   use std::cmp; use num::bigint::BigUint;   fn cumu(n: usize, cache: &mut Vec<Vec<BigUint>>) { for l in cache.len()..n+1 { let mut r = vec![BigUint::from(0u32)]; for x in 1..l+1 { let prev = r[r.len() - 1].clone(); r.push(prev + cache[l-x][cmp::min(x, l-x)]....
http://rosettacode.org/wiki/9_billion_names_of_God_the_integer
9 billion names of God the integer
This task is a variation of the short story by Arthur C. Clarke. (Solvers should be aware of the consequences of completing this task.) In detail, to specify what is meant by a   “name”: The integer 1 has 1 name     “1”. The integer 2 has 2 names   “1+1”,   and   “2”. The integer 3 has 3 names   “1+1+1”,   “2+1”,   ...
#Scala
Scala
  object Main {   // This is a special class for memoization case class Memo[A,B](f: A => B) extends (A => B) { private val cache = Map.empty[A, B] def apply(x: A) = cache getOrElseUpdate (x, f(x)) }   // Naive, but memoized solution lazy val namesStartingMemo : Memo[Tuple2[Int, Int], BigInt] = Memo { ...
http://rosettacode.org/wiki/A%2BB
A+B
A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separated by space(s): ( − 1000 ≤...
#Bracmat
Bracmat
( out $ ( put$"Enter two integer numbers between -1000 and 1000:" & (filter=~/#%:~<-1000:~>1000) & get':(!filter:?a) (!filter:?b) & !a+!b | "Invalid input. Try again" ) );
http://rosettacode.org/wiki/Ackermann_function
Ackermann function
The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree. The Ackermann function is usually defined as follows: A ( m , n ) = { n + 1 if  m = 0 A ( m ...
#Stata
Stata
mata function ackermann(m,n) { if (m==0) { return(n+1) } else if (n==0) { return(ackermann(m-1,1)) } else { return(ackermann(m-1,ackermann(m,n-1))) } }   for (i=0; i<=3; i++) printf("%f\n",ackermann(i,4)) 5 6 11 125 end
http://rosettacode.org/wiki/ABC_problem
ABC problem
ABC problem You are encouraged to solve this task according to the task description, using any language you may know. You are given a collection of ABC blocks   (maybe like the ones you had when you were a kid). There are twenty blocks with two letters on each block. A complete alphabet is guaranteed amongst all sid...
#Elena
Elena
import system'routines; import system'collections; import extensions; import extensions'routines;   extension op { canMakeWordFrom(blocks) { var list := ArrayList.load(blocks);   ^ nil == (cast string(self)).upperCase().seekEach:(ch) { var index := list.indexOfElement ...
http://rosettacode.org/wiki/100_prisoners
100 prisoners
The Problem 100 prisoners are individually numbered 1 to 100 A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside. Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start. Prisoners start outside the room They can decid...
#C.23
C#
using System; using System.Linq;   namespace Prisoners { class Program { static bool PlayOptimal() { var secrets = Enumerable.Range(0, 100).OrderBy(a => Guid.NewGuid()).ToList();   for (int p = 0; p < 100; p++) { bool success = false;   var choice = p;...
http://rosettacode.org/wiki/Abundant_odd_numbers
Abundant odd numbers
An Abundant number is a number n for which the   sum of divisors   σ(n) > 2n, or,   equivalently,   the   sum of proper divisors   (or aliquot sum)       s(n) > n. E.G. 12   is abundant, it has the proper divisors     1,2,3,4 & 6     which sum to   16   ( > 12 or n);        or alternately,   has the sigma sum of ...
#REXX
REXX
/*REXX pgm displays abundant odd numbers: 1st 25, one─thousandth, first > 1 billion. */ parse arg Nlow Nuno Novr . /*obtain optional arguments from the CL*/ if Nlow=='' | Nlow=="," then Nlow= 25 /*Not specified? Then use the default.*/ if Nuno=='' | Nuno=="," then Nuno= 1000...
http://rosettacode.org/wiki/21_game
21 game
21 game You are encouraged to solve this task according to the task description, using any language you may know. 21 is a two player game, the game is played by choosing a number (1, 2, or 3) to be added to the running total. The game is won by the player whose chosen number causes the running total to reach exactly ...
#Nim
Nim
  # 21 game.   import random import strformat import strutils   const Target = 21 PossibleChoices: array[18..20, seq[string]] = [@["1", "2", "3"], @["1", "2"], @["1"]] Targets = [1, 5, 9, 13, 17, 21] # Totals that a player must obtain to win.   #----------------------------------------------------------------...
http://rosettacode.org/wiki/24_game/Solve
24 game/Solve
task Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the 24 game. Show examples of solutions generated by the program. Related task   Arithmetic Evaluator
#EchoLisp
EchoLisp
  ;; use task [[RPN_to_infix_conversion#EchoLisp]] to print results (define (rpn->string rpn) (if (vector? rpn) (infix->string (rpn->infix rpn)) "😥 Not found"))     (string-delimiter "") (define OPS #(* + - // )) ;; use float division (define-syntax-rule (commutative? op) (or (= op *) (= op +)))...
http://rosettacode.org/wiki/2048
2048
Task Implement a 2D sliding block puzzle game where blocks with numbers are combined to add their values. Rules of the game   The rules are that on each turn the player must choose a direction   (up, down, left or right).   All tiles move as far as possible in that direction, some move more than others.   Two ...
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program 2048_64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesARM64...
http://rosettacode.org/wiki/4-rings_or_4-squares_puzzle
4-rings or 4-squares puzzle
4-rings or 4-squares puzzle You are encouraged to solve this task according to the task description, using any language you may know. Task Replace       a, b, c, d, e, f,   and   g       with the decimal digits   LOW   ───►   HIGH such that the sum of the letters inside of each of the four large squares add up to t...
#Pascal
Pascal
program square4; {$MODE DELPHI} {$R+,O+} const LoDgt = 0; HiDgt = 9; type tchkset = set of LoDgt..HiDgt; tSol = record solMin : integer; solDat : array[1..7] of integer; end;   var sum,a,b,c,d,e,f,g,cnt,uniqueCount : NativeInt; sol : array of tSol;   procedure SolOut; var i,...
http://rosettacode.org/wiki/15_puzzle_solver
15 puzzle solver
Your task is to write a program that finds a solution in the fewest moves possible single moves to a random Fifteen Puzzle Game. For this task you will be using the following puzzle: 15 14 1 6 9 11 4 12 0 10 7 3 13 8 5 2 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0 The output must show the moves' dir...
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program puzzle15solvex64.s */ /* this program is a adaptation algorithme C++ and go rosetta code */ /* thanck for the creators */ /* 1 byte by box on game board */   /* create a file with nano */ /* 15, 2, 3, 4 5, 6, 7, 1 9, 10, 8, 11 13, ...
http://rosettacode.org/wiki/99_bottles_of_beer
99 bottles of beer
Task Display the complete lyrics for the song:     99 Bottles of Beer on the Wall. The beer song The lyrics follow this form: 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of beer on the wall 98 bottles of beer Take one dow...
#Aime
Aime
integer bottles;   bottles = 99;   do { o_(bottles, " bottles of beer on the wall\n"); o_(bottles, " bottles of beer\n"); o_("Take one down, pass it around\n"); o_(bottles -= 1, " bottles of beer on the wall\n\n"); } while (bottles);
http://rosettacode.org/wiki/24_game
24 game
The 24 Game tests one's mental arithmetic. Task Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed. The program should prompt for the player to enter an arithmetic expression using just those, and all of those four digits, used exactly once each. T...
#Clojure
Clojure
  (ns rosettacode.24game)   (def ^:dynamic *luser* "You guessed wrong, or your input was not in prefix notation.")   (def ^:private start #(println "Your numbers are: " %1 ". Your goal is " %2 ".\n" "Use the ops [+ - * /] in prefix notation to reach" %2 ".\n" "q[enter] to quit."))   (defn play ([] (play 24)) ([goa...
http://rosettacode.org/wiki/9_billion_names_of_God_the_integer
9 billion names of God the integer
This task is a variation of the short story by Arthur C. Clarke. (Solvers should be aware of the consequences of completing this task.) In detail, to specify what is meant by a   “name”: The integer 1 has 1 name     “1”. The integer 2 has 2 names   “1+1”,   and   “2”. The integer 3 has 3 names   “1+1+1”,   “2+1”,   ...
#scheme
scheme
(define (f m n) (define (sigma g x y) (define (sum i) (if (< i 0) 0 (+ (f x (- y i) ) (sum (- i 1))))) (sum y)) (cond ((eq? m n) 1) ((eq? n 1) 1) ((eq? n 0) 0) ((< m n) (f m m)) ((< (/ m 2) n) (sigma f (- m n) (- m n))) (else (sigma f (- m n) n)))) (define (line...
http://rosettacode.org/wiki/A%2BB
A+B
A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separated by space(s): ( − 1000 ≤...
#Brainf.2A.2A.2A
Brainf***
INPUT AND SUMMATION TODO if first symbol is a minus sign print Qgo awayQ +> initialize sum to one ++[ loop for each input ie twice [>>,----------[----------------------[-<+>]]<] eat digits until space or newline ...
http://rosettacode.org/wiki/Ackermann_function
Ackermann function
The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree. The Ackermann function is usually defined as follows: A ( m , n ) = { n + 1 if  m = 0 A ( m ...
#Swift
Swift
func ackerman(m:Int, n:Int) -> Int { if m == 0 { return n+1 } else if n == 0 { return ackerman(m-1, 1) } else { return ackerman(m-1, ackerman(m, n-1)) } }
http://rosettacode.org/wiki/ABC_problem
ABC problem
ABC problem You are encouraged to solve this task according to the task description, using any language you may know. You are given a collection of ABC blocks   (maybe like the ones you had when you were a kid). There are twenty blocks with two letters on each block. A complete alphabet is guaranteed amongst all sid...
#Elixir
Elixir
defmodule ABC do def can_make_word(word, avail) do can_make_word(String.upcase(word) |> to_charlist, avail, []) end   defp can_make_word([], _, _), do: true defp can_make_word(_, [], _), do: false defp can_make_word([l|tail], [b|rest], tried) do (l in b and can_make_word(tail, rest++tried, [])) o...
http://rosettacode.org/wiki/100_prisoners
100 prisoners
The Problem 100 prisoners are individually numbered 1 to 100 A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside. Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start. Prisoners start outside the room They can decid...
#C.2B.2B
C++
#include <cstdlib> // for rand #include <algorithm> // for random_shuffle #include <iostream> // for output   using namespace std;   class cupboard { public: cupboard() { for (int i = 0; i < 100; i++) drawers[i] = i; random_shuffle(drawers, drawers + 100); }   bool playRandom(...
http://rosettacode.org/wiki/Abundant_odd_numbers
Abundant odd numbers
An Abundant number is a number n for which the   sum of divisors   σ(n) > 2n, or,   equivalently,   the   sum of proper divisors   (or aliquot sum)       s(n) > n. E.G. 12   is abundant, it has the proper divisors     1,2,3,4 & 6     which sum to   16   ( > 12 or n);        or alternately,   has the sigma sum of ...
#Ring
Ring
  #Project: Anbundant odd numbers   max = 100000000 limit = 25 nr = 0 m = 1 check = 0 index = 0 see "working..." + nl see "wait for done..." + nl while true check = 0 if m%2 = 1 nice(m) ok if check = 1 nr = nr + 1 ok if nr = max exit ok m = m + ...
http://rosettacode.org/wiki/21_game
21 game
21 game You are encouraged to solve this task according to the task description, using any language you may know. 21 is a two player game, the game is played by choosing a number (1, 2, or 3) to be added to the running total. The game is won by the player whose chosen number causes the running total to reach exactly ...
#Objeck
Objeck
class TwentyOne { @quit : Bool; @player_total : Int; @computer_total : Int;   function : Main(args : String[]) ~ Nil { TwentyOne->New()->Play(); }   New() { }   method : Play() ~ Nil { player_first := Int->Random(1) = 1;   "Enter 'q' to quit\n==="->PrintLine(); do { if(player_first...
http://rosettacode.org/wiki/24_game/Solve
24 game/Solve
task Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the 24 game. Show examples of solutions generated by the program. Related task   Arithmetic Evaluator
#Elixir
Elixir
defmodule Game24 do @expressions [ ["((", "", ")", "", ")", ""], ["(", "(", "", "", "))", ""], ["(", "", ")", "(", "", ")"], ["", "((", "", "", ")", ")"], ["", "(", "", "(", "", "))"] ]   def solve(digits) do dig_perm = permute(digits) |> Enum....
http://rosettacode.org/wiki/2048
2048
Task Implement a 2D sliding block puzzle game where blocks with numbers are combined to add their values. Rules of the game   The rules are that on each turn the player must choose a direction   (up, down, left or right).   All tiles move as far as possible in that direction, some move more than others.   Two ...
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO; with System.Random_Numbers; procedure Play_2048 is -- ----- Keyboard management type t_Keystroke is (Up, Down, Right, Left, Quit, Restart, Invalid); -- Redefining this standard procedure as function to allow Get_Keystroke as an expression function function Get_Immediate re...
http://rosettacode.org/wiki/4-rings_or_4-squares_puzzle
4-rings or 4-squares puzzle
4-rings or 4-squares puzzle You are encouraged to solve this task according to the task description, using any language you may know. Task Replace       a, b, c, d, e, f,   and   g       with the decimal digits   LOW   ───►   HIGH such that the sum of the letters inside of each of the four large squares add up to t...
#Perl
Perl
use ntheory qw/forperm/; use Set::CrossProduct;   sub four_sq_permute { my($list) = @_; my @solutions; forperm { @c = @$list[@_]; push @solutions, [@c] if check(@c); } @$list; print +@solutions . " unique solutions found using: " . join(', ', @$list) . "\n"; return @solutions; }   ...
http://rosettacode.org/wiki/15_puzzle_solver
15 puzzle solver
Your task is to write a program that finds a solution in the fewest moves possible single moves to a random Fifteen Puzzle Game. For this task you will be using the following puzzle: 15 14 1 6 9 11 4 12 0 10 7 3 13 8 5 2 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0 The output must show the moves' dir...
#Ada
Ada
with Ada.Text_IO;   procedure Puzzle_15 is   type Direction is (Up, Down, Left, Right); type Row_Type is range 0 .. 3; type Col_Type is range 0 .. 3; type Tile_Type is range 0 .. 15;   To_Col : constant array (Tile_Type) of Col_Type := (3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2); To_Row : co...
http://rosettacode.org/wiki/99_bottles_of_beer
99 bottles of beer
Task Display the complete lyrics for the song:     99 Bottles of Beer on the Wall. The beer song The lyrics follow this form: 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of beer on the wall 98 bottles of beer Take one dow...
#Algae
Algae
  # 99 Bottles of Beer on the Wall # in Algae # bottles.A for (i in 99:1:1) { if (i != 1) { printf("%d bottles of beer on the wall\n";i); printf("%d bottles of beer...\n";i); printf("you take on down and pass it around...\n"); if ( i == 2) { printf("%d bottles of beer ...
http://rosettacode.org/wiki/24_game
24 game
The 24 Game tests one's mental arithmetic. Task Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed. The program should prompt for the player to enter an arithmetic expression using just those, and all of those four digits, used exactly once each. T...
#COBOL
COBOL
>>SOURCE FORMAT FREE *> This code is dedicated to the public domain *> This is GNUCobol 2.0 identification division. program-id. twentyfour. environment division. configuration section. repository. function all intrinsic. data division. working-storage section. 01 p pic 999. 01 p1 pic 999. 01 p-max pic 999 v...
http://rosettacode.org/wiki/9_billion_names_of_God_the_integer
9 billion names of God the integer
This task is a variation of the short story by Arthur C. Clarke. (Solvers should be aware of the consequences of completing this task.) In detail, to specify what is meant by a   “name”: The integer 1 has 1 name     “1”. The integer 2 has 2 names   “1+1”,   and   “2”. The integer 3 has 3 names   “1+1+1”,   “2+1”,   ...
#Sidef
Sidef
var cache = [[1]]   func cumu (n) { for l (cache.len .. n) { var r = [0] for i (1..l) { r << (r[-1] + cache[l-i][min(i, l-i)]) } cache << r } cache[n] }   func row (n) { var r = cumu(n) n.of {|i| r[i+1] - r[i] } }   say "rows:" for i (1..15) { "%2s: %s...
http://rosettacode.org/wiki/A%2BB
A+B
A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separated by space(s): ( − 1000 ≤...
#Brat
Brat
numbers = g.split[0,1].map(:to_i) p numbers[0] + numbers[1] #Prints the sum of the input
http://rosettacode.org/wiki/Ackermann_function
Ackermann function
The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree. The Ackermann function is usually defined as follows: A ( m , n ) = { n + 1 if  m = 0 A ( m ...
#Tcl
Tcl
proc ack {m n} { if {$m == 0} { expr {$n + 1} } elseif {$n == 0} { ack [expr {$m - 1}] 1 } else { ack [expr {$m - 1}] [ack $m [expr {$n - 1}]] } }
http://rosettacode.org/wiki/ABC_problem
ABC problem
ABC problem You are encouraged to solve this task according to the task description, using any language you may know. You are given a collection of ABC blocks   (maybe like the ones you had when you were a kid). There are twenty blocks with two letters on each block. A complete alphabet is guaranteed amongst all sid...
#Erlang
Erlang
-module(abc). -export([can_make_word/1, can_make_word/2, blocks/0]).   blocks() -> ["BO", "XK", "DQ", "CP", "NA", "GT", "RE", "TG", "QD", "FS", "JW", "HU", "VI", "AN", "OB", "ER", "FS", "LY", "PC", "ZM"].   can_make_word(Word) -> can_make_word(Word, blocks()). can_make_word(Word, Avail) -> can_make_word(s...
http://rosettacode.org/wiki/100_prisoners
100 prisoners
The Problem 100 prisoners are individually numbered 1 to 100 A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside. Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start. Prisoners start outside the room They can decid...
#Clojure
Clojure
(ns clojure-sandbox.prisoners)   (defn random-drawers [] "Returns a list of shuffled numbers" (-> 100 range shuffle))   (defn search-50-random-drawers [prisoner-number drawers] "Select 50 random drawers and return true if the prisoner's number was found" (->> drawers shuffle ;; Put drawer cont...
http://rosettacode.org/wiki/Abundant_odd_numbers
Abundant odd numbers
An Abundant number is a number n for which the   sum of divisors   σ(n) > 2n, or,   equivalently,   the   sum of proper divisors   (or aliquot sum)       s(n) > n. E.G. 12   is abundant, it has the proper divisors     1,2,3,4 & 6     which sum to   16   ( > 12 or n);        or alternately,   has the sigma sum of ...
#Ruby
Ruby
require "prime"   class Integer def proper_divisors return [] if self == 1 primes = prime_division.flat_map{|prime, freq| [prime] * freq} (1...primes.size).each_with_object([1]) do |n, res| primes.combination(n).map{|combi| res << combi.inject(:*)} end.flatten.uniq end end   def generator_odd_...
http://rosettacode.org/wiki/21_game
21 game
21 game You are encouraged to solve this task according to the task description, using any language you may know. 21 is a two player game, the game is played by choosing a number (1, 2, or 3) to be added to the running total. The game is won by the player whose chosen number causes the running total to reach exactly ...
#Pascal
Pascal
  program Game21;   {$APPTYPE CONSOLE}   {$R *.res}   uses System.SysUtils, System.StrUtils, // for IfThen Winapi.Windows; // for ClearScreen   const HARD_MODE = True;   var computerPlayer: string = 'Computer'; humanPlayer: string = 'Player 1';   // for change color ConOut: THandle; BufInfo: TConsole...
http://rosettacode.org/wiki/24_game/Solve
24 game/Solve
task Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the 24 game. Show examples of solutions generated by the program. Related task   Arithmetic Evaluator
#ERRE
ERRE
  PROGRAM 24SOLVE   LABEL 98,99,2540,2550,2560   ! possible brackets CONST NBRACKETS=11,ST_CONST$="+-*/^("   DIM D[4],PERM[24,4] DIM BRAKETS$[NBRACKETS] DIM OP$[3] DIM STACK$[50]   PROCEDURE COMPATTA_STACK IF NS>1 THEN R=1 WHILE R<NS DO IF INSTR(ST_CONST$,STACK$[R])=0 AND INSTR(ST_CONST$,STACK$[...
http://rosettacode.org/wiki/2048
2048
Task Implement a 2D sliding block puzzle game where blocks with numbers are combined to add their values. Rules of the game   The rules are that on each turn the player must choose a direction   (up, down, left or right).   All tiles move as far as possible in that direction, some move more than others.   Two ...
#ALGOL_68
ALGOL 68
  main:( INT side = 4; INT right = 1, up = 2, left = 3, down = 4; []CHAR direction letters = "ruld"; []STRING direction descriptions = ("right", "up", "left", "down");   MODE BOARD = REF[,]INT; MODE CELL = REF INT;   OP = = (BOARD a, BOARD b) BOOL: (FOR i TO side DO FOR j TO side DO IF a[i,j] /= b[i,j] THEN mismatch ...
http://rosettacode.org/wiki/4-rings_or_4-squares_puzzle
4-rings or 4-squares puzzle
4-rings or 4-squares puzzle You are encouraged to solve this task according to the task description, using any language you may know. Task Replace       a, b, c, d, e, f,   and   g       with the decimal digits   LOW   ───►   HIGH such that the sum of the letters inside of each of the four large squares add up to t...
#Phix
Phix
-- demo/rosetta/4_rings_or_4_squares_puzzle.exw with javascript_semantics integer solutions procedure check(sequence set, bool show) integer {a,b,c,d,e,f,g} = set, ab = a+b if ab=b+d+c and ab=d+e+f and ab=f+g then solutions += 1 if show then ?set end if end if end proce...
http://rosettacode.org/wiki/15_puzzle_solver
15 puzzle solver
Your task is to write a program that finds a solution in the fewest moves possible single moves to a random Fifteen Puzzle Game. For this task you will be using the following puzzle: 15 14 1 6 9 11 4 12 0 10 7 3 13 8 5 2 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0 The output must show the moves' dir...
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI */ /* program puzzle15solver.s */ /* my first other program find à solution in 134 moves !!! */ /* this second program is a adaptation algorithme C++ and go rosetta code */ /* thanck for the creators */ /* 1 byte by box on game board */   /* create a file with nano */ /* 15, 2, ...
http://rosettacode.org/wiki/99_bottles_of_beer
99 bottles of beer
Task Display the complete lyrics for the song:     99 Bottles of Beer on the Wall. The beer song The lyrics follow this form: 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of beer on the wall 98 bottles of beer Take one dow...
#ALGOL_60
ALGOL 60
begin integer n;   for n:= 99 step -1 until 2 do begin outinteger(1,n); outstring(1,"bottles of beer on the wall,"); outinteger(1,n); outstring(1,"bottles of beer.\nTake one down and pass it around,"); outstring(1,"of beer on the wall...\n\n") end;   outstring(1," 1 bott...
http://rosettacode.org/wiki/24_game
24 game
The 24 Game tests one's mental arithmetic. Task Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed. The program should prompt for the player to enter an arithmetic expression using just those, and all of those four digits, used exactly once each. T...
#CoffeeScript
CoffeeScript
tty = require 'tty' tty.setRawMode true   buffer = "" numbers = []   for n in [0...4] numbers.push Math.max 1, Math.floor(Math.random() * 9)   console.log "You can use the numbers: #{numbers.join ' '}"   process.stdin.on 'keypress', (char, key) ->   # accept operator if char and isNaN(char) and /[()*\/+-]/...
http://rosettacode.org/wiki/9_billion_names_of_God_the_integer
9 billion names of God the integer
This task is a variation of the short story by Arthur C. Clarke. (Solvers should be aware of the consequences of completing this task.) In detail, to specify what is meant by a   “name”: The integer 1 has 1 name     “1”. The integer 2 has 2 names   “1+1”,   and   “2”. The integer 3 has 3 names   “1+1+1”,   “2+1”,   ...
#SPL
SPL
'print triangle > n, 1..25 k = 50-n*2 #.output(#.str("","<"+k+"<"),#.rs) > k, 1..n i = p(n,k) s = #.str(i,">3<")  ? k<n, s += " "+#.rs #.output(s) < < p(n,k)=  ? k=0 | k>n, <= 0  ? k=n, <= 1 <= p(n-1,k-1)+p(n-k,k) .   'calculate partition function #.output() #.output("G(23) = ",g(23)) #.ou...
http://rosettacode.org/wiki/9_billion_names_of_God_the_integer
9 billion names of God the integer
This task is a variation of the short story by Arthur C. Clarke. (Solvers should be aware of the consequences of completing this task.) In detail, to specify what is meant by a   “name”: The integer 1 has 1 name     “1”. The integer 2 has 2 names   “1+1”,   and   “2”. The integer 3 has 3 names   “1+1+1”,   “2+1”,   ...
#Stata
Stata
mata function part(n) { a = J(n,n,.) for (i=1;i<=n;i++) a[i,1] = a[i,i] = 1 for (i=3;i<=n;i++) { for (j=2;j<i;j++) a[i,j] = sum(a[i-j,1..min((j,i-j))]) } return(a) } end
http://rosettacode.org/wiki/A%2BB
A+B
A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separated by space(s): ( − 1000 ≤...
#Burlesque
Burlesque
ps++
http://rosettacode.org/wiki/Ackermann_function
Ackermann function
The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree. The Ackermann function is usually defined as follows: A ( m , n ) = { n + 1 if  m = 0 A ( m ...
#TI-83_BASIC
TI-83 BASIC
PROGRAM:ACKERMAN :If not(M :Then :N+1→N :Return :Else :If not(N :Then :1→N :M-1→M :prgmACKERMAN :Else :N-1→N :M→L1(1+dim(L1 :prgmACKERMAN :Ans→N :L1(dim(L1))-1→M :dim(L1)-1→dim(L1 :prgmACKERMAN :End :End
http://rosettacode.org/wiki/ABC_problem
ABC problem
ABC problem You are encouraged to solve this task according to the task description, using any language you may know. You are given a collection of ABC blocks   (maybe like the ones you had when you were a kid). There are twenty blocks with two letters on each block. A complete alphabet is guaranteed amongst all sid...
#ERRE
ERRE
  PROGRAM BLOCKS   !$INCLUDE="PC.LIB"   PROCEDURE CANMAKEWORD(WORD$) LOCAL B$,P% B$=BLOCKS$ PRINT(WORD$;" -> ";) P%=INSTR(B$,CHR$(ASC(WORD$) AND $DF)) WHILE P%>0 AND WORD$>"" DO CHANGE(B$,P%-1+(P% MOD 2),".."->B$) WORD$=MID$(WORD$,2) EXIT IF WORD$="" P%=INSTR(B$,CHR$(ASC(WORD$) AN...
http://rosettacode.org/wiki/100_prisoners
100 prisoners
The Problem 100 prisoners are individually numbered 1 to 100 A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside. Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start. Prisoners start outside the room They can decid...
#CLU
CLU
% This program needs to be merged with PCLU's "misc" library % to use the random number generator. % % pclu -merge $CLUHOME/lib/misc.lib -compile prisoners.clu   % Seed the random number generator with the current time init_rng = proc () d: date := now() seed: int := ((d.hour*60) + d.minute)*60 + d.second r...
http://rosettacode.org/wiki/Abundant_odd_numbers
Abundant odd numbers
An Abundant number is a number n for which the   sum of divisors   σ(n) > 2n, or,   equivalently,   the   sum of proper divisors   (or aliquot sum)       s(n) > n. E.G. 12   is abundant, it has the proper divisors     1,2,3,4 & 6     which sum to   16   ( > 12 or n);        or alternately,   has the sigma sum of ...
#Rust
Rust
fn divisors(n: u64) -> Vec<u64> { let mut divs = vec![1]; let mut divs2 = Vec::new();   for i in (2..).take_while(|x| x * x <= n).filter(|x| n % x == 0) { divs.push(i); let j = n / i; if i != j { divs2.push(j); } } divs.extend(divs2.iter().rev());   di...
http://rosettacode.org/wiki/Abundant_odd_numbers
Abundant odd numbers
An Abundant number is a number n for which the   sum of divisors   σ(n) > 2n, or,   equivalently,   the   sum of proper divisors   (or aliquot sum)       s(n) > n. E.G. 12   is abundant, it has the proper divisors     1,2,3,4 & 6     which sum to   16   ( > 12 or n);        or alternately,   has the sigma sum of ...
#Scala
Scala
import scala.collection.mutable.ListBuffer   object Abundant { def divisors(n: Int): ListBuffer[Int] = { val divs = new ListBuffer[Int] divs.append(1)   val divs2 = new ListBuffer[Int] var i = 2   while (i * i <= n) { if (n % i == 0) { val j = n / i divs.append(i) if ...
http://rosettacode.org/wiki/21_game
21 game
21 game You are encouraged to solve this task according to the task description, using any language you may know. 21 is a two player game, the game is played by choosing a number (1, 2, or 3) to be added to the running total. The game is won by the player whose chosen number causes the running total to reach exactly ...
#Perl
Perl
print <<'HERE'; The 21 game. Each player chooses to add 1, 2, or 3 to a running total. The player whose turn it is when the total reaches 21 wins. Enter q to quit. HERE   my $total = 0;   while () { print "Running total is: $total\n"; my ($me,$comp); while () { print 'What number do you play> '; ...
http://rosettacode.org/wiki/24_game/Solve
24 game/Solve
task Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the 24 game. Show examples of solutions generated by the program. Related task   Arithmetic Evaluator
#Euler_Math_Toolbox
Euler Math Toolbox
  >function try24 (v) ... $n=cols(v); $if n==1 and v[1]~=24 then $ "Solved the problem", $ return 1; $endif $loop 1 to n $ w=tail(v,2); $ loop 1 to n-1 $ h=w; a=v[1]; b=w[1]; $ w[1]=a+b; if try24(w); ""+a+"+"+b+"="+(a+b), return 1; endif; $ w[1]=a-b; if try24(w); ""+a+"-"+b+"="+(a-b), return 1; endif; $ ...
http://rosettacode.org/wiki/2048
2048
Task Implement a 2D sliding block puzzle game where blocks with numbers are combined to add their values. Rules of the game   The rules are that on each turn the player must choose a direction   (up, down, left or right).   All tiles move as far as possible in that direction, some move more than others.   Two ...
#Amazing_Hopper
Amazing Hopper
VERSION 1: "Hopper" flavour.
http://rosettacode.org/wiki/4-rings_or_4-squares_puzzle
4-rings or 4-squares puzzle
4-rings or 4-squares puzzle You are encouraged to solve this task according to the task description, using any language you may know. Task Replace       a, b, c, d, e, f,   and   g       with the decimal digits   LOW   ───►   HIGH such that the sum of the letters inside of each of the four large squares add up to t...
#Picat
Picat
import cp.   main => puzzle_all(1, 7, true, Sol1), foreach(Sol in Sol1) println(Sol) end, nl,   puzzle_all(3, 9, true, Sol2), foreach(Sol in Sol2) println(Sol) end, nl,   puzzle_all(0, 9, false, Sol3), println(len=Sol3.len), nl.   puzzle_all(Min, Max, Distinct, LL) => L = [A,B,C,D,E,F,G], L ...
http://rosettacode.org/wiki/15_puzzle_solver
15 puzzle solver
Your task is to write a program that finds a solution in the fewest moves possible single moves to a random Fifteen Puzzle Game. For this task you will be using the following puzzle: 15 14 1 6 9 11 4 12 0 10 7 3 13 8 5 2 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0 The output must show the moves' dir...
#C
C
  /**@file HybridIDA.c * @brief solve 4x4 sliding puzzle with IDA* algorithm * by RMM 2021-feb-22   * The Interative Deepening A* is relatively easy to code in 'C' since * it does not need Queues and Lists to manage memory. Instead the * search space state is held on the LIFO stack frame of recursive * search fu...
http://rosettacode.org/wiki/99_bottles_of_beer
99 bottles of beer
Task Display the complete lyrics for the song:     99 Bottles of Beer on the Wall. The beer song The lyrics follow this form: 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of beer on the wall 98 bottles of beer Take one dow...
#ALGOL_68
ALGOL 68
main:( FOR bottles FROM 99 TO 1 BY -1 DO printf(($z-d" bottles of beer on the wall"l$, bottles)); printf(($z-d" bottles of beer"l$, bottles)); printf(($"Take one down, pass it around"l$)); printf(($z-d" bottles of beer on the wall"ll$, bottles-1)) OD )
http://rosettacode.org/wiki/24_game
24 game
The 24 Game tests one's mental arithmetic. Task Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed. The program should prompt for the player to enter an arithmetic expression using just those, and all of those four digits, used exactly once each. T...
#Commodore_BASIC
Commodore BASIC
1 rem 24 game 2 rem for rosetta code 10 rem use appropriate basic base address 11 bh=08:bl=01: rem $0801 commodore 64 12 rem bh=16:bl=01: rem $1001 commodore +4 13 rem bh=18:bl=01: rem $1201 commodore vic-20 (35k ram) 14 rem bh=04:bl=01: rem $0401 commodore pet 15 rem bh=28:bl=01: rem $1c01 commodore 128 (bank 0)   35 ...
http://rosettacode.org/wiki/9_billion_names_of_God_the_integer
9 billion names of God the integer
This task is a variation of the short story by Arthur C. Clarke. (Solvers should be aware of the consequences of completing this task.) In detail, to specify what is meant by a   “name”: The integer 1 has 1 name     “1”. The integer 2 has 2 names   “1+1”,   and   “2”. The integer 3 has 3 names   “1+1+1”,   “2+1”,   ...
#Swift
Swift
var cache = [[1]] func namesOfGod(n:Int) -> [Int] { for l in cache.count...n { var r = [0] for x in 1...l { r.append(r[r.count - 1] + cache[l - x][min(x, l-x)]) } cache.append(r) } return cache[n] }   func row(n:Int) -> [Int] { let r = namesOfGod(n) var re...
http://rosettacode.org/wiki/9_billion_names_of_God_the_integer
9 billion names of God the integer
This task is a variation of the short story by Arthur C. Clarke. (Solvers should be aware of the consequences of completing this task.) In detail, to specify what is meant by a   “name”: The integer 1 has 1 name     “1”. The integer 2 has 2 names   “1+1”,   and   “2”. The integer 3 has 3 names   “1+1+1”,   “2+1”,   ...
#Tcl
Tcl
set cache 1 proc cumu {n} { global cache for {set l [llength $cache]} {$l <= $n} {incr l} { set r 0 for {set x 1; set y [expr {$l-1}]} {$y >= 0} {incr x; incr y -1} { lappend r [expr { [lindex $r end] + [lindex $cache $y [expr {min($x, $y)}]] }] } lappend cache $r } return [lindex $cache...
http://rosettacode.org/wiki/A%2BB
A+B
A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separated by space(s): ( − 1000 ≤...
#C
C
// Standard input-output streams #include <stdio.h> int main() { int a, b; scanf("%d%d", &a, &b); printf("%d\n", a + b); return 0; }
http://rosettacode.org/wiki/Ackermann_function
Ackermann function
The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree. The Ackermann function is usually defined as follows: A ( m , n ) = { n + 1 if  m = 0 A ( m ...
#TI-89_BASIC
TI-89 BASIC
Define A(m,n) = when(m=0, n+1, when(n=0, A(m-1,1), A(m-1, A(m, n-1))))
http://rosettacode.org/wiki/ABC_problem
ABC problem
ABC problem You are encouraged to solve this task according to the task description, using any language you may know. You are given a collection of ABC blocks   (maybe like the ones you had when you were a kid). There are twenty blocks with two letters on each block. A complete alphabet is guaranteed amongst all sid...
#Euphoria
Euphoria
  include std/text.e   sequence blocks = {{'B','O'},{'X','K'},{'D','Q'},{'C','P'},{'N','A'}, {'G','T'},{'R','E'},{'T','G'},{'Q','D'},{'F','S'}, {'J','W'},{'H','U'},{'V','I'},{'A','N'},{'O','B'}, {'E','R'},{'F','S'},{'L','Y'},{'P','C'},{'Z','M'}} sequence words = ...
http://rosettacode.org/wiki/100_prisoners
100 prisoners
The Problem 100 prisoners are individually numbered 1 to 100 A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside. Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start. Prisoners start outside the room They can decid...
#Commodore_BASIC
Commodore BASIC
  10 rem 100 prisoners 20 rem set arrays 30 rem dr = drawers containing card values 40 rem ig = a list of numbers 1 through 100, shuffled to become the 41 rem guess sequence for each inmate - method 1 50 dim dr(100),ig(100) 55 rem initialize drawers with own card in each drawer 60 for i=1 to 100:dr(i)=i:next   1000 p...
http://rosettacode.org/wiki/Abundant_odd_numbers
Abundant odd numbers
An Abundant number is a number n for which the   sum of divisors   σ(n) > 2n, or,   equivalently,   the   sum of proper divisors   (or aliquot sum)       s(n) > n. E.G. 12   is abundant, it has the proper divisors     1,2,3,4 & 6     which sum to   16   ( > 12 or n);        or alternately,   has the sigma sum of ...
#Sidef
Sidef
func is_abundant(n) { n.sigma > 2*n }   func odd_abundants (from = 1) { from = (from + 2)//3 from += (from%2 - 1) 3*from .. Inf `by` 6 -> lazy.grep(is_abundant) }   say " Index | Number | proper divisor sum" const sep = "-------+-------------+-------------------\n" const fstr = "%6s | %...
http://rosettacode.org/wiki/21_game
21 game
21 game You are encouraged to solve this task according to the task description, using any language you may know. 21 is a two player game, the game is played by choosing a number (1, 2, or 3) to be added to the running total. The game is won by the player whose chosen number causes the running total to reach exactly ...
#Phix
Phix
-- -- demo\rosetta\21_Game.exw -- ======================== -- with javascript_semantics -- DEV NORMALIZESIZE, CANFOCUS, "You" not checked, VALUE_HANDLE. -- The radio_texts simply don't do anything at all in p2js. constant title = "21 Game", help_text = """ Play by choosing 1, 2, or 3 ...
http://rosettacode.org/wiki/24_game/Solve
24 game/Solve
task Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the 24 game. Show examples of solutions generated by the program. Related task   Arithmetic Evaluator
#F.23
F#
open System   let rec gcd x y = if x = y || x = 0 then y else if x < y then gcd y x else gcd y (x-y) let abs (x : int) = Math.Abs x let sign (x: int) = Math.Sign x let cint s = Int32.Parse(s)   type Rat(x : int, y : int) = let g = if y = 0 then 0 else gcd (abs x) (abs y) member this.n = if g = 0 then sign y * s...
http://rosettacode.org/wiki/2048
2048
Task Implement a 2D sliding block puzzle game where blocks with numbers are combined to add their values. Rules of the game   The rules are that on each turn the player must choose a direction   (up, down, left or right).   All tiles move as far as possible in that direction, some move more than others.   Two ...
#Applesoft_BASIC
Applesoft BASIC
PRINT "Game 2048"   10 REM ************ 20 REM * 2024 * 30 REM ************ 40 HOME 100 W = 2: REM **** W=0 FOR LOOSE W=1 FOR WIN W=2 FOR PLAYING **** 110 DIM MA(4,4) 120 FC = 16: REM FREECELLS 130 A$ = "":SC = 0:MT = 2 140 GOSUB 1000: DRAW THESCREEN 150 GOSUB 1500: REM PRINT SCORE AND...
http://rosettacode.org/wiki/4-rings_or_4-squares_puzzle
4-rings or 4-squares puzzle
4-rings or 4-squares puzzle You are encouraged to solve this task according to the task description, using any language you may know. Task Replace       a, b, c, d, e, f,   and   g       with the decimal digits   LOW   ───►   HIGH such that the sum of the letters inside of each of the four large squares add up to t...
#PL.2FSQL
PL/SQL
  CREATE TABLE allints (v NUMBER); CREATE TABLE results ( a NUMBER, b NUMBER, c NUMBER, d NUMBER, e NUMBER, f NUMBER, g NUMBER );   CREATE OR REPLACE PROCEDURE foursquares(lo NUMBER,hi NUMBER,uniq BOOLEAN,show BOOLEAN) AS a NUMBER; b NUMBER; c NUMBER; d NUMBER; e NUMBER; f NUMBER; g NUMBER;...