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/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 down, pass it around 97 bottles of beer on the wall ... and so on, until reaching   0     (zero). Grammatical support for   1 bottle of beer   is optional. As with any puzzle, try to do it in as creative/concise/comical a way as possible (simple, obvious solutions allowed, too). Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet See also   http://99-bottles-of-beer.net/   Category:99_Bottles_of_Beer   Category:Programming language families   Wikipedia 99 bottles of beer
#Chef
Chef
  execute() {   // this class provides synchronization // to get unique number of the bottle   class monitor giver { int number = 100; .get() { return --number; } } var g = new giver();   // start 99 concurrently worked threads // each thread gets own number of the bottle and prints out his own verse // (notice that the output lines from the threads will be mixed together)   {#[99] int nr = g.get(); // get own number host.println(nr," bottles of beer on the wall, "+nr+" bottles of beer"); host.print("Take one down, pass it around,"); if (nr > 1) { host.println((nr-1)," bottles of beer on the wall."); } else { host.println("no more bottles of beer on the wall."); } } host.println("No more bottles of beer on the wall, no more bottles of beer."); host.println("Go to the store and buy some more, 99 bottles of beer on the wall."); return 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. The program should check then evaluate the expression. The goal is for the player to enter an expression that (numerically) evaluates to 24. Only the following operators/functions are allowed: multiplication, division, addition, subtraction Division should use floating point or rational arithmetic, etc, to preserve remainders. Brackets are allowed, if using an infix expression evaluator. Forming multiple digit numbers from the supplied digits is disallowed. (So an answer of 12+12 when given 1, 2, 2, and 1 is wrong). The order of the digits when given does not have to be preserved. Notes The type of expression evaluator used is not mandated. An RPN evaluator is equally acceptable for example. The task is not for the program to generate the expression, or test whether an expression is even possible. Related tasks 24 game/Solve Reference The 24 Game on h2g2.
#Nit
Nit
redef class Char fun is_op: Bool do return "-+/*".has(self) end   # Get `numbers` and `operands` from string `operation` collect with `gets` in `main` function # Fill `numbers` and `operands` array with previous extraction fun exportation(operation: String, numbers: Array[Int], operands: Array[Char]) do var previous_char: nullable Char = null var number: nullable Int = null var negative = false   for i in operation.length.times do var current_char = operation[i] var current_int = current_char.to_i   if (previous_char == null or previous_char.is_op) and current_char == '-' then negative = true continue end   if current_char.is_digit then if number == null then number = current_int else number = number * 10 + current_int end end   if negative and (current_char.is_op or i == operation.length - 1) then number = number - number * 2 negative = false end   if (current_char.is_op or i == operation.length - 1) and number != null then numbers.add(number) number = null end   if not negative and current_char.is_op then operands.add(current_char) end previous_char = current_char end # Update `numbers` and `operands` array in main function with pointer end   # Create random numbers between 1 to 9 fun random: Array[Int] do return [for i in 4.times do 1 + 9.rand] end   # Make mathematical operation with `numbers` and `operands` and add the operation result into `random_numbers` fun calculation(random_numbers, numbers: Array[Int], operands: Array[Char]) do var number = 0 var temp_numbers = numbers.clone   while temp_numbers.length > 1 do var operand = operands.shift var a = temp_numbers.shift var b = temp_numbers.shift   if operand == '+' then number = a + b if operand == '-' then number = a - b if operand == '*' then number = a * b if operand == '/' then number = a / b   temp_numbers.unshift(number) end if number != 0 then random_numbers.add(number) end   # Check if used `numbers` exist in the `random_numbers` created fun numbers_exists(random_numbers, numbers: Array[Int]): Bool do for number in numbers do if not random_numbers.count(number) >= numbers.count(number) then return false end return true end   # Remove `numbers` when they are used fun remove_numbers(random_numbers, numbers: Array[Int]) do for number in numbers do random_numbers.remove(number) end   # Check if the mathematical `operation` is valid fun check(operation: String): Bool do var previous_char: nullable Char = null var next_char: nullable Char = null var next_1_char: nullable Char = null   for i in operation.length.times do var current_char = operation[i]   if i + 1 < operation.length then next_char = operation[i + 1] if i + 2 < operation.length then next_1_char = operation[i + 2] else next_1_char = null end else next_char = null end   if not current_char.is_op and not current_char.is_digit then return false if next_char == null and current_char.is_op then return false   if previous_char == null then if next_char == null or next_1_char == null then return false if current_char == '-' and not next_char.is_digit then return false if current_char != '-' and not current_char.is_digit then return false else if next_char != null then if previous_char.is_digit and current_char.is_op and not (next_char == '-' and next_1_char != null and next_1_char.is_digit or next_char.is_digit) then return false end end end previous_char = current_char end return true end   var random_numbers = new Array[Int] var operation = ""   random_numbers = random while not random_numbers.has(24) and random_numbers.length > 1 do var numbers = new Array[Int] var operands = new Array[Char]   print "numbers: " + random_numbers.join(", ") operation = gets if check(operation) then exportation(operation, numbers, operands) if numbers_exists(random_numbers, numbers) then calculation(random_numbers, numbers, operands) remove_numbers(random_numbers, numbers) else print "NUMBERS ERROR!" end else print "STRING ERROR!" end end   if random_numbers.has(24) then print "CONGRATULATIONS" else print "YOU LOSE"
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 ≤ A , B ≤ + 1000 ) {\displaystyle (-1000\leq A,B\leq +1000)} Output data The required output is one integer:   the sum of A and B. Example input   output   2 2 4 3 2 5
#Fantom
Fantom
class APlusB { public static Void main () { echo ("Enter two numbers: ") Str input := Env.cur.in.readLine Int sum := 0 input.split.each |n| { sum += n.toInt } echo (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 sides of the blocks. The sample collection of 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) Task Write a function that takes a string (word) and determines whether the word can be spelled with the given collection of blocks. The rules are simple:   Once a letter on a block is used that block cannot be used again   The function should be case-insensitive   Show the output on this page for the following 7 words in the following example Example >>> can_make_word("A") True >>> can_make_word("BARK") True >>> can_make_word("BOOK") False >>> can_make_word("TREAT") True >>> can_make_word("COMMON") False >>> can_make_word("SQUAD") True >>> can_make_word("CONFUSE") True Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Phix
Phix
sequence blocks, words, used function ABC_Solve(sequence word, integer idx) integer ch, res = 0 if idx>length(word) then res = 1 -- or: res = length(word)>0 -- (if "" -> false desired) else ch = word[idx] for k=1 to length(blocks) do if used[k]=0 and find(ch,blocks[k]) then used[k] = 1 res = ABC_Solve(word,idx+1) used[k] = 0 if res then exit end if end if end for end if return res end function constant tests = {{{"BO","XK","DQ","CP","NA","GT","RE","TG","QD","FS", "JW","HU","VI","AN","OB","ER","FS","LY","PC","ZM"}, {"","A","BarK","BOOK","TrEaT","COMMON","SQUAD","CONFUSE"}}, {{"US","TZ","AO","QA"},{"AuTO"}}, {{"AB","AB","AC","AC"},{"abba"}}} for i=1 to length(tests) do {blocks,words} = tests[i] used = repeat(0,length(blocks)) for j=1 to length(words) do printf(1,"%s: %t\n",{words[j],ABC_Solve(upper(words[j]),1)}) end for end for
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 decide some strategy before any enter the room. Prisoners enter the room one by one, can open a drawer, inspect the card number in the drawer, then close the drawer. A prisoner can open no more than 50 drawers. A prisoner tries to find his own number. A prisoner finding his own number is then held apart from the others. If all 100 prisoners find their own numbers then they will all be pardoned. If any don't then all sentences stand. The task Simulate several thousand instances of the game where the prisoners randomly open drawers Simulate several thousand instances of the game where the prisoners use the optimal strategy mentioned in the Wikipedia article, of: First opening the drawer whose outside number is his prisoner number. If the card within has his number then he succeeds otherwise he opens the drawer with the same number as that of the revealed card. (until he opens his maximum). Show and compare the computed probabilities of success for the two strategies, here, on this page. References The unbelievable solution to the 100 prisoner puzzle standupmaths (Video). wp:100 prisoners problem 100 Prisoners Escape Puzzle DataGenetics. Random permutation statistics#One hundred prisoners on Wikipedia.
#PureBasic
PureBasic
#PRISONERS=100 #DRAWERS =100 #LOOPS = 50 #MAXPROBE = 10000 OpenConsole()   Dim p1(#PRISONERS,#DRAWERS) Dim p2(#PRISONERS,#DRAWERS) Dim d(#DRAWERS)   For i=1 To #DRAWERS : d(i)=i : Next Start: For probe=1 To #MAXPROBE RandomizeArray(d(),1,100) c1=0 : c2=0 For m=1 To #PRISONERS p2(m,1)=d(m) : If d(m)=m : p2(m,0)=1 : EndIf For n=1 To #LOOPS p1(m,n)=d(Random(100,1)) If p1(m,n)=m : p1(m,0)=1 : EndIf If n>1 : p2(m,n)=d(p2(m,n-1)) : If p2(m,n)=m : p2(m,0)=1 : EndIf : EndIf Next n Next m   For m=1 To #PRISONERS If p1(m,0) : c1+1 : p1(m,0)=0 : EndIf If p2(m,0) : c2+1 : p2(m,0)=0 : EndIf Next m   If c1=#PRISONERS : w1+1 : EndIf If c2=#PRISONERS : w2+1 : EndIf Next probe Print("TRIALS: "+Str(#MAXPROBE)) Print(" RANDOM= "+StrF(100*w1/#MAXPROBE,2)+"% STATEGY= "+StrF(100*w2/#MAXPROBE,2)+"%") PrintN(~"\tFIN =q.") : inp$=Input() w1=0 : w2=0 If inp$<>"q" : Goto Start : EndIf
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
#Wren
Wren
import "random" for Random import "/dynamic" for Tuple, Enum, Struct   var N_CARDS = 4 var SOLVE_GOAL = 24 var MAX_DIGIT = 9   var Frac = Tuple.create("Frac", ["num", "den"])   var OpType = Enum.create("OpType", ["NUM", "ADD", "SUB", "MUL", "DIV"])   var Expr = Struct.create("Expr", ["op", "left", "right", "value"])   var showExpr // recursive function showExpr = Fn.new { |e, prec, isRight| if (!e) return if (e.op == OpType.NUM) { System.write(e.value) return } var op = (e.op == OpType.ADD) ? " + " : (e.op == OpType.SUB) ? " - " : (e.op == OpType.MUL) ? " x " : (e.op == OpType.DIV) ? " / " : e.op if ((e.op == prec && isRight) || e.op < prec) System.write("(") showExpr.call(e.left, e.op, false) System.write(op) showExpr.call(e.right, e.op, true) if ((e.op == prec && isRight) || e.op < prec) System.write(")") }   var evalExpr // recursive function evalExpr = Fn.new { |e| if (!e) return Frac.new(0, 1) if (e.op == OpType.NUM) return Frac.new(e.value, 1) var l = evalExpr.call(e.left) var r = evalExpr.call(e.right) var res = (e.op == OpType.ADD) ? Frac.new(l.num * r.den + l.den * r.num, l.den * r.den) : (e.op == OpType.SUB) ? Frac.new(l.num * r.den - l.den * r.num, l.den * r.den) : (e.op == OpType.MUL) ? Frac.new(l.num * r.num, l.den * r.den) : (e.op == OpType.DIV) ? Frac.new(l.num * r.den, l.den * r.num) : Fiber.abort("Unknown op: %(e.op)") return res }   var solve // recursive function solve = Fn.new { |ea, len| if (len == 1) { var final = evalExpr.call(ea[0]) if (final.num == final.den * SOLVE_GOAL && final.den != 0) { showExpr.call(ea[0], OpType.NUM, false) return true } } var ex = List.filled(N_CARDS, null) for (i in 0...len - 1) { for (j in i + 1...len) ex[j - 1] = ea[j] var node = Expr.new(OpType.NUM, null, null, 0) ex[i] = node for (j in i + 1...len) { node.left = ea[i] node.right = ea[j] for (k in OpType.startsFrom+1...OpType.members.count) { node.op = k if (solve.call(ex, len - 1)) return true } node.left = ea[j] node.right = ea[i] node.op = OpType.SUB if (solve.call(ex, len - 1)) return true node.op = OpType.DIV if (solve.call(ex, len - 1)) return true ex[j] = ea[j] } ex[i] = ea[i] } return false }   var solve24 = Fn.new { |n| var l = List.filled(N_CARDS, null) for (i in 0...N_CARDS) l[i] = Expr.new(OpType.NUM, null, null, n[i]) return solve.call(l, N_CARDS) }   var r = Random.new() var n = List.filled(N_CARDS, 0) for (j in 0..9) { for (i in 0...N_CARDS) { n[i] = 1 + r.int(MAX_DIGIT) System.write(" %(n[i])") } System.write(": ") System.print(solve24.call(n) ? "" : "No solution") }
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
#Nim
Nim
import random, terminal   type Tile = uint8 Board = array[16, Tile]   type Operation = enum opInvalid opUp opDown opLeft opRight opQuit opRestart   func charToOperation(c: char): Operation = case c of 'w', 'W': opUp of 'a', 'A': opLeft of 's', 'S': opDown of 'd', 'D': opRight of 'q', 'Q': opQuit of 'r', 'R': opRestart else: opInvalid   proc getKey(): Operation = var c = getch() if c == '\e': c = getch() if c == '[': case getch() of 'A': opUp of 'D': opLeft of 'B': opDown of 'C': opRight else: opInvalid else: charToOperation c else: charToOperation c   func isSolved(board: Board): bool = for i in 0..<board.high: if i != board[i].int - 1: return false true   func findTile(b: Board, n: Tile): int = for i in 0..b.high: if b[i] == n: return i   func canSwap(a, b: int): bool = let dist = a - b dist == 4 or dist == -4 or (dist == 1 and a mod 4 != 0) or (dist == -1 and b mod 4 != 0)   func pad(i: Tile): string = if i == 0: "│ " elif i < 10: "│ " & $i else: "│" & $i   proc draw(b: Board) = echo "┌──┬──┬──┬──┐\n", b[0].pad, b[1].pad, b[2].pad, b[3].pad, "│\n├──┼──┼──┼──┤\n", b[4].pad, b[5].pad, b[6].pad, b[7].pad, "│\n├──┼──┼──┼──┤\n", b[8].pad, b[9].pad, b[10].pad, b[11].pad, "│\n├──┼──┼──┼──┤\n", b[12].pad, b[13].pad, b[14].pad, b[15].pad, "│\n└──┴──┴──┴──┘"   proc clearScreen ()= for i in 1..10: eraseLine() cursorUp()   func calcPosMove(b: var Board; o: Operation; ): int = var posEmpty = b.findTile 0 case o of opUp: return posEmpty + 4 of opDown: return posEmpty - 4 of opLeft: return posEmpty + 1 of opRight: return posEmpty - 1 else: return -1   proc moveTile (b : var Board, op : Operation) : bool = let posMove = b.calcPosMove op let posEmpty = b.findTile 0 if posMove < 16 and posMove >= 0 and canSwap(posEmpty, posMove): swap b[posEmpty], b[posMove] return true return false   proc shuffleBoard ( b: var Board, nSteps : int = 2000 ) = var opMove = @[opUp, opLeft, opDown, opRight] for i in 0 ..< nSteps: let op = opMove[rand(3)] discard b.moveTile op   proc generateBoard: Board = for i in 0..15: if i == 15 : result[i] = 0 else: result[i] = (i + 1).Tile shuffleBoard result   when isMainModule: randomize() var board = generateBoard() empty = board.findTile 0   block gameLoop: while not isSolved board: # draw draw board echo "Press arrow keys or WASD to move, R to Restart, Q to Quit"   # handle input while true: let op = getKey() case op of opRestart: board = generateBoard() empty = board.findTile 0 break of opQuit: break gameLoop of opInvalid: continue else: if board.moveTile op: empty = board.findTile 0 break   clearScreen()   draw board echo "You win!"
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 adjacent tiles (in that direction only) with matching numbers combine into one bearing the sum of those numbers.   A move is valid when at least one tile can be moved,   if only by combination.   A new tile with the value of   2   is spawned at the end of each turn at a randomly chosen empty square   (if there is one).   Adding a new tile on a blank space.   Most of the time,   a new   2   is to be added,   and occasionally   (10% of the time),   a   4.   To win,   the player must create a tile with the number   2048.   The player loses if no valid moves are possible. The name comes from the popular open-source implementation of this game mechanic, 2048. Requirements   "Non-greedy" movement.     The tiles that were created by combining other tiles should not be combined again during the same turn (move).     That is to say,   that moving the tile row of: [2][2][2][2] to the right should result in: ......[4][4] and not: .........[8]   "Move direction priority".     If more than one variant of combining is possible,   move direction shall indicate which combination will take effect.   For example, moving the tile row of: ...[2][2][2] to the right should result in: ......[2][4] and not: ......[4][2]   Check for valid moves.   The player shouldn't be able to skip their turn by trying a move that doesn't change the board.   Check for a  win condition.   Check for a lose condition.
#Pony
Pony
  use "term" use "random" use "time"   interface EdgeRow fun val row() : Iterator[U32] ref fun val inc() : I32   primitive TopRow is EdgeRow fun row() : Iterator[U32] ref => let r : Array[U32] box = [0,1,2,3] r.values() fun inc() : I32 => 4   primitive LeftRow is EdgeRow fun row() : Iterator[U32] ref => let r : Array[U32] box = [0,4,8,12] r.values() fun inc() : I32 => 1   primitive RightRow is EdgeRow fun row() : Iterator[U32] ref => let r : Array[U32] box = [3,7,11,15] r.values() fun inc() : I32 => -1   primitive BottomRow is EdgeRow fun row() : Iterator[U32] ref => let r : Array[U32] box = [12,13,14,15] r.values() fun inc() : I32 => -4   primitive LEFT primitive RIGHT primitive UP primitive DOWN type Move is (LEFT|RIGHT|UP|DOWN)   class KeyboardHandler is ANSINotify let _game : Game tag new iso create(game : Game tag) => _game = game   fun ref apply(term: ANSITerm ref, input: U8 val) => if input == 113 then _game.quit() term.dispose() end fun ref left(ctrl: Bool, alt: Bool, shift: Bool) => _game.move(LEFT) fun ref down(ctrl: Bool, alt: Bool, shift: Bool) => _game.move(DOWN) fun ref up(ctrl: Bool, alt: Bool, shift: Bool) => _game.move(UP) fun ref right(ctrl: Bool, alt: Bool, shift: Bool) => _game.move(RIGHT)   type ROW is (U32,U32,U32,U32)   primitive Merger fun tag apply(r : ROW) : ROW => match r | (0,0,0,_) => (r._4,0,0,0) | (0,0,_,r._3) => (r._3<<1,0,0,0) | (0,0,_,_) => (r._3,r._4,0,0) | (0,_,r._2,_) => (r._2<<1,r._4,0,0) | (0,_,0,r._2) => (r._2<<1,0,0,0) | (0,_,0,_) => (r._2,r._4,0,0) | (0,_,_,r._3) => (r._2,r._3<<1,0,0) | (0,_,_,_) => (r._2,r._3,r._4,0) | (_, r._1, _, r._3) => (r._1<<1, r._3<<1, 0, 0) | (_, r._1, 0, _) => (r._1<<1, r._4, 0, 0) | (_, r._1, _, _) => (r._1<<1, r._3, r._4, 0) | (_, 0,r._1, _) => (r._1<<1,r._4,0,0) | (_, 0,0, r._1) => (r._1<<1,0,0,0) | (_, 0,0, _) => (r._1,r._4,0,0) | (_, 0,_, r._3) => (r._1, r._3<<1,0,0) | (_, 0,_, _) => (r._1, r._3,r._4,0) | (_,_,r._2,_) => (r._1, r._2<<1,r._4,0) | (_,_,0,r._2) => (r._1, r._2<<1,0,0) | (_,_,0,_) => (r._1, r._2,r._4,0) | (_,_,_,r._3) => (r._1, r._2,r._3<<1,0) else r end /** * Game actor */ actor Game embed _grid : Array[U32] = Array[U32].init(0, 16) let _rand : Random = MT(Time.millis()) let _env : Env let _board : String ref = recover String(1024) end   new create(env: Env)=> _env = env _add_block() _add_block() _draw()   fun _merge(start : U32, inc : I32) : (ROW | None) => var st = start.i32() let rval : ROW = (_get(st), _get(st + inc), _get(st + (inc * 2)), _get(st + (inc * 3))) let rout = Merger(rval) if rout is rval then None else rout end   fun ref _update(start : U32, inc : I32) : Bool => match _merge(start, inc) | let rout : ROW => var st = start.i32() _set(st, rout._1) _set(st + inc, rout._2) _set(st + (inc * 2), rout._3) _set(st + (inc * 3), rout._4) true else false end   fun ref _shift_to(edge : EdgeRow val) : Bool => var updated = false for r in edge.row() do if _update(r, edge.inc()) then updated = true end end updated   fun _fmt(i : U32) : String => match i | 0 => " __ " | 2 => "\x1B[31m 2 \x1B[0m" | 4 => "\x1B[32m 4 \x1B[0m" | 8 => "\x1B[33m 8 \x1B[0m" | 16 => "\x1B[34m 16 \x1B[0m" | 32 => "\x1B[35m 32 \x1B[0m" | 64 => "\x1B[36m 64 \x1B[0m" | 128 => "\x1B[37m128 \x1B[0m" | 256 => "\x1B[41m\x1B[37m256 \x1B[0m" | 512 => "\x1B[42m\x1B[37m512 \x1B[0m" | 1024 => "\x1B[43m\x1B[37m1024\x1B[0m" | 2048 => "\x1B[47m\x1B[35m\x1B[1m\x1B[5m2048\x1B[0m" else i.string() end   fun ref _draw() => let s : String ref = _board s.truncate(0) var i : U32 = 0 repeat if (i % 4) == 0 then s.append("---------------------\n") end s.append(_fmt(_get(i))) s.append(" ") i = i + 1 if (i % 4) == 0 then s.append("\n") end until i==16 end _env.out.print(s.string()) _env.out.print("Arrow keys to move. Press (q)uit key to quit.")   fun ref _set(i:(I32|U32), v : U32) => try _grid.update(i.usize(),v) else _env.out.print("cant update!") end   fun _count() : U64 => var c : U64 = 0 for v in _grid.values() do c = c + if v == 0 then 0 else 1 end end c   fun ref _add_block() => let c = _count() if c == 16 then return end   var hit = _rand.int(16 - c) var i : U32 = 0 while i < 16 do if (_get(i) == 0) then if hit == 0 then _set(i, if _rand.int(10) > 0 then 2 else 4 end) break end hit = hit - 1 end i = i + 1 end   fun _get(i : (I32|U32)) : U32 => try _grid(i.usize()) else 0 end   fun _win() : Bool => for v in _grid.values() do if v == 2048 then return true end end false   fun _no_moves(edge : EdgeRow val) : Bool => for r in edge.row() do match _merge(r, edge.inc()) | let rout : ROW => if (rout._1 == 0) or (rout._2 == 0) or (rout._3 == 0) or (rout._4 == 0) then return false end end end true   fun _lose() : Bool => (_grid.size() >= 16) and _no_moves(LeftRow) and _no_moves(RightRow) and _no_moves(TopRow) and _no_moves(BottomRow)   be quit()=> _env.out.print("Exiting.. some terminals may require <ctrl-c>") _env.exitcode(0) _env.input.dispose()   be move(m: Move) => let updated = match m | LEFT => _shift_to(LeftRow) | RIGHT => _shift_to(RightRow) | UP => _shift_to(TopRow) | DOWN => _shift_to(BottomRow) else false end   if _win() then _draw() _env.out.print("You win :)") quit() else if updated then _add_block() _draw() end if _lose() then _env.out.print("You lose :(") quit() end end   actor Main new create(env: Env) => // unit test ifdef "test" then TestMain(env) return end // else game let input : Stdin tag = env.input env.out.print("Welcome to ponylang-2048...") let game = Game(env) let term = ANSITerm(KeyboardHandler(game), input)   let notify : StdinNotify iso = object iso let term: ANSITerm = term let _in: Stdin tag = input fun ref apply(data: Array[U8] iso) => term(consume data) fun ref dispose() => _in.dispose() end   input(consume notify)  
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 down, pass it around 97 bottles of beer on the wall ... and so on, until reaching   0     (zero). Grammatical support for   1 bottle of beer   is optional. As with any puzzle, try to do it in as creative/concise/comical a way as possible (simple, obvious solutions allowed, too). Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet See also   http://99-bottles-of-beer.net/   Category:99_Bottles_of_Beer   Category:Programming language families   Wikipedia 99 bottles of beer
#Cind
Cind
  execute() {   // this class provides synchronization // to get unique number of the bottle   class monitor giver { int number = 100; .get() { return --number; } } var g = new giver();   // start 99 concurrently worked threads // each thread gets own number of the bottle and prints out his own verse // (notice that the output lines from the threads will be mixed together)   {#[99] int nr = g.get(); // get own number host.println(nr," bottles of beer on the wall, "+nr+" bottles of beer"); host.print("Take one down, pass it around,"); if (nr > 1) { host.println((nr-1)," bottles of beer on the wall."); } else { host.println("no more bottles of beer on the wall."); } } host.println("No more bottles of beer on the wall, no more bottles of beer."); host.println("Go to the store and buy some more, 99 bottles of beer on the wall."); return 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. The program should check then evaluate the expression. The goal is for the player to enter an expression that (numerically) evaluates to 24. Only the following operators/functions are allowed: multiplication, division, addition, subtraction Division should use floating point or rational arithmetic, etc, to preserve remainders. Brackets are allowed, if using an infix expression evaluator. Forming multiple digit numbers from the supplied digits is disallowed. (So an answer of 12+12 when given 1, 2, 2, and 1 is wrong). The order of the digits when given does not have to be preserved. Notes The type of expression evaluator used is not mandated. An RPN evaluator is equally acceptable for example. The task is not for the program to generate the expression, or test whether an expression is even possible. Related tasks 24 game/Solve Reference The 24 Game on h2g2.
#Objeck
Objeck
use Collection.Generic; use System.Matrix;   class RPNParser { @stk : Stack<IntHolder>; @digits : List<IntHolder>;   function : Main(args : String[]) ~ Nil { digits := List->New()<IntHolder>; "Make 24 with the digits: "->Print(); for(i := 0; i < 4; i += 1;) { n : Int := Int->Random(1, 9); " {$n}"->Print(); digits->AddBack(n); }; '\n'->Print();   parser := RPNParser->New(); if(parser->Parse(System.IO.Console->ReadString(), digits)) { result := parser->GetResult(); if(result = 24) { "Good job!"->PrintLine(); } else { "{$result}, Try again."->PrintLine(); }; } else { "Invalid sequence"->PrintLine(); }; }   New() { @stk := Stack->New()<IntHolder>; @digits := List->New()<IntHolder>; }   method : Op(f : \Func->Calc) ~ Nil { if(@stk->Size() < 2) { "Improperly written expression"->ErrorLine(); Runtime->Exit(1); }; b := @stk->Pop(); a := @stk->Pop(); @stk->Push(f(a, b)); }   method : Parse(c : Char) ~ Nil { if(c >= '0' & c <= '9') { value : Int := c - '0'; @stk->Push(value); @digits->AddBack(value); } else if(c = '+') { Op(\Func->Calc : (a, b) => a + b); } else if(c = '-') { Op(\Func->Calc : (a, b) => a - b); } else if(c = '*') { Op(\Func->Calc : (a, b) => a * b); } else if(c = '/') { Op(\Func->Calc : (a, b) => { if(b <> 0) { return a / b; } else { return 0; }; }); }; }   method : GetResult() ~ Int { if(@stk->Size() = 1) { return @stk->Top(); };   return 0; }   method : Parse(s : String, digits : List<IntHolder>) ~ Bool { each(i : s) { Parse(s->Get(i)); };   @digits->Rewind(); while(@digits->More()) { left := @digits->Get()->Get(); digits->Rewind(); found := false; while(digits->More() & found = false) { right := digits->Get()->Get(); if(left = right) { digits->Remove(); found := true; } else { digits->Next(); }; }; @digits->Next(); };   return digits->IsEmpty(); } }   alias Func { Calc : (IntHolder, IntHolder) ~ IntHolder }
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 ≤ A , B ≤ + 1000 ) {\displaystyle (-1000\leq A,B\leq +1000)} Output data The required output is one integer:   the sum of A and B. Example input   output   2 2 4 3 2 5
#FBSL
FBSL
#APPTYPE CONSOLE   DIM %a, %b SCANF("%d%d", @a, @b) PRINT a, "+", b, "=", a + b   PAUSE
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 sides of the blocks. The sample collection of 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) Task Write a function that takes a string (word) and determines whether the word can be spelled with the given collection of blocks. The rules are simple:   Once a letter on a block is used that block cannot be used again   The function should be case-insensitive   Show the output on this page for the following 7 words in the following example Example >>> can_make_word("A") True >>> can_make_word("BARK") True >>> can_make_word("BOOK") False >>> can_make_word("TREAT") True >>> can_make_word("COMMON") False >>> can_make_word("SQUAD") True >>> can_make_word("CONFUSE") True Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#PHP
PHP
  <?php $words = array("A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "Confuse");   function canMakeWord($word) { $word = strtoupper($word); $blocks = array( "BO", "XK", "DQ", "CP", "NA", "GT", "RE", "TG", "QD", "FS", "JW", "HU", "VI", "AN", "OB", "ER", "FS", "LY", "PC", "ZM", );   foreach (str_split($word) as $char) { foreach ($blocks as $k => $block) { if (strpos($block, $char) !== FALSE) { unset($blocks[$k]); continue(2); } } return false; } return true; }   foreach ($words as $word) { echo $word.': '; echo canMakeWord($word) ? "True" : "False"; echo "\r\n"; }
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 decide some strategy before any enter the room. Prisoners enter the room one by one, can open a drawer, inspect the card number in the drawer, then close the drawer. A prisoner can open no more than 50 drawers. A prisoner tries to find his own number. A prisoner finding his own number is then held apart from the others. If all 100 prisoners find their own numbers then they will all be pardoned. If any don't then all sentences stand. The task Simulate several thousand instances of the game where the prisoners randomly open drawers Simulate several thousand instances of the game where the prisoners use the optimal strategy mentioned in the Wikipedia article, of: First opening the drawer whose outside number is his prisoner number. If the card within has his number then he succeeds otherwise he opens the drawer with the same number as that of the revealed card. (until he opens his maximum). Show and compare the computed probabilities of success for the two strategies, here, on this page. References The unbelievable solution to the 100 prisoner puzzle standupmaths (Video). wp:100 prisoners problem 100 Prisoners Escape Puzzle DataGenetics. Random permutation statistics#One hundred prisoners on Wikipedia.
#Python
Python
import random   def play_random(n): # using 0-99 instead of ranges 1-100 pardoned = 0 in_drawer = list(range(100)) sampler = list(range(100)) for _round in range(n): random.shuffle(in_drawer) found = False for prisoner in range(100): found = False for reveal in random.sample(sampler, 50): card = in_drawer[reveal] if card == prisoner: found = True break if not found: break if found: pardoned += 1 return pardoned / n * 100 # %   def play_optimal(n): # using 0-99 instead of ranges 1-100 pardoned = 0 in_drawer = list(range(100)) for _round in range(n): random.shuffle(in_drawer) for prisoner in range(100): reveal = prisoner found = False for go in range(50): card = in_drawer[reveal] if card == prisoner: found = True break reveal = card if not found: break if found: pardoned += 1 return pardoned / n * 100 # %   if __name__ == '__main__': n = 100_000 print(" Simulation count:", n) print(f" Random play wins: {play_random(n):4.1f}% of simulations") print(f"Optimal play wins: {play_optimal(n):4.1f}% of simulations")
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
#Yabasic
Yabasic
operators$ = "*+-/" space$ = " "   sub present() clear screen print "24 Game" print "============\n" print "Computer provide 4 numbers (1 to 9). With operators +, -, * and / you try to\nobtain 24." print "Use Reverse Polish Notation (first operand and then the operators)" print "For example: instead of 2 + 4, type 2 4 +\n\n" end sub   repeat present() serie$ = sortString$(genSerie$()) valid$ = serie$+operators$ print "If you give up, press ENTER and the program attempts to find a solution." line input "Write your solution: " input$ if input$ = "" then print "Thinking ... " res$ = explorer$() if res$ = "" print "Can not get 24 with these numbers.." else input$ = delSpace$(input$) inputSort$ = sortString$(input$) if (right$(inputSort$,4) <> serie$) or (len(inputSort$)<>7) then print "Syntax error" else result = evalInput(input$) print "Your solution = ",result," is "; if result = 24 then print "Correct!" else print "Wrong!" end if end if end if print "\nDo you want to try again? (press N for exit, other key to continue)" until(upper$(left$(inkey$(),1)) = "N")   exit   sub genSerie$() local i, c$, s$   print "The numbers you should use are: "; i = ran() for i = 1 to 4 c$ = str$(int(ran(9))+1) print c$," "; s$ = s$ + c$ next i print return s$ end sub     sub evalInput(entr$) local d1, d2, c$, n(4), i   while(entr$<>"") c$ = left$(entr$,1) entr$ = mid$(entr$,2) if instr(serie$,c$) then i = i + 1 n(i) = val(c$) elseif instr(operators$,c$) then d2 = n(i) n(i) = 0 i = i - 1 if i = 0 return d1 = n(i) n(i) = evaluator(d1, d2, c$) else print "Invalid symbol" return end if wend   return n(i)   end sub     sub evaluator(d1, d2, op$) local t   switch op$ case "+": t = d1 + d2 : break case "-": t = d1 - d2 : break case "*": t = d1 * d2 : break case "/": t = d1 / d2 : break end switch   return t end sub     sub delSpace$(entr$) local n, i, s$, t$(1)   n = token(entr$,t$()," ")   for i=1 to n s$ = s$ + t$(i) next i return s$ end sub     sub sortString$(string$) local signal, n, fin, c$   fin = len(string$)-1 repeat signal = false for n = 1 to fin if mid$(string$,n,1) > mid$(string$,n+1,1) then signal = true c$ = mid$(string$,n,1) mid$(string$,n,1) = mid$(string$,n+1,1) mid$(string$,n+1,1) = c$ end if next n until(signal = false) return string$ end sub     sub explorer$() local d1,d2,o3,x4,x5,x6,o7,p$,result,solution,solutions$,n   for d1 = 1 to 4 for d2 = 1 to 4 for o3 = 1 to 4 for x4 = 1 to 8 for x5 = 1 to 8 for x6 = 1 to 8 for o7 = 1 to 4 p$ = mid$(serie$,d1,1)+mid$(serie$,d2,1)+mid$(operators$,o3,1) p$ = p$+mid$(valid$,x4,1)+mid$(valid$,x5,1)+mid$(valid$,x6,1) p$ = p$+mid$(operators$,o7,1) if not instr(solutions$,p$) then if validateInput(p$) then result = evalInput(p$) if result = 24 then solution = solution + 1 print "Solution: ",solution," = "; solutions$ = solutions$ + p$ for n = 1 to 7 print mid$(p$,n,1)," "; next n print end if end if end if next o7 next x6 next x5 next x4 next o3 next d2 next d1 return p$ end sub     sub validateInput(e$) local n, inputSort$   inputSort$ = sortString$(e$) if serie$ <> right$(inputSort$,4) return false for n=1 to 3 if not instr(operators$,mid$(inputSort$,n,1)) then return false end if next n return true end sub
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
#OCaml
OCaml
module Puzzle = struct type t = int array let make () = [| 15; (* 0: the empty space *) 0; 1; 2; 3; 4; 5; 6; 7; 8; 9; 10; 11; 12; 13; 14; |]   let move p n = let hole, i = p.(0), p.(n) in p.(0) <- i; p.(n) <- hole   let print p = let out = Array.make 16 " " in for i = 1 to 15 do out.(p.(i)) <- Printf.sprintf " %2d" i done; for i = 0 to 15 do if (i mod 4) = 0 then print_newline (); print_string out.(i); done   let shuffle p n = for i = 1 to n do move p (1 + Random.int 15) done end   let play () = let p = Puzzle.make () in Puzzle.shuffle p 20; while true do Puzzle.print p; print_string " > "; Puzzle.move p (read_line () |> int_of_string) done
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 adjacent tiles (in that direction only) with matching numbers combine into one bearing the sum of those numbers.   A move is valid when at least one tile can be moved,   if only by combination.   A new tile with the value of   2   is spawned at the end of each turn at a randomly chosen empty square   (if there is one).   Adding a new tile on a blank space.   Most of the time,   a new   2   is to be added,   and occasionally   (10% of the time),   a   4.   To win,   the player must create a tile with the number   2048.   The player loses if no valid moves are possible. The name comes from the popular open-source implementation of this game mechanic, 2048. Requirements   "Non-greedy" movement.     The tiles that were created by combining other tiles should not be combined again during the same turn (move).     That is to say,   that moving the tile row of: [2][2][2][2] to the right should result in: ......[4][4] and not: .........[8]   "Move direction priority".     If more than one variant of combining is possible,   move direction shall indicate which combination will take effect.   For example, moving the tile row of: ...[2][2][2] to the right should result in: ......[2][4] and not: ......[4][2]   Check for valid moves.   The player shouldn't be able to skip their turn by trying a move that doesn't change the board.   Check for a  win condition.   Check for a lose condition.
#Prolog
Prolog
/* ------------------------------------------------------------- Entry point, just create a blank grid and enter a 'game loop' -------------------------------------------------------------*/ play_2048 :- welcome_msg, length(Grid, 16), maplist(=(' '), Grid), % create a blank grid play(Grid, yes), !. % don't have to cut here but it makes the exit cleaner     /* ----------------------------------------------- Messages that will be printed at various points -----------------------------------------------*/ welcome_msg :- format('~nWelcome to the Prolog version of 2048~n~n'), format('To play using w,s,a,d keys for movement, q to quit~n~n'). contrats_msg :- format('Congratulations, you reached 2048!~n~n'). loser_msg :- format('Uh Oh, you could not quite make it to 2048...~n~n'). quit_msg :- format('Bye then!~n~n').     /* ------------------- End game conditions -------------------*/ player_not_won_yet(Grid) :- maplist(dif(2048), Grid). player_wins(Grid) :- member(2048, Grid). player_loses(G) :- move(up, G, G), move(down, G, G), move(left, G, G), move(right, G, G).     /* --------- Game loop ---------*/ % First check if the player has reached the win condition, if not find how many spaces are left play(Grid, _) :- player_wins(Grid), draw_grid(Grid), contrats_msg. play(Grid, CreateNewNum) :- player_not_won_yet(Grid), include(=(' '), Grid, Spaces), length(Spaces, NSpaces), % the number of spaces in the grid play(Grid, CreateNewNum, NSpaces).   % knowing the number of spaces, determine if there is a space, and if we need a new number, and generate. play(Grid, no, _) :- play(Grid). play(Grid, yes, 0) :- play(Grid). play(Grid, yes, NSpaces) :- dif(NSpaces, 0), random_space(NSpaces, Grid, GridWithRandom), play(GridWithRandom).   % with the new number on the grid we can tell if the player has lost the game yet % if not, draw the grid and get the next action by the player play(Grid) :- player_loses(Grid), draw_grid(Grid), loser_msg. play(Grid) :- \+ player_loses(Grid), draw_grid(Grid), next_move_by_player(Move), player_made_move(Grid, Move).   % determine the result of player move player_made_move(_, quit). player_made_move(Grid, Move) :- dif(Move, quit), move(Move, Grid, Grid), % The move creating the same grid indicates that no merge was done play(Grid, no). % don't create a new number player_made_move(Grid, Move) :- dif(Move, quit), move(Move, Grid, MovedGrid), dif(Grid, MovedGrid), play(MovedGrid, yes).     /* --------------------------------------- Get the next move from the player input ---------------------------------------*/ next_move_by_player(Move) :- repeat, get_single_char(Char), key_move(Char, Move).   % valid keys are: up = 'w', down = 's', left = 'a' right = 'd', quit = 'q' key_move(119, up). key_move(115, down). key_move(97, left). key_move(100, right). key_move(113, quit).     /* ------------------ Draw the Game grid ------------------*/ draw_grid([A1,A2,A3,A4,B1,B2,B3,B4,C1,C2,C3,C4,D1,D2,D3,D4]) :- format( '+-------------------+~n'), row([A1,A2,A3,A4]), row([B1,B2,B3,B4]), row([C1,C2,C3,C4]), maplist(draw, [D1,D2,D3,D4]), format('¦~n+-------------------+~n~n~n').   row([A,B,C,D]) :- maplist(draw, [A,B,C,D]), format('¦~n¦----+----+----+----¦~n').   draw(' ') :- format('¦ '). draw(X) :- member(X,[2,4,8]), format('¦ ~d ', X). draw(X) :- member(X,[16,32,64]), format('¦ ~d ', X). draw(X) :- member(X,[128,256,512]), format('¦ ~d', X). draw(X) :- member(X,[1024,2048]), format('¦~d', X).     /* ---------------------------------------- Populate a random space with a new value ----------------------------------------*/ random_space(0, G, G). random_space(1, Grid, GridWithRandom) :- four_or_two(V), select(' ', Grid, V, GridWithRandom). random_space(N, Grid, GridWithRandom) :- N > 1, four_or_two(V), random(1, N, P), replace_space(P, V, Grid, GridWithRandom).   replace_space(0, V, [' '|T], [V|T]). replace_space(P, V, [' '|T], [' '|R]) :- succ(NextP, P), replace_space(NextP, V, T, R). replace_space(P, V, [H|T], [H|R]) :- dif(' ', H), replace_space(P, V, T, R).   four_or_two(V) :- random(1, 10, IsFour), IsFour = 1 -> V = 4 ; V = 2.     /* ------------------------------------------ Process a game move based on the direction ------------------------------------------*/ move(Direction, UnMoved, Moved) :- map_move(Direction, UnMoved, UnMovedMapped), maplist(combine_row, UnMovedMapped, MovedMapped), map_move(Direction, Moved, MovedMapped).   % convert the array to a set of lists that can be moved in the same % direction. This can be reversed after the move is completed. map_move(up, [A1,A2,A3,A4,B1,B2,B3,B4,C1,C2,C3,C4,D1,D2,D3,D4], [[D1,C1,B1,A1],[D2,C2,B2,A2],[D3,C3,B3,A3],[D4,C4,B4,A4]]). map_move(down, [A1,A2,A3,A4,B1,B2,B3,B4,C1,C2,C3,C4,D1,D2,D3,D4], [[A1,B1,C1,D1],[A2,B2,C2,D2],[A3,B3,C3,D3],[A4,B4,C4,D4]]). map_move(left, [A1,A2,A3,A4,B1,B2,B3,B4,C1,C2,C3,C4,D1,D2,D3,D4], [[A4,A3,A2,A1],[B4,B3,B2,B1],[C4,C3,C2,C1],[D4,D3,D2,D1]]). map_move(right, [A1,A2,A3,A4,B1,B2,B3,B4,C1,C2,C3,C4,D1,D2,D3,D4], [[A1,A2,A3,A4],[B1,B2,B3,B4],[C1,C2,C3,C4],[D1,D2,D3,D4]]).   % remove all the spaces, then put them at the front of the list combine_row(UnMoved, Moved) :- partition(=(' '), UnMoved, Blank, Set), append(Blank, Set, ReadyToMove), combine(ReadyToMove, Moved).   % combine based on the rules of the game. combine([A,B,C,D], [A,B,C,D]) :- dif(A,B), dif(B,C), dif(C,D). combine([A,A,B,B], [' ',' ',Ad,Bd]) :- dbl(A,Ad), dbl(B,Bd). combine([A,B,C,C], [' ',A,B,Cd]) :- dif(A,B), dbl(C,Cd). combine([A,B,B,C], [' ',A,Bd,C]) :- dif(B,C), dbl(B,Bd). combine([A,A,B,C], [' ',Ad,B,C]) :- dif(A,B), dif(B,C), dbl(A, Ad). combine([A,B,C,C], [' ',A,B,Cd]) :- dif(A,B), dif(B,C), dbl(C,Cd).   % this could be done using maths, but it is more prology this way. dbl(' ', ' '). dbl(2,4). dbl(4,8). dbl(8,16). dbl(16,32). dbl(32,64). dbl(64,128). dbl(128,256). dbl(256,512). dbl(512,1028). dbl(1028,2048).  
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 down, pass it around 97 bottles of beer on the wall ... and so on, until reaching   0     (zero). Grammatical support for   1 bottle of beer   is optional. As with any puzzle, try to do it in as creative/concise/comical a way as possible (simple, obvious solutions allowed, too). Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet See also   http://99-bottles-of-beer.net/   Category:99_Bottles_of_Beer   Category:Programming language families   Wikipedia 99 bottles of beer
#Clay
Clay
/* A few options here: I could give n type Int; or specify that n is of any numeric type; but here I just let it go -- that way it'll work with anything that compares with 1 and that printTo knows how to convert to a string. And all checked at compile time, remember. */ getRound(n) { var s = String(); var bottle = if (n == 1) " bottle " else " bottles ";   printTo(s, n, bottle, "of beer on the wall\n", n, bottle, "of beer\n", "take one down, pass it around\n", n, bottle, "of beer on the wall!\n");   return s; }   main() { println(join("\n", mapped(getRound, reversed(range(100))))); }  
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. The program should check then evaluate the expression. The goal is for the player to enter an expression that (numerically) evaluates to 24. Only the following operators/functions are allowed: multiplication, division, addition, subtraction Division should use floating point or rational arithmetic, etc, to preserve remainders. Brackets are allowed, if using an infix expression evaluator. Forming multiple digit numbers from the supplied digits is disallowed. (So an answer of 12+12 when given 1, 2, 2, and 1 is wrong). The order of the digits when given does not have to be preserved. Notes The type of expression evaluator used is not mandated. An RPN evaluator is equally acceptable for example. The task is not for the program to generate the expression, or test whether an expression is even possible. Related tasks 24 game/Solve Reference The 24 Game on h2g2.
#OCaml
OCaml
ocamlopt -pp camlp4o g24.ml -o g24.opt
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 ≤ A , B ≤ + 1000 ) {\displaystyle (-1000\leq A,B\leq +1000)} Output data The required output is one integer:   the sum of A and B. Example input   output   2 2 4 3 2 5
#Fhidwfe
Fhidwfe
  function listint scanint (num:ptr) {// as of writing, fhidwfe has no builtin int scanning reset negative read = num num1 = 0 num2 = 0 while ~ = deref_ubyte$ read ' ' { char = deref_ubyte$ read if = char '-' { set negative } { num1 = + * 10 num1 as - char '0' int } read = + read 1u } if negative { num1 = !num1 } ; reset negative read = + read 1u while ~ = deref_ubyte$ read 0ub { char2 = deref_ubyte$ read if = char2 '-' { set negative } { num2 = + * 10 num2 as - char2 '0' int } read = + read 1u } if negative { num2 = !num2 } ; return (num1 num2) }   //the real program text = malloc$ 12u//worst input is -1000 -1000, or 11 bytes + null terminator getline$ text inp = scanint$ text free$ text puti$ + access_word$ inp 0u access_word$ inp 1u free$ inp  
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 sides of the blocks. The sample collection of 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) Task Write a function that takes a string (word) and determines whether the word can be spelled with the given collection of blocks. The rules are simple:   Once a letter on a block is used that block cannot be used again   The function should be case-insensitive   Show the output on this page for the following 7 words in the following example Example >>> can_make_word("A") True >>> can_make_word("BARK") True >>> can_make_word("BOOK") False >>> can_make_word("TREAT") True >>> can_make_word("COMMON") False >>> can_make_word("SQUAD") True >>> can_make_word("CONFUSE") True Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Picat
Picat
go => test_it(check_word), test_it(check_word2), nl.   % Get all possible solutions (via fail) go2 ?=> test_version(check_word2), fail, nl. go2 => true.   % % Test a version. % test_it(Pred) => println(testing=Pred), Blocks = findall([A,B], block(A,B)), Words = findall(W,word(W)), foreach(Word in Words) println(word=Word), ( call(Pred,Word,Blocks) ; println("Cannot make word.")), nl end, nl.   % % Picat style: Using nth/3 for getting the chars % check_word(Word, Blocks) => WordC = atom_chars(Word), % convert atom to string WordLen = length(WordC), X = new_list(WordLen), Pos = new_list(WordLen), foreach(I in 1..WordLen)  % find a character at the specific position nth(X[I],Blocks,XI), nth(Pos[I],XI, WordC[I]) end, alldiff(X), % ensure unique selection foreach(I in 1..WordLen) println([WordC[I], Blocks[X[I]]]) end, nl.   % % Prolog style (recursive) version using select/3. % (where we don't have to worry about duplicate blocks) % check_word2(Word, Blocks) :- pick_block(atom_chars(Word),Blocks,[],X), println(X).   pick_block([], _,Res,Res). pick_block([C|WordRest], Blocks, Res1,[Block|Res]) :-  % pick (non-deterministically) one of the blocks select(Block,Blocks,BlocksRest), membchk(C,Block), pick_block(WordRest,BlocksRest,Res1,Res).   % % alldiff(L): % ensure that all elements in L are different % alldiff([]). alldiff([_]). alldiff([H|T]) :- neq(H,T), alldiff(T).   neq(_,[]). neq(X,[H|T]) :- X != H, neq(X,T).   % The words to check. word(a). word(bark). word(book). word(treat). word(common). word(squad). word(confuse). word(auto). word(abba). word(coestablishment). word(schoolmastering).   % The blocks block(b,o). block(x,k). block(d,q). block(c,p). block(n,a). block(g,t). block(r,e). block(t,g). block(q,d). block(f,s). block(j,w). block(h,u). block(v,i). block(a,n). block(o,b). block(e,r). block(f,s). block(l,y). block(p,c). block(z,m).  
http://rosettacode.org/wiki/100_prisoners
100 prisoners
The Problem 100 prisoners are individually numbered 1 to 100 A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside. Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start. Prisoners start outside the room They can decide some strategy before any enter the room. Prisoners enter the room one by one, can open a drawer, inspect the card number in the drawer, then close the drawer. A prisoner can open no more than 50 drawers. A prisoner tries to find his own number. A prisoner finding his own number is then held apart from the others. If all 100 prisoners find their own numbers then they will all be pardoned. If any don't then all sentences stand. The task Simulate several thousand instances of the game where the prisoners randomly open drawers Simulate several thousand instances of the game where the prisoners use the optimal strategy mentioned in the Wikipedia article, of: First opening the drawer whose outside number is his prisoner number. If the card within has his number then he succeeds otherwise he opens the drawer with the same number as that of the revealed card. (until he opens his maximum). Show and compare the computed probabilities of success for the two strategies, here, on this page. References The unbelievable solution to the 100 prisoner puzzle standupmaths (Video). wp:100 prisoners problem 100 Prisoners Escape Puzzle DataGenetics. Random permutation statistics#One hundred prisoners on Wikipedia.
#R
R
t = 100000 #number of trials success.r = rep(0,t) #this will keep track of how many prisoners find their ticket on each trial for the random method success.o = rep(0,t) #this will keep track of how many prisoners find their ticket on each trial for the optimal method   #random method for(i in 1:t){ escape = rep(F,100) ticket = sample(1:100) for(j in 1:length(prisoner)){ escape[j] = j %in% sample(ticket,50) } success.r[i] = sum(escape) }   #optimal method for(i in 1:t){ escape = rep(F,100) ticket = sample(1:100) for(j in 1:100){ boxes = 0 current.box = j while(boxes<50 && !escape[j]){ boxes=boxes+1 escape[j] = ticket[current.box]==j current.box = ticket[current.box] } } success.o[i] = sum(escape) }   cat("Random method resulted in a success rate of ",100*mean(success.r==100), "%.\nOptimal method resulted in a success rate of ",100*mean(success.o==100),"%.",sep="")
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
#zkl
zkl
var [const] H=Utils.Helpers; fcn u(xs){ xs.reduce(fcn(us,s){us.holds(s) and us or us.append(s) },L()) } var ops=u(H.combosK(3,"+-*/".split("")).apply(H.permute).flatten()); var fs=T( fcn f0(a,b,c,d,x,y,z){ Op(z)(Op(y)(Op(x)(a,b),c),d) }, // ((AxB)yC)zD fcn f1(a,b,c,d,x,y,z){ Op(y)(Op(x)(a,b),Op(z)(c,d)) }, // (AxB)y(CzD) fcn f2(a,b,c,d,x,y,z){ Op(z)(Op(x)(a,Op(y)(b,c)),d) }, // (Ax(ByC))zD fcn f3(a,b,c,d,x,y,z){ Op(x)(a,Op(z)(Op(y)(b,c),d)) }, // Ax((ByC)zD) fcn f4(a,b,c,d,x,y,z){ Op(x)(a,Op(y)(b,Op(z)(c,d))) }, // Ax(By(CzD)) );   var fts= // format strings for human readable formulas T("((d.d).d).d", "(d.d).(d.d)", "(d.(d.d)).d", "d.((d.d).d)", "d.(d.(d.d))") .pump(List,T("replace","d","%d"),T("replace",".","%s"));   fcn f2s(digits,ops,f){ fts[f.name[1].toInt()].fmt(digits.zip(ops).flatten().xplode(),digits[3]); }   fcn game24Solver(digitsString){ digits:=digitsString.split("").apply("toFloat"); [[(digits4,ops3,f); H.permute(digits); ops; // list comprehension fs,{ try{f(digits4.xplode(),ops3.xplode()).closeTo(24,0.001) } catch(MathError){ False } }; { f2s(digits4,ops3,f) }]]; }
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
#Pascal
Pascal
  program fifteen; {$mode objfpc} {$modeswitch advancedrecords} {$coperators on} uses SysUtils, crt; type TPuzzle = record private const ROW_COUNT = 4; COL_COUNT = 4; CELL_COUNT = ROW_COUNT * COL_COUNT; RAND_RANGE = 101; type TTile = 0..Pred(CELL_COUNT); TAdjacentCell = (acLeft, acTop, acRight, acBottom); TPossibleMoves = set of TTile; TCellAdjacency = set of TAdjacentCell; TBoard = array[0..Pred(CELL_COUNT)] of TTile; class var HBar: string; var FBoard: TBoard; FZeroPos, FMoveCount: Integer; FZeroAdjacency: TCellAdjacency; FPossibleMoves: TPossibleMoves; FSolved: Boolean; procedure DoMove(aTile: TTile); procedure CheckPossibleMoves; procedure PrintBoard; procedure PrintPossibleMoves; procedure TestSolved; procedure GenerateBoard; class constructor Init; public procedure New; function UserMoved: Boolean; property MoveCount: Integer read FMoveCount; property Solved: Boolean read FSolved; end;   procedure TPuzzle.DoMove(aTile: TTile); var Pos: Integer = -1; Adj: TAdjacentCell; begin for Adj in FZeroAdjacency do begin case Adj of acLeft: Pos := Pred(FZeroPos); acTop: Pos := FZeroPos - COL_COUNT; acRight: Pos := Succ(FZeroPos); acBottom: Pos := FZeroPos + COL_COUNT; end; if FBoard[Pos] = aTile then break; end; FBoard[FZeroPos] := aTile; FZeroPos := Pos; FBoard[Pos] := 0; end;   procedure TPuzzle.CheckPossibleMoves; var Row, Col: Integer; begin Row := FZeroPos div COL_COUNT; Col := FZeroPos mod COL_COUNT; FPossibleMoves := []; FZeroAdjacency := []; if Row > 0 then begin FPossibleMoves += [FBoard[FZeroPos - COL_COUNT]]; FZeroAdjacency += [acTop]; end; if Row < Pred(ROW_COUNT) then begin FPossibleMoves += [FBoard[FZeroPos + COL_COUNT]]; FZeroAdjacency += [acBottom]; end; if Col > 0 then begin FPossibleMoves += [FBoard[Pred(FZeroPos)]]; FZeroAdjacency += [acLeft]; end; if Col < Pred(COL_COUNT) then begin FPossibleMoves += [FBoard[Succ(FZeroPos)]]; FZeroAdjacency += [acRight]; end; end;   procedure TPuzzle.PrintBoard; const Space = ' '; VBar = '|'; VBar1 = '| '; VBar2 = '| '; VBar3 = '| '; var I, J, Pos, Tile: Integer; Row: string; begin ClrScr; Pos := 0; WriteLn(HBar); for I := 1 to ROW_COUNT do begin Row := ''; for J := 1 to COL_COUNT do begin Tile := Integer(FBoard[Pos]); case Tile of 0: Row += VBar3; 1..9: Row += VBar2 + Tile.ToString + Space; else Row += VBar1 + Tile.ToString + Space; end; Inc(Pos); end; WriteLn(Row + VBar); WriteLn(HBar); end; if not Solved then PrintPossibleMoves; end;   procedure TPuzzle.PrintPossibleMoves; var pm: TTile; spm: string = ''; begin for pm in FPossibleMoves do spm += Integer(pm).ToString + ' '; WriteLn('possible moves: ', spm); end;   procedure TPuzzle.TestSolved; function IsSolved: Boolean; var I: Integer; begin for I := 0 to CELL_COUNT - 3 do if FBoard[I] <> Pred(FBoard[Succ(I)]) then exit(False); Result := True; end; begin FSolved := IsSolved; if not Solved then CheckPossibleMoves; end;   procedure TPuzzle.GenerateBoard; var I, CurrMove, SelMove: Integer; Tile: TTile; begin FZeroPos := Pred(CELL_COUNT); FBoard[FZeroPos] := 0; for I := 0 to CELL_COUNT - 2 do FBoard[I] := Succ(I); for I := 1 to Random(RAND_RANGE) do begin CheckPossibleMoves; SelMove := 0; for Tile in FPossibleMoves do Inc(SelMove); SelMove := Random(SelMove); CurrMove := 0; for Tile in FPossibleMoves do begin if CurrMove = SelMove then begin DoMove(Tile); break; end; Inc(CurrMove); end; end; end;   class constructor TPuzzle.Init; var I: Integer; begin HBar := ''; for I := 1 to COL_COUNT do HBar += '+----'; HBar += '+'; end;   procedure TPuzzle.New; begin FSolved := False; FMoveCount := 0; GenerateBoard; CheckPossibleMoves; PrintBoard; end;   function TPuzzle.UserMoved: Boolean; const Sorry = 'sorry, '; InvalidInput = ' is invalid input'; ImpossibleMove = ' is impossible move'; var UserInput: string; Tile: Integer = 0; begin ReadLn(UserInput); case LowerCase(UserInput) of 'c', 'cancel': exit(False); end; Result := True; if not Tile.TryParse(UserInput, Tile) then begin WriteLn(Sorry, UserInput, InvalidInput); exit; end; if not (Tile in [1..Pred(CELL_COUNT)]) then begin WriteLn(Sorry, Tile, InvalidInput); exit; end; if not (Tile in FPossibleMoves) then begin WriteLn(Sorry, Tile, ImpossibleMove); PrintPossibleMoves; exit; end; DoMove(Tile); Inc(FMoveCount); TestSolved; PrintBoard; end;   procedure PrintStart; begin ClrScr; WriteLn('Fifteen puzzle start:'); WriteLn(' enter a tile number and press <enter> to move' ); WriteLn(' enter Cancel(C) and press <enter> to exit' ); Window(10, 4, 58, 21); end;   procedure Terminate; begin ClrScr; Window(1, 1, 80, 25); ClrScr; WriteLn('Fifteen puzzle exit.'); Halt; end;   function UserWantContinue(aMoveCount: Integer): Boolean; var UserInput: string; begin WriteLn('Congratulations! Puzzle solved in ', aMoveCount, ' moves.'); WriteLn('Play again(Yes(Y)/<any button>)?'); ReadLn(UserInput); case LowerCase(UserInput) of 'y', 'yes': exit(True); end; Result := False; end;   procedure Run; var Puzzle: TPuzzle; begin Randomize; PrintStart; repeat Puzzle.New; while not Puzzle.Solved do if not Puzzle.UserMoved then Terminate; if not UserWantContinue(Puzzle.MoveCount) then Terminate; until False; end;   begin Run; end.  
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 adjacent tiles (in that direction only) with matching numbers combine into one bearing the sum of those numbers.   A move is valid when at least one tile can be moved,   if only by combination.   A new tile with the value of   2   is spawned at the end of each turn at a randomly chosen empty square   (if there is one).   Adding a new tile on a blank space.   Most of the time,   a new   2   is to be added,   and occasionally   (10% of the time),   a   4.   To win,   the player must create a tile with the number   2048.   The player loses if no valid moves are possible. The name comes from the popular open-source implementation of this game mechanic, 2048. Requirements   "Non-greedy" movement.     The tiles that were created by combining other tiles should not be combined again during the same turn (move).     That is to say,   that moving the tile row of: [2][2][2][2] to the right should result in: ......[4][4] and not: .........[8]   "Move direction priority".     If more than one variant of combining is possible,   move direction shall indicate which combination will take effect.   For example, moving the tile row of: ...[2][2][2] to the right should result in: ......[2][4] and not: ......[4][2]   Check for valid moves.   The player shouldn't be able to skip their turn by trying a move that doesn't change the board.   Check for a  win condition.   Check for a lose condition.
#Python
Python
#!/usr/bin/env python3   import curses from random import randrange, choice # generate and place new tile from collections import defaultdict   letter_codes = [ord(ch) for ch in 'WASDRQwasdrq'] actions = ['Up', 'Left', 'Down', 'Right', 'Restart', 'Exit'] actions_dict = dict(zip(letter_codes, actions * 2))   def get_user_action(keyboard): char = "N" while char not in actions_dict: char = keyboard.getch() return actions_dict[char]   def transpose(field): return [list(row) for row in zip(*field)]   def invert(field): return [row[::-1] for row in field]   class GameField(object): def __init__(self, height=4, width=4, win=2048): self.height = height self.width = width self.win_value = win self.score = 0 self.highscore = 0 self.reset()   def reset(self): if self.score > self.highscore: self.highscore = self.score self.score = 0 self.field = [[0 for i in range(self.width)] for j in range(self.height)] self.spawn() self.spawn()   def move(self, direction): def move_row_left(row): def tighten(row): # squeese non-zero elements together new_row = [i for i in row if i != 0] new_row += [0 for i in range(len(row) - len(new_row))] return new_row   def merge(row): pair = False new_row = [] for i in range(len(row)): if pair: new_row.append(2 * row[i]) self.score += 2 * row[i] pair = False else: if i + 1 < len(row) and row[i] == row[i + 1]: pair = True new_row.append(0) else: new_row.append(row[i]) assert len(new_row) == len(row) return new_row return tighten(merge(tighten(row)))   moves = {} moves['Left'] = lambda field: \ [move_row_left(row) for row in field] moves['Right'] = lambda field: \ invert(moves['Left'](invert(field))) moves['Up'] = lambda field: \ transpose(moves['Left'](transpose(field))) moves['Down'] = lambda field: \ transpose(moves['Right'](transpose(field)))   if direction in moves: if self.move_is_possible(direction): self.field = moves[direction](self.field) self.spawn() return True else: return False   def is_win(self): return any(any(i >= self.win_value for i in row) for row in self.field)   def is_gameover(self): return not any(self.move_is_possible(move) for move in actions)   def draw(self, screen): help_string1 = '(W)Up (S)Down (A)Left (D)Right' help_string2 = ' (R)Restart (Q)Exit' gameover_string = ' GAME OVER' win_string = ' YOU WIN!' def cast(string): screen.addstr(string + '\n')   def draw_hor_separator(): top = '┌' + ('┬──────' * self.width + '┐')[1:] mid = '├' + ('┼──────' * self.width + '┤')[1:] bot = '└' + ('┴──────' * self.width + '┘')[1:] separator = defaultdict(lambda: mid) separator[0], separator[self.height] = top, bot if not hasattr(draw_hor_separator, "counter"): draw_hor_separator.counter = 0 cast(separator[draw_hor_separator.counter]) draw_hor_separator.counter += 1   def draw_row(row): cast(''.join('│{: ^5} '.format(num) if num > 0 else '| ' for num in row) + '│')   screen.clear() cast('SCORE: ' + str(self.score)) if 0 != self.highscore: cast('HIGHSCORE: ' + str(self.highscore)) for row in self.field: draw_hor_separator() draw_row(row) draw_hor_separator() if self.is_win(): cast(win_string) else: if self.is_gameover(): cast(gameover_string) else: cast(help_string1) cast(help_string2)   def spawn(self): new_element = 4 if randrange(100) > 89 else 2 (i,j) = choice([(i,j) for i in range(self.width) for j in range(self.height) if self.field[i][j] == 0]) self.field[i][j] = new_element   def move_is_possible(self, direction): def row_is_left_movable(row): def change(i): # true if there'll be change in i-th tile if row[i] == 0 and row[i + 1] != 0: # Move return True if row[i] != 0 and row[i + 1] == row[i]: # Merge return True return False return any(change(i) for i in range(len(row) - 1))   check = {} check['Left'] = lambda field: \ any(row_is_left_movable(row) for row in field)   check['Right'] = lambda field: \ check['Left'](invert(field))   check['Up'] = lambda field: \ check['Left'](transpose(field))   check['Down'] = lambda field: \ check['Right'](transpose(field))   if direction in check: return check[direction](self.field) else: return False   def main(stdscr): curses.use_default_colors() game_field = GameField(win=32) state_actions = {} # Init, Game, Win, Gameover, Exit def init(): game_field.reset() return 'Game'   state_actions['Init'] = init   def not_game(state): game_field.draw(stdscr) action = get_user_action(stdscr) responses = defaultdict(lambda: state) responses['Restart'], responses['Exit'] = 'Init', 'Exit' return responses[action]   state_actions['Win'] = lambda: not_game('Win') state_actions['Gameover'] = lambda: not_game('Gameover')   def game(): game_field.draw(stdscr) action = get_user_action(stdscr) if action == 'Restart': return 'Init' if action == 'Exit': return 'Exit' if game_field.move(action): # move successful if game_field.is_win(): return 'Win' if game_field.is_gameover(): return 'Gameover' return 'Game'   state_actions['Game'] = game   state = 'Init' while state != 'Exit': state = state_actions[state]()   curses.wrapper(main)  
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 down, pass it around 97 bottles of beer on the wall ... and so on, until reaching   0     (zero). Grammatical support for   1 bottle of beer   is optional. As with any puzzle, try to do it in as creative/concise/comical a way as possible (simple, obvious solutions allowed, too). Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet See also   http://99-bottles-of-beer.net/   Category:99_Bottles_of_Beer   Category:Programming language families   Wikipedia 99 bottles of beer
#Clio
Clio
fn bottle n: n -> if = 0: 'no more bottles' elif = 1: n + ' bottle' else: n + ' bottles'   [99:0] -> * (@eager) fn i: i -> bottle -> print (transform i: sentence-case) 'of beer on the wall,' @ 'of beer.' if i = 0: 'Go to the store, buy some more, 99 bottles of beer on the wall.' -> print else: i - 1 -> bottle -> print 'Take one down and pass it around,' @ '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. The program should check then evaluate the expression. The goal is for the player to enter an expression that (numerically) evaluates to 24. Only the following operators/functions are allowed: multiplication, division, addition, subtraction Division should use floating point or rational arithmetic, etc, to preserve remainders. Brackets are allowed, if using an infix expression evaluator. Forming multiple digit numbers from the supplied digits is disallowed. (So an answer of 12+12 when given 1, 2, 2, and 1 is wrong). The order of the digits when given does not have to be preserved. Notes The type of expression evaluator used is not mandated. An RPN evaluator is equally acceptable for example. The task is not for the program to generate the expression, or test whether an expression is even possible. Related tasks 24 game/Solve Reference The 24 Game on h2g2.
#Oforth
Oforth
import: mapping   : game | l expr w n i | 4 #[ 9 rand ] Array init ->l   System.Out "Digits : " << l << " --> RPN Expression for 24 : " << drop System.Console accept ->expr   expr words forEach: w [ w "+" == ifTrue: [ + continue ] w "-" == ifTrue: [ - continue ] w "*" == ifTrue: [ * continue ] w "/" == ifTrue: [ >float / continue ]   w >integer dup ->n ifNull: [ System.Out "Word " << w << " not allowed " << cr break ] n l indexOf dup ->i ifNull: [ System.Out "Integer " << n << " is wrong " << cr break ] n l put(i, null) ] #null? l conform? ifFalse: [ "Sorry, all numbers must be used..." . return ] 24 if=: [ "You won !" ] else: [ "You loose..." ] . ;
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 ≤ A , B ≤ + 1000 ) {\displaystyle (-1000\leq A,B\leq +1000)} Output data The required output is one integer:   the sum of A and B. Example input   output   2 2 4 3 2 5
#Fish
Fish
i:o:"-"=?v1$68*-v v >~01-0 > >i:o:" "=?v68*-$a*+ >~*i:o:"-"=?v1$68*-v v >~01-0 > >i:o:d=?v68*-$a*+ >~*+aonao;
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 sides of the blocks. The sample collection of 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) Task Write a function that takes a string (word) and determines whether the word can be spelled with the given collection of blocks. The rules are simple:   Once a letter on a block is used that block cannot be used again   The function should be case-insensitive   Show the output on this page for the following 7 words in the following example Example >>> can_make_word("A") True >>> can_make_word("BARK") True >>> can_make_word("BOOK") False >>> can_make_word("TREAT") True >>> can_make_word("COMMON") False >>> can_make_word("SQUAD") True >>> can_make_word("CONFUSE") True Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#PicoLisp
PicoLisp
(setq *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) ) ) (setq *Words '("" "1" "A" "BARK" "BOOK" "TREAT" "Bbb" "COMMON" "SQUAD" "Confuse" "abba" "ANBOCPDQERSFTGUVWXLZ") )   (de abc (W B) (let Myblocks (copy B) (fully '((C) (when (seek '((Lst) (member C (car Lst))) Myblocks) (set @) T ) ) (chop (uppc W)) ) ) )   (de abcR (W B) (nond ((car W) T) ((car B) NIL) (NIL (setq W (chop W)) (let? I (find '((Lst) (member (uppc (car W)) Lst)) B ) (abcR (cdr W) (delete I B)) ) ) ) )   (for Word *Words (println Word (abc Word *Blocks) (abcR Word *Blocks)) )   (bye)
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 decide some strategy before any enter the room. Prisoners enter the room one by one, can open a drawer, inspect the card number in the drawer, then close the drawer. A prisoner can open no more than 50 drawers. A prisoner tries to find his own number. A prisoner finding his own number is then held apart from the others. If all 100 prisoners find their own numbers then they will all be pardoned. If any don't then all sentences stand. The task Simulate several thousand instances of the game where the prisoners randomly open drawers Simulate several thousand instances of the game where the prisoners use the optimal strategy mentioned in the Wikipedia article, of: First opening the drawer whose outside number is his prisoner number. If the card within has his number then he succeeds otherwise he opens the drawer with the same number as that of the revealed card. (until he opens his maximum). Show and compare the computed probabilities of success for the two strategies, here, on this page. References The unbelievable solution to the 100 prisoner puzzle standupmaths (Video). wp:100 prisoners problem 100 Prisoners Escape Puzzle DataGenetics. Random permutation statistics#One hundred prisoners on Wikipedia.
#QB64
QB64
  Const Found = -1, Searching = 0, Status = 1, Tries = 2 Const Attempt = 1, Victories = 2, RandomW = 1, ChainW = 2 Randomize Timer   Dim Shared Prisoners(1 To 100, Status To Tries) As Integer, Drawers(1 To 100) As Integer, Results(1 To 2, 1 To 2) As Integer Print "100 prisoners" Print "Random way to search..." For a = 1 To 2000 Init Results(RandomW, Attempt) = Results(RandomW, Attempt) + 1 RandomWay If verify% Then Results(RandomW, Victories) = Results(RandomW, Victories) + 1 Next   Print: Print "Chain way to search..." For a = 1 To 2000 Init Results(ChainW, Attempt) = Results(ChainW, Attempt) + 1 ChainWay If verify% Then Results(ChainW, Victories) = Results(ChainW, Victories) + 1 Next Print: Print "Results: " Print " Attempts "; Results(RandomW, Attempt); " "; "Victories "; Results(RandomW, Victories); " Ratio:"; Results(RandomW, Victories); "/"; Results(RandomW, Attempt) Print Print " Attempts "; Results(ChainW, Attempt); " "; "Victories "; Results(ChainW, Victories); " Ratio:"; Results(ChainW, Victories); "/"; Results(ChainW, Attempt) End   Function verify% Dim In As Integer Print "veryfing " verify = 0 For In = 1 To 100 If Prisoners(In, Status) = Searching Then Exit For Next If In = 101 Then verify% = Found End Function   Sub ChainWay Dim In As Integer, ChainChoice As Integer Print "Chain search" For In = 1 To 100 ChainChoice = In Do Prisoners(In, Tries) = Prisoners(In, Tries) + 1 If Drawers(ChainChoice) = In Then Prisoners(In, Status) = Found: Exit Do ChainChoice = Drawers(ChainChoice) Loop Until Prisoners(In, Tries) = 50 Next In End Sub   Sub RandomWay Dim In As Integer, RndChoice As Integer Print "Random search" For In = 1 To 100 Do Prisoners(In, Tries) = Prisoners(In, Tries) + 1 If Drawers(Int(Rnd * 100) + 1) = In Then Prisoners(In, Status) = Found: Exit Do Loop Until Prisoners(In, Tries) = 50 Next Print "Executed " End Sub     Sub Init Dim I As Integer, I2 As Integer Print "initialization" For I = 1 To 100 Prisoners(I, Status) = Searching Prisoners(I, Tries) = Searching Do Drawers(I) = Int(Rnd * 100) + 1 For I2 = 1 To I If Drawers(I2) = Drawers(I) Then Exit For Next If I2 = I Then Exit Do Loop Next I Print "Done " End Sub    
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
#Perl
Perl
    use strict; use warnings;   use Getopt::Long; use List::Util 1.29 qw(shuffle pairmap first all); use Tk; # 5 options 1 label text my ($verbose,@fixed,$nocolor,$charsize,$extreme,$solvability);   unless (GetOptions ( 'verbose!' => \$verbose, 'tiles|positions=i{16}' => \@fixed, 'nocolor' => \$nocolor, 'charsize|size|c|s=i' => \$charsize, 'extreme|x|perl' => \$extreme, ) ) { die "invalid arguments!";}   @fixed = &check_req_pos(@fixed) if @fixed;   my $mw = Tk::MainWindow->new(-bg=>'black',-title=>'Giuoco del 15');   if ($nocolor){ $mw->optionAdd( '*Button.background', 'ivory' );}   $mw->optionAdd('*Button.font', 'Courier '.($charsize or 16).' bold' ); $mw->bind('<Control-s>', sub{#&init_board; &shuffle_board});   my $top_frame = $mw->Frame( -borderwidth => 2, -relief => 'groove', )->pack(-expand => 1, -fill => 'both');   $top_frame->Label( -textvariable=>\$solvability, )->pack(-expand => 1, -fill => 'both');   my $game_frame = $mw->Frame( -background=>'saddlebrown', -borderwidth => 10, -relief => 'groove', )->pack(-expand => 1, -fill => 'both');   # set victory conditions in pairs of coordinates my @vic_cond = pairmap { [$a,$b] } qw(0 0 0 1 0 2 0 3 1 0 1 1 1 2 1 3 2 0 2 1 2 2 2 3 3 0 3 1 3 2 3 3);   my $board = [];   my $victorious = 0;   &init_board;   if ( $extreme ){ &extreme_perl}   &shuffle_board;   MainLoop;   ################################################################################ sub init_board{ # tiles from 1 to 15 for (0..14){ $$board[$_]={ btn=>$game_frame->Button( -text => $_+1, -relief => 'raised', -borderwidth => 3, -height => 2, -width => 4, -background=>$nocolor?'ivory':'gold1', -activebackground => $nocolor?'ivory':'gold1', -foreground=> $nocolor?'black':'DarkRed', -activeforeground=>$nocolor?'black':'DarkRed' ), name => $_+1, # x and y set by shuffle_board }; if (($_+1) =~ /^(2|4|5|7|10|12|13|15)$/ and !$nocolor){ $$board[$_]{btn}->configure( -background=>'DarkRed', -activebackground => 'DarkRed', -foreground=> 'gold1', -activeforeground=>'gold1' ); } } # empty tile $$board[15]={ btn=>$game_frame->Button( -relief => 'sunken', -borderwidth => 3, -background => 'lavender', -height => 2, -width => 4, ), name => 16, # x and y set by shuffle_board }; } ################################################################################ sub shuffle_board{ if ($victorious){ $victorious=0; &init_board; } if (@fixed){ my $index = 0;   foreach my $tile(@$board[@fixed]){ my $xy = $vic_cond[$index]; ($$tile{x},$$tile{y}) = @$xy; $$tile{btn}->grid(-row=>$$xy[0], -column=> $$xy[1]); $$tile{btn}->configure(-command =>[\&move,$$xy[0],$$xy[1]]); $index++; } undef @fixed; } else{ my @valid = shuffle (0..15); foreach my $tile ( @$board ){ my $xy = $vic_cond[shift @valid]; ($$tile{x},$$tile{y}) = @$xy; $$tile{btn}->grid(-row=>$$xy[0], -column=> $$xy[1]); $$tile{btn}->configure(-command => [ \&move, $$xy[0], $$xy[1] ]); } } my @appear = map {$_->{name}==16?'X':$_->{name}} sort{$$a{x}<=>$$b{x}||$$a{y}<=>$$b{y}}@$board; print "\n".('-' x 57)."\n". "Appearence of the board:\n[@appear]\n". ('-' x 57)."\n". "current\tfollowers\t less than current\n". ('-' x 57)."\n" if $verbose; # remove the, from now on inutile, 'X' for the empty space @appear = grep{$_ ne 'X'} @appear; my $permutation; foreach my $num (0..$#appear){ last if $num == $#appear; my $perm; $perm += grep {$_ < $appear[$num]} @appear[$num+1..$#appear]; if ($verbose){ print "[$appear[$num]]\t@appear[$num+1..$#appear]". (" " x (37 - length "@appear[$num+1..$#appear]")). "\t $perm ".($num == $#appear - 1 ? '=' : '+')."\n"; } $permutation+=$perm; } print +(' ' x 50)."----\n" if $verbose; if ($permutation % 2){ print "Impossible game with odd permutations!".(' ' x 13). "$permutation\n"if $verbose; $solvability = "Impossible game with odd permutations [$permutation]\n". "(ctrl-s to shuffle)". (($verbose or $extreme) ? '' : " run with --verbose to see more info"); return; } # 105 is the max permutation my $diff = $permutation == 0 ? 'SOLVED' : $permutation < 35 ? 'EASY ' : $permutation < 70 ? 'MEDIUM' : 'HARD '; print "$diff game with even permutations".(' ' x 17). "$permutation\n" if $verbose; $solvability = "$diff game with permutation parity of [$permutation]\n". "(ctrl-s to shuffle)"; } ################################################################################ sub move{ # original x and y my ($ox, $oy) = @_; my $self = first{$_->{x} == $ox and $_->{y} == $oy} @$board; return if $$self{name}==16; # check if one in n,s,e,o is the empty one my $empty = first {$_->{name} == 16 and ( ($_->{x}==$ox-1 and $_->{y}==$oy) or ($_->{x}==$ox+1 and $_->{y}==$oy) or ($_->{x}==$ox and $_->{y}==$oy-1) or ($_->{x}==$ox and $_->{y}==$oy+1) ) } @$board; return unless $empty; # empty x and y my ($ex,$ey) = ($$empty{x},$$empty{y}); # reconfigure emtpy tile $$empty{btn}->grid(-row => $ox, -column => $oy); $$empty{x}=$ox; $$empty{y}=$oy; # reconfigure pressed tile $$self{btn}->grid(-row => $ex, -column => $ey); $$self{btn}->configure(-command => [ \&move, $ex, $ey ]); $$self{x}=$ex; $$self{y}=$ey; # check for victory if the empty one is at the bottom rigth tile (3,3) &check_win if $$empty{x} == 3 and $$empty{y} == 3; } ################################################################################ sub check_win{ foreach my $pos (0..$#$board){ return unless ( $$board[$pos]->{'x'} == $vic_cond[$pos]->[0] and $$board[$pos]->{'y'} == $vic_cond[$pos]->[1]); } # victory! $victorious = 1; my @text = ('Dis','ci','pu','lus','15th','','','at', 'P','e','r','l','M','o','n','ks*'); foreach my $tile(@$board){ $$tile{btn}->configure( -text=> shift @text, -command=>sub{return}); $mw->update; sleep 1; } } ################################################################################ sub check_req_pos{ my @wanted = @_; # fix @wanted: seems GetOptions does not die if more elements are passed @wanted = @wanted[0..15]; my @check = (1..16); unless ( all {$_ == shift @check} sort {$a<=>$b} @wanted ){ die "tiles must be from 1 to 16 (empty tile)\nyou passed [@wanted]\n"; } return map {$_-1} @wanted; } ################################################################################ sub extreme_perl { $verbose = 0; $mw->optionAdd('*font', 'Courier 20 bold'); my @extreme = ( 'if $0', #1 "\$_=\n()=\n\"foo\"=~/o/g", #2 "use warnings;\n\$^W ?\nint((length\n'Discipulus')/3)\n:'15'", #3 "length \$1\nif \$^X=~\n\/(?:\\W)(\\w*)\n(?:\\.exe)\$\/", #4 "use Config;\n\$Config{baserev}", #5. "(split '',\nvec('JAPH'\n,1,8))[0]", #6 "scalar map\n{ord(\$_)=~/1/g}\nqw(p e r l)", #7 "\$_ = () =\n'J A P H'\n=~\/\\b\/g", # 8 "eval join '+',\nsplit '',\n(substr\n'12345',3,2)", #9 'printf \'%b\',2', #10 "int(((1+sqrt(5))\n/ 2)** 7 /\nsqrt(5)+0.5)-2", #11 "split '',\nunpack('V',\n01234567))\n[6,4]", # 12 'J','A','P','H' # 13..16 ); foreach (0..15){ $$board[$_]{btn}->configure(-text=> $extreme[$_], -height => 8, -width => 16, ) if $extreme[$_];   } @fixed = qw(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15); $mw->after(5000,\&shuffle_board);# }      
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 adjacent tiles (in that direction only) with matching numbers combine into one bearing the sum of those numbers.   A move is valid when at least one tile can be moved,   if only by combination.   A new tile with the value of   2   is spawned at the end of each turn at a randomly chosen empty square   (if there is one).   Adding a new tile on a blank space.   Most of the time,   a new   2   is to be added,   and occasionally   (10% of the time),   a   4.   To win,   the player must create a tile with the number   2048.   The player loses if no valid moves are possible. The name comes from the popular open-source implementation of this game mechanic, 2048. Requirements   "Non-greedy" movement.     The tiles that were created by combining other tiles should not be combined again during the same turn (move).     That is to say,   that moving the tile row of: [2][2][2][2] to the right should result in: ......[4][4] and not: .........[8]   "Move direction priority".     If more than one variant of combining is possible,   move direction shall indicate which combination will take effect.   For example, moving the tile row of: ...[2][2][2] to the right should result in: ......[2][4] and not: ......[4][2]   Check for valid moves.   The player shouldn't be able to skip their turn by trying a move that doesn't change the board.   Check for a  win condition.   Check for a lose condition.
#QB64
QB64
  _DEFINE A-Z AS _INTEGER64 DIM SHARED Grid(0 TO 5, 0 TO 5) AS INTEGER CONST Left = 19200 CONST Right = 19712 CONST Down = 20480 CONST Up = 18432 CONST ESC = 27 CONST LCtrl = 100306 CONST RCtrl = 100305   Init MakeNewGame DO _LIMIT 30 ShowGrid CheckInput flag IF flag THEN GetNextNumber _DISPLAY LOOP   SUB CheckInput (flag) flag = 0 k = _KEYHIT SELECT CASE k CASE ESC: SYSTEM CASE 83, 115 'S IF _KEYDOWN(LCtrl) OR _KEYDOWN(RCtrl) THEN MakeNewGame CASE Left MoveLeft flag = -1 'we hit a valid move key. Even if we don't move, get a new number CASE Up MoveUp flag = -1 CASE Down MoveDown flag = -1 CASE Right MoveRight flag = -1 END SELECT END SUB   SUB MoveDown 'first move everything left to cover the blank spaces DO moved = 0 FOR y = 4 TO 1 STEP -1 FOR x = 1 TO 4 IF Grid(x, y) = 0 THEN 'every point above this moves down FOR j = y TO 1 STEP -1 Grid(x, j) = Grid(x, j - 1) IF Grid(x, j) <> 0 THEN moved = -1 NEXT END IF NEXT NEXT IF moved THEN y = y + 1 'recheck the same column LOOP UNTIL NOT moved FOR y = 4 TO 1 STEP -1 FOR x = 1 TO 4 IF Grid(x, y) <> 0 AND Grid(x, y) = Grid(x, y - 1) THEN 'add them together and every point above this moves Grid(x, y) = Grid(x, y) * 2 FOR j = y - 1 TO 1 Grid(x, j) = Grid(x, j - 1) NEXT END IF NEXT NEXT END SUB   SUB MoveLeft 'first move everything to cover the blank spaces DO moved = 0 FOR x = 1 TO 4 FOR y = 1 TO 4 IF Grid(x, y) = 0 THEN 'every point right of this moves left FOR j = x TO 4 Grid(j, y) = Grid(j + 1, y) IF Grid(j, y) <> 0 THEN moved = -1 NEXT END IF NEXT NEXT IF moved THEN x = x - 1 'recheck the same row LOOP UNTIL NOT moved FOR x = 1 TO 4 FOR y = 1 TO 4 IF Grid(x, y) <> 0 AND Grid(x, y) = Grid(x + 1, y) THEN 'add them together and every point right of this moves left Grid(x, y) = Grid(x, y) * 2 FOR j = x + 1 TO 4 Grid(j, y) = Grid(j + 1, y) NEXT END IF NEXT NEXT END SUB   SUB MoveUp 'first move everything to cover the blank spaces DO moved = 0 FOR y = 1 TO 4 FOR x = 1 TO 4 IF Grid(x, y) = 0 THEN 'every point below of this moves up FOR j = y TO 4 Grid(x, j) = Grid(x, j + 1) IF Grid(x, j) <> 0 THEN moved = -1 NEXT END IF NEXT NEXT IF moved THEN y = y - 1 'recheck the same column LOOP UNTIL NOT moved FOR y = 1 TO 4 FOR x = 1 TO 4 IF Grid(x, y) <> 0 AND Grid(x, y) = Grid(x, y + 1) THEN 'add them together and every point below this moves Grid(x, y) = Grid(x, y) * 2 FOR j = y + 1 TO 4 Grid(x, j) = Grid(x, j + 1) NEXT Grid(x, 4) = 0 END IF NEXT NEXT END SUB   SUB MoveRight 'first move everything to cover the blank spaces DO moved = 0 FOR x = 4 TO 1 STEP -1 FOR y = 1 TO 4 IF Grid(x, y) = 0 THEN 'every point right of this moves left FOR j = x TO 1 STEP -1 Grid(j, y) = Grid(j - 1, y) IF Grid(j, y) <> 0 THEN moved = -1 NEXT END IF NEXT NEXT IF moved THEN x = x - 1 'recheck the same row LOOP UNTIL NOT moved   FOR x = 4 TO 1 STEP -1 FOR y = 1 TO 4 IF Grid(x, y) <> 0 AND Grid(x, y) = Grid(x - 1, y) THEN 'add them together and every point right of this moves left Grid(x, y) = Grid(x, y) * 2 FOR j = x - 1 TO 1 STEP -1 Grid(j, y) = Grid(j - 1, y) NEXT END IF NEXT NEXT END SUB   SUB ShowGrid 'SUB MakeBox (Mode AS INTEGER, x1 AS INTEGER, y1 AS INTEGER, x2 AS INTEGER, y2 AS INTEGER, 'Caption AS STRING, FontColor AS _UNSIGNED LONG, FontBackground AS _UNSIGNED LONG, 'BoxColor AS _UNSIGNED LONG, BoxHighLight AS _UNSIGNED LONG, XOffset AS INTEGER, YOffset AS INTEGER) w = 120 h = 120 FOR x = 1 TO 4 FOR y = 1 TO 4 t$ = LTRIM$(STR$(Grid(x, y))) IF t$ = "0" THEN t$ = "" MakeBox 4, (x - 1) * w, (y - 1) * h, w, h, t$, -1, 0, 0, -1, 0, 0 NEXT NEXT END SUB   SUB Init ws = _NEWIMAGE(480, 480, 32) SCREEN ws _DELAY 1 _TITLE "Double Up" _SCREENMOVE _MIDDLE RANDOMIZE TIMER f& = _LOADFONT("C:\Windows\Fonts\courbd.ttf", 32, "MONOSPACE") _FONT f&   END SUB   SUB MakeNewGame FOR x = 1 TO 4 FOR y = 1 TO 4 Grid(x, y) = 0 NEXT NEXT GetNextNumber GetNextNumber END SUB   SUB GetNextNumber FOR x = 1 TO 4 FOR y = 1 TO 4 IF Grid(x, y) = 0 THEN valid = -1 NEXT NEXT IF valid THEN 'If all the grids are full, we can't add any more numbers 'This doesn't mean the game is over, as the player may be able to DO x = _CEIL(RND * 4) y = _CEIL(RND * 4) LOOP UNTIL Grid(x, y) = 0 Grid(x, y) = 2 END IF END SUB   SUB MakeBox (Mode AS INTEGER, x1 AS INTEGER, y1 AS INTEGER, x2 AS INTEGER, y2 AS INTEGER, Caption AS STRING, FontColor AS _UNSIGNED LONG, FontBackground AS _UNSIGNED LONG, BoxColor AS _UNSIGNED LONG, BoxHighLight AS _UNSIGNED LONG, XOffset AS INTEGER, YOffset AS INTEGER)   'This is an upgrade version of my original Button routine. 'It's more versitile (but complex) than the original. 'Mode 0 (or any unsupported number) will tell the box to size itself from X1,Y1 to X2,Y2 'Mode 1 will tell the box to autosize itself according to whatever text is placed within it. 'Mode 2 will tell the box to use X2 and Y2 as relative coordinates and not absolute coordinates. 'Mode 3 will tell the box to autocenter text with X2, Y2 being absolute coordinates. 'Mode 4 will tell the box to autocenter text with X2, Y2 being relative coordinates. 'Mode otherwise is unused, but available for expanded functionality. 'X1 carries the X location of where we want to place our box on the screen. 'Y2 carries the Y location of where we want to place our box on the screen. 'X2 is the X boundry of our box on the screen, depending on our mode. 'Y2 is the Y boundry of our box on the screen, depending on our mode.   'Caption is the text that we want our box to contain.   'FontColor is our font color for our caption 'FontBackground is the font background color for our caption 'NOTE: IF FONTCOLOR OR FONTBACKGROUND IS SET TO ZERO, THEY WILL **NOT** AFFECT THE COLOR BEHIND THEM. 'This can be used to mimic the function of _KEEPBACKGROUND, _FILLBACKGROUND, or _ONLYBACKGROUND   'BoxColor is our box color 'BoxHighlight is our box highligh colors 'NOTE: SAME WITH BOXCOLOR AND BOXHIGHLIGHT. IF SET TO ZERO, THEY WILL HAVE **NO** COLOR AT ALL TO THEM, AND WILL NOT AFFECT THE BACKGROUND OF ANYTHING BEHIND THEM.   'XOffset is used to offset our text # pixels from the X1 top. 'YOffset is used to offset our text # pixels from the Y1 top. 'These can be used to place our text wherever we want on our box. 'But remember, if Mode = 3 or 4, the box will autocenter the text and ignore these parameters completely.   DIM BoxBlack AS _UNSIGNED LONG   dc& = _DEFAULTCOLOR: bg& = _BACKGROUNDCOLOR IF Black <> 0 THEN 'We have black either as a CONST or a SHARED color BoxBlack = Black ELSE 'We need to define what Black is for our box. BoxBlack = _RGB32(0, 0, 0) END IF   IF _FONTWIDTH <> 0 THEN cw = _FONTWIDTH * LEN(Caption) ELSE cw = _PRINTWIDTH(Caption) ch = _FONTHEIGHT   tx1 = x1: tx2 = x2: ty1 = y1: ty2 = y2 SELECT CASE Mode CASE 0 'We use the X2, Y2 coordinates provided as absolute coordinates CASE 1 tx2 = tx1 + cw + 8 ty2 = ty1 + ch + 8 XOffset = 5: YOffset = 5 CASE 2 tx2 = tx1 + x2 ty2 = ty1 + y2 CASE 3 XOffset = (tx2 - tx1 - cw) \ 2 YOffset = (ty2 - ty1 - ch) \ 2 CASE 4 tx2 = tx1 + x2 ty2 = ty1 + y2 XOffset = (tx2 - tx1) \ 2 - cw \ 2 YOffset = (ty2 - ty1 - ch) \ 2 END SELECT LINE (tx1, ty1)-(tx2, ty2), BoxBlack, BF LINE (tx1 + 1, ty1 + 1)-(tx2 - 1, ty2 - 1), BoxHighLight, B LINE (tx1 + 2, ty1 + 2)-(tx2 - 2, ty2 - 2), BoxHighLight, B LINE (tx1 + 3, ty1 + 3)-(tx2 - 3, ty2 - 3), BoxBlack, B LINE (tx1, ty1)-(tx1 + 3, ty1 + 3), BoxBlack LINE (tx2, ty1)-(tx2 - 3, ty1 + 3), BoxBlack LINE (tx1, ty2)-(tx1 + 3, ty2 - 3), BoxBlack LINE (tx2, ty2)-(tx2 - 3, ty2 - 3), BoxBlack LINE (tx1 + 3, y1 + 3)-(tx2 - 3, ty2 - 3), BoxColor, BF COLOR FontColor, FontBackground _PRINTSTRING (tx1 + XOffset, ty1 + YOffset), Caption$ COLOR dc&, bg& END SUB  
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 down, pass it around 97 bottles of beer on the wall ... and so on, until reaching   0     (zero). Grammatical support for   1 bottle of beer   is optional. As with any puzzle, try to do it in as creative/concise/comical a way as possible (simple, obvious solutions allowed, too). Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet See also   http://99-bottles-of-beer.net/   Category:99_Bottles_of_Beer   Category:Programming language families   Wikipedia 99 bottles of beer
#CLIPS
CLIPS
(deffacts beer-bottles (bottles 99))   (deffunction bottle-count (?count) (switch ?count (case 0 then "No more bottles of beer") (case 1 then "1 more bottle of beer") (default (str-cat ?count " bottles of beer"))))   (defrule stanza  ?bottles <- (bottles ?count) => (retract ?bottles) (printout t (bottle-count ?count) " on the wall," crlf) (printout t (bottle-count ?count) "." crlf) (printout t "Take one down, pass it around," crlf) (printout t (bottle-count (- ?count 1)) " on the wall." crlf crlf) (if (> ?count 1) then (assert (bottles (- ?count 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. The program should check then evaluate the expression. The goal is for the player to enter an expression that (numerically) evaluates to 24. Only the following operators/functions are allowed: multiplication, division, addition, subtraction Division should use floating point or rational arithmetic, etc, to preserve remainders. Brackets are allowed, if using an infix expression evaluator. Forming multiple digit numbers from the supplied digits is disallowed. (So an answer of 12+12 when given 1, 2, 2, and 1 is wrong). The order of the digits when given does not have to be preserved. Notes The type of expression evaluator used is not mandated. An RPN evaluator is equally acceptable for example. The task is not for the program to generate the expression, or test whether an expression is even possible. Related tasks 24 game/Solve Reference The 24 Game on h2g2.
#ooRexx
ooRexx
DEFINE TEMP-TABLE tt NO-UNDO FIELD ii AS INTEGER.   DEFINE VARIABLE p_deanswer AS DECIMAL NO-UNDO. DEFINE VARIABLE idigits AS INTEGER NO-UNDO EXTENT 4. DEFINE VARIABLE ii AS INTEGER NO-UNDO. DEFINE VARIABLE Digits AS CHARACTER NO-UNDO FORMAT "x(7)". DEFINE VARIABLE Answer AS CHARACTER NO-UNDO FORMAT "x(7)". DEFINE VARIABLE cexpression AS CHARACTER NO-UNDO. DEFINE VARIABLE cmessage AS CHARACTER NO-UNDO. DEFINE VARIABLE cchar AS CHARACTER NO-UNDO.   FUNCTION calculate RETURNS LOGICAL ( i_de AS DECIMAL ): p_deanswer = i_de. END FUNCTION.   /* generate problem */ DO ii = 1 TO 4: ASSIGN idigits [ii] = RANDOM( 1, 9 ). Digits = Digits + STRING( idigits [ii] ) + " " . END.   /* ui */ DISPLAY Digits. UPDATE Answer.   /* check valid input */ DO ii = 1 TO 7: cchar = SUBSTRING( Answer, ii, 1 ). IF cchar > "" THEN DO: IF ii MODULO 2 = 1 THEN DO: IF LOOKUP( cchar, Digits, " " ) = 0 THEN cmessage = cmessage + SUBSTITUTE( "Invalid digit: &1.~r", cchar ). ELSE ENTRY( LOOKUP( cchar, Digits, " " ), Digits, " " ) = "". END. ELSE DO: IF LOOKUP( cchar, "+,-,/,*" ) = 0 THEN cmessage = cmessage + SUBSTITUTE( "&1 is not a valid operator.~r", cchar ). END. END. END. IF TRIM( Digits ) > "" THEN cmessage = cmessage + SUBSTITUTE( "You did not use digits: &1":U, TRIM( Digits ) ).   IF cmessage = "" THEN DO: /* expressions need spacing */ DO ii = 1 TO 7: cexpression = cexpression + SUBSTRING( Answer, ii, 1 ) + " ". END. /* use dynamic query to parse expression */ TEMP-TABLE tt:DEFAULT-BUFFER-HANDLE:FIND-FIRST( SUBSTITUTE( "WHERE NOT DYNAMIC-FUNCTION( 'calculate', DECIMAL( &1 ) )", cexpression ) ) NO-ERROR. IF p_deanswer <> 24 THEN cmessage = cmessage + SUBSTITUTE( "The expression evaluates to &1.", p_deanswer ). ELSE cmessage = "Solved!". END.   MESSAGE cmessage VIEW-AS ALERT-BOX.  
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 ≤ A , B ≤ + 1000 ) {\displaystyle (-1000\leq A,B\leq +1000)} Output data The required output is one integer:   the sum of A and B. Example input   output   2 2 4 3 2 5
#Forth
Forth
pad dup 80 accept evaluate + .
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 sides of the blocks. The sample collection of 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) Task Write a function that takes a string (word) and determines whether the word can be spelled with the given collection of blocks. The rules are simple:   Once a letter on a block is used that block cannot be used again   The function should be case-insensitive   Show the output on this page for the following 7 words in the following example Example >>> can_make_word("A") True >>> can_make_word("BARK") True >>> can_make_word("BOOK") False >>> can_make_word("TREAT") True >>> can_make_word("COMMON") False >>> can_make_word("SQUAD") True >>> can_make_word("CONFUSE") True Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#PL.2FI
PL/I
ABC: procedure options (main); /* 12 January 2014 */   declare word character (20) varying, blocks character (200) varying initial ('((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))'); declare tblocks character (200) varying; declare (true value ('1'b), false value ('0'b), flag) bit (1); declare ch character (1); declare (i, k) fixed binary;   do word = 'A', 'BARK', 'BOOK', 'TREAT', 'COMMON', 'SQuAd', 'CONFUSE'; flag = true; tblocks = blocks; do i = 1 to length(word) while(flag = true); ch = substr(word, i, 1); k = index(tblocks, uppercase(ch)); if k = 0 then flag = false; else /* Found a block with the letter on it. */ substr(tblocks, k-1, 4) = ' '; /* Delete the block. */ end; if flag then put skip list (word, 'true'); else put skip list (word, 'false'); end;   end ABC;
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 decide some strategy before any enter the room. Prisoners enter the room one by one, can open a drawer, inspect the card number in the drawer, then close the drawer. A prisoner can open no more than 50 drawers. A prisoner tries to find his own number. A prisoner finding his own number is then held apart from the others. If all 100 prisoners find their own numbers then they will all be pardoned. If any don't then all sentences stand. The task Simulate several thousand instances of the game where the prisoners randomly open drawers Simulate several thousand instances of the game where the prisoners use the optimal strategy mentioned in the Wikipedia article, of: First opening the drawer whose outside number is his prisoner number. If the card within has his number then he succeeds otherwise he opens the drawer with the same number as that of the revealed card. (until he opens his maximum). Show and compare the computed probabilities of success for the two strategies, here, on this page. References The unbelievable solution to the 100 prisoner puzzle standupmaths (Video). wp:100 prisoners problem 100 Prisoners Escape Puzzle DataGenetics. Random permutation statistics#One hundred prisoners on Wikipedia.
#Quackery
Quackery
[ this ] is 100prisoners.qky   [ dup size 2 / split ] is halve ( [ --> [ [ )   [ stack ] is successes ( --> s )   [ [] swap times [ i join ] shuffle ] is drawers ( n --> [ )   [ false unrot temp put dup shuffle halve drop witheach [ dip dup peek temp share = if [ dip not conclude ] ] drop temp release ] is naive ( [ n --> b )   [ false unrot dup temp put over size 2 / times [ dip dup peek dup temp share = if [ rot not unrot conclude ] ] 2drop temp release ] is smart ( [ n --> b )   [ ]'[ temp put drawers 0 successes put dup size times [ dup i temp share do successes tally ] size successes take = temp release ] is prisoners ( n --> b )   [ say "100 naive prisoners were pardoned " 0 10000 times [ 100 prisoners naive + ] echo say " times out of 10000 simulations." cr   say "100 smart prisoners were pardoned " 0 10000 times [ 100 prisoners smart + ] echo say " times out of 10000 simulations." cr ] is simulate ( --> )
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
#Phix
Phix
constant ESC=27, UP=328, LEFT=331, RIGHT=333, DOWN=336 sequence board = tagset(15)&0, solve = board integer pos = 16 procedure print_board() for i=1 to length(board) do puts(1,iff(i=pos?" ":sprintf("%3d",{board[i]}))) if mod(i,4)=0 then puts(1,"\n") end if end for puts(1,"\n") end procedure procedure move(integer d) integer new_pos = pos+{+4,+1,-1,-4}[d] if new_pos>=1 and new_pos<=16 and (mod(pos,4)=mod(new_pos,4) -- same col, or row: or floor((pos-1)/4)=floor((new_pos-1)/4)) then {board[pos],board[new_pos]} = {board[new_pos],0} pos = new_pos end if end procedure for i=1 to 5 do move(rand(4)) end for while 1 do print_board() if board=solve then exit end if integer c = find(wait_key(),{ESC,UP,LEFT,RIGHT,DOWN})-1 if c=0 then exit end if move(c) end while puts(1,"solved!\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 adjacent tiles (in that direction only) with matching numbers combine into one bearing the sum of those numbers.   A move is valid when at least one tile can be moved,   if only by combination.   A new tile with the value of   2   is spawned at the end of each turn at a randomly chosen empty square   (if there is one).   Adding a new tile on a blank space.   Most of the time,   a new   2   is to be added,   and occasionally   (10% of the time),   a   4.   To win,   the player must create a tile with the number   2048.   The player loses if no valid moves are possible. The name comes from the popular open-source implementation of this game mechanic, 2048. Requirements   "Non-greedy" movement.     The tiles that were created by combining other tiles should not be combined again during the same turn (move).     That is to say,   that moving the tile row of: [2][2][2][2] to the right should result in: ......[4][4] and not: .........[8]   "Move direction priority".     If more than one variant of combining is possible,   move direction shall indicate which combination will take effect.   For example, moving the tile row of: ...[2][2][2] to the right should result in: ......[2][4] and not: ......[4][2]   Check for valid moves.   The player shouldn't be able to skip their turn by trying a move that doesn't change the board.   Check for a  win condition.   Check for a lose condition.
#R
R
  GD <- function(vec) { c(vec[vec != 0], vec[vec == 0]) } DG <- function(vec) { c(vec[vec == 0], vec[vec != 0]) }   DG_ <- function(vec, v = TRUE) { if (v) print(vec) rev(GD_(rev(vec), v = FALSE)) }   GD_ <- function(vec, v = TRUE) { if (v) { print(vec) } vec2 <- GD(vec) # on cherche les 2 cote a cote pos <- which(vec2 == c(vec2[-1], 9999)) # put pas y avoir consécutif dans pos pos[-1][which(abs(pos - c(pos[-1], 999)) == 1)] av <- which(c(0, c(pos[-1], 9) - pos) == 1) if (length(av) > 0) { pos <- pos[-av] } vec2[pos] <- vec2[pos] + vec2[pos + 1] vec2[pos + 1] <- 0 GD(vec2)   }   H_ <- function(base) { apply(base, MARGIN = 2, FUN = GD_, v = FALSE) } B_ <- function(base) { apply(base, MARGIN = 2, FUN = DG_, v = FALSE) } G_ <- function(base) { t(apply(base, MARGIN = 1, FUN = GD_, v = FALSE)) } D_ <- function(base) { t(apply(base, MARGIN = 1, FUN = DG_, v = FALSE)) }   H <- function(base) { apply(base, MARGIN = 2, FUN = GD, v = FALSE) } B <- function(base) { apply(base, MARGIN = 2, FUN = DG, v = FALSE) } G <- function(base) { t(apply(base, MARGIN = 1, FUN = GD, v = FALSE)) } D <- function(base) { t(apply(base, MARGIN = 1, FUN = DG, v = FALSE)) }   add2or4 <- function(base, p = 0.9) { lw <- which(base == 0) if (length(lw) > 1) { tirage <- sample(lw, 1) } else { tirage <- lw } base[tirage] <- sample(c(2, 4), 1, prob = c(p, 1 - p)) base } print.dqh <- function(base) { cat("\n\n") for (i in 1:nrow(base)) { cat(paste(" ", base[i, ], " ")) cat("\n") } cat("\n") }       # -*- coding: utf-8 -*- #' @encoding UTF-8 #' @title run_2048 #' @description The 2048 game #' @param nrow nomber of row #' @param ncol numver of col #' @param p probability to obtain a 2 (1-p) is the probability to obtain a 4 #' @examples #' \dontrun{ #' run_2048() #' } #' @export     run_2048 <- function(nrow, ncol, p = 0.9) {       help <- function() { cat(" *** KEY BINDING *** \n\n") cat("press ECHAP to quit\n\n") cat("choose moove E (up) ; D (down) ; S (left); F (right) \n") cat("choose moove 8 (up) ; 2 (down) ; 4 (left); 6 (right) \n") cat("choose moove I (up) ; K (down) ; J (left); L (right) \n\n\n")   }     if (missing(nrow) & missing(ncol)) { nrow <- ncol <- 4 } if (missing(nrow)) { nrow <- ncol } if (missing(ncol)) { ncol <- nrow }   base <- matrix(0, nrow = nrow, ncol = ncol)   while (length(which(base == 2048)) == 0) { base <- add2or4(base, p = p) # print(base)   class(base) <- "dqh" print(base) flag <- sum((base == rbind(base[-1, ], 0)) + (base == rbind(0, base[-nrow(base), ])) + (base == cbind(base[, -1], 0)) + (base == cbind(0, base[, -nrow(base)]))) if (flag == 0) {   break }   y <- character(0) while (length(y) == 0) { cat("\n", "choose moove E (up) ; D (down) ; s (left); f (right) OR H for help", "\n") # prompt y <- scan(n = 1, what = "character") }     baseSAVE <- base base <- switch(EXPR = y, E = H_(base), D = B_(base), S = G_(base), F = D_(base), e = H_(base), d = B_(base), s = G_(base), f = D_(base), `8` = H_(base), `2` = B_(base), `4` = G_(base), `6` = D_(base), H = help(), h = help(), i = H_(base), k = B_(base), j = G_(base), l = D_(base), I = H_(base), K = B_(base), J = G_(base), L = D_(base)) if (is.null(base)) { cat(" wrong KEY \n") base <- baseSAVE }       }   if (sum(base >= 2048) > 1) { cat("YOU WIN ! \n") } else { cat("YOU LOOSE \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 down, pass it around 97 bottles of beer on the wall ... and so on, until reaching   0     (zero). Grammatical support for   1 bottle of beer   is optional. As with any puzzle, try to do it in as creative/concise/comical a way as possible (simple, obvious solutions allowed, too). Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet See also   http://99-bottles-of-beer.net/   Category:99_Bottles_of_Beer   Category:Programming language families   Wikipedia 99 bottles of beer
#Clojure
Clojure
(defn paragraph [num] (str num " bottles of beer on the wall\n" num " bottles of beer\n" "Take one down, pass it around\n" (dec num) " bottles of beer on the wall.\n"))   (defn lyrics [] (let [numbers (range 99 0 -1) paragraphs (map paragraph numbers)] (clojure.string/join "\n" paragraphs)))     (print (lyrics))
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. The program should check then evaluate the expression. The goal is for the player to enter an expression that (numerically) evaluates to 24. Only the following operators/functions are allowed: multiplication, division, addition, subtraction Division should use floating point or rational arithmetic, etc, to preserve remainders. Brackets are allowed, if using an infix expression evaluator. Forming multiple digit numbers from the supplied digits is disallowed. (So an answer of 12+12 when given 1, 2, 2, and 1 is wrong). The order of the digits when given does not have to be preserved. Notes The type of expression evaluator used is not mandated. An RPN evaluator is equally acceptable for example. The task is not for the program to generate the expression, or test whether an expression is even possible. Related tasks 24 game/Solve Reference The 24 Game on h2g2.
#OpenEdge.2FProgress
OpenEdge/Progress
DEFINE TEMP-TABLE tt NO-UNDO FIELD ii AS INTEGER.   DEFINE VARIABLE p_deanswer AS DECIMAL NO-UNDO. DEFINE VARIABLE idigits AS INTEGER NO-UNDO EXTENT 4. DEFINE VARIABLE ii AS INTEGER NO-UNDO. DEFINE VARIABLE Digits AS CHARACTER NO-UNDO FORMAT "x(7)". DEFINE VARIABLE Answer AS CHARACTER NO-UNDO FORMAT "x(7)". DEFINE VARIABLE cexpression AS CHARACTER NO-UNDO. DEFINE VARIABLE cmessage AS CHARACTER NO-UNDO. DEFINE VARIABLE cchar AS CHARACTER NO-UNDO.   FUNCTION calculate RETURNS LOGICAL ( i_de AS DECIMAL ): p_deanswer = i_de. END FUNCTION.   /* generate problem */ DO ii = 1 TO 4: ASSIGN idigits [ii] = RANDOM( 1, 9 ). Digits = Digits + STRING( idigits [ii] ) + " " . END.   /* ui */ DISPLAY Digits. UPDATE Answer.   /* check valid input */ DO ii = 1 TO 7: cchar = SUBSTRING( Answer, ii, 1 ). IF cchar > "" THEN DO: IF ii MODULO 2 = 1 THEN DO: IF LOOKUP( cchar, Digits, " " ) = 0 THEN cmessage = cmessage + SUBSTITUTE( "Invalid digit: &1.~r", cchar ). ELSE ENTRY( LOOKUP( cchar, Digits, " " ), Digits, " " ) = "". END. ELSE DO: IF LOOKUP( cchar, "+,-,/,*" ) = 0 THEN cmessage = cmessage + SUBSTITUTE( "&1 is not a valid operator.~r", cchar ). END. END. END. IF TRIM( Digits ) > "" THEN cmessage = cmessage + SUBSTITUTE( "You did not use digits: &1":U, TRIM( Digits ) ).   IF cmessage = "" THEN DO: /* expressions need spacing */ DO ii = 1 TO 7: cexpression = cexpression + SUBSTRING( Answer, ii, 1 ) + " ". END. /* use dynamic query to parse expression */ TEMP-TABLE tt:DEFAULT-BUFFER-HANDLE:FIND-FIRST( SUBSTITUTE( "WHERE NOT DYNAMIC-FUNCTION( 'calculate', DECIMAL( &1 ) )", cexpression ) ) NO-ERROR. IF p_deanswer <> 24 THEN cmessage = cmessage + SUBSTITUTE( "The expression evaluates to &1.", p_deanswer ). ELSE cmessage = "Solved!". END.   MESSAGE cmessage VIEW-AS ALERT-BOX.  
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 ≤ A , B ≤ + 1000 ) {\displaystyle (-1000\leq A,B\leq +1000)} Output data The required output is one integer:   the sum of A and B. Example input   output   2 2 4 3 2 5
#Fortran
Fortran
program a_plus_b implicit none integer :: a,b read (*, *) a, b write (*, '(i0)') a + b end program a_plus_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 sides of the blocks. The sample collection of 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) Task Write a function that takes a string (word) and determines whether the word can be spelled with the given collection of blocks. The rules are simple:   Once a letter on a block is used that block cannot be used again   The function should be case-insensitive   Show the output on this page for the following 7 words in the following example Example >>> can_make_word("A") True >>> can_make_word("BARK") True >>> can_make_word("BOOK") False >>> can_make_word("TREAT") True >>> can_make_word("COMMON") False >>> can_make_word("SQUAD") True >>> can_make_word("CONFUSE") True Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#PL.2FM
PL/M
100H:   /* ABC PROBLEM ON $-TERMINATED STRING */ CAN$MAKE$WORD: PROCEDURE (STRING) BYTE; DECLARE STRING ADDRESS, CHAR BASED STRING BYTE; DECLARE CONST$BLOCKS DATA ('BOKXDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM'); DECLARE I BYTE, BLOCKS (40) BYTE;   DO I=0 TO 39; /* MAKE COPY OF BLOCKS */ BLOCKS(I) = CONST$BLOCKS(I); END;   STEP: DO WHILE CHAR <> '$'; DO I=0 TO 39; /* FIND BLOCK WITH CURRENT CHAR */ IF BLOCKS(I) = CHAR THEN DO; /* FOUND IT */ BLOCKS(I) = 0; /* CLEAR OUT BOTH LETTERS ON BLOCK */ BLOCKS(I XOR 1) = 0; STRING = STRING + 1; GO TO STEP; /* NEXT CHARACTER */ END; END; RETURN 0; /* NO BLOCK WITH LETTER */ END;   RETURN 1; /* WE FOUND THEM ALL */ END CAN$MAKE$WORD;   /* CP/M BDOS CALL */ BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS;   PRINT: PROCEDURE (STRING); DECLARE STRING ADDRESS; CALL BDOS(9, STRING); END PRINT;   /* TEST SEVERAL STRINGS */ DECLARE TEST (7) ADDRESS, I BYTE; TEST(0) = .'A$'; TEST(1) = .'BARK$'; TEST(2) = .'BOOK$'; TEST(3) = .'TREAT$'; TEST(4) = .'COMMON$'; TEST(5) = .'SQUAD$'; TEST(6) = .'CONFUSE$';   DO I = 0 TO LAST(TEST); CALL PRINT(TEST(I)); CALL PRINT(.': $'); IF CAN$MAKE$WORD(TEST(I)) THEN CALL PRINT(.'YES$'); ELSE CALL PRINT(.'NO$'); CALL PRINT(.(13,10,'$')); END;   CALL BDOS(0,0); EOF
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 decide some strategy before any enter the room. Prisoners enter the room one by one, can open a drawer, inspect the card number in the drawer, then close the drawer. A prisoner can open no more than 50 drawers. A prisoner tries to find his own number. A prisoner finding his own number is then held apart from the others. If all 100 prisoners find their own numbers then they will all be pardoned. If any don't then all sentences stand. The task Simulate several thousand instances of the game where the prisoners randomly open drawers Simulate several thousand instances of the game where the prisoners use the optimal strategy mentioned in the Wikipedia article, of: First opening the drawer whose outside number is his prisoner number. If the card within has his number then he succeeds otherwise he opens the drawer with the same number as that of the revealed card. (until he opens his maximum). Show and compare the computed probabilities of success for the two strategies, here, on this page. References The unbelievable solution to the 100 prisoner puzzle standupmaths (Video). wp:100 prisoners problem 100 Prisoners Escape Puzzle DataGenetics. Random permutation statistics#One hundred prisoners on Wikipedia.
#Racket
Racket
#lang racket (require srfi/1)   (define current-samples (make-parameter 10000)) (define *prisoners* 100) (define *max-guesses* 50)   (define (evaluate-strategy instance-solved? strategy (s (current-samples))) (/ (for/sum ((_ s) #:when (instance-solved? strategy)) 1) s))   (define (build-drawers) (list->vector (shuffle (range *prisoners*))))   (define (100-prisoners-problem strategy) (every (strategy (build-drawers)) (range *prisoners*)))   (define ((strategy-1 drawers) p) (any (λ (_) (= p (vector-ref drawers (random *prisoners*)))) (range *max-guesses*)))   (define ((strategy-2 drawers) p) (define-values (_ found?) (for/fold ((d p) (found? #f)) ((_ *max-guesses*)) #:break found? (let ((card (vector-ref drawers d))) (values card (= card p))))) found?)   (define (print-sample-percentage caption f (s (current-samples))) (printf "~a: ~a%~%" caption (real->decimal-string (* 100 f) (- (order-of-magnitude s) 2))))   (module+ main (print-sample-percentage "random" (evaluate-strategy 100-prisoners-problem strategy-1)) (print-sample-percentage "optimal" (evaluate-strategy 100-prisoners-problem strategy-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
#PHP
PHP
<?php // Puzzle 15 Game - Rosseta Code - PHP 7 as the server-side script language.   // This program DOES NOT use cookies.   session_start([ "use_only_cookies" => 0, "use_cookies" => 0, "use_trans_sid" => 1, ]);   class Location { protected $column, $row;   function __construct($column, $row){ $this->column = $column; $this->row = $row; } function create_neighbor($direction){ $dx = 0; $dy = 0; switch ($direction){ case 0: case 'left': $dx = -1; break; case 1: case 'right': $dx = +1; break; case 2: case 'up': $dy = -1; break; case 3: case 'down': $dy = +1; break; } return new Location($this->column + $dx, $this->row + $dy); } function equals($that){ return $this->column == $that->column && $this->row == $that->row; } function is_inside_rectangle($left, $top, $right, $bottom){ return $left <= $this->column && $this->column <= $right && $top <= $this->row && $this->row <= $bottom; } function is_nearest_neighbor($that){ $s = abs($this->column - $that->column) + abs($this->row - $that->row); return $s == 1; } }   class Tile { protected $index; protected $content; protected $target_location; protected $current_location;   function __construct($index, $content, $row, $column){ $this->index = $index; $this->content = $content; $this->target_location = new Location($row, $column); $this->current_location = $this->target_location; } function get_content(){ return $this->content; } function get_index(){ return $this->index; } function get_location(){ return $this->current_location; } function is_completed(){ return $this->current_location->equals($this->target_location); } function is_empty(){ return $this->content == NULL; } function is_nearest_neighbor($that){ $a = $this->current_location; $b = $that->current_location; return $a->is_nearest_neighbor($b); } function swap_locations($that){ $a = $this->current_location; $b = $that->current_location; $this->current_location = $b; $that->current_location = $a; } }   class Model { protected $N; protected $M; protected $tiles;   function __construct($N, $M){ $this->N = $N; $this->M = $M; $this->tiles[0] = new Tile(0, NULL, $N, $M); for ($k = 1; $k < $N * $M; $k++ ){ $i = 1 + intdiv($k - 1, $M); $j = 1 + ($k - 1) % $M; $this->tiles[$k] = new Tile($k, (string)$k, $i, $j); } $number_of_shuffles = 1000; $i = 0; while ($i < $number_of_shuffles) if ($this->move_in_direction(random_int(0, 3))) $i++; } function get_N(){ return $this->N; } function get_M(){ return $this->M; } function get_tile_by_index($index){ return $this->tiles[$index]; } function get_tile_at_location($location){ foreach($this->tiles as $tile) if ($location->equals($tile->get_location())) return $tile; return NULL; } function is_completed(){ foreach($this->tiles as $tile) if (!$tile->is_completed()) return FALSE; return TRUE; } function move($tile){ if ($tile != NULL) foreach($this->tiles as $target){ if ($target->is_empty() && $target->is_nearest_neighbor($tile)){ $tile->swap_locations($target); break; } } } function move_in_direction($direction){ foreach($this->tiles as $tile) if ($tile->is_empty()) break; $location = $tile->get_location()->create_neighbor($direction); if ($location->is_inside_rectangle(0, 0, $this->M, $this->N)){ $tile = $this->get_tile_at_location($location); $this->move($tile); return TRUE; } return FALSE; } }   class View { protected $model;   function __construct($model){ $this->model = $model; } function show(){ $N = $this->model->get_N(); $M = $this->model->get_M(); echo "<form>"; for ($i = 1; $i <= $N; $i++){ for ($j = 1; $j <= $M; $j++){ $tile = $this->model->get_tile_at_location(new Location($i, $j)); $content = $tile->get_content(); if ($content != NULL) echo "<span class='puzzle'>" . "<input type='submit' class='puzzle' name='index'" . "value='$content'>" . "</span>"; else echo "<span class='puzzle'></span>"; } echo "<br>"; } echo "</form>"; if ($this->model->is_completed()){ echo "<p class='end-game'>"; echo "You win!"; echo "</p>"; } } }   class Controller { protected $model; protected $view;   function __construct($model, $view){ $this->model = $model; $this->view = $view; } function run(){ if (isset($_GET['index'])){ $index = $_GET['index']; $this->model->move($this->model->get_tile_by_index($index)); } $this->view->show(); } } ?>   <!DOCTYPE html> <html lang="en"><meta charset="UTF-8"> <head> <title>15 puzzle game</title> <style> .puzzle{width: 4ch; display: inline-block; margin: 0; padding: 0.25ch;} span.puzzle{padding: 0.1ch;} .end-game{font-size: 400%; color: red;} </style> </head> <body> <p><?php if (!isset($_SESSION['model'])){ $width = 4; $height = 4; $model = new Model($width, $height); } else $model = unserialize($_SESSION['model']); $view = new View($model); $controller = new Controller($model, $view); $controller->run(); $_SESSION['model'] = serialize($model); ?></p> </body> </html>
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 adjacent tiles (in that direction only) with matching numbers combine into one bearing the sum of those numbers.   A move is valid when at least one tile can be moved,   if only by combination.   A new tile with the value of   2   is spawned at the end of each turn at a randomly chosen empty square   (if there is one).   Adding a new tile on a blank space.   Most of the time,   a new   2   is to be added,   and occasionally   (10% of the time),   a   4.   To win,   the player must create a tile with the number   2048.   The player loses if no valid moves are possible. The name comes from the popular open-source implementation of this game mechanic, 2048. Requirements   "Non-greedy" movement.     The tiles that were created by combining other tiles should not be combined again during the same turn (move).     That is to say,   that moving the tile row of: [2][2][2][2] to the right should result in: ......[4][4] and not: .........[8]   "Move direction priority".     If more than one variant of combining is possible,   move direction shall indicate which combination will take effect.   For example, moving the tile row of: ...[2][2][2] to the right should result in: ......[2][4] and not: ......[4][2]   Check for valid moves.   The player shouldn't be able to skip their turn by trying a move that doesn't change the board.   Check for a  win condition.   Check for a lose condition.
#Racket
Racket
  ;; LICENSE: See License file LICENSE (MIT license) ;; ;; Repository: https://github.com/danprager/2048 ;; ;; Copyright 2014: Daniel Prager ;; daniel.a.prager@gmail.com ;; ;; This is a largely clean-room, functional implementation in Racket ;; of the game 2048 by Gabriele Cirulli, based on 1024 by Veewo Studio, ;; and conceptually similar to Threes by Asher Vollmer. ;; ;; ;; HOW TO PLAY: ;; * Use your arrow keys to slide the tiles. ;; * When two tiles with the same number touch, they merge into one! ;; * Press <space> to rotate the board. ;;   #lang racket   (require rackunit 2htdp/image (rename-in 2htdp/universe [left left-arrow] [right right-arrow] [up up-arrow] [down down-arrow]))     (define *side* 4)  ; Side-length of the grid (define *time-limit* #f)  ; Use #f for no time limit, or number of seconds   (define *amber-alert* 60)  ; Time indicator goes orange when less than this number of seconds remaining (define *red-alert* 10)  ; Time indicator goes red when less than this number of seconds remaining   (define *tile-that-wins* 2048) ; You win when you get a tile = this number (define *magnification* 2)  ; Scales the game board   (define (set-side! n) (set! *side* n))   ;; ;; Numbers can be displayed with substiture text. Just edit this table... ;; (define *text* '((0 "") (2 "2")))   ;; Color scheme ;; ;; From https://github.com/gabrielecirulli/2048/blob/master/style/main.css ;; (define *grid-color* (color #xbb #xad #xa0))   (define *default-tile-bg-color* (color #x3c #x3a #x32)) (define *default-tile-fg-color* 'white)   (define *tile-bg-colors* (map (lambda (x) (match-define (list n r g b) x) (list n (color r g b))) '((0 #xcc #xc0 #xb3) (2 #xee #xe4 #xda) (4 #xed #xe0 #xc8) (8 #xf2 #xb1 #x79) (16 #xf5 #x95 #x63) (32 #xf6 #x7c #x5f) (64 #xf6 #x5e #x3b) (128 #xed #xcf #x72) (256 #xed #xcc #x61) (512 #xed #xc8 #x50) (1024 #xed #xc5 #x3f) (2048 #xed #xc2 #x2e))))   (define *tile-fg-colors* '((0 dimgray) (2 dimgray) (4 dimgray) (8 white) (16 white) (32 white) (64 white) (128 white) (256 white) (512 white) (1024 white) (2048 white)))   ;;-------------------------------------------------------------------- ;; Rows may be represented as lists, with 0s representing empty spots. ;;   (define (nonzero? x) (not (zero? x)))   ;; Append padding to lst to make it n items long ;; (define (pad-right lst padding n) (append lst (make-list (- n (length lst)) padding)))   ;; Slide items towards the head of the list, doubling adjacent pairs ;; when no item is a 0. ;; ;; E.g. (combine '(2 2 2 4 4)) -> '(4 2 8) ;; (define (combine lst) (cond [(<= (length lst) 1) lst] [(= (first lst) (second lst)) (cons (* 2 (first lst)) (combine (drop lst 2)))] [else (cons (first lst) (combine (rest lst)))]))   ;; Total of new elements introduced by combining. ;; ;; E.g. (combine-total '(2 2 2 4 4)) -> 4 + 8 = 12 ;; (define (combine-total lst) (cond [(<= (length lst) 1) 0] [(= (first lst) (second lst)) (+ (* 2 (first lst)) (combine-total (drop lst 2)))] [else (combine-total (rest lst))]))   ;; Slide towards the head of the list, doubling pairs, 0 are ;; allowed (and slid through), and length is preserved by ;; padding with 0s. ;; ;; E.g. (slide-left '(2 2 2 0 4 4)) -> '(4 2 8 0 0 0) ;; (define (slide-left row) (pad-right (combine (filter nonzero? row)) 0 (length row)))   ;; Slide towards the tail of the list: ;; ;; E.g. (slide-right '(2 2 0 0 4 4)) -> '(0 0 0 0 0 4 8) ;; (define (slide-right row) (reverse (slide-left (reverse row))))     ;;-------------------------------------------------------------------- ;; We use a sparse representation for transitions in a row. ;; ;; Moves take the form '(value initial-position final-position) ;; (define (moves-row-left row [last #f] [i 0] [j -1]) (if (null? row) null (let ([head (first row)]) (cond [(zero? head) (moves-row-left (rest row) last (add1 i) j)] [(equal? last head) (cons (list head i j) (moves-row-left (rest row) #f (add1 i) j))] [else (cons (list head i (add1 j)) (moves-row-left (rest row) head (add1 i) (add1 j)))]))))   ;; Convert a row into the sparse representaiton without any sliding. ;; ;; E.g. (moves-row-none '(0 2 0 4)) -> '((2 1 1) (4 3 3)) ;; (define (moves-row-none row) (for/list ([value row] [i (in-naturals)] #:when (nonzero? value)) (list value i i)))   ;; Reverse all moves so that: ;; ;; '(value initial final) -> '(value (- n initial 1) (- n final 1) ;; (define (reverse-moves moves n) (define (flip i) (- n i 1)) (map (λ (m) (match-define (list a b c) m) (list a (flip b) (flip c))) moves))   (define (transpose-moves moves) (for/list ([m moves]) (match-define (list v (list a b) (list c d)) m) (list v (list b a) (list d c))))   (define (moves-row-right row [n *side*]) (reverse-moves (moves-row-left (reverse row)) n))   ;;-------------------------------------------------------------------- ;; Lift the sparse representation for transitions ;; up to two dimensions... ;; ;; '(value initial final) -> '(value (x initial) (x final)) ;; (define (add-row-coord i rows) (for/list ([r rows]) (match-define (list a b c) r) (list a (list i b) (list i c))))   (define (transpose lsts) (apply map list lsts))   ;; Slide the entire grid in the specified direction ;; (define (left grid) (map slide-left grid))   (define (right grid) (map slide-right grid))   (define (up grid) ((compose transpose left transpose) grid))   (define (down grid) ((compose transpose right transpose) grid))   ;; Calculate the change to score from sliding the grid left or right. ;; (define (score-increment grid) (apply + (map (λ (row) (combine-total (filter nonzero? row))) grid)))   ;; Slide the grid in the specified direction and ;; determine the transitions of the tiles. ;; ;; We'll use these operations to animate the sliding of the tiles. ;; (define (moves-grid-action grid action) (let ([n (length (first grid))]) (apply append (for/list ([row grid] [i (in-range n)]) (add-row-coord i (action row))))))   (define (moves-grid-left grid) (moves-grid-action grid moves-row-left))   (define (moves-grid-right grid) (moves-grid-action grid moves-row-right))   (define (moves-grid-up grid) ((compose transpose-moves moves-grid-left transpose) grid))   (define (moves-grid-down grid) ((compose transpose-moves moves-grid-right transpose) grid))   ;; Rotating the entire grid doesn't involve sliding. ;; It's a convenience to allow the player to view the grid from a different ;; orientation. (define (moves-grid-rotate grid) (let ([n (length (first grid))]) (for/list ([item (moves-grid-action grid moves-row-none)]) (match-define (list v (list i j) _) item) (list v (list i j) (list j (- n i 1))))))   ;; Chop a list into a list of sub-lists of length n. Used to move from ;; a flat representation of the grid into a list of rows. ;; ;; (define (chop lst [n *side*]) (if (<= (length lst) n) (list lst) (cons (take lst n) (chop (drop lst n) n))))   ;; The next few functions are used to determine where to place a new ;; number in the grid... ;;   ;; How many zeros in the current state? ;; (define (count-zeros state) (length (filter zero? state)))   ;; What is the absolute index of the nth zero in lst? ;; ;; E.g. (index-of-nth-zero '(0 2 0 4) 1 2)) 1) -> 2 ;; (define (index-of-nth-zero lst n) (cond [(null? lst) #f] [(zero? (first lst)) (if (zero? n) 0 (add1 (index-of-nth-zero (rest lst) (sub1 n))))] [else (add1 (index-of-nth-zero (rest lst) n))]))   ;; Place the nth zero in the lst with val. ;; ;; E.g. (replace-nth-zero '(0 2 0 4) 1 2)) -> '(0 2 2 4) ;; (define (replace-nth-zero lst n val) (let ([i (index-of-nth-zero lst n)]) (append (take lst i) (cons val (drop lst (add1 i))))))   ;; There's a 90% chance that a new tile will be a two; 10% a four. ;; (define (new-tile) (if (> (random) 0.9) 4 2))   ;; Create a random initial game-board with two non-zeros (2 or 4) ;; and the rest 0s. ;; ;; E.g. '(0 0 0 0 ;; 0 2 0 0 ;; 2 0 0 0 ;; 0 0 0 0) ;; (define (initial-state [side *side*]) (shuffle (append (list (new-tile) (new-tile)) (make-list (- (sqr side) 2) 0))))   ;; The game finishes when no matter which way you slide, the board doesn't ;; change. ;; (define (finished? state [n *side*]) (let ([grid (chop state n)]) (for/and ([op (list left right up down)]) (equal? grid (op grid)))))   ;;-------------------------------------------------------------------- ;; Graphics ;; (define *text-size* 30) (define *max-text-width* 40) (define *tile-side* 50) (define *grid-spacing* 5) (define *grid-side* (+ (* *side* *tile-side*) (* (add1 *side*) *grid-spacing*)))   ;; Memoization - caching images takes the strain off the gc ;; (define-syntax define-memoized (syntax-rules () [(_ (f args ...) bodies ...) (define f (let ([results (make-hash)]) (lambda (args ...) ((λ vals (when (not (hash-has-key? results vals)) (hash-set! results vals (begin bodies ...))) (hash-ref results vals)) args ...))))]))   ;; Look-up the (i,j)th element in the flat representation. ;; (define (square/ij state i j) (list-ref state (+ (* *side* i) j)))   ;; Linear interpolation between a and b: ;; ;; (interpolate 0.0 a b) -> a ;; (interpolate 1.0 a b) -> b ;; (define (interpolate k a b) (+ (* (- 1 k) a) (* k b)))   ;; Key value lookup with default return - is there an out-of-the-box function ;; for this? ;; (define (lookup key lst default) (let ([value (assoc key lst)]) (if value (second value) default)))     ;; Make a tile without a number on it in the appropriate color. ;; (define (plain-tile n) (square *tile-side* 'solid (lookup n *tile-bg-colors* *default-tile-bg-color*)))   ;; Make text for a tile ;; (define (tile-text n) (let* ([t (text (lookup n *text* (number->string n)) *text-size* (lookup n *tile-fg-colors* *default-tile-fg-color*))] [side (max (image-width t) (image-height t))]) (scale (if (> side *max-text-width*) (/ *max-text-width* side) 1) t)))   (define-memoized (make-tile n) (overlay (tile-text n) (plain-tile n)))   ;; Place a tile on an image of the grid at (i,j) ;; (define (place-tile/ij tile i j grid-image) (define (pos k) (+ (* (add1 k) *grid-spacing*) (* k *tile-side*))) (underlay/xy grid-image (pos j) (pos i) tile))   ;; Make an image of the grid from the flat representation ;; (define *last-state* null) ; Cache the previous grid to avoid (define *last-grid* null)  ; senseless regeneration   (define (state->image state) (unless (equal? state *last-state*) (set! *last-grid* (for*/fold ([im (square *grid-side* 'solid *grid-color*)]) ([i (in-range *side*)] [j (in-range *side*)]) (place-tile/ij (make-tile (square/ij state i j)) i j im))) (set! *last-state* state)) *last-grid*)   (define *empty-grid-image* (state->image (make-list (sqr *side*) 0)))   ;; Convert the sparse representation of moves into a single frame in an ;; animation at time k, where k is between 0.0 (start state) and 1.0 ;; (final state). ;; (define (moves->frame moves k) (for*/fold ([grid *empty-grid-image*]) ([m moves]) (match-define (list value (list i1 j1) (list i2 j2)) m) (place-tile/ij (make-tile value) (interpolate k i1 i2) (interpolate k j1 j2) grid)))   ;; Animation of simultaneously moving tiles. ;; (define (animate-moving-tiles state op) (let ([grid (chop state)]) (build-list 9 (λ (i) (λ () (moves->frame (op grid) (* 0.1 (add1 i))))))))   ;; Animation of a tile appearing in a previously blank square. ;; (define (animate-appearing-tile state value index) (let ([start (state->image state)] [tile (make-tile value)] [i (quotient index *side*)] [j (remainder index *side*)]) (build-list 4 (λ (m) (λ () (place-tile/ij (overlay (scale (* 0.2 (add1 m)) tile) (plain-tile 0)) i j start))))))   ;;-------------------------------------------------------------- ;; ;; The Game ;;   ;; an image-procedure is a procedure of no arguments that produces an image   ;; a world contains: ;; state is a ? ;; score is a number ;; winning-total is #f or a number, representing the final score <-- is this ;; necessary? ;; frames is a (list-of image-procedure) ;; start-time is a number, in seconds (define-struct world (state score winning-total frames start-time) #:transparent)   ;; The game is over when any animations have been finished and ;; no more moves are possible. ;; ;; note that winning the game does *not* end the game. ;; (define (game-over? w) (match-define (world state score wt frames start-time) w) (and (null? frames) ; Finish animations to reach final state and show the banner (or (finished? state) (out-of-time? (world-start-time w)))))   ;; Is the player out of time? (define (out-of-time? start-time) (and *time-limit* (< (+ start-time *time-limit*) (current-seconds))))   ;; Given an arrow key return the operations to change the state and ;; produce the sliding animation. ;; (define (key->ops a-key) (cond [(key=? a-key "left") (list left moves-grid-left)] [(key=? a-key "right") (list right moves-grid-right)] [(key=? a-key "up") (list up moves-grid-up)] [(key=? a-key "down") (list down moves-grid-down)] [else (list #f #f)]))   ;; Respond to a key-press ;; (define (change w a-key) (match-let ([(list op moves-op) (key->ops a-key)] [(world st score wt frames start-time) w]) (cond [(out-of-time? start-time) w] ; Stop accepting key-presses [op (let* ([grid (chop st)] [slide-state (flatten (op grid))]) (if (equal? slide-state st) w  ; sliding had no effect (let* ([replace (random (count-zeros slide-state))] [index (index-of-nth-zero slide-state replace)] [value (new-tile)] [new-state (replace-nth-zero slide-state replace value)] [horizontal? (member a-key (list "left" "right"))]) (make-world new-state (+ score (score-increment (if horizontal? grid (transpose grid)))) (cond [wt wt] [(won-game? new-state) (apply + (flatten new-state))] [else #f]) (append frames (animate-moving-tiles st moves-op) (animate-appearing-tile slide-state value index)) start-time))))] [(key=? a-key " ")  ; rotate the board (make-world ((compose flatten transpose reverse) (chop st)) score wt (append frames (animate-moving-tiles st moves-grid-rotate)) start-time)] [else w])))  ; unrecognised key - no effect   ;; Are we there yet? ;; (define (won-game? state) (= (apply max state) *tile-that-wins*))   ;; Banner overlay text: e.g. You won! / Game Over, etc. ;; (define (banner txt state [color 'black]) (let ([b-text (text txt 30 color)]) (overlay b-text (rectangle (* 1.2 (image-width b-text)) (* 1.4 (image-height b-text)) 'solid 'white) (state->image state))))   ;; Convert number of seconds to "h:mm:ss" or "m:ss" format ;; (define (number->time-string s) (define hrs (quotient s 3600)) (define mins (quotient (remainder s 3600) 60)) (define secs (remainder s 60)) (define (xx n) (cond [(<= n 0) "00"] [(<= n 9) (format "0~a" n)] [else (remainder n 60)])) (if (>= s 3600) (format "~a:~a:~a" hrs (xx mins) (xx secs)) (format "~a:~a" mins (xx secs))))   (define (time-remaining start) (+ *time-limit* start (- (current-seconds))))   (define (time-elapsed start) (- (current-seconds) start))   ;; Display the grid with score below. ;; ;; If there are frames, show the next one. Otherwise show the steady state. ;; (define (show-world w) (match-define (world state score wt frames start-time) w) (let* ([board (if (null? frames) (cond [(finished? state) (banner "Game over" state)] [(out-of-time? start-time) (banner "Out of Time" state 'red)]    ;; Q: Why wt (i.e. winning-total) rather than won-game?  ;; A: wt allows the keen player to continue playing... [(equal? (apply + (flatten state)) wt) (banner "You won!" state)] [else (state->image state)]) ((first frames)))] [score-text (text (format "Score: ~a" score) 16 'dimgray)] [seconds ((if *time-limit* time-remaining time-elapsed) start-time)] [time-text (text (format "Time: ~a" (number->time-string seconds)) 16 (cond [(or (> seconds *amber-alert*) (not *time-limit*)) 'gray] [(> seconds *red-alert*) 'orange] [else 'red]))]) (scale *magnification* (above board (rectangle 0 5 'solid 'white) (beside score-text (rectangle (- (image-width board) (image-width score-text) (image-width time-text)) 0 'solid 'white) time-text)))))   ;; Move to the next frame in the animation. ;; (define (advance-frame w) (match-define (world state score wt frames start-time) w) (if (null? frames) w (make-world state score wt (rest frames) start-time)))   ;; Use this state to preview the appearance of all the tiles ;; (define (all-tiles-state) (let ([all-tiles '(0 2 4 8 16 32 64 128 256 512 1024 2048 4096)]) (append all-tiles (make-list (- (sqr *side*) (length all-tiles)) 0))))   ;; The event loop ;; (define (start) (big-bang (make-world (initial-state)  ;(all-tiles-state) 0 #f null (current-seconds)) (to-draw show-world) (on-key change) (on-tick advance-frame 0.01) (stop-when game-over? show-world) (name "2048 - Racket edition")))   ;; ;; TESTS ;; (module+ test (set-side! 4)   (check-equal? (slide-left '(0 0 0 0)) '(0 0 0 0)) (check-equal? (slide-left '(1 2 3 4)) '(1 2 3 4)) (check-equal? (slide-left '(2 0 4 0)) '(2 4 0 0)) (check-equal? (slide-left '(0 0 2 4)) '(2 4 0 0)) (check-equal? (slide-left '(2 0 2 0)) '(4 0 0 0)) (check-equal? (slide-left '(0 8 8 0)) '(16 0 0 0)) (check-equal? (slide-left '(4 4 8 8)) '(8 16 0 0)) (check-equal? (slide-right '(4 4 8 8)) '(0 0 8 16)) (check-equal? (slide-right '(4 4 4 0)) '(0 0 4 8))   (check-equal? (moves-row-left '(0 0 0 0)) '()) (check-equal? (moves-row-left '(1 2 3 4)) '((1 0 0) (2 1 1) (3 2 2) (4 3 3)))   (check-equal? (moves-row-left '(2 0 4 0)) '((2 0 0) (4 2 1)))   (check-equal? (moves-row-right '(2 0 4 0)) '((4 2 3) (2 0 2)))   (check-equal? (moves-row-left '(0 0 2 4)) '((2 2 0) (4 3 1)))   (check-equal? (moves-row-left '(2 0 2 0)) '((2 0 0) (2 2 0)))   (check-equal? (moves-row-left '(2 2 2 0)) '((2 0 0) (2 1 0) (2 2 1)))   (check-equal? (moves-row-right '(2 2 2 0)) '((2 2 3) (2 1 3) (2 0 2)))   (check-equal? (moves-row-left '(2 2 4 4)) '((2 0 0) (2 1 0) (4 2 1) (4 3 1)))   (check-equal? (moves-row-right '(2 2 4 4)) '((4 3 3) (4 2 3) (2 1 2) (2 0 2)))   (check-equal? (add-row-coord 7 '((2 0 0) (2 1 0) (4 2 1))) '((2 (7 0) (7 0)) (2 (7 1) (7 0)) (4 (7 2) (7 1))))   (check-equal? (left '(( 0 8 8 0) (16 0 0 0) ( 2 2 4 4) ( 0 2 2 2))) '((16 0 0 0) (16 0 0 0) ( 4 8 0 0) ( 4 2 0 0))) (check-equal? (right '(( 0 8 8 0) (16 0 0 0) ( 2 2 4 4) ( 0 2 2 2))) '((0 0 0 16) (0 0 0 16) (0 0 4 8) (0 0 2 4))) (check-equal? (up '((0 16 2 0) (8 0 2 2) (8 0 4 2) (0 0 4 2))) '((16 16 4 4) (0 0 8 2) (0 0 0 0) (0 0 0 0))) (check-equal? (down '((0 16 2 0) (8 0 2 2) (8 0 4 2) (0 0 4 2))) '((0 0 0 0) (0 0 0 0) (0 0 4 2) (16 16 8 4)))   (check-equal? (left '(( 0 8 8 0) (16 0 0 0) ( 2 2 4 4) ( 0 2 2 2))) '((16 0 0 0) (16 0 0 0) ( 4 8 0 0) ( 4 2 0 0)))   (check-equal? (moves-grid-left '(( 0 8 8 0) (16 0 0 0) ( 2 2 4 4) ( 0 2 2 2))) '((8 (0 1) (0 0)) (8 (0 2) (0 0)) (16 (1 0) (1 0)) (2 (2 0) (2 0)) (2 (2 1) (2 0)) (4 (2 2) (2 1)) (4 (2 3) (2 1)) (2 (3 1) (3 0)) (2 (3 2) (3 0)) (2 (3 3) (3 1))))   (check-equal? (moves-grid-right '(( 0 8 8 0) (16 0 0 0) ( 2 2 4 4) ( 0 2 2 2))) '((8 (0 2) (0 3)) (8 (0 1) (0 3)) (16 (1 0) (1 3)) (4 (2 3) (2 3)) (4 (2 2) (2 3)) (2 (2 1) (2 2)) (2 (2 0) (2 2)) (2 (3 3) (3 3)) (2 (3 2) (3 3)) (2 (3 1) (3 2))))     (check-equal? (moves-grid-up '(( 0 8 8 0) (16 0 0 0) ( 2 2 4 4) ( 0 2 2 2))) '((16 (1 0) (0 0)) (2 (2 0) (1 0)) (8 (0 1) (0 1)) (2 (2 1) (1 1)) (2 (3 1) (1 1)) (8 (0 2) (0 2)) (4 (2 2) (1 2)) (2 (3 2) (2 2)) (4 (2 3) (0 3)) (2 (3 3) (1 3))))   (check-equal? (moves-grid-down '(( 0 8 8 0) (16 0 0 0) ( 2 2 4 4) ( 0 2 2 2))) '((2 (2 0) (3 0)) (16 (1 0) (2 0)) (2 (3 1) (3 1)) (2 (2 1) (3 1)) (8 (0 1) (2 1)) (2 (3 2) (3 2)) (4 (2 2) (2 2)) (8 (0 2) (1 2)) (2 (3 3) (3 3)) (4 (2 3) (2 3))))   (check-equal? (chop '(1 2 3 4 5 6 7 8) 4) '((1 2 3 4) (5 6 7 8)))   (check-equal? (length (initial-state 5)) 25)   (let* ([initial (initial-state)] [initial-sum (apply + initial)] [largest-3 (take (sort initial >) 3)]) (check-equal? (length initial) 16) (check-true (or (= initial-sum 4) (= initial-sum 6) (= initial-sum 8))) (check-true (or (equal? largest-3 '(2 2 0)) (equal? largest-3 '(4 2 0)) (equal? largest-3 '(4 4 0)))))   (check-equal? (count-zeros '(1 0 1 0 0 0 1)) 4) (check-equal? (count-zeros '(1 1)) 0) (check-equal? (replace-nth-zero '(0 0 0 1 2 0) 2 5) '(0 0 5 1 2 0))   (check-true (finished? '(1 2 3 4) 2)) (check-false (finished? '(2 2 3 4) 2)))   (start)  
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 down, pass it around 97 bottles of beer on the wall ... and so on, until reaching   0     (zero). Grammatical support for   1 bottle of beer   is optional. As with any puzzle, try to do it in as creative/concise/comical a way as possible (simple, obvious solutions allowed, too). Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet See also   http://99-bottles-of-beer.net/   Category:99_Bottles_of_Beer   Category:Programming language families   Wikipedia 99 bottles of beer
#CLU
CLU
bottles = proc (n: int) returns (string) if n<0 then return("99 bottles") elseif n=0 then return("No more bottles") elseif n=1 then return("1 bottle") else return(int$unparse(n) || " bottles") end end bottles   thirdline = proc (n: int) returns (string) if n=0 then return("Go to the store and buy some more,\n") else s: string if n=1 then s := "it" else s := "one" end return("Take " || s || " down and pass it around,\n"); end end thirdline   verse = proc (n: int) returns (string) v: string := bottles(n) || " bottles of beer on the wall,\n" v := v || bottles(n) || " bottles of beer,\n" v := v || thirdline(n) v := v || bottles(n-1) || " bottles of beer on the wall.\n\n" return(v) end verse   start_up = proc () po: stream := stream$primary_output()   for n: int in int$from_to_by(99, 0, -1) do stream$puts(po, verse(n)) end end start_up
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. The program should check then evaluate the expression. The goal is for the player to enter an expression that (numerically) evaluates to 24. Only the following operators/functions are allowed: multiplication, division, addition, subtraction Division should use floating point or rational arithmetic, etc, to preserve remainders. Brackets are allowed, if using an infix expression evaluator. Forming multiple digit numbers from the supplied digits is disallowed. (So an answer of 12+12 when given 1, 2, 2, and 1 is wrong). The order of the digits when given does not have to be preserved. Notes The type of expression evaluator used is not mandated. An RPN evaluator is equally acceptable for example. The task is not for the program to generate the expression, or test whether an expression is even possible. Related tasks 24 game/Solve Reference The 24 Game on h2g2.
#PARI.2FGP
PARI/GP
game()={ my(v=vecsort(vector(4,i,random(8)+1))); print("Form 24 using */+-() and: "v); while(1, my(ans=input); if (!valid(s,v), next); trap(, print("Arithmetic error"); next , if(eval(s)==24, break, print("Bad sum")) ) ); print("You win!") }; valid(s,v)={ my(op=vecsort(Vec("+-*/()")),u=[]); s=Vec(s); for(i=1,#s, if(setsearch(op,s[i]),next); trap(, print("Invalid character "s[i]); return(0) , if(setsearch(v,eval(s[i])), u=concat(u,eval(s[i])) , print(s[i]" not allowed"); return(0) ) ) ); for(i=2,#s, if(!setsearch(op,s[i])&!setsearch(op,s[i-1]), print("Concatenating digits is not allowed!"); return(0) ) ); if(vecsort(u)!=v, print("Invalid digits"); 0 , 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 ≤ A , B ≤ + 1000 ) {\displaystyle (-1000\leq A,B\leq +1000)} Output data The required output is one integer:   the sum of A and B. Example input   output   2 2 4 3 2 5
#Free_Pascal
Free Pascal
program SUMA; uses SysUtils; var s1, s2:integer; begin ReadLn(s1); Readln(s2); WriteLn(IntToStr(s1 + s2)); 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 sides of the blocks. The sample collection of 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) Task Write a function that takes a string (word) and determines whether the word can be spelled with the given collection of blocks. The rules are simple:   Once a letter on a block is used that block cannot be used again   The function should be case-insensitive   Show the output on this page for the following 7 words in the following example Example >>> can_make_word("A") True >>> can_make_word("BARK") True >>> can_make_word("BOOK") False >>> can_make_word("TREAT") True >>> can_make_word("COMMON") False >>> can_make_word("SQUAD") True >>> can_make_word("CONFUSE") True Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#PowerBASIC
PowerBASIC
#COMPILE EXE #DIM ALL ' ' A B C p r o b l e m . b a s ' ' by Geary Chopoff ' for Chopoff Consulting and RosettaCode.org ' on 2014Jul23 ' '2014Jul23 ' 'You are given a collection of ABC blocks. Just like the ones you had when you were a kid. 'There are twenty blocks with two letters on each block. You are guaranteed to have a complete 'alphabet amongst all sides of the blocks. The sample blocks are: '((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)) 'The goal of this task is to write a function that takes a string and can determine whether 'you can spell the word with the given collection of blocks. ' 'The rules are simple: '1.Once a letter on a block is used that block cannot be used again '2.The function should be case-insensitive '3. Show your output on this page for the following words: ' A, BARK, BOOK, TREAT, COMMON, SQUAD, CONFUSE '----------------------------------------------------------------------------- ' G l o b a l C o n s t a n t s ' %Verbose = 0 'make this 1 to have a lot of feedback %MAX_BLOCKS = 20 'total number of blocks %MAX_SIDES = 2 'total number of sides containing a unique letter per block   %MAX_ASC = 255 %FALSE = 0 'this is correct because there is ONLY ONE value for FALSE %TRUE = (NOT %FALSE) 'this is one of MANY values of TRUE! $FLAG_TRUE = "1" $FLAG_FALSE = "0" '----------------------------------------------------------------------------- ' G l o b a l V a r i a b l e s ' GLOBAL blk() AS STRING '----------------------------------------------------------------------------- 'i n i t B l o c k s ' ' as we will use this array only once we build it each time program is run ' SUB initBlocks LOCAL j AS INTEGER j=1 blk(j)="BO" j=j+1 blk(j)="XK" j=j+1 blk(j)="DQ" j=j+1 blk(j)="CP" j=j+1 blk(j)="NA" j=j+1 blk(j)="GT" j=j+1 blk(j)="RE" j=j+1 blk(j)="TG" j=j+1 blk(j)="QD" j=j+1 blk(j)="FS" j=j+1 blk(j)="JW" j=j+1 blk(j)="HU" j=j+1 blk(j)="VI" j=j+1 blk(j)="AN" j=j+1 blk(j)="OB" j=j+1 blk(j)="ER" j=j+1 blk(j)="FS" j=j+1 blk(j)="LY" j=j+1 blk(j)="PC" j=j+1 blk(j)="ZM" IF j <> %MAX_BLOCKS THEN STDOUT "initBlocks:Error: j is not same as MAX_BLOCKS!",j,%MAX_BLOCKS END IF END SUB '----------------------------------------------------------------------------- ' m a k e W o r d ' FUNCTION makeWord(tryWord AS STRING) AS BYTE LOCAL retTF AS BYTE LOCAL j AS INTEGER LOCAL s AS INTEGER 'which side of block we are looking at LOCAL k AS INTEGER LOCAL c AS STRING 'character in tryWord we are looking for     FOR j = 1 TO LEN(tryWord) c = UCASE$(MID$(tryWord,j,1)) 'character we want to show with block   retTF = %FALSE 'we assume this will fail   FOR k = 1 TO %MAX_BLOCKS IF LEN(blk(k)) = %MAX_SIDES THEN FOR s = 1 TO %MAX_SIDES IF c = MID$(blk(k),s,1) THEN retTF = %TRUE 'this block has letter we want blk(k) = "" 'remove this block from further consideration EXIT FOR END IF NEXT s END IF IF retTF THEN EXIT FOR 'can go on to next character in word NEXT k IF ISFALSE retTF THEN EXIT FOR 'if character not found then all is done NEXT j   FUNCTION = retTF END FUNCTION '----------------------------------------------------------------------------- ' P B M A I N ' FUNCTION PBMAIN () AS LONG DIM blk(1 TO %MAX_BLOCKS, 1 TO %MAX_SIDES) AS STRING LOCAL cmdLine AS STRING   initBlocks 'setup global array of blocks   cmdLine=COMMAND$ IF LEN(cmdLine)= 0 THEN STDOUT "Useage for ABCproblem Version 1.00:" STDOUT "" STDOUT " >ABCproblem tryThisWord" STDOUT "" STDOUT "Where tryThisWord is a word you want to see if"+STR$(%MAX_BLOCKS)+" blocks can make." STDOUT "If word can be made TRUE is returned." STDOUT "Otherwise FALSE is returned." EXIT FUNCTION END IF   IF INSTR(TRIM$(cmdLine)," ") = 0 THEN IF makeWord(cmdLine) THEN STDOUT "TRUE" ELSE STDOUT "FALSE" END IF ELSE STDOUT "Error:Missing word to try to make with blocks! <" & cmdLine & ">" EXIT FUNCTION END IF END FUNCTION  
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 decide some strategy before any enter the room. Prisoners enter the room one by one, can open a drawer, inspect the card number in the drawer, then close the drawer. A prisoner can open no more than 50 drawers. A prisoner tries to find his own number. A prisoner finding his own number is then held apart from the others. If all 100 prisoners find their own numbers then they will all be pardoned. If any don't then all sentences stand. The task Simulate several thousand instances of the game where the prisoners randomly open drawers Simulate several thousand instances of the game where the prisoners use the optimal strategy mentioned in the Wikipedia article, of: First opening the drawer whose outside number is his prisoner number. If the card within has his number then he succeeds otherwise he opens the drawer with the same number as that of the revealed card. (until he opens his maximum). Show and compare the computed probabilities of success for the two strategies, here, on this page. References The unbelievable solution to the 100 prisoner puzzle standupmaths (Video). wp:100 prisoners problem 100 Prisoners Escape Puzzle DataGenetics. Random permutation statistics#One hundred prisoners on Wikipedia.
#Raku
Raku
unit sub MAIN (:$prisoners = 100, :$simulations = 10000); my @prisoners = ^$prisoners; my $half = floor +@prisoners / 2;   sub random ($n) { ^$n .race.map( { my @drawers = @prisoners.pick: *; @prisoners.map( -> $prisoner { my $found = 0; for @drawers.pick($half) -> $card { $found = 1 and last if $card == $prisoner } last unless $found; $found } ).sum == @prisoners } ).grep( *.so ).elems / $n * 100 }   sub optimal ($n) { ^$n .race.map( { my @drawers = @prisoners.pick: *; @prisoners.map( -> $prisoner { my $found = 0; my $card = @drawers[$prisoner]; if $card == $prisoner { $found = 1 } else { for ^($half - 1) { $card = @drawers[$card]; $found = 1 and last if $card == $prisoner } } last unless $found; $found } ).sum == @prisoners } ).grep( *.so ).elems / $n * 100 }   say "Testing $simulations simulations with $prisoners prisoners."; printf " Random play wins: %.3f%% of simulations\n", random $simulations; printf "Optimal play wins: %.3f%% of simulations\n", optimal $simulations;
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
#Picat
Picat
  import util.   main => Board = {{1,2,3,4}, {5,6,7,8}, {9,10,11,12}, {13,14,15,0}}, Goal = copy_term(Board), shuffle(Board), play(Board,Goal).   shuffle(Board) => foreach (_ in 1..1000) R1 = random() mod 4 + 1, C1 = random() mod 4 + 1, R2 = random() mod 4 + 1, C2 = random() mod 4 + 1, T := Board[R1,C1], Board[R1,C1] := Board[R2,C2], Board[R2,C2] := T end.   play(Board,Goal) => while (Board != Goal) print_board(Board), possible_moves(Board,R0,C0,Moves), printf("Possible moves are: %w, 0 to exit. Your move? => ", Moves), S = read_line().strip(), if S == "0" || S == "" then halt else move_hole(Board,R0,C0,to_int(S)) end end, print_board(Board), println("Puzzle solved.").   print_board(Board) => N = len(Board), print("+----+----+----+----+\n"), foreach (R in 1..N) print("|"), foreach (C in 1..N) printf("%4d|", Board[R,C]) end, nl end, println("+----+----+----+----+").   possible_moves(Board,R0,C0,Moves) => N = len(Board), between(1,N,R0), between(1,N,C0), Board[R0,C0] == 0, !, NeibsOfHole = [(R1,C1) : (R1,C1) in [(R0-1,C0), (R0+1,C0), (R0,C0-1), (R0,C0+1)], R1 >= 1, R1 =< N, C1 >= 1, C1 =< N], Moves = sort([Board[R,C] : (R,C) in NeibsOfHole]).   move_hole(Board,R0,C0,S) => N = len(Board), between(1,N,R), between(1,N,C), Board[R,C] == S, !, Board[R0,C0] := S, Board[R,C] := 0.  
http://rosettacode.org/wiki/2048
2048
Task Implement a 2D sliding block puzzle game where blocks with numbers are combined to add their values. Rules of the game   The rules are that on each turn the player must choose a direction   (up, down, left or right).   All tiles move as far as possible in that direction, some move more than others.   Two adjacent tiles (in that direction only) with matching numbers combine into one bearing the sum of those numbers.   A move is valid when at least one tile can be moved,   if only by combination.   A new tile with the value of   2   is spawned at the end of each turn at a randomly chosen empty square   (if there is one).   Adding a new tile on a blank space.   Most of the time,   a new   2   is to be added,   and occasionally   (10% of the time),   a   4.   To win,   the player must create a tile with the number   2048.   The player loses if no valid moves are possible. The name comes from the popular open-source implementation of this game mechanic, 2048. Requirements   "Non-greedy" movement.     The tiles that were created by combining other tiles should not be combined again during the same turn (move).     That is to say,   that moving the tile row of: [2][2][2][2] to the right should result in: ......[4][4] and not: .........[8]   "Move direction priority".     If more than one variant of combining is possible,   move direction shall indicate which combination will take effect.   For example, moving the tile row of: ...[2][2][2] to the right should result in: ......[2][4] and not: ......[4][2]   Check for valid moves.   The player shouldn't be able to skip their turn by trying a move that doesn't change the board.   Check for a  win condition.   Check for a lose condition.
#Raku
Raku
use Term::termios;   constant $saved = Term::termios.new(fd => 1).getattr; constant $termios = Term::termios.new(fd => 1).getattr; # raw mode interferes with carriage returns, so # set flags needed to emulate it manually $termios.unset_iflags(<BRKINT ICRNL ISTRIP IXON>); $termios.unset_lflags(< ECHO ICANON IEXTEN ISIG>); $termios.setattr(:DRAIN);   # reset terminal to original setting on exit END { $saved.setattr(:NOW) }   constant n = 4; # board size constant cell = 6; # cell width constant ansi = True; # color!   my @board = ( ['' xx n] xx n ); my $save = ''; my $score = 0;   constant $top = join '─' x cell, '┌', '┬' xx n-1, '┐'; constant $mid = join '─' x cell, '├', '┼' xx n-1, '┤'; constant $bot = join '─' x cell, '└', '┴' xx n-1, '┘';   my %dir = ( "\e[A" => 'up', "\e[B" => 'down', "\e[C" => 'right', "\e[D" => 'left', );   my @ANSI = <0 1;97 1;93 1;92 1;96 1;91 1;95 1;94 1;30;47 1;43 1;42 1;46 1;41 1;45 1;44 1;33;43 1;33;42 1;33;41 1;33;44>;   sub row (@row) { '│' ~ (join '│', @row».&center) ~ '│' }   sub center ($s){ my $c = cell - $s.chars; my $pad = ' ' x ceiling($c/2); my $tile = sprintf "%{cell}s", "$s$pad"; my $idx = $s ?? $s.log(2) !! 0; ansi ?? "\e[{@ANSI[$idx]}m$tile\e[0m" !! $tile; }   sub draw-board { run('clear'); print qq:to/END/;     Press direction arrows to move.   Press q to quit.   $top { join "\n\t$mid\n\t", map { .&row }, @board } $bot   Score: $score   END }   sub squash (@c) { my @t = grep { .chars }, @c; map { combine(@t[$_], @t[$_+1]) if @t[$_] && @t[$_+1] == @t[$_] }, ^@t-1; @t = grep { .chars }, @t; @t.push: '' while @t < n; @t; }   sub combine ($v is rw, $w is rw) { $v += $w; $w = ''; $score += $v; }   proto sub move (|) {*};   multi move('up') { map { @board[*;$_] = squash @board[*;$_] }, ^n; }   multi move('down') { map { @board[*;$_] = reverse squash reverse @board[*;$_] }, ^n; }   multi move('left') { map { @board[$_] = squash @board[$_] }, ^n; }   multi move('right') { map { @board[$_;*] = reverse squash reverse @board[$_] }, ^n; }   sub another { my @empties; for @board.kv -> $r, @row { @empties.push(($r, $_)) for @row.grep(:k, ''); } my ( $x, $y ) = @empties.roll; @board[$x; $y] = (flat 2 xx 9, 4).roll; }   sub save () { join '|', flat @board».list }   loop { another if $save ne save(); draw-board; $save = save();   # Read up to 4 bytes from keyboard buffer. # Page navigation keys are 3-4 bytes each. # Specifically, arrow keys are 3. my $key = $*IN.read(4).decode;   move %dir{$key} if so %dir{$key}; last if $key eq 'q'; # (q)uit }
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 down, pass it around 97 bottles of beer on the wall ... and so on, until reaching   0     (zero). Grammatical support for   1 bottle of beer   is optional. As with any puzzle, try to do it in as creative/concise/comical a way as possible (simple, obvious solutions allowed, too). Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet See also   http://99-bottles-of-beer.net/   Category:99_Bottles_of_Beer   Category:Programming language families   Wikipedia 99 bottles of beer
#COBOL
COBOL
identification division. program-id. ninety-nine. environment division. data division. working-storage section. 01 counter pic 99. 88 no-bottles-left value 0. 88 one-bottle-left value 1.   01 parts-of-counter redefines counter. 05 tens pic 9. 05 digits pic 9.   01 after-ten-words. 05 filler pic x(7) value spaces. 05 filler pic x(7) value "Twenty". 05 filler pic x(7) value "Thirty". 05 filler pic x(7) value "Forty". 05 filler pic x(7) value "Fifty". 05 filler pic x(7) value "Sixty". 05 filler pic x(7) value "Seventy". 05 filler pic x(7) value "Eighty". 05 filler pic x(7) value "Ninety". 05 filler pic x(7) value spaces.   01 after-ten-array redefines after-ten-words. 05 atens occurs 10 times pic x(7).   01 digit-words. 05 filler pic x(9) value "One". 05 filler pic x(9) value "Two". 05 filler pic x(9) value "Three". 05 filler pic x(9) value "Four". 05 filler pic x(9) value "Five". 05 filler pic x(9) value "Six". 05 filler pic x(9) value "Seven". 05 filler pic x(9) value "Eight". 05 filler pic x(9) value "Nine". 05 filler pic x(9) value "Ten". 05 filler pic x(9) value "Eleven". 05 filler pic x(9) value "Twelve". 05 filler pic x(9) value "Thirteen". 05 filler pic x(9) value "Fourteen". 05 filler pic x(9) value "Fifteen". 05 filler pic x(9) value "Sixteen". 05 filler pic x(9) value "Seventeen". 05 filler pic x(9) value "Eighteen". 05 filler pic x(9) value "Nineteen". 05 filler pic x(9) value spaces.   01 digit-array redefines digit-words. 05 adigits occurs 20 times pic x(9).   01 number-name pic x(15).   procedure division. 100-main section. 100-setup. perform varying counter from 99 by -1 until no-bottles-left perform 100-show-number display " of beer on the wall" perform 100-show-number display " of beer" display "Take " with no advancing if one-bottle-left display "it " with no advancing else display "one " with no advancing end-if display "down and pass it round" subtract 1 from counter giving counter perform 100-show-number display " of beer on the wall" add 1 to counter giving counter display space end-perform. display "No more bottles of beer on the wall" display "No more bottles of beer" display "Go to the store and buy some more" display "Ninety Nine bottles of beer on the wall" stop run.   100-show-number. if no-bottles-left display "No more" with no advancing else if counter < 20 display function trim( adigits( counter ) ) with no advancing else if counter < 100 move spaces to number-name string atens( tens ) delimited by space, space delimited by size, adigits( digits ) delimited by space into number-name display function trim( number-name) with no advancing end-if end-if end-if. if one-bottle-left display " bottle" with no advancing else display " bottles" with no advancing end-if.   100-end. end-program.
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. The program should check then evaluate the expression. The goal is for the player to enter an expression that (numerically) evaluates to 24. Only the following operators/functions are allowed: multiplication, division, addition, subtraction Division should use floating point or rational arithmetic, etc, to preserve remainders. Brackets are allowed, if using an infix expression evaluator. Forming multiple digit numbers from the supplied digits is disallowed. (So an answer of 12+12 when given 1, 2, 2, and 1 is wrong). The order of the digits when given does not have to be preserved. Notes The type of expression evaluator used is not mandated. An RPN evaluator is equally acceptable for example. The task is not for the program to generate the expression, or test whether an expression is even possible. Related tasks 24 game/Solve Reference The 24 Game on h2g2.
#Perl
Perl
#!/usr/bin/env perl use warnings; use strict; use feature 'say';   print <<'EOF'; 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 parentheses, (), show how to make an answer of 24.   An answer of "q" or EOF will quit the game. A blank answer will generate a new set of four digits. Otherwise you are repeatedly asked for an expression until it evaluates to 24.   Note: you cannot form multiple digit numbers from the supplied digits, so an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed. EOF   my $try = 1; while (1) { my @digits = map { 1+int(rand(9)) } 1..4; say "\nYour four digits: ", join(" ", @digits); print "Expression (try ", $try++, "): ";   my $entry = <>; if (!defined $entry || $entry eq 'q') { say "Goodbye. Sorry you couldn't win."; last; } $entry =~ s/\s+//g; # remove all white space next if $entry eq '';   my $given_digits = join "", sort @digits; my $entry_digits = join "", sort grep { /\d/ } split(//, $entry); if ($given_digits ne $entry_digits || # not correct digits $entry =~ /\d\d/ || # combined digits $entry =~ m|[-+*/]{2}| || # combined operators $entry =~ tr|-0-9()+*/||c) # Invalid characters { say "That's not valid"; next; }   my $n = eval $entry;   if (!defined $n) { say "Invalid expression"; } elsif ($n == 24) { say "You win!"; last; } else { say "Sorry, your expression is $n, not 24"; } }
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 ≤ A , B ≤ + 1000 ) {\displaystyle (-1000\leq A,B\leq +1000)} Output data The required output is one integer:   the sum of A and B. Example input   output   2 2 4 3 2 5
#Frink
Frink
  sum[eval[split[%r/\s+/, input[""]]]]  
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 sides of the blocks. The sample collection of 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) Task Write a function that takes a string (word) and determines whether the word can be spelled with the given collection of blocks. The rules are simple:   Once a letter on a block is used that block cannot be used again   The function should be case-insensitive   Show the output on this page for the following 7 words in the following example Example >>> can_make_word("A") True >>> can_make_word("BARK") True >>> can_make_word("BOOK") False >>> can_make_word("TREAT") True >>> can_make_word("COMMON") False >>> can_make_word("SQUAD") True >>> can_make_word("CONFUSE") True Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#PowerShell
PowerShell
<# .Synopsis ABC Problem .DESCRIPTION You are given a collection of ABC blocks. Just like the ones you had when you were a kid. There are twenty blocks with two letters on each block. You are guaranteed to have a complete alphabet amongst all sides of the blocks blocks = "BO","XK","DQ","CP","NA","GT","RE","TG","QD","FS","JW","HU","VI","AN","OB","ER","FS","LY","PC","ZM" The goal of this task is to write a function that takes a string and can determine whether you can spell the word with the given collection of blocks.   The rules are simple: 1.Once a letter on a block is used that block cannot be used again 2.The function should be case-insensitive 3. Show your output on this page for the following words: >>> can_make_word("A") True >>> can_make_word("BARK") True >>> can_make_word("BOOK") False >>> can_make_word("TREAT") True >>> can_make_word("COMMON") False >>> can_make_word("SQUAD") True >>> can_make_word("CONFUSE") True   Using the examples below you can either see just the value or status and the values using the verbose switch   .EXAMPLE test-blocks -testword confuse   .EXAMPLE test-blocks -testword confuse -verbose   #>   function test-blocks { [CmdletBinding()] # [OutputType([int])] Param ( # word to test against blocks [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)] $testword   )   $word = $testword   #define array of blocks [System.Collections.ArrayList]$blockarray = "BO", "XK", "DQ", "CP", "NA", "GT", "RE", "TG", "QD", "FS", "JW", "HU", "VI", "AN", "OB", "ER", "FS", "LY", "PC", "ZM"   #send word to chararray $chararray = $word.ToCharArray() $chars = $chararray   #get the character count $charscount = $chars.count   #get the initial count of the blocks $blockcount = $blockarray.Count   #find out how many blocks should be left from the difference #of the blocks and characters in the word - 1 letter/1 block $correctblockcount = $blockcount - $charscount   #loop through the characters in the word foreach ($char in $chars) {   #loop through the blocks foreach ($block in $blockarray) {   #check the current character against each letter on the current block #and break if found so the array can reload if ($char -in $block[0] -or $char -in $block[1]) {   write-verbose "match for letter - $char - removing block $block" $blockarray.Remove($block) break   }   }   } #get final count of blocks left in array to determine if the word was #correctly made $finalblockcount = $blockarray.count if ($finalblockcount -ne $correctblockcount) { write-verbose "$word : $false " return $false } else { write-verbose "$word : $true " return $true }   }   #loop all the words and pass them to the function $wordlist = "a", "bark", "book", "treat", "common", "squad", "confuse" foreach ($word in $wordlist) { test-blocks -testword $word -Verbose }
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 decide some strategy before any enter the room. Prisoners enter the room one by one, can open a drawer, inspect the card number in the drawer, then close the drawer. A prisoner can open no more than 50 drawers. A prisoner tries to find his own number. A prisoner finding his own number is then held apart from the others. If all 100 prisoners find their own numbers then they will all be pardoned. If any don't then all sentences stand. The task Simulate several thousand instances of the game where the prisoners randomly open drawers Simulate several thousand instances of the game where the prisoners use the optimal strategy mentioned in the Wikipedia article, of: First opening the drawer whose outside number is his prisoner number. If the card within has his number then he succeeds otherwise he opens the drawer with the same number as that of the revealed card. (until he opens his maximum). Show and compare the computed probabilities of success for the two strategies, here, on this page. References The unbelievable solution to the 100 prisoner puzzle standupmaths (Video). wp:100 prisoners problem 100 Prisoners Escape Puzzle DataGenetics. Random permutation statistics#One hundred prisoners on Wikipedia.
#Red
Red
  Red []   K_runs: 100000 repeat n 100 [append rand_arr: [] n] ;; define array/series with numbers 1..100   ;;------------------------------- strat_optimal: function [pris ][ ;;------------------------------- locker: pris ;; start with locker equal to prisoner number loop 50 [ if Board/:locker = pris [ return true ] ;; locker with prisoner number found locker: Board/:locker ] false ;; number not found - fail ] ;;------------------------------- strat_rand: function [pris ][ ;;------------------------------- random rand_arr ;; define set of random lockers repeat n 50 [ if Board/(rand_arr/:n) = pris [ return true ] ] ;; try first 50, found ? then return success false ]   ;;------------------------------ check_board: function [ strat][ ;;------------------------------ repeat pris 100 [ ;; for each prisoner either strat = 'optimal [ unless strat_optimal pris [return false ] ] [ unless strat_rand pris [return false ] ] ] true ;; all 100 prisoners passed test ]   saved: saved_rand: 0 ;; count all saved runs per strategy loop K_runs [ Board: random copy rand_arr ;; new board for every run if check_board 'optimal [saved: saved + 1] ;; optimal stategy if check_board 'rand [saved_rand: saved_rand + 1] ;; random strategy ]   print ["runs" k_runs newline "Percent saved opt.strategy:" saved * 100.0 / k_runs ] print ["Percent saved random strategy:" saved_rand * 100.0 / k_runs ]  
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
#Powershell
Powershell
  #15 Puzzle Game $Script:Neighbours = @{ "1" = @("2","5") "2" = @("1","3","6") "3" = @("2","4","7") "4" = @("3","8") "5" = @("1","6","9") "6" = @("2","5","7","10") "7" = @("3","6","8","11") "8" = @("4","7","12") "9" = @("5","10","13") "10" = @("6","9","11","14") "11" = @("7","10","12","15") "12" = @("8","11","0") "13" = @("9","14") "14" = @("10","13","15") "15" = @("11","14","0") "0" = @("12","15") } $script:blank = '' #region XAML window definition $xaml = @' <Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" MinWidth="200" Width ="333.333" Title="15 Game" Topmost="True" Height="398.001" VerticalAlignment="Center" HorizontalAlignment="Center"> <Grid HorizontalAlignment="Center" Height="285" Margin="0" VerticalAlignment="Center" Width="300"> <Grid.ColumnDefinitions> <ColumnDefinition/> <ColumnDefinition/> <ColumnDefinition/> <ColumnDefinition/> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition/> <RowDefinition/> <RowDefinition/> <RowDefinition/> </Grid.RowDefinitions> <Button x:Name="B_1" Content="01" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Height="72" FontSize="24"/> <Button x:Name="B_2" Content="02" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Height="72" FontSize="24" Grid.Column="1"/> <Button x:Name="B_3" Content="03" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Height="72" FontSize="24" Grid.Column="2"/> <Button x:Name="B_4" Content="04" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Height="72" FontSize="24" Grid.Column="3"/> <Button x:Name="B_5" Content="05" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Height="72" FontSize="24" Grid.Row="1"/> <Button x:Name="B_6" Content="06" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Height="72" FontSize="24" Grid.Column="1" Grid.Row="1"/> <Button x:Name="B_7" Content="07" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Height="72" FontSize="24" Grid.Column="2" Grid.Row="1"/> <Button x:Name="B_8" Content="08" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Height="72" FontSize="24" Grid.Column="3" Grid.Row="1"/> <Button x:Name="B_9" Content="09" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Height="72" FontSize="24" Margin="0,71,0,0" Grid.Row="1" Grid.RowSpan="2"/> <Button x:Name="B_10" Content="10" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Height="72" FontSize="24" Grid.Column="1" Grid.Row="1" Margin="0,71,0,0" Grid.RowSpan="2"/> <Button x:Name="B_11" Content="11" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Height="72" FontSize="24" Grid.Column="2" Grid.Row="1" Margin="0,71,0,0" Grid.RowSpan="2"/> <Button x:Name="B_12" Content="12" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Height="72" FontSize="24" Grid.Column="3" Grid.Row="1" Margin="0,71,0,0" Grid.RowSpan="2"/> <Button x:Name="B_13" Content="13" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Height="72" FontSize="24" Margin="0,71,0,0" Grid.Row="2" Grid.RowSpan="2"/> <Button x:Name="B_14" Content="14" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Height="72" FontSize="24" Grid.Column="1" Grid.Row="2" Margin="0,71,0,0" Grid.RowSpan="2"/> <Button x:Name="B_15" Content="15" HorizontalAlignment="Center" VerticalAlignment="Center" Width="75" Height="72" FontSize="24" Grid.Column="2" Grid.Row="2" Margin="0,71,0,0" Grid.RowSpan="2"/> <Button x:Name="B_0" Content="00" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Height="72" FontSize="24" Grid.Column="3" Grid.Row="2" Margin="0,71,0,0" Grid.RowSpan="2"/> <Button x:Name="B_Jumble" Grid.ColumnSpan="2" Content="Jumble Tiles" Grid.Column="1" HorizontalAlignment="Left" Height="23" Margin="0,81,0,-33" Grid.Row="3" VerticalAlignment="Top" Width="150"/> </Grid> </Window> '@ #endregion   #region Code Behind function Convert-XAMLtoWindow { param ( [Parameter(Mandatory=$true)] [string] $XAML )   Add-Type -AssemblyName PresentationFramework   $reader = [XML.XMLReader]::Create([IO.StringReader]$XAML) $result = [Windows.Markup.XAMLReader]::Load($reader) $reader.Close() $reader = [XML.XMLReader]::Create([IO.StringReader]$XAML) while ($reader.Read()) { $name=$reader.GetAttribute('Name') if (!$name) { $name=$reader.GetAttribute('x:Name') } if($name) {$result | Add-Member NoteProperty -Name $name -Value $result.FindName($name) -Force} } $reader.Close() $result } function Show-WPFWindow { param ( [Parameter(Mandatory=$true)] [Windows.Window] $Window )   $result = $null $null = $window.Dispatcher.InvokeAsync{ $result = $window.ShowDialog() Set-Variable -Name result -Value $result -Scope 1 }.Wait() $result } #endregion Code Behind   #region Convert XAML to Window $window = Convert-XAMLtoWindow -XAML $xaml   #endregion   #region Define Event Handlers function Test-Victory{ #Evaluate if all the labels are in the correct position $victory = $true foreach($num in 1..15){ if([int]$window."b_$num".Content -ne $num){$victory = $false;break} } return($victory) } function Test-Move($Number){ #Number is a string of the pressed button number. if($Script:Neighbours[$Number] -contains $script:blank){ return($true) } else { return($false) } } Function Move-Tile($Number,$Bypass){ if((!(Test-Victory)) -or $Bypass){ if(Test-Move $Number){ #Set the new window label $window."B_$script:blank".content = $window."B_$Number".content $window."B_$script:blank".background = $window."B_$Number".background $window."B_$Number".background = "#FFDDDDDD" #Set the new blank window label $window."B_$Number".content = '' #Enable the old blank tile $window."B_$script:blank".isenabled = $true #disable the new blank tile $window."B_$Number".isenabled = $false #set the new blank $script:blank = $Number } } } function Move-TileRandom{ $lastmove = "1" for($i=0;$i -lt 500;$i++){ $move = $Script:Neighbours[$script:blank] | Where-Object {$_ -ne $lastmove} | Get-Random $lastmove = $move Move-Tile $move $true } } function Set-TileColour($Tile){ #I was curious about setting tiles to a checkerboard pattern at this stage. It's probably far better to just define it in the xaml #Ignore the blank tile if($Tile -ne 0){ #check if the row of the tile is odd or even if((([math]::floor(($Tile - 1)/4)) % 2 -eq 0)){ #check if the tile is odd or even if($Tile % 2 -eq 0){ $window."B_$Tile".Background = "#FFFF7878" } else { $window."B_$Tile".Background = "#FF9696FF" } }else{ if($Tile % 2 -eq 0){ $window."B_$Tile".Background = "#FF9696FF" } else { $window."B_$Tile".Background = "#FFFF7878" } } } else { $window.B_0.Background = "#FFDDDDDD" } } $window.B_1.add_Click{ $n = "1" move-tile $n } $window.B_2.add_Click{ $n = "2" move-tile $n } $window.B_3.add_Click{ $n = "3" move-tile $n } $window.B_4.add_Click{ $n = "4" move-tile $n } $window.B_5.add_Click{ $n = "5" move-tile $n } $window.B_6.add_Click{ $n = "6" move-tile $n } $window.B_7.add_Click{ $n = "7" move-tile $n } $window.B_8.add_Click{ $n = "8" move-tile $n } $window.B_9.add_Click{ $n = "9" move-tile $n } $window.B_10.add_Click{ $n = "10" move-tile $n } $window.B_11.add_Click{ $n = "11" move-tile $n } $window.B_12.add_Click{ $n = "12" move-tile $n } $window.B_13.add_Click{ $n = "13" move-tile $n } $window.B_14.add_Click{ $n = "14" move-tile $n } $window.B_15.add_Click{ $n = "15" move-tile $n } $window.B_0.add_Click{ $n = "0" move-tile $n }   $window.B_Jumble.add_Click{ Move-TileRandom } #endregion Event Handlers (([math]::floor(("9" - 1)/4)) % 2 -eq 0) #region Manipulate Window Content #initial processing of tiles $array = 0..15 | ForEach-Object {"{0:00}" -f $_} 0..15 | ForEach-Object {if($array[$_] -ne '00'){$window."B_$_".content = $array[$_]} else {$window."B_$_".content = '';$script:blank = "$_";$window."B_$_".isenabled = $false};Set-TileColour $_} #Shove them around a bit Move-TileRandom #endregion # Show Window $result = Show-WPFWindow -Window $window  
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 adjacent tiles (in that direction only) with matching numbers combine into one bearing the sum of those numbers.   A move is valid when at least one tile can be moved,   if only by combination.   A new tile with the value of   2   is spawned at the end of each turn at a randomly chosen empty square   (if there is one).   Adding a new tile on a blank space.   Most of the time,   a new   2   is to be added,   and occasionally   (10% of the time),   a   4.   To win,   the player must create a tile with the number   2048.   The player loses if no valid moves are possible. The name comes from the popular open-source implementation of this game mechanic, 2048. Requirements   "Non-greedy" movement.     The tiles that were created by combining other tiles should not be combined again during the same turn (move).     That is to say,   that moving the tile row of: [2][2][2][2] to the right should result in: ......[4][4] and not: .........[8]   "Move direction priority".     If more than one variant of combining is possible,   move direction shall indicate which combination will take effect.   For example, moving the tile row of: ...[2][2][2] to the right should result in: ......[2][4] and not: ......[4][2]   Check for valid moves.   The player shouldn't be able to skip their turn by trying a move that doesn't change the board.   Check for a  win condition.   Check for a lose condition.
#Red
Red
Red [Needs: 'View]   random/seed now board: random [2 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0]   ; ----------- move engine ----------- tasse: function [b] [ forall b [while [b/1 = 0] [remove b]] head append/dup b 0 4 - length? b ] somme: function [b] [ tasse b repeat n 3 [ m: n + 1 if all [b/:n <> 0 b/:n = b/:m] [ poke b n b/:n * 2 poke b m 0 ] ] tasse b ] reshape: function [b d][ res: copy [] switch d [ up [repeat n 4 [extract/index/into b 4 n res] res] down [repeat n 4 [extract/index/into b 4 n res] reverse res] left [res: copy b] right [res: reverse copy b] ] ] mov: function [b d][ b1: reshape b d moved: copy [] foreach [x y z t] b1 [append moved somme reduce [x y z t]] reshape moved d ]   ; --------- GUI --------- colors: [0 gray 2 snow 4 linen 8 brick 16 brown 32 sienna 64 water 128 teal 256 olive 512 khaki 1024 tanned 2028 wheat] tsize: 110x110 padsize: 4x4 padlen: 114 mainsize: tsize * 4 + (padsize * 5) tfont: make font! [size: 30 color: black style: 'bold]   display: does [ foreach face lay/pane [ n: face/data face/text: either board/:n = 0 [""] [form board/:n] face/color: reduce select colors board/:n ] ] lay: layout [ size mainsize title "2048 game" backdrop white on-key [ if find [up down left right] d: event/key [ if board <> newboard: mov board d [ board: newboard if find board 2048 [alert "You win!"] until [ pos: random 16 0 = board/:pos ] poke board pos either 1 = random 10 [4] [2] display conds: reduce [not find board 0] foreach d [up down left right] [ append conds board = mov board d ] if all conds [alert "You lose!"] ] ] ] space padsize ] repeat n length? board [append lay/pane make face! [ type: 'base offset: padsize + padlen * as-pair (n - 1 % 4) (n - 1 / 4) size: tsize color: reduce select colors board/:n data: n font: tfont ]] display view lay  
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 down, pass it around 97 bottles of beer on the wall ... and so on, until reaching   0     (zero). Grammatical support for   1 bottle of beer   is optional. As with any puzzle, try to do it in as creative/concise/comical a way as possible (simple, obvious solutions allowed, too). Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet See also   http://99-bottles-of-beer.net/   Category:99_Bottles_of_Beer   Category:Programming language families   Wikipedia 99 bottles of beer
#CoffeeScript
CoffeeScript
  bottlesOfBeer = (n) -> "#{n} bottle#{if n is 1 then '' else 's'} of beer"   console.log """ #{bottlesOfBeer n} on the wall #{bottlesOfBeer n} Take one down, pass it around #{bottlesOfBeer n - 1} on the wall \n""" for n in [99..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. The program should check then evaluate the expression. The goal is for the player to enter an expression that (numerically) evaluates to 24. Only the following operators/functions are allowed: multiplication, division, addition, subtraction Division should use floating point or rational arithmetic, etc, to preserve remainders. Brackets are allowed, if using an infix expression evaluator. Forming multiple digit numbers from the supplied digits is disallowed. (So an answer of 12+12 when given 1, 2, 2, and 1 is wrong). The order of the digits when given does not have to be preserved. Notes The type of expression evaluator used is not mandated. An RPN evaluator is equally acceptable for example. The task is not for the program to generate the expression, or test whether an expression is even possible. Related tasks 24 game/Solve Reference The 24 Game on h2g2.
#Phix
Phix
-- Note this uses simple/strict left association, so for example: -- 1+2*1*8 is ((1+2)*1)*8 not 1+((2*1)*8) [or 1+(2*(1*8))], and -- 7-(2*2)*8 is (7-(2*2))*8 not 7-((2*2)*8) -- Does not allow unary minus on the first digit. -- Uses solve24() from the next task, when it can. -- (you may want to comment out the last 2 lines/uncomment the if 0, in that file) -- --include 24_game_solve.exw --with trace forward function eval(string equation, sequence unused, integer idx=1) -- (the above definition is entirely optional, but good coding style) constant errorcodes = {"digit expected", -- 1 "')' expected", -- 2 "digit already used", -- 3 "digit not offered", -- 4 "operand expected"} -- 5 function card(integer idx) -- (for error handling) if idx=1 then return "1st" end if if idx=2 then return "2nd" end if -- (assumes expression is less than 21 characters) return sprintf("%dth",idx) end function function errorchar(sequence equation, integer idx) if idx>length(equation) then return "" end if return sprintf("(%s)",equation[idx]) end function sequence rset = repeat(0,4) procedure new_rset() for i=1 to length(rset) do rset[i] = rand(9) end for end procedure function get_operand(string equation, integer idx, sequence unused) integer error = 1 -- "digit expected" atom res if idx<=length(equation) then integer ch = equation[idx] if ch='(' then {error,res,unused,idx} = eval(equation,unused,idx+1) if error=0 and idx<=length(equation) then ch = equation[idx] if ch=')' then return {0,res,unused,idx+1} end if end if if error=0 then error = 2 -- "')' expected" end if elsif ch>='0' and ch<='9' then res = ch-'0' integer k = find(res,unused) if k!=0 then unused[k..k] = {} return {0,res,unused,idx+1} end if if find(res,rset) then error = 3 -- "digit already used" else error = 4 -- "digit not offered" end if end if end if return {error,0,unused,idx} end function function get_operator(string equation, integer idx) integer error = 5 -- "operand expected" if idx<=length(equation) then integer ch = equation[idx] if find(ch,"+-/*") then return {0,ch,idx+1} end if end if return {error,0,idx} end function function eval(string equation, sequence unused, integer idx=1) atom lhs, rhs integer ch, error {error,lhs,unused,idx} = get_operand(equation,idx,unused) if error=0 then while 1 do {error,ch,idx} = get_operator(equation,idx) if error!=0 then exit end if {error,rhs,unused,idx} = get_operand(equation,idx,unused) if error!=0 then exit end if if ch='+' then lhs += rhs elsif ch='-' then lhs -= rhs elsif ch='/' then lhs /= rhs elsif ch='*' then lhs *= rhs else ?9/0 -- (should not happen) end if if idx>length(equation) then return {0,lhs,unused,idx} end if ch = equation[idx] if ch=')' then return {0,lhs,unused,idx} end if end while end if return {error,0,unused,idx} end function function strip(string equation) for i=length(equation) to 1 by -1 do if find(equation[i]," \t\r\n") then equation[i..i] = "" end if end for return equation end function function strip0(atom a) -- (for error handling) string res = sprintf("%f",a) for i=length(res) to 2 by -1 do integer ch = res[i] if ch='.' then return res[1..i-1] end if if ch!='0' then return res[1..i] end if end for return res end function procedure play() sequence unused string equation integer error,idx atom res new_rset() printf(1,"Enter an expression which evaluates to exactly 24\n"& "Use all of, and only, the digits %d, %d, %d, and %d\n"& "You may only use the operators + - * /\n"& "Parentheses and spaces are allowed\n",rset) while 1 do equation = strip(gets(0)) if upper(equation)="Q" then exit end if if equation="?" then puts(1,"\n") integer r_solve24 = routine_id("solve24") -- see below if r_solve24=-1 then -- (someone copied just this code out?) puts(1,"no solve24 routine\n") else call_proc(r_solve24,{rset}) end if else {error,res,unused,idx} = eval(equation, rset) if error!=0 then printf(1,"  %s on the %s character%s\n",{errorcodes[error],card(idx),errorchar(equation,idx)}) elsif idx<=length(equation) then printf(1,"\neval() returned only having processed %d of %d characters\n",{idx,length(equation)}) elsif length(unused) then printf(1," not all the digits were used\n",error) elsif res!=24 then printf(1,"\nresult is %s, not 24\n",{strip0(res)}) else puts(1," correct! Press any key to quit\n") {} = wait_key() exit end if end if puts(1,"enter Q to give up and quit\n") end while end procedure play()
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 ≤ A , B ≤ + 1000 ) {\displaystyle (-1000\leq A,B\leq +1000)} Output data The required output is one integer:   the sum of A and B. Example input   output   2 2 4 3 2 5
#FunL
FunL
println( sum(map(int, readLine().split(' +'))) )
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 sides of the blocks. The sample collection of 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) Task Write a function that takes a string (word) and determines whether the word can be spelled with the given collection of blocks. The rules are simple:   Once a letter on a block is used that block cannot be used again   The function should be case-insensitive   Show the output on this page for the following 7 words in the following example Example >>> can_make_word("A") True >>> can_make_word("BARK") True >>> can_make_word("BOOK") False >>> can_make_word("TREAT") True >>> can_make_word("COMMON") False >>> can_make_word("SQUAD") True >>> can_make_word("CONFUSE") True Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Prolog
Prolog
abc_problem :- maplist(abc_problem, ['', 'A', bark, bOOk, treAT, 'COmmon', sQuaD, 'CONFUSE']).     abc_problem(Word) :- L = [[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]],   ( abc_problem(L, Word) -> format('~w OK~n', [Word]) ; format('~w KO~n', [Word])).   abc_problem(L, Word) :- atom_chars(Word, C_Words), maplist(downcase_atom, C_Words, D_Words), can_makeword(L, D_Words).   can_makeword(_L, []).   can_makeword(L, [H | T]) :- ( select([H, _], L, L1); select([_, H], L, L1)), can_makeword(L1, 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 decide some strategy before any enter the room. Prisoners enter the room one by one, can open a drawer, inspect the card number in the drawer, then close the drawer. A prisoner can open no more than 50 drawers. A prisoner tries to find his own number. A prisoner finding his own number is then held apart from the others. If all 100 prisoners find their own numbers then they will all be pardoned. If any don't then all sentences stand. The task Simulate several thousand instances of the game where the prisoners randomly open drawers Simulate several thousand instances of the game where the prisoners use the optimal strategy mentioned in the Wikipedia article, of: First opening the drawer whose outside number is his prisoner number. If the card within has his number then he succeeds otherwise he opens the drawer with the same number as that of the revealed card. (until he opens his maximum). Show and compare the computed probabilities of success for the two strategies, here, on this page. References The unbelievable solution to the 100 prisoner puzzle standupmaths (Video). wp:100 prisoners problem 100 Prisoners Escape Puzzle DataGenetics. Random permutation statistics#One hundred prisoners on Wikipedia.
#REXX
REXX
/*REXX program to simulate the problem of 100 prisoners: random, and optimal strategy.*/ parse arg men trials seed . /*obtain optional arguments from the CL*/ if men=='' | men=="," then men= 100 /*number of prisoners for this run.*/ if trials=='' | trials=="," then trials= 100000 /* " " simulations " " " */ if datatype(seed, 'W') then call random ,,seed /*seed for the random number generator.*/ try= men % 2; swaps= men * 3 /*number tries for searching for a card*/ $.1= ' a simple '; $.2= "an optimal" /*literals used for the SAY instruction*/ say center(' running' commas(trials) "trials with" commas(men) 'prisoners ', 70, "═") say do strategy=1 for 2; pardons= 0 /*perform the two types of strategies. */   do trials; call gCards /*do trials for a strategy; gen cards.*/ do p=1 for men until failure /*have each prisoner go through process*/ if strategy==1 then failure= simple() /*Is 1st strategy? Use simple strategy*/ else failure= picker() /* " 2nd " " optimal " */ end /*p*/ /*FAILURE ≡ 1? Then a prisoner failed.*/ if #==men then pardons= pardons + 1 /*was there a pardon of all prisoners? */ end /*trials*/ /*if 1 prisoner fails, then they all do*/   pc= format( pardons/trials*100, , 3); _= left('', pc<10) say right('Using', 9) $.strategy "strategy yields pardons " _||pc"% of the time." end /*strategy*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ commas: parse arg _; do c=length(_)-3 to 1 by -3; _= insert(',', _, c); end; return _ /*──────────────────────────────────────────────────────────────────────────────────────*/ gCards: #= 0; do j=1 for men; @.j= j /*define seq. of cards*/ end /*j*/ /*same as seq. of men.*/ do swaps; a= random(1, men) /*get 1st rand number.*/ do until b\==a; b= random(1, men) /* " 2nd " " */ end /*until*/ /* [↑] ensure A ¬== B */ parse value @.a @.b with @.b @.a /*swap 2 random cards.*/ end /*swaps*/; return /*──────────────────────────────────────────────────────────────────────────────────────*/ simple: !.= 0; do try; do until !.?==0; ?= random(1, men) /*get random card ··· */ end /*until*/ /*··· not used before.*/ if @.?==p then do; #= #+1; return 0; end /*found his own card? */  !.?= 1 /*flag as being used. */ end /*try*/; return 1 /*didn't find his card*/ /*──────────────────────────────────────────────────────────────────────────────────────*/ picker: ?= p; do try; if @.?==p then do; #= #+1; return 0 /*Found his own card? */ end /* [↑] indicate success for prisoner. */  ?= @.? /*choose next drawer from current card.*/ end /*try*/; return 1 /*choose half of the number of drawers.*/
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
#Processing
Processing
  int number_of_grid_cells = 16; // Set the number of cells of the board here 9, 16, 25 etc color piece_color = color(255, 175, 0); color background_color = color(235, 231, 178); color piece_shadow_dark = color(206, 141, 0); color piece_shadow_light = color(255, 214, 126); int z, t, p, piece_number, row_length, piece_side_length;   PuzzlePiece[] piece = new PuzzlePiece[number_of_grid_cells]; // Number of puzzle pieces objects array   void setup() { size(400, 400); // Window size width and height must be egual background(200, 50, 0); row_length = int(sqrt(number_of_grid_cells)); piece_side_length = width/row_length; textSize(piece_side_length/2.7); textAlign(CENTER);   PVector[] xy_values = new PVector[number_of_grid_cells]; // Setting the x and y values for each cell on grid for (int i = 0; i < number_of_grid_cells; i += row_length) { // Values are the top left pixel of the cell for (int j = 0; j < row_length; j++) { xy_values[z] = new PVector(); xy_values[z].x = j*piece_side_length; xy_values[z].y = t*piece_side_length; z++; } t++; }   int[] place = new int[number_of_grid_cells]; // This array is to help placing the pieces randomly and store values in piece objects array for (int i = 0; i < number_of_grid_cells; i++) place[i] = 0; piece_number = 0;   while (piece_number < number_of_grid_cells) { // Placing pieces randomly in grid p = int(random(0, number_of_grid_cells)); if (place[p] == 0) { // Once placed will be set to 1 to avoid designing again at this location piece[piece_number] = new PuzzlePiece(piece_number, xy_values[p].x, xy_values[p].y); // Creating the piece objects array place[p] = 1; piece[piece_number].design(); // Design newly create piece object piece_number++; } } }   void draw() { for (int i = 0; i < number_of_grid_cells; i++) { // Search all piece object indexes and verify which one is mouse pressed in this loop if (mousePressed == true && mouseX >= piece[i].xPosition() && mouseX <= piece[i].xPosition()+piece_side_length && mouseY >= piece[i].yPosition() && mouseY <= piece[i].yPosition()+piece_side_length && piece[i].pieceNumber() != 15) { if (pieceMove(piece[number_of_grid_cells-1].xPosition(), piece[number_of_grid_cells-1].yPosition(), piece[i].xPosition(), piece[i].yPosition())) { float temp_x = piece[number_of_grid_cells-1].xPosition(); // Remember x and y value of final piece index (white piece) float temp_y = piece[number_of_grid_cells-1].yPosition(); piece[number_of_grid_cells-1].storePos(piece[i].xPosition(), piece[i].yPosition()); // Store clicked x and y value in final index of piece array piece[i].storePos(temp_x, temp_y); // Store temp x and y value (the last/previous final index values) in current clicked piece index piece[number_of_grid_cells-1].design(); // draw the final index piece index (only final piece index is painted white) piece[i].design(); // Draw a numbered piece of current index } } } }   boolean pieceMove(float final_index_piece_x, float final_index_piece_y, float current_index_x, float current_index_y) { // If both x values from clicked and white piece have same value meaning in same horizontal column // AND current clicked y value is equal to white piece y value - piece side lenght OR current clicked y value + piece side lenght is egual to white piece y if (current_index_x == final_index_piece_x && (current_index_y == final_index_piece_y-piece_side_length || (current_index_y == final_index_piece_y+piece_side_length))) return true; // If both y values from clicked and white piece have same value meaning in same vertical column // AND current clicked x value is equal to white piece x value - piece side lenght OR current clicked x value + piece side lenght is egual to white piece x else if (current_index_y == final_index_piece_y && (current_index_x == final_index_piece_x-piece_side_length || (current_index_x == final_index_piece_x+piece_side_length))) return true; else return false; }   class PuzzlePiece { int piece_number; float x_pos, y_pos;   PuzzlePiece(int _piece_nr, float _xp, float _yp) { piece_number = _piece_nr; x_pos = _xp; y_pos = _yp; }   void storePos(float _xp, float _yp) { x_pos = _xp; y_pos = _yp; }   int pieceNumber() { return piece_number; }   float xPosition() { return x_pos; }   float yPosition() { return y_pos; }   void design() { noStroke(); fill(piece_color); if (piece_number == number_of_grid_cells-1) fill(background_color); rect(x_pos+1, y_pos+1, piece_side_length-1, piece_side_length-1); if (piece_number != number_of_grid_cells-1) { fill(0); // Black text shadow text(piece_number+1, x_pos+piece_side_length/2+1, y_pos+piece_side_length/2+textAscent()/2); fill(255); text(piece_number+1, x_pos+piece_side_length/2, y_pos+piece_side_length/2+textAscent()/2); stroke(piece_shadow_dark); line(x_pos+piece_side_length-1, y_pos+1, x_pos+piece_side_length-1, y_pos+piece_side_length-1); // Right side shadow line(x_pos+2, y_pos+piece_side_length, x_pos+piece_side_length-1, y_pos+piece_side_length); // Bottom side shadow stroke(piece_shadow_light); line(x_pos+2, y_pos-1, x_pos+2, y_pos+piece_side_length); // Left bright line(x_pos+2, y_pos+1, x_pos+piece_side_length-1, y_pos+1); // Upper bright } } }
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 adjacent tiles (in that direction only) with matching numbers combine into one bearing the sum of those numbers.   A move is valid when at least one tile can be moved,   if only by combination.   A new tile with the value of   2   is spawned at the end of each turn at a randomly chosen empty square   (if there is one).   Adding a new tile on a blank space.   Most of the time,   a new   2   is to be added,   and occasionally   (10% of the time),   a   4.   To win,   the player must create a tile with the number   2048.   The player loses if no valid moves are possible. The name comes from the popular open-source implementation of this game mechanic, 2048. Requirements   "Non-greedy" movement.     The tiles that were created by combining other tiles should not be combined again during the same turn (move).     That is to say,   that moving the tile row of: [2][2][2][2] to the right should result in: ......[4][4] and not: .........[8]   "Move direction priority".     If more than one variant of combining is possible,   move direction shall indicate which combination will take effect.   For example, moving the tile row of: ...[2][2][2] to the right should result in: ......[2][4] and not: ......[4][2]   Check for valid moves.   The player shouldn't be able to skip their turn by trying a move that doesn't change the board.   Check for a  win condition.   Check for a lose condition.
#REXX
REXX
/*REXX program lets a user play the 2048 game on an NxN grid (default is 4x4 grid).*/ parse arg N win seed . /*obtain optional arguments from the CL*/ if N=='' | N=="," then N= 4 /*Not specified? Then use the default.*/ if win=='' | win=="," then win= 2**11 /* " " " " " " */ if datatype(seed, 'W') then call random ,,seed /*Specified? Then use seed for RANDOM.*/ L= length(win) + 2 /*L: used for displaying the grid #'s.*/ eye=copies("─", 8); pad=left('', length(eye)+2) /*eye catchers; and perusable perusing.*/ b= ' ' /*comfortable readable name for a blank*/ @cls= 'CLS' /*hardcoded command to clear the screen*/ prompt= eye "Please enter a direction (Up, Down, Right, Left) ───or─── Quit:" move= 1; moves= 0; score= 0; ok= 1 /*simulation that a move was performed.*/ @.= b /*define all grid elements to a blank. */ do until any(win); if ok then call put; ok= 1; say; call showGrid say; say prompt; parse pull a x . 1 d 2 1 way xx /*show prompt; obtain answer.*/ if datatype(a, 'U') then @cls /*if uppercase, then clear the screen. */ if a=='' then do; ok= 0 /*the user entered blank(s) or nothing.*/ say copies(eye, 5) 'moves:' moves eye "score:" score iterate /* [↑] display # of moves & the score.*/ end upper d a x /*uppercase contents of three variables*/ if x\=='' then call err "too many arguments entered: " xx if abbrev('QUIT',a,1) then do; say; say eye "quitting the game".; exit 1; end good=abbrev('UP',a,1) | abbrev("DOWN",a,1) | abbrev('RIGHT',a,1) | abbrev("LEFT",a,1) if \good then call err "invalid direction: " way if \ok then iterate; moves= moves + 1; call mov end /*until*/ say say translate(eye "Congrats!! You've won the" win 'game!' eye,"═",'─') "score:" score exit 0 /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ @: procedure expose @.; parse arg row,col; return @.row.col any: arg ?; do r=1 for N; do c=1 for N; if @.r.c==? then return 1; end; end; return 0 err: say; say eye '***error*** ' arg(1); say; ok=0; return o_c: $=; do k=1 for N; $=$ word(@.k.c .,1); end;  !=space(translate($,,.))==''; return $ o_r: $=; do k=1 for N; $=$ word(@.r.k .,1); end;  !=space(translate($,,.))==''; return $ put: if \any(b) then call err ,"game over, no more moves."; if move then call two; return row: if r==0 | r>N then return copies('═', L); return center(@.r.c, L) ten: if random(9)==4 then return 4; return 2 /*10% of the time, use 4 instead of 2.*/ two: do until @.p.q==b; p= random(1,N); q= random(1,N); end; @.p.q= ten(); return /*──────────────────────────────────────────────────────────────────────────────────────*/ showGrid: do r=0 for N+2; _= '║'; __= "╠" do c=1 for N; _= _ || row()'║'; __= __ || copies("═", L)'╬' end /*c*/ if r==0 then _= '╔'translate( substr(_, 2, length(_) - 2), "╦", '║')"╗" if r >N then _= '╚'translate( substr(_, 2, length(_) - 2), "╩", '║')"╝" say pad _ if r<N & r>0 then say pad substr(__, 1, length(__) - 1)"╣" end /*r*/; return /*──────────────────────────────────────────────────────────────────────────────────────*/ mov: move= 0; if d=='R' then call moveLR N, 1, -1 /*move (slide) numbers ► */ if d=='L' then call moveLR 1, N, +1 /* " " " ◄ */ if d=='U' then call moveUD 1, N, +1 /* " " " ↑ */ if d=='D' then call moveUD N, 1, -1 /* " " " ↓ */ if \move then call err 'moving ' way " doesn't change anything."; return /*──────────────────────────────────────────────────────────────────────────────────────*/ moveLR: parse arg start, sTo, # /*slide ◄ or ► */ do r=1 for N; old= o_r(); if ! then iterate /*is this row blank? */ do N-1; call packLR /*pack ◄ or ► */ end /*N-1*/ /* [↓] get new tiles.*/ new= o_r(); move= move | (old\==new) /*indicate tiles moved*/ do c=start for N-1 by # while @.r.c\==b /*slide ◄ or ► */ if @.r.c\==@(r,c+#) then iterate /*not a duplicate ? */ @.r.c= @.r.c * 2; score= score + @.r.c /*double; bump score */ c= c + #  ; @.r.c= b; move= 1 /*bump C; blank dup 2.*/ end /*c*/ /* [↑] indicate move.*/ call packLR /*pack ◄ or ► */ end /*r*/; return /*──────────────────────────────────────────────────────────────────────────────────────*/ moveUD: parse arg start, Sto, # /*slide ↑ or ↓ */ do c=1 for N; old= o_c(); if ! then iterate /*is this col blank? */ do N-1; call packUD /*pack up or down. */ end /*N-1*/ /* [↓] get new tiles.*/ new= o_c(); move= move | (old\==new) /*indicate tiles moved*/ do r=start for N-1 by # while @.r.c\==b /*slide ↑ or ↓ */ if @.r.c\==@(r+#,c) then iterate /*not a duplicate ? */ @.r.c= @.r.c * 2; score= score + @.r.c /*double; bump score */ r= r + #  ; @.r.c= b; move= 1 /*bump R; blank dup 2.*/ end /*r*/ /* [↑] indicate move.*/ call packUD /*pack ↑ or ↓ */ end /*c*/; return /*──────────────────────────────────────────────────────────────────────────────────────*/ packLR: do c=start for N-1 by #; if @.r.c\==b then iterate /*Not a blank? Skip. */ do s=c to sTo by #; @.r.s= @(r, s + #) /*slide ◄ or ► */ end /*s*/; @.r.sTo= b /*handle the last one.*/ end /*c*/; return /*──────────────────────────────────────────────────────────────────────────────────────*/ packUD: do r=start for N-1 by #; if @.r.c\==b then iterate /*Not a blank? Skip. */ do s=r to sTo by #; @.s.c= @(s + #, c) /*slide ↑ or ↓ */ end /*s*/; @.sTo.c= b /*handle the last one.*/ end /*r*/; return
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 down, pass it around 97 bottles of beer on the wall ... and so on, until reaching   0     (zero). Grammatical support for   1 bottle of beer   is optional. As with any puzzle, try to do it in as creative/concise/comical a way as possible (simple, obvious solutions allowed, too). Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet See also   http://99-bottles-of-beer.net/   Category:99_Bottles_of_Beer   Category:Programming language families   Wikipedia 99 bottles of beer
#ColdFusion
ColdFusion
<cfoutput> <cfloop index="x" from="99" to="0" step="-1"> <cfset plur = iif(x is 1,"",DE("s"))> #x# bottle#plur# of beer on the wall<br> #x# bottle#plur# of beer<br> Take one down, pass it around<br> #iif(x is 1,DE("No more"),"x-1")# bottle#iif(x is 2,"",DE("s"))# of beer on the wall<br><br> </cfloop> </cfoutput>
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. The program should check then evaluate the expression. The goal is for the player to enter an expression that (numerically) evaluates to 24. Only the following operators/functions are allowed: multiplication, division, addition, subtraction Division should use floating point or rational arithmetic, etc, to preserve remainders. Brackets are allowed, if using an infix expression evaluator. Forming multiple digit numbers from the supplied digits is disallowed. (So an answer of 12+12 when given 1, 2, 2, and 1 is wrong). The order of the digits when given does not have to be preserved. Notes The type of expression evaluator used is not mandated. An RPN evaluator is equally acceptable for example. The task is not for the program to generate the expression, or test whether an expression is even possible. Related tasks 24 game/Solve Reference The 24 Game on h2g2.
#PHP
PHP
#!/usr/bin/env php 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 four digits. Otherwise you are repeatedly asked for an expression until it evaluates to 24   Note: you cannot form multiple digit numbers from the supplied digits, so an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.   <?php   while (true) { $numbers = make_numbers();   for ($iteration_num = 1; ; $iteration_num++) { echo "Expresion $iteration_num: ";   $entry = rtrim(fgets(STDIN));   if ($entry === '!') break; if ($entry === 'q') exit;   $result = play($numbers, $entry);   if ($result === null) { echo "That's not valid\n"; continue; } elseif ($result != 24) { echo "Sorry, that's $result\n"; continue; } else { echo "That's right! 24!!\n"; exit; } } }   function make_numbers() { $numbers = array();   echo "Your four digits: ";   for ($i = 0; $i < 4; $i++) { $number = rand(1, 9); // The check is needed to avoid E_NOTICE from PHP if (!isset($numbers[$number])) { $numbers[$number] = 0; } $numbers[$number]++; print "$number "; }   print "\n";   return $numbers; }   function play($numbers, $expression) { $operator = true; for ($i = 0, $length = strlen($expression); $i < $length; $i++) { $character = $expression[$i];   if (in_array($character, array('(', ')', ' ', "\t"))) continue;   $operator = !$operator;   if (!$operator) { if (!empty($numbers[$character])) { $numbers[$character]--; continue; } return; } elseif (!in_array($character, array('+', '-', '*', '/'))) { return; } }   foreach ($numbers as $remaining) { if ($remaining > 0) { return; } }   return eval("return $expression;"); } ?>
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 ≤ A , B ≤ + 1000 ) {\displaystyle (-1000\leq A,B\leq +1000)} Output data The required output is one integer:   the sum of A and B. Example input   output   2 2 4 3 2 5
#Furor
Furor
  cin sto mystring #s dec mystring @mystring sprintnl #g ."The length of the input is: " @mystring~ print ." characters.\n" mylist @mystring 32 strtolist ."Quantity of the items: " mylist~ printnl mylist~ mem sto nums mylist 10 ![ ."Item #" [:] #g print ." = " [|] sprintnl @nums [:] [|] #s (#g) [^] ] ."Sum = " 0 #g mylist~ {| @nums {} [] + |} printnl @nums free @mystring free @mylist free end { „mystring” } { „mylist” } { „nums” }  
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 sides of the blocks. The sample collection of 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) Task Write a function that takes a string (word) and determines whether the word can be spelled with the given collection of blocks. The rules are simple:   Once a letter on a block is used that block cannot be used again   The function should be case-insensitive   Show the output on this page for the following 7 words in the following example Example >>> can_make_word("A") True >>> can_make_word("BARK") True >>> can_make_word("BOOK") False >>> can_make_word("TREAT") True >>> can_make_word("COMMON") False >>> can_make_word("SQUAD") True >>> can_make_word("CONFUSE") True Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#PureBasic
PureBasic
EnableExplicit #LETTERS = "BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM "   Procedure.s can_make_word(word.s) Define letters.s = #LETTERS, buffer.s Define index1.i, index2.i Define match.b For index1=1 To Len(word) index2=1 : match=#False Repeat buffer=StringField(letters,index2,Space(1)) If FindString(buffer,Mid(word,index1,1),1,#PB_String_NoCase) letters=RemoveString(letters,buffer+Chr(32),0,1,1) match=#True Break EndIf index2+1 Until index2>CountString(letters,Space(1)) If Not match : ProcedureReturn word+#TAB$+"FALSE" : EndIf Next ProcedureReturn word+#TAB$+"TRUE" EndProcedure   OpenConsole() PrintN(can_make_word("a")) PrintN(can_make_word("BaRK")) PrintN(can_make_word("BOoK")) PrintN(can_make_word("TREAt")) PrintN(can_make_word("cOMMON")) PrintN(can_make_word("SqUAD")) PrintN(can_make_word("COnFUSE")) Input()
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 decide some strategy before any enter the room. Prisoners enter the room one by one, can open a drawer, inspect the card number in the drawer, then close the drawer. A prisoner can open no more than 50 drawers. A prisoner tries to find his own number. A prisoner finding his own number is then held apart from the others. If all 100 prisoners find their own numbers then they will all be pardoned. If any don't then all sentences stand. The task Simulate several thousand instances of the game where the prisoners randomly open drawers Simulate several thousand instances of the game where the prisoners use the optimal strategy mentioned in the Wikipedia article, of: First opening the drawer whose outside number is his prisoner number. If the card within has his number then he succeeds otherwise he opens the drawer with the same number as that of the revealed card. (until he opens his maximum). Show and compare the computed probabilities of success for the two strategies, here, on this page. References The unbelievable solution to the 100 prisoner puzzle standupmaths (Video). wp:100 prisoners problem 100 Prisoners Escape Puzzle DataGenetics. Random permutation statistics#One hundred prisoners on Wikipedia.
#Ruby
Ruby
prisoners = [*1..100] N = 10_000 generate_rooms = ->{ [nil]+[*1..100].shuffle }   res = N.times.count do rooms = generate_rooms[] prisoners.all? {|pr| rooms[1,100].sample(50).include?(pr)} end puts "Random strategy : %11.4f %%" % (res.fdiv(N) * 100)   res = N.times.count do rooms = generate_rooms[] prisoners.all? do |pr| cur_room = pr 50.times.any? do found = (rooms[cur_room] == pr) cur_room = rooms[cur_room] found end end end puts "Optimal strategy: %11.4f %%" % (res.fdiv(N) * 100)  
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
#PureBasic
PureBasic
  #difficulty=10 ;higher is harder #up="u" #down="d" #left="l" #right="r" OpenConsole("15 game"):EnableGraphicalConsole(1) Global Dim Game.i(3,3) Global hole.point   Procedure NewBoard() num.i=0 For j=0 To 3 For i=0 To 3 Game(i,j)=num num+1 Next i Next j EndProcedure Procedure.s displayBoard() For j=0 To 3 For i=0 To 3 ConsoleLocate(i,j) If Game(i,j)=0:Print(" "):Continue:EndIf Print(Hex(Game(i,j))) Next i Next j PrintN("") Print("Your Choice Up :"+#up+", Down :"+#down+", Left :"+#left+" Or Right :"+#right+" ") Repeat keypress$=Inkey() Until keypress$<>"" keypress$=LCase(keypress$) ProcedureReturn keypress$ EndProcedure Procedure UpdateBoard(key$) If key$=#up And hole\y<3 Swap game(hole\x,hole\y),game(hole\x,hole\y+1):hole\y+1 ElseIf key$=#down And hole\y Swap game(hole\x,hole\y),game(hole\x,hole\y-1):hole\y-1 ElseIf key$=#left And hole\x<3 Swap game(hole\x,hole\y),game(hole\x+1,hole\y):hole\x+1 ElseIf key$=#right And hole\x Swap game(hole\x,hole\y),game(hole\x-1,hole\y):hole\x-1 EndIf EndProcedure Procedure TestGameWin() For j=0 To 3 For i=0 To 3 num+1 If game(i,j)=num:win+1:EndIf Next i Next j If win=15:ProcedureReturn 1:EndIf EndProcedure Procedure ShuffleBoard(difficulty.i) Dim randomKey$(3) randomkey$(0)=#up:randomkey$(1)=#down:randomkey$(2)=#left:randomkey$(3)=#right For i=1 To difficulty UpdateBoard(randomKey$(Random(3))) Next i EndProcedure NewBoard() ShuffleBoard(#difficulty) Repeat choice$=displayBoard() UpdateBoard(choice$) Until TestGameWin() Print("Won !") CloseConsole()  
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 adjacent tiles (in that direction only) with matching numbers combine into one bearing the sum of those numbers.   A move is valid when at least one tile can be moved,   if only by combination.   A new tile with the value of   2   is spawned at the end of each turn at a randomly chosen empty square   (if there is one).   Adding a new tile on a blank space.   Most of the time,   a new   2   is to be added,   and occasionally   (10% of the time),   a   4.   To win,   the player must create a tile with the number   2048.   The player loses if no valid moves are possible. The name comes from the popular open-source implementation of this game mechanic, 2048. Requirements   "Non-greedy" movement.     The tiles that were created by combining other tiles should not be combined again during the same turn (move).     That is to say,   that moving the tile row of: [2][2][2][2] to the right should result in: ......[4][4] and not: .........[8]   "Move direction priority".     If more than one variant of combining is possible,   move direction shall indicate which combination will take effect.   For example, moving the tile row of: ...[2][2][2] to the right should result in: ......[2][4] and not: ......[4][2]   Check for valid moves.   The player shouldn't be able to skip their turn by trying a move that doesn't change the board.   Check for a  win condition.   Check for a lose condition.
#Ring
Ring
  # Project : 2048 Game   load "stdlib.ring" load "guilib.ring"   C_GAMETITLE = '2048 Game' C_WINDOWBACKGROUND = "background-color: gray;" if isMobile() C_LABELFONTSIZE = "font-size:120px;" C_BUTTONFONTSIZE = "font-size:160px;" else C_LABELFONTSIZE = "font-size:50px;" C_BUTTONFONTSIZE = "font-size:80px;" ok C_PLAYERSCORESTYLE = "color:white;background-color:rgb(50,50,50);border-radius:17px;" + C_LABELFONTSIZE C_NEWGAMESTYLE = 'color:white;background-color:rgb(50,50,50);border-radius:17px;' + C_LABELFONTSIZE C_EMPTYBUTTONSTYLE = 'border-radius:17px;background-color:silver;' + C_BUTTONFONTSIZE C_BUTTON2STYLE = 'border-radius:17px;color:black; background-color: yellow ;' + C_BUTTONFONTSIZE C_BUTTON4STYLE = 'border-radius:17px;color:black; background-color: violet ;' + C_BUTTONFONTSIZE C_BUTTON8STYLE = 'border-radius:17px;color:white; background-color: purple ;' + C_BUTTONFONTSIZE C_BUTTON16STYLE = 'border-radius:17px;color:white; background-color: blue ;' + C_BUTTONFONTSIZE C_BUTTON32STYLE = 'border-radius:17px;color:white; background-color: red ;' + C_BUTTONFONTSIZE C_BUTTON64STYLE = 'border-radius:17px;color:black; background-color: lightgray ;' + C_BUTTONFONTSIZE C_BUTTON128STYLE = 'border-radius:17px;color:black; background-color: white ;' + C_BUTTONFONTSIZE C_BUTTON256STYLE = 'border-radius:17px;color:white; background-color: black ;' + C_BUTTONFONTSIZE C_BUTTON512STYLE = 'border-radius:17px;color:white; background-color: Purple ;' + C_BUTTONFONTSIZE C_BUTTON1024STYLE = 'border-radius:17px;color:black; background-color: Yellow ;' + C_BUTTONFONTSIZE C_BUTTON2048STYLE = 'border-radius:17px;color:white; background-color: Green ;' + C_BUTTONFONTSIZE C_LAYOUTSPACING = 10 C_PLAYERSCORE = 'Player Score : '   size = 4 limit = 2 num = 0 flag = 0 x1 = 0 x2 = 0 y1 = 0 y2 = 0 nScore = 0 button = newlist(size,size) buttonsave = newlist(size,size) LayoutButtonRow = list(size+2) moveleft = [] moveright = [] moveup = [] movedown = [] myfilter2 = null myfilter3 = null winheight = 0 winwidth = 0   app = new qApp { StyleFusion() processevents() win = new qWidget() { setWindowTitle(C_GAMETITLE) setgeometry(100,100,600,700) setminimumwidth(300) setminimumheight(300) if not isMobile() grabkeyboard() ok setstylesheet(C_WINDOWBACKGROUND) move(490,100) for n = 1 to size for m = 1 to size button[n][m] = new MyButton(win) next next newgame = new qLabel(win) playerscore = new qLabel(win) myfilter3 = new qAllEvents(win) { setMouseButtonPressEvent("pPress()") setMouseButtonReleaseEvent("pRelease()")} installeventfilter(myfilter3) myfilter2 = new qAllEvents(win) { setkeypressevent("keypress()") } installeventfilter(myfilter2) winwidth = win.width() winheight = win.height() for n = 1 to size + 2 LayoutButtonRow[n] = new QHBoxLayout() { setSpacing(C_LAYOUTSPACING) } next for n = 1 to size for m = 1 to size button[n][m] { temp = text() } buttonsave[n][m] = temp button[n][m] = new MyButton(win) { setalignment(Qt_AlignHCenter | Qt_AlignVCenter) setstylesheet(C_EMPTYBUTTONSTYLE) show() } next next for n = 1 to size for m = 1 to size LayoutButtonRow[n].AddWidget(button[m][n]) win.show() temp = buttonsave[n][m] button[n][m].settext(temp) next LayoutButtonRow[n].setSpacing(C_LAYOUTSPACING) next playerscore { setGeometry(0,4*floor(winheight/6),winwidth,floor(winheight/6)) setalignment(Qt_AlignHCenter | Qt_AlignVCenter) settext(C_PLAYERSCORE + nScore) setStylesheet(C_PLAYERSCORESTYLE) show() } newgame { setGeometry(0,5*floor(winheight/6),winwidth,floor(winheight/6)) setalignment(Qt_AlignHCenter | Qt_AlignVCenter) setstylesheet(C_NEWGAMESTYLE) settext('New Game') myfilter4 = new qallevents(newgame) myfilter4.setMouseButtonPressEvent("pbegin()") installeventfilter(myfilter4) show() } LayoutButtonRow[size+1].AddWidget(playerscore) LayoutButtonRow[size+2].AddWidget(newgame) LayoutButtonMain = new QVBoxLayout() { setSpacing(C_LAYOUTSPACING) for n = 1 to size+2 AddLayout(LayoutButtonRow[n]) win.show() next } win.setLayout(LayoutButtonMain) win.show() pbegin() show() } exec() }   func pPress() x1 = myfilter3.getglobalx() y1 = myfilter3.getglobaly()   func pRelease() x2 = myfilter3.getglobalx() y2 = myfilter3.getglobaly() difx = x2 - x1 dify = y2 - y1 if fabs(difx) > fabs(dify) if difx < 0 pleft() else pRight() ok else if dify < 0 pUp() else pDown() ok ok   func keypress() nKey = myfilter2.getkeycode() switch nKey on 16777234 pleft() on 16777236 pright() on 16777235 pup() on 16777237 pdown() off   func pbegin() numbers = [['2','2'],['2','4']] randnew = newlist(2,2) for n = 1 to size for m = 1 to size button[n][m].setStylesheet(C_EMPTYBUTTONSTYLE) button[n][m].settext('') next next while true rn1 = random(size - 1) + 1 rm1 = random(size - 1) + 1 rn2 = random(size - 1) + 1 rm2 = random(size - 1) + 1 bool = (rn1 = rn2) and (rm1 = rm2) if not bool exit ok end rand = random(limit - 1) + 1 button[rn1][rm1].settext(numbers[rand][1]) button[rn2][rm2].settext(numbers[rand][2]) nScore = 0 playerscore.settext(C_PLAYERSCORE)   func pMoveInDirection cFunc num = gameover() if num = size*size flag = 1 msgBox('You lost!') pbegin() ok if flag = 0 call cFunc() sleep(0.5) newnum() ok   func pdown() pMoveInDirection(:pMoveDown)   func pup() pMoveInDirection(:pMoveUp)   func pleft() pMoveInDirection(:pMoveLeft)   func pright() pMoveInDirection(:pMoveRight)   func pmoveleft() for n = 1 to size moveleft = [] for m = 1 to size button[m][n] {temp = text()} if temp != '' add(moveleft,temp) ok next movetilesleft(n,moveleft) next   func pmoveright() for n = 1 to size moveright = [] for m = size to 1 step -1 button[m][n] {temp = text()} if temp != '' add(moveright,temp) ok next movetilesright(n,moveright) next return   func pmoveup() for n = 1 to size moveup = [] for m = 1 to size button[n][m] {temp = text()} if temp != '' add(moveup,temp) ok next movetilesup(n,moveup) next return   func pmovedown() for n = 1 to size movedown = [] for m = size to 1 step -1 button[n][m] {temp = text()} if temp != '' add(movedown,temp) ok next movetilesdown(n,movedown) next return   func movetilesleft(nr,moveleft) for p = 1 to len(moveleft) - 1 temp1 = moveleft[p] temp2 = moveleft[p+1] temp = string(number(temp1) + number(temp2)) if (temp1 = temp2) and (temp1 != '0') and (temp2 != '0') and (temp1 != '') and (temp2 != '') if temp != '0' and temp != '' nScore = nScore + temp playerscore.settext(C_PLAYERSCORE + nScore) flag = 1 moveleft[p] = temp del(moveleft,p+1) ok ok next for n = 1 to len(moveleft) button[n][nr].settext(moveleft[n]) next for n = len(moveleft) + 1 to size if n <= size button[n][nr].setStylesheet(C_EMPTYBUTTONSTYLE) button[n][nr].settext('') ok next return   func movetilesright(nr,moveright) flag = 0 for p = 2 to len(moveright) temp1 = moveright[p] temp2 = moveright[p-1] if (temp1 = temp2) and (temp1 != '0') and (temp2 != '0') and (temp1 != '') and (temp2 != '') temp = string(number(temp1) + number(temp2)) if temp != '0' and temp != '' nScore = nScore + temp playerscore.settext(C_PLAYERSCORE + nScore) flag = 1 moveright[p] = temp del(moveright,p-1) ok ok next for n = 1 to len(moveright) button[size-n+1][nr].settext(moveright[n]) next for n = 1 to size - len(moveright) if n <= size button[n][nr].setStylesheet(C_EMPTYBUTTONSTYLE) button[n][nr].settext('') ok next     func movetilesup(nr,moveup) flag = 0 for p = 1 to len(moveup) - 1 temp1 = moveup[p] temp2 = moveup[p+1] if (temp1 = temp2) and (temp1 != '0') and (temp2 != '0') and (temp1 != '') and (temp2 != '') temp = string(number(temp1) + number(temp2)) if temp != '0' and temp != '' nScore = nScore + temp playerscore.settext(C_PLAYERSCORE + nScore) flag = 1 moveup[p] = temp del(moveup,p+1) ok ok next for n = 1 to len(moveup) button[nr][n].settext(moveup[n]) next for n = len(moveup) + 1 to size if n <= size button[nr][n].setStylesheet(C_EMPTYBUTTONSTYLE) button[nr][n].settext('') ok next   func movetilesdown(nr,movedown) flag = 0 for p = 1 to len(movedown) - 1 temp1 = movedown[p] temp2 = movedown[p+1] if (temp1 = temp2) and (temp1 != '0') and (temp2 != '0') and (temp1 != '') and (temp2 != '') temp = string(number(temp1) + number(temp2)) if temp != '0' and temp != '' nScore = nScore + temp playerscore.settext(C_PLAYERSCORE + nScore) flag = 1 movedown[p] = temp del(movedown,p+1) ok ok next for n = 1 to len(movedown) button[nr][size-n+1].settext(movedown[n]) next for n = size - len(movedown) to 1 step -1 if n <= size button[nr][n].setStylesheet(C_EMPTYBUTTONSTYLE) app.processevents() button[nr][n].settext('') ok next   func newnum() while true rn = random(size - 1) + 1 rm = random(size - 1) + 1 if button[rn][rm].text() = '' button[rn][rm].settext('2') exit ok end return   func gameover() num = 0 flag = 0 for n = 1 to size for m = 1 to size if button[n][m].text() != '' num = num + 1 ok next next return num   func msgBox(text) { m = new qMessageBox(win) { setWindowTitle('2048 Game') setText(text) show() } }   func showarray(vect) see "[" svect = "" for n = 1 to len(vect) svect = svect + vect[n] + " " next svect = left(svect, len(svect) - 1) see svect see "]" + nl   class MyButton from qLabel func setText(cValue) Super.setText(cValue) switch cValue on '2' setStyleSheet(C_BUTTON2STYLE) on '4' setStylesheet(C_BUTTON4STYLE) on '8' setStylesheet(C_BUTTON8STYLE) on '16' setStylesheet(C_BUTTON16STYLE) on '32' setStylesheet(C_BUTTON32STYLE) on '64' setStylesheet(C_BUTTON64STYLE) on '128' setStylesheet(C_BUTTON128STYLE) on '256' setStylesheet(C_BUTTON256STYLE) on '512' setStylesheet(C_BUTTON512STYLE) on '1024' setStylesheet(C_BUTTON1024STYLE) on '2048' setStylesheet(C_BUTTON2048STYLE) off  
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 down, pass it around 97 bottles of beer on the wall ... and so on, until reaching   0     (zero). Grammatical support for   1 bottle of beer   is optional. As with any puzzle, try to do it in as creative/concise/comical a way as possible (simple, obvious solutions allowed, too). Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet See also   http://99-bottles-of-beer.net/   Category:99_Bottles_of_Beer   Category:Programming language families   Wikipedia 99 bottles of beer
#Comal
Comal
0010 DIM itone$(0:1) 0020 itone$(0):="one";itone$(1):="it" 0030 FOR b#:=99 TO 1 STEP -1 DO 0040 bottles(b#) 0050 PRINT "of beer on the wall," 0060 bottles(b#) 0070 PRINT "of beer," 0080 PRINT "Take ",itone$(b#=1)," down and pass it around," 0090 bottles(b#-1) 0100 PRINT "of beer on the wall!" 0110 PRINT 0120 ENDFOR b# 0130 PROC bottles(b#) CLOSED 0140 CASE b# OF 0150 WHEN 0 0160 PRINT "No more bottles ", 0170 WHEN 1 0180 PRINT "1 bottle ", 0190 OTHERWISE 0200 PRINT b#," bottles ", 0210 ENDCASE 0220 ENDPROC bottles 0230 END
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. The program should check then evaluate the expression. The goal is for the player to enter an expression that (numerically) evaluates to 24. Only the following operators/functions are allowed: multiplication, division, addition, subtraction Division should use floating point or rational arithmetic, etc, to preserve remainders. Brackets are allowed, if using an infix expression evaluator. Forming multiple digit numbers from the supplied digits is disallowed. (So an answer of 12+12 when given 1, 2, 2, and 1 is wrong). The order of the digits when given does not have to be preserved. Notes The type of expression evaluator used is not mandated. An RPN evaluator is equally acceptable for example. The task is not for the program to generate the expression, or test whether an expression is even possible. Related tasks 24 game/Solve Reference The 24 Game on h2g2.
#Picat
Picat
import util.   main => play.   play => nl, Digits = [random() mod 9 + 1 : _ in 1..4].sort(), println("Enter \"q\" to quit"), println("Enter \"!\" to request a new set of four digits."), printf("Or enter expression using %w => ", Digits), Exp = read_line().strip(), evaluate(Digits,Exp).   evaluate(_Digits,"q") => halt. evaluate(_Digits,"!") => play. evaluate(Digits,Exp) => Operands = [to_int(D) : D in Exp, digit(D)].sort(), (Digits !== Operands -> println("You must use the given digits:" ++ to_string(Digits))  ; catch(Term = parse_term(Exp), Exception, println(Exception)), Res is Term, (Res =:= 24 -> println("Good work!")  ; println("Wong expression") ) ), play.  
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 ≤ A , B ≤ + 1000 ) {\displaystyle (-1000\leq A,B\leq +1000)} Output data The required output is one integer:   the sum of A and B. Example input   output   2 2 4 3 2 5
#Gambas
Gambas
Public Sub Main() Dim sInput As String = InputBox("Input 2 numbers seperated by a space", "A + B")   Print Split(sInput, " ")[0] & " + " & Split(sInput, " ")[1] & " = " & Str(Val(Split(sInput, " ")[0]) + Val(Split(sInput, " ")[1]))   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 sides of the blocks. The sample collection of 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) Task Write a function that takes a string (word) and determines whether the word can be spelled with the given collection of blocks. The rules are simple:   Once a letter on a block is used that block cannot be used again   The function should be case-insensitive   Show the output on this page for the following 7 words in the following example Example >>> can_make_word("A") True >>> can_make_word("BARK") True >>> can_make_word("BOOK") False >>> can_make_word("TREAT") True >>> can_make_word("COMMON") False >>> can_make_word("SQUAD") True >>> can_make_word("CONFUSE") True Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Python
Python
  ''' Note that this code is broken, e.g., it won't work when blocks = [("A", "B"), ("A","C")] and the word is "AB", where the answer should be True, but the code returns False. ''' 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")]     def can_make_word(word, block_collection=blocks): """ Return True if `word` can be made from the blocks in `block_collection`.   >>> can_make_word("") False >>> can_make_word("a") True >>> can_make_word("bark") True >>> can_make_word("book") False >>> can_make_word("treat") True >>> can_make_word("common") False >>> can_make_word("squad") True >>> can_make_word("coNFused") True """ if not word: return False   blocks_remaining = block_collection[:] for char in word.upper(): for block in blocks_remaining: if char in block: blocks_remaining.remove(block) break else: return False return True     if __name__ == "__main__": import doctest doctest.testmod() print(", ".join("'%s': %s" % (w, can_make_word(w)) for w in ["", "a", "baRk", "booK", "treat", "COMMON", "squad", "Confused"]))  
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 decide some strategy before any enter the room. Prisoners enter the room one by one, can open a drawer, inspect the card number in the drawer, then close the drawer. A prisoner can open no more than 50 drawers. A prisoner tries to find his own number. A prisoner finding his own number is then held apart from the others. If all 100 prisoners find their own numbers then they will all be pardoned. If any don't then all sentences stand. The task Simulate several thousand instances of the game where the prisoners randomly open drawers Simulate several thousand instances of the game where the prisoners use the optimal strategy mentioned in the Wikipedia article, of: First opening the drawer whose outside number is his prisoner number. If the card within has his number then he succeeds otherwise he opens the drawer with the same number as that of the revealed card. (until he opens his maximum). Show and compare the computed probabilities of success for the two strategies, here, on this page. References The unbelievable solution to the 100 prisoner puzzle standupmaths (Video). wp:100 prisoners problem 100 Prisoners Escape Puzzle DataGenetics. Random permutation statistics#One hundred prisoners on Wikipedia.
#Rust
Rust
[dependencies] rand = '0.7.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
#Python
Python
  ''' Structural Game for 15 - Puzzle with different difficulty levels''' from random import randint     class Puzzle: def __init__(self): self.items = {} self.position = None   def main_frame(self): d = self.items print('+-----+-----+-----+-----+') print('|%s|%s|%s|%s|' % (d[1], d[2], d[3], d[4])) print('+-----+-----+-----+-----+') print('|%s|%s|%s|%s|' % (d[5], d[6], d[7], d[8])) print('+-----+-----+-----+-----+') print('|%s|%s|%s|%s|' % (d[9], d[10], d[11], d[12])) print('+-----+-----+-----+-----+') print('|%s|%s|%s|%s|' % (d[13], d[14], d[15], d[16])) print('+-----+-----+-----+-----+')   def format(self, ch): ch = ch.strip() if len(ch) == 1: return ' ' + ch + ' ' elif len(ch) == 2: return ' ' + ch + ' ' elif len(ch) == 0: return ' '   def change(self, to): fro = self.position for a, b in self.items.items(): if b == self.format(str(to)): to = a break self.items[fro], self.items[to] = self.items[to], self.items[fro] self.position = to   def build_board(self, difficulty): for i in range(1, 17): self.items[i] = self.format(str(i)) tmp = 0 for a, b in self.items.items(): if b == ' 16 ': self.items[a] = ' ' tmp = a break self.position = tmp if difficulty == 0: diff = 10 elif difficulty == 1: diff = 50 else: diff = 100 for _ in range(diff): lst = self.valid_moves() lst1 = [] for j in lst: lst1.append(int(j.strip())) self.change(lst1[randint(0, len(lst1)-1)])   def valid_moves(self): pos = self.position if pos in [6, 7, 10, 11]: return self.items[pos - 4], self.items[pos - 1],\ self.items[pos + 1], self.items[pos + 4] elif pos in [5, 9]: return self.items[pos - 4], self.items[pos + 4],\ self.items[pos + 1] elif pos in [8, 12]: return self.items[pos - 4], self.items[pos + 4],\ self.items[pos - 1] elif pos in [2, 3]: return self.items[pos - 1], self.items[pos + 1], self.items[pos + 4] elif pos in [14, 15]: return self.items[pos - 1], self.items[pos + 1],\ self.items[pos - 4] elif pos == 1: return self.items[pos + 1], self.items[pos + 4] elif pos == 4: return self.items[pos - 1], self.items[pos + 4] elif pos == 13: return self.items[pos + 1], self.items[pos - 4] elif pos == 16: return self.items[pos - 1], self.items[pos - 4]   def game_over(self): flag = False for a, b in self.items.items(): if b == ' ': pass else: if a == int(b.strip()): flag = True else: flag = False return flag     g = Puzzle() g.build_board(int(input('Enter the difficulty : 0 1 2\n2 ' '=> highest 0=> lowest\n'))) g.main_frame() print('Enter 0 to exit') while True: print('Hello user:\nTo change the position just enter the no. near it') lst = g.valid_moves() lst1 = [] for i in lst: lst1.append(int(i.strip())) print(i.strip(), '\t', end='') print() x = int(input()) if x == 0: break elif x not in lst1: print('Wrong move') else: g.change(x) g.main_frame() if g.game_over(): print('You WON') break  
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 adjacent tiles (in that direction only) with matching numbers combine into one bearing the sum of those numbers.   A move is valid when at least one tile can be moved,   if only by combination.   A new tile with the value of   2   is spawned at the end of each turn at a randomly chosen empty square   (if there is one).   Adding a new tile on a blank space.   Most of the time,   a new   2   is to be added,   and occasionally   (10% of the time),   a   4.   To win,   the player must create a tile with the number   2048.   The player loses if no valid moves are possible. The name comes from the popular open-source implementation of this game mechanic, 2048. Requirements   "Non-greedy" movement.     The tiles that were created by combining other tiles should not be combined again during the same turn (move).     That is to say,   that moving the tile row of: [2][2][2][2] to the right should result in: ......[4][4] and not: .........[8]   "Move direction priority".     If more than one variant of combining is possible,   move direction shall indicate which combination will take effect.   For example, moving the tile row of: ...[2][2][2] to the right should result in: ......[2][4] and not: ......[4][2]   Check for valid moves.   The player shouldn't be able to skip their turn by trying a move that doesn't change the board.   Check for a  win condition.   Check for a lose condition.
#Ruby
Ruby
  #!/usr/bin/ruby   require 'io/console'   class Board def initialize size=4, win_limit=2048, cell_width = 6 @size = size; @cw = cell_width; @win_limit = win_limit @board = Array.new(size) {Array.new(size, 0)} @moved = true; @score = 0; @no_more_moves = false spawn end   def draw print "\n\n" if @r_vert print ' ' if @r_hori print '┌' + (['─' * @cw] * @size).join('┬') + '┐' @board.each do |row| print "\n" formated = row.map {|num| num == 0 ? ' ' * @cw : format(num)} print ' ' if @r_hori puts '│' + formated.join('│') + '│' print ' ' if @r_hori print '├' + ([' ' * @cw] * @size).join('┼') + '┤' end print "\r" print ' ' if @r_hori puts '└' + (['─' * @cw] * @size).join('┴') + '┘' end   def move direction case direction when :up @board = column_map {|c| logic(c)} @r_vert = false if $rumble when :down @board = column_map {|c| logic(c.reverse).reverse} @r_vert = true if $rumble when :left @board = row_map {|r| logic(r)} @r_hori = false if $rumble when :right @board = row_map {|r| logic(r.reverse).reverse} @r_hori = true if $rumble end spawn @moved = false end   def print_score puts "Your Score is #@score." puts "Congratulations, you have won!" if to_enum.any? {|e| e >= @win_limit} end   def no_more_moves?; @no_more_moves; end def won?; to_enum.any? {|e| e >= @win_limit}; end def reset!; initialize @size, @win_limit, @cw; end   private   def set x, y, val @board[y][x] = val end   def spawn free_pos = to_enum.select{|elem,x,y| elem == 0}.map{|_,x,y| [x,y]} unless free_pos.empty? set *free_pos.sample, rand > 0.1 ? 2 : 4 if @moved else snap = @board unless @stop @stop = true %i{up down left right}.each{|s| move(s)} @no_more_moves = true if snap.flatten == @board.flatten @board = snap @stop = false end end end   def logic list jump = false result = list.reduce([]) do |res, val| if res.last == val && !jump res[-1] += val @score += val jump = true elsif val != 0 res.push val jump = false end res end result += [0] * (@size - result.length) @moved ||= list != result result end   def column_map xboard = @board.transpose xboard.map!{|c| yield c } xboard.transpose end   def row_map @board.map {|r| yield r } end   def to_enum @enum ||= Enumerator.new(@size * @size) do |yielder| (@size*@size).times do |i| yielder.yield (@board[i / @size][i % @size]), (i % @size), (i / @size ) end end @enum.rewind end   def format(num) if $color cstart = "\e[" + $colors[Math.log(num, 2)] + "m" cend = "\e[0m" else cstart = cend = "" end cstart + num.to_s.center(@cw) + cend end end   $color = true $colors = %W{0 1;97 1;93 1;92 1;96 1;91 1;95 1;94 1;30;47 1;43 1;42 1;46 1;41 1;45 1;44 1;33;43 1;33;42 1;33;41 1;33;44} $rumble = false   $check_score = true unless ARGV.empty? puts "Usage: #$0 [gridsize] [score-threshold] [padwidth] [--no-color] [--rumble]"; exit if %W[-h --help].include?(ARGV[0]) args = ARGV.map(&:to_i).reject{|n| n == 0} b = Board.new(*args) unless args.empty? $rumble = true if ARGV.any?{|a| a =~ /rumble/i } $color = false if ARGV.any?{|a| a =~ /no.?color/i} end   b ||= Board.new puts "\e[H\e[2J" b.draw puts "Press h for help, q to quit" loop do input = STDIN.getch if input == "\e" 2.times {input << STDIN.getch} end   case input when "\e[A", "w" then b.move(:up) when "\e[B", "s" then b.move(:down) when "\e[C", "d" then b.move(:right) when "\e[D", "a" then b.move(:left)   when "q","\u0003","\u0004" then b.print_score; exit   when "h" puts <<-EOM.gsub(/^\s*/, '') ┌─ ─┐ │Use the arrow-keys or WASD on your keyboard to push board in the given direction. │Tiles with the same number merge into one. │Get a tile with a value of #{ARGV[1] || 2048} to win. │In case you cannot move or merge any tiles anymore, you loose. │You can start this game with different settings by providing commandline argument: │For instance: │ %> #$0 6 8192 --rumble └─ ─┘ PRESS q TO QUIT (or Ctrl-C or Ctrl-D) EOM input = STDIN.getch end   puts "\e[H\e[2J" b.draw   if b.no_more_moves? or $check_score && b.won? b.print_score if b.no_more_moves? puts "No more moves possible" puts "Again? (y/n)" exit if STDIN.gets.chomp.downcase == "n" $check_score = true b.reset! puts "\e[H\e[2J" b.draw else puts "Continue? (y/n)" exit if STDIN.gets.chomp.downcase == "n" $check_score = false puts "\e[H\e[2J" b.draw end end end  
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 down, pass it around 97 bottles of beer on the wall ... and so on, until reaching   0     (zero). Grammatical support for   1 bottle of beer   is optional. As with any puzzle, try to do it in as creative/concise/comical a way as possible (simple, obvious solutions allowed, too). Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet See also   http://99-bottles-of-beer.net/   Category:99_Bottles_of_Beer   Category:Programming language families   Wikipedia 99 bottles of beer
#Comefrom0x10
Comefrom0x10
bottles = ' bottles ' remaining = 99 one_less_bottle = remaining depluralize comefrom drinking if one_less_bottle is 1 bottles = ' bottle '   drinking comefrom if remaining is one_less_bottle remaining bottles 'of beer on the wall' remaining bottles 'of beer' 'Take one down, pass it around' one_less_bottle = remaining - 1 one_less_bottle bottles 'of beer on the wall`n' remaining = remaining - 1   comefrom if one_less_bottle is 0 '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. The program should check then evaluate the expression. The goal is for the player to enter an expression that (numerically) evaluates to 24. Only the following operators/functions are allowed: multiplication, division, addition, subtraction Division should use floating point or rational arithmetic, etc, to preserve remainders. Brackets are allowed, if using an infix expression evaluator. Forming multiple digit numbers from the supplied digits is disallowed. (So an answer of 12+12 when given 1, 2, 2, and 1 is wrong). The order of the digits when given does not have to be preserved. Notes The type of expression evaluator used is not mandated. An RPN evaluator is equally acceptable for example. The task is not for the program to generate the expression, or test whether an expression is even possible. Related tasks 24 game/Solve Reference The 24 Game on h2g2.
#PicoLisp
PicoLisp
  (load "@lib/frac.l")   (de random4digits () (setq Numbers (make (do 4 (link (rand 1 9))))) Numbers )   (de prompt () (prinl "^JPlease enter a 'Lisp' expression (integer or fractional math) that equals 24,^J" "using (, ), frac, + or f+, - or f-, * or f*, / or f/, and " Numbers "^J" "(use each number only once). Enter . to quit." ) )   (de getinput () (setq Expression (catch ’NIL (in NIL (read)))) Expression )   (de checkexpression (Numbers Expression) (make (when (diff Numbers (fish num? Expression)) (link "Not all numbers used.") ) (when (diff (fish num? Expression) Numbers) (link "Using wrong number(s).")) (if (sub? "f" (pack Expression)) (when (diff (fish sym? Expression) '(frac f+ f- f* f/)) (link "Illegal operator(s). If fractional expression, must use frac, f+, f-, f*, f/ only.") ) (when (diff (fish sym? Expression) '(+ - * /)) (link "Using illegal operator(s).") ) ) ) )   (de instructions () (prinl "Example 'Lisp' expression: (- (* 3 9) (+ 1 2))") (prinl "Example 'Lisp' fractional expression:^J" "(f- (f* (frac 3 1)(frac 9 1)) (f+ (frac 1 1)(frac 2 1)))" ) (prinl "Use a fractional expression 'just for fun (as above)' OR if your solution^J" "would lose remainder value(s) otherwise (through integer division)." ) )   (de loopuntilquit () (instructions) (loop (set 'Numbers (random4digits)) (prompt) (set 'Expression (getinput)) (if (= Expression ".") (prog (prinl "bye!") (bye))) (set 'Check (checkexpression Numbers Expression)) (if (car Check) (mapcar prinl Check) (prog (set 'Evaluated (eval Expression)) (if (or (= Evaluated 24) (= Evaluated (24 . 1))) (prinl "Congratulations!") (prinl "That evaluated to " Evaluated " Try again!") ) ) ) ) )   (loopuntilquit)    
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 ≤ A , B ≤ + 1000 ) {\displaystyle (-1000\leq A,B\leq +1000)} Output data The required output is one integer:   the sum of A and B. Example input   output   2 2 4 3 2 5
#Gastona
Gastona
#listix#   <main> "@<p1> + @<p2> = " =, p1 + p2  
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 sides of the blocks. The sample collection of 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) Task Write a function that takes a string (word) and determines whether the word can be spelled with the given collection of blocks. The rules are simple:   Once a letter on a block is used that block cannot be used again   The function should be case-insensitive   Show the output on this page for the following 7 words in the following example Example >>> can_make_word("A") True >>> can_make_word("BARK") True >>> can_make_word("BOOK") False >>> can_make_word("TREAT") True >>> can_make_word("COMMON") False >>> can_make_word("SQUAD") True >>> can_make_word("CONFUSE") True Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#q
q
BLOCKS:string`BO`XK`DQ`CP`NA`GT`RE`TG`QD`FS`JW`HU`VI`AN`OB`ER`FS`LY`PC`ZM WORDS:string`A`BARK`BOOK`TREAT`COMMON`SQUAD`CONFUSE   cmw:{[s;b] / [str;blocks] $[0=count s; 1b; / empty string not any found:any each b=s 0; 0b; / cannot proceed any(1_s).z.s/:b(til count b)except/:where found] }
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 decide some strategy before any enter the room. Prisoners enter the room one by one, can open a drawer, inspect the card number in the drawer, then close the drawer. A prisoner can open no more than 50 drawers. A prisoner tries to find his own number. A prisoner finding his own number is then held apart from the others. If all 100 prisoners find their own numbers then they will all be pardoned. If any don't then all sentences stand. The task Simulate several thousand instances of the game where the prisoners randomly open drawers Simulate several thousand instances of the game where the prisoners use the optimal strategy mentioned in the Wikipedia article, of: First opening the drawer whose outside number is his prisoner number. If the card within has his number then he succeeds otherwise he opens the drawer with the same number as that of the revealed card. (until he opens his maximum). Show and compare the computed probabilities of success for the two strategies, here, on this page. References The unbelievable solution to the 100 prisoner puzzle standupmaths (Video). wp:100 prisoners problem 100 Prisoners Escape Puzzle DataGenetics. Random permutation statistics#One hundred prisoners on Wikipedia.
#Sather
Sather
class MAIN is shuffle (a: ARRAY{INT}) is ARR_PERMUTE_ALG{INT, ARRAY{INT}}::shuffle(a); end;   try_random (n: INT, drawers: ARRAY{INT}, tries: INT): BOOL is my_tries ::= drawers.inds; shuffle(my_tries); loop tries.times!; if drawers[my_tries.elt!] = n then return true; end; end; return false; end;   try_optimal (n: INT, drawers: ARRAY{INT}, tries: INT): BOOL is num ::= n; loop tries.times!; num := drawers[num]; if num = n then return true; end; end; return false; end;   stats (label: STR, rounds, successes: INT): STR is return #FMT("<^###########>: <#######> rounds. Successes: <#######> (<##.###>%%)\n", label, rounds, successes, (successes.flt / rounds.flt)*100.0).str; end;   try (name: STR, nrounds, ndrawers, npris, ntries: INT, strategy: ROUT{INT,ARRAY{INT},INT}:BOOL) is drawers: ARRAY{INT} := #(ndrawers); loop drawers.set!(drawers.ind!); end; successes ::= 0; loop nrounds.times!; shuffle(drawers); success ::= true; loop n ::= npris.times!; if ~strategy.call(n, drawers, ntries) then success := false; break!; end; end; if success then successes := successes + 1; end; end; #OUT + stats(name, nrounds, successes); end;   main is RND::seed := #TIMES.wall_time; #OUT +"100 prisoners, 100 drawers, 50 tries:\n"; try("random", 100000, 100, 100, 50, bind(try_random(_, _, _))); try("optimal", 100000, 100, 100, 50, bind(try_optimal(_, _, _)));   #OUT +"\n10 prisoners, 10 drawers, 5 tries:\n"; try("random", 100000, 10, 10, 5, bind(try_random(_, _, _))); try("optimal", 100000, 10, 10, 5, bind(try_optimal(_, _, _))); end; end;
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
#QB64
QB64
  _TITLE "GUI Sliding Blocks Game " RANDOMIZE TIMER   ' get from user the desired board size = s DO LOCATE CSRLIN, 3: INPUT "(0 quits) Enter your number of blocks per side 3 - 9 you want > ", s IF s = 0 THEN END LOOP UNTIL s > 2 AND s < 10   ' screen setup: based on the square blocks q pixels a sides q = 540 / s 'square size, shoot for 540 x 540 pixel board display SCREEN _NEWIMAGE(q * s + 1, q * s + 1, 32): _SCREENMOVE 360, 60   'initialize board = solution DIM board(s, s) FOR r = 1 TO s FOR c = 1 TO s board(c, r) = c + (r - 1) * s NEXT NEXT board(s, s) = 0: c0 = s: r0 = s   'scramble board for puzzle FOR i = 0 TO s ^ 5 ' mix blocks SELECT CASE INT(RND * 4) + 1 CASE 1: IF c0 < s THEN board(c0, r0) = board(c0 + 1, r0): board(c0 + 1, r0) = 0: c0 = c0 + 1 CASE 2: IF c0 > 1 THEN board(c0, r0) = board(c0 - 1, r0): board(c0 - 1, r0) = 0: c0 = c0 - 1 CASE 3: IF r0 < s THEN board(c0, r0) = board(c0, r0 + 1): board(c0, r0 + 1) = 0: r0 = r0 + 1 CASE 4: IF r0 > 1 THEN board(c0, r0) = board(c0, r0 - 1): board(c0, r0 - 1) = 0: r0 = r0 - 1 END SELECT NEXT   t = TIMER: update = -1 'OK user here you go! DO IF update THEN 'display status and determine if solved solved = -1: update = 0 FOR r = 1 TO s FOR c = 1 TO s IF board(c, r) THEN IF board(c, r) <> (r - 1) * s + c THEN solved = 0 COLOR _RGB32(255, 255, 255), _RGB32(0, 0, 255) LINE ((c - 1) * q + 1, (r - 1) * q + 2)-(c * q - 2, r * q - 2), _RGB32(0, 0, 255), BF _PRINTSTRING ((c - 1) * q + .4 * q, (r - 1) * q + .4 * q), RIGHT$(" " + STR$(board(c, r)), 2) ELSE IF board(s, s) <> 0 THEN solved = 0 COLOR _RGB32(0, 0, 0), _RGB32(0, 0, 0) LINE ((c - 1) * q, (r - 1) * q)-(c * q, r * q), , BF END IF NEXT NEXT IF solved THEN 'flash the Solved Report until user closes window else report status _DISPLAY flash$ = "Solved!" + STR$(mc) + " Moves in " + STR$(INT(TIMER - t)) + " secs." WHILE 1: _TITLE flash$: _DELAY .2: _TITLE " ": _DELAY .2: WEND ELSE _TITLE STR$(mc) + " Moves in " + STR$(INT(TIMER - t)) + " secs." + STR$(test) END IF _DISPLAY END IF   'get next mouse click, check if on block next to empty space make move or beep m = _MOUSEINPUT: mb = _MOUSEBUTTON(1): mx = _MOUSEX: my = _MOUSEY IF mb AND solved = 0 THEN 'get last place mouse button was down mb = _MOUSEBUTTON(1): mx = _MOUSEX: my = _MOUSEY WHILE mb 'left button down, wait for mouse button release m = _MOUSEINPUT: mb = _MOUSEBUTTON(1): mx = _MOUSEX: my = _MOUSEY WEND   'convert mouse position to board array (x, y) are we near empty space? bx = INT(mx / q) + 1: by = INT(my / q) + 1: update = -1 IF bx = c0 + 1 AND by = r0 THEN board(c0, r0) = board(c0 + 1, r0): board(c0 + 1, r0) = 0: c0 = c0 + 1: mc = mc + 1 ELSEIF bx = c0 - 1 AND by = r0 THEN board(c0, r0) = board(c0 - 1, r0): board(c0 - 1, r0) = 0: c0 = c0 - 1: mc = mc + 1 ELSEIF bx = c0 AND by = r0 + 1 THEN board(c0, r0) = board(c0, r0 + 1): board(c0, r0 + 1) = 0: r0 = r0 + 1: mc = mc + 1 ELSEIF bx = c0 AND by = r0 - 1 THEN board(c0, r0) = board(c0, r0 - 1): board(c0, r0 - 1) = 0: r0 = r0 - 1: mc = mc + 1 ELSE BEEP END IF END IF LOOP  
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 adjacent tiles (in that direction only) with matching numbers combine into one bearing the sum of those numbers.   A move is valid when at least one tile can be moved,   if only by combination.   A new tile with the value of   2   is spawned at the end of each turn at a randomly chosen empty square   (if there is one).   Adding a new tile on a blank space.   Most of the time,   a new   2   is to be added,   and occasionally   (10% of the time),   a   4.   To win,   the player must create a tile with the number   2048.   The player loses if no valid moves are possible. The name comes from the popular open-source implementation of this game mechanic, 2048. Requirements   "Non-greedy" movement.     The tiles that were created by combining other tiles should not be combined again during the same turn (move).     That is to say,   that moving the tile row of: [2][2][2][2] to the right should result in: ......[4][4] and not: .........[8]   "Move direction priority".     If more than one variant of combining is possible,   move direction shall indicate which combination will take effect.   For example, moving the tile row of: ...[2][2][2] to the right should result in: ......[2][4] and not: ......[4][2]   Check for valid moves.   The player shouldn't be able to skip their turn by trying a move that doesn't change the board.   Check for a  win condition.   Check for a lose condition.
#Rust
Rust
  use std::io::{self,BufRead}; extern crate rand;   enum Usermove { Up, Down, Left, Right, }   fn print_game(field :& [[u32;4];4] ){ println!("{:?}",&field[0] ); println!("{:?}",&field[1] ); println!("{:?}",&field[2] ); println!("{:?}",&field[3] ); }   fn get_usermove()-> Usermove { let umove: Usermove ; loop{ let mut input = String::new(); io::stdin().read_line(&mut input).unwrap();   match input.chars().nth(0){ Some('a') =>{umove = Usermove::Left ;break }, Some('w') =>{umove = Usermove::Up  ;break }, Some('s') =>{umove = Usermove::Down ;break }, Some('d') =>{umove = Usermove::Right;break }, _ => {println!("input was {}: invalid character should be a,s,w or d ",input.chars().nth(0).unwrap());} , } } umove }   //this function inplements the user moves. //for every element it looks if the element is zero // if the element is zero it looks against the direction of the movement if any //element is not zero then it will move it to the element its place then it will look for //a matching element // if the element is not zero then it will look for a match if no match is found // then it will look for the next element   fn do_game_step(step : &Usermove, field:&mut [[u32;4];4]){ match *step { Usermove::Left =>{ for array in field{ for col in 0..4 { for testcol in (col+1)..4 { if array[testcol] != 0 { if array[col] == 0 { array[col] += array[testcol]; array[testcol] = 0; } else if array[col] == array[testcol] { array[col] += array[testcol]; array[testcol] = 0; break; } else { break } } } } } } , Usermove::Right=>{ for array in field{ for col in (0..4).rev() { for testcol in (0..col).rev() { if array[testcol] != 0 { if array[col] == 0 { array[col] += array[testcol]; array[testcol] = 0; } else if array[col] == array[testcol] { array[col] += array[testcol]; array[testcol] = 0; break; }else { break; } } } } } } , Usermove::Down =>{ for col in 0..4 { for row in (0..4).rev() { for testrow in (0..row).rev() { if field[testrow][col] != 0 { if field[row][col] == 0 { field[row][col] += field[testrow][col]; field[testrow][col] = 0; } else if field[row][col] == field[testrow][col] { field[row][col] += field[testrow][col]; field[testrow][col] = 0; break; }else { break; }   } } } } } , Usermove::Up =>{ for col in 0..4 { for row in 0..4{ for testrow in (row+1)..4 { if field[testrow][col] != 0 { if field[row][col] == 0 { field[row][col] += field[testrow][col]; field[testrow][col] = 0; } else if field[row][col] == field[testrow][col] { field[row][col] += field[testrow][col]; field[testrow][col] = 0; break; }else { break; } } } } } }, } }   fn spawn( field: &mut [[u32;4];4]){ loop{ let x = rand::random::<usize>(); if field[x % 4][(x/4)%4] == 0 { if x % 10 == 0 { field[x % 4][(x/4)%4]= 4; }else{ field[x % 4][(x/4)%4]= 2; } break; } } }     fn main() { let mut field : [[u32; 4];4] = [[0;4];4]; let mut test : [[u32; 4];4] ; 'gameloop:loop { //check if there is still an open space test=field.clone(); spawn(&mut field); //if all possible moves do not yield a change then there is no valid move left //and it will be game over for i in [Usermove::Up,Usermove::Down,Usermove::Left,Usermove::Right].into_iter(){ do_game_step(i, &mut test); if test != field{ break;//found a valid move } match *i{ Usermove::Right=> { println!("No more valid move, you lose"); break 'gameloop; }, _=>{}, } } print_game(&field); println!("move the blocks");   test=field.clone(); while test==field { do_game_step(&get_usermove(), &mut field); }   for row in field.iter(){ if row.iter().any(|x| *x == 2048){ print_game(&field ); println!("You Won!!"); break; } } } }  
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 down, pass it around 97 bottles of beer on the wall ... and so on, until reaching   0     (zero). Grammatical support for   1 bottle of beer   is optional. As with any puzzle, try to do it in as creative/concise/comical a way as possible (simple, obvious solutions allowed, too). Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet See also   http://99-bottles-of-beer.net/   Category:99_Bottles_of_Beer   Category:Programming language families   Wikipedia 99 bottles of beer
#Common_Lisp
Common Lisp
include "cowgol.coh";   sub Bottles(n: uint8) is if n == 0 then print("No more"); else print_i8(n); end if;   print(" bottle"); if n != 1 then print("s"); end if; end sub;   sub Verse(n: uint8) is Bottles(n); print(" of beer on the wall,\n"); Bottles(n); print(" of beer,\n"); print("Take "); if n == 1 then print("it"); else print("one"); end if; print(" down and pass it around,\n"); Bottles(n-1); print(" of beer on the wall.\n\n"); end sub;   var verse: uint8 := 99; while verse > 0 loop Verse(verse); verse := verse - 1; end loop;
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. The program should check then evaluate the expression. The goal is for the player to enter an expression that (numerically) evaluates to 24. Only the following operators/functions are allowed: multiplication, division, addition, subtraction Division should use floating point or rational arithmetic, etc, to preserve remainders. Brackets are allowed, if using an infix expression evaluator. Forming multiple digit numbers from the supplied digits is disallowed. (So an answer of 12+12 when given 1, 2, 2, and 1 is wrong). The order of the digits when given does not have to be preserved. Notes The type of expression evaluator used is not mandated. An RPN evaluator is equally acceptable for example. The task is not for the program to generate the expression, or test whether an expression is even possible. Related tasks 24 game/Solve Reference The 24 Game on h2g2.
#PL.2FI
PL/I
  /* Plays the game of 24. */   TWENTYFOUR: procedure options (main); /* 14 August 2010 */   CTP: procedure (E) returns (character(50) varying); declare E character (*) varying; declare OUT character (length(E)) varying; declare S character (length(E)) varying controlled; declare c character (1); declare i fixed binary;   /* This procedure converts an arithmetic expression to Reverse Polish Form. */ /* A push-down pop-up stack is used for operators. */ priority: procedure (a) returns (fixed decimal (1)); declare a character (1); declare ops character (10) initial ('#+-*/') varying static; declare pri(6) fixed decimal (1) initial (1,2,2,3,3,4) static; declare i fixed binary;   i = index(ops,a); return (pri(i)); end priority;   allocate S; S = '#'; out = ''; do i = 1 to length(E); c = substr(E, i, 1); if index('+-*/', c) > 0 then do; /* Copy any higher priority operators on the stack to the output. */ do while ( priority(c) <= priority((S)) ); out = out || S; free S; end; /* Copy the input character to the stack. */ allocate S; S = c; end;   if index('123456789', c) > 0 then out = out || c; end; do while (allocation(S) > 1); out = out || s; free S; end; return (out); end CTP;   /* Given a push-down pop-up stack, and an expresion in */ /* Reverse Polish notation, evaluate the expression. */ EVAL: procedure (E) returns (fixed decimal(15)); declare E character (*) varying; declare S fixed decimal (15) controlled; declare (a, b) fixed decimal (15); declare c character (1); declare p fixed binary; declare (empty_stack, invalid_expression) condition;   on condition (empty_stack) begin; put skip list ('Your expression is not valid.'); stop; end; on condition (invalid_expression) begin; put skip list ('Your expression is not valid.'); stop; end;   do p = 1 to length(E); c = substr(E, p, 1); if index('123456789', c) > 0 then do; allocate S; S = c; end; else do; if allocation(S) = 0 then signal condition (empty_stack); b = S; free S; if allocation(S) = 0 then signal condition (empty_stack); a = S; select (c); when ('+') S = a + b; when ('-') S = a - b; when ('*') S = a * b; when ('/') S = a / b; when ('^') S = a ** b; otherwise signal condition (invalid_expression); end; end; end; if allocation(S) ^= 1 then signal condition (invalid_expression); return (S); END eval;   /* Check that the player has used every digit and no others. */ VALIDATE: procedure (E); declare E character (*) varying; declare E2 character (length(E)), (i, j) fixed binary; declare digits(9) character (1) static initial ('1', '2', '3', '4', '5', '6', '7', '8', '9');   E2 = translate(E, ' ', '+-*/' ); do i = 1 to 4; j = index(E2, digits(k(i))); if j > 0 then substr(E2, j, 1) = ' '; else do; put skip list ('You must use the digits supplied.'); stop; end; end; if E2 ^= '' then do; put skip list ('You must use every digit supplied, and no others.'); stop; end; end VALIDATE;   declare E character (40) varying; declare k(4) fixed decimal; declare (time, random) builtin; declare V fixed decimal (15);   k = random(TIME); k = 9*random() + 1; put skip edit ('Here are four integers:', k) (a); put skip list ('With these integers, make up an arithmetic expression' || ' that evaluates to 24.'); put skip list ('You can use any of the operators +, -, *, and /'); put skip list ('E.g., Given the integers 1, 3, 7, and 6,' || ' the expression 6*3+7-1 evaluates to 24.');   put skip list ('Please type an arithmetic expression :'); get edit (E) (L) COPY;   CALL VALIDATE (E); /* Check that the player has used every digit and no others. */   E = CTP(E); V = EVAL (E); if V = 24 then put skip list ('Congratulations: the expression evaluates to 24.'); else put skip edit ('The result is ', trim(V), ' which is not correct') (a);   end TWENTYFOUR;  
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 ≤ A , B ≤ + 1000 ) {\displaystyle (-1000\leq A,B\leq +1000)} Output data The required output is one integer:   the sum of A and B. Example input   output   2 2 4 3 2 5
#Gema
Gema
<D> <D>=@add{$1;$2}
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 sides of the blocks. The sample collection of 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) Task Write a function that takes a string (word) and determines whether the word can be spelled with the given collection of blocks. The rules are simple:   Once a letter on a block is used that block cannot be used again   The function should be case-insensitive   Show the output on this page for the following 7 words in the following example Example >>> can_make_word("A") True >>> can_make_word("BARK") True >>> can_make_word("BOOK") False >>> can_make_word("TREAT") True >>> can_make_word("COMMON") False >>> can_make_word("SQUAD") True >>> can_make_word("CONFUSE") True Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Quackery
Quackery
[ $ "BOXKDQCPNAGTRETGQDFS" $ "JWHUVIANOBERFSLYPCZM" join ] constant is blocks ( --> $ )   [ -2 & tuck pluck drop swap pluck drop ] is remove2 ( $ n --> $ )   [ iff [ say "True" ] else [ say "False" ] ] is echotruth ( b --> )   [ true blocks rot witheach [ upper over find 2dup swap found iff remove2 else [ drop dip not conclude ] ] drop echotruth ] is can_make_word ( $ --> )
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 decide some strategy before any enter the room. Prisoners enter the room one by one, can open a drawer, inspect the card number in the drawer, then close the drawer. A prisoner can open no more than 50 drawers. A prisoner tries to find his own number. A prisoner finding his own number is then held apart from the others. If all 100 prisoners find their own numbers then they will all be pardoned. If any don't then all sentences stand. The task Simulate several thousand instances of the game where the prisoners randomly open drawers Simulate several thousand instances of the game where the prisoners use the optimal strategy mentioned in the Wikipedia article, of: First opening the drawer whose outside number is his prisoner number. If the card within has his number then he succeeds otherwise he opens the drawer with the same number as that of the revealed card. (until he opens his maximum). Show and compare the computed probabilities of success for the two strategies, here, on this page. References The unbelievable solution to the 100 prisoner puzzle standupmaths (Video). wp:100 prisoners problem 100 Prisoners Escape Puzzle DataGenetics. Random permutation statistics#One hundred prisoners on Wikipedia.
#Scala
Scala
import scala.util.Random import scala.util.control.Breaks._   object Main { def playOptimal(n: Int): Boolean = { val secretList = Random.shuffle((0 until n).toBuffer)   for (i <- secretList.indices) { var prev = i breakable { for (_ <- 0 until secretList.size / 2) { if (secretList(prev) == i) { break() } prev = secretList(prev) } return false } }   true }   def playRandom(n: Int): Boolean = { val secretList = Random.shuffle((0 until n).toBuffer)   for (i <- secretList.indices) { val trialList = Random.shuffle((0 until n).toBuffer)   breakable { for (j <- 0 until trialList.size / 2) { if (trialList(j) == i) { break() } } return false } }   true }   def exec(n: Int, p: Int, play: Int => Boolean): Double = { var succ = 0.0 for (_ <- 0 until n) { if (play(p)) { succ += 1 } } (succ * 100.0) / n }   def main(args: Array[String]): Unit = { val n = 100000 val p = 100 printf("# of executions: %,d\n", n) printf("Optimal play success rate: %f%%\n", exec(n, p, playOptimal)) printf("Random play success rate: %f%%\n", exec(n, p, playRandom)) } }
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
#Quackery
Quackery
  ( moves: 0 - up, 1 - down, 2 - left, 3 - right )   [ stack ] is 15.solver ( --> [ )   [ 0 swap find ] is find-empty ( board --> n )   [ over + dup -1 > over 4 < and iff [ nip true ] else [ drop false ] ] is try-nudge ( coord delta --> coord ? )   [ dip [ dup find-empty 4 /mod ] 2 /mod 2 * 1 - swap iff try-nudge else [ dip swap try-nudge dip swap ] dip [ swap 4 * + ] ] is try-move-target ( board move --> board target ? )   [ 2dup peek dip [ -1 unrot poke 0 over find ] unrot poke 0 swap -1 over find poke ] is move-to ( board target --> board )   [ try-move-target iff [ move-to true ] else [ drop false ] ] is try-move ( board move --> board ? )   [ [] 15 times [ i^ 1+ join ] 0 join ] constant is <board> ( --> board )   [ <board> 410 times ( 2 * the upper bound on the maximum moves required to solve ) [ 4 random try-move drop ] ] is <random-board> ( --> board )   [ peek dup iff [ number$ dup size 1 = if [ space swap join ] ] else [ drop $ ' ' ] echo$ ] is echo-cell ( board n --> )   [ 4 * 4 times [ say '| ' 2dup i^ + echo-cell say ' ' ] say '|' 2drop ] is echo-row ( board n --> )   [ 4 times [ say '+----+----+----+----+' cr dup i^ echo-row cr ] say '+----+----+----+----+' cr drop ] is echo-board ( board --> )   [ <board> = ] is solved? ( board --> ? )   [ $ 'Moves: ' input ] is input-moves ( --> $ )   [ dup char w = iff [ drop 0 true ] done dup char s = iff [ drop 1 true ] done dup char a = iff [ drop 2 true ] done dup char d = iff [ drop 3 true ] done false ] is char-to-move ( c --> move true | c false )   [ input-moves witheach [ char-to-move if try-move drop ] ] is player-move ( board --> board )   [ ]'[ 15.solver put [ cr dup echo-board dup solved? not while 15.solver share do again ] 15.solver release drop ] is 15-solve-with ( board 'solver --> board )   [ <random-board> 15-solve-with player-move ] is 15-puzzle ( --> )   15-puzzle  
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 adjacent tiles (in that direction only) with matching numbers combine into one bearing the sum of those numbers.   A move is valid when at least one tile can be moved,   if only by combination.   A new tile with the value of   2   is spawned at the end of each turn at a randomly chosen empty square   (if there is one).   Adding a new tile on a blank space.   Most of the time,   a new   2   is to be added,   and occasionally   (10% of the time),   a   4.   To win,   the player must create a tile with the number   2048.   The player loses if no valid moves are possible. The name comes from the popular open-source implementation of this game mechanic, 2048. Requirements   "Non-greedy" movement.     The tiles that were created by combining other tiles should not be combined again during the same turn (move).     That is to say,   that moving the tile row of: [2][2][2][2] to the right should result in: ......[4][4] and not: .........[8]   "Move direction priority".     If more than one variant of combining is possible,   move direction shall indicate which combination will take effect.   For example, moving the tile row of: ...[2][2][2] to the right should result in: ......[2][4] and not: ......[4][2]   Check for valid moves.   The player shouldn't be able to skip their turn by trying a move that doesn't change the board.   Check for a  win condition.   Check for a lose condition.
#Scala
Scala
import java.awt.event.{KeyAdapter, KeyEvent, MouseAdapter, MouseEvent} import java.awt.{BorderLayout, Color, Dimension, Font, Graphics2D, Graphics, RenderingHints} import java.util.Random   import javax.swing.{JFrame, JPanel, SwingUtilities}   object Game2048 { val target = 2048 var highest = 0   def main(args: Array[String]): Unit = { SwingUtilities.invokeLater(() => { val f = new JFrame f.setDefaultCloseOperation(3) f.setTitle("2048") f.add(new Game, BorderLayout.CENTER) f.pack() f.setLocationRelativeTo(null) f.setVisible(true) }) }   class Game extends JPanel { private val (rand , side)= (new Random, 4) private var (tiles, gamestate)= (Array.ofDim[Tile](side, side), Game2048.State.start)   final private val colorTable = Seq(new Color(0x701710), new Color(0xFFE4C3), new Color(0xfff4d3), new Color(0xffdac3), new Color(0xe7b08e), new Color(0xe7bf8e), new Color(0xffc4c3), new Color(0xE7948e), new Color(0xbe7e56), new Color(0xbe5e56), new Color(0x9c3931), new Color(0x701710))   setPreferredSize(new Dimension(900, 700)) setBackground(new Color(0xFAF8EF)) setFont(new Font("SansSerif", Font.BOLD, 48)) setFocusable(true) addMouseListener(new MouseAdapter() { override def mousePressed(e: MouseEvent): Unit = { startGame() repaint() } }) addKeyListener(new KeyAdapter() { override def keyPressed(e: KeyEvent): Unit = { e.getKeyCode match { case KeyEvent.VK_UP => moveUp() case KeyEvent.VK_DOWN => moveDown() case KeyEvent.VK_LEFT => moveLeft() case KeyEvent.VK_RIGHT => moveRight() case _ => } repaint() } })   override def paintComponent(gg: Graphics): Unit = { super.paintComponent(gg) val g = gg.asInstanceOf[Graphics2D] g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) drawGrid(g) }   private def drawGrid(g: Graphics2D): Unit = { val (gridColor, emptyColor, startColor) = (new Color(0xBBADA0), new Color(0xCDC1B4), new Color(0xFFEBCD))   if (gamestate == State.running) { g.setColor(gridColor) g.fillRoundRect(200, 100, 499, 499, 15, 15) for ( r <- 0 until side; c <- 0 until side ) if (Option(tiles(r)(c)).isEmpty) { g.setColor(emptyColor) g.fillRoundRect(215 + c * 121, 115 + r * 121, 106, 106, 7, 7) } else drawTile(g, r, c) } else { g.setColor(startColor) g.fillRoundRect(215, 115, 469, 469, 7, 7) g.setColor(gridColor.darker) g.setFont(new Font("SansSerif", Font.BOLD, 128)) g.drawString("2048", 310, 270) g.setFont(new Font("SansSerif", Font.BOLD, 20)) if (gamestate == Game2048.State.won) g.drawString("you made it!", 390, 350) else if (gamestate == Game2048.State.over) g.drawString("game over", 400, 350) g.setColor(gridColor) g.drawString("click to start a new game", 330, 470) g.drawString("(use arrow keys to move tiles)", 310, 530) } }   private def drawTile(g: Graphics2D, r: Int, c: Int): Unit = { val value = tiles(r)(c).value g.setColor(colorTable((math.log(value) / math.log(2)).toInt + 1)) g.fillRoundRect(215 + c * 121, 115 + r * 121, 106, 106, 7, 7) g.setColor(if (value < 128) colorTable.head else colorTable(1)) val (s , fm)= (value.toString, g.getFontMetrics) val asc = fm.getAscent val (x, y) = (215 + c * 121 + (106 - fm.stringWidth(s)) / 2,115 + r * 121 + (asc + (106 - (asc + fm.getDescent)) / 2)) g.drawString(s, x, y) }   private def moveUp(checkingAvailableMoves: Boolean = false) = move(0, -1, 0, checkingAvailableMoves)   private def moveDown(checkingAvailableMoves: Boolean = false) = move(side * side - 1, 1, 0, checkingAvailableMoves)   private def moveLeft(checkingAvailableMoves: Boolean = false) = move(0, 0, -1, checkingAvailableMoves)   private def moveRight(checkingAvailableMoves: Boolean = false) = move(side * side - 1, 0, 1, checkingAvailableMoves)   private def clearMerged(): Unit = for (row <- tiles; tile <- row) if (Option(tile).isDefined) tile.setMerged()   private def movesAvailable() = moveUp(true) || moveDown(true) || moveLeft(true) || moveRight(true)   def move(countDownFrom: Int, yIncr: Int, xIncr: Int, checkingAvailableMoves: Boolean): Boolean = { var moved = false for (i <- 0 until side * side) { val j = math.abs(countDownFrom - i) var( r,c) = (j / side, j % side) if (Option(tiles(r)(c)).isDefined) { var (nextR, nextC, breek) = (r + yIncr, c + xIncr, false) while ((nextR >= 0 && nextR < side && nextC >= 0 && nextC < side) && !breek) { val (next, curr) = (tiles(nextR)(nextC),tiles(r)(c)) if (Option(next).isEmpty) if (checkingAvailableMoves) return true else { tiles(nextR)(nextC) = curr tiles(r)(c) = null r = nextR c = nextC nextR += yIncr nextC += xIncr moved = true } else if (next.canMergeWith(curr)) { if (checkingAvailableMoves) return true Game2048.highest = math.max(next.mergeWith(curr), Game2048.highest) tiles(r)(c) = null breek = true moved = true } else breek = true } } } if (moved) if (Game2048.highest < Game2048.target) { clearMerged() addRandomTile() if (!movesAvailable) gamestate = State.over } else if (Game2048.highest == Game2048.target) gamestate = State.won moved }   private def startGame(): Unit = { if (gamestate ne Game2048.State.running) { Game2048.highest = 0 gamestate = Game2048.State.running tiles = Array.ofDim[Tile](side, side) addRandomTile() addRandomTile() } }   private def addRandomTile(): Unit = { var pos = rand.nextInt(side * side) var (row, col) = (0, 0) do { pos = (pos + 1) % (side * side) row = pos / side col = pos % side } while (Option(tiles(row)(col)).isDefined) tiles(row)(col) = new Tile(if (rand.nextInt(10) == 0) 4 else 2) }   class Tile(var value: Int) { private var merged = false   def setMerged(): Unit = merged = false   def mergeWith(other: Tile): Int = if (canMergeWith(other)) { merged = true value *= 2 value } else -1   def canMergeWith(other: Tile): Boolean = !merged && Option(other).isDefined && !other.merged && value == other.value } }   object State extends Enumeration { type State = Value val start, won, running, over = Value }   }
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 down, pass it around 97 bottles of beer on the wall ... and so on, until reaching   0     (zero). Grammatical support for   1 bottle of beer   is optional. As with any puzzle, try to do it in as creative/concise/comical a way as possible (simple, obvious solutions allowed, too). Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet See also   http://99-bottles-of-beer.net/   Category:99_Bottles_of_Beer   Category:Programming language families   Wikipedia 99 bottles of beer
#Component_Pascal
Component Pascal
include "cowgol.coh";   sub Bottles(n: uint8) is if n == 0 then print("No more"); else print_i8(n); end if;   print(" bottle"); if n != 1 then print("s"); end if; end sub;   sub Verse(n: uint8) is Bottles(n); print(" of beer on the wall,\n"); Bottles(n); print(" of beer,\n"); print("Take "); if n == 1 then print("it"); else print("one"); end if; print(" down and pass it around,\n"); Bottles(n-1); print(" of beer on the wall.\n\n"); end sub;   var verse: uint8 := 99; while verse > 0 loop Verse(verse); verse := verse - 1; end loop;
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. The program should check then evaluate the expression. The goal is for the player to enter an expression that (numerically) evaluates to 24. Only the following operators/functions are allowed: multiplication, division, addition, subtraction Division should use floating point or rational arithmetic, etc, to preserve remainders. Brackets are allowed, if using an infix expression evaluator. Forming multiple digit numbers from the supplied digits is disallowed. (So an answer of 12+12 when given 1, 2, 2, and 1 is wrong). The order of the digits when given does not have to be preserved. Notes The type of expression evaluator used is not mandated. An RPN evaluator is equally acceptable for example. The task is not for the program to generate the expression, or test whether an expression is even possible. Related tasks 24 game/Solve Reference The 24 Game on h2g2.
#Potion
Potion
is_num = (s): x = s ord(0) if (x >= "0"ord && x <= "9"ord): true. else: false. .   nums = (s): res = () 0 to (s length, (b): c = s(b) if (is_num(c)): res push(c). .) res.   try = 1 while (true): r = rand string digits = (r(0),r(1),r(2),r(3)) "\nMy next four digits: " print digits join(" ") say digit_s = digits ins_sort string   ("Your expression to create 24 (try ", try, "): ") print entry = read slice(0,-1) expr = entry eval parse = nums(entry) parse_s = parse clone ins_sort string try++ if (parse length != 4): ("Wrong number of digits:", parse) say. elsif (parse_s != digit_s): ("Wrong digits:", parse) say. elsif (expr == 24): "You won!" say entry print, " => 24" say return(). else: (entry, " => ", expr string, " != 24") join("") say. .
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 ≤ A , B ≤ + 1000 ) {\displaystyle (-1000\leq A,B\leq +1000)} Output data The required output is one integer:   the sum of A and B. Example input   output   2 2 4 3 2 5
#Genie
Genie
[indent=4] /* A+B in Genie valac aplusb-genie.gs ./aplusb-genie */ init a:int64 = 0 b:int64 = 0 leftover:string = ""   print "Enter A and B, two numbers separated by space" line:string = stdin.read_line() res:bool = int64.try_parse(line, out a, out leftover) res = int64.try_parse(leftover, out b)   warning:string = " outside range (-1000, 1000), but it's ok, no one will tell" if a < -1000 or a > 1000 print "A" + warning if b < -1000 or b > 1000 print "B" + warning   print "From %s\nA + B = %llu", line, 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 sides of the blocks. The sample collection of 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) Task Write a function that takes a string (word) and determines whether the word can be spelled with the given collection of blocks. The rules are simple:   Once a letter on a block is used that block cannot be used again   The function should be case-insensitive   Show the output on this page for the following 7 words in the following example Example >>> can_make_word("A") True >>> can_make_word("BARK") True >>> can_make_word("BOOK") False >>> can_make_word("TREAT") True >>> can_make_word("COMMON") False >>> can_make_word("SQUAD") True >>> can_make_word("CONFUSE") True Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#R
R
blocks <- rbind(c("B","O"), c("X","K"), c("D","Q"), c("C","P"), c("N","A"), c("G","T"), c("R","E"), c("T","G"), c("Q","D"), c("F","S"), c("J","W"), c("H","U"), c("V","I"), c("A","N"), c("O","B"), c("E","R"), c("F","S"), c("L","Y"), c("P","C"), c("Z","M"))   canMake <- function(x) { x <- toupper(x) used <- rep(FALSE, dim(blocks)[1L]) charList <- strsplit(x, character(0)) tryChars <- function(chars, pos, used, inUse=NA) { if (pos > length(chars)) { TRUE } else { used[inUse] <- TRUE possible <- which(blocks == chars[pos] & !used, arr.ind=TRUE)[, 1L] any(vapply(possible, function(possBlock) tryChars(chars, pos + 1, used, possBlock), logical(1))) } } setNames(vapply(charList, tryChars, logical(1), 1L, used), x) } canMake(c("A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "CONFUSE"))
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 decide some strategy before any enter the room. Prisoners enter the room one by one, can open a drawer, inspect the card number in the drawer, then close the drawer. A prisoner can open no more than 50 drawers. A prisoner tries to find his own number. A prisoner finding his own number is then held apart from the others. If all 100 prisoners find their own numbers then they will all be pardoned. If any don't then all sentences stand. The task Simulate several thousand instances of the game where the prisoners randomly open drawers Simulate several thousand instances of the game where the prisoners use the optimal strategy mentioned in the Wikipedia article, of: First opening the drawer whose outside number is his prisoner number. If the card within has his number then he succeeds otherwise he opens the drawer with the same number as that of the revealed card. (until he opens his maximum). Show and compare the computed probabilities of success for the two strategies, here, on this page. References The unbelievable solution to the 100 prisoner puzzle standupmaths (Video). wp:100 prisoners problem 100 Prisoners Escape Puzzle DataGenetics. Random permutation statistics#One hundred prisoners on Wikipedia.
#Swift
Swift
import Foundation   struct PrisonersGame { let strategy: Strategy let numPrisoners: Int let drawers: [Int]   init(numPrisoners: Int, strategy: Strategy) { self.numPrisoners = numPrisoners self.strategy = strategy self.drawers = (1...numPrisoners).shuffled() }   @discardableResult func play() -> Bool { for num in 1...numPrisoners { guard findNumber(num) else { return false } }   return true }   private func findNumber(_ num: Int) -> Bool { var tries = 0 var nextDrawer = num - 1   while tries < 50 { tries += 1   switch strategy { case .random where drawers.randomElement()! == num: return true case .optimum where drawers[nextDrawer] == num: return true case .optimum: nextDrawer = drawers[nextDrawer] - 1 case _: continue } }   return false }   enum Strategy { case random, optimum } }   let numGames = 100_000 let lock = DispatchSemaphore(value: 1) var done = 0   print("Running \(numGames) games for each strategy")   DispatchQueue.concurrentPerform(iterations: 2) {i in let strat = i == 0 ? PrisonersGame.Strategy.random : .optimum var numPardoned = 0   for _ in 0..<numGames { let game = PrisonersGame(numPrisoners: 100, strategy: strat)   if game.play() { numPardoned += 1 } }   print("Probability of pardon with \(strat) strategy: \(Double(numPardoned) / Double(numGames))")   lock.wait() done += 1 lock.signal()   if done == 2 { exit(0) } }   dispatchMain()
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
#R
R
  puz15<-function(scramble.length=100){ m=matrix(c(1:15,0),byrow=T,ncol=4) scramble=sample(c("w","a","s","d"),scramble.length,replace=T) for(i in 1:scramble.length){ m=move(m,scramble[i]) } win=F turn=0 while(!win){ print.puz(m) newmove=getmove() if(newmove=="w"|newmove=="a"|newmove=="s"|newmove=="d"){ m=move(m,newmove) turn=turn+1 } else{ cat("Input not recognized","\n") } if(!(F %in% m==matrix(c(1:15,0),byrow=T,ncol=4))){ win=T } } print.puz(m) cat("\n") print("You win!") cat("\n","It took you",turn,"moves.","\n") }   getmove<-function(){ direction<-readline(prompt="Move:") return(direction) } move<-function(m,direction){ if(direction=="w"){ m=move.u(m) } else if(direction=="s"){ m=move.d(m) } else if(direction=="a"){ m=move.l(m) } else if(direction=="d"){ m=move.r(m) } return(m) } move.u<-function(m){ if(0 %in% m[4,]){} else{ pos=which(m==0) m[pos]=m[pos+1] m[pos+1]=0 } return(m) } move.d<-function(m){ if(0 %in% m[1,]){} else{ pos=which(m==0) m[pos]=m[pos-1] m[pos-1]=0 } return(m) } move.l<-function(m){ if(0 %in% m[,4]){return(m)} else{return(t(move.u(t(m))))} } move.r<-function(m){ if(0 %in% m[,1]){return(m)} else{return(t(move.d(t(m))))} } print.puz<-function(m){ cat("+----+----+----+----+","\n") for(r in 1:4){ string="|" for(c in 1:4){ if(m[r,c]==0) string=paste(string," |",sep="") else if(m[r,c]<10) string=paste(string," ",m[r,c]," |",sep="") else string=paste(string," ",m[r,c]," |",sep="") } cat(string,"\n","+----+----+----+----+","\n",sep="") } }