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/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.2B.2B
C++
  // Solve Random 15 Puzzles : Nigel Galloway - October 18th., 2017 class fifteenSolver{ const int Nr[16]{3,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3}, Nc[16]{3,0,1,2,3,0,1,2,3,0,1,2,3,0,1,2}; int n{},_n{}, N0[100]{},N3[100]{},N4[100]{}; unsigned long N2[100]{}; const bool fY(){ if (N4[n]<_n) return fN(); if (N2[n]...
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-M
ALGOL-M
  BEGIN   COMMENT PRINT LYRICS TO "99 BOTTLES OF BEER ON THE WALL";   STRING FUNCTION BOTTLE(N); % GIVE CORRECT GRAMMATICAL FORM % INTEGER N; BEGIN IF N = 1 THEN BOTTLE := " BOTTLE" ELSE BOTTLE := " BOTTLES"; END;   INTEGER N;   N := 99; WHILE N > 0 DO BEGIN WRITE(N, BOTTLE(N), " OF BEER ON T...
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...
#Common_Lisp
Common Lisp
(define-condition choose-digits () ()) (define-condition bad-equation (error) ())   (defun 24-game () (let (chosen-digits) (labels ((prompt () (format t "Chosen digits: ~{~D~^, ~}~%~ Enter expression (or `bye' to quit, `!' to choose new digits): " ch...
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”,   ...
#VBA
VBA
Public Sub nine_billion_names() Dim p(25, 25) As Long p(1, 1) = 1 For i = 2 To 25 For j = 1 To i p(i, j) = p(i - 1, j - 1) + p(i - j, j) Next j Next i For i = 1 To 25 Debug.Print String$(50 - 2 * i, " "); For j = 1 To i Debug.Print String$(4 - ...
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”,   ...
#Vlang
Vlang
import math.big   fn int_min(a int, b int) int { if a < b { return a } else { return b } }   fn cumu (mut cache [][]big.Integer, n int) []big.Integer { for y := cache.len; y <= n; y++ { mut row := [big.zero_int] for x := 1; x <= y; x++ { cache_value := cache[y...
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.23
C#
using System; using System.Linq;   class Program { static void Main() { Console.WriteLine(Console.ReadLine().Split().Select(int.Parse).Sum()); } }
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 ...
#TorqueScript
TorqueScript
function ackermann(%m,%n) { if(%m==0) return %n+1; if(%m>0&&%n==0) return ackermann(%m-1,1); if(%m>0&&%n>0) return ackermann(%m-1,ackermann(%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...
#F.23
F#
let rec spell_word_with blocks w = let rec look_for_right_candidate candidates noCandidates c rest = match candidates with | [] -> false | c0::cc -> if spell_word_with (cc@noCandidates) rest then true else look_for_right_candidate cc (c0::noCandidates) c rest   m...
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...
#Common_Lisp
Common Lisp
  (defparameter *samples* 10000) (defparameter *prisoners* 100) (defparameter *max-guesses* 50)   (defun range (n) "Returns a list from 0 to N." (loop for i below n collect i))   (defun nshuffle (list) "Returns a shuffled LIST." (loop for i from (length list) downto 2 do (rotatef (nth (rando...
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 ...
#Smalltalk
Smalltalk
divisors := [:nr | |divs|   divs := Set with:1. "no need to check even factors; we are only looking for odd nrs" 3 to:(nr integerSqrt) by:2 do:[:d | nr % d = 0 ifTrue:[divs add:d; add:(nr / d)]]. divs. ].   isAbundant := [:nr | (divisors value:nr) sum > nr].   "from set ...
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 ...
#PHP
PHP
<!DOCTYPE html> <html lang="en">   <head> <meta charset="UTF-8"> <meta name="keywords" content="Game 21"> <meta name="description" content=" 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 whos...
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
#Factor
Factor
USING: continuations grouping io kernel math math.combinatorics prettyprint quotations random sequences sequences.deep ; IN: rosetta-code.24-game   : 4digits ( -- seq ) 4 9 random-integers [ 1 + ] map ;   : expressions ( digits -- exprs ) all-permutations [ [ + - * / ] 3 selections [ append ] with map ] map fla...
http://rosettacode.org/wiki/15_puzzle_game
15 puzzle game
Task Implement the Fifteen Puzzle Game. The   15-puzzle   is also known as:   Fifteen Puzzle   Gem Puzzle   Boss Puzzle   Game of Fifteen   Mystic Square   14-15 Puzzle   and some others. Related Tasks   15 Puzzle Solver   16 Puzzle Game
#11l
11l
T Puzzle position = 0 [Int = String] items   F main_frame() V& d = .items print(‘+-----+-----+-----+-----+’) print(‘|#.|#.|#.|#.|’.format(d[1], d[2], d[3], d[4])) print(‘+-----+-----+-----+-----+’) print(‘|#.|#.|#.|#.|’.format(d[5], d[6], d[7], d[8])) print(‘+-----+-----+---...
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 ...
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI */ /* program 2048.s */   /* REMARK 1 : this program use routines in a include file see task Include a file language arm assembly for the routine affichageMess conversion10 see at end of this program the instruction include */ /* for constantes see task include a file in ...
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...
#Prolog
Prolog
  :- use_module(library(clpfd)).   % main predicate my_sum(Min, Max, Top, LL):- L = [A,B,C,D,E,F,G], L ins Min..Max, ( Top == 0 -> all_distinct(L) ; true), R #= A+B, R #= B+C+D, R #= D+E+F, R #= F+G, setof(L, labeling([ff], L), LL).     my_sum_1(Min, Max) :- my_sum(Min,...
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...
#Common_Lisp
Common Lisp
;;; Using a priority queue for the A* search (eval-when (:load-toplevel :compile-toplevel :execute) (ql:quickload "pileup"))   ;; * The package definition (defpackage :15-solver (:use :common-lisp :pileup) (:export "15-puzzle-solver" "*initial-state*" "*goal-state*")) (in-package :15-solver)   ;; * Data types (de...
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...
#AmigaE
AmigaE
PROC main() DEF t: PTR TO CHAR, s: PTR TO CHAR, u: PTR TO CHAR, i, x t := 'Take one down, pass it around\n' s := '\d bottle\s of beer\s\n' u := ' on the wall' FOR i := 99 TO 0 STEP -1 ForAll({x}, [u, NIL], `WriteF(s, i, IF i <> 1 THEN 's' ELSE NIL, x)) IF i > 0 T...
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...
#D
D
import std.stdio, std.random, std.math, std.algorithm, std.range, std.typetuple;   void main() { void op(char c)() { if (stack.length < 2) throw new Exception("Wrong expression."); stack[$ - 2] = mixin("stack[$ - 2]" ~ c ~ "stack[$ - 1]"); stack.popBack(); }   cons...
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”,   ...
#Wren
Wren
import "/big" for BigInt import "/fmt" for Fmt   var cache = [[BigInt.one]] var cumu = Fn.new { |n| if (cache.count <= n) { (cache.count..n).each { |l| var r = [BigInt.zero] (1..l).each { |x| var min = l - x if (x < min) min = x r.add(r...
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.2B.2B
C++
// Standard input-output streams #include <iostream> using namespace std; int main() { int a, b; cin >> a >> b; cout << a + b << endl; }
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 ...
#TSE_SAL
TSE SAL
// library: math: get: ackermann: recursive <description></description> <version>1.0.0.0.5</version> <version control></version control> (filenamemacro=getmaare.s) [kn, ri, tu, 27-12-2011 14:46:59] INTEGER PROC FNMathGetAckermannRecursiveI( INTEGER mI, INTEGER nI ) IF ( mI == 0 ) RETURN( nI + 1 ) ENDIF IF ( nI == ...
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...
#Factor
Factor
USING: assocs combinators.short-circuit formatting grouping io kernel math math.statistics qw sequences sets unicode ; IN: rosetta-code.abc-problem   ! === CONSTANTS ================================================   CONSTANT: blocks qw{ BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM }   CONSTANT: inpu...
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...
#Cowgol
Cowgol
include "cowgol.coh"; include "argv.coh";   # Parameters const Drawers  := 100; # Amount of drawers (and prisoners) const Attempts  := 50; # Amount of attempts a prisoner may make const Simulations := 2000; # Amount of simulations to run   typedef NSim is int(0, Simulations);   # Random number generator reco...
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 ...
#Swift
Swift
extension BinaryInteger { @inlinable public func factors(sorted: Bool = true) -> [Self] { let maxN = Self(Double(self).squareRoot()) var res = Set<Self>()   for factor in stride(from: 1, through: maxN, by: 1) where self % factor == 0 { res.insert(factor) res.insert(self / factor) }   ...
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 ...
#Picat
Picat
import util.   main => N = 0, Level = prompt("Level of play (1=dumb, 3=smart)"), Algo = choosewisely, if Level == "1" then Algo := choosefoolishly elseif Level == "2" then Algo := choosesemiwisely elseif Level != "3" then println("Bad choice syntax--default to smart choic...
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
#Fortran
Fortran
program solve_24 use helpers implicit none real :: vector(4), reals(4), p, q, r, s integer :: numbers(4), n, i, j, k, a, b, c, d character, parameter :: ops(4) = (/ '+', '-', '*', '/' /) logical :: last real,parameter :: eps = epsilon(1.0)   do n=1,12 ...
http://rosettacode.org/wiki/15_puzzle_game
15 puzzle game
Task Implement the Fifteen Puzzle Game. The   15-puzzle   is also known as:   Fifteen Puzzle   Gem Puzzle   Boss Puzzle   Game of Fifteen   Mystic Square   14-15 Puzzle   and some others. Related Tasks   15 Puzzle Solver   16 Puzzle Game
#68000_Assembly
68000 Assembly
;15 PUZZLE GAME ;Ram Variables Cursor_X equ $00FF0000 ;Ram for Cursor Xpos Cursor_Y equ $00FF0000+1 ;Ram for Cursor Ypos joypad1 equ $00FF0002   GameRam equ $00FF1000 ;Ram for where the pieces are GameRam_End equ $00FF100F ;the last valid slot in the array ;Video Ports VDP_data EQU $C00000 ; VDP data, R/W word or lon...
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 ...
#AutoHotkey
AutoHotkey
Grid := [], s := 16, w := h := S * 4.5 Gui, font, s%s% Gui, add, text, y1 loop, 4 { row := A_Index loop, 4 { col := A_Index if col = 1 Gui, add, button, v%row%_%col% xs y+1 w%w% h%h% -TabStop, % Grid[row,col] := 0 else Gui, add, button, v%row%_%col% x+1 yp w%w% h%h% -TabStop, % Grid[row,col] := 0 } }...
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...
#Python
Python
import itertools   def all_equal(a,b,c,d,e,f,g): return a+b == b+c+d == d+e+f == f+g   def foursquares(lo,hi,unique,show): solutions = 0 if unique: uorn = "unique" citer = itertools.combinations(range(lo,hi+1),7) else: uorn = "non-unique" citer = itertools.combinations_w...
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...
#F.23
F#
  // A Naive 15 puzzle solver using no memory. Nigel Galloway: October 6th., 2017 let Nr,Nc = [|3;0;0;0;0;1;1;1;1;2;2;2;2;3;3;3|],[|3;0;1;2;3;0;1;2;3;0;1;2;3;0;1;2|] type G= |N |I |G |E |L type N={i:uint64;g:G list;e:int;l:int} let fN n=let g=(11-n.e)*4 in let a=n.i&&&(15UL<<<g) {i=n.i-a+(a<<<16);g=N:...
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...
#Apache_Ant
Apache Ant
<?xml version="1.0"?> <project name="n bottles" default="99_bottles">   <!-- ant-contrib.sourceforge.net for arithmetic and if --> <taskdef resource="net/sf/antcontrib/antcontrib.properties"/>   <!-- start count of bottles, you can set this with e.g. ant -f 99.xml -Dcount=10 --> <property name="count" value...
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...
#EchoLisp
EchoLisp
  (string-delimiter "") ;; check that nums are in expr, and only once (define (is-valid? expr sorted: nums) (when (equal? 'q expr) (error "24-game" "Thx for playing")) (unless (and (list? expr) (equal? nums (list-sort < (filter number? (flatten expr))))) (writeln "🎃 Please use" nums) ...
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”,   ...
#Yabasic
Yabasic
clear screen   Sub nine_billion_names(rows) local p(rows, rows), i, j, column   p(1, 1) = 1   For i = 2 To rows For j = 1 To i p(i, j) = p(i - 1, j - 1) + p(i - j, j) Next j Next i For i = 1 To rows column = rows * 2 - 2 * i - 2 For j = 1 To i ...
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”,   ...
#zkl
zkl
var [const] BN=Import.lib("zklBigNum");   const N=0d100_000; p:=List.createLong(N+1,BN.fp(0),True); // (0,0,...) all different   fcn calc(n,p){ p[n].set(0); // reset array for each run foreach k in ([1..n]){ d:=n - k *(3*k - 1)/2; do(2){ if (d<0) break(2); if (k.isOdd) p[n].add(p[d]); e...
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 ≤...
#Ceylon
Ceylon
shared void run() {   print("please enter two numbers for me to add"); value input = process.readLine(); if (exists input) { value tokens = input.split().map(Integer.parse); if (tokens.any((element) => element is ParseException)) { print("numbers only, please"); retur...
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 ...
#TXR
TXR
(defmacro defmemofun (name (. args) . body) (let ((hash (gensym "hash-")) (argl (gensym "args-")) (hent (gensym "hent-")) (uniq (copy-str "uniq"))) ^(let ((,hash (hash :equal-based))) (defun ,name (,*args) (let* ((,argl (list ,*args)) (,hent (inhash ,hash ,a...
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...
#FBSL
FBSL
  #APPTYPE CONSOLE SUB MAIN() BlockCheck("A") BlockCheck("BARK") BlockCheck("BooK") BlockCheck("TrEaT") BlockCheck("comMON") BlockCheck("sQuAd") BlockCheck("Confuse") pause END SUB   FUNCTION BlockCheck(str) PRINT str " " iif( Blockable( str ), "can", "cannot" ) " be spelled with blocks." END FUNCTION   FUNCTI...
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...
#Crystal
Crystal
prisoners = (1..100).to_a N = 100_000 generate_rooms = ->{ (1..100).to_a.shuffle }   res = N.times.count do rooms = generate_rooms.call prisoners.all? { |pr| rooms[1, 100].sample(50).includes?(pr) } end puts "Random strategy : %11.4f %%" % (res.fdiv(N) * 100)   res = N.times.count do rooms = generate_rooms.call ...
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 ...
#Visual_Basic_.NET
Visual Basic .NET
Module AbundantOddNumbers ' find some abundant odd numbers - numbers where the sum of the proper ' divisors is bigger than the number ' itself   ' returns the sum of the proper divisors of n Private Function divisorSum(n As Integer) A...
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 ...
#Python
Python
  from random import randint def start(): game_count=0 print("Enter q to quit at any time.\nThe computer will choose first.\nRunning total is now {}".format(game_count)) roundno=1 while game_count<21: print("\nROUND {}: \n".format(roundno)) t = select_count(game_count) game_count = game_count+t print("Runni...
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
#GAP
GAP
# Solution in '''RPN''' check := function(x, y, z) local r, c, s, i, j, k, a, b, p; i := 0; j := 0; k := 0; s := [ ]; r := ""; for c in z do if c = 'x' then i := i + 1; k := k + 1; s[k] := x[i]; Append(r, String(x[i])); else j := j + 1; b := s[k]; k := k - 1; a := s[k]; p := y[j]; ...
http://rosettacode.org/wiki/15_puzzle_game
15 puzzle game
Task Implement the Fifteen Puzzle Game. The   15-puzzle   is also known as:   Fifteen Puzzle   Gem Puzzle   Boss Puzzle   Game of Fifteen   Mystic Square   14-15 Puzzle   and some others. Related Tasks   15 Puzzle Solver   16 Puzzle Game
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program puzzle15_64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesAR...
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 ...
#Batch_File
Batch File
:: 2048 Game Task from RosettaCode :: Batch File Implementation v2.0.1   @echo off setlocal enabledelayedexpansion rem initialization :begin_game set "size=4" %== board size ==% set "score=0" %== current score ==% set "won=0" %== boolean for winning ==% set "target=2048" %== as the game title says ==% for /l %...
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...
#R
R
# 4 rings or 4 squares puzzle   perms <- function (n, r, v = 1:n, repeats.allowed = FALSE) { if (repeats.allowed) sub <- function(n, r, v) { if (r == 1) matrix(v, n, 1) else if (n == 1) matrix(v, 1, r) else { inner <- Recall(n, r - 1, v) cbind(rep(v, rep(nrow(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...
#Forth
Forth
  #! /usr/bin/gforth   cell 8 <> [if] s" 64-bit system required" exception throw [then]   \ In the stack comments below, \ "h" stands for the hole position (0..15), \ "s" for a 64-bit integer representing a board state, \ "t" a tile value (0..15, 0 is the hole), \ "b" for a bit offset of a position within a state, \ "m...
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...
#Apex
Apex
  for(Integer i = 99; i=0; i--){ system.debug(i + ' bottles of beer on the wall'); system.debug('\n'); system.debug(i + ' bottles of beer on the wall'); system.debug(i + ' bottles of beer'); system.debug('take one down, pass it around'); }  
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...
#Elena
Elena
import system'routines; import system'collections; import system'dynamic; import extensions;   // --- Expression ---   class ExpressionTree { object theTree;   constructor(s) { auto level := new Integer(0);   s.forEach:(ch) { var node := new DynamicStruct();   ...
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 ≤...
#Clojure
Clojure
(println (+ (Integer/parseInt (read-line)) (Integer/parseInt (read-line)))) 3 4 =>7
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 ...
#UNIX_Shell
UNIX Shell
ack() { local m=$1 local n=$2 if [ $m -eq 0 ]; then echo -n $((n+1)) elif [ $n -eq 0 ]; then ack $((m-1)) 1 else ack $((m-1)) $(ack $m $((n-1))) fi }
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...
#Forth
Forth
: blockslist s" BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM" ; variable blocks : allotblocks ( -- ) here blockslist dup allot here over - swap move blocks ! ; : freeblocks blockslist nip negate allot ; : toupper 223 and ;   : clearblock ( addr-block -- ) dup '_' swap c! dup blocks @ - 1 and if 1- else 1+ then '_' swap c!...
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...
#D
D
import std.array; import std.random; import std.range; import std.stdio; import std.traits;   bool playOptimal() { auto secrets = iota(100).array.randomShuffle();   prisoner: foreach (p; 0..100) { auto choice = p; foreach (_; 0..50) { if (secrets[choice] == p) continue prisoner; ...
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 ...
#Vlang
Vlang
fn divisors(n i64) []i64 { mut divs := [i64(1)] mut divs2 := []i64{} for i := 2; i*i <= n; i++ { if n%i == 0 { j := n / i divs << i if i != j { divs2 << j } } } for i := divs2.len - 1; i >= 0; i-- { divs << divs2...
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 ...
#Quackery
Quackery
[ say "Who goes first: Computer, Player" say " or Random?" cr [ $ "Enter C, P or R: " input dup size 1 != iff drop again 0 peek dup char C = iff [ drop 0 ] done dup char P = iff [ drop 1 ] done char R = iff [ 2 random ] done again ] cr dup iff [ say "You go fi...
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
#Go
Go
package main   import ( "fmt" "math/rand" "time" )   const ( op_num = iota op_add op_sub op_mul op_div )   type frac struct { num, denom int }   // Expression: can either be a single number, or a result of binary // operation from left and right node type Expr struct { op int left, right *Expr valu...
http://rosettacode.org/wiki/15_puzzle_game
15 puzzle game
Task Implement the Fifteen Puzzle Game. The   15-puzzle   is also known as:   Fifteen Puzzle   Gem Puzzle   Boss Puzzle   Game of Fifteen   Mystic Square   14-15 Puzzle   and some others. Related Tasks   15 Puzzle Solver   16 Puzzle Game
#Action.21
Action!
DEFINE BOARDSIZE="16" DEFINE X0="13" DEFINE Y0="6" DEFINE ITEMW="3" DEFINE ITEMH="2"   BYTE ARRAY board(BOARDSIZE) BYTE emptyX,emptyY,solved,first=[1]   BYTE FUNC Index(BYTE x,y) RETURN (x+y*4)   PROC UpdateItem(BYTE x,y) BYTE item   Position(X0+x*ITEMW+1,Y0+y*ITEMH+1) item=board(Index(x,y)) IF item=0 THEN ...
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 ...
#BASIC
BASIC
  SCREEN 13 PALETTE 1, pColor(35, 33, 31) PALETTE 2, pColor(46, 46, 51) PALETTE 3, pColor(59, 56, 50) PALETTE 4, pColor(61, 44, 30) PALETTE 5, pColor(61, 37, 25) PALETTE 6, pColor(62, 31, 24) PALETTE 7, pColor(62, 24, 15) PALETTE 8, pColor(59, 52, 29) PALETTE 9, pColor(59, 51, 24) PALETTE 10, pColor(59, 50, 20) PALETTE...
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...
#Racket
Racket
#lang racket   (define solution? (match-lambda [(list a b c d e f g) (= (+ a b) (+ b c d) (+ d e f) (+ f g))]))   (define (fold-4-rings-or-4-squares-puzzle lo hi kons k0) (for*/fold ((k k0)) ((combination (in-combinations (range lo (add1 hi)) 7)) (permutation (in-permutations combination)) ...
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...
#Fortran
Fortran
59: H = MOD(ABS(PRODUCT(BRD)),APRIME) 004016E3 mov esi,1 004016E8 mov ecx,1 004016ED cmp ecx,2 004016F0 jg MAIN$SLIDESOLVE+490h (0040171e) 004016F2 cmp ecx,1 004016F5 jl MAIN$SLIDESOLVE+46Eh (004016fc) 004016F7 cmp ecx,2 004016FA jle ...
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...
#APL
APL
bob ← { (⍕⍵), ' bottle', (1=⍵)↓'s of beer'} bobw ← {(bob ⍵) , ' on the wall'} beer ← { (bobw ⍵) , ', ', (bob ⍵) , '; take one down and pass it around, ', bobw ⍵-1}
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...
#Elixir
Elixir
defmodule Game24 do def main do IO.puts "24 Game" play end   defp play do IO.puts "Generating 4 digits..." digts = for _ <- 1..4, do: Enum.random(1..9) IO.puts "Your digits\t#{inspect digts, char_lists: :as_lists}" read_eval(digts) play end   defp read_eval(digits) do exp = IO....
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 ≤...
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. A-Plus-B.   DATA DIVISION. WORKING-STORAGE SECTION. 01 A PIC S9(5). 01 B PIC S9(5).   01 A-B-Sum PIC S9(5).   PROCEDURE DIVISION. ACCEPT A ACCEPT B   ADD A TO B GIVING A-B-Sum   ...
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 ...
#Ursala
Ursala
#import std #import nat   ackermann =   ~&al^?\successor@ar ~&ar?( ^R/~&f ^/predecessor@al ^|R/~& ^|/~& predecessor, ^|R/~& ~&\1+ predecessor@l)
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...
#Fortran
Fortran
!-*- mode: compilation; default-directory: "/tmp/" -*- !Compilation started at Thu Jun 5 01:52:03 ! !make f && for a in '' a bark book treat common squad confuse ; do echo $a | ./f ; done !gfortran -std=f2008 -Wall -fopenmp -ffree-form -fall-intrinsics -fimplicit-none -g f.f08 -o f ! T ! T A ...
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...
#Delphi
Delphi
for i range 100 drawer[] &= i sampler[] &= i . subr shuffle_drawer for i = len drawer[] downto 2 r = random i swap drawer[r] drawer[i - 1] . . subr play_random call shuffle_drawer found = 1 prisoner = 0 while prisoner < 100 and found = 1 found = 0 i = 0 while i < 50 and found = 0 ...
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 ...
#Wren
Wren
import "/fmt" for Fmt import "/math" for Int, Nums   var sumStr = Fn.new { |divs| divs.reduce("") { |acc, div| acc + "%(div) + " }[0...-3] }   var abundantOdd = Fn.new { |searchFrom, countFrom, countTo, printOne| var count = countFrom var n = searchFrom while (count < countTo) { var divs = Int.prope...
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 ...
#R
R
game21<-function(first = c("player","ai","random"),sleep=.5){ state = 0 finished = F turn = 1 if(length(first)==1 && startsWith(tolower(first),"r")){ first = rbinom(1,1,.5) }else{ first = (length(first)>1 || startsWith(tolower(first),"p")) } while(!finished){ if(turn>1 || first){ cat("Th...
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
#Gosu
Gosu
  uses java.lang.Integer uses java.lang.Double uses java.lang.System uses java.util.ArrayList uses java.util.LinkedList uses java.util.List uses java.util.Scanner uses java.util.Stack   function permutations<T>( lst : List<T> ) : List<List<T>> { if( lst.size() == 0 ) return {} if( lst.size() == 1 ) return { lst...
http://rosettacode.org/wiki/15_puzzle_game
15 puzzle game
Task Implement the Fifteen Puzzle Game. The   15-puzzle   is also known as:   Fifteen Puzzle   Gem Puzzle   Boss Puzzle   Game of Fifteen   Mystic Square   14-15 Puzzle   and some others. Related Tasks   15 Puzzle Solver   16 Puzzle Game
#Ada
Ada
generic Rows, Cols: Positive; with function Name(N: Natural) return String; -- with Pre => (N < Rows*Cols); -- Name(0) shall return the name for the empty tile package Generic_Puzzle is   subtype Row_Type is Positive range 1 .. Rows; subtype Col_Type is Positive range 1 .. Cols; type Moves is (Up, Dow...
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 ...
#BBC_BASIC
BBC BASIC
SIZE = 4  : MAX = SIZE-1 Won% = FALSE : Lost% = FALSE @% = 5 DIM Board(MAX,MAX),Stuck% 3   PROCBreed PROCPrint REPEAT Direction = GET-135 IF Direction > 0 AND Direction < 5 THEN Moved% = FALSE PROCShift PROCMerge PROCSh...
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...
#Raku
Raku
sub four-squares ( @list, :$unique=1, :$show=1 ) {   my @solutions;   for $unique.&combos -> @c { @solutions.push: @c if [==] @c[0] + @c[1], @c[1] + @c[2] + @c[3], @c[3] + @c[4] + @c[5], @c[5] + @c[6]; }   say +@solutions, ($unique ?? ' ' !! ' non-'), "uni...
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...
#Go
Go
package main   import "fmt"   var ( Nr = [16]int{3, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3} Nc = [16]int{3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2} )   var ( n, _n int N0, N3, N4 [85]int N2 [85]uint64 )   const ( i = 1 g = 8 e = 2 l = 4 )   func fY() bool { ...
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...
#App_Inventor
App Inventor
repeat with beerCount from 99 to 1 by -1 set bottles to "bottles" if beerCount < 99 then if beerCount = 1 then set bottles to "bottle" end log "" & beerCount & " " & bottles & " of beer on the wall" log "" end log "" & beerCount & " " & bottles & " of beer on the wall" log "" & beerCount...
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...
#Erlang
Erlang
-module(g24). -export([main/0]).   main() -> random:seed(now()), io:format("24 Game~n"), play().   play() -> io:format("Generating 4 digits...~n"), Digts = [random:uniform(X) || X <- [9,9,9,9]], io:format("Your digits\t~w~n", [Digts]), read_eval(Digts), play().   read_eval(Digits) -> ...
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 ≤...
#CoffeeScript
CoffeeScript
<html> <script type="text/javascript" src="http://jashkenas.github.com/coffee-script/extras/coffee-script.js"></script> <script type="text/coffeescript"> a = window.prompt 'enter A number', '' b = window.prompt 'enter B number', '' document.getElementById('input').innerHTML = a + ' ' + b sum = parseInt(a) + parseInt(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 ...
#V
V
[ack [ [pop zero?] [popd succ] [zero?] [pop pred 1 ack] [true] [[dup pred swap] dip pred ack ack ] ] when].
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...
#FreeBASIC
FreeBASIC
' version 28-01-2019 ' compile with: fbc -s console   Dim As String blocks(1 To 20, 1 To 2) => {{"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"}, {"...
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...
#EasyLang
EasyLang
for i range 100 drawer[] &= i sampler[] &= i . subr shuffle_drawer for i = len drawer[] downto 2 r = random i swap drawer[r] drawer[i - 1] . . subr play_random call shuffle_drawer found = 1 prisoner = 0 while prisoner < 100 and found = 1 found = 0 i = 0 while i < 50 and found = 0 ...
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 ...
#X86_Assembly
X86 Assembly
.model tiny .code .486 org 100h ;ebp=counter, edi=Num, ebx=Div, esi=Sum start: xor ebp, ebp ;odd abundant number counter:= 0 mov edi, 3 ;Num:= 3 ab10: mov ebx, 3 ;Div:= 3 mov esi, 1 ;Sum:= 1 ab20: mov eax, ed...
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 ...
#Racket
Racket
#lang racket   (define limit 21) (define max-resp 3)   (define (get-resp) (let loop () (match (read-line) [(app (conjoin string? string->number) n) #:when (and (exact-integer? n) (<= 1 n max-resp)) n] ["q" (exit)] [n (printf "~a is not in range 1 and ~a\n" n max-resp) (loo...
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
#Haskell
Haskell
import Data.List import Data.Ratio import Control.Monad import System.Environment (getArgs)   data Expr = Constant Rational | Expr :+ Expr | Expr :- Expr | Expr :* Expr | Expr :/ Expr deriving (Eq)   ops = [(:+), (:-), (:*), (:/)]   instance Show Expr where show (Constant x) = show $ numerator x -...
http://rosettacode.org/wiki/15_puzzle_game
15 puzzle game
Task Implement the Fifteen Puzzle Game. The   15-puzzle   is also known as:   Fifteen Puzzle   Gem Puzzle   Boss Puzzle   Game of Fifteen   Mystic Square   14-15 Puzzle   and some others. Related Tasks   15 Puzzle Solver   16 Puzzle Game
#APL
APL
fpg←{⎕IO←0 ⍺←4 4 (s∨.<0)∨2≠⍴s←⍺:'invalid shape:'s 0≠⍴⍴⍵:'invalid shuffle count:'⍵ d←d,-d←↓2 2⍴3↑1 e←¯1+⍴c←'↑↓←→○' b←w←s⍴w←1⌽⍳×/s z←⊃{ z p←⍵ n←(?⍴p)⊃p←(p≡¨(⊂s)|p)/p←(d~p)+⊂z b[z n]←b[n z] -⍨\n z }⍣⍵⊢(s-1)0 ⎕←b ⍬{ b≡w:'win' 0=⍴⍺:⍞∇ ⍵ ...
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 ...
#C
C
  #include <stdio.h> #include <stdlib.h> #include <string.h> #include <termios.h> #include <time.h> #include <unistd.h>   #define D_INVALID -1 #define D_UP 1 #define D_DOWN 2 #define D_RIGHT 3 #define D_LEFT 4   const long values[] = { 0, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048 };   const ch...
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...
#REXX
REXX
/*REXX pgm solves the 4-rings puzzle, where letters represent unique (or not) digits). */ arg LO HI unique show . /*the ARG statement capitalizes args.*/ if LO=='' | LO=="," then LO=1 /*Not specified? Then use the default.*/ if HI=='' | HI=="," then HI=7 ...
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...
#Julia
Julia
const Nr = [3, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3] const Nc = [3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2]   const N0 = zeros(Int, 85) const N2 = zeros(UInt64, 85) const N3 = zeros(UInt8, 85) const N4 = zeros(Int, 85) const i = 1 const g = 8 const ee = 2 const l = 4 const _n = Vector{Int32}([0])   function...
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...
#AppleScript
AppleScript
repeat with beerCount from 99 to 1 by -1 set bottles to "bottles" if beerCount < 99 then if beerCount = 1 then set bottles to "bottle" end log "" & beerCount & " " & bottles & " of beer on the wall" log "" end log "" & beerCount & " " & bottles & " of beer on the wall" log "" & beerCount...
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...
#F.23
F#
open System open System.Text.RegularExpressions   // Some utilities let (|Parse|_|) regex str = let m = Regex(regex).Match(str) if m.Success then Some ([for g in m.Groups -> g.Value]) else None 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 le...
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 ≤...
#Common_Lisp
Common Lisp
(write (+ (read) (read)))
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 ...
#Vala
Vala
uint64 ackermann(uint64 m, uint64 n) { if (m == 0) return n + 1; if (n == 0) return ackermann(m - 1, 1); return ackermann(m - 1, ackermann(m, n - 1)); }   void main () { for (uint64 m = 0; m < 4; ++m) { for (uint64 n = 0; n < 10; ++n) { print(@"A($m,$n) = $(ackermann(m,n))\n"); } } }
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...
#Gambas
Gambas
Public Sub Main() Dim sCheck As String[] = ["A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "CONFUSE"] Dim sBlock As String[] = ["BO", "XK", "DQ", "CP", "NA", "GT", "RE", "TG", "QD", "FS", "JW", "HU", "VI", "AN", "OB", "ER", "FS", "LY", "PC", "ZM"] Dim sList As New String[] Dim siCount, siLoop As Short Dim sTemp, sAns...
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...
#Elixir
Elixir
defmodule HundredPrisoners do def optimal_room(_, _, _, []), do: [] def optimal_room(prisoner, current_room, rooms, [_ | tail]) do found = Enum.at(rooms, current_room - 1) == prisoner next_room = Enum.at(rooms, current_room - 1) [found] ++ optimal_room(prisoner, next_room, rooms, tail) end   def opt...
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 ...
#XPL0
XPL0
int Cnt, Num, Div, Sum, Quot; [Cnt:= 0; Num:= 3; \find odd abundant numbers loop [Div:= 1; Sum:= 0; loop [Quot:= Num/Div; if Div > Quot then quit; if rem(0) = 0 then [Sum:= Sum + Div; if Div # Quot then Sum:= Sum + Quot...
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 ...
#Raku
Raku
say qq :to '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; loop { say "Running total is: $total"; my ($me,$comp); loop { $me = prompt '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
#Icon_and_Unicon
Icon and Unicon
invocable all link strings # for csort, deletec, permutes   procedure main() static eL initial { eoP := [] # set-up expression and operator permutation patterns every ( e := !["a@b#c$d", "a@(b#c)$d", "a@b#(c$d)", "a@(b#c$d)", "a@(b#(c$d))"] ) & ( o := !(opers := "+-*/") || !opers || !opers ) do ...
http://rosettacode.org/wiki/15_puzzle_game
15 puzzle game
Task Implement the Fifteen Puzzle Game. The   15-puzzle   is also known as:   Fifteen Puzzle   Gem Puzzle   Boss Puzzle   Game of Fifteen   Mystic Square   14-15 Puzzle   and some others. Related Tasks   15 Puzzle Solver   16 Puzzle Game
#ARM_Assembly
ARM Assembly
    /* ARM assembly Raspberry PI */ /* program puzzle15.s */   /************************************/ /* Constantes */ /************************************/ .equ STDIN, 0 @ Linux input console .equ STDOUT, 1 @ Linux output console .equ EXIT, 1 @ Linux syscall .equ READ, 3 ...
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 ...
#C.23
C#
using System;   namespace g2048_csharp { internal class Tile { public Tile() { Value = 0; IsBlocked = false; }   public int Value { get; set; } public bool IsBlocked { get; set; } }   internal enum MoveDirection { Up, Do...
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...
#Ruby
Ruby
def four_squares(low, high, unique=true, show=unique) f = -> (a,b,c,d,e,f,g) {[a+b, b+c+d, d+e+f, f+g].uniq.size == 1} if unique uniq = "unique" solutions = [*low..high].permutation(7).select{|ary| f.call(*ary)} else uniq = "non-unique" solutions = [*low..high].repeated_permutation(7).select{|ary|...
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...
#Lua
Lua
  #!/usr/bin/lua --[[ Solve 3X3 sliding tile puzzle using Astar on Lua. Requires 3mb and millions of recursions. by RMM 2020-may-1 ]]--   local SOLUTION_LIMIT, MAX_F_VALUE = 100,100 local NR, NC, RCSIZE = 4,4,4*4 local Up, Down, Right, Left = 'u','d','r','l' local G_cols = {} -- goal columns local G_rows = {} -- goa...
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...
#Arbre
Arbre
  bottle(x): template: ' $x bottles of beer on the wall. $x bottles of beer. Take one down and pass it around, $y bottles of beer on the wall. '   if x==0 template~{x: 'No more', y: 'No more'} else if x==1 template~{x: x, y: 'No more'} else template~{x: x, y: x-1}   bottles(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...
#Factor
Factor
USING: combinators.short-circuit continuations eval formatting fry kernel io math math.ranges prettyprint random sequences sets ; IN: 24game   : choose4 ( -- seq ) 4 [ 9 [1,b] random ] replicate ;   : step ( numbers -- ? ) readln [ parse-string ...
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 ≤...
#Component_Pascal
Component Pascal
  MODULE AB; IMPORT StdLog, DevCommanders,TextMappers;   PROCEDURE DoAB(x,y: INTEGER); BEGIN StdLog.Int(x);StdLog.Int(y);StdLog.Int(x + y);StdLog.Ln; END DoAB;   PROCEDURE Go*; VAR params: DevCommanders.Par; s: TextMappers.Scanner; p : ARRAY 2 OF INTEGER; ...