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/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...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
ClearAll[PlayRandom, PlayOptimal] PlayRandom[n_] := Module[{pardoned = 0, sampler, indrawer, found, reveal}, sampler = indrawer = Range[100]; Do[ indrawer //= RandomSample; found = 0; Do[ reveal = RandomSample[sampler, 50]; If[MemberQ[indrawer[[reveal]], p], found++; ] , {p, 100...
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
#R
R
  library(gtools)   solve24 <- function(vals=c(8, 4, 2, 1), goal=24, ops=c("+", "-", "*", "/")) {   val.perms <- as.data.frame(t( permutations(length(vals), length(vals))))   nop <- length(vals)-1 op.perms <- as.data.frame(t( do.call(expa...
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
#Haskell
Haskell
import Data.Array import System.Random   type Puzzle = Array (Int, Int) Int   main :: IO () main = do putStrLn "Please enter the difficulty level: 0, 1 or 2" userInput <- getLine let diffLevel = read userInput if userInput == "" || any (\c -> c < '0' || c > '9') userInput || diffLevel > 2 || diffLevel <...
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 ...
#Latitude
Latitude
  use 'format import '[format]. use 'random.   Pos := Object clone tap {   self x := 0. self y := 0.   self move := { localize. case ($1) do { when 'left do { pos (this x - 1, this y). }. when 'right do { pos (this x + 1, this y). }. when 'down do { pos (this x, this y + 1). }. w...
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...
#Befunge
Befunge
local bot:int = 99   repeat print string(bot)+" bottles of beer on the wall," print string(bot)+" bottles of beer." print "Take one down, pass it around," bot:-1 print string(bot)+" bottles of beer on the wall." print until bot = 1   print "1 bottle of beer on the wall," print "1 bottle of beer....
http://rosettacode.org/wiki/24_game
24 game
The 24 Game tests one's mental arithmetic. Task Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed. The program should prompt for the player to enter an arithmetic expression using just those, and all of those four digits, used exactly once each. T...
#Locomotive_Basic
Locomotive Basic
10 CLS:RANDOMIZE TIME 20 PRINT "The 24 Game" 30 PRINT "===========":PRINT 40 PRINT "Enter an arithmetic expression" 50 PRINT "that evaluates to 24," 60 PRINT "using only the provided digits" 70 PRINT "and +, -, *, /, (, )." 80 PRINT "(Just hit Return for new digits.)" 90 ' create new digits 100 FOR i=1 TO 4:a(i)=INT(RN...
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 ≤...
#Elixir
Elixir
IO.gets("Enter two numbers seperated by a space: ") |> String.split |> Enum.map(&String.to_integer(&1)) |> Enum.sum |> IO.puts
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...
#Mercury
Mercury
:- module abc. :- interface. :- import_module io. :- pred main(io::di, io::uo) is det. :- implementation. :- import_module list, string, char.   :- type block == {char, char}.   :- pred take(char, list(block), list(block)). :- mode take(in, in, out) is nondet. take(C, !Blocks) :- list.delete(!.Blocks, {A, B}, !:Blo...
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...
#MATLAB
MATLAB
function [randSuccess,idealSuccess]=prisoners(numP,numG,numT) %numP is the number of prisoners %numG is the number of guesses %numT is the number of trials randSuccess=0;   %Random for trial=1:numT drawers=randperm(numP); won=1; for i=1:numP correct=0; ...
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
#Racket
Racket
  (define (in-variants n1 o1 n2 o2 n3 o3 n4) (let ([o1n (object-name o1)] [o2n (object-name o2)] [o3n (object-name o3)]) (with-handlers ((exn:fail:contract:divide-by-zero? (λ (_) empty-sequence))) (in-parallel (list (o1 (o2 (o3 n1 n2) n3) n4) (o1 (o2 n1 (o3 n2 n3)) n4...
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
#J
J
require'general/misc/prompt'   genboard=:3 :0 b=. ?~16 if. 0<C.!.2 b do. b=. (<0 _1)C. b end. a: (b i.0)} <"0 b )   done=: (<"0]1+i.15),a:   shift=: |.!._"0 2 taxi=: |:,/"2(_1 1 shift i.4 4),_1 1 shift"0 1/ i.4 4   showboard=:3 :0 echo 'current board:' echo 4 4$y )   help=:0 :0   Slide a number block ...
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 ...
#Lua
Lua
-- 2048 for Lua 5.1-5.4, 12/3/2020 db local unpack = unpack or table.unpack -- for 5.3 +/- compatibility game = { cell = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, best = 0, draw = function(self) local t = self.cell print("+----+----+----+----+") for r=0,12,4 do print(string.format("|%4d|%4d|%4d|%4d|\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...
#BlitzMax
BlitzMax
local bot:int = 99   repeat print string(bot)+" bottles of beer on the wall," print string(bot)+" bottles of beer." print "Take one down, pass it around," bot:-1 print string(bot)+" bottles of beer on the wall." print until bot = 1   print "1 bottle of beer on the wall," print "1 bottle of beer....
http://rosettacode.org/wiki/24_game
24 game
The 24 Game tests one's mental arithmetic. Task Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed. The program should prompt for the player to enter an arithmetic expression using just those, and all of those four digits, used exactly once each. T...
#Logo
Logo
; useful constants make "false 1=0 make "true 1=1 make "lf char 10 make "sp char 32   ; non-digits legal in expression make "operators (lput sp [+ - * / \( \)])   ; display help message to show_help :digits type lf print sentence quoted [Using only these digits:] :digits print sentence quoted [and these operato...
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 ≤...
#Elm
Elm
  --To write this function directly run cmd --Type elm-repl to start --Next enter this code sum x y=x+y   --This creates a sum function --When you enter sum A B --You get output as A+B : number --Task done! --END    
http://rosettacode.org/wiki/ABC_problem
ABC problem
ABC problem You are encouraged to solve this task according to the task description, using any language you may know. You are given a collection of ABC blocks   (maybe like the ones you had when you were a kid). There are twenty blocks with two letters on each block. A complete alphabet is guaranteed amongst all sid...
#MiniScript
MiniScript
allBlocks = ["BO", "XK", "DQ", "CP", "NA", "GT", "RE", "TG", "QD", "FS", "JW", "HU", "VI", "AN", "OB", "ER", "FS", "LY", "PC", "ZM"]   swap = function(list, index1, index2) tmp = list[index1] list[index1] = list[index2] list[index2] = tmp end function   canMakeWord = function(str, blocks) if str == "" 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...
#MiniScript
MiniScript
playRandom = function(n) // using 0-99 instead of 1-100 pardoned = 0 numInDrawer = range(99) choiceOrder = range(99) for round in range(1, n) numInDrawer.shuffle choiceOrder.shuffle for prisoner in range(99) found = false for card in choiceOrder[:50] ...
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
#Raku
Raku
use MONKEY-SEE-NO-EVAL;   my @digits; my $amount = 4;   # Get $amount digits from the user, # ask for more if they don't supply enough while @digits.elems < $amount { @digits.append: (prompt "Enter {$amount - @digits} digits from 1 to 9, " ~ '(repeats allowed): ').comb(/<[1..9]>/); } # Throw away any extras @di...
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
#Java
Java
package fifteenpuzzle;   import java.awt.*; import java.awt.event.*; import java.util.Random; import javax.swing.*;   class FifteenPuzzle extends JPanel {   private final int side = 4; private final int numTiles = side * side - 1;   private final Random rand = new Random(); private final int[] tiles = 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 ...
#M2000_Interpreter
M2000 Interpreter
  Module Game2048 { \\ 10% 4 and 90% 2 Def GetTlleNumber()=If(Random(10)<2->4, 2) \\ tile Def Tile$(x)=If$(x=0->"[ ]", format$("[{0::-4}]", x)) \\ empty board BoardTileRight=lambda (x, y)->x+y*4 BoardTileLeft=lambda (x, y)->3-x+y*4 BoardTileUp=lambda (x, y)->x*4+y ...
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...
#BlooP
BlooP
  DEFINE PROCEDURE ''MINUS'' [A,B]: BLOCK 0: BEGIN IF A < B, THEN: QUIT BLOCK 0; LOOP AT MOST A TIMES: BLOCK 1: BEGIN IF OUTPUT + B = A, THEN: QUIT BLOCK 0; OUTPUT <= OUTPUT + 1; BLOCK 1: END; BLOCK 0: END.   DEFINE PROCEDURE ''BOTTLES'' [COUNT]: BLOCK 0: BEGIN CELL(0) <= COUNT; LOOP COUNT +...
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...
#Lua
Lua
  local function help() print [[ The 24 Game   Given any four digits in the range 1 to 9, which may have repetitions, Using just the +, -, *, and / operators; and the possible use of brackets, (), show how to make an answer of 24.   An answer of "q" will quit the game. An answer of "!" will generate a new set of...
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 ≤...
#Emacs_Lisp
Emacs Lisp
(let* ((input (read-from-minibuffer "")) (numbers (mapcar #'string-to-number (split-string input))) (a (car numbers)) (b (cadr numbers))) (message "%d" (+ a b)))
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...
#Nim
Nim
import std / strutils   func canMakeWord(blocks: seq[string]; word: string): bool = if blocks.len < word.len: return false if word.len == 0: return true   let ch = word[0].toUpperAscii for i, pair in blocks: if ch in pair and (blocks[0..<i] & blocks[i+1..^1]).canMakeWord(word[1..^1]):...
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...
#Nim
Nim
import random, sequtils, strutils   type Sample = tuple succ: int fail: int   const numPrisoners = 100 numDrawsEachPrisoner = numPrisoners div 2 numDrawings: Positive = 1_000_000 div 1   proc `$`(s: Sample): string = "Succs: $#\tFails: $#\tTotal: $#\tSuccess Rate: $#%." % [$s.succ, $s.fail, $(s.succ +...
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
#REXX
REXX
/*REXX program helps the user find solutions to the game of 24. */ /* start-of-help ┌───────────────────────────────────────────────────────────────────────┐ │ Argument is either of three forms: (blank) │~ │ ...
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
#JavaScript
JavaScript
  var board, zx, zy, clicks, possibles, clickCounter, oldzx = -1, oldzy = -1; function getPossibles() { var ii, jj, cx = [-1, 0, 1, 0], cy = [0, -1, 0, 1]; possibles = []; for( var i = 0; i < 4; i++ ) { ii = zx + cx[i]; jj = zy + cy[i]; if( ii < 0 || ii > 3 || jj < 0 || jj > 3 ) continue; ...
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 ...
#Maple
Maple
  macro(SP=DocumentTools:-SetProperty, GP=DocumentTools:-GetProperty); G := module()   export reset,f,getname; local a:=Matrix(4): local buttonpress:="False"; local score:=0; local highscoreM,highscore,hscore,hname,M,j,k,z,e,move,r,c,q,w,checklose,loss,matrixtotextarea;   getname:=proc(); hname:=GP("Name",valu...
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...
#Bracmat
Bracmat
No more bottles of beer on the wall, no more bottles of beer. Go to the store and buy some more, 99 bottles of beer on the wall.
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...
#Maple
Maple
play24 := module() export ModuleApply; local cheating; cheating := proc(input, digits) local i, j, stringDigits; use StringTools in stringDigits := Implode([seq(convert(i, string), i in digits)]); for i in digits do for j in digits do if Search(cat(convert(i, string), j), input) > 0 then ret...
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 ≤...
#Emojicode
Emojicode
🏁🍇 🆕🔡▶️👂🏼❗️ ➡️ input 💭 Get numbers as input string 🔫 input 🔤 🔤❗ ➡️ nums 💭 Split numbers by space 🍺🔢 🐽 nums 0❗ 10❗ ➡️ A 💭 Retrieve first number 🍺🔢 🐽 nums 1❗ 10❗ ➡️ B 💭 Retrieve second number 😀 🔤🧲A➕B🧲🔤 ❗ 💭 Output sum 🍉️
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...
#Oberon-2
Oberon-2
  MODULE ABCBlocks; IMPORT Object, Out;   VAR blocks: ARRAY 20 OF STRING;   PROCEDURE CanMakeWord(w: STRING): BOOLEAN; VAR used: ARRAY 20 OF LONGINT; wChars: Object.CharsLatin1; i,j: LONGINT;   PROCEDURE IsUsed(i: LONGINT): BOOLEAN; VAR b: LONGINT; BEGIN ...
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...
#Pascal
Pascal
program Prisoners100;   const rounds = 100000;   type tValue = Uint32; tPrisNum = array of tValue; var drawers, PrisonersChoice : tPrisNum;   procedure shuffle(var N:tPrisNum); var i,j,lmt : nativeInt; tmp: tValue; Begin lmt := High(N); For i := lmt downto 1 do begin //take on from index i..lim...
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
#Ruby
Ruby
class TwentyFourGame EXPRESSIONS = [ '((%dr %s %dr) %s %dr) %s %dr', '(%dr %s (%dr %s %dr)) %s %dr', '(%dr %s %dr) %s (%dr %s %dr)', '%dr %s ((%dr %s %dr) %s %dr)', '%dr %s (%dr %s (%dr %s %dr))', ]   OPERATORS = [:+, :-, :*, :/].repeated_permutation(3).to_a   def self.solve(digits) solu...
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
#Julia
Julia
  using Random   const size = 4 const puzzle = string.(reshape(1:16, size, size)) puzzle[16] = " " rng = MersenneTwister(Int64(round(time()))) shufflepuzzle() = (puzzle .= shuffle(rng, puzzle)) findtile(t) = findfirst(x->x == t, puzzle) findhole() = findtile(" ")   function issolvable() inversioncount = 1 asint...
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 ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
SetOptions[InputNotebook[],NotebookEventActions->{ "LeftArrowKeyDown":>(stat=Coalesce[stat];AddNew[]), "RightArrowKeyDown":>(stat=Reverse/@Coalesce[Reverse/@stat];AddNew[]), "UpArrowKeyDown":>(stat=Coalesce[stat\[Transpose]]\[Transpose];AddNew[]), "DownArrowKeyDown":>(stat=(Reverse/@(Coalesce[Reverse/@(stat\[Transpose]...
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...
#Brainf.2A.2A.2A
Brainf***
99.to 2 { n | p "#{n} bottles of beer on the wall, #{n} bottles of beer!" p "Take one down, pass it around, #{n - 1} bottle#{true? n > 2 's' ''} of beer on the wall." }   p "One bottle of beer on the wall, one bottle of beer!" p "Take one down, pass it around, no more bottles of beer on the wall."
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...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
isLegal[n_List, x_String] := Quiet[Check[ With[{h = ToExpression[x, StandardForm, HoldForm]}, If[Cases[Level[h, {2, \[Infinity]}, Hold, Heads -> True], Except[_Integer | Plus | _Plus | Times | _Times | Power | Power[_, -1]]] === {} && Sort[Level[h /. Power[q_, -1] -> q, {-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 ≤...
#Erlang
Erlang
-module(aplusb). -export([start/0]).   start() -> case io:fread("","~d~d") of eof -> ok; {ok, [A,B]} -> io:format("~w~n",[A+B]), start() end.
http://rosettacode.org/wiki/ABC_problem
ABC problem
ABC problem You are encouraged to solve this task according to the task description, using any language you may know. You are given a collection of ABC blocks   (maybe like the ones you had when you were a kid). There are twenty blocks with two letters on each block. A complete alphabet is guaranteed amongst all sid...
#Objeck
Objeck
class Abc { function : Main(args : String[]) ~ Nil { blocks := ["BO", "XK", "DQ", "CP", "NA", "GT", "RE", "TG", "QD", "FS", "JW", "HU", "VI", "AN", "OB", "ER", "FS", "LY", "PC", "ZM"];   IO.Console->Print("\"\": ")->PrintLine(CanMakeWord("", blocks)); IO.Console->Print("A: ")->PrintLi...
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...
#Perl
Perl
use strict; use warnings; use feature 'say'; use List::Util 'shuffle';   sub simulation { my($population,$trials,$strategy) = @_; my $optimal = $strategy =~ /^o/i ? 1 : 0; my @prisoners = 0..$population-1; my $half = int $population / 2; my $pardoned = 0;   for (1..$trials) { my ...
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
#Rust
Rust
#[derive(Clone, Copy, Debug)] enum Operator { Sub, Plus, Mul, Div, }   #[derive(Clone, Debug)] struct Factor { content: String, value: i32, }   fn apply(op: Operator, left: &[Factor], right: &[Factor]) -> Vec<Factor> { let mut ret = Vec::new(); for l in left.iter() { for r in rig...
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
#Kotlin
Kotlin
// version 1.1.3   import java.awt.BorderLayout import java.awt.Color import java.awt.Dimension import java.awt.Font import java.awt.Graphics import java.awt.Graphics2D import java.awt.RenderingHints import java.awt.event.MouseAdapter import java.awt.event.MouseEvent import java.util.Random import javax.swing.JFrame im...
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 ...
#MATLAB
MATLAB
function field = puzzle2048(field)   if nargin < 1 || isempty(field) field = zeros(4); field = addTile(field); end   clc rng('shuffle')   while true oldField = field; clc score = displayField(field);   % check losing condition if isGameLost(field) sprintf('You lose with a score of %g...
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...
#Brat
Brat
99.to 2 { n | p "#{n} bottles of beer on the wall, #{n} bottles of beer!" p "Take one down, pass it around, #{n - 1} bottle#{true? n > 2 's' ''} of beer on the wall." }   p "One bottle of beer on the wall, one bottle of beer!" p "Take one down, pass it around, no more bottles of beer on the wall."
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...
#MATLAB_.2F_Octave
MATLAB / Octave
function twentyfour() N = 4; n = ceil(rand(1,N)*9); printf('Generate a equation with the numbers %i, %i, %i, %i and +, -, *, /, () operators ! \n',n); s = input(': ','s'); t = s; for k = 1:N, [x,t] = strtok(t,'+-*/() \t'); if length(x)~=1, error('invalid sign %s\n',x); end; 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 ≤...
#ERRE
ERRE
  PROGRAM SUM2   BEGIN   LOOP INPUT(LINE,Q$) EXIT IF Q$="" SP%=INSTR(Q$," ") PRINT(VAL(LEFT$(Q$,SP%-1))+VAL(MID$(Q$,SP%+1))) END LOOP   END PROGRAM  
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...
#OCaml
OCaml
let blocks = [ ('B', 'O'); ('X', 'K'); ('D', 'Q'); ('C', 'P'); ('N', 'A'); ('G', 'T'); ('R', 'E'); ('T', 'G'); ('Q', 'D'); ('F', 'S'); ('J', 'W'); ('H', 'U'); ('V', 'I'); ('A', 'N'); ('O', 'B'); ('E', 'R'); ('F', 'S'); ('L', 'Y'); ('P', 'C'); ('Z', 'M'); ]   let find_letter blocks c = let fou...
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...
#PicoLisp
PicoLisp
(de shuffle (Lst) (by '(NIL (rand)) sort Lst) )   # Extend this class with a `next-guess>` method and a `str>` method. (class +Strategy +Entity) (dm prev-drawer> (Num) (=: prev Num) )   (class +Random +Strategy) (dm T (Prisoner) (=: guesses (nth (shuffle (range 1 100)) 51)) ) (dm next-guess> () (pop (:: gue...
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
#Scala
Scala
def permute(l: List[Double]): List[List[Double]] = l match { case Nil => List(Nil) case x :: xs => for { ys <- permute(xs) position <- 0 to ys.length (left, right) = ys splitAt position } yield left ::: (x :: right) }   def computeAllOperations(l: List[Double]): List[(Double,String)] = l m...
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
#Liberty_BASIC
Liberty BASIC
  ' 15-PUZZLE GAME ' ******************************** dim d(16) dim ds$(16) ' Board pieces dim sh(3)   call buildBoard introAndLevel() call printPuzzle do print "To move a piece, enter its number: " input x while isMoveValid(x, y, z) = 0 print "Wrong move." call printPuzzle print "To move a piece, ent...
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 ...
#Nim
Nim
import random, strutils, terminal   const BoardLength = 4 BoardSize = BoardLength * BoardLength Target = 2048   type Operation = enum opInvalid opUp opDown opLeft opRight opQuit opRestart   Board = object len: Natural largestNumber: Natural score: Natural rows: arra...
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...
#BQN
BQN
Pl ← {(𝕩≠1)/"s"} {𝕨∾(@+10)∾𝕩}´{(•Fmt 𝕨)∾" "∾𝕩}´¨∾{ ⟨ ⟨𝕩,"bottle"∾(Pl 𝕩)∾" of beer on the wall"⟩ ⟨𝕩,"bottle"∾(Pl 𝕩)∾" of beer"⟩ ⟨"Take one down, pass it around"⟩ ⟨𝕩-1,"bottle"∾(Pl 𝕩-1)∾" of beer on the wall"∾@+10⟩ ⟩ }¨⌽1+↕99
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...
#MiniScript
MiniScript
evalAddSub = function() result = evalMultDiv while true if not tokens then return result op = tokens[0] if op != "+" and op != "-" then return result tokens.pull // (discard operator) rhs = evalMultDiv if result == null or rhs == null then return null if ...
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 ≤...
#Euler_Math_Toolbox
Euler Math Toolbox
  >s=lineinput("Two numbers seperated by a blank"); Two numbers seperated by a blank? >4 5 >vs=strtokens(s) 4 5 >vs[1]()+vs[2]() 9  
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...
#Oforth
Oforth
import: mapping   ["BO","XK","DQ","CP","NA","GT","RE","TG","QD","FS","JW","HU","VI","AN","OB","ER","FS","LY","PC","ZM"] const: ABCBlocks   : canMakeWord(w, blocks) | i | w empty? ifTrue: [ true return ] blocks size loop: i [ w first >upper blocks at(i) include? ifFalse: [ continue ] canMakeWord( w ...
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...
#Phix
Phix
function play(integer prisoners, iterations, bool optimal) sequence drawers = shuffle(tagset(prisoners)) integer pardoned = 0 bool found = false for i=1 to iterations do drawers = shuffle(drawers) for prisoner=1 to prisoners do found = false integer drawer = iff(o...
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
#Scheme
Scheme
  #!r6rs   (import (rnrs) (rnrs eval) (only (srfi :1 lists) append-map delete-duplicates iota))   (define (map* fn . lis) (if (null? lis) (list (fn)) (append-map (lambda (x) (apply map* (lambda xs (apply fn x xs)) (c...
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
#LiveCode
LiveCode
  #Please note that all this code can be performed in livecode with just few mouse clicks #This is just a pure script exampe on OpenStack show me #Usually not necessary #tile creation set the width of the templateButton to 50 set the height of the templateButton to 50 repeat with i=1 to 16 create ...
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 ...
#OCaml
OCaml
  let list_make x v = let rec aux acc i = if i <= 0 then acc else aux (v::acc) (i-1) in aux [] x     let pad_right n line = let len = List.length line in let x = n - len in line @ (list_make x 0)     let _move_left line = let n = List.length line in let line = List.filter ((<>) 0) line in let rec ...
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...
#C
C
/* * 99 Bottles, C, KISS (i.e. keep it simple and straightforward) version */   #include <stdio.h>   int main(void) { int n;   for( n = 99; n > 2; n-- ) printf( "%d bottles of beer on the wall, %d bottles of beer.\n" "Take one down and pass it around, %d bottles of beer on the wall.\n\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...
#mIRC_Scripting_Language
mIRC Scripting Language
alias 24 { dialog -m 24-Game 24-Game }   dialog 24-Game { title "24-Game" size -1 -1 100 70 option dbu text "", 1, 29 7 42 8 text "Equation", 2, 20 21 21 8 edit "", 3, 45 20 40 10 text "Status", 4, 10 34 80 8, center button "Calculate", 5, 5 45 40 20 button "New", 6, 57 47 35 15 }   on *:DIALOG:24-G...
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 ≤...
#Euphoria
Euphoria
include get.e   function snd(sequence s) return s[2] end function   integer a,b   a = snd(get(0)) b = snd(get(0))   printf(1," %d\n",a+b)
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...
#OpenEdge.2FProgress
OpenEdge/Progress
FUNCTION canMakeWord RETURNS LOGICAL (INPUT pWord AS CHARACTER) FORWARD.   /* List of blocks */ DEFINE TEMP-TABLE ttBlocks NO-UNDO FIELD ttFaces AS CHARACTER FORMAT "x(1)" EXTENT 2 FIELD ttUsed AS LOGICAL.   /* Fill in list of blocks */ RUN AddBlock("BO"). RUN AddBlock("XK"). RUN AddBlock("DQ"). RUN AddBlock("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...
#Phixmonti
Phixmonti
/# Rosetta Code problem: http://rosettacode.org/wiki/100_prisoners by Galileo, 05/2022 #/   include ..\Utilitys.pmt   def random rand * 1 + int enddef   def shuffle len var l l for var a l random var b b get var p a get b set p a set endfor enddef   def play var optimal var i...
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
#Sidef
Sidef
var formats = [ '((%d %s %d) %s %d) %s %d', '(%d %s (%d %s %d)) %s %d', '(%d %s %d) %s (%d %s %d)', '%d %s ((%d %s %d) %s %d)', '%d %s (%d %s (%d %s %d))', ]   var op = %w( + - * / ) var operators = op.map { |a| op.map {|b| op.map {|c| "#{a} #{b} #{c}" } } }.flat   loop { var input = read("Enter...
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
#Lua
Lua
  math.randomseed( os.time() ) local puz = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0 } local dir = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } } local sx, sy = 4, 4   function isValid( tx, ty ) return tx > 0 and tx < 5 and ty > 0 and ty < 5 end function display() io.write( "\n\n" ) for j = 1,...
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 ...
#Pascal
Pascal
  program game2048; uses Crt; const SIZE_MAP = 4; SIZETOPBOT = SIZE_MAP*6+6; (* Calculate the length of the top and bottom to create a box around the game *) NOTHING = 0; UP = 93; RIGHT = 92; LEFT = 91; DOWN = 90; type type_vector = array [1..SIZE_MAP] of integer; type_game = recor...
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...
#C.23
C#
using System;   class Program { static void Main(string[] args) { for (int i = 99; i > -1; i--) { if (i == 0) { Console.WriteLine("No more bottles of beer on the wall, no more bottles of beer."); Console.WriteLine("Go to the store and buy s...
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...
#Modula-2
Modula-2
MODULE TwentyFour;   FROM InOut IMPORT WriteString, WriteLn, Write, ReadString, WriteInt; FROM RandomGenerator IMPORT Random;   TYPE operator_t = (add, sub, mul, div); expr_t = RECORD operand : ARRAY[0..3] OF CARDINAL; operator : ARRAY[1..3] OF operator_t; END;(*of RECORD*) numbers_t...
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 ≤...
#Excel
Excel
  =A1+B1  
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...
#Order
Order
#include <order/interpreter.h> #include <order/lib.h>   // Because of technical limitations, characters within a "string" must be separated by white spaces. // For the sake of simplicity, only upper-case characters are supported here.   // A few lines of boiler-plate oriented programming are needed to enable character ...
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...
#PL.2FM
PL/M
100H: /* PARAMETERS */ DECLARE N$DRAWERS LITERALLY '100'; /* AMOUNT OF DRAWERS */ DECLARE N$ATTEMPTS LITERALLY '50'; /* ATTEMPTS PER PRISONER */ DECLARE N$SIMS LITERALLY '2000'; /* N. OF SIMULATIONS TO RUN */ DECLARE RAND$SEED LITERALLY '193'; /* RANDOM SEED */   /* CP/M CALLS */ BDOS: PROCEDURE (FN, ARG); D...
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
#Simula
Simula
BEGIN       CLASS EXPR; BEGIN     REAL PROCEDURE POP; BEGIN IF STACKPOS > 0 THEN BEGIN STACKPOS := STACKPOS - 1; POP := STACK(STACKPOS); END; END POP;     PROCEDURE PUSH(NEWTOP); REAL NEWTOP; BEGIN STACK(STACKPOS) := NEWTOP; ...
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
#M2000_Interpreter
M2000 Interpreter
  Module Puzzle15 {   00 BASE 1 : DEF RND(X)=RND 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...
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 ...
#Perl
Perl
#!/usr/bin/perl   use strict; # https://rosettacode.org/wiki/2048 use warnings; use Tk;   my $N = shift // 4; $N < 2 and $N = 2; my @squares = 1 .. $N*$N; my %n2ch = (' ' => ' '); @n2ch{ map 2**$_, 1..26} = 'a'..'z'; my %ch2n = reverse %n2ch; my $winner = ''; my @arow = 0 .. $N - 1; my @acol = map $_ * $N, @arow;   my ...
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...
#C.2B.2B
C++
#include <iostream> using std::cout;   int main() { for(int bottles(99); bottles > 0; bottles -= 1){ cout << bottles << " bottles of beer on the wall\n" << bottles << " bottles of beer\n" << "Take one down, pass it around\n" << bottles - 1 << " bottles of beer on the wall\n\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...
#MUMPS
MUMPS
24Game k number, operator, bracket ; generate 4 random numbers each between 1 & 9 ; duplicates allowed! s n1=$r(9)+1, n2=$r(9)+1, n3=$r(9)+1, n4=$r(9)+1 ; save a copy of them so that we can keep restarting ; if the user gets it wrong s s1=n1,s2=n2,s3=n3,s4=n4 Question s (numcount,opcount,lbrackcount,rbrackcount...
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 ≤...
#F.23
F#
open System   let SumOf(str : string) = str.Split() |> Array.sumBy(int)   [<EntryPoint>] let main argv = Console.WriteLine(SumOf(Console.ReadLine())) 0
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...
#PARI.2FGP
PARI/GP
BLOCKS = "BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM"; WORDS = ["A","Bark","BOOK","Treat","COMMON","SQUAD","conFUSE"];   can_make_word(w) = check(Vecsmall(BLOCKS), Vecsmall(w))   check(B,W,l=1,n=1) = { if (l > #W, return(1), n > #B, return(0));   forstep (i = 1, #B-2, 2, if (B[i] != bitand(W[l],223) && B[i+1] !=...
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...
#Pointless
Pointless
optimalSeq(drawers, n) = iterate(ind => drawers[ind - 1], n) |> takeUntil(ind => drawers[ind - 1] == n)   optimalTrial(drawers) = range(1, 100) |> map(optimalSeq(drawers))   randomSeq(drawers, n) = iterate(ind => randRange(1, 100), randRange(1, 100)) |> takeUntil(ind => drawers[ind - 1] == n)   randomTrial(...
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
#Swift
Swift
  import Darwin import Foundation   var solution = ""   println("24 Game") println("Generating 4 digits...")   func randomDigits() -> [Int] { var result = [Int]() for i in 0 ..< 4 { result.append(Int(arc4random_uniform(9)+1)) } return result }   // Choose 4 digits let digits = randomDigits()   print("Make 2...
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
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
grid = MapThread[{#1,#2} &, {Range @ 16, Range @ 16}]   Move[x_] := (empty = Select[grid, #[[1]]==16 &][[1,2]]; If[(empty == x+4) || (empty == x-4) || (Mod[empty,4] != 0 && empty == x-1) || (Mod[empty,4] != 1 && empty == x+1), oldEmpty = grid[[empty]][[1]]; ...
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 ...
#Phix
Phix
-- demo\rosetta\2048.exw with javascript_semantics include pGUI.e Ihandle canvas, dialog cdCanvas cddbuffer, cdcanvas constant tile_colours = {#CCC0B4, -- blank #EEE4DA, -- 2 #EDE0C8, -- 4 #F2B179, -- 8 #F59563...
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...
#Ceylon
Ceylon
shared void ninetyNineBottles() {   String bottles(Integer count) => "``count == 0 then "No" else count`` bottle``count == 1 then "" else "s"``".normalized;   for(i in 99..1) { print("``bottles(i)`` of beer on the wall ``bottles(i)`` of beer! Take one down, pass it around ``bottl...
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...
#Nanoquery
Nanoquery
import Nanoquery.Lang import Nanoquery.Util   // a function to get the digits from an arithmetic expression def extract_digits(input) input = str(input) digits = {}   loc = 0 digit = "" while (loc < len(input)) if input[loc] in "0123456789" digit += input[loc] else if len(digit) > 0 digits.append(int...
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 ≤...
#Factor
Factor
USING: math.parser splitting ; : a+b ( -- ) readln " " split1 [ string>number ] bi@ + number>string print ;
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...
#Pascal
Pascal
  #!/usr/bin/instantfpc //program ABCProblem;   {$mode objfpc}{$H+}   uses SysUtils, Classes;   const // every couple of chars is a block // remove one by replacing its 2 chars by 2 spaces Blocks = 'BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM'; BlockSize = 3;   function can_make_word(Str: Strin...
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...
#PowerShell
PowerShell
  ### Clear Screen from old Output Clear-Host   Function RandomOpening () { $Prisoners = 1..100 | Sort-Object {Get-Random} $Cupboard = 1..100 | Sort-Object {Get-Random} ## Loop for the Prisoners $Survived = $true for ($I=1;$I -le 100;$i++) { $OpeningListe = 1..100 | Sort-Object {G...
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
#Tcl
Tcl
package require struct::list # Encoding the various expression trees that are possible set patterns { {((A x B) y C) z D} {(A x (B y C)) z D} {(A x B) y (C z D)} {A x ((B y C) z D)} {A x (B y (C z D))} } # Encoding the various permutations of digits set permutations [struct::list map [struct::...
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
#Mercury
Mercury
:- module fifteen. :- interface. :- use_module random, io.   :- type board. :- type invalid_board ---> invalid_board(board). :- type move ---> up  ; down  ; left  ; right.    % init(Board):  % Board is fifteen game in its initial state  % :- pred init(board::out) is det...
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 ...
#PHP
PHP
  <?php   $game = new Game();   while(true) { $game->cycle(); }   class Game { private $field; private $fieldSize; private $command; private $error; private $lastIndexX, $lastIndexY; private $score; private $finishScore;   function __construct() { $this->field = array(); $this->fieldSize = 4; $this->f...
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...
#Chapel
Chapel
  /*********************************************************************** * Chapel implementation of "99 bottles of beer" * * by Brad Chamberlain and Steve Deitz * 07/13/2006 in Knoxville airport while waiting for flight home from * HPLS workshop * compiles and runs with chpl compiler version 1.7.0 *...
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...
#Nim
Nim
from random import randomize, rand from strutils import Whitespace from algorithm import sort from sequtils import newSeqWith   randomize()   var problem = newSeqWith(4, rand(1..9)) stack: seq[float] digits: seq[int]   echo "Make 24 with the digits: ", problem   template op(c: untyped) = let a = stack.pop sta...
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 ≤...
#FALSE
FALSE
[0[^$$'9>'0@>|~]['0-\10*+]#%]n: {read an integer} 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...
#Perl
Perl
#!/usr/bin/perl use warnings; use strict;     sub can_make_word { my ($word, @blocks) = @_; $_ = uc join q(), sort split // for @blocks; my %blocks; $blocks{$_}++ for @blocks; return _can_make_word(uc $word, %blocks) }     sub _can_make_word { my ($word, %blocks) = @_; my $char = substr $wor...
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...
#Processing
Processing
IntList drawers = new IntList(); int trials = 100000; int succes_count;   void setup() { for (int i = 0; i < 100; i++) { drawers.append(i); } println(trials + " trials\n");   //Random strategy println("Random strategy"); succes_count = trials; for (int i = 0; i < trials; i++) { drawers.shuffle(); ...
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
#Ursala
Ursala
#import std #import nat #import rat   tree_shapes = "n". (@vLPiYo //eql iota "n")*~ (rep"n" ~&iiiK0NlrNCCVSPTs) {0^:<>} with_leaves = ^|DrlDrlK34SPSL/permutations ~& with_roots = ^DrlDrlK35dlPvVoPSPSL\~&r @lrhvdNCBvLPTo2DlS @hiNCSPtCx ~&K0=> value = *^ ~&v?\(@d ~&\1) ^|H\~&hthPX '+-*/'-$<sum,difference,product,q...
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
#MUMPS
MUMPS
15Game ; ; setting the layout f i=1:1:15 s box(i)=16-i ; no number for box 16 s box(16)="" f { ; initialise i for incrementation s i=0 ; write out the 4-by-4 box f row=1:1:4 { w !?20 f column=1:1:4 { s i=$i(i) w $j(box(i),2)," " } } r !!,"Enter number to move (q to quit): ",number q: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 ...
#PicoLisp
PicoLisp
(load "@lib/simul.l")   (symbols 'simul 'pico)   (seed (in "/dev/urandom" (rd 8)))   (setq *G (grid 4 4) *D NIL)   (de cell () (use This (while (get (setq This (intern (pack (char (+ 96 (rand 1 4))) (rand 1 4) ) ) ...