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/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.
#Seed7
Seed7
$ include "seed7_05.s7i"; include "console.s7i"; include "keybd.s7i";   const integer: boardLength is 4; const integer: boardSize is boardLength * boardLength; const integer: target is 2048;   const type: stateType is new struct var integer: fieldsOccupied is 0; var integer: largestNumber is 0; var integer: score is 0; var array array integer: board is boardLength times boardLength times 0; end struct;   const proc: addTile (inout stateType: state) is func local var integer: row is 0; var integer: col is 0; var integer: field is 2; begin if state.fieldsOccupied < boardSize then repeat col := rand(1, boardLength); row := rand(1, boardLength); until state.board[row][col] = 0; if rand(1, 10) = 10 then field := 4; end if; state.board[row][col] := field; incr(state.fieldsOccupied); state.largestNumber := max(field, state.largestNumber); end if; end func;   const proc: showBoard (in stateType: state) is func local var integer: row is 0; var integer: field is 0; begin writeln("┌────┬────┬────┬────┐"); for key row range state.board do for field range state.board[row] do if field = 0 then write("│ "); else write("│" <& field lpad (5 + length(str(field))) div 2 rpad 4); end if; end for; writeln("│"); if row < maxIdx(state.board) then writeln("├────┼────┼────┼────┤"); end if; end for; writeln("└────┴────┴────┴────┘"); end func;   const func boolean: doMove (inout stateType: state, in integer: startRow, in integer: startCol, in integer: deltaRow, in integer: deltaCol, in boolean: doMerge) is func result var boolean: boardChanged is FALSE; local const set of integer: boardRange is {1 .. boardLength}; var integer: row is 1; var integer: col is 1; var integer: nextRow is 0; var integer: nextCol is 0; begin row := startRow; col := startCol; while row in boardRange and col in boardRange do while row in boardRange and col in boardRange do nextRow := row + deltaRow; nextCol := col + deltaCol; if state.board[row][col] = 0 and nextRow in boardRange and nextCol in boardRange and state.board[nextRow][nextCol] <> 0 then boardChanged := TRUE; state.board[row][col] := state.board[nextRow][nextCol]; state.board[nextRow][nextCol] := 0; if row - deltaRow in boardRange and col - deltaCol in boardRange then nextRow := row - deltaRow; nextCol := col - deltaCol; end if; end if; row := nextRow; col := nextCol; end while;   if doMerge then if deltaRow <> 0 then row := startRow; elsif deltaCol <> 0 then col := startCol; end if; while row in boardRange and col in boardRange do nextRow := row + deltaRow; nextCol := col + deltaCol; if state.board[row][col] <> 0 and nextRow in boardRange and nextCol in boardRange and state.board[nextRow][nextCol] = state.board[row][col] then boardChanged := TRUE; state.board[row][col] *:= 2; state.largestNumber := max(state.board[row][col], state.largestNumber); state.score +:= state.board[row][col]; state.board[nextRow][nextCol] := 0; decr(state.fieldsOccupied); end if; row := nextRow; col := nextCol; end while; end if;   if deltaRow = 0 then incr(row); col := startCol; elsif deltaCol = 0 then incr(col); row := startRow; end if; end while; if doMerge and boardChanged then ignore(doMove(state, startRow, startCol, deltaRow, deltaCol, FALSE)); end if; end func;   const func boolean: canMove (in stateType: state) is func result var boolean: canMove is FALSE; local var integer: row is 0; var integer: col is 0; begin for row range 1 to boardLength until canMove do for col range 1 to boardLength until canMove do canMove := state.board[row][col] = 0 or (row < boardLength and state.board[row][col] = state.board[succ(row)][col]) or (col < boardLength and state.board[row][col] = state.board[row][succ(col)]); end for; end for; end func;   const proc: main is func local var stateType: state is stateType.value; var integer: highscore is 0; var char: command is ' '; var boolean: quit is FALSE; var boolean: moveOkay is FALSE; begin OUT := open(CONSOLE); addTile(state); repeat setPos(STD_CONSOLE, 1, 1); showBoard(state); highscore := max(highscore, state.score); writeln("Score = " <& state.score <& " Highscore = " <& highscore); if canMove(state) and state.largestNumber < target then writeln("Press arrow keys to move, R to Restart, Q to Quit"); elsif state.largestNumber >= target then writeln("You win! Press R to Restart, Q to Quit "); else writeln("Game over! Press R to Restart, Q to Quit "); end if; repeat moveOkay := FALSE; command := getc(KEYBOARD); case command of when {'r', 'R'}: state := stateType.value; clear(STD_CONSOLE); moveOkay := TRUE; when {'q', 'Q'}: moveOkay := TRUE; quit := TRUE; when {KEY_LEFT}: moveOkay := doMove(state, 1, 1, 0, 1, TRUE); when {KEY_RIGHT}: moveOkay := doMove(state, 1, boardLength, 0, -1, TRUE); when {KEY_UP}: moveOkay := doMove(state, 1, 1, 1, 0, TRUE); when {KEY_DOWN}: moveOkay := doMove(state, boardLength, 1, -1, 0, TRUE); end case; if moveOkay and not quit then addTile(state); end if; until moveOkay; until quit; end func;
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
#Cowgol
Cowgol
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.
#PowerShell
PowerShell
  CLS   Function isNumeric ($x) { $x2 = 0 $isNum = [System.Int32]::TryParse($x,[ref]$x2) Return $isNum }   $NumberArray = @() While( $NumberArray.Count -lt 4 ){ $NumberArray += Random -Minimum 1 -Maximum 10 }   Write-Host @" Welcome to the 24 game!   Here are your numbers: $($NumberArray -join ","). Use division, multiplication, subtraction and addition to get 24 as a result with these 4 numbers. "@   Do { $Wrong = 0 $EndResult = $null $TempChar = $null $TempChar2 = $null $Count = $null   $AllowableCharacters = $NumberArray + "+-*/()".ToCharArray() $Result = Read-Host Foreach($Char in $Result.ToCharArray()) { If( $AllowableCharacters -notcontains $Char ){ $Wrong = 1 } }   If($Wrong -eq 1) { Write-Warning "Wrong input! Please use only the given numbers." } Foreach($Char in $Result.ToCharArray()) { If((IsNumeric $TempChar) -AND (IsNumeric $Char)) { Write-Warning "Wrong input! Combining two or more numbers together is not allowed!" } $TempChar = $Char } Foreach($Char in $Result.ToCharArray()) { If(IsNumeric $Char) { $Count++ } } If($Count -eq 4) { $EndResult = Invoke-Expression $Result If($EndResult -eq 24) { Write-Host "`nYou've won the game!" } Else { Write-Host "`n$EndResult is not 24! Too bad." } } Else { Write-Warning "Wrong input! You did not supply four numbers." } } While($EndResult -ne 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
#GML
GML
var add, a, b; add = argument0; // get the string with the numbers to add a = real(string_copy(add, 1, string_pos(" ", add))); b = real(string_copy(add, string_pos(" ", add) + 1, string_length(add) - string_pos(" ", add))); return(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
#Racket
Racket
#lang racket (define block-strings (list "BO" "XK" "DQ" "CP" "NA" "GT" "RE" "TG" "QD" "FS" "JW" "HU" "VI" "AN" "OB" "ER" "FS" "LY" "PC" "ZM")) (define BLOCKS (map string->list block-strings))   (define (can-make-word? w) (define (usable-block blocks word-char) (for/first ((b (in-list blocks)) #:when (memf (curry char-ci=? word-char) b)) b))   (define (inner word-chars blocks tried-blocks) (cond [(null? word-chars) #t] [(usable-block blocks (car word-chars)) => (lambda (b) (or (inner (cdr word-chars) (append tried-blocks (remove b blocks)) null) (inner word-chars (remove b blocks) (cons b tried-blocks))))] [else #f])) (inner (string->list w) BLOCKS null))   (define WORD-LIST '("" "A" "BARK" "BOOK" "TREAT" "COMMON" "SQUAD" "CONFUSE")) (define (report-word w) (printf "Can we make: ~a? ~a~%" (~s w #:min-width 9) (if (can-make-word? w) "yes" "no")))   (module+ main (for-each report-word WORD-LIST))   (module+ test (require rackunit) (check-true (can-make-word? "")) (check-true (can-make-word? "A")) (check-true (can-make-word? "BARK")) (check-false (can-make-word? "BOOK")) (check-true (can-make-word? "TREAT")) (check-false (can-make-word? "COMMON")) (check-true (can-make-word? "SQUAD")) (check-true (can-make-word? "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.
#Tcl
Tcl
set Samples 10000 set Prisoners 100 set MaxGuesses 50 set Strategies {random optimal}   # returns a random number between 0 and N-1. proc random {n} { expr int(rand()*$n) }   # Returns a list from 0 to N-1. proc range {n} { set res {} for {set i 0} {$i < $n} {incr i} { lappend res $i } return $res }   # Returns shuffled LIST. proc nshuffle {list} { set len [llength $list] while {$len} { set n [expr {int($len * rand())}] set tmp [lindex $list $n] lset list $n [lindex $list [incr len -1]] lset list $len $tmp } return $list }   # Returns a list of shuffled drawers. proc buildDrawers {} { global Prisoners nshuffle [range $Prisoners] }   # Returns true if P is found in DRAWERS within $MaxGuesses attempts using a # random strategy. proc randomStrategy {drawers p} { global Prisoners MaxGuesses foreach i [range $MaxGuesses] { if {$p == [lindex $drawers [random $Prisoners]]} { return 1 } } return 0 }   # Returns true if P is found in DRAWERS within $MaxGuesses attempts using an # optimal strategy. proc optimalStrategy {drawers p} { global Prisoners MaxGuesses set j $p foreach i [range $MaxGuesses] { set k [lindex $drawers $j] if {$k == $p} { return 1 } set j $k } return 0 }   # Returns true if all prisoners find their number using the given STRATEGY. proc run100prisonersProblem {strategy} { global Prisoners set drawers [buildDrawers] foreach p [range $Prisoners] { if {![$strategy $drawers $p]} { return 0 } } return 1 }   # Runs the given STRATEGY $Samples times and returns the number of times all # prisoners succeed. proc sampling {strategy} { global Samples set successes 0 foreach s [range $Samples] { if {[run100prisonersProblem $strategy]} { incr successes } } return $successes }   # Returns true if the given STRING starts with a vowel. proc startsWithVowel {string} { expr [lsearch -exact {a e i o u} [string index $string 0]] >= 0 }   # Runs each of the STRATEGIES and prints a report on how well they # worked. proc compareStrategies {strategies} { global Samples set fmt "Using %s %s strategy, the prisoners were freed in %5.2f%% of the cases." foreach strategy $strategies { set article [expr [startsWithVowel $strategy] ? {"an"} : {"a"}] set pct [expr [sampling ${strategy}Strategy] / $Samples.0 * 100] puts [format $fmt $article $strategy $pct] } }   compareStrategies $Strategies
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
#Racket
Racket
#lang racket/base (require 2htdp/universe 2htdp/image racket/list racket/match)   (define ((fifteen->pict (finished? #f)) fifteen) (for/fold ((i (empty-scene 0 0))) ((r 4)) (define row (for/fold ((i (empty-scene 0 0))) ((c 4)) (define v (list-ref fifteen (+ (* r 4) c))) (define cell (if v (overlay/align "center" "center" (rectangle 50 50 'outline (if finished? "white" "blue")) (text (number->string v) 30 "black")) (rectangle 50 50 'solid (if finished? "white" "powderblue")))) (beside i cell))) (above i row)))   (define (move-space fifteen direction) (define idx (for/first ((i (in-naturals)) (x fifteen) #:unless x) i)) (define-values (row col) (quotient/remainder idx 4)) (define dest (+ idx (match direction ['l #:when (> col 0) -1] ['r #:when (< col 3) 1] ['u #:when (> row 0) -4] ['d #:when (< row 3) 4] [else 0]))) (list-set (list-set fifteen idx (list-ref fifteen dest)) dest #f))   (define (key-move-space fifteen a-key) (cond [(key=? a-key "left") (move-space fifteen 'l)] [(key=? a-key "right") (move-space fifteen 'r)] [(key=? a-key "up") (move-space fifteen 'u)] [(key=? a-key "down") (move-space fifteen 'd)] [else fifteen]))   (define (shuffle-15 fifteen shuffles) (for/fold ((rv fifteen)) ((_ shuffles)) (move-space rv (list-ref '(u d l r) (random 4)))))   (define fifteen0 '(1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 #f))   (define (solved-world? w) (equal? w fifteen0))   (big-bang (shuffle-15 fifteen0 200) (name "Fifteen") (to-draw (fifteen->pict)) (stop-when solved-world? (fifteen->pict #t)) (on-key key-move-space))
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.
#Tcl
Tcl
  # A minimal implementation of the game 2048 in Tcl. # For a maintained version with expanded functionality see # https://tcl.wiki/40557. package require Tcl 8.5 package require struct::matrix package require struct::list   # Board size. set size 4   # Iterate over all cells of the game board and run script for each. # # The game board is a 2D matrix of a fixed size that consists of elements # called "cells" that each can contain a game tile (corresponds to numerical # values of 2, 4, 8, ..., 2048) or nothing (zero). # # - cellList is a list of cell indexes (coordinates), which are # themselves lists of two numbers each. They each represent the location # of a given cell on the board. # - varName1 are varName2 are names of the variables the will be assigned # the index values. # - cellVarName is the name of the variable that at each step of iteration # will contain the numerical value of the present cell. Assigning to it will # change the cell's value. # - script is the script to run. proc forcells {cellList varName1 varName2 cellVarName script} { upvar $varName1 i upvar $varName2 j upvar $cellVarName c foreach cell $cellList { set i [lindex $cell 0] set j [lindex $cell 1] set c [cell-get $cell] uplevel $script cell-set "$i $j" $c } }   # Generate a list of cell indexes for all cells on the board, i.e., # {{0 0} {0 1} ... {0 size-1} {1 0} {1 1} ... {size-1 size-1}}. proc cell-indexes {} { global size set list {} foreach i [::struct::list iota $size] { foreach j [::struct::list iota $size] { lappend list [list $i $j] } } return $list }   # Check if a number is a valid cell index (is 0 to size-1). proc valid-index {i} { global size expr {0 <= $i && $i < $size} }   # Return 1 if the predicate pred is true when applied to all items on the list # or 0 otherwise. proc map-and {list pred} { set res 1 foreach item $list { set res [expr {$res && [$pred $item]}] if {! $res} break } return $res }   # Check if list represents valid cell coordinates. proc valid-cell? cell { map-and $cell valid-index }   # Get the value of a game board cell. proc cell-get cell { board get cell {*}$cell }   # Set the value of a game board cell. proc cell-set {cell value} { board set cell {*}$cell $value }   # Filter a list of board cell indexes cellList to only have those indexes # that correspond to empty board cells. proc empty {cellList} {  ::struct::list filterfor x $cellList {[cell-get $x] == 0} }   # Pick a random item from the given list. proc pick list { lindex $list [expr {int(rand() * [llength $list])}] }   # Put a "2" into an empty cell on the board. proc spawn-new {} { set emptyCell [pick [empty [cell-indexes]]] if {[llength $emptyCell] > 0} { forcells [list $emptyCell] i j cell { set cell 2 } } return $emptyCell }   # Return vector sum of lists v1 and v2. proc vector-add {v1 v2} { set result {} foreach a $v1 b $v2 { lappend result [expr {$a + $b}] } return $result }   # If checkOnly is false try to shift all cells one step in the direction of # directionVect. If checkOnly is true just say if that move is possible. proc move-all {directionVect {checkOnly 0}} { set changedCells 0   forcells [cell-indexes] i j cell { set newIndex [vector-add "$i $j" $directionVect] set removedStar 0   # For every nonempty source cell and valid destination cell... if {$cell != 0 && [valid-cell? $newIndex]} { if {[cell-get $newIndex] == 0} { # Destination is empty. if {$checkOnly} { # -level 2 is to return from both forcells and move-all. return -level 2 true } else { # Move tile to empty cell. cell-set $newIndex $cell set cell 0 incr changedCells } } elseif {([cell-get $newIndex] eq $cell) && [string first + $cell] == -1} { # Destination is the same number as source. if {$checkOnly} { return -level 2 true } else { # When merging two tiles into one mark the new tile with # the marker of "+" to ensure it doesn't get combined # again this turn. cell-set $newIndex [expr {2 * $cell}]+ set cell 0 incr changedCells } } } }   if {$checkOnly} { return false }   # Remove "changed this turn" markers at the end of the turn. if {$changedCells == 0} { forcells [cell-indexes] i j cell { set cell [string trim $cell +] } } return $changedCells }   # Is it possible to move any tiles in the direction of directionVect? proc can-move? {directionVect} { move-all $directionVect 1 }   # Check win condition. The player wins when there's a 2048 tile. proc check-win {} { forcells [cell-indexes] i j cell { if {$cell == 2048} { puts "You win!" exit 0 } } }   # Check lose condition. The player loses when the win condition isn't met and # there are no possible moves. proc check-lose {possibleMoves} { set values [dict values $possibleMoves] if {!(true in $values || 1 in $values)} { puts "You lose." exit 0 } }   # Pretty-print the board. Specify an index in highlight to highlight a cell. proc print-board {{highlight {-1 -1}}} { forcells [cell-indexes] i j cell { if {$j == 0} { puts "" } puts -nonewline [ if {$cell != 0} { if {[::struct::list equal "$i $j" $highlight]} { format "\[%4s\]" $cell* } else { format "\[%4s\]" $cell }   } else { lindex "......" } ] } puts "\n" }   proc main {} { global size   struct::matrix board   # Generate an empty board of a given size. board add columns $size board add rows $size forcells [cell-indexes] i j cell { set cell 0 }   set controls { h {0 -1} j {1 0} k {-1 0} l {0 1} }   # Game loop. while true { set playerMove 0 set possibleMoves {}   # Add new tile to the board and print the board highlighting this tile. print-board [spawn-new]   check-win   # Find possible moves. foreach {button vector} $controls { dict set possibleMoves $button [can-move? $vector] } check-lose $possibleMoves   # Get valid input from the player. while {$playerMove == 0} { # Print prompt. puts -nonewline "Move (" foreach {button vector} $controls { if {[dict get $possibleMoves $button]} { puts -nonewline $button } } puts ")?"   set playerInput [gets stdin]   # Validate input. if {[dict exists $possibleMoves $playerInput] && [dict get $possibleMoves $playerInput]} { set playerMove [dict get $controls $playerInput] } }   # Apply current move until no changes occur on the board. while true { if {[move-all $playerMove] == 0} break } } }   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
#Crystal
Crystal
99.downto(1) do |n| puts "#{n} bottle#{n > 1 ? "s" : ""} of beer on the wall" puts "#{n} bottle#{n > 1 ? "s" : ""} of beer" puts "Take one down, pass it around" puts "#{n-1} bottle#{n > 2 ? "s" : ""} of beer on the wall\n\n" if n > 1 end puts "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.
#ProDOS
ProDOS
:a editvar /modify -random- = <10 printline These are your four digits: -random- -random- -random- -random- printline Use an algorithm to make the number 24. editvar /newvar /value=a /userinput=1 /title=Algorithm: do -a- if -a- /hasvalue 24 printline Your algorithm worked! & goto :b ( ) else printline Your algorithm did not work. :b editvar /newvar /value=b /userinput=1 /title=Do you want to play again? if -b- /hasvalue y goto :a else exitcurrentprogram
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
#Go
Go
package main   import "fmt"   func main() { var a, b int fmt.Scan(&a, &b) fmt.Println(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
#Raku
Raku
multi can-spell-word(Str $word, @blocks) { my @regex = @blocks.map({ my @c = .comb; rx/<@c>/ }).grep: { .ACCEPTS($word.uc) } can-spell-word $word.uc.comb.list, @regex; }   multi can-spell-word([$head,*@tail], @regex) { for @regex -> $re { if $head ~~ $re { return True unless @tail; return False if @regex == 1; return True if can-spell-word @tail, list @regex.grep: * !=== $re; } } False; }   my @b = <BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM>;   for <A BaRK BOoK tREaT COmMOn SqUAD CoNfuSE> { say "$_ &can-spell-word($_, @b)"; }
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.
#Transact-SQL
Transact-SQL
USE rosettacode; GO   SET NOCOUNT ON; GO   CREATE TABLE dbo.numbers (n INT PRIMARY KEY); GO   -- NOTE If you want to play more than 10000 games, you need to extend the query generating the numbers table by adding -- next cross joins. Now the table contains enough values to solve the task and it takes less processing time.   WITH sample100 AS ( SELECT TOP(100) object_id FROM master.sys.objects ) INSERT numbers SELECT ROW_NUMBER() OVER (ORDER BY A.object_id) AS n FROM sample100 AS A CROSS JOIN sample100 AS B; GO   CREATE TABLE dbo.drawers (drawer INT PRIMARY KEY, card INT); GO   CREATE TABLE dbo.results (strategy VARCHAR(10), game INT, result BIT, PRIMARY KEY (game, strategy)); GO   CREATE PROCEDURE dbo.shuffleDrawers @prisonersCount INT AS BEGIN SET NOCOUNT ON;   IF NOT EXISTS (SELECT * FROM drawers) INSERT drawers (drawer, card) SELECT n AS drawer, n AS card FROM numbers WHERE n <= @prisonersCount;   DECLARE @randoms TABLE (n INT, random INT); DECLARE @n INT = 1; WHILE @n <= @prisonersCount BEGIN INSERT @randoms VALUES (@n, ROUND(RAND() * (@prisonersCount - 1), 0) + 1);   SET @n = @n + 1; END;   WITH ordered AS ( SELECT ROW_NUMBER() OVER (ORDER BY random ASC) AS drawer, n AS card FROM @randoms ) UPDATE drawers SET card = o.card FROM drawers AS s INNER JOIN ordered AS o ON o.drawer = s.drawer; END GO   CREATE PROCEDURE dbo.find @prisoner INT, @strategy VARCHAR(10) AS BEGIN -- A prisoner can open no more than 50 drawers. DECLARE @drawersCount INT = (SELECT COUNT(*) FROM drawers); DECLARE @openMax INT = @drawersCount / 2;   -- Prisoners start outside the room. DECLARE @card INT = NULL; DECLARE @open INT = 1; WHILE @open <= @openMax BEGIN -- A prisoner tries to find his own number. IF @strategy = 'random' BEGIN DECLARE @random INT = ROUND(RAND() * (@drawersCount - 1), 0) + 1; SET @card = (SELECT TOP(1) card FROM drawers WHERE drawer = @random); END IF @strategy = 'optimal' BEGIN IF @card IS NULL BEGIN SET @card = (SELECT TOP(1) card FROM drawers WHERE drawer = @prisoner); END ELSE BEGIN SET @card = (SELECT TOP(1) card FROM drawers WHERE drawer = @card); END END   -- A prisoner finding his own number is then held apart from the others. IF @card = @prisoner RETURN 1;   SET @open = @open + 1; END   RETURN 0; END GO   CREATE PROCEDURE dbo.playGame @gamesCount INT, @strategy VARCHAR(10), @prisonersCount INT = 100 AS BEGIN SET NOCOUNT ON;   IF @gamesCount <> (SELECT COUNT(*) FROM results WHERE strategy = @strategy) BEGIN DELETE results WHERE strategy = @strategy;   INSERT results (strategy, game, result) SELECT @strategy AS strategy, n AS game, 0 AS result FROM numbers WHERE n <= @gamesCount; END   UPDATE results SET result = 0 WHERE strategy = @strategy;   DECLARE @game INT = 1; WHILE @game <= @gamesCount BEGIN -- 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. EXECUTE shuffleDrawers @prisonersCount;   -- A prisoner tries to find his own number. -- Prisoners start outside the room. -- They can decide some strategy before any enter the room. DECLARE @prisoner INT = 1; DECLARE @found INT = 0; WHILE @prisoner <= @prisonersCount BEGIN EXECUTE @found = find @prisoner, @strategy; IF @found = 1 SET @prisoner = @prisoner + 1; ELSE BREAK; END;   -- If all 100 findings find their own numbers then they will all be pardoned. If any don't then all sentences stand. IF @found = 1 UPDATE results SET result = 1 WHERE strategy = @strategy AND game = @game;   SET @game = @game + 1; END END GO   CREATE FUNCTION dbo.computeProbability(@strategy VARCHAR(10)) RETURNS decimal (18, 2) AS BEGIN RETURN ( SELECT (SUM(CAST(result AS INT)) * 10000 / COUNT(*)) / 100 FROM results WHERE strategy = @strategy ); END GO   -- Simulate several thousand instances of the game: DECLARE @gamesCount INT = 2000;   -- ...where the prisoners randomly open drawers. EXECUTE playGame @gamesCount, 'random';   -- ...where the prisoners use the optimal strategy mentioned in the Wikipedia article. EXECUTE playGame @gamesCount, 'optimal';   -- Show and compare the computed probabilities of success for the two strategies. DECLARE @log VARCHAR(max); SET @log = CONCAT('Games count: ', @gamesCount); RAISERROR (@log, 0, 1) WITH NOWAIT; SET @log = CONCAT('Probability of success with "random" strategy: ', dbo.computeProbability('random')); RAISERROR (@log, 0, 1) WITH NOWAIT; SET @log = CONCAT('Probability of success with "optimal" strategy: ', dbo.computeProbability('optimal')); RAISERROR (@log, 0, 1) WITH NOWAIT; GO   DROP FUNCTION dbo.computeProbability; DROP PROCEDURE dbo.playGame; DROP PROCEDURE dbo.find; DROP PROCEDURE dbo.shuffleDrawers; DROP TABLE dbo.results; DROP TABLE dbo.drawers; DROP TABLE dbo.numbers; GO
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
#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 $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 @solved = [1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,' ']; my @board; new();   sub new () { loop { @board = shuffle(); last if parity-ok(@board); } }   sub parity-ok (@b) { my $row = @b.first(/' '/,:k); my $col = @b[$row].first(/' '/,:k); so ([3,3] <<->> [$row,$col]).sum %% 2; }   sub shuffle () { my @c = [1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,' ']; for (^16).pick(*) -> $y, $x { my ($yd, $ym, $xd, $xm) = ($y div n, $y mod n, $x div n, $x mod n); @(@c[$ym;$yd],@c[$xm;$xd]) = @(@c[$xm;$xd],@c[$ym;$yd]); } @c; }   sub row (@row) { '│' ~ (join '│', @row».&center) ~ '│' }   sub center ($s){ my $c = cell - $s.chars; my $pad = ' ' x ceiling($c/2); sprintf "%{cell}s", "$s$pad"; }   sub draw-board { run('clear'); print qq:to/END/;     Press direction arrows to move.   Press q to quit. Press n for a new puzzle.   $top { join "\n\t$mid\n\t", map { .&row }, @board } $bot   { (so @board ~~ @solved) ?? 'Solved!!' !! '' } END }   sub slide (@c is copy) { my $t = (grep { /' '/ }, :k, @c)[0]; return @c unless $t and $t > 0; @c[$t,$t-1] = @c[$t-1,$t]; @c; }   proto sub move (|) {*};   multi move('up') { map { @board[*;$_] = reverse slide reverse @board[*;$_] }, ^n; }   multi move('down') { map { @board[*;$_] = slide @board[*;$_] }, ^n; }   multi move('left') { map { @board[$_] = reverse slide reverse @board[$_] }, ^n; }   multi move('right') { map { @board[$_] = slide @board[$_] }, ^n; }   loop { draw-board;   # 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 new() if $key eq '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.
#Visual_Basic_.NET
Visual Basic .NET
Friend Class Tile Public Sub New() Me.Value = 0 Me.IsBlocked = False End Sub Public Property Value As Integer Public Property IsBlocked As Boolean End Class   Friend Enum MoveDirection Up Down Left Right End Enum   Friend Class G2048 Public Sub New() _isDone = False _isWon = False _isMoved = True _score = 0 InitializeBoard() End Sub   Private Sub InitializeBoard() For y As Integer = 0 To 3 For x As Integer = 0 To 3 _board(x, y) = New Tile() Next Next End Sub   Private _isDone As Boolean Private _isWon As Boolean Private _isMoved As Boolean Private _score As Integer Private ReadOnly _board As Tile(,) = New Tile(3, 3) {} Private ReadOnly _rand As Random = New Random() Const empty As String = " "   Public Sub [Loop]() AddTile() While True If _isMoved Then AddTile() DrawBoard() If _isDone Then Exit While WaitKey() End While Dim endMessage As String = If(_isWon, "You've made it!", "Game Over!") Console.WriteLine(endMessage) End Sub   Public Sub DrawBoard() Console.Clear() Console.WriteLine("Score: " & _score & vbNewLine) For y As Integer = 0 To 3 Console.WriteLine("+------+------+------+------+") Console.Write("| ") For x As Integer = 0 To 3 If _board(x, y).Value = 0 Then Console.Write(empty.PadRight(4)) Else Console.Write(_board(x, y).Value.ToString().PadRight(4)) End If Console.Write(" | ") Next Console.WriteLine() Next Console.WriteLine("+------+------+------+------+" & vbNewLine & vbNewLine) End Sub   Private Sub WaitKey() _isMoved = False Console.WriteLine("(W) Up (S) Down (A) Left (D) Right") Dim input As Char Char.TryParse(Console.ReadKey().Key.ToString(), input) Select Case input Case "W"c Move(MoveDirection.Up) Case "A"c Move(MoveDirection.Left) Case "S"c Move(MoveDirection.Down) Case "D"c Move(MoveDirection.Right) End Select For y As Integer = 0 To 3 For x As Integer = 0 To 3 _board(x, y).IsBlocked = False Next Next End Sub   Private Sub AddTile() For y As Integer = 0 To 3 For x As Integer = 0 To 3 If _board(x, y).Value <> 0 Then Continue For Dim a As Integer, b As Integer Do a = _rand.Next(0, 4) b = _rand.Next(0, 4) Loop While _board(a, b).Value <> 0 Dim r As Double = _rand.NextDouble() _board(a, b).Value = If(r > 0.89F, 4, 2) If CanMove() Then Return Next Next _isDone = True End Sub   Private Function CanMove() As Boolean For y As Integer = 0 To 3 For x As Integer = 0 To 3 If _board(x, y).Value = 0 Then Return True Next Next For y As Integer = 0 To 3 For x As Integer = 0 To 3 If TestAdd(x + 1, y, _board(x, y).Value) OrElse TestAdd(x - 1, y, _board(x, y).Value) OrElse TestAdd(x, y + 1, _board(x, y).Value) OrElse TestAdd(x, y - 1, _board(x, y).Value) Then Return True Next Next Return False End Function   Private Function TestAdd(ByVal x As Integer, ByVal y As Integer, ByVal value As Integer) As Boolean If x < 0 OrElse x > 3 OrElse y < 0 OrElse y > 3 Then Return False Return _board(x, y).Value = value End Function   Private Sub MoveVertically(ByVal x As Integer, ByVal y As Integer, ByVal d As Integer) If _board(x, y + d).Value <> 0 AndAlso _board(x, y + d).Value = _board(x, y).Value AndAlso Not _board(x, y).IsBlocked AndAlso Not _board(x, y + d).IsBlocked Then _board(x, y).Value = 0 _board(x, y + d).Value *= 2 _score += _board(x, y + d).Value _board(x, y + d).IsBlocked = True _isMoved = True ElseIf _board(x, y + d).Value = 0 AndAlso _board(x, y).Value <> 0 Then _board(x, y + d).Value = _board(x, y).Value _board(x, y).Value = 0 _isMoved = True End If If d > 0 Then If y + d < 3 Then MoveVertically(x, y + d, 1) Else If y + d > 0 Then MoveVertically(x, y + d, -1) End If End Sub   Private Sub MoveHorizontally(ByVal x As Integer, ByVal y As Integer, ByVal d As Integer) If _board(x + d, y).Value <> 0 AndAlso _board(x + d, y).Value = _board(x, y).Value AndAlso Not _board(x + d, y).IsBlocked AndAlso Not _board(x, y).IsBlocked Then _board(x, y).Value = 0 _board(x + d, y).Value *= 2 _score += _board(x + d, y).Value _board(x + d, y).IsBlocked = True _isMoved = True ElseIf _board(x + d, y).Value = 0 AndAlso _board(x, y).Value <> 0 Then _board(x + d, y).Value = _board(x, y).Value _board(x, y).Value = 0 _isMoved = True End If If d > 0 Then If x + d < 3 Then MoveHorizontally(x + d, y, 1) Else If x + d > 0 Then MoveHorizontally(x + d, y, -1) End If End Sub   Private Sub Move(ByVal direction As MoveDirection) Select Case direction Case MoveDirection.Up For x As Integer = 0 To 3 Dim y As Integer = 1 While y < 4 If _board(x, y).Value <> 0 Then MoveVertically(x, y, -1) y += 1 End While Next Case MoveDirection.Down For x As Integer = 0 To 3 Dim y As Integer = 2 While y >= 0 If _board(x, y).Value <> 0 Then MoveVertically(x, y, 1) y -= 1 End While Next Case MoveDirection.Left For y As Integer = 0 To 3 Dim x As Integer = 1 While x < 4 If _board(x, y).Value <> 0 Then MoveHorizontally(x, y, -1) x += 1 End While Next Case MoveDirection.Right For y As Integer = 0 To 3 Dim x As Integer = 2 While x >= 0 If _board(x, y).Value <> 0 Then MoveHorizontally(x, y, 1) x -= 1 End While Next End Select End Sub End Class   Module Module1 Sub Main() RunGame() End Sub   Private Sub RunGame() Dim game As G2048 = New G2048() game.Loop() CheckRestart() End Sub   Private Sub CheckRestart() Console.WriteLine("(N) New game (P) Exit") While True Dim input As Char Char.TryParse(Console.ReadKey().Key.ToString(), input) Select Case input Case "N"c RunGame() Case "P"c Return Case Else ClearLastLine() End Select End While End Sub   Private Sub ClearLastLine() Console.SetCursorPosition(0, Console.CursorTop) Console.Write(New String(" ", Console.BufferWidth)) Console.SetCursorPosition(0, Console.CursorTop - 1) End Sub End Module  
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
#D
D
import std.stdio;   void main() { int bottles = 99;   while (bottles > 1) { writeln(bottles, " bottles of beer on the wall,"); writeln(bottles, " bottles of beer."); writeln("Take one down, pass it around,"); if (--bottles > 1) { writeln(bottles, " bottles of beer on the wall.\n"); } } writeln("1 bottle of beer on the wall.\n");   writeln("No more bottles of beer on the wall,"); writeln("no more bottles of beer."); writeln("Go to the store and buy some more,"); writeln("99 bottles of beer on the wall."); }
http://rosettacode.org/wiki/24_game
24 game
The 24 Game tests one's mental arithmetic. Task Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed. The program should prompt for the player to enter an arithmetic expression using just those, and all of those four digits, used exactly once each. 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.
#Prolog
Prolog
:- initialization(main).     answer(24). play :- round, play ; true.   round :- prompt(Ns), get_line(Input), Input \= "stop" , ( phrase(parse(Ns,[]), Input) -> Result = 'correct' ; Result = 'wrong' ), write(Result), nl, nl . % where prompt(Ns) :- length(Ns,4), maplist(random(1,10), Ns) , write('Digits: '), write(Ns), nl .   parse([],[X]) --> { answer(X) }. parse(Ns,[Y,X|S]) --> "+", { Z is X + Y }, parse(Ns,[Z|S]). parse(Ns,[Y,X|S]) --> "-", { Z is X - Y }, parse(Ns,[Z|S]). parse(Ns,[Y,X|S]) --> "*", { Z is X * Y }, parse(Ns,[Z|S]). parse(Ns,[Y,X|S]) --> "/", { Z is X div Y }, parse(Ns,[Z|S]). parse(Ns,Stack) --> " ", parse(Ns,Stack). parse(Ns,Stack) --> { select(N,Ns,Ns1), number_codes(N,[Code]) } , [Code], parse(Ns1,[N|Stack]) .   get_line(Xs) :- get_code(X) , ( X == 10 -> Xs = [] ; Xs = [X|Ys], get_line(Ys) ) . main :- randomize, play, halt.
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
#Golfscript
Golfscript
~+
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
#RapidQ
RapidQ
dim Blocks as string dim InWord as string   Function CanMakeWord (FInWord as string, FBlocks as string) as integer dim WIndex as integer, BIndex as integer   FBlocks = UCase$(FBlocks) - " " - "," FInWord = UCase$(FInWord)   for WIndex = 1 to len(FInWord) BIndex = instr(FBlocks, FInWord[WIndex])   if BIndex then FBlocks = Replace$(FBlocks,"**",iif(BIndex mod 2,BIndex,BIndex-1)) else Result = 0 exit function end if next   Result = 1 end function   InWord = "Confuse" Blocks = "BO, XK, DQ, CP, NA, GT, RE, TG, QD, FS, JW, HU, VI, AN, OB, ER, FS, LY, PC, ZM" showmessage "Can make: " + InWord + " = " + iif(CanMakeWord(InWord, Blocks), "True", "False")  
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.
#VBA.2FVisual_Basic
VBA/Visual Basic
Sub HundredPrisoners()   NumberOfPrisoners = Int(InputBox("Number of Prisoners", "Prisoners", 100)) Tries = Int(InputBox("Numer of Tries", "Tries", 1000)) Selections = Int(InputBox("Number of Selections", "Selections", NumberOfPrisoners / 2))   StartTime = Timer   AllFoundOptimal = 0 AllFoundRandom = 0 AllFoundRandomMem = 0   For i = 1 To Tries OptimalCount = HundredPrisoners_Optimal(NumberOfPrisoners, Selections) RandomCount = HundredPrisoners_Random(NumberOfPrisoners, Selections) RandomMemCount = HundredPrisoners_Random_Mem(NumberOfPrisoners, Selections)   If OptimalCount = NumberOfPrisoners Then AllFoundOptimal = AllFoundOptimal + 1 End If If RandomCount = NumberOfPrisoners Then AllFoundRandom = AllFoundRandom + 1 End If If RandomMemCount = NumberOfPrisoners Then AllFoundRandomMem = AllFoundRandomMem + 1 End If Next i     ResultString = "Optimal: " & AllFoundOptimal & " of " & Tries & ": " & AllFoundOptimal / Tries * 100 & "%" ResultString = ResultString & Chr(13) & "Random: " & AllFoundRandom & " of " & Tries & ": " & AllFoundRandom / Tries * 100 & "%" ResultString = ResultString & Chr(13) & "RandomMem: " & AllFoundRandomMem & " of " & Tries & ": " & AllFoundRandomMem / Tries * 100 & "%"   EndTime = Timer   ResultString = ResultString & Chr(13) & "Elapsed Time: " & Round(EndTime - StartTime, 2) & " s" ResultString = ResultString & Chr(13) & "Trials/sec: " & Tries / Round(EndTime - StartTime, 2)   MsgBox ResultString, vbOKOnly, "Results"   End Sub   Function HundredPrisoners_Optimal(ByVal NrPrisoners, ByVal NrSelections) As Long Dim DrawerArray() As Long   ReDim DrawerArray(NrPrisoners - 1)   For Counter = LBound(DrawerArray) To UBound(DrawerArray) DrawerArray(Counter) = Counter + 1 Next Counter   FisherYates DrawerArray   For i = 1 To NrPrisoners NumberFromDrawer = DrawerArray(i - 1) For j = 1 To NrSelections - 1 If NumberFromDrawer = i Then FoundOwnNumber = FoundOwnNumber + 1 Exit For End If NumberFromDrawer = DrawerArray(NumberFromDrawer - 1) Next j Next i HundredPrisoners_Optimal = FoundOwnNumber End Function   Function HundredPrisoners_Random(ByVal NrPrisoners, ByVal NrSelections) As Long Dim DrawerArray() As Long ReDim DrawerArray(NrPrisoners - 1)   FoundOwnNumber = 0   For Counter = LBound(DrawerArray) To UBound(DrawerArray) DrawerArray(Counter) = Counter + 1 Next Counter   FisherYates DrawerArray     For i = 1 To NrPrisoners For j = 1 To NrSelections RandomDrawer = Int(NrPrisoners * Rnd) NumberFromDrawer = DrawerArray(RandomDrawer) If NumberFromDrawer = i Then FoundOwnNumber = FoundOwnNumber + 1 Exit For End If Next j Next i HundredPrisoners_Random = FoundOwnNumber End Function   Function HundredPrisoners_Random_Mem(ByVal NrPrisoners, ByVal NrSelections) As Long Dim DrawerArray() As Long Dim SelectionArray() As Long ReDim DrawerArray(NrPrisoners - 1) ReDim SelectionArray(NrPrisoners - 1)   HundredPrisoners_Random_Mem = 0 FoundOwnNumberMem = 0   For Counter = LBound(DrawerArray) To UBound(DrawerArray) DrawerArray(Counter) = Counter + 1 Next Counter   For Counter = LBound(SelectionArray) To UBound(SelectionArray) SelectionArray(Counter) = Counter + 1 Next Counter   FisherYates DrawerArray   For i = 1 To NrPrisoners FisherYates SelectionArray For j = 1 To NrSelections NumberFromDrawer = DrawerArray(SelectionArray(j - 1) - 1) If NumberFromDrawer = i Then FoundOwnNumberMem = FoundOwnNumberMem + 1 Exit For End If Next j Next i HundredPrisoners_Random_Mem = FoundOwnNumberMem End Function   Sub FisherYates(ByRef InputArray() As Long)   Dim Temp As Long Dim PosRandom As Long Dim Counter As Long Dim Upper As Long Dim Lower As Long   Lower = LBound(InputArray) Upper = UBound(InputArray)   Randomize   For Counter = Upper To (Lower + 1) Step -1 PosRandom = CLng(Int((Counter - Lower + 1) * Rnd + Lower)) Temp = InputArray(Counter) InputArray(Counter) = InputArray(PosRandom) InputArray(PosRandom) = Temp Next Counter   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
#Rebol
Rebol
rebol [] random/seed now g: [style t box red [ if not find [0x108 108x0 0x-108 -108x0] face/offset - e/offset [exit] x: face/offset face/offset: e/offset e/offset: x] across ] x: random repeat i 15 [append x:[] i] repeat i 15 [ repend g ['t mold x/:i random white] if find [4 8 12] i [append g 'return] ] append g [e: box] view layout g
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.
#Wren
Wren
import "/dynamic" for Enum, Struct import "random" for Random import "/ioutil" for Input import "/fmt" for Fmt import "/str" for Str   var MoveDirection = Enum.create("MoveDirection", ["up", "down", "left", "right"])   var Tile = Struct.create("Tile", ["value", "isBlocked"])   class G2048 { construct new() { _isDone = false _isWon = false _isMoved = true _score = 0 _board = List.filled(4, null) for (i in 0..3) { _board[i] = List.filled(4, null) for (j in 0..3) _board[i][j] = Tile.new(0, false) } _rand = Random.new() initializeBoard() }   initializeBoard() { for (y in 0..3) { for (x in 0..3) _board[x][y] = Tile.new(0, false) } }   loop() { addTile() while (true) { if (_isMoved) addTile() drawBoard() if (_isDone) break waitKey() } var endMessage = _isWon ? "You've made it!" : "Game Over!" System.print(endMessage) }   drawBoard() { System.print("\e[2J") // clear terminal System.print("Score: %(_score)\n") for (y in 0..3) { System.print("+------+------+------+------+") System.write("| ") for (x in 0..3) { if (_board[x][y].value == 0) { System.write(" ") } else { Fmt.write("$-4s", _board[x][y].value) } System.write(" | ") } System.print() } System.print("+------+------+------+------+\n\n") }   waitKey() { _isMoved = false var input = Str.upper(Input.option("(W) Up (S) Down (A) Left (D) Right: ", "WSADwsad")) if (input == "W") { move(MoveDirection.up) } else if (input == "A") { move(MoveDirection.left) } else if (input == "S") { move(MoveDirection.down) } else if (input == "D") { move(MoveDirection.right) } for (y in 0..3) { for (x in 0..3) _board[x][y].isBlocked = false } }   addTile() { for (y in 0..3) { for (x in 0..3) { if (_board[x][y].value != 0) continue var a var b while (true) { a = _rand.int(4) b = _rand.int(4) if (_board[a][b].value == 0) break } var r = _rand.float() _board[a][b].value = (r > 0.89) ? 4 : 2 if (canMove()) return } } _isDone = true }   canMove() { for (y in 0..3) { for (x in 0..3) { if (_board[x][y].value == 0) return true } }   for (y in 0..3) { for (x in 0..3) { if (testAdd(x + 1, y, _board[x][y].value) || testAdd(x - 1, y, _board[x][y].value) || testAdd(x, y + 1, _board[x][y].value) || testAdd(x, y - 1, _board[x][y].value)) return true } }   return false }   testAdd(x, y, value) { if (x < 0 || x > 3 || y < 0 || y > 3) return false return _board[x][y].value == value }   moveVertically(x, y, d) { if (_board[x][y + d].value != 0 && _board[x][y + d].value == _board[x][y].value && !_board[x][y].isBlocked && !_board[x][y + d].isBlocked) { _board[x][y].value = 0 _board[x][y + d].value = _board[x][y + d].value * 2 _score = _score + _board[x][y + d].value _board[x][y + d].isBlocked = true _isMoved = true } else if (_board[x][y + d].value == 0 && _board[x][y].value != 0) { _board[x][y + d].value = _board[x][y].value _board[x][y].value = 0 _isMoved = true }   if (d > 0) { if (y + d < 3) moveVertically(x, y + d, 1) } else { if (y + d > 0) moveVertically(x, y + d, -1) } }   moveHorizontally(x, y, d) { if (_board[x + d][y].value != 0 && _board[x + d][y].value == _board[x][y].value && !_board[x + d][y].isBlocked && !_board[x][y].isBlocked) { _board[x][y].value = 0 _board[x + d][y].value = _board[x + d][y].value * 2 _score = _score + _board[x + d][y].value _board[x + d][y].isBlocked = true _isMoved = true } else if (_board[x + d][y].value == 0 && _board[x][y].value != 0) { _board[x + d][y].value = _board[x][y].value _board[x][y].value = 0 _isMoved = true }   if (d > 0) { if (x + d < 3) moveHorizontally(x + d, y, 1) } else { if (x + d > 0) moveHorizontally(x + d, y, -1) } }   move(direction) { if (direction == MoveDirection.up) { for (x in 0..3) { for (y in 1..3) { if (_board[x][y].value != 0) moveVertically(x, y, -1) } } } else if (direction == MoveDirection.down) { for (x in 0..3) { for (y in 2..0) { if (_board[x][y].value != 0) moveVertically(x, y, 1) } } } else if (direction == MoveDirection.left) { for (y in 0..3) { for (x in 1..3) { if (_board[x][y].value != 0) moveHorizontally(x, y, -1) } } } else if (direction == MoveDirection.right) { for (y in 0..3) { for (x in 2..0) { if (_board[x][y].value != 0) moveHorizontally(x, y, 1) } } } } }   var runGame // forward declaration   var checkRestart = Fn.new { var input = Str.upper(Input.option("(N) New game (P) Exit: ", "NPnp")) if (input == "N") { runGame.call() } else if (input == "P") return }   runGame = Fn.new { var game = G2048.new() game.loop() checkRestart.call() }   runGame.call()
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
#Dart
Dart
main() { BeerSong beerSong = BeerSong(); //pass a 'starting point' and 'end point' as parameters respectively String printTheLyrics = beerSong.recite(99, 1).join('\n'); print(printTheLyrics); }   class Song { String bottleOnTheWall(int index) { String bottleOnTheWallText = '$index bottles of beer on the wall, $index bottles of beer,'; return bottleOnTheWallText; }   String bottleTakenDown(int index) { String englishGrammar = (index >= 2) ? 'bottle' : 'bottles'; String bottleTakenDownText = 'Take one down and pass it around, ${index - 1} $englishGrammar of beer on the wall.'; return bottleTakenDownText; } }   class BeerSong extends Song { @override String bottleOnTheWall(int index) { String originalText = super.bottleOnTheWall(index); if (index < 2) { String bottleOnTheWallText = '$index bottle of beer on the wall, $index bottle of beer,'; return bottleOnTheWallText; } return originalText; }   @override String bottleTakenDown(int index) { if (index < 2) { String bottleTakenDownText = 'Take it down and pass it around, no more bottles of beer on the wall.'; return bottleTakenDownText; } String originalText = super.bottleTakenDown(index); return originalText; }   List<String> recite(int actualBottleOnTheWall, int remainingBottleOnTheWall) { List<String> theLyrics = []; for (int index = actualBottleOnTheWall; index >= remainingBottleOnTheWall; index--) { String onTheWall = bottleOnTheWall(index); String takenDown = bottleTakenDown(index); theLyrics.add(onTheWall); theLyrics.add(takenDown); theLyrics.add(''); } return theLyrics; } }   }
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.
#PureBasic
PureBasic
#digitCount = 4 Global Dim digits(#digitCount - 1) ;holds random digits   Procedure showDigits() Print(#CRLF$ + "These are your four digits: ") Protected i For i = 0 To #digitCount - 1 Print(Str(digits(i))) If i < (#digitCount - 1) Print(", ") Else PrintN("") EndIf Next Print("24 = ") EndProcedure   Procedure playAgain() Protected answer.s Repeat Print("Play again (y/n)? ") answer = LCase(Left(Trim(Input()), 1)) Select answer Case "n" ProcedureReturn #False Case "y" ProcedureReturn #True Default PrintN("") Continue EndSelect ForEver EndProcedure   Procedure allDigitsUsed() Protected i For i = 0 To #digitCount - 1 If digits(i) <> 0 ProcedureReturn #False EndIf Next ProcedureReturn #True EndProcedure   Procedure isValidDigit(d) For i = 0 To #digitCount - 1 If digits(i) = d digits(i) = 0 ProcedureReturn #True EndIf Next ProcedureReturn #False EndProcedure   Procedure doOperation(List op.c(), List operand.f()) Protected x.f, y.f, op.c op = op(): DeleteElement(op()) If op = '(' ProcedureReturn #False ;end of sub-expression EndIf   y = operand(): DeleteElement(operand()) x = operand() Select op Case '+' x + y Case '-' x - y Case '*' x * y Case '/' x / y EndSelect operand() = x ProcedureReturn #True ;operation completed EndProcedure   ;returns error if present and the expression results in *result\f Procedure.s parseExpression(expr.s, *result.Float) NewList op.c() NewList operand.f() expr = ReplaceString(expr, " ", "") ;remove spaces   If Len(expr) = 0: *result\f = 0: ProcedureReturn "": EndIf ;no expression, return zero   Protected *ech.Character = @expr, lastWasDigit, lastWasOper, parenCheck, c.c While *ech\c c = *ech\c Select c Case '*', '/', '-', '+' If Not lastWasDigit: ProcedureReturn "Improper syntax, need a digit between operators.": EndIf If ListSize(op()) And (FindString("*/", Chr(op()), 1) Or (FindString("+-", Chr(op()), 1) And FindString("+-", Chr(c), 1))) doOperation(op(), operand()) EndIf AddElement(op()): op() = c lastWasOper = #True: lastWasDigit = #False Case '(' If lastWasDigit: ProcedureReturn "Improper syntax, need an operator before left paren.": EndIf AddElement(op()): op() = c parenCheck + 1: lastWasOper = #False Case ')' parenCheck - 1: If parenCheck < 0: ProcedureReturn "Improper syntax, missing a left paren.": EndIf If Not lastWasDigit: ProcedureReturn "Improper syntax, missing a digit before right paren.": EndIf Repeat: Until Not doOperation(op(),operand()) lastWasDigit = #True Case '1' To '9' If lastWasDigit: ProcedureReturn "Improper syntax, need an operator between digits.": EndIf AddElement(operand()): operand() = c - '0' If Not isValidDigit(operand()): ProcedureReturn "'" + Chr(c) + "' is not a valid digit.": EndIf lastWasDigit = #True: lastWasOper = #False Default ProcedureReturn "'" + Chr(c) + "' is not allowed in the expression." EndSelect *ech + SizeOf(Character) Wend   If parenCheck <> 0 Or lastWasOper: ProcedureReturn "Improper syntax, missing a right paren or digit.": EndIf Repeat If Not ListSize(op()): Break: EndIf Until Not doOperation(op(),operand()) *result\f = operand() ProcedureReturn "" ;no error EndProcedure   Define success, failure, result.f, error.s, i If OpenConsole() PrintN("The 24 Game" + #CRLF$) PrintN("Given four digits and using just the +, -, *, and / operators; and the") PrintN("possible use of brackets, (), enter an expression that equates to 24.") Repeat For i = 0 To #digitCount - 1 digits(i) = 1 + Random(8) Next   showDigits() error = parseExpression(Input(), @result) If error = "" If Not allDigitsUsed() PrintN( "Wrong! (you didn't use all digits)"): failure + 1 ElseIf result = 24.0 PrintN("Correct!"): success + 1 Else Print("Wrong! (you got ") If result <> Int(result) PrintN(StrF(result, 2) + ")") Else PrintN(Str(result) + ")") EndIf failure + 1 EndIf Else PrintN(error): failure + 1 EndIf Until Not playAgain()   PrintN("success:" + Str(success) + " failure:" + Str(failure) + " total:" + Str(success + failure))   Print(#CRLF$ + "Press ENTER to exit"): Input() CloseConsole() EndIf
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
#Golo
Golo
#!/usr/bin/env golosh ---- This module asks for two numbers, adds them, and prints the result. ---- module Aplusb   import gololang.IO   function main = |args| {   let line = readln("Please enter two numbers (just leave a space in between them) ") let numbers = line: split("[ ]+"): asList()   require(numbers: size() == 2, "we need two numbers")   try {   let a, b = numbers: map(|i| -> i: toInt())   require(a >= -1000 and a <= 1000 and b >= -1000 and b <= 1000, "both numbers need to be between -1000 and 1000")   println(a + b)   } catch (e) { println("they both need to be numbers for this to work") } }
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
#Red
Red
Red [] test: func [ s][ p: copy "BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM" forever [ if 0 = length? s [ return 'true ]  ;; if string cleared, all chars found/removed if tail? p [ return 'false ]  ;; if at end of search block - not found rule: reduce [ first p '| second p]  ;; construct parse rule from string either parse s [ to rule remove rule to end ] [  ;; remove found char from string remove/part p 2  ;;character found , remove block p: head p  ;;start from remaining string at beginning aka head ] [ p: skip p 2 ]  ;; else move to next block ] ] foreach word split {A bark book TrEAT COmMoN SQUAD conFUsE} space [ print reduce [ pad copy word 8 ":" test 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.
#Visual_Basic_.NET
Visual Basic .NET
Module Module1   Function PlayOptimal() As Boolean Dim secrets = Enumerable.Range(0, 100).OrderBy(Function(a) Guid.NewGuid).ToList   For p = 1 To 100 Dim success = False   Dim choice = p - 1 For i = 1 To 50 If secrets(choice) = p - 1 Then success = True Exit For End If choice = secrets(choice) Next   If Not success Then Return False End If Next   Return True End Function   Function PlayRandom() As Boolean Dim secrets = Enumerable.Range(0, 100).OrderBy(Function(a) Guid.NewGuid).ToList   For p = 1 To 100 Dim choices = Enumerable.Range(0, 100).OrderBy(Function(a) Guid.NewGuid).ToList   Dim success = False For i = 1 To 50 If choices(i - 1) = p Then success = True Exit For End If Next   If Not success Then Return False End If Next   Return True End Function   Function Exec(n As UInteger, play As Func(Of Boolean)) Dim success As UInteger = 0 For i As UInteger = 1 To n If play() Then success += 1 End If Next Return 100.0 * success / n End Function   Sub Main() Dim N = 1_000_000 Console.WriteLine("# of executions: {0}", N) Console.WriteLine("Optimal play success rate: {0:0.00000000000}%", Exec(N, AddressOf PlayOptimal)) Console.WriteLine(" Random play success rate: {0:0.00000000000}%", Exec(N, AddressOf PlayRandom)) End Sub   End Module
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
#Red
Red
  Red [Needs: 'view] system/view/screens/1/pane/-1/visible?: false ;; suppress console window ;; because this code is heavily influenced / (copied from ... ) ;; by the rebol version ( which actually works with red as well with ;; some minimal changes ) i added some comments to make the ;; code more readable...   ;;----------------------------------------- ;; check, if puzzle is solved, OK button closes program ;;----------------------------------------- check: does [ ;; the text on each tile must be equal to its position: repeat pos 15 [ unless pos = to-integer lay/pane/:pos/text [exit] ] view/flags [ title "SuCCeSS" text "You solved the puzzle ! " button "OK" [quit] ] [modal popup] ] ;;-------------------------------------- ;; actually only changes text / Number on tile / button ;;--------------------------------------- changeTiles: func [ f ][  ;; this is tricky, check if e(mpty) button is one in of the  ;; four valid positions , by simply subtracting their offsets...else exit ( no change) unless find [ 0x52 0x-52 52x0 -52x0 ] f/offset - e/offset [return false] e/text: f/text  ;; empty button gets Number from clicked button e/visible?: true  ;; empty gets visible f/visible?: false ;; clicked button gets invisible e: f  ;; e(mpty) refers now to clicked button return true ;; true - change has happened ] ;;----------------------------------------- ;; function which is executed, when button is clicked ;; argument is face - button ;;------------------------------------- bClicked: func [f][ if changeTiles f [check] ]   ;; define the window: ;; style is a prototype definition for a button element win: [ title "15 Puzzle" backdrop silver style btn: button 40x40 [bClicked face] font-size 15 bold ] ;; generate 1..15 buttons with number repeat nr 15 [ repend win [ 'btn form nr ] ;; repend reduces and then appends.. if 0 = mod nr 4 [ append win 'return ] ;; "carriage return" in window after 4 buttons ]  ;; append empty / hidden button no 16 and return/quit button: append win [ e: btn "16" hidden return button "Quit" [quit]]   lay: layout win ;; define win as layout, so each button can now be addressed as ;; layout/pane/index ( 1..15 - redbol is 1 based )   flip: 0 ;; start random generator, otherwise we always get the same puzzle random/seed now/time/precise ;; lets flip random tiles a few times to initialize the puzzle ;; ( actually numbers < 100 are quite easy to solve )   while [ flip < 40 ] [ if changeTiles lay/pane/(random 16) [ flip: flip + 1 ] ]   ;; show the window... view lay    
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.
#XPL0
XPL0
include c:\cxpl\codes; \intrinsic 'code' declarations int Box(16), Moved;   proc ShiftTiles(I0, DI); \Shift tiles, add adjacents, shift again int I0, DI; int Done, M, N, I; [Done:= false; loop [for M:= 1 to 3 do \shift all tiles in a single row or column [I:= I0; for N:= 1 to 3 do [if Box(I)=0 & Box(I+DI)#0 then [Box(I):= Box(I+DI); Box(I+DI):= 0; Moved:= true]; I:= I+DI; ]; ]; if Done then return; Done:= true; I:= I0; \add identical adjacent tiles into a new tile for N:= 1 to 3 do [if Box(I)=Box(I+DI) & Box(I)#0 then [Box(I):= Box(I)+1; Box(I+DI):= 0; Moved:= true]; I:= I+DI; ]; ]; \loop back to close any gaps that were opened ]; \ShiftTiles   int I, J, X, Y, C; [Clear; for I:= 0 to 15 do Box(I):= 0; \empty the box of tiles loop [repeat I:= Ran(16) until Box(I)=0; \in a random empty location Box(I):= if Ran(10) then 1 else 2; \insert a 2^1=2 or 2^2=4 for I:= 0 to 15 do \show board with its tiles [X:= ((I&3)+5)*6; \get coordinates of tile Y:= I>>2*3+6; Attrib(((Box(I)+1)&7)<<4 + $F);\set color based on tile value for J:= 0 to 2 do \draw a square (6*8x3*16) [Cursor(X, Y+J); Text(6, " "); ]; if Box(I)#0 then \box contains a tile [J:= 1; \center numbers somewhat if Box(I) <= 9 then J:= 2; if Box(I) <= 3 then J:= 3; Cursor(X+J, Y+1); IntOut(6, 1<<Box(I)); ]; ]; Moved:= false; \a tile must move to continue repeat repeat C:= ChIn(1) until C#0; \get key scan code, or ASCII for I:= 3 downto 0 do \for all rows or columns [case C of $4B: ShiftTiles(I*4, 1); \left arrow $4D: ShiftTiles(I*4+3, -1); \right arrow $50: ShiftTiles(I+12, -4); \down arrow $48: ShiftTiles(I, 4); \up arrow $1B: [Clear; exit] \Esc other []; \ignore all other keys ]; until Moved; ]; ]
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
#Dc
Dc
[ dnrpr dnlBP lCP 1-dnrp rd2r >L ]sL   [Take one down, pass it around ]sC [ bottles of beer ]sB [ bottles of beer on the wall] 99   lLx   dnrpsA dnlBP lCP 1- dn[ bottle of beer on the wall]p rdnrpsA n[ bottle of beer ]P [Take it down, pass it around ]P [no more bottles of beer on the wall ]P
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.
#Python
Python
''' 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.   '''   from __future__ import division, print_function import random, ast, re import sys   if sys.version_info[0] < 3: input = raw_input   def choose4(): 'four random digits >0 as characters' return [str(random.randint(1,9)) for i in range(4)]   def welcome(digits): print (__doc__) print ("Your four digits: " + ' '.join(digits))   def check(answer, digits): allowed = set('() +-*/\t'+''.join(digits)) ok = all(ch in allowed for ch in answer) and \ all(digits.count(dig) == answer.count(dig) for dig in set(digits)) \ and not re.search('\d\d', answer) if ok: try: ast.parse(answer) except: ok = False return ok   def main(): digits = choose4() welcome(digits) trial = 0 answer = '' chk = ans = False while not (chk and ans == 24): trial +=1 answer = input("Expression %i: " % trial) chk = check(answer, digits) if answer.lower() == 'q': break if answer == '!': digits = choose4() print ("New digits:", ' '.join(digits)) continue if not chk: print ("The input '%s' was wonky!" % answer) else: ans = eval(answer) print (" = ", ans) if ans == 24: print ("Thats right!") print ("Thank you and goodbye")   if __name__ == '__main__': main()
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
#Gosu
Gosu
  uses java.io.InputStreamReader uses java.util.Scanner uses java.lang.System   var scanner = new Scanner( new InputStreamReader( System.in ) ) var a = scanner.nextInt() var b = scanner.nextInt()   print( 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
#REXX
REXX
/*REXX pgm finds if words can be spelt from a pool of toy blocks (each having 2 letters)*/ list= 'A bark bOOk treat common squaD conFuse' /*words can be: upper/lower/mixed case*/ blocks= 'BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM' do k=1 for words(list) /*traipse through a list of some words.*/ call spell word(list, k) /*display if word can be spelt (or not)*/ end /*k*/ /* [↑] tests each word in the list. */ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ spell: procedure expose blocks; arg x /*ARG uppercases the word to be spelt.*/ L= length(x); @.= 0 /*get length of the word to be spelt. */ do try=1 for L; z= blocks; upper z /*use a fresh copy of the "Z" blocks.*/ do n=1 for L; y= substr(x, n, 1) /*attempt another letter in the word. */ @.n= pos(y, z, 1 + @.n); if @.n==0 then leave /*not found? Try again*/ z= overlay(' ', z, @.n) /*mutate the toy block ───► a onesy. */ do q=1 for words(z); if length(word(z,q))==1 then z= delword(z, q, 1) end /*q*/ /* [↑] elide any existing onesy block.*/ if n==L then leave try /*was last letter used in the spelling?*/ end /*n*/ /* [↑] end of a toy block usage. */ end /*try*/ /* [↑] end of a "TRY" permute. */ say right( arg(1), 30) right( word( "can't can", (n==L) + 1), 6) 'be spelt.' return
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.
#VBScript
VBScript
  option explicit const npris=100 const ntries=50 const ntests=1000. dim drawer(100),opened(100),i for i=1 to npris: drawer(i)=i:next shuffle drawer wscript.echo rf(tests(false)/ntests*100,10," ") &" % success for random" wscript.echo rf(tests(true) /ntests*100,10," ") &" % success for optimal strategy"   function rf(v,n,s) rf=right(string(n,s)& v,n):end function   sub shuffle(d) 'knut's shuffle dim i,j,t randomize timer for i=1 to npris j=int(rnd()*i+1) t=d(i):d(i)=d(j):d(j)=t next end sub   function tests(strat) dim cntp,i,j tests=0 for i=1 to ntests shuffle drawer cntp=0 if strat then for j=1 to npris if not trystrat(j) then exit for next else for j=1 to npris if not tryrand(j) then exit for next end if if j>=npris then tests=tests+1 next end function   function tryrand(pris) dim i,r erase opened for i=1 to ntries do r=int(rnd*npris+1) loop until opened(r)=false opened(r)=true if drawer(r)= pris then tryrand=true : exit function next tryrand=false end function   function trystrat(pris) dim i,r r=pris for i=1 to ntries if drawer(r)= pris then trystrat=true :exit function r=drawer(r) next trystrat=false end function
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
#REXX
REXX
/*REXX pgm implements the 15─puzzle (AKA: Gem Puzzle, Boss Puzzle, Mystic Square, 14─15)*/ parse arg N seed . /*obtain optional arguments from the CL*/ if N=='' | N=="," then N=4 /*Not specified? Then use the default.*/ if datatype(seed, 'W') then call random ,,seed /*use repeatability seed for RANDOM BIF*/ nh= N**2; @.=; nn= nh - 1; w= length(nn) /*define/initialize some handy values. */ $= /*$: will hold the solution for testing*/ do i=1 for nn; $= $ i /* [◄] build a solution for testing. */ end /*i*/ done= $ /* [↓] scramble the tiles in puzzle. */ do j=1 for nn; a= random(1, words($) ); @.j= word($, a); $= delword($, a, 1) end /*j*/ /*═══════════════════ play the 15─puzzle 'til done or quit.*/ do until puzz==done & @.nh=='' /*perform moves until puzzle is solved.*/ call getmv /*get user's move(s) and validate it.*/ if errMsg\=='' then do; say sep errMsg; iterate /*possible error msg? */ end call showGrid 0 /*don't display puzzle, just find hole.*/ if wordpos(x, !)==0 then do; say sep 'tile ' x " can't be moved."; iterate end @.hole= x; @.tile= call showGrid 0 /*move specified tile ───► puzzle hole.*/ end /*until*/ /*═════════════════════════════════════════════════════════*/   call showGrid 1; say; say sep 'Congratulations! The' nn"-puzzle is solved." exit 0 /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ getmv: x= 0; sep= copies('─', 8); pad= left('', 1 + length(sep) ) /*pad=9 blanks*/ prompt= sep 'Please enter a tile number or numbers ' sep " (or Quit)." if queued()==0 then do; say; call showGrid 1; say; say prompt end parse pull x . 1 ox . 1 . zx; upper x /*obtain a number (or numbers) from CL.*/ if abbrev('QUIT', x, 1) then do; say; say; say sep "quitting."; exit end if words(zx)>0 then do; parse var zx xq; queue xq end /* [↑] Extra moves? Stack for later. */ select /* [↓] Check for possible errors/typos*/ when x=='' then errMsg= "nothing entered." when \datatype(x, 'N') then errMsg= "tile number isn't numeric: " ox when \datatype(x, 'W') then errMsg= "tile number isn't an integer: " ox when x=0 then errMsg= "tile number can't be zero: " ox when x<0 then errMsg= "tile number can't be negative: " ox when x>nn then errMsg= "tile number can't be greater than" nn otherwise errMsg= end /*select*/ /* [↑] verify the human entered data. */ return /*──────────────────────────────────────────────────────────────────────────────────────*/ showGrid: parse arg show;  !.=; x= x/1; #= 0; puzz= top= '╔'copies( copies("═", w)'╦', N); top= left( top, length(top) -1)"╗" bar= '╠'copies( copies("═", w)'╬', N); bar= left( bar, length(bar) -1)"╣" bot= '╚'copies( copies("═", w)'╩', N); bot= left( bot, length(bot) -1)"╝" if show then say pad top   do r=1 for N; z= '║' do c=1 for N; #= #+1; y= @.#; puzz= puzz y;  !.r.c= y _= right(@.#, w)"║"; z= z || _ /* [↓] find hole*/ if @.# == '' then do; hole= #; holeRow= r; holeCol= c; end if @.# == x then do; tile= #; tileRow= r; tileCol= c; end end /*c*/ /* [↑] find X. */ if show then do; say pad z; if r\==N then say pad bar; end end /*r*/   rm=holeRow-1; rp=holeRow+1; cm=holeCol-1; cp=holeCol+1 /*possible moves.*/  !=!.rm.holeCol  !.rp.holeCol  !.holeRow.cm  !.holeRow.cp /* legal moves.*/ if show then say pad bot; 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
#DBL
DBL
; ;=============================================================================== ; Oringinal Author: Bob Welton ([email protected]) ; Language: DIBOL or DBL ; ; Modified to work with DBL version 4 ; by Dario B. ;===============================================================================     RECORD   NRBOT,D2,99  ;Default # of bottles to 99 A2, A2     PROC ;-------------------------------------------------------------------------------   XCALL FLAGS (0007000000,1)  ;Suppress STOP message OPEN (1,O,"TT:")  ;Open the terminal/display   DO FOREVER BEGIN A2=NRBOT,'ZX' DISPLAY (1,A2," Bottles of Beer on the wall,",10)   A2=NRBOT,'ZX' DISPLAY (1,A2," Bottles of Beer,",10) DISPLAY (1," Take one down, pass it around,",10)   DECR NRBOT  ;Reduce # of bottles by 1 IF (NRBOT.LE.1) EXITLOOP  ;If just 1 bottle left, get out   A2=NRBOT,'ZX' DISPLAY (1,A2," Bottles of Beer on the wall.",10,10) END   A2=NRBOT,'ZX' DISPLAY (1,A2," Bottle of Beer on the wall,",10,10)   A2=NRBOT,'ZX' DISPLAY (1,A2," Bottle of Beer,",10)   DISPLAY (1," Take one down, pass it around,",10) DISPLAY (1,"0 Bottles of Beer on the wall,",10) DISPLAY (1,"0 Bottles of Beer,",10) DISPLAY (1,"Go to the store and buy some more,",10) DISPLAY (1,"99 Bottles of Beer on the wall,",10,10,10) CLOSE 1 STOP
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.
#Quackery
Quackery
[ stack ] is operators ( --> s )   0 $ "*/+-" witheach [ bit | ] operators put   [ stack ] is numbers ( --> s )   [ 0 swap witheach [ bit | ] numbers put ] is putnumbers ( $ --> )   [ $ "123456789" shuffle 4 split drop sort ] is choosenumbers ( --> $ )   [ say "Using any of the operators * / + -" cr say "and each of the numbers " witheach [ emit sp ] say "once," cr say "enter an RPN expression equal to 24." cr $ "Spaces between characters are optional: " input ] is getexpression ( $ --> $ )   [ $ "" swap witheach [ dup space = iff drop else join ] ] is stripspaces ( $ --> $ )   [ stack ] is opcount ( --> s ) [ stack ] is numcount ( --> s ) [ stack ] is numsused ( --> s )   [ true swap 0 opcount put 0 numcount put 0 numsused put witheach [ bit dup numbers share & iff [ 1 numcount tally numsused take | numsused put ] else [ operators share & if [ 1 opcount tally ] ] opcount share numcount share < not if [ drop false conclude ] ] numsused take numbers share != if [ drop false ] numcount take 4 != if [ drop false ] opcount take 3 != if [ drop false ] ] is checkexpression ( $ --> b )   [ $ "" swap witheach [ dup char 0 char 9 1+ within iff [ join $ " n->v " join ] done [ switch char * case [ $ "v* " join ] char / case [ $ "v/ " join ] char + case [ $ "v+ " join ] char - case [ $ "v- " join ] otherwise [ $ "Error!" fail ] ] ] ] is quackerise ( $ --> [ )   [ choosenumbers dup putnumbers [ dup getexpression stripspaces dup checkexpression not while cr say "Badly formed expression. Try again." cr cr drop again ] nip quackerise quackery cr say "Your expression is equal to " 2dup 10 point$ echo$ 24 n->v v- v0= iff [ say ". :-)" ] else [ say ". :-(" ] numbers release ] is game ( --> )
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
#Groovy
Groovy
def abAdder = { def reader = new Scanner(System.in) def a = reader.nextInt(); def b = reader.nextInt(); assert (-1000..1000).containsAll([a,b]) : "both numbers must be between -1000 and 1000 (inclusive)" a + b } abAdder()
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
#Ring
Ring
Blocks = [ :BO, :XK, :DQ, :CP, :NA, :GT, :RE, :TG, :QD, :FS, :JW, :HU, :VI, :AN, :OB, :ER, :FS, :LY, :PC, :ZM ] Words = [ :A, :BARK, :BOOK, :TREAT, :COMMON, :SQUAD, :CONFUSE ]   for x in words see '>>> can_make_word("' + upper(x) + '")' + nl if checkword(x,blocks) see "True" + nl else see "False" + nl ok next   func CheckWord Word,Blocks cBlocks = BLocks for x in word Found = false for y = 1 to len(cblocks) if x = cblocks[y][1] or x = cblocks[y][2] cblocks[y] = "--" found = true exit ok next if found = false return false ok next return true
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.
#Vlang
Vlang
import rand import rand.seed // Uses 0-based numbering rather than 1-based numbering throughout. fn do_trials(trials int, np int, strategy string) { mut pardoned := 0 for _ in 0..trials { mut drawers := []int{len: 100, init: it} rand.shuffle<int>(mut drawers) or {panic('shuffle failed')} mut next_trial := false for p in 0..np { mut next_prisoner := false if strategy == "optimal" { mut prev := p for _ in 0..50 { this := drawers[prev] if this == p { next_prisoner = true break } prev = this } } else { // Assumes a prisoner remembers previous drawers (s)he opened // and chooses at random from the others. mut opened := [100]bool{} for _ in 0..50 { mut n := 0 for { n = rand.intn(100) or {0} if !opened[n] { opened[n] = true break } } if drawers[n] == p { next_prisoner = true break } } } if !next_prisoner { next_trial = true break } } if !next_trial { pardoned++ } } rf := f64(pardoned) / f64(trials) * 100 println(" strategy = ${strategy:-7} pardoned = ${pardoned:-6} relative frequency = ${rf:-5.2f}%\n") }   fn main() { rand.seed(seed.time_seed_array(2)) trials := 100000 for np in [10, 100] { println("Results from $trials trials with $np prisoners:\n") for strategy in ["random", "optimal"] { do_trials(trials, np, strategy) } } }
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
#Ring
Ring
  # Project : CalmoSoft Fifteen Puzzle Game # Date  : 2018/12/01 # Author  : Gal Zsolt (CalmoSoft), Bert Mariani # Email  : [email protected]   load "guilib.ring"   app1 = new qapp {   stylefusionblack() empty = 16 nr_moves = 0 nr_sleep = 1 button_size = 4 current_button = 4 temp = 0 flag_init = 0 flag_save = 0 flag_move = 0 button = list(52) size_button = list(7) table1 = [] table2 = [] table3 = [] n_degree = 0 nr_degree = [0,90,180,270 ,-90,-180,-270] n_degreeRight = 0 n_degreeLeft = 0 btn_degree = newlist(52,2) counter_man = 0 t1 = 0   win1 = new qwidget() { move(0,0) resize(380,760) setwindowtitle("CalmoSoft Fifteen Puzzle Game")   for n=1 to 52 for m=1 to 2 btn_degree[n][m] = 0 next next   for n = 4 to 7 size_button[n] = new qpushbutton(win1) { col = n%4 setgeometry(100+col*40,60,40,40) settext(string(n) + "x" + string(n)) setclickevent("newsize(" + string(n) + ")") } next   btnMoves = new qpushbutton(win1) { setgeometry(100,260,80,40) settext("0") show() }   scramblebtn = new qpushbutton(win1) { setgeometry(100,300,160,40) settext("Scramble") setclickevent("scramble()") }   resetbtn = new qpushbutton(win1) { setgeometry(100,340,160,40) settext("Reset") setclickevent("resettiles()") }   savebtn = new qpushbutton(win1) { setgeometry(100,380,160,40) settext("Save Game") setclickevent("pSave()") }   playbtn = new qpushbutton(win1) { setgeometry(100,420,160,40) settext("Resume Game") setclickevent("pPlay()") }   sleepbtn = new qpushbutton(win1) { setgeometry(100,460,160,40) settext("Sleep Time: ")   }   decbtn = new qpushbutton(win1) { setgeometry(220,460,40,40) settext("<-") setclickevent("pDecSleep()") }   incbtn = new qpushbutton(win1) { setgeometry(260,460,40,40) settext("->") setclickevent("pIncSleep()") }   rightbtn = new qpushbutton(win1) { setgeometry(100,500,160,40) settext("In the Right Place : ") }   timebtn = new qpushbutton(win1) { setgeometry(100,540,160,40) settext("Elapsed Time : ") }   TimerMan = new qtimer(win1) { setinterval(500) settimeoutevent("pTime()") stop() } newsize(4) show() } exec() }   Func newlist x, y if isstring(x) x=0+x ok if isstring(y) y=0+y ok alist = list(x) for t in alist t = list(y) next return alist   func scramble for n= 1 to 1000 current_button=random(button_size*button_size-1)+1 up = (empty = (current_button - button_size)) down = (empty = (current_button + button_size)) left = ((empty = (current_button - 1)) and ((current_button % button_size) != 1)) right = ((empty = (current_button + 1)) and ((current_button % button_size) != 0)) move = up or down or left or right if move = 1 button[current_button] { temp2 = text() } col = empty%button_size if col = 0 col = button_size ok row = ceil(empty/button_size) button[empty] { setgeometry(60+col*40,60+row*40,40,40) rnd = random(6)+1 n_degree = nr_degree[rnd] button[empty].setbuttoncolor("yellow") button[empty].settext(temp2) button[empty].setClickEvent("movetile(" + string(empty) +")") btn_degree[empty] [1] = temp2 btn_degree[empty] [2] = n_degree } button[current_button].setbuttoncolor("yellow") btn_degree[current_button][2] = 0 button[current_button]{settext("")} empty = current_button ok next button[button_size*button_size+2]{settext("Here")} for n=1 to button_size*button_size button[n].setbuttoncolor("yellow") next table1 = [] table2 = [] table3 = [] for n = 1 to button_size*button_size add(table1, button[n].text()) add(table2, button[n].text()) add(table3, string(btn_degree[n][2])) next add(table1, string(empty)) add(table2, string(empty)) add(table3, string(empty)) add(table1, "OK") add(table2, "OK") add(table3, "OK") flag_save = 0 flag_move = 0 nr_moves = 0 btnMoves.settext(string(nr_moves)) timebtn.settext("Elapsed Time : ") t1 = clock() rightPlace() return   func movetile current_button2 if (current_button2 = button_size*button_size-1 and button[current_button2].text() = "In") pBack() else see char(7) up = (empty = (current_button2 - button_size)) down = (empty = (current_button2 + button_size)) left = ((empty = (current_button2- 1)) and ((current_button2 % button_size) != 1)) right = ((empty = (current_button2 + 1)) and ((current_button2 % button_size) != 0)) move = up or down or left or right if move = 1 temp2 = button[current_button2].text() btn_degree[empty][1] = temp2 add(table1, temp2) add(table2, string(current_button2)) col = empty%button_size if col = 0 col = button_size ok row = ceil(empty/button_size) button[empty] { setgeometry(60+col*40,60+row*40,40,40) n_degree = btn_degree[current_button2][2] btn_degree[empty][2] = n_degree button[empty].setbuttoncolor("orange") button[empty].settext(temp2) } add(table3, string(n_degree)) button[current_button2].setbuttoncolor("cyan") button[current_button2]{settext("")} empty = current_button2 nr_moves = nr_moves + 1 btnMoves.settext(string(nr_moves)) isGameOver() ok ok flag_move = 1 pElapsedTime() rightPlace() return   func resettiles n_degree = 0 empty = button_size*button_size for empty = 1 to button_size*button_size-1 btn_degree[empty][2] = 0 n_degree = 0 btn_degree[empty][1] = string(empty) button[empty].setstylesheet("background-color:yellow") button[empty] {settext(string(empty))} next button[button_size*button_size].setstylesheet("background-color:yellow") button[button_size*button_size] {settext("")} table1 = [] table2 = [] table3 = [] for n = 1 to button_size*button_size add(table1, button[n].text()) add(table2, button[n].text()) add(table3, string(btn_degree[n][2])) next add(table1, string(empty)) add(table2, string(empty)) add(table3, string(empty)) add(table1, "OK") add(table2, "OK") add(table3, "OK") flag_save = 0 flag_move = 0 nr_moves = 0 btnMoves.settext(string(nr_moves)) timebtn.settext("Elapsed Time : ") t1 = clock() rightPlace() return   func pHere if button[button_size*button_size-1].text() != "" and button[button_size*button_size+2].text() = "Here" button[button_size*button_size-1] { temp = text() } button[button_size*button_size+2].close() button[button_size*button_size+2] = new ButtonWithRotatedText(win1) button[button_size*button_size+2] { setgeometry(60+(button_size-1)*40,60+(button_size+1)*40,40,40) setstylesheet("background-color:yellow") btn_degree[button_size*button_size+2][2] = btn_degree[button_size*button_size-1][2] n_degree = btn_degree[button_size*button_size+2][2] emptysave = empty empty = button_size*button_size+2 btn_degree[empty][1] = temp settext(temp) } n_degree = 0 empty = button_size*button_size-1 btn_degree[empty][1] = "In" button[button_size*button_size-1]{settext("In")} for n = 1 to button_size*button_size button[n].setenabled(false) next button[button_size*button_size-1].setenabled(true) scramblebtn.setenabled(false) resetbtn.setenabled(false) savebtn.setenabled(false) playbtn.setenabled(false) empty = emptysave ok   func pBack button[button_size*button_size+2] { temp = text() } n_degree = btn_degree[button_size*button_size+2][2] btn_degree[button_size*button_size-1][2] = btn_degree[button_size*button_size+2][2] emptysave = empty empty = button_size*button_size-1 btn_degree[empty][1] = temp button[button_size*button_size-1] {settext(temp)} button[button_size*button_size+2].close() button[button_size*button_size+2] = new qpushbutton(win1) { setgeometry(60+(button_size-1)*40,60+(button_size+1)*40,40,40) settext("Here") setclickevent("pHere()") show() } for n = 1 to button_size*button_size button[n].setenabled(true) next scramblebtn.setenabled(true) resetbtn.setenabled(true) savebtn.setenabled(true) playbtn.setenabled(true) empty = emptysave isGameOver()   func rotateleft if button[button_size*button_size+2].text() != "Here" button[button_size*button_size+2].close() button[button_size*button_size+2] = new ButtonWithRotatedText(win1) button[button_size*button_size+2] { setgeometry(60+(button_size-1)*40,60+(button_size+1)*40,40,40) setstylesheet("background-color:yellow") n_degreeLeft = (n_degreeLeft-90)%360 n_degree = n_degreeLeft btn_degree[button_size*button_size+2][2] = n_degree emptysave = empty empty = button_size*button_size+2 btn_degree[empty][1] = temp button[button_size*button_size+2]{settext(temp)} } empty = emptysave ok   func rotateright if button[button_size*button_size+2].text() != "Here" button[button_size*button_size+2].close() button[button_size*button_size+2] = new ButtonWithRotatedText(win1) button[button_size*button_size+2] { setgeometry(60+(button_size-1)*40,60+(button_size+1)*40,40,40) setstylesheet("background-color:yellow") n_degreeRight = (n_degreeRight+90)%360 n_degree = n_degreeRight btn_degree[button_size*button_size+2][2] = n_degree emptysave = empty empty = button_size*button_size+2 btn_degree[empty][1] = temp button[button_size*button_size+2]{settext(temp)} } empty = emptysave ok   func newsize current_button win1{ sizenew = current_button%4 win1.resize(360+sizenew*40,640+sizenew*40) if flag_init != 0 for nb = 1 to button_size*button_size+3 button[nb] {close()} next btnMoves.close() ok scramblebtn.close() resetbtn.close() savebtn.close() playbtn.close() btnMoves.close() sleepbtn.close() decbtn.close() incbtn.close() rightbtn.close() timebtn.close()   for n = 1 to current_button*current_button col = n%current_button if col = 0 col = current_button ok row = ceil(n/current_button) button[n] = new ButtonWithRotatedText(win1) button[n] { setgeometry(60+col*40,60+row*40,40,40) button[n].setbuttoncolor("yellow") n_degree = 0 if n < current_button*current_button button[n].settext(string(n)) but n = current_button*current_button button[n].settext("") ok setClickEvent("movetile(" + string(n) +")") } next   btnMoves = new qpushbutton(win1) { setgeometry(100,60+(current_button+1)*40,(current_button-3)*40,40) setStyleSheet("text-align:center") settext("0") show() }   button[current_button*current_button+1] = new qpushbutton(win1) { setgeometry(60+(current_button-2)*40,60+(current_button+1)*40,40,40) settext("<-") setclickevent("rotateLeft()") show() }   button[current_button*current_button+2] = new qpushbutton(win1) { setgeometry(60+(current_button-1)*40,60+(current_button+1)*40,40,40) settext("Here") setclickevent("pHere()") show() }   button[current_button*current_button+3] = new qpushbutton(win1) { setgeometry(60+current_button*40,60+(current_button+1)*40,40,40) settext("->") setclickevent("rotateRight()") show() }   scramblebtn = new qpushbutton(win1) { setgeometry(100,100+(current_button+1)*40,current_button*40,40) settext("Scramble") setclickevent("scramble()") show() }   resetbtn = new qpushbutton(win1) { setgeometry(100,100+(current_button+2)*40,current_button*40,40) settext("Reset") setclickevent("resettiles()") show() }   savebtn = new qpushbutton(win1) { setgeometry(100,100+(current_button+3)*40,current_button*40,40) settext("Save Game") setclickevent("pSave()") show() }   playbtn = new qpushbutton(win1) { setgeometry(100,100+(current_button+4)*40,current_button*40,40) settext("Resume Game") setclickevent("pPlay()") show() }   sleepbtn = new qpushbutton(win1) { setgeometry(100,100+(current_button+5)*40,(current_button-2)*40,40) settext("Sleep Time: " + string(nr_sleep) + " s") show() }   decbtn = new qpushbutton(win1) { setgeometry(100+(current_button-2)*40,100+(current_button+5)*40,40,40) settext("<-") setclickevent("pDecSleep()") show() }   incbtn = new qpushbutton(win1) { setgeometry(100+(current_button-1)*40,100+(current_button+5)*40,40,40) settext("->") setclickevent("pIncSleep()") show() }   rightbtn = new qpushbutton(win1) { setgeometry(100,100+(current_button+6)*40,current_button*40,40) settext("In the Right Place : ") show() }   timebtn = new qpushbutton(win1) { setgeometry(100,100+(current_button+7)*40,current_button*40,40) settext("Elapsed Time : ") show() }   table1 = [] table2 = [] table3 = [] for n = 1 to button_size*button_size add(table1, button[n].text()) add(table2, button[n].text()) add(table3, string(0)) next add(table1, string(empty)) add(table2, string(empty)) add(table3, string(empty)) add(table1, "OK") add(table2, "OK") add(table3, "OK") empty = current_button*current_button button_size = current_button flag_init = 1 flag_save = 0 flag_move = 0 nr_moves = 0 timebtn.settext("Elapsed Time : ") t1 = clock() scramble() }   func pSave textedit1 = list2str(table1) textedit2 = list2str(table2) textedit3 = list2str(table3) chdir(currentdir()) cName1 = "CalmoSoftPuzzle1.txt" cName2 = "CalmoSoftPuzzle2.txt" cName3 = "CalmoSoftPuzzle3.txt" write(cName1,textedit1) write(cName2,textedit2) write(cName3,textedit3) flag_save = 1 timebtn.settext("Elapsed Time : ") t1 = clock() return   func pPlay if flag_save = 0 or flag_move = 0 warning() else chdir(currentdir()) cName1 = "CalmoSoftPuzzle1.txt" textedit1 = read(cName1) table1 = str2list(textedit1) cName2 = "CalmoSoftPuzzle2.txt" textedit2 = read(cName2) table2 = str2list(textedit2) cName3 = "CalmoSoftPuzzle3.txt" textedit3 = read(cName3) table3 = str2list(textedit3) for empty = 1 to button_size*button_size button[empty].setbuttoncolor("yellow") n_degree = number(table3[empty]) btn_degree[empty][1] = table1[empty] button[empty] {settext(table1[empty])} next empty = number(table1[button_size*button_size + 1]) counter_man = button_size*button_size+2 nr_moves = 0 t1 = clock() TimerMan.start() ok   func pTime() if flag_save = 0 or flag_move = 0 warning() else counter_man++ pPlaySleep() sleep(nr_sleep*1000) pElapsedTime() if counter_man = len(table1) TimerMan.stop() ok ok   func pPlaySleep see char(7) value = table1[counter_man] place = table2[counter_man] n_degree = number(table3[counter_man]) btn_degree[empty][1] = value button[empty].setbuttoncolor("orange") button[empty] {settext(value)} n_degree = 0 button[number(place)].setbuttoncolor("cyan") button[number(place)] {settext("")} empty = number(place) nr_moves = nr_moves + 1 btnMoves.settext(string(nr_moves))   func pIncSleep nr_sleep = nr_sleep + 1 sleepbtn.settext("Sleep Time: " + string(nr_sleep) + " s")   func pDecSleep if nr_sleep > 1 nr_sleep = nr_sleep - 1 sleepbtn.settext("Sleep Time: " + string(nr_sleep) + " s") ok   func sleep(x) nTime = x oTest = new qTest oTest.qsleep(nTime) return   func isGameOver flagend = 1 for n=1 to button_size*button_size-1 if button[n].text() != n or btn_degree[n][2] != 0 flagend = 0 exit ok next if flagend = 1 new qmessagebox(win1) { setwindowtitle("Game Over") settext("Congratulations!") show() } ok   func rightPlace count = 0 for n=1 to button_size*button_size if button[n].text() = n and btn_degree[n][2] = 0 count = count + 1 ok next rightbtn.settext("In the Right Place : " + count)   func warning new qmessagebox(win1) { setwindowtitle("Warning!") settext("First you must play and save the game.") show() }   func pElapsedTime t2 = (clock() - t1)/1000 timebtn.settext("Elapsed Time : " + t2 + " s")   Class ButtonWithRotatedText   oButton oLabel cText="We are here" n_degree = 30 nTransX = 50 nTransY = 0   func init( oParent) oButton = new qPushButton(oParent) oLabel = new qLabel(oParent) oLabel.setAttribute(Qt_WA_TransparentForMouseEvents,True) oLabel.setAttribute(Qt_WA_DeleteOnClose, True) oButton.setAttribute(Qt_WA_DeleteOnClose, True) oButton.Show() return   func close() oLabel.close() oButton.close() return   func setstylesheet(x) oButton.setstylesheet(x)   func setgeometry( x,y,width,height) oButton.setgeometry(x,y,width,height) oLabel.setgeometry( x,y,width,height)   func setText( cValue) cText = cValue return   func Text() return cText   func setTranslate( x,y ) nTransX = x nTransY = y return   func TranslateOffsetX() return nTransX   func TranslateOffsetY() return nTransY   func setRotation_degree( nValue) n_degree = nValue return   func Rotation_degree() return n_degree   func setClickEvent( cEvent) oButton.setClickEvent(cEvent) return   func braceend() draw() return   func setEnabled(value) oButton.setenabled(value) return   func setButtonColor(color) colorIt = "background-color:" + color oButton.setstylesheet(colorIt) return   func draw() picture = new qpicture() color = new qcolor() { setrgb(0,0,255,255) } pen = new qpen() { setcolor(color) setwidth(10) }   painter = new qpainter() { begin(picture) setpen(pen) oFont = new qfont("Courier New",12,75,0) oFont.setpointsize(20) setfont(oFont) if n_degree = 0 if btn_degree[empty] [1]="In" p1 = -8 p2=0 translate(p1,p2) ok ok if n_degree = 0 if btn_degree[empty] [1]<10 p1 = 10 p2=10 else p1=5 p2=10 ok translate(p1,p2) but n_degree = 90 if btn_degree[empty] [1]<10 p=-10 else p=-15 ok translate(10,p) but n_degree = 180 if btn_degree[empty] [1]<10 p1= 30 p2=-10 else p1=35 p2=-10 ok translate(p1,p2) but n_degree = 270 if btn_degree[empty] [1]<10 p=10 else p=15 ok translate(30,p) but n_degree = -90 if btn_degree[empty] [1]<10 p=10 else p=15 ok translate(30,p) but n_degree = -180 if btn_degree[empty] [1]<10 p1=30 p2=-10 else p1=35 p2=-10 ok translate(p1,p2) but n_degree = -270 if btn_degree[empty] [1]<10 p1=10 p2=-10 else p1=10 p2=-15 ok translate(p1,p2) ok rotate(n_degree) drawtext(0,0,this.Text()) endpaint() } oLabel { setpicture(picture) show() } 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
#Delphi
Delphi
proc nonrec bottles(byte b) void: if b=0 then write("No more") else write(b) fi; write(" bottle"); if b~=1 then write("s") fi corp;   proc nonrec verse(byte v) void: bottles(v); writeln(" of beer on the wall,"); bottles(v); writeln(" of beer,"); writeln("Take ", if v=1 then "it" else "one" fi, " down and pass it around"); bottles(v-1); writeln(" of beer on the wall!\n"); corp;   proc nonrec main() void: byte v; for v from 99 downto 1 do verse(v) od corp
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.
#R
R
twenty.four <- function(operators=c("+", "-", "*", "/", "("), selector=function() sample(1:9, 4, replace=TRUE), arguments=selector(), goal=24) { newdigits <- function() { arguments <<- selector() cat("New digits:", paste(arguments, collapse=", "), "\n") } help <- function() cat("Make", goal, "out of the numbers",paste(arguments, collapse=", "), "and the operators",paste(operators, collapse=", "), ".", "\nEnter 'q' to quit, '!' to select new digits,", "or '?' to repeat this message.\n") help() repeat { switch(input <- readline(prompt="> "), q={ cat("Goodbye!\n"); break }, `?`=help(), `!`=newdigits(), tryCatch({ expr <- parse(text=input, n=1)[[1]] check.call(expr, operators, arguments) result <- eval(expr) if (isTRUE(all.equal(result, goal))) { cat("Correct!\n") newdigits() } else { cat("Evaluated to", result, "( goal", goal, ")\n") } },error=function(e) cat(e$message, "\n"))) } }   check.call <- function(expr, operators, arguments) { unexpr <- function(x) { if (is.call(x)) unexpr(as.list(x)) else if (is.list(x)) lapply(x,unexpr) else x } leaves <- unlist(unexpr(expr)) if (any(disallowed <-  !leaves %in% c(lapply(operators, as.name), as.list(arguments)))) { stop("'", paste(sapply(leaves[disallowed], as.character), collapse=", "), "' not allowed. ") } numbers.used <- unlist(leaves[sapply(leaves, mode) == 'numeric'])   if (! isTRUE(all.equal(sort(numbers.used), sort(arguments)))) stop("Must use each number once.") }
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
#GUISS
GUISS
Start,Programs,Accessories,Calculator,Button:3,Button:[plus], Button:2,Button:[equals]
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
#Ruby
Ruby
words = %w(A BaRK BOoK tREaT COmMOn SqUAD CoNfuSE) << ""   words.each do |word| blocks = "BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM" res = word.each_char.all?{|c| blocks.sub!(/\w?#{c}\w?/i, "")} #regexps can be interpolated like strings puts "#{word.inspect}: #{res}" end  
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.
#Wren
Wren
import "random" for Random import "/fmt" for Fmt   var rand = Random.new()   var doTrials = Fn.new{ |trials, np, strategy| var pardoned = 0 for (t in 0...trials) { var drawers = List.filled(100, 0) for (i in 0..99) drawers[i] = i rand.shuffle(drawers) var nextTrial = false for (p in 0...np) { var nextPrisoner = false if (strategy == "optimal") { var prev = p for (d in 0..49) { var curr = drawers[prev] if (curr == p) { nextPrisoner = true break } prev = curr } } else { var opened = List.filled(100, false) for (d in 0..49) { var n while (true) { n = rand.int(100) if (!opened[n]) { opened[n] = true break } } if (drawers[n] == p) { nextPrisoner = true break } } } if (!nextPrisoner) { nextTrial = true break } } if (!nextTrial) pardoned = pardoned + 1 } var rf = pardoned/trials * 100 Fmt.print(" strategy = $-7s pardoned = $,6d relative frequency = $5.2f\%\n", strategy, pardoned, rf) }   var trials = 1e5 for (np in [10, 100]) { Fmt.print("Results from $,d trials with $d prisoners:\n", trials, np) for (strategy in ["random", "optimal"]) doTrials.call(trials, np, strategy) }
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
#Ruby
Ruby
require 'io/console'   class Board SIZE = 4 RANGE = 0...SIZE   def initialize width = (SIZE*SIZE-1).to_s.size @frame = ("+" + "-"*(width+2)) * SIZE + "+" @form = "| %#{width}d " * SIZE + "|" @step = 0 @orign = [*0...SIZE*SIZE].rotate.each_slice(SIZE).to_a.freeze @board = @orign.map{|row | row.dup} randomize draw message play end   private   def randomize @board[0][0], @board[SIZE-1][SIZE-1] = 0, 1 @board[SIZE-1][0], @board[0][SIZE-1] = @board[0][SIZE-1], @board[SIZE-1][0] x, y, dx, dy = 0, 0, 1, 0 50.times do nx,ny = [[x+dx,y+dy], [x+dy,y-dx], [x-dy,y+dx]] .select{|nx,ny| RANGE.include?(nx) and RANGE.include?(ny)} .sample @board[nx][ny], @board[x][y] = 0, @board[nx][ny] x, y, dx, dy = nx, ny, nx-x, ny-y end @x, @y = x, y end   def draw puts "\e[H\e[2J" @board.each do |row| puts @frame puts (@form % row).sub(" 0 ", " ") end puts @frame puts "Step: #{@step}" end   DIR = {up: [-1,0], down: [1,0], left: [0,-1], right: [0,1]} def move(direction) dx, dy = DIR[direction] nx, ny = @x + dx, @y + dy if RANGE.include?(nx) and RANGE.include?(ny) @board[nx][ny], @board[@x][@y] = 0, @board[nx][ny] @x, @y = nx, ny @step += 1 draw end end   def play until @board == @orign case key_in when "\e[A", "w" then move(:up) when "\e[B", "s" then move(:down) when "\e[C", "d" then move(:right) when "\e[D", "a" then move(:left)   when "q","\u0003","\u0004" then exit when "h" then message end end   puts "Congratulations, you have won!" end   def key_in input = STDIN.getch if input == "\e" 2.times {input << STDIN.getch} end input end   def message puts <<~EOM Use the arrow-keys or WASD on your keyboard to push board in the given direction. PRESS q TO QUIT (or Ctrl-C or Ctrl-D) EOM end end   Board.new
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
#Draco
Draco
proc nonrec bottles(byte b) void: if b=0 then write("No more") else write(b) fi; write(" bottle"); if b~=1 then write("s") fi corp;   proc nonrec verse(byte v) void: bottles(v); writeln(" of beer on the wall,"); bottles(v); writeln(" of beer,"); writeln("Take ", if v=1 then "it" else "one" fi, " down and pass it around"); bottles(v-1); writeln(" of beer on the wall!\n"); corp;   proc nonrec main() void: byte v; for v from 99 downto 1 do verse(v) od corp
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.
#Racket
Racket
  #lang racket   (define (interprete expr numbers)  ;; the cashe for used numbers (define cashe numbers)    ;; updating the cashe and handling invalid cases (define (update-cashe! x) (unless (member x numbers) (error "Number is not in the given set:" x)) (unless (member x cashe) (error "Number is used more times then it was given:" x)) (set! cashe (remq x cashe)))    ;; the parser (define parse (match-lambda  ;; parsing arythmetics [`(,x ... + ,y ...) (+ (parse x) (parse y))] [`(,x ... - ,y ...) (- (parse x) (parse y))] [`(,x ... * ,y ...) (* (parse x) (parse y))] [`(,x ... / ,y ...) (/ (parse x) (parse y))] [`(,x ,op ,y ...) (error "Unknown operator: " op)]  ;; opening redundant brackets [`(,expr) (parse expr)]  ;; parsing numbers [(? number? x) (update-cashe! x) x]  ;; unknown token [x (error "Not a number: " x)]))    ;; parse the expresion (define result (parse expr))    ;; return the result if cashe is empty (if (empty? cashe) result (error "You didn`t use all numbers!")))  
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
#Harbour
Harbour
PROCEDURE Main() LOCAL GetList := {} LOCAL bValid := { |n| iif(n>-1001, iif(n<1001, .T.,.F.),.F.) } LOCAL a := 0 , b := 0   SetColor( "G+/N" ) CLS @ 10, 01 SAY "Enter two integers (range -1000...+1000):" GET a VALID Eval(bValid,a) @ Row(), Col() + 1 GET b VALID Eval(bValid,b) READ @ 12, 01 SAY "Sum of given numbers is " + hb_ntos(a+b)   RETURN  
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
#Run_BASIC
Run BASIC
blocks$ = "BO,XK,DQ,CP,NA,GT,RE,TG,QD,FS,JW,HU,VI,AN,OB,ER,FS,LY,PC,ZM" makeWord$ = "A,BARK,BOOK,TREAT,COMMON,SQUAD,Confuse" b = int((len(blocks$) /3) + 1) dim blk$(b)   for i = 1 to len(makeWord$) wrd$ = word$(makeWord$,i,",") dim hit(b) n = 0 if wrd$ = "" then exit for for k = 1 to len(wrd$) w$ = upper$(mid$(wrd$,k,1)) for j = 1 to b if hit(j) = 0 then if w$ = left$(word$(blocks$,j,","),1) or w$ = right$(word$(blocks$,j,","),1) then hit(j) = 1 n = n + 1 exit for end if end if next j next k print wrd$;chr$(9); if n = len(wrd$) then print " True" else print " False" next i
http://rosettacode.org/wiki/100_prisoners
100 prisoners
The Problem 100 prisoners are individually numbered 1 to 100 A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside. Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start. Prisoners start outside the room They can 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.
#XPL0
XPL0
int Drawer(100);   proc KShuffle; \Randomly rearrange the cards in the drawers \(Woe unto thee if Stattolo shuffle is used instead of Knuth shuffle.) int I, J, T; [for I:= 100-1 downto 1 do [J:= Ran(I+1); \range [0..I] T:= Drawer(I); Drawer(I):= Drawer(J); Drawer(J):= T; ]; ];   func Stategy2; \Return 'true' if stragegy succeeds int Prisoner, Card, Try; [for Prisoner:= 1 to 100 do [Card:= Drawer(Prisoner-1); Try:= 1; loop [if Card = Prisoner then quit; if Try >= 50 then return false; Card:= Drawer(Card-1); Try:= Try+1; ]; ]; return true; ];   func Stategy1; \Return 'true' if stragegy succeeds int Prisoner, I, D(100); [for Prisoner:= 1 to 100 do loop [for I:= 0 to 100-1 do D(I):= I+1; KShuffle; for I:= 1 to 50 do if Drawer(D(I-1)) = Prisoner then quit; return false; ]; return true; ];   proc Strategy(S); int S, I, Sample; real Successes; [Successes:= 0.; for Sample:= 1 to 100_000 do [for I:= 0 to 100-1 do Drawer(I):= I+1; KShuffle; case S of 1: if Stategy1 then Successes:= Successes + 1.; 2: if Stategy2 then Successes:= Successes + 1. other []; ]; RlOut(0, Successes/100_000.*100.); Text(0, "%^m^j"); ];   [Format(3, 12); Text(0, "Random strategy success rate: "); Strategy(1); Text(0, "Optimal strategy success rate: "); 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
#Run_BASIC
Run BASIC
call SetCSS ' ---- fill 15 squares with 1 to 15 dim sq(16) for i = 1 to 15: sq(i) = i: next   '----- shuffle the squares [newGame] for i = 1 to 100 ' Shuffle the squares j = rnd(0) * 16 + 1 k = rnd(0) * 16 + 1 h = sq(j) sq(j) = sq(k) sq(k) = h next i   ' ---- show the squares [loop] cls html "<CENTER><TABLE><TR align=center>" for i = 1 to 16 html "<TD>" if sq(i) <> 0 then button #pick, str$(sq(i)), [pick] #pick setkey(str$(i)) #pick cssclass("lBtn") end if html "</TD>" if i mod 4 = 0 then html "</TR><TR align=center>" next i html "</table>" wait   ' ---- Find what square they picked [pick] picked = val(EventKey$) move = 0 ' 0000000001111111 if picked - 1 > 0 then ' LEFT 1234567890123456 if mid$(" *** *** *** ***",picked,1) = "*" and sq(picked -1) = 0 then move = -1 :end if if picked + 1 < 17 then ' RIGHT if mid$("*** *** *** *** ",picked,1) = "*" and sq(picked +1) = 0 then move = 1 :end if if picked - 4 > 0 then ' UP if mid$(" ************",picked,1) = "*" and sq(picked -4) = 0 then move = -4 :end if if picked + 4 < 17 then ' DOWN if mid$("************ ",picked,1) = "*" and sq(picked +4) = 0 then move = 4 :end if ' ---- See if they picked a valid square next to the blank square if move = 0 then print "Invalid move: ";sq(picked) wait end if   ' ---- Valid squire, switch it with the blank square sq(picked + move) = sq(picked) ' move to the empty square sq(picked) = 0 for i = 1 to 15 ' ---- If they got them all in a row they are a winner if sq(i) <> i then goto [loop] next i   print "----- You are a winner -----" input "Play again (Y/N)";a$ if a$ = "Y" then goto [newGame] ' set up new game end   ' ---- Make the squares look nice SUB SetCSS CSSClass ".lBtn", "{ background:wheat;border-width:5px;width:70px; Text-Align:Center;Font-Size:24pt;Font-Weight:Bold;Font-Family:Arial; }" 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
#Dyalect
Dyalect
for i in 99^-1..1 { print("\(i) bottles of beer on the wall, \(i) bottles of beer.") let next = i is 1 ? "no" : i - 1 print("Take one down and pass it around, \(next) 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.
#Raku
Raku
use MONKEY-SEE-NO-EVAL;   say "Here are your digits: ", constant @digits = (1..9).roll(4)».Str;   grammar Exp24 { token TOP { ^ <exp> $ { fail unless EVAL($/) == 24 } } rule exp { <term>+ % <op> } rule term { '(' <exp> ')' | <@digits> } token op { < + - * / > } }   while my $exp = prompt "\n24? " { if try Exp24.parse: $exp { say "You win :)"; last; } else { say ( 'Sorry. Try again.' xx 20, 'Try harder.' xx 5, 'Nope. Not even close.' xx 2, 'Are you five or something?', 'Come on, you can do better than that.' ).flat.pick } }  
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
#Haskell
Haskell
main = print . sum . map read . words =<< getLine
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
#Rust
Rust
use std::iter::repeat;   fn rec_can_make_word(index: usize, word: &str, blocks: &[&str], used: &mut[bool]) -> bool { let c = word.chars().nth(index).unwrap().to_uppercase().next().unwrap(); for i in 0..blocks.len() { if !used[i] && blocks[i].chars().any(|s| s == c) { used[i] = true; if index == 0 || rec_can_make_word(index - 1, word, blocks, used) { return true; } used[i] = false; } } false }   fn can_make_word(word: &str, blocks: &[&str]) -> bool { return rec_can_make_word(word.chars().count() - 1, word, blocks, &mut repeat(false).take(blocks.len()).collect::<Vec<_>>()); }   fn main() { let blocks = [("BO"), ("XK"), ("DQ"), ("CP"), ("NA"), ("GT"), ("RE"), ("TG"), ("QD"), ("FS"), ("JW"), ("HU"), ("VI"), ("AN"), ("OB"), ("ER"), ("FS"), ("LY"), ("PC"), ("ZM")]; let words = ["A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "CONFUSE"]; for word in &words { println!("{} -> {}", word, can_make_word(word, &blocks)) } }  
http://rosettacode.org/wiki/100_prisoners
100 prisoners
The Problem 100 prisoners are individually numbered 1 to 100 A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside. Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start. Prisoners start outside the room They can 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.
#Yabasic
Yabasic
// Rosetta Code problem: http://rosettacode.org/wiki/100_prisoners // by Galileo, 05/2022   sub play(prisoners, iterations, optimal) local prisoner, pardoned, found, drawer, drawers(prisoners), i, j, k, p, x   for i = 1 to prisoners : drawers(i) = i : next   for i = 1 to iterations for k = 1 to prisoners : x = ran(prisoners) + 1 : p = drawers(x) : drawers(x) = drawers(k) : drawers(k) = p : next for prisoner = 1 to prisoners found = false if optimal then drawer = prisoner else drawer = ran(prisoners) + 1 end if for j = 1 to prisoners / 2 drawer = drawers(drawer) if drawer = prisoner found = true : break if not optimal drawer = ran(prisoners) + 1 next if not found break next pardoned = pardoned + found next   return 100 * pardoned / iterations end sub   iterations = 10000 print "Simulation count: ", iterations for prisoners = 10 to 100 step 90 random = play(prisoners, iterations, false) optimal = play(prisoners, iterations, true) print "Prisoners: ", prisoners, ", random: ", random, ", optimal: ", optimal next
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
#Rust
Rust
extern crate rand;   use std::collections::HashMap; use std::fmt;   use rand::Rng; use rand::seq::SliceRandom;   #[derive(Copy, Clone, PartialEq, Debug)] enum Cell { Card(usize), Empty, }   #[derive(Eq, PartialEq, Hash, Debug)] enum Direction { Up, Down, Left, Right, }   enum Action { Move(Direction), Quit, }   type Board = [Cell; 16]; const EMPTY: Board = [Cell::Empty; 16];   struct P15 { board: Board, }   impl P15 { fn new() -> Self { let mut board = EMPTY; for (i, cell) in board.iter_mut().enumerate().skip(1) { *cell = Cell::Card(i); }   let mut rng = rand::thread_rng();   board.shuffle(&mut rng); if !Self::is_valid(board) { // random swap let i = rng.gen_range(0, 16); let mut j = rng.gen_range(0, 16); while j == i { j = rng.gen_range(0, 16); } board.swap(i, j); }   Self { board } }   fn is_valid(mut board: Board) -> bool { // TODO: optimize let mut permutations = 0;   let pos = board.iter().position(|&cell| cell == Cell::Empty).unwrap();   if pos != 15 { board.swap(pos, 15); permutations += 1; }   for i in 1..16 { let pos = board .iter() .position(|&cell| match cell { Cell::Card(value) if value == i => true, _ => false, }) .unwrap();   if pos + 1 != i { board.swap(pos, i - 1); permutations += 1; } }   permutations % 2 == 0 }   fn get_empty_position(&self) -> usize { self.board.iter().position(|&c| c == Cell::Empty).unwrap() }   fn get_moves(&self) -> HashMap<Direction, Cell> { let mut moves = HashMap::new(); let i = self.get_empty_position();   if i > 3 { moves.insert(Direction::Up, self.board[i - 4]); } if i % 4 != 0 { moves.insert(Direction::Left, self.board[i - 1]); } if i < 12 { moves.insert(Direction::Down, self.board[i + 4]); } if i % 4 != 3 { moves.insert(Direction::Right, self.board[i + 1]); } moves }   fn play(&mut self, direction: &Direction) { let i = self.get_empty_position(); // This is safe because `ask_action` only returns legal moves match *direction { Direction::Up => self.board.swap(i, i - 4), Direction::Left => self.board.swap(i, i - 1), Direction::Right => self.board.swap(i, i + 1), Direction::Down => self.board.swap(i, i + 4), }; }   fn is_complete(&self) -> bool { self.board.iter().enumerate().all(|(i, &cell)| match cell { Cell::Card(value) => value == i + 1, Cell::Empty => i == 15, }) } }   impl fmt::Display for P15 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { r#try!(write!(f, "+----+----+----+----+\n")); for (i, &cell) in self.board.iter().enumerate() { match cell { Cell::Card(value) => r#try!(write!(f, "| {:2} ", value)), Cell::Empty => r#try!(write!(f, "| ")), }   if i % 4 == 3 { r#try!(write!(f, "|\n")); r#try!(write!(f, "+----+----+----+----+\n")); } } Ok(()) } }   fn main() { let mut p15 = P15::new();   for turns in 1.. { println!("{}", p15); match ask_action(&p15.get_moves()) { Action::Move(direction) => { p15.play(&direction); } Action::Quit => { println!("Bye !"); break; } }   if p15.is_complete() { println!("Well done ! You won in {} turns", turns); break; } } }   fn ask_action(moves: &HashMap<Direction, Cell>) -> Action { use std::io::{self, Write}; use Action::*; use Direction::*;   println!("Possible moves:");   if let Some(&Cell::Card(value)) = moves.get(&Up) { println!("\tU) {}", value); } if let Some(&Cell::Card(value)) = moves.get(&Left) { println!("\tL) {}", value); } if let Some(&Cell::Card(value)) = moves.get(&Right) { println!("\tR) {}", value); } if let Some(&Cell::Card(value)) = moves.get(&Down) { println!("\tD) {}", value); } println!("\tQ) Quit"); print!("Choose your move : "); io::stdout().flush().unwrap();   let mut action = String::new(); io::stdin().read_line(&mut action).expect("read error"); match action.to_uppercase().trim() { "U" if moves.contains_key(&Up) => Move(Up), "L" if moves.contains_key(&Left) => Move(Left), "R" if moves.contains_key(&Right) => Move(Right), "D" if moves.contains_key(&Down) => Move(Down), "Q" => Quit, _ => { println!("Unknown action: {}", action); ask_action(moves) } } }
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
#Dylan
Dylan
Module: bottles define method bottles (n :: <integer>) for (n from 99 to 1 by -1) format-out("%d bottles of beer on the wall,\n" "%d bottles of beer\n" "Take one down, pass it around\n" "%d bottles of beer on the wall\n", n, n, n - 1); end end method
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.
#Red
Red
  Red [] print "Evaluation from left to right with no precedence, unless you use parenthesis." print "" a: "123456789" guess: "" valid: "" sucess: false random/seed now/time loop 4 [append valid last random a] print ["The numbers are: " valid/1 ", " valid/2 ", " valid/3 " and " valid/4] sort valid insert valid " "   expr: [term ["+" | "-"] expr | term] term: [primary ["*" | "/"] term | primary] primary: [some digit | "(" expr ")"] digit: charset valid   while [not sucess] [ guess: ask "Enter your expression: " if guess = "q" [halt] numbers: copy guess sort numbers numbers: take/last/part numbers 4 insert numbers " " either (parse guess expr) and (valid = numbers) [ repeat i length? guess [insert at guess (i * 2) " "] result: do guess print ["The result of your expression is: " result] if (result = 24) [sucess: true] ][ print "Something is wrong with the expression, try again." ] ] print "You got it right!"    
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
#hexiscript
hexiscript
fun split s delim let ret dict 32 let l len s let j 0 let ret[0] "" for let i 0; i < l; i++ if s[i] = delim if len ret[j] > 0 let ret[++j] "" endif continue endif let ret[j] (ret[j] + s[i]) endfor return ret endfun   let nums split (scan str) ' ' let a tonum nums[0] let b tonum nums[1] println 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
#Scala
Scala
object AbcBlocks extends App {   protected class Block(face1: Char, face2: Char) {   def isFacedWith(that: Char) = { that == face1 || that == face2 } override def toString() = face1.toString + face2 } protected object Block { def apply(faces: String) = new Block(faces.head, faces.last) }   type word = Seq[Block]   private val blocks = List(Block("BO"), Block("XK"), Block("DQ"), Block("CP"), Block("NA"), Block("GT"), Block("RE"), Block("TG"), Block("QD"), Block("FS"), Block("JW"), Block("HU"), Block("VI"), Block("AN"), Block("OB"), Block("ER"), Block("FS"), Block("LY"), Block("PC"), Block("ZM"))   private def isMakeable(word: String, blocks: word) = {   def getTheBlocks(word: String, blocks: word) = {   def inner(word: String, toCompare: word, rest: word, accu: word): word = { if (word.isEmpty || rest.isEmpty || toCompare.isEmpty) accu else if (toCompare.head.isFacedWith(word.head)) { val restant = rest diff List(toCompare.head) inner(word.tail, restant, restant, accu :+ toCompare.head) } else inner(word, toCompare.tail, rest, accu) } inner(word, blocks, blocks, Nil) }   word.lengthCompare(getTheBlocks(word, blocks).size) == 0 }   val words = List("A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "CONFUSED", "ANBOCPDQERSFTGUVWXLZ") // Automatic tests assert(isMakeable(words(0), blocks)) assert(isMakeable(words(1), blocks)) assert(!isMakeable(words(2), blocks)) // BOOK not assert(isMakeable(words(3), blocks)) assert(!isMakeable(words(4), blocks)) // COMMON not assert(isMakeable(words(5), blocks)) assert(isMakeable(words(6), blocks)) assert(isMakeable(words(7), blocks))   //words(7).mkString.permutations.foreach(s => assert(isMakeable(s, blocks)))   words.foreach(w => println(s"$w can${if (isMakeable(w, blocks)) " " else "not "}be made.")) }
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.
#zkl
zkl
const SLOTS=100, PRISONERS=100, TRIES=50, N=10_000; fcn oneHundredJDI{ // just do it strategy cupboard,picks := [0..SLOTS-1].walk().shuffle(), cupboard.copy(); // if this prisoner can't find their number in TRIES, all fail foreach p in (PRISONERS){ if(picks.shuffle().find(p)>=TRIES) return(False); } True // all found their number } fcn oneHundredO{ // Optimal strategy cupboard := [0..SLOTS-1].walk().shuffle(); foreach p in (PRISONERS){ d:=p; do(TRIES){ if((d=cupboard[d]) == p) continue(2) } // found my number return(False); // this prisoner failed to find their number, all fail } True // all found their number }
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
#Scala
Scala
import java.util.Random   import jline.console._   import scala.annotation.tailrec import scala.collection.immutable import scala.collection.parallel.immutable.ParVector   object FifteenPuzzle { def main(args: Array[String]): Unit = play()   @tailrec def play(len: Int = 1000): Unit = if(gameLoop(Board.randState(len))) play(len) def gameLoop(board: Board): Boolean = { val read = new ConsoleReader() val km = KeyMap.keyMaps().get("vi-insert") val opMap = immutable.HashMap[Operation, Char]( Operation.PREVIOUS_HISTORY -> 'u', Operation.BACKWARD_CHAR -> 'l', Operation.NEXT_HISTORY -> 'd', Operation.FORWARD_CHAR -> 'r')   @tailrec def gloop(b: Board): Boolean = { println(s"\u001B[2J\u001B[2;0H$b\n←↑→↓q") if(b.isSolved) println("Solved!\nPlay again? (y/n)")   read.readBinding(km) match{ case Operation.SELF_INSERT => read.getLastBinding match{ case "q" => false case "y" if b.isSolved => true case "n" if b.isSolved => false case _ => gloop(b) } case op: Operation if opMap.isDefinedAt(op) => gloop(b.move(opMap(op))) case _ => gloop(b) } }   gloop(board) }   case class Board(mat: immutable.HashMap[(Int, Int), Int], x: Int, y: Int) { def move(mvs: Seq[Char]): Board = mvs.foldLeft(this){case (b, m) => b.move(m)} def move(mov: Char): Board = mov match { case 'r' if x < 3 => Board(mat ++ Seq(((x, y), mat((x + 1, y))), ((x + 1, y), 0)), x + 1, y) case 'l' if x > 0 => Board(mat ++ Seq(((x, y), mat((x - 1, y))), ((x - 1, y), 0)), x - 1, y) case 'd' if y < 3 => Board(mat ++ Seq(((x, y), mat((x, y + 1))), ((x, y + 1), 0)), x, y + 1) case 'u' if y > 0 => Board(mat ++ Seq(((x, y), mat((x, y - 1))), ((x, y - 1), 0)), x, y - 1) case _ => this }   def isSolved: Boolean = sumDist == 0 def sumDist: Int = mat.to(LazyList).map{ case ((a, b), n) => if(n == 0) 6 - a - b else (a + b - ((n - 1) % 4) - ((n - 1) / 4)).abs }.sum   override def toString: String = { val lst = mat.toVector.map { case ((a, b), n) => (4 * b + a, n) }.sortWith(_._1 < _._1).map(_._2) lst.map { n => if (n == 0) " " else f"$n%2d" }.grouped(4).map(_.mkString(" ")).mkString("\n") } }   object Board { val moves: Vector[Char] = Vector('r', 'l', 'd', 'u')   def apply(config: Vector[Int]): Board = { val ind = config.indexOf(0) val formed = config.zipWithIndex.map { case (n, i) => ((i % 4, i / 4), n) } val builder = immutable.HashMap.newBuilder[(Int, Int), Int] builder ++= formed Board(builder.result, ind % 4, ind / 4) }   def solveState: Board = apply((1 to 15).toVector :+ 0) def randState(len: Int, rand: Random = new Random()): Board = Iterator .fill(len)(moves(rand.nextInt(4))) .foldLeft(Board.solveState) { case (state, mv) => state.move(mv) } } }
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
#D.C3.A9j.C3.A0_Vu
Déjà Vu
plural i: if = 1 i "" "s"   bottles i: local :s plural i !print( to-str i " bottle"s" of beer on the wall, " to-str i " bottle"s" of beer," ) !print\ "You take one down, pass it around, " set :i -- i if i: set :s plural i !print( to-str i " bottle"s" of beer on the wall." ) bottles i else: !print "no more bottles of beer on the wall, no more bottles of beer." !print "Go to the store and buy some more, 99 bottles of beer on the wall."   bottles 99
http://rosettacode.org/wiki/24_game
24 game
The 24 Game tests one's mental arithmetic. Task Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed. The program should prompt for the player to enter an arithmetic expression using just those, and all of those four digits, used exactly once each. 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.
#REXX
REXX
/*REXX program helps the user find solutions to the game of 24.   ╔═════════════════════════════════════════════════════════════════════════════╗ ║ Argument is either of these forms: (blank) ║⌂ ║ ssss ║⌂ ║ ssss,total,limit ║⌂ ║ ssss-ffff ║⌂ ║ ssss-ffff,total,limit ║⌂ ║ -ssss ║⌂ ║ +ssss ║⌂ ║ ║⌂ ║ where SSSS and/or FFFF must be exactly four numerals (decimal digits) ║⌂ ║ comprised soley of the numerals (digits) 1 ──► 9 (no zeroes). ║⌂ ║ ║⌂ ║ SSSS is the start, and FFFF is the end (inclusive). ║⌂ ║ ║⌂ ║ If ssss has a leading plus (+) sign, it's used as the digits, and ║⌂ ║ the user is prompted to enter a solution (using those decimal digits). ║⌂ ║ ║⌂ ║ If ssss has a leading minus (-) sign, a solution is searched for and ║⌂ ║ the user is told there is a solution (or not), but no solutions are shown).║⌂ ║ ║⌂ ║ If no argument is specified, this program generates four digits (no zeros) ║⌂ ║ which has at least one solution, and shows the sorted digits to the user, ║⌂ ║ requesting that they enter a solution (the digits used may be in any order).║⌂ ║ ║⌂ ║ If TOTAL is entered, it's the desired answer. The default is 24. ║⌂ ║ If LIMIT is entered, it limits the number of solutions shown. ║⌂ ║ ║⌂ ║ A solution to be entered can be in the form of: ║ ║ ║ ║ digit1 operator digit2 operator digit3 operator digit4 ║ ║ ║ ║ where DIGITn is one of the digits shown (in any order), and ║ ║ OPERATOR can be any one of: + - * / ║ ║ ║ ║ Parentheses () may be used in the normal manner for grouping, as well as ║ ║ brackets [] or braces {}. Blanks can be used anywhere. ║ ║ ║ ║ I.E.: for the digits 3448 the following could be entered: 3*8 + (4-4) ║ ╚═════════════════════════════════════════════════════════════════════════════╝ */   numeric digits 30 /*where rational arithmetic is needed. */ parse arg orig; uargs= orig /*get the guess from the command line*/ orig= space(orig, 0) /*remove all the blanks from ORIG. */ negatory= left(orig, 1)=='-' /*=1, suppresses showing. */ pository= left(orig, 1)=='+' /*=1, force pgm to use specific number.*/ if pository | negatory then orig=substr(orig,2) /*now, just use the absolute vaue. */ parse var orig orig ',' $ "," limit /*get optional total ($) and/or limit*/ parse var orig start '-' finish /*get start and finish (maybe). */ opers= '*' || "/+-" /*arithmetic opers; order is important.*/ ops= length(opers) /*the number of arithmetic operators. */ groupsym= space(' ( ) [ ] { } « » ', 0) /*the allowable grouping symbols. */ indent= left('', 30) /*indents the display of solutions. */ show= 1 /*=1, shows solutions (a semifore). */ digs= 123456789 /*numerals (digits) that can be used.*/ if $=='' then $= 24 /*the name (goal) of the game: (24) */ if limit=='' then limit= 1 /*=1, shows only one solution. */ __= copies('─', 8) /*used for output messages to the user.*/ abuttals = 0 /*=1, allows digit abuttal: 12+12 */ do j=1 for ops; o.j= substr(opers, j, 1) /*these are used for fast execution. */ end /*j*/ if \datatype(limit, 'N') then do; call ger limit "isn't numeric"; exit 13; end limit= limit / 1 /*normalize the number for limit. */ if \datatype($, 'N') then do; call ger $ "isn't numeric"; exit 13; end $= $ / 1 /*normalize the number for total. */ if start\=='' & \pository then do; call ranger start,finish; exit 1; end show= 0 /*stop blabbing solutions in SOLVE. */ do forever while \negatory /*keep truckin' until a solution. */ x.= 0 /*way to hold unique expressions. */ rrrr= random(1111, 9999) /*get a random set of digits. */ if pos(0, rrrr)\==0 then iterate /*but don't the use of zeroes. */ if solve(rrrr)\==0 then leave /*try to solve for these digits. */ end /*forever*/ show= 1 /*enable SOLVE to show solutions. */ if pository then rrrr= start /*use what's specified. */ rrrr= sortc(rrrr) /*sort four elements. */ rd.= x. do j=1 for 9; _= substr(rrrr, j, 1); rd._= #chrs(rrrr, _) end /*j*/ /* [↑] count for each digit in RRRR. */ do guesses=1; say say __ "Using the numerals (digits) " rrrr", enter an expression that equals " $ say right('(or  ? or Quit):', 79) pull y; uargs= y; y= space(y, 0) /*obtain user's response (expression). */ if abbrev('QUIT', y, 1) then exit 0 /*does the user want to quit this game?*/ if y=='?' then do j=2 for sourceline()-1; _= sourceline(j) /*get a line of pgm. */ if right(_, 1)=='⌂' then iterate /*ignore this doc part*/ say ' ' strip( left(_, 79), 'T') /*show " " " doc. */ if left(_, 1)=='╚' then iterate guesses end /*j*/ /* [↑] use an in─line way to show help*/ _v= verify(y, digs || opers || groupsym) /*any illegal characters? */ if _v\==0 then do; call ger 'invalid character:' substr(y, _v, 1); iterate; end if y='' then do; call validate y; iterate; end   do j=1 for length(y)-1 while \abuttals /*check for two adjacent decimal digits*/ if datatype( substr(y, j, 1), 'W') & datatype( substr(y, j+1, 1), 'W') then , do; call ger 'invalid use of digit abuttal:' substr(y, j, 2) iterate guesses end end /*j*/   yy= translate(y, ')))', "]}»") /*use a simlier form for the expression*/   do j=1 for 9 while \abuttals /*check for a dig following a group sym*/ _= pos(')'j, yy) /*is there a string with: )DIGIT  ? */ if _>0 then do; call ger 'invalid use of digit abuttal' substr(y, _, 2) iterate guesses end end /*j*/   yd= #chrs(y, digs) /*count of legal digits 123456789 */ if yd<4 then do; call ger 'not enough numerals were entered.'; iterate guesses; end if yd>4 then do; call ger 'too many numerals were entered.'  ; iterate guesses; end   do j=1 for length(groupsym) by 2 if #chrs(y, substr(groupsym, j , 1))\==, #chrs(y, substr(groupsym, j+1, 1)) then do; call ger 'mismatched' , substr(groupsym, j, 2) iterate guesses end end /*j*/   do k=1 for 2 /*check for ** and // */ _= copies( substr( opers, k, 1), 2) /*only examine the first two operators.*/ if pos(_, y)\==0 then do; call ger 'illegal operator:' _; iterate guesses; end end /*k*/   do j=1 for 9; if rd.j==0 then iterate; _d= #chrs(y, j) if _d==rd.j then iterate if _d<rd.j then call ger 'not enough' j "numerals were entered, must be" rd.j else call ger 'too many' j "numerals were entered, must be" rd.j iterate guesses end /*j*/   y= translate(y, '()()', "[]{}") /*change extended grouping symbols──►()*/ interpret 'ans=(' y ") / 1" /*evalualte a normalized expression. */ oldDigs= digits() /*save current decimal digit setting. */ numeric digits digits()%2 /*normalize expresssion to less digits.*/ if ans/1=$ then leave guesses /*the expression calculates to 24. */ say __ "incorrect, " y"="ans /*issue an error message (incorrect). */ numeric digits oldDigs /*re─instate the decimal digs precision*/ end /*guesses*/   say; say center('┌─────────────────────┐', 79) say center('│ │', 79) say center('│ congratulations ! │', 79) say center('│ │', 79) say center('└─────────────────────┘', 79); say exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ #chrs:procedure; parse arg x,c; return length(x) - length( space( translate(x, , c), 0) ) div: procedure; parse arg q; if q=0 then q=1e9; return q /*tests if dividing by zero.*/ ger: say __ '***error*** for argument: ' uargs; say __ arg(1); errCode= 1; return 0 s: if arg(1)==1 then return arg(3); return word( arg(2) 's', 1) /*──────────────────────────────────────────────────────────────────────────────────────*/ ranger: parse arg ssss,ffff /*parse args passed to this sub. */ ffff= word(ffff ssss, 1) /*create a FFFF if necessary. */ do g=ssss to ffff /*process possible range of values. */ if pos(0, g)\==0 then iterate /*ignore any G number with zeroes. */ sols= solve(g); wols= sols if sols==0 then wols= 'No' /*un─geek number of solutions (if any).*/ if negatory & sols\==0 then wols= 'A' /*found only the first solution? */ if sols==1 & limit==1 then wols= 'A' say; say wols 'solution's(sols) "found for" g if $\==24 then say 'for answers that equal' $ end /*g*/ return /*──────────────────────────────────────────────────────────────────────────────────────*/ solve: parse arg qqqq; finds= 0; x.=0; nq.= x. /*parse args passed to this function. */ if \validate(qqqq) then return -1 parse value '( (( )) )' with L LL RR R /*assign some static variables (fastly)*/   do jq=1 for 4; _= substr(qqqq,jq,1) /*count the number of each digit. */ nq._= nq._ + 1 end /*jq*/   gLO= 1111; gHI= 9999 if $==24 then do; gLO= 1118; gHI= 9993; end /*24: lowest poss.# that has solutions*/   do gggg=gLO to gHI; if pos(0, gggg)\==0 then iterate /*ignore values with zeroes.*/ if verify(gggg, qqqq)\==0 then iterate if verify(qqqq, gggg)\==0 then iterate ng.= 0 do jg=1 for 4; _= substr(gggg, jg, 1); g.jg= _; ng._= ng._ + 1 end /*jg*/ /* [↑] count the number of each digit.*/ do kg=1 for 9; if nq.kg\==ng.kg then iterate gggg end /*kg*/ /* [↑] verify number has same # digits*/ do i=1 for ops /*insert operator after 1st numeral. */ do j=1 for ops /* " " " 2nd " */ do k=1 for ops /* " " " 3rd " */ do m=0 for 10;  !.= /*nullify all grouping symbols (parens)*/ select /*used to generate grouped expressions.*/ when m==1 then do; !.1=L;  !.3=R; end when m==2 then do; !.1=L;  !.5=R; end when m==3 then do; !.1=L;  !.3=R;  !.4=L;  !.6=R; end when m==4 then do;  !.2=L;  !.5=R; end when m==5 then do;  !.2=L;  !.6=R; end when m==6 then do; !.1=LL;  !.5=R;  !.6=R; end when m==7 then do;  !.2=LL;  !.5=R;  !.6=R; end when m==8 then do; !.1=L;  !.2=L;  !.6=RR; end when m==9 then do;  !.2=L;  !.4=L;  !.6=RR; end otherwise nop end /*select*/   e= space(!.1 g.1 o.i  !.2 g.2 !.3 o.j  !.4 g.3 !.5 o.k g.4  !.6, 0) if x.e then iterate /*was the expression already used? */ x.e= 1 /*mark this expression as being used. */ origE= e /*keep original version for the display*/ pd= pos('/(', e) /*find pos of /( in E. */ if pd\==0 then do /*Found? Might have possible ÷ by zero*/ eo= e lr= lastpos(')', e) /*find the last right parenthesis. */ lm= pos('-', e, pd+1) /*find a minus sign (-) after ( */ if lm>pd & lm<lr then e= changestr('/(',e,"/div(") /*change*/ if eo\==e then if x.e then iterate /*expression already used?*/ x.e= 1 /*mark this expression as being used. */ end interpret 'x=(' e ") / 1" /*have REXX do the heavy lifting here. */ if x\==$ then do /*Not correct? Then try again. */ numeric digits 9; x= x / 1 /*re─do evaluation.*/ numeric digits 12 /*re─instate digits*/ if x\==$ then iterate /*Not correct? Then try again. */ end finds= finds + 1 /*bump number of found solutions. */ if \show | negatory then return finds _= translate(origE, '][', ")(") /*display [], not (). */ if show then say indent 'a solution for' gggg':' $"=" _ /*show solution.*/ if limit==1 & finds==limit then leave gggg /*leave big loop*/ end /*m*/ end /*k*/ end /*j*/ end /*i*/ end /*gggg*/ return finds /*──────────────────────────────────────────────────────────────────────────────────────*/ sortc: procedure; arg nnnn; @.= /*sorts the digits of NNNN */ do i=1 for length(nnnn); _= substr(nnnn, i, 1); @._= @._||_; end /*i*/ return @.0 || @.1 || @.2 || @.3 || @.4 || @.5 || @.6 || @.7 || @.8 || @.9 /*──────────────────────────────────────────────────────────────────────────────────────*/ validate: parse arg y; errCode= 0; _v= verify(y, digs) select when y=='' then call ger 'no digits were entered.' when length(y)<4 then call ger 'not enough digits entered, must be 4' when length(y)>4 then call ger 'too many digits entered, must be 4' when pos(0,y)\==0 then call ger "can't use the digit 0 (zero)" when _v\==0 then call ger 'illegal character:' substr(y, _v, 1) otherwise nop end /*select*/
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
#HicEst
HicEst
DLG(Edit=A, DNum, MIn=-1000, MAx=1000, E=B, DN, MI=-1000, MA=1000) WRITE(Messagebox, Name) A, B, "Sum = ", 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
#Scheme
Scheme
(define *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)))   (define (exists p? li) (and (not (null? li)) (or (p? (car li)) (exists p? (cdr li)))))   (define (remove-one x li) (cond ((null? li) '()) ((equal? (car li) x) (cdr li)) (else (cons (car li) (remove-one x (cdr li))))))   (define (can-make-list? li blocks) (or (null? li) (exists (lambda (block) (and (member (char-upcase (car li)) block) (can-make-list? (cdr li) (remove-one block blocks)))) blocks)))   (define (can-make-word? word) (can-make-list? (string->list word) *blocks*))     (define *words* '("A" "Bark" "book" "TrEaT" "COMMON" "squaD" "CONFUSE"))   (for-each (lambda (word) (display (if (can-make-word? word) " Can make word: " "Cannot make word: ")) (display word) (newline)) *words*)
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
#Scheme
Scheme
  (import (scheme base) (scheme read) (scheme write) (srfi 27)) ; random numbers   (define *start-position* #(1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 #\space)) (random-source-randomize! default-random-source)   ;; return a 16-place vector with the tiles randomly shuffled (define (create-start-position) (let ((board (vector-copy *start-position*))) (do ((i 0 (+ 1 i)) (moves (find-moves board) (find-moves board))) ((and (>= i 100) (not (finished? board))) board) (make-move board (list-ref moves (random-integer (length moves)))))))   ;; return index of space (define (find-space board) (do ((i 0 (+ 1 i))) ((equal? #\space (vector-ref board i)) i)))   ;; return a list of symbols indicating available moves (define (find-moves board) (let* ((posn (find-space board)) (row (quotient posn 4)) (col (remainder posn 4)) (result '())) (when (> row 0) (set! result (cons 'up result))) (when (< row 3) (set! result (cons 'down result))) (when (> col 0) (set! result (cons 'left result))) (when (< col 3) (set! result (cons 'right result))) result))   ;; make given move - assume it is legal (define (make-move board move) (define (swap posn-1 posn-2) (let ((tmp (vector-ref board posn-1))) (vector-set! board posn-1 (vector-ref board posn-2)) (vector-set! board posn-2 tmp))) ; (let ((posn (find-space board))) (case move ((left) (swap posn (- posn 1))) ((right) (swap posn (+ posn 1))) ((up) (swap posn (- posn 4))) ((down) (swap posn (+ posn 4))))))   (define (finished? board) (equal? board *start-position*))   (define (display-board board) (do ((i 0 (+ 1 i))) ((= i (vector-length board)) (newline)) (when (zero? (modulo i 4)) (newline)) (let ((curr (vector-ref board i))) (display curr) (display (if (and (number? curr) (> curr 9)) " " " ")))))   ;; the main game loop (define (play-game) (let ((board (create-start-position))) (do ((count 1 (+ count 1)) (moves (find-moves board) (find-moves board))) ((finished? board) (display (string-append "\nCOMPLETED PUZZLE in " (number->string count) " moves\n"))) (display-board board) (display "Enter a move: ") (display moves) (newline) (let ((move (read))) (if (memq move moves) (make-move board move) (display "Invalid move - try again"))))))   (play-game)  
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
#DIBOL-11
DIBOL-11
  ; ;=============================================================================== ======================== ; Oringinal Author: Bob Welton ([email protected]) ; Language: DIBOL or DBL ; ; Modified to work with DEC DIBOL-11 ; by Bill Gunshannon ;=============================================================================== ========================   RECORD MISC NUMBOTTLES ,D2,99  ;Default # of bottles to 99   RECORD LINE1 ANUMBOTTLES, A2 , A32, " Bottles of Beer on the wall,"   RECORD LINE2 BNUMBOTTLES, A2 , A32, " Bottles of Beer,"   RECORD LINE3 CNUMBOTTLES, A2 , A32, " Bottles of Beer on the wall."   RECORD LINE4 DNUMBOTTLES, A2 , A32, " Bottle of Beer on the wall,"   RECORD LINE5 ENUMBOTTLES, A2 , A32, " Bottle of Beer,"           .PROC XCALL FLAGS (0007000000,1)  ;Suppress STOP message OPEN (8,O:C,"TT:")  ;Open the terminal/display REPEAT BEGIN ANUMBOTTLES = NUMBOTTLES,'ZX' WRITES (8,LINE1) BNUMBOTTLES = NUMBOTTLES,'ZX' WRITES (8,LINE2) WRITES (8," Take one down, pass it around,") DECR NUMBOTTLES  ;Reduce # of bottles by 1 IF (NUMBOTTLES .LE. 1) EXITLOOP ;If just 1 bottle left, get out CNUMBOTTLES = NUMBOTTLES,'ZX' WRITES (8,LINE3) WRITES (8," ") END DNUMBOTTLES = NUMBOTTLES,'ZX' WRITES(8,LINE4) WRITES (8," ") ENUMBOTTLES = NUMBOTTLES,'ZX' WRITES(8,LINE5) WRITES (8," Take one down, pass it around,") WRITES(8,"0 Bottles of Beer on the wall,") WRITES(8,"0 Bottles of Beer,") WRITES(8,"Go to the store and buy some more,") WRITES(8,"99 Bottles of Beer on the wall,")   WRITES (8," ") WRITES (8," ") SLEEP 2 CLOSE 8 STOP .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.
#Ring
Ring
  # Project : 24 game   load "stdlib.ring" digits = list(4) check = list(4) for choice = 1 to 4 digits[choice] = random(9) next   see "enter an equation (using all of, and only, the single digits " + nl for index = 1 to 4 see digits[index] if index != 4 see " " ok next see ")" see " which evaluates to exactly 24. only multiplication (*), division (/)," + nl see "addition (+) & subtraction (-) operations and parentheses are allowed:" + nl see "24 = " give equation see "equation = " + equation + nl   while true for char = 1 to len(equation) digit = substr("0123456789", equation[char]) - 1 if digit >= 0 for index = 1 to 4 if digit = digits[index] if not check[index] check[index] = 1 exit ok ok next if index > 4 see "sorry, you used the illegal digit " + digit + nl exit 2 ok ok next for index = 1 to 4 if check[index] = 0 see "sorry, you failed to use the digit " + digits[index] + nl exit 2 ok next for pair = 11 to 99 if substr(equation, string(pair)) see "sorry, you may not use a pair of digits " + pair + nl ok next eval("result = " + equation) if result = 24 see "congratulations, you succeeded in the task!" + nl exit else see "sorry, your equation evaluated to " + result + " rather than 24!" + nl ok end  
http://rosettacode.org/wiki/A%2BB
A+B
A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separated by space(s): ( − 1000 ≤ 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
#Hoon
Hoon
  |= [a=@ud b=@ud] (add 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
#Seed7
Seed7
$ include "seed7_05.s7i";   const func boolean: canMakeWords (in array string: blocks, in string: word) is func result var boolean: okay is FALSE; local var integer: index is 1; begin if word = "" then okay := TRUE; elsif length(blocks) <> 0 then while index <= length(blocks) and not okay do if blocks[index][1] = word[1] or blocks[index][2] = word[1] then okay := canMakeWords(blocks[.. pred(index)] & blocks[succ(index) ..], word[2 ..]); end if; incr(index); end while; end if; end func;   const array string: blocks is [] ("BO", "XK", "DQ", "CP", "NA", "GT", "RE", "TG", "QD", "FS", "JW", "HU", "VI", "AN", "OB", "ER", "FS", "LY", "PC", "ZM");   const func boolean: canMakeWords (in string: word) is return canMakeWords(blocks, upper(word));   const proc: main is func local var string: word is ""; begin for word range [] ("", "A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "Confuse") do writeln(word rpad 10 <& canMakeWords(word)); end for; end func;
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
#Scilab
Scilab
tiles=[1:15,0]; solution=[tiles(1:4);... tiles(5:8);... tiles(9:12);... tiles(13:16)]; solution=string(solution); solution(16)=" ";   init_pos=grand(1,"prm",tiles); puzzle=[init_pos(1:4);... init_pos(5:8);... init_pos(9:12);... init_pos(13:16)]; puzzle=string(puzzle);   blank_pos=[]; for i=1:4 for j=1:4 if puzzle(i,j)=="0" then blank_pos=[i,j]; end end end   clear i j   puzzle(blank_pos(1),blank_pos(2))=" ";   n_moves=0; solved=%F; while ~solved disp(puzzle); mprintf("\n");   neighbours=[0 -1;... -1 0;... 0 +1;... +1 0]; neighbours(:,1)=neighbours(:,1)+blank_pos(1); neighbours(:,2)=neighbours(:,2)+blank_pos(2); neighbours=[neighbours zeros(4,1)]   i=0; for i=1:4 if ~(neighbours(i,1)<1 | neighbours(i,1)>4 |... neighbours(i,2)<1 | neighbours(i,2)>4) then neighbours(i,3)=evstr(puzzle(neighbours(i,1),neighbours(i,2))); end end   valid_move=%F; while ~valid_move move_tile=[]; move_tile=input("Enter tile you want to move (0 to exit):"); if sum(move_tile==neighbours(:,3)) & move_tile~=0 then valid_move=%T; n_moves=n_moves+1; elseif move_tile==0 then disp("Exit"); abort else disp(puzzle); disp("Invalid input"); end end   neighb_i=find(neighbours(:,3)'==move_tile); puzzle(neighbours(neighb_i,1),neighbours(neighb_i,2))=" "; puzzle(blank_pos(1),blank_pos(2))=string(move_tile); blank_pos=neighbours(neighb_i,1:2);   if sum(puzzle==solution)==16 then solved=%T; disp(puzzle); mprintf("\n"+... " _____ _ _ _ \n"+... " / ____| | | | | |\n"+... " | (___ ___ | |_ _____ __| | |\n"+... " \\___ \\ / _ \\| \\ \\ / / _ \\/ _` | |\n"+... " ____) | (_) | |\\ V / __/ (_| |_|\n"+... " |_____/ \\___/|_| \\_/ \\___|\\__,_(_)\n") end end   disp("Solved in "+string(n_moves)+" moves.");
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
#E
E
def bottles(n) { return switch (n) { match ==0 { "No bottles" } match ==1 { "1 bottle" } match _ { `$n bottles` } } } for n in (1..99).descending() { println(`${bottles(n)} of beer on the wall, ${bottles(n)} of beer. Take one down, pass it around, ${bottles(n.previous())} 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.
#Ruby
Ruby
class Guess < String def self.play nums = Array.new(4){rand(1..9)} loop do result = get(nums).evaluate! break if result == 24.0 puts "Try again! That gives #{result}!" end puts "You win!" end   def self.get(nums) loop do print "\nEnter a guess using #{nums}: " input = gets.chomp return new(input) if validate(input, nums) end end   def self.validate(guess, nums) name, error = { invalid_character: ->(str){ !str.scan(%r{[^\d\s()+*/-]}).empty? }, wrong_number: ->(str){ str.scan(/\d/).map(&:to_i).sort != nums.sort }, multi_digit_number: ->(str){ str.match(/\d\d/) } } .find {|name, validator| validator[guess] }   error ? puts("Invalid input of a(n) #{name.to_s.tr('_',' ')}!") : true end   def evaluate! as_rat = gsub(/(\d)/, '\1r') # r : Rational suffix eval "(#{as_rat}).to_f" rescue SyntaxError "[syntax error]" end end   Guess.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
#Hope
Hope
$ cd lib $ ../src/hope >: dec add : num # num -> num; >: --- add(a,b) <= a + b; >: add(3,99) >: ^D >> 102 : num
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
#SenseTalk
SenseTalk
function CanMakeWord word   put [ ("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") ] into blocks   repeat with each character letter of word put False into found repeat with each item block of blocks by reference if item 1 of block is letter ignoring case or item 2 of block is letter ignoring case delete block put True into found exit repeat end if end repeat if found is False return False end if end repeat return True   end CanMakeWord
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
#Simula
Simula
  BEGIN CLASS FIFTEENPUZZLE(NUMTILES, SIDE, WIDTH, SEED); INTEGER NUMTILES, SIDE, WIDTH, SEED; BEGIN INTEGER ARRAY TILES(0:NUMTILES); INTEGER BLANKPOS;   PROCEDURE INVARIANT; BEGIN INTEGER ARRAY UQ(0:NUMTILES); INTEGER I; FOR I := 0 STEP 1 UNTIL NUMTILES DO UQ(I) := -1; FOR I := 0 STEP 1 UNTIL NUMTILES DO BEGIN INTEGER T; T := TILES(I); IF UQ(T) <> -1 THEN ERROR("TILES ARE NOT UNIQUE"); UQ(T) := T; END; IF TILES(BLANKPOS) <> 0 THEN ERROR("BLANKPOS IS NOT BLANK"); END;   PROCEDURE SHUFFLE; BEGIN BOOLEAN B; WHILE NOT B DO BEGIN INTEGER N; RESET;  ! DON'T INCLUDE THE BLANK SPACE IN THE SHUFFLE, LEAVE IT  ! IN THE HOME POSITION ; N := NUMTILES; WHILE N > 1 DO BEGIN INTEGER R, TMP; R := UNIFORM(0, N, SEED); N := N - 1; TMP := TILES(R); TILES(R) := TILES(N); TILES(N) := TMP; END; B := ISSOLVABLE; END; INVARIANT; END;   PROCEDURE RESET; BEGIN INTEGER I; FOR I := 0 STEP 1 UNTIL NUMTILES DO TILES(I) := MOD((I + 1), NUMTILES + 1); BLANKPOS := NUMTILES; INVARIANT; END;    ! ONLY HALF THE PERMUTATIONS OF THE PUZZLE ARE SOLVABLE.  ! WHENEVER A TILE IS PRECEDED BY A TILE WITH HIGHER VALUE IT COUNTS  ! AS AN INVERSION. IN OUR CASE, WITH THE BLANK SPACE IN THE HOME  ! POSITION, THE NUMBER OF INVERSIONS MUST BE EVEN FOR THE PUZZLE  ! TO BE SOLVABLE.  ! SEE ALSO:  ! WWW.CS.BHAM.AC.UK/~MDR/TEACHING/MODULES04/JAVA2/TILESSOLVABILITY.HTML  ;   BOOLEAN PROCEDURE ISSOLVABLE; BEGIN INTEGER COUNTINVERSIONS; INTEGER I, J; FOR I := 0 STEP 1 UNTIL NUMTILES - 1 DO FOR J := 0 STEP 1 UNTIL I - 1 DO IF TILES(J) > TILES(I) THEN COUNTINVERSIONS := COUNTINVERSIONS + 1; ISSOLVABLE := MOD(COUNTINVERSIONS, 2) = 0; END;   PROCEDURE PRINTBOARD; BEGIN INTEGER I, J;   PROCEDURE PRINTLINE; BEGIN INTEGER ROW, COL;  ! +-----+-----+-----+-----+ ; FOR ROW := 1 STEP 1 UNTIL SIDE DO BEGIN OUTCHAR('+'); FOR COL := 0 STEP 1 UNTIL WIDTH DO OUTCHAR('-'); END; OUTCHAR('+'); OUTIMAGE; END;   PROCEDURE PRINTCELL(T); INTEGER T; BEGIN IF T = 0 THEN BEGIN INTEGER R; FOR R := 1 STEP 1 UNTIL WIDTH DO OUTCHAR(' '); END ELSE OUTINT(T, WIDTH); OUTCHAR(' '); END;    ! +-----+-----+-----+-----+  ! | 1 | 2 | 3 | 4 |  ! +-----+-----+-----+-----+  ! | 5 | 6 | 7 | 8 |  ! +-----+-----+-----+-----+  ! | 9 | 10 | 11 | |  ! +-----+-----+-----+-----+  ! | 13 | 14 | 15 | 12 |  ! +-----+-----+-----+-----+  ;   FOR I := 1 STEP 1 UNTIL SIDE DO BEGIN PRINTLINE; OUTCHAR('|'); FOR J := 1 STEP 1 UNTIL SIDE DO BEGIN INTEGER T; T := TILES((I - 1) * SIDE + (J - 1)); PRINTCELL(T); OUTCHAR('|'); END; OUTIMAGE; END; PRINTLINE; END;   BOOLEAN PROCEDURE DONE; BEGIN BOOLEAN ORDERED; INTEGER I, EXPECT; ORDERED := TRUE; EXPECT := 1; FOR I := 0 STEP 1 UNTIL NUMTILES - 1 DO BEGIN IF I <> BLANKPOS THEN BEGIN IF TILES(I) <> EXPECT THEN ORDERED := FALSE; EXPECT := EXPECT + 1; END; END; DONE := ORDERED; END;   PROCEDURE REQUEST; BEGIN INTEGER ARRAY CANDIDATES(1:4); INTEGER I, CANDCOUNT, CHOOSE; BOOLEAN VALIDINPUT;   PROCEDURE ADDCAND(IDX); INTEGER IDX; BEGIN IF IDX >= 0 AND IDX <= NUMTILES THEN BEGIN CANDCOUNT := CANDCOUNT + 1; CANDIDATES(CANDCOUNT) := TILES(IDX); END; END;   PRINTBOARD;   IF BLANKPOS <= NUMTILES - SIDE THEN ADDCAND(BLANKPOS + SIDE); IF BLANKPOS >= SIDE THEN ADDCAND(BLANKPOS - SIDE); IF MOD(BLANKPOS, SIDE) <> SIDE - 1 THEN ADDCAND(BLANKPOS + 1); IF MOD(BLANKPOS, SIDE) <> 0 THEN ADDCAND(BLANKPOS - 1);   WHILE NOT VALIDINPUT DO BEGIN OUTTEXT("YOUR MOVE: ");   FOR I := 1 STEP 1 UNTIL CANDCOUNT DO OUTINT(CANDIDATES(I), SIDE); OUTIMAGE; CHOOSE := ININT;   FOR I := 1 STEP 1 UNTIL CANDCOUNT DO IF CHOOSE = CANDIDATES(I) THEN BEGIN INTEGER LOOKUP; FOR LOOKUP := 0 STEP 1 UNTIL NUMTILES DO IF NOT VALIDINPUT AND TILES(LOOKUP) = CHOOSE THEN BEGIN TILES(BLANKPOS) := TILES(LOOKUP); TILES(LOOKUP) := 0; BLANKPOS := LOOKUP; INVARIANT; VALIDINPUT := TRUE; END; END;   IF NOT VALIDINPUT THEN BEGIN OUTTEXT("INVALID INPUT!"); OUTIMAGE; END; END; END;   SHUFFLE; END;   REF(FIFTEENPUZZLE) P;   OUTTEXT("INPUT RANDOM SEED: "); OUTIMAGE; P :- NEW FIFTEENPUZZLE(15, 4, 3, ININT); ! ININT = RANDOM SEED ; WHILE NOT P.DONE DO P.REQUEST; P.PRINTBOARD; 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
#ECL
ECL
  Layout := RECORD UNSIGNED1 RecID1; UNSIGNED1 RecID2; STRING30 txt; END; Beers := DATASET(99,TRANSFORM(Layout, SELF.RecID1 := COUNTER,SELF.RecID2 := 0,SELF.txt := ''));   Layout XF(Layout L,INTEGER C) := TRANSFORM IsOneNext := L.RecID1-1 = 1; IsOne := L.RecID1 = 1; SELF.txt := CHOOSE(C, (STRING)(L.RecID1-1) + ' bottle'+IF(IsOneNext,'','s')+' of beer on the wall', 'Take one down, pass it around', (STRING)(L.RecID1) + ' bottle'+IF(IsOne,'','s')+' of beer', (STRING)(L.RecID1) + ' bottle'+IF(IsOne,'','s')+' of beer on the wall',''); SELF.RecID2 := C; SELF := L; END;   Rev := NORMALIZE(Beers,5,XF(LEFT,COUNTER)); OUTPUT(SORT(Rev,-Recid1,-RecID2),{txt},ALL);  
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.
#Rust
Rust
use std::io::{self,BufRead}; extern crate rand; use rand::Rng;   fn op_type(x: char) -> i32{ match x { '-' | '+' => return 1, '/' | '*' => return 2, '(' | ')' => return -1, _ => return 0, } }   fn to_rpn(input: &mut String){   let mut rpn_string : String = String::new(); let mut rpn_stack : String = String::new(); let mut last_token = '#'; for token in input.chars(){ if token.is_digit(10) { rpn_string.push(token); } else if op_type(token) == 0 { continue; } else if op_type(token) > op_type(last_token) || token == '(' { rpn_stack.push(token); last_token=token; } else { while let Some(top) = rpn_stack.pop() { if top=='(' { break; } rpn_string.push(top); } if token != ')'{ rpn_stack.push(token); } } } while let Some(top) = rpn_stack.pop() { rpn_string.push(top); }   println!("you formula results in {}", rpn_string);   *input=rpn_string; }   fn calculate(input: &String, list : &mut [u32;4]) -> f32{ let mut stack : Vec<f32> = Vec::new(); let mut accumulator : f32 = 0.0;   for token in input.chars(){ if token.is_digit(10) { let test = token.to_digit(10).unwrap() as u32; match list.iter().position(|&x| x == test){ Some(idx) => list[idx]=10 , _ => println!(" invalid digit: {} ",test), } stack.push(accumulator); accumulator = test as f32; }else{ let a = stack.pop().unwrap(); accumulator = match token { '-' => a-accumulator, '+' => a+accumulator, '/' => a/accumulator, '*' => a*accumulator, _ => {accumulator},//NOP }; } } println!("you formula results in {}",accumulator); accumulator }   fn main() {   let mut rng = rand::thread_rng(); let mut list :[u32;4]=[rng.gen::<u32>()%10,rng.gen::<u32>()%10,rng.gen::<u32>()%10,rng.gen::<u32>()%10];   println!("form 24 with using + - / * {:?}",list); //get user input let mut input = String::new(); io::stdin().read_line(&mut input).unwrap(); //convert to rpn to_rpn(&mut input); let result = calculate(&input, &mut list);   if list.iter().any(|&list| list !=10){ println!("and you used all numbers"); match result { 24.0 => println!("you won"), _ => println!("but your formulla doesn't result in 24"), } }else{ println!("you didn't use all the numbers"); }   }
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
#Huginn
Huginn
import Algorithms as algo; import Text as text;   main() { print( "{}\n".format( algo.reduce( algo.map( text.split( input().strip(), " " ), integer ), @( x, y ){ x + y; } ) ); ); }
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
#SequenceL
SequenceL
import <Utilities/Conversion.sl>; import <Utilities/Sequence.sl>;   main(args(2)) := let result[i] := args[i] ++ ": " ++ boolToString(can_make_word(args[i], InitBlocks)); in delimit(result, '\n');   InitBlocks := ["BO", "XK", "DQ", "CP", "NA", "GT", "RE", "TG", "QD", "FS", "JW", "HU", "VI", "AN", "OB", "ER", "FS", "LY", "PC", "ZM"];   can_make_word(word(1), blocks(2)) := let choices[i] := i when some(blocks[i] = toUpper(head(word))); blocksAfterChoice[i] := blocks[(1 ... (choices[i] - 1)) ++ ((choices[i] + 1) ... size(blocks))]; in true when size(word) = 0 else false when size(choices) = 0 else some(can_make_word(tail(word), blocksAfterChoice));   toUpper(letter(0)) := let ascii := asciiToInt(letter); in letter when ascii >= 65 and ascii <= 90 else intToAscii(ascii - 32);
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
#Standard_ML
Standard ML
  (* Load required Modules for Moscow ML *) load "Int"; load "Random";     (* Mutable Matrix *) signature MATRIX = sig type 'a matrix val construct : 'a -> int * int -> 'a matrix val size : 'a matrix -> int * int val get : 'a matrix -> int * int -> 'a val set : 'a matrix -> int * int -> 'a -> unit end   structure Matrix :> MATRIX = struct (* Array of rows, where the rows are a array of 'a *) type 'a matrix = 'a Array.array Array.array   fun 'a construct (a : 'a) (width, height) : 'a matrix = if width < 1 orelse height < 1 then raise Subscript else Array.tabulate (height, fn _ => Array.tabulate (width, fn _ => a))   fun size b = let val firstrow = Array.sub (b, 0) in (Array.length firstrow, Array.length b) end     fun get b (x, y) = Array.sub (Array.sub (b, y), x)   fun set b (x, y) v = Array.update (Array.sub (b, y), x, v) end   signature P15BOARD = sig type board datatype direction = North | East | South | West   val construct : int * int -> board val emptyField : board -> int * int val get : board -> int * int -> int option val size : board -> int * int   exception IllegalMove val moves : board -> int list val move : board -> int -> unit   val issolved : board -> bool end   (* Game Logic and data *)   structure Board :> P15BOARD = struct (* Matrix + empty Field position *) type board = int option Matrix.matrix * (int * int) ref   datatype direction = North | East | South | West   exception IllegalMove   fun numberat width (x, y) = (y*width + x + 1)   fun construct (width, height) = let val emptyBoard : int option Matrix.matrix = Matrix.construct NONE (width, height) in (* Fill the board with numbers *) List.tabulate (height, fn y => List.tabulate (width, fn x => Matrix.set emptyBoard (x, y) (SOME (numberat width (x, y))))); (* Clear the last field *) Matrix.set emptyBoard (width-1, height-1) NONE; (* Return the board *) (emptyBoard, ref (width-1, height-1)) end   fun emptyField (_, rfield) = !rfield   fun get (mat, _) (x, y) = Matrix.get mat (x, y)   fun size (mat, _) = Matrix.size mat   (* toggle the empty field with a given field *) fun toggle (mat, rpos) pos = let val pos' = !rpos val value = Matrix.get mat pos in Matrix.set mat pos NONE; Matrix.set mat pos' value; rpos := pos end   (* Get list of positions of the neighbors of a given field *) fun neighbors mat (x, y) : (int * int) list = let val (width, height) = Matrix.size mat val directions = [(x, y-1), (x+1, y), (x, y+1), (x-1, y)] in List.mapPartial (fn pos => SOME (Matrix.get mat pos; pos) handle Subscript => NONE) directions end   fun moves (mat, rpos) = let val neighbors = neighbors mat (!rpos) in map (fn pos => valOf (Matrix.get mat pos)) neighbors end   fun move (mat, rpos) m = let val (hx, hy) = !rpos val neighbors = neighbors mat (hx, hy) val optNeighbor = List.find (fn pos => SOME m = Matrix.get mat pos) neighbors in if isSome optNeighbor then toggle (mat, rpos) (valOf optNeighbor) else raise IllegalMove end   fun issolved board = let val (width, height) = size board val xs = List.tabulate (width, fn x => x) val ys = List.tabulate (height, fn y => y) in List.all (fn x => List.all (fn y => (x + 1 = width andalso y + 1 = height) orelse get board (x, y) = SOME (numberat width (x,y))) ys) xs end end   (* Board Shuffle *) signature BOARDSHUFFLE = sig val shuffle : Board.board -> int -> unit end   structure Shuffle :> BOARDSHUFFLE = struct (* * Note: Random Number Interfaces are different in SML/NJ and Moscow ML. Comment out the corresponding version: *)   (* (* SML/NJ - Version *) val time = Time.now () val timeInf = Time.toMicroseconds time val timens = Int.fromLarge (LargeInt.mod (timeInf, 1073741823)); val rand = Random.rand (timens, timens)   fun next n = Random.randRange (0, n) rand *)   (* Moscow ML - Version *) val generator = Random.newgen () fun next n = Random.range (0, n) generator     fun shuffle board 0 = if (Board.issolved board) then shuffle board 1 else () | shuffle board n = let val moves = Board.moves board val move = List.nth (moves, next (List.length moves - 1)) in Board.move board move; shuffle board (n-1) end end     (* Console interface *)   signature CONSOLEINTERFACE = sig val start : unit -> unit val printBoard : Board.board -> unit end   structure Console :> CONSOLEINTERFACE = struct fun cls () = print "\^[[1;1H\^[[2J"   fun promptNumber prompt = let val () = print prompt (* Input + "\n" *) val line = valOf (TextIO.inputLine TextIO.stdIn) val length = String.size line val input = String.substring (line, 0, length - 1) val optnum = Int.fromString input in if isSome optnum then valOf optnum else (print "Input is not a number.\n"; promptNumber prompt) end   fun fieldToString (SOME x) = Int.toString x | fieldToString (NONE ) = ""   fun boardToString board = let val (width, height) = Board.size board val xs = List.tabulate (width, fn x => x) val ys = List.tabulate (height, fn y => y) in foldl (fn (y, str) => (foldl (fn (x, str') => str' ^ (fieldToString (Board.get board (x, y))) ^ "\t") str xs) ^ "\n") "" ys end   fun printBoard board = print (boardToString board)     fun loop board = let val rvalidInput = ref false val rinput = ref 42 val () = cls () val () = printBoard board in (* Ask for a move and repeat until it is a valid move *) while (not (!rvalidInput)) do ( rinput := promptNumber "Input the number to move: "; Board.move board (!rinput); rvalidInput := true ) handle Board.IllegalMove => print "Illegal move!\n" end     fun start () = let val () = cls () val () = print "Welcome to nxm-Puzzle!\n" val (width, height) = (promptNumber "Enter the width: ", promptNumber "Enter the height: ") val diff = (promptNumber "Enter the difficulty (number of shuffles): ") val board = Board.construct (width, height) in Shuffle.shuffle board diff; while (not (Board.issolved board)) do loop board; print "Solved!\n" end end     val () = Console.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
#Egel
Egel
  import "prelude.eg" import "io.ego"   using System using IO   def print_rhyme = [ 0 -> print "better go to the store, and buy some more\n" | N -> let _ = print N " bottles of beer on the wall\n" in let _ = print N " bottles of beer\n" in let _ = print "take one down, pass it around\n" in print_rhyme (N - 1) ]   def main = print_rhyme 99  
http://rosettacode.org/wiki/24_game
24 game
The 24 Game tests one's mental arithmetic. Task Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed. The program should prompt for the player to enter an arithmetic expression using just those, and all of those four digits, used exactly once each. 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.
#Scala
Scala
C:\Workset>scala TwentyFourGame 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. Your four digits: 2, 7, 7, 2. Expression 1: 2*7+2+7 Sorry, that's 23.0. Expression 2: 7*7/2-2 Sorry, that's 22.5. Expression 3: 2*7+(7-2) Sorry, that's 19.0. Expression 4: 2*(7+7-2) That's right! Thank you and goodbye!
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
#Hy
Hy
(print (sum (map int (.split (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
#Sidef
Sidef
func can_make_word(word, blocks) {   blocks.map! { |b| b.uc.chars.sort.join }.freq!   func(word, blocks) { var char = word.shift var candidates = blocks.keys.grep { |k| 0 <= k.index(char) }   for candidate in candidates { blocks{candidate} <= 0 && next; local blocks{candidate} = (blocks{candidate} - 1); return true if (word.is_empty || __FUNC__(word, blocks)); }   return false; }(word.uc.chars, blocks) }
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
#Tcl
Tcl
# 15puzzle_21.tcl - HaJo Gurt - 2016-02-16 # http://wiki.tcl.tk/14403   #: 15-Puzzle - with grid, buttons and colors   package require Tk   set progVersion "15-Puzzle v0.21"; # 2016-02-20   global Msg Moves PuzzNr GoalNr set Msg " " set Moves -1 set PuzzNr 0 set GoalNr 0   set Keys { 11 12 13 14 21 22 23 24 31 32 33 34 41 42 43 44 }   set Puzz_T { T h e F i f t e e n P u z z l e }; # Title set Goal_T { x x x F i f t e e n x x x x x x }; # Title-highlight   set Puzz_0 { E G P N C A F B D L H I O K M _ }; # - / 116 set Puzz_1 { C A F B E G P N D L H I O K M _ }; # E / 156 from Tk-demo set Puzz_2 { E O N K M I _ G B H L P C F A D }; # L / 139 set Puzz_3 { P G M _ E L N D O K H I B C F A }; # EK / 146   set Goal_0 { A B C D E F G H I K L M N O P _ }; # Rows LTR / 1:E : 108 set Goal_1 { A E I N B F K O C G L P D H M _ }; # Cols forw. / 1:M : 114   set Puzz $Puzz_T set Goal $Goal_T   #---+----1----+----2----+----3----+----4----+----5----+----6----+----7----+---   proc Move {k} { # find the key with the empty tile: set e -1 foreach p $::Keys { set t [.key$p cget -text] if { $t eq "_" } { set e $p } } if {$e < 0} {return 0}; # no key with empty tile found if {$k == $e} {return 0}; # click was on the empty tile   set t [.key$k cget -text] .key$e config -text $t .key$k config -text "_"; return 1 }   proc Check {} { set ok 0 set i 0 foreach k $::Keys { set t [.key$k cget -text] set g [lindex $::Goal $i] incr i   .key$k config -background white if { $t eq $g } { .key$k config -background lightgreen; incr ok } if { $t eq "_" } { .key$k config -background gray } }   # Solved: update if { $ok > 15 && $::Moves > 0} { foreach k $::Keys { .key$k flash; bell; } } }   proc Click {k} { set ::Msg "" set val [.key$k cget -text] set ok [Move $k]   incr ::Moves $ok wm title . "$::Moves moves" Check }   proc ShowKeys {} { set i 0 foreach k $::Keys { set t [lindex $::Puzz $i] incr i .key$k config -text $t -background white; } Check }   proc NewGame {N} { global Msg Moves PuzzNr GoalNr   incr PuzzNr $N if { $PuzzNr > 3} { set PuzzNr 0 }   set ::Goal $::Goal_0; if { $GoalNr == 1} { set ::Goal $::Goal_1; }   if { $PuzzNr == 0} { set ::Puzz $::Puzz_0; } if { $PuzzNr == 1} { set ::Puzz $::Puzz_1; } if { $PuzzNr == 2} { set ::Puzz $::Puzz_2; } if { $PuzzNr == 3} { set ::Puzz $::Puzz_3; }   set Msg "Try again" if { $N>0 } { set Msg "New game" }   set Moves 0 ShowKeys wm title . "$Msg " }   #---+----1----+----2----+----3----+----4----+----5----+----6----+----7----+---   button .reset -text "Restart" -fg blue -command {NewGame 0} button .newGame -text "New Game" -fg red -command {NewGame +1}   foreach k $::Keys { button .key$k -text "$k" -width 4 -command "Click $k" }   grid .newGame x .reset x -sticky nsew   grid .key11 .key12 .key13 .key14 -sticky nsew -padx 2 -pady 2 grid .key21 .key22 .key23 .key24 -sticky nsew -padx 2 -pady 2 grid .key31 .key32 .key33 .key34 -sticky nsew -padx 2 -pady 2 grid .key41 .key42 .key43 .key44 -sticky nsew -padx 2 -pady 2   grid configure .newGame .reset -columnspan 2 -padx 4   ShowKeys; Check wm title . $progVersion focus -force . wm resizable . 0 0   # For some more versions, see: http://wiki.tcl.tk/15067 : Classic 15 Puzzle and http://wiki.tcl.tk/15085 : N-Puzzle  
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
#EGL
EGL
program TestProgram type BasicProgram {}   function main() for (count int from 99 to 1 decrement by 1) SysLib.writeStdout( bottleStr( count ) :: " of beer on the wall." ); SysLib.writeStdout( bottleStr( count ) :: " of beer." ); SysLib.writeStdout( "Take one down, pass it around." ); SysLib.writeStdout( bottleStr( count - 1) :: " of beer on the wall.\n"); end end   private function bottleStr( count int in) returns( string ) case ( count ) when ( 1 ) return( "1 bottle" ); when ( 0 ) return( "No more bottles" ); otherwise return( count :: " bottles" ); end end 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.
#Scheme
Scheme
#lang scheme (require srfi/27 srfi/1) ;; random-integer, every   (define (play) (let* ([numbers (build-list 4 (lambda (n) (add1 (random-integer 9))))] [valid? (curryr valid? numbers)]) (printf startup-message numbers) (let loop ([exp (read)]) (with-handlers ([exn:fail? (lambda (err) (printf error-message exp (exn-message err)) (loop (read)))]) (cond [(eq? exp '!) (play)]   [(or (eq? exp 'q) (eof-object? exp)) (printf quit-message)]   [(not (valid? exp)) (printf bad-exp-message exp) (loop (read))]   [(not (= (eval exp) 24)) (printf bad-result-message exp (eval exp)) (loop (read))]   [else (printf winning-message)])))))   (define (valid? exp numbers) ;; must contain each number exactly once and only valid symbols (define (valid-symbol? sym) ;; only +, -, *, and / are valid (case sym [(+ - * /) #t] [else #f]))   (let* ([ls (flatten exp)] [numbers* (filter number? ls)] [symbols (remove number? ls)]) (and (equal? (sort numbers <) (sort numbers* <)) (every valid-symbol? symbols))))   (define startup-message " Write a lisp expression that evaluates to 24 using only (, ), +, -, *, / and these four numbers: ~a   or '!' to get a new set of numbers or 'q' to quit")   (define error-message " Your expression ~a raised an exception:   \"~a\"   Please try again")   (define bad-exp-message "Sorry, ~a is a bad expression.") (define bad-result-message "Sorry, ~a evaluates to ~a, not 24.") (define quit-message "Thanks for playing...") (define winning-message "You win!")   (provide 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
#i
i
main: print(integer(in(' '))+integer(in('\n'))); ignore
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
#Simula
Simula
COMMENT ABC PROBLEM; BEGIN   CLASS BLOCK(CH1, CH2); CHARACTER CH1, CH2; BEGIN BOOLEAN USED; END;   CLASS GAME(WORD, POSSIBLE); TEXT WORD; BOOLEAN POSSIBLE;;   BOOLEAN PROCEDURE CANMAKEWORD(WORD); TEXT WORD; BEGIN INTEGER I, NUMBLOCKS; BOOLEAN ALLPOSSIBLE, FOUND; NUMBLOCKS := UPPERBOUND(BLOCKS, 1); FOR I := 1 STEP 1 UNTIL NUMBLOCKS DO BLOCKS(I).USED := FALSE; ALLPOSSIBLE := TRUE;   WORD.SETPOS(1); WHILE ALLPOSSIBLE AND WORD.MORE DO BEGIN CHARACTER WORDCHAR; WORDCHAR := WORD.GETCHAR; FOUND := FALSE; FOR I := 1 STEP 1 UNTIL NUMBLOCKS DO BEGIN INSPECT BLOCKS(I) DO BEGIN IF (WORDCHAR = CH1 OR WORDCHAR = CH2) AND NOT USED THEN BEGIN USED := FOUND := TRUE; GOTO L; END; END; END; L: IF NOT FOUND THEN ALLPOSSIBLE := FALSE; END; CANMAKEWORD := ALLPOSSIBLE; END CANMAKEWORD;   REF(BLOCK) ARRAY BLOCKS(1:20); REF(GAME) ARRAY GAMES(1:7); TEXT WORD; BEGIN INTEGER I; I := I+1; BLOCKS(I) :- NEW BLOCK('B', 'O'); I := I+1; BLOCKS(I) :- NEW BLOCK('X', 'K'); I := I+1; BLOCKS(I) :- NEW BLOCK('D', 'Q'); I := I+1; BLOCKS(I) :- NEW BLOCK('C', 'P'); I := I+1; BLOCKS(I) :- NEW BLOCK('N', 'A'); I := I+1; BLOCKS(I) :- NEW BLOCK('G', 'T'); I := I+1; BLOCKS(I) :- NEW BLOCK('R', 'E'); I := I+1; BLOCKS(I) :- NEW BLOCK('T', 'G'); I := I+1; BLOCKS(I) :- NEW BLOCK('Q', 'D'); I := I+1; BLOCKS(I) :- NEW BLOCK('F', 'S'); I := I+1; BLOCKS(I) :- NEW BLOCK('J', 'W'); I := I+1; BLOCKS(I) :- NEW BLOCK('H', 'U'); I := I+1; BLOCKS(I) :- NEW BLOCK('V', 'I'); I := I+1; BLOCKS(I) :- NEW BLOCK('A', 'N'); I := I+1; BLOCKS(I) :- NEW BLOCK('O', 'B'); I := I+1; BLOCKS(I) :- NEW BLOCK('E', 'R'); I := I+1; BLOCKS(I) :- NEW BLOCK('F', 'S'); I := I+1; BLOCKS(I) :- NEW BLOCK('L', 'Y'); I := I+1; BLOCKS(I) :- NEW BLOCK('P', 'C'); I := I+1; BLOCKS(I) :- NEW BLOCK('Z', 'M'); END; BEGIN INTEGER N, I; BOOLEAN ANSWER; N := N+1; GAMES(N) :- NEW GAME("A", TRUE); N := N+1; GAMES(N) :- NEW GAME("BARK", TRUE); N := N+1; GAMES(N) :- NEW GAME("BOOK", FALSE); N := N+1; GAMES(N) :- NEW GAME("TREAT", TRUE); N := N+1; GAMES(N) :- NEW GAME("COMMON", FALSE); N := N+1; GAMES(N) :- NEW GAME("SQUAD", TRUE); N := N+1; GAMES(N) :- NEW GAME("CONFUSE", TRUE); FOR I := 1 STEP 1 UNTIL N DO BEGIN INSPECT GAMES(I) DO BEGIN OUTTEXT(WORD); OUTTEXT(" => "); ANSWER := CANMAKEWORD(WORD); OUTCHAR(IF ANSWER THEN 'T' ELSE 'F'); IF ANSWER EQV POSSIBLE THEN OUTTEXT(" OK") ELSE OUTTEXT(" ------------- WRONG!"); OUTIMAGE; END; END; 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
#UNIX_Shell
UNIX Shell
#!/usr/bin/env bash main() { local puzzle=({1..15} " ") blank moves_kv i key count total last printf '\n' show_puzzle "${puzzle[@]}" printf '\nPress return to scramble.' read _ IFS= readarray -t puzzle < <(scramble "${puzzle[@]}") printf '\r\e[A\e[A\e[A\e[A\e[A\e[A' show_puzzle "${puzzle[@]}" printf '\nUse hjkl to slide tiles. ' printf '\r\e[A\e[A\e[A\e[A\e[A' total=0 while ! solved "${puzzle[@]}"; do show_puzzle "${puzzle[@]}" { read blank; readarray -t moves_kv; } < <(find_moves "${puzzle[@]}") local count=${#moves_kv[@]}/2 local -A moves for (( i=0; i<count; i++ )); do moves[${moves_kv[i]}]=${moves_kv[i+count]} done read -r -n 1 key printf '\r ' if [[ "$key" = u ]]; then (( total -= 2 )) case "$last" in h) key=l;; j) key=k;; k) key=j;; l) key=h;; esac fi if [[ -n "${moves[$key]}" ]]; then last=$key (( total++ )) i=${moves[$key]} puzzle[$blank]=${puzzle[i]} puzzle[i]=' ' fi printf '\r\e[A\e[A\e[A\e[A' done show_puzzle "${puzzle[@]}" printf '\nSolved in %d moves. \n' "$total" }     solved() { local solved=({1..15} ' ') [[ "${puzzle[*]}" == "${solved[*]}" ]] }   show_puzzle() { printf '%2s %2s %2s %2s\n' "$@" }   find_moves() { local puzzle=("$@") local i j blank for (( i=0; i<${#puzzle[@]}; ++i )); do if [[ "${puzzle[i]}" == " " ]]; then blank=$i break fi done local -A moves=() if (( blank%4 )); then # swapping blank with tile to its left # is sliding that tile right, which is the l key moves['l']=$(( blank-1 )) fi if (( blank%4 != 3 )); then moves['h']=$(( blank+1 )) # left fi if (( blank >= 4 )); then moves['j']=$(( blank-4 )) # down fi if (( blank < 12 )); then moves['k']=$(( blank+4 )) # up fi printf '%s\n' "$blank" "${!moves[@]}" "${moves[@]}" }   scramble() { local puzzle=("$@") i j for (( i=0; i<256; ++i )); do local blank moves { read blank; readarray -t moves; } < <(find_moves "${puzzle[@]}") moves=(${moves[@]:${#moves[@]}/2}) local dir=$(( RANDOM % ${#moves[@]} )) j=${moves[dir]} puzzle[blank]=${puzzle[j]} puzzle[j]=' ' done printf '%s\n' "${puzzle[@]}" }   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
#Eiffel
Eiffel
  class APPLICATION   create make   feature {NONE} -- Initialization   make local bottles: INTEGER do from bottles := 99 invariant bottles <= 99 and bottles >= 1 until bottles = 1 loop print (bottles) print (" bottles of beer on the wall,%N") print (bottles) print (" bottles of beer.%N") print ("Take one down, pass it around,%N") bottles := bottles - 1 if bottles > 1 then print (bottles) print (" bottles of beer on the wall.%N%N") end variant bottles end print ("1 bottle of beer on the wall.%N%N"); print ("No more bottles of beer on the wall,%N"); print ("no more bottles of beer.%N"); print ("Go to the store and buy some more,%N"); print ("99 bottles of beer on the wall.%N"); end   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.
#Sidef
Sidef
const digits = (1..9 -> pick(4)) const grammar = Regex( '^ (?&exp) \z (?(DEFINE) (?<exp> ( (?&term) (?&op) (?&term) )+ ) (?<term> \( (?&exp) \) | [' + digits.join + ']) (?<op> [\-+*/] ) )', 'x' )   say "Here are your digits: #{digits.join(' ')}"   loop { var input = read("Expression: ", String)   var expr = input expr -= /\s+/g # remove all whitespace   if (input == 'q') { say "Goodbye. Sorry you couldn't win." break }   var given_digits = digits.map{.to_s}.sort.join var entry_digits = input.scan(/\d/).sort.join   if ((given_digits != entry_digits) || (expr !~ grammar)) { say "That's not valid" next }   given(var n = eval(input)) { when (24) { say "You win!"; break } default { 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
#Icon_and_Unicon
Icon and Unicon
procedure main() numChars := '-'++&digits read() ? { A := (tab(upto(numChars)), integer(tab(many(numChars)))) B := (tab(upto(numChars)), integer(tab(many(numChars)))) } write((\A + \B) | "Bad input") 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
#Smalltalk
Smalltalk
  ABCPuzzle>>test #('A' 'BARK' 'BOOK' 'TreaT' 'COMMON' 'sQUAD' 'CONFuSE') do: [ :each | Transcript crShow: each, ': ', (self solveFor: each) asString ]   ABCPuzzle>>solveFor: letters | blocks | blocks := #('BO' 'XK' 'DQ' 'CP' 'NA' 'GT' 'RE' 'TG' 'QD' 'FS' 'JW' 'HU' 'VI' 'AN' 'OB' 'ER' 'FS' 'LY' 'PC' 'ZM'). ^ self solveFor: letters asUppercase with: blocks asOrderedCollection   ABCPuzzle>>solveFor: letters with: blocks | l ldash matches | letters isEmpty ifTrue: [ ^ true ]. l := letters first. ldash := letters allButFirst. matches := blocks select: [  :b | b includes: l ]. matches isEmpty ifTrue: [ ^ false ]. matches do: [  :m | | bdash | bdash := blocks copy. bdash remove: m. (self solveFor: ldash with: bdash) ifTrue: [ ^ true ] ]. ^ false  
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
#VBA
VBA
  Public iSide As Integer Public iSize As Integer Public iGrid() As Integer Public lMoves As Long Public sMessage As String Public Const sTitle As String = "Tile Puzzle"     Sub PlayGame() Dim iNum As Integer Dim i As Integer Dim vInput As Variant   DefineGrid: vInput = InputBox("Enter size of grid, as a whole number" & String(2, vbCr) & "(e.g. for a 4 x 4 grid, enter '4')", sTitle, 4) If vInput = "" Then Exit Sub If Not IsNumeric(vInput) Then GoTo DefineGrid iSide = vInput If iSide < 3 Or iNum > 10 Then GoTo DefineGrid iSize = iSide ^ 2 ReDim iGrid(1 To iSize)   Initalize: InitializeGrid If Not IsSolvable Then GoTo Initalize   GetInput: vInput = InputBox(ShowGrid & vbCr & "Enter number to move into empty tile", sTitle) If vInput = "" Then If MsgBox("Are you sure? This will end the current game.", vbExclamation + vbYesNo, sTitle) = vbYes Then Exit Sub End If If Not IsNumeric(vInput) Then sMessage = "'" & vInput & "' is not a valid tile" GoTo GetInput End If iNum = vInput If iNum < 1 Or iNum > iSize - 1 Then sMessage = iNum & " is not a valid tile" GoTo GetInput End If i = FindTile(iNum) If Not ValidMove(i) Then GoTo GetInput MoveTile (i) If TestGrid Then MsgBox "SUCCESS! You solved the puzzle in " & lMoves & " moves", vbInformation + vbOKOnly, sTitle Else GoTo GetInput End If End Sub   Function RandomTile() As Integer Randomize RandomTile = Int(Rnd * iSize) + 1 End Function   Function GetX(ByVal i As Integer) As Integer GetX = Int((i - 1) / iSide) + 1 End Function   Function GetY(ByVal i As Integer) As Integer GetY = (i - 1) Mod iSide + 1 End Function   Function GetI(ByVal x As Integer, y As Integer) GetI = (x - 1) * iSide + y End Function   Function InitializeGrid() Dim i As Integer Dim x As Integer Dim y As Integer   sMessage = "New " & iSide & " x " & iSide & " game started" & vbCr   For i = 1 To iSize iGrid(i) = 0 Next i For i = 1 To iSize - 1 Do x = RandomTile If iGrid(x) = 0 Then iGrid(x) = i Loop Until iGrid(x) = i Next i lMoves = 0 End Function   Function IsSolvable() As Boolean Dim i As Integer Dim j As Integer Dim iCount As Integer For i = 1 To iSize - 1 For j = i + 1 To iSize If iGrid(j) < iGrid(i) And iGrid(j) > 0 Then iCount = iCount + 1 Next j Next i If iSide Mod 2 Then IsSolvable = Not iCount Mod 2 Else IsSolvable = iCount Mod 2 = GetX(FindTile(0)) Mod 2 End If End Function   Function TestGrid() As Boolean Dim i As Integer   For i = 1 To iSize - 1 If Not iGrid(i) = i Then TestGrid = False Exit Function End If Next i TestGrid = True End Function   Function FindTile(ByVal iNum As Integer) As Integer Dim i As Integer For i = 1 To iSize If iGrid(i) = iNum Then FindTile = i Exit Function End If Next i End Function   Function ValidMove(ByVal i As Integer) As Boolean Dim e As Integer Dim xDiff As Integer Dim yDiff As Integer   e = FindTile(0) xDiff = GetX(i) - GetX(e) yDiff = GetY(i) - GetY(e) If xDiff = 0 Then If yDiff = 1 Then sMessage = "Tile " & iGrid(i) & " was moved left" ValidMove = True ElseIf yDiff = -1 Then sMessage = "Tile " & iGrid(i) & " was moved right" ValidMove = True End If ElseIf yDiff = 0 Then If xDiff = 1 Then sMessage = "Tile " & iGrid(i) & " was moved up" ValidMove = True ElseIf xDiff = -1 Then sMessage = "Tile " & iGrid(i) & " was moved down" ValidMove = True End If End If If Not ValidMove Then sMessage = "Tile " & iGrid(i) & " may not be moved" End Function   Function MoveTile(ByVal i As Integer) Dim e As Integer e = FindTile(0) iGrid(e) = iGrid(i) iGrid(i) = 0 lMoves = lMoves + 1 End Function   Function ShowGrid() Dim x As Integer Dim y As Integer Dim i As Integer Dim sNum As String Dim s As String   For x = 1 To iSide For y = 1 To iSide sNum = iGrid(GetI(x, y)) If sNum = "0" Then sNum = "" s = s & sNum & vbTab Next y s = s & vbCr Next x If Not sMessage = "" Then s = s & vbCr & sMessage & vbCr End If ShowGrid = s End Function