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/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 ...
#VBA
VBA
Private Function Ackermann_function(m As Variant, n As Variant) As Variant Dim result As Variant Debug.Assert m >= 0 Debug.Assert n >= 0 If m = 0 Then result = CDec(n + 1) Else If n = 0 Then result = Ackermann_function(m - 1, 1) Else result = Ackermann...
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...
#Go
Go
package main   import ( "fmt" "strings" )   func newSpeller(blocks string) func(string) bool { bl := strings.Fields(blocks) return func(word string) bool { return r(word, bl) } }   func r(word string, bl []string) bool { if word == "" { return true } c := word[0] | 32 for i, b := range bl { if c == b[0]|...
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...
#F.23
F#
let rnd = System.Random() let shuffled min max = [|min..max|] |> Array.sortBy (fun _ -> rnd.Next(min,max+1))   let drawers () = shuffled 1 100   // strategy randomizing drawer opening let badChoices (drawers' : int array) = Seq.init 100 (fun _ -> shuffled 1 100 |> Array.take 50) // selections for each 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 ...
#zkl
zkl
fcn oddAbundants(startAt=3){ //--> iterator Walker.zero().tweak(fcn(rn){ n:=rn.value; while(True){ sum:=0; foreach d in ([3.. n.toFloat().sqrt().toInt(), 2]){ if( (y:=n/d) *d != n) continue; sum += ((y==d) and y or y+d) } if(sum>n){ rn.set(n+2); return(n) } n+=2; } }.fp(Ref(...
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 ...
#REXX
REXX
/*REXX program plays the 21 game with a human, each player chooses 1, 2, or 3 which */ /*──────────── is added to the current sum, the first player to reach 21 exactly wins.*/ sep= copies('─', 8); sep2= " "copies('═', 8)" " /*construct an eye─catching msg fences.*/ say sep 'Playing the 21 game.' ...
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
#J
J
perm=: (A.&i.~ !) 4 ops=: ' ',.'+-*%' {~ >,{i.each 4 4 4 cmask=: 1 + 0j1 * i.@{:@$@[ e. ] left=: [ #!.'('~"1 cmask right=: [ #!.')'~"1 cmask paren=: 2 :'[: left&m right&n' parens=: ], 0 paren 3, 0 paren 5, 2 paren 5, [: 0 paren 7 (0 paren 3) all=: [: parens [:,/ ops ,@,."1/ perm { [:;":each answer=: ({.@#~ 24 = ".)@al...
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
#Astro
Astro
type Puzzle(var items: {}, var position: -1)   fun mainframe(puz): let d = puz.items print('+-----+-----+-----+-----+') print(d[1], d[2], d[3], d[4], first: '|', sep: '|', last: '|') print('+-----+-----+-----+-----+') print(d[5], d[6], d[7], d[8], first: '|', sep: '|', last: '|') 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 ...
#C.2B.2B
C++
  #include <time.h> #include <iostream> #include <string> #include <iomanip> #include <cstdlib>   typedef unsigned int uint; using namespace std; enum movDir { UP, DOWN, LEFT, RIGHT };   class tile { public: tile() : val( 0 ), blocked( false ) {} uint val; bool blocked; };   class g2048 { public: g2048(...
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...
#Rust
Rust
  #![feature(inclusive_range_syntax)]   fn is_unique(a: u8, b: u8, c: u8, d: u8, e: u8, f: u8, g: u8) -> bool { a != b && a != c && a != d && a != e && a != f && a != g && b != c && b != d && b != e && b != f && b != g && c != d && c != e && c != f && c != g && d != e && d != f && d != g && e != f &...
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...
#Nim
Nim
  # 15 puzzle.   import strformat import times   const 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]   type   Solver = object n: int np: int n0: array[100, int] n2: array[100, uint64] n3: array[100, char] n4: array[100, int]   ...
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...
#Argile
Argile
use std   let X be an int for each X from 99 down to 1 prints X bottles of beer on the wall prints X bottles of beer prints "Take one down, pass it" around if X == 1 echo No more "beer." Call da "amber lamps" break X-- prints X bottles of beer on the wall "\n" X++ .:around :. -> text {X>59 ? "ar...
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...
#Falcon
Falcon
load compiler   function genRandomNumbers( amount ) rtn = [] for i in [ 0 : amount ]: rtn += random( 1, 9 ) return( rtn ) end   function getAnswer( exp ) ic = ICompiler() ic.compileAll(exp)   return( ic.result ) end   function validInput( str ) for i in [ 0 : str.len() ] if str[i] notin ' ()[]01234567...
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 ≤...
#Computer.2Fzero_Assembly
Computer/zero Assembly
STP  ; wait for input a: 0 b: 0 LDA a ADD b STP
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 ...
#VBScript
VBScript
option explicit '~ dim depth function ack(m, n) '~ wscript.stdout.write depth & " " if m = 0 then '~ depth = depth + 1 ack = n + 1 '~ depth = depth - 1 elseif m > 0 and n = 0 then '~ depth = depth + 1 ack = ack(m - 1, 1) '~ depth = depth - 1 '~ elseif m > 0 and n > 0 then else '~ depth = depth + 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...
#Groovy
Groovy
class ABCSolver { def blocks   ABCSolver(blocks = []) { this.blocks = blocks }   boolean canMakeWord(rawWord) { if (rawWord == '' || rawWord == null) { return true; } def word = rawWord.toUpperCase() def blocksLeft = [] + blocks word.every { letter -> blocksLeft.remove(blocks...
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...
#Factor
Factor
USING: arrays formatting fry io kernel math random sequences ;   : setup ( -- seq seq ) 100 <iota> dup >array randomize ;   : rand ( -- ? ) setup [ 50 sample member? not ] curry find nip >boolean not ;   : trail ( m seq -- n ) 50 pick '[ [ nth ] keep over _ = ] replicate [ t = ] any? 2nip ;   : optimal ( --...
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 ...
#Ring
Ring
  # Project : 21 Game   load "guilib.ring"   limit = 21 posold = 0 button = list(limit) mynum = list(3) yournum = list(3)   new qapp { win1 = new qwidget() { setwindowtitle("21 Game") setgeometry(100,100,1000,600) label1 = new qlabel(win1) { ...
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
#Java
Java
import java.util.*;   public class Game24Player { final String[] patterns = {"nnonnoo", "nnonono", "nnnoono", "nnnonoo", "nnnnooo"}; final String ops = "+-*/^";   String solution; List<Integer> digits;   public static void main(String[] args) { new Game24Player().play(); }   ...
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
#AutoHotkey
AutoHotkey
Size := 20 Grid := [], Deltas := ["-1,0","1,0","0,-1","0,1"], Width := Size * 2.5 Gui, font, S%Size% Gui, add, text, y1 loop, 4 { Row := A_Index loop, 4 { Col := A_Index Gui, add, button, % (Col=1 ? "xs y+1" : "x+1 yp") " v" Row "_" Col " w" Width " gButton -TabStop", % Grid[Row,Col] := Col + (Row-1)*4 ; 1-16 }...
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 ...
#Clojure
Clojure
  (ns 2048 (:require [clojure.string :as str]))   ;Preferences (def textures {:wall "----+"  :cell "%4s|"  :cell-edge "|"  :wall-edge "+"})   (def directions {:w :up  :s :down  :a :left  :d :right})   (def field-size {...
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...
#Scala
Scala
object FourRings {   def fourSquare(low: Int, high: Int, unique: Boolean, print: Boolean): Unit = { def isValid(needle: Integer, haystack: Integer*) = !unique || !haystack.contains(needle)   if (print) println("a b c d e f g")   var count = 0 for { a <- low to high b <- low to high if isVa...
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...
#Pascal
Pascal
  unit FifteenSolverT; \\ Solve 15 Puzzle. Nigel Galloway; February 1st., 2019. interface type TN=record n:UInt64; i,g,e,l:shortint; end; type TG=record found:boolean; path:array[0..99] of TN; end; function solve15(const board : UInt64; const bPos:shortint; const d:shortint; const ng:shortint):TG; const endPos:UInt64=$...
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...
#ARM_Assembly
ARM Assembly
IT'S SHOWTIME HEY CHRISTMAS TREE is0 YOU SET US UP @NO PROBLEMO HEY CHRISTMAS TREE bottles YOU SET US UP 99 STICK AROUND is0 TALK TO THE HAND bottles TALK TO THE HAND " bottles of beer on the wall" TALK TO THE HAND bottles TALK TO THE HAND " bottles of beer" TALK TO THE HAND "Take one down, pass it around" GET TO THE C...
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...
#Fortran
Fortran
program game_24 implicit none real :: vector(4), reals(11), result, a, b, c, d integer :: numbers(4), ascii(11), i character(len=11) :: expression character :: syntax(11) ! patterns: character, parameter :: one(11) = (/ '(','(','1','x','1',')','x','1',')','x','1' /) ...
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 ≤...
#Crystal
Crystal
puts gets.not_nil!.split.map(&.to_i).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 ...
#Visual_Basic
Visual Basic
  Option Explicit Dim calls As Long Sub main() Const maxi = 4 Const maxj = 9 Dim i As Long, j As Long For i = 0 To maxi For j = 0 To maxj Call print_acker(i, j) Next j Next i End Sub 'main Sub print_acker(m As Long, n As Long) calls = 0 Debug.Print "ackermann("; m...
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...
#Harbour
Harbour
PROCEDURE Main()   LOCAL cStr   FOR EACH cStr IN { "A", "BARK", "BooK", "TrEaT", "comMON", "sQuAd", "Confuse" } ? PadL( cStr, 10 ), iif( Blockable( cStr ), "can", "cannot" ), "be spelled with blocks." NEXT   RETURN   STATIC FUNCTION Blockable( cStr )   LOCAL blocks := { ; "BO", "XK", "DQ", "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...
#FOCAL
FOCAL
01.10 T %5.02," RANDOM";S CU=0 01.20 F Z=1,2000;D 5;S CU=CU+SU 01.30 T CU/20,!,"OPTIMAL";S CU=0 01.40 F Z=1,2000;D 6;S CU=CU+SU 01.50 T CU/20,! 01.60 Q   02.01 C-- PUT CARDS IN RANDOM DRAWERS 02.10 F X=1,100;S D(X)=X 02.20 F X=1,99;D 2.3;S B=D(X);S D(X)=D(A);S D(A)=B 02.30 D 2.4;S A=X+FITR(A*(101-X)) 02.40 S A=FABS(FRA...
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 ...
#Ruby
Ruby
  # 21 Game - an example in Ruby for Rosetta Code.   GOAL = 21 MIN_MOVE = 1 MAX_MOVE = 3   DESCRIPTION = " *** Welcome to the 21 Game! *** 21 is a two player 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 will win the game. The running total starts a...
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
#JavaScript
JavaScript
var ar=[],order=[0,1,2],op=[],val=[]; var NOVAL=9999,oper="+-*/",out;   function rnd(n){return Math.floor(Math.random()*n)}   function say(s){ try{document.write(s+"<br>")} catch(e){WScript.Echo(s)} }   function getvalue(x,dir){ var r=NOVAL; if(dir>0)++x; while(1){ if(val[x]!=NOVAL){ r=val[x]; val[x]=NOVAL...
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
#BASIC
BASIC
10 REM 15-PUZZLE GAME 20 REM COMMODORE BASIC 2.0 30 REM ******************************** 40 GOSUB 400 : REM INTRO AND LEVEL 50 GOSUB 510 : REM SETUP BOARD 60 GOSUB 210 : REM PRINT PUZZLE 70 PRINT "TO MOVE A PIECE, ENTER ITS NUMBER:" 80 INPUT X 90 GOSUB 760 : REM CHECK IF MOVE IS VALID 100 IF MV=0 THEN PRINT "WRONG MOVE...
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 ...
#Common_Lisp
Common Lisp
(ql:quickload '(cffi alexandria))   (defpackage :2048-lisp (:use :common-lisp :cffi :alexandria))   (in-package :2048-lisp)   (defvar *lib-loaded* nil)   (unless *lib-loaded* ;; Load msvcrt.dll to access _getch. (define-foreign-library msvcrt (:windows (:default "msvcrt")))   (use-foreign-library msvcrt)   ...
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...
#Scheme
Scheme
  (import (scheme base) (scheme write) (srfi 1))   ;; return all combinations of size elements from given set (define (combinations size set unique?) (if (zero? size) (list '()) (let loop ((base-combns (combinations (- size 1) set unique?)) (results '()) (items se...
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...
#Picat
Picat
import planner.   main => init(InitS), goal(GoalS), best_plan((InitS,GoalS),Plan), println(Plan).   init(InitS) => M = {{15, 14, 1, 6}, {9 , 11, 4, 12}, {0, 10, 7, 3}, {13, 8, 5, 2}}, InitS = [(R,C) : T in 0..15, pos(M,T,R,C)].   goal(GoalS) => M = {{1, 2, 3...
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...
#ArnoldC
ArnoldC
IT'S SHOWTIME HEY CHRISTMAS TREE is0 YOU SET US UP @NO PROBLEMO HEY CHRISTMAS TREE bottles YOU SET US UP 99 STICK AROUND is0 TALK TO THE HAND bottles TALK TO THE HAND " bottles of beer on the wall" TALK TO THE HAND bottles TALK TO THE HAND " bottles of beer" TALK TO THE HAND "Take one down, pass it around" GET TO THE C...
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...
#FreeBASIC
FreeBASIC
  ' The 24 game en FreeBASIC   Const operaciones = "*/+-"   Declare Sub Encabezado Declare Function escoge4() As String Declare Function quitaEspacios(cadena As String, subcadena1 As String, subcadena2 As String) As String Declare Function evaluaEntrada(cadena As String) As Integer Declare Function evaluador(oper1 A...
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 ≤...
#D
D
import std.stdio, std.conv, std.string;   void main() { string[] r; try r = readln().split(); catch (StdioException e) r = ["10", "20"];   writeln(to!int(r[0]) + to!int(r[1])); }
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 ...
#Vlang
Vlang
fn ackermann(m int, n int ) int { if m == 0 { return n + 1 } else if n == 0 { return ackermann(m - 1, 1) } return ackermann(m - 1, ackermann(m, n - 1) ) }   fn main() { for m := 0; m <= 4; m++ { for n := 0; n < ( 6 - m ); n++ { println('Ackermann($m, $n) = ${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...
#Haskell
Haskell
import Data.List (delete) import Data.Char (toUpper)   -- returns list of all solutions, each solution being a list of blocks abc :: (Eq a) => [[a]] -> [a] -> [[[a]]] abc _ [] = [[]] abc blocks (c:cs) = [b:ans | b <- blocks, c `elem` b, ans <- abc (delete b blocks) cs]   blocks = ["BO", "XK...
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...
#Forth
Forth
INCLUDE ran4.seq   100 CONSTANT #drawers #drawers CONSTANT #players 100000 CONSTANT #tries   CREATE drawers #drawers CELLS ALLOT \ index 0..#drawers-1   : drawer[] ( n -- addr ) \ return address of drawer n CELLS drawers + ;   : random_drawer ...
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 ...
#rust
rust
use rand::Rng; use std::io;   #[derive(Clone)] enum PlayerType { Human, Computer, }   #[derive(Clone)] struct Player { name: String, wins: u32, // holds wins level: u32, // difficulty level of Computer player_type: PlayerType, }   trait Choose { fn choose(&self, game: &Game) -> u8; }   imp...
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
#jq
jq
# Generate a stream of the permutations of the input array. def permutations: if length == 0 then [] else range(0;length) as $i | [.[$i]] + (del(.[$i])|permutations) end ;   # Generate a stream of arrays of length n, # with members drawn from the input array. def take(n): length as $l | if n == 1 then ran...
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
#BBC_BASIC
BBC BASIC
IF INKEY(-256)=77 OR (INKEY(-256) AND &F0)=&A0 THEN MODE 1: COLOUR 0: COLOUR 143: *FX4,1   SIZE=4 : DIFFICULTY=3   MAX=SIZE * SIZE - 1 DIM Board(MAX) FOR I%=1 TO MAX : Board(I% - 1)=I% : NEXT Gap=MAX WHILE N% < DIFFICULTY ^ 2 PROCSlide(RND(4)) : ENDWHILE : REM Shuffle N%=...
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 ...
#D
D
import std.stdio, std.string, std.random; import core.stdc.stdlib: exit;   struct G2048 { public void gameLoop() /*@safe @nogc*/ { addTile; while (true) { if (moved) addTile; drawBoard; if (done) break; waitKey; ...
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...
#Sidef
Sidef
func four_squares (list, unique=true, show=true) {   var solutions = []   func check(c) { solutions << c if ([ c[0] + c[1], c[1] + c[2] + c[3], c[3] + c[4] + c[5], c[5] + c[6], ].uniq.len == 1) }   if (unique) { list.combinations(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...
#Perl
Perl
use strict; no warnings;   use enum qw(False True); use constant Nr => <3 0 0 0 0 1 1 1 1 2 2 2 2 3 3 3>; use constant Nc => <3 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2>;   my ($n, $m) = (0, 0); my(@N0, @N2, @N3, @N4);   sub fY { printf "Solution found in $n moves: %s\n", join('', @N3) and exit if $N2[$n] == 0x123456789abcdef0...
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...
#Arturo
Arturo
s: "s"   loop 99..1 'i [ print ~"|i| bottle|s| of beer on the wall," print ~"|i| bottle|s| of beer" print ~"Take one down, pass it around!" if 1=i-1 -> s: ""   if? i>1 [ print ~"|i-1| bottle|s| of beer on the wall!" print "" ] else -> print "No more bottles of beer on the wal...
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...
#GAP
GAP
Play24 := function() local input, digits, line, c, chars, stack, stackptr, cur, p, q, ok, a, b, run; input := InputTextUser(); run := true; while run do digits := List([1 .. 4], n -> Random(1, 9)); while true do Display(digits); line := ReadLine(input); line := Chomp(line); if line = "end" then ...
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 ≤...
#Dart
Dart
import 'dart:io';   // a little helper function that checks if the string only contains // digits and an optional minus sign at the front bool isAnInteger(String str) => str.contains(new RegExp(r'^-?\d+$'));   void main() { while(true) { String input = stdin.readLineSync(); var chunks = input.split(new RegExp...
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 ...
#Wart
Wart
def (ackermann m n) (if m=0 n+1 n=0 (ackermann m-1 1)  :else (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...
#Icon_and_Unicon
Icon and Unicon
procedure main(A) blocks := ["bo","xk","dq","cp","na","gt","re","tg","qd","fs", "jw","hu","vi","an","ob","er","fs","ly","pc","zm",&null] every write("\"",word := !A,"\" ",checkSpell(map(word),blocks)," with blocks.") end   procedure checkSpell(w,blocks) blks := copy(blocks) w ? return if ...
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...
#Fortran
Fortran
SUBROUTINE SHUFFLE_ARRAY(INT_ARRAY) ! Takes an input array and shuffles the elements by swapping them ! in pairs in turn 10 times IMPLICIT NONE   INTEGER, DIMENSION(100), INTENT(INOUT) :: INT_ARRAY INTEGER, PARAMETER :: N_PASSES = 10 ! Local Variables   INTEGER :: TEMP_1, TEMP_2 ! Temporar...
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 ...
#Scala
Scala
  object Game21 {   import scala.collection.mutable.ListBuffer import scala.util.Random   val N = 21 // the same game would also work for N other than 21...   val RND = new Random() // singular random number generator; add a seed number, if you want reproducibility   /** tuple: name and a play function: (rest...
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
#Julia
Julia
function solve24(nums) length(nums) != 4 && error("Input must be a 4-element Array") syms = [+,-,*,/] for x in syms, y in syms, z in syms for i = 1:24 a,b,c,d = nthperm(nums,i) if round(x(y(a,b),z(c,d)),5) == 24 return "($a$y$b)$x($c$z$d)" elseif r...
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
#BQN
BQN
_while_ ← {𝔽⍟𝔾∘𝔽_𝕣_𝔾∘𝔽⍟𝔾𝕩} FPG←{ 𝕊𝕩: 4‿4𝕊𝕩; (∧´𝕨<0)∨2≠≠𝕨 ? •Out "Invalid shape: "∾•Fmt 𝕨; 0≠=𝕩 ? •Out "Invalid shuffle count: "∾•Fmt 𝕩; s𝕊𝕩: d←⟨1‿0⋄¯1‿0⋄0‿1⋄0‿¯1⟩ # Directions w←𝕨⥊1⌽↕×´𝕨 # Solved grid b←w # Board z←⊑{ z‿p←𝕩 p↩(⊢≡s⊸|)¨⊸/(<z)+d(¬∘∊/⊣)p # filter out inv...
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 ...
#Delphi
Delphi
  program Game2048;   {$APPTYPE CONSOLE}   uses System.SysUtils, System.Math, Velthuis.Console;   type TTile = class Value: integer; IsBlocked: Boolean; constructor Create; end;   TMoveDirection = (mdUp, mdDown, mdLeft, mdRight);   TG2048 = class FisDone, FisWon, FisMoved: boolean; Fsc...
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...
#Simula
Simula
BEGIN   INTEGER PROCEDURE GETCOMBS(LOW, HIGH, UNIQUE, COMBS); INTEGER LOW, HIGH; INTEGER ARRAY COMBS; BOOLEAN UNIQUE; BEGIN INTEGER A, B, C, D, E, F, G; INTEGER NUM;   BOOLEAN PROCEDURE ISUNIQUE(A, B, C, D, E, F, G); INTEGER A, B, C, D, E, F, G; ...
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...
#Phix
Phix
-- demo\rosetta\Solve15puzzle.exw constant STM = 0 -- single-tile metrics. constant MTM = 0 -- multi-tile metrics. if STM and MTM then ?9/0 end if -- both prohibited -- 0 0 -- fastest, but non-optimal -- 1 0 -- optimal in STM -- 0 1 -- optimal in MTM (slowest by far) --Note: The fast ...
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...
#AsciiDots
AsciiDots
/-99#-. />*$_#-$_" bottles of beer on the wall, "-$_#-$" bottles of beer."\ |[-]1#-----" ,dnuora ti ssap dna nwod eno ekaT"_$-----------------/ | | | | &-".llaw eht no reeb fo selttob 99 ,erom emos yub dna erots eht ot oG"$\ | |/$""-$"No more bottles of beer on the wall, no more bottles of beer."---/ | |\".llaw eht no...
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...
#Go
Go
package main   import ( "fmt" "math" "math/rand" "time" )   func main() { rand.Seed(time.Now().Unix()) n := make([]rune, 4) for i := range n { n[i] = rune(rand.Intn(9) + '1') } fmt.Printf("Your numbers: %c\n", n) fmt.Print("Enter RPN: ") var expr string fmt.Scan(&...
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 ≤...
#dc
dc
? + psz
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 ...
#WDTE
WDTE
let memo a m n => true { == m 0 => + n 1; == n 0 => a (- m 1) 1; true => 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...
#J
J
reduce=: verb define 'rows cols'=. i.&.> $y for_c. cols do. r=. 1 i.~ c {"1 y NB. row idx of first 1 in col if. r = #rows do. continue. end. y=. 0 (<((r+1)}.rows);c) } y NB. zero rest of col y=. 0 (<(r;(c+1)}.cols)) } y NB. zero rest of row end. )   abc=: *./@(+./)@reduce@(e."1~ ,)&t...
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...
#FreeBASIC
FreeBASIC
#include once "knuthshuf.bas" 'use the routines in https://rosettacode.org/wiki/Knuth_shuffle#FreeBASIC   function gus( i as long, strat as boolean ) as long if strat then return i return 1+int(rnd*100) end function   sub trials( byref c_success as long, byref c_fail as long, byval strat as boolean ) ...
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 ...
#Visual_Basic_.NET
Visual Basic .NET
' Game 21 in VB.NET - an example for Rosetta Code   Class MainWindow Private Const GOAL As Integer = 21 Private total As Integer = 0 Private random As New Random   Private Sub Update(box As TextBox, player As String, move As Integer) total = total + move box.Text = move boxTotal....
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
#Kotlin
Kotlin
// version 1.1.3   import java.util.Random   const val N_CARDS = 4 const val SOLVE_GOAL = 24 const val MAX_DIGIT = 9   class Frac(val num: Int, val den: Int)   enum class OpType { NUM, ADD, SUB, MUL, DIV }   class Expr( var op: OpType = OpType.NUM, var left: Expr? = null, var right: Expr? = null, ...
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
#C
C
/* RosettaCode: Fifteen puzle game, C89, plain vanillia TTY, MVC, § 22 */ #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <time.h> #define N 4 #define M 4 enum Move{UP,DOWN,LEFT,RIGHT};int hR;int hC;int cc[N][M];const int nS=100;int update(enum Move m){const int dx[]={0,0,-1,1};const int...
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 ...
#Elixir
Elixir
defmodule Game2048 do @size 4 @range 0..@size-1   def play(goal \\ 2048), do: setup() |> play(goal)   defp play(board, goal) do show(board) cond do goal in Map.values(board) -> IO.puts "You win!" exit(:normal) 0 in Map.values(board) or combinable?(board) -> move...
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...
#SQL_PL
SQL PL
  --#SET TERMINATOR @   SET SERVEROUTPUT ON @   CREATE TABLE ALL_INTS ( V INTEGER )@   CREATE TABLE RESULTS ( A INTEGER, B INTEGER, C INTEGER, D INTEGER, E INTEGER, F INTEGER, G INTEGER )@   CREATE OR REPLACE PROCEDURE FOUR_SQUARES( IN LO INTEGER, IN HI INTEGER, IN UNIQ SMALLINT, --IN UNIQ BOOLE...
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...
#Astro
Astro
fun bottles(n): match __args__: (0) => "No more bottles" (1) => "1 bottle" (_) => "$n bottles"   for n in 99..-1..1: print @format""" {bottles n} of beer on the wall {bottles n} of beer Take one down, pass it around {bottles n-1} 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...
#Gosu
Gosu
  uses java.lang.Double uses java.lang.Integer uses java.util.ArrayList uses java.util.List uses java.util.Scanner uses java.util.Stack   function doEval( scanner : Scanner, allowed : List<Integer> ) : double { var stk = new Stack<Double>()   while( scanner.hasNext() ) { if( scanner.hasNextInt() ) { ...
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 ≤...
#DCL
DCL
$ read sys$command line $ a = f$element( 0, " ", line ) $ b = f$element( 1, " ", line ) $ write sys$output a, "+", b, "=", 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 ...
#Wren
Wren
// To use recursion definition and declaration must be on separate lines var Ackermann Ackermann = Fn.new {|m, n| if (m == 0) return n + 1 if (n == 0) return Ackermann.call(m - 1, 1) return Ackermann.call(m - 1, Ackermann.call(m, n - 1)) }   var pairs = [ [1, 3], [2, 3], [3, 3], [1, 5], [2, 5], [3, 5] ] fo...
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...
#Java
Java
import java.util.Arrays; import java.util.Collections; import java.util.List;   public class ABC {   public static void main(String[] args) { List<String> blocks = Arrays.asList( "BO", "XK", "DQ", "CP", "NA", "GT", "RE", "TG", "QD", "FS", "JW", "HU", "VI", "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...
#Gambas
Gambas
' Gambas module file   Public DrawerArray As Long[] Public NumberFromDrawer As Long Public FoundOwnNumber As Long   Public Sub Main()   Dim NumberOfPrisoners As Long Dim Selections As Long Dim Tries As Long   Print "Number of prisoners (default, 100)?" Try Input NumberOfPrisoners If Error Then NumberOfPriso...
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 ...
#Vlang
Vlang
import os import rand import rand.seed import strconv   fn get_choice(mut total &int) bool { for { text := os.input("Your choice 1 to 3 : ") if text == "q" || text == "Q" { return true } input := strconv.atoi(text) or {-1} if input == -1 { println("Inv...
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
#Liberty_BASIC
Liberty BASIC
dim d(4) input "Enter 4 digits: "; a$ nD=0 for i =1 to len(a$) c$=mid$(a$,i,1) if instr("123456789",c$) then nD=nD+1 d(nD)=val(c$) end if next 'for i = 1 to 4 ' print d(i); 'next   'precompute permutations. Dumb way. nPerm = 1*2*3*4 dim perm(nPerm, 4) n = 0 for i = 1 to 4 for j = 1 to...
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
#C.23
C#
using System; using System.Drawing; using System.Linq; using System.Windows.Forms;   public class FifteenPuzzle { const int gridSize = 4; //Standard 15 puzzle is 4x4 const bool evenSized = gridSize % 2 == 0; const int blockCount = gridSize * gridSize; const int last = blockCount - 1; const int butto...
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 ...
#Elm
Elm
module Main exposing (..)   import Html exposing (Html, div, p, text, button, span, h2) import Html.Attributes exposing (class, style) import Html.Events exposing (onClick) import Keyboard exposing (KeyCode) import Random import Tuple     main = Html.program { init = ( { initialModel | waitingForRandom = Tr...
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...
#Stata
Stata
perm 7 rename * (a b c d e f g) list if a==c+d & b+c==e+f & d+e==g, noobs sep(50)   +---------------------------+ | a b c d e f g | |---------------------------| | 3 7 2 1 5 4 6 | | 4 5 3 1 6 2 7 | | 4 7 1 3 2 6 5 | | 5 6 2 3 1 7 4 | | 6 4 ...
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...
#Asymptote
Asymptote
// Rosetta Code problem: http://rosettacode.org/wiki/99_bottles_of_beer // by Jjuanhdez, 05/2022   int bottles = 99;   for (int i = bottles; i > 0; --i) { write(string(i), " bottles of beer on the wall,"); write(string(i), " bottles of beer."); write("Take one down and pass it around,"); if (i == 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...
#Groovy
Groovy
final random = new Random() final input = new Scanner(System.in)     def evaluate = { expr -> if (expr == 'QUIT') { return 'QUIT' } else { try { Eval.me(expr.replaceAll(/(\d)/, '$1.0')) } catch (e) { 'syntax error' } } }     def readGuess = { digits -> while (true) { prin...
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 ≤...
#Delphi
Delphi
program SUM;   {$APPTYPE CONSOLE}   uses SysUtils;   procedure var s1, s2:string; begin ReadLn(s1); Readln(s2); Writeln(StrToIntDef(s1, 0) + StrToIntDef(s2,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 ...
#X86_Assembly
X86 Assembly
  section .text   global _main _main: mov eax, 3 ;m mov ebx, 4 ;n call ack ;returns number in ebx ret   ack: cmp eax, 0 je M0 ;if M == 0 cmp ebx, 0 je N0 ;if N == 0 dec ebx ;else N-1 push eax ;save M call ack1 ;ack(m,n) -> returned in ebx so no further instructions needed ...
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...
#JavaScript
JavaScript
var blocks = "BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM";   function CheckWord(blocks, word) { // Makes sure that word only contains letters. if(word !== /([a-z]*)/i.exec(word)[1]) return false; // Loops through each character to see if a block exists. for(var i = 0; i < word.length; ++i) ...
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...
#Go
Go
package main   import ( "fmt" "math/rand" "time" )   // Uses 0-based numbering rather than 1-based numbering throughout. func doTrials(trials, np int, strategy string) { pardoned := 0 trial: for t := 0; t < trials; t++ { var drawers [100]int for i := 0; i < 100; i++ { dra...
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 ...
#Wren
Wren
import "/fmt" for Conv import "/ioutil" for Input import "random" for Random   var total = 0 var quit = false   var getChoice = Fn.new { while (true) { var input = Input.integer("Your choice 1 to 3: ", 0, 3) if (input == 0) { quit = true return } var newTotal ...
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
#Lua
Lua
  local SIZE = #arg[1] local GOAL = tonumber(arg[2]) or 24   local input = {} for v in arg[1]:gmatch("%d") do table.insert(input, v) end assert(#input == SIZE, 'Invalid input')   local operations = {'+', '-', '*', '/'}   local function BinaryTrees(vert) if vert == 0 then return {false} else local buf = {} for ...
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
#C.2B.2B
C++
  #include <time.h> #include <stdlib.h> #include <vector> #include <string> #include <iostream> class p15 { public : void play() { bool p = true; std::string a; while( p ) { createBrd(); while( !isDone() ) { drawBrd();getMove(); } drawBrd(); st...
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 ...
#F.23
F#
  // the board is represented with a list of 16 integers let empty = List.init 16 (fun _ -> 0) let win = List.contains 2048   // a single movement (a hit) consists of stacking and then possible joining let rec stack = function | 0 :: t -> stack t @ [0] | h :: t -> h :: stack t | [] -> [] let rec join = fun...
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...
#Tcl
Tcl
set vars {a b c d e f g} set exprs { {$a+$b} {$b+$c+$d} {$d+$e+$f} {$f+$g} }   proc permute {xs} { if {[llength $xs] < 2} { return $xs } set i -1 foreach x $xs { incr i set rest [lreplace $xs $i $i] foreach rest [permute $rest] { lappend res [l...
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...
#ATS
ATS
// #include "share/atspre_staload.hats" // (* ****** ****** *)   fun bottles (n0: int): void = let // fun loop (n: int): void = ( if n > 0 then ( if n0 > n then println! (); println! (n, " bottles of beer on the wall"); println! (n, " bottles of beer"); println! ("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...
#Haskell
Haskell
import Data.List (sort) import Data.Char (isDigit) import Data.Maybe (fromJust) import Control.Monad (foldM) import System.Random (randomRs, getStdGen) import System.IO (hSetBuffering, stdout, BufferMode(NoBuffering))   main = do hSetBuffering stdout NoBuffering mapM_ putStrLn [ "THE 24 GAME\n" , "Given...
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 ≤...
#Diego
Diego
begin_instuct(A + B); ask_human()_msg(Please enter two integers between -1000 and 1000, separated by a space:)_split( )_var(A, B); with_var(A, B)_trim()_parse({integer})_test([A]<=-1000)_test([B]>=1000)  : with_human[]_msg(Invalid input: [A], [B]); exec_instruct[];  ; add_var(sum)_calc(...
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 ...
#XLISP
XLISP
(defun ackermann (m n) (cond ((= m 0) (+ n 1)) ((= n 0) (ackermann (- m 1) 1)) (t (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...
#jq
jq
  # when_index(cond;ary) returns the index of the first element in ary # that satisfies cond; it uses a helper function that takes advantage # of tail-recursion optimization in recent versions of jq. def index_when(cond; ary): # state variable: counter def when: if . >= (ary | length) then null elif ary...
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...
#Groovy
Groovy
import java.util.function.Function import java.util.stream.Collectors import java.util.stream.IntStream   class Prisoners { private static boolean playOptimal(int n) { List<Integer> secretList = IntStream.range(0, n).boxed().collect(Collectors.toList()) Collections.shuffle(secretList)   pris...
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
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
  treeR[n_] := Table[o[trees[a], trees[n - a]], {a, 1, n - 1}] treeR[1] := n tree[n_] := Flatten[treeR[n] //. {o[a_List, b_] :> (o[#, b] & /@ a), o[a_, b_List] :> (o[a, #] & /@ b)}] game24play[val_List] := Union[StringReplace[StringTake[ToString[#, InputForm], {10, -2}], "-1*" ~~ n_ :> "-" <> n] & /@ (Ho...
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
#COBOL
COBOL
>>SOURCE FORMAT FREE *> This code is dedicated to the public domain *> This is GNUCOBOL 2.0 identification division. program-id. fifteen. environment division. configuration section. repository. function all intrinsic. data division. working-storage section.   01 r pic 9. 01 r-empty pic 9. 01 r-to pic 9. 01...
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 ...
#Factor
Factor
  USE: accessors FROM: arrays => <array> array ; FROM: assocs => assoc-filter keys zip ; FROM: combinators => case cleave cond ; FROM: combinators.short-circuit => 1|| 1&& 2&& ; FROM: continuations => cleanup ; FROM: formatting => printf sprintf ; FROM: fry => '[ _ ; FROM: grouping => all-equal? clump group ; FROM: io ...