task_url
stringlengths 30
116
| task_name
stringlengths 2
86
| task_description
stringlengths 0
14.4k
| language_url
stringlengths 2
53
| language_name
stringlengths 1
52
| code
stringlengths 0
61.9k
|
---|---|---|---|---|---|
http://rosettacode.org/wiki/100_prisoners | 100 prisoners |
The Problem
100 prisoners are individually numbered 1 to 100
A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside.
Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start.
Prisoners start outside the room
They can 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.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ClearAll[PlayRandom, PlayOptimal]
PlayRandom[n_] :=
Module[{pardoned = 0, sampler, indrawer, found, reveal},
sampler = indrawer = Range[100];
Do[
indrawer //= RandomSample;
found = 0;
Do[
reveal = RandomSample[sampler, 50];
If[MemberQ[indrawer[[reveal]], p],
found++;
]
,
{p, 100}
];
If[found == 100, pardoned++];
,
{n}
];
N[pardoned/n]
]
PlayOptimal[n_] :=
Module[{pardoned = 0, indrawer, reveal, found, card},
indrawer = Range[100];
Do[
indrawer //= RandomSample;
Do[
reveal = p;
found = False;
Do[
card = indrawer[[reveal]];
If[card == p,
found = True;
Break[];
];
reveal = card;
,
{g, 50}
];
If[! found, Break[]];
,
{p, 100}
];
If[found, pardoned++];
,
{n}
];
N[pardoned/n]
];
PlayRandom[1000]
PlayOptimal[10000] |
http://rosettacode.org/wiki/24_game/Solve | 24 game/Solve | task
Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the 24 game.
Show examples of solutions generated by the program.
Related task
Arithmetic Evaluator
| #R | R |
library(gtools)
solve24 <- function(vals=c(8, 4, 2, 1),
goal=24,
ops=c("+", "-", "*", "/")) {
val.perms <- as.data.frame(t(
permutations(length(vals), length(vals))))
nop <- length(vals)-1
op.perms <- as.data.frame(t(
do.call(expand.grid,
replicate(nop, list(ops)))))
ord.perms <- as.data.frame(t(
do.call(expand.grid,
replicate(n <- nop, 1:((n <<- n-1)+1)))))
for (val.perm in val.perms)
for (op.perm in op.perms)
for (ord.perm in ord.perms)
{
expr <- as.list(vals[val.perm])
for (i in 1:nop) {
expr[[ ord.perm[i] ]] <- call(as.character(op.perm[i]),
expr[[ ord.perm[i] ]],
expr[[ ord.perm[i]+1 ]])
expr <- expr[ -(ord.perm[i]+1) ]
}
if (identical(eval(expr[[1]]), goal)) return(expr[[1]])
}
return(NA)
}
|
http://rosettacode.org/wiki/15_puzzle_game | 15 puzzle game |
Task
Implement the Fifteen Puzzle Game.
The 15-puzzle is also known as:
Fifteen Puzzle
Gem Puzzle
Boss Puzzle
Game of Fifteen
Mystic Square
14-15 Puzzle
and some others.
Related Tasks
15 Puzzle Solver
16 Puzzle Game
| #Haskell | Haskell | import Data.Array
import System.Random
type Puzzle = Array (Int, Int) Int
main :: IO ()
main = do
putStrLn "Please enter the difficulty level: 0, 1 or 2"
userInput <- getLine
let diffLevel = read userInput
if userInput == "" || any (\c -> c < '0' || c > '9') userInput || diffLevel > 2 || diffLevel < 0
then putStrLn "That is not a valid difficulty level." >> main
else shufflePuzzle ([10, 50, 100] !! diffLevel) solvedPuzzle >>= gameLoop
gameLoop :: Puzzle -> IO ()
gameLoop puzzle
| puzzle == solvedPuzzle = putStrLn "You solved the puzzle!" >> printPuzzle puzzle
| otherwise = do
printPuzzle puzzle
putStrLn "Please enter number to move"
userInput <- getLine
if any (\c -> c < '0' || c > '9') userInput
then putStrLn "That is not a valid number." >> gameLoop puzzle
else let move = read userInput in
if move `notElem` validMoves puzzle
then putStrLn "This move is not available." >> gameLoop puzzle
else gameLoop (applyMove move puzzle)
validMoves :: Puzzle -> [Int]
validMoves puzzle = [puzzle ! (row', column') |
row' <- [rowEmpty-1..rowEmpty+1], column' <- [columnEmpty-1..columnEmpty+1],
row' < 4, row' >= 0, column' < 4, column' >= 0,
(row' == rowEmpty) /= (column' == columnEmpty)]
where (rowEmpty, columnEmpty) = findIndexOfNumber 16 puzzle
applyMove :: Int -> Puzzle -> Puzzle
applyMove numberToMove puzzle = puzzle // [(indexToMove, 16), (emptyIndex, numberToMove)]
where indexToMove = findIndexOfNumber numberToMove puzzle
emptyIndex = findIndexOfNumber 16 puzzle
findIndexOfNumber :: Int -> Puzzle -> (Int, Int)
findIndexOfNumber number puzzle = case filter (\idx -> number == puzzle ! idx)
(indices puzzle) of
[idx] -> idx
_ -> error "BUG: number not in puzzle"
printPuzzle :: Puzzle -> IO ()
printPuzzle puzzle = do
putStrLn "+--+--+--+--+"
putStrLn $ "|" ++ formatCell (0, 0) ++ "|" ++ formatCell (0, 1) ++ "|" ++ formatCell (0, 2) ++ "|" ++ formatCell (0, 3) ++ "|"
putStrLn "+--+--+--+--+"
putStrLn $ "|" ++ formatCell (1, 0) ++ "|" ++ formatCell (1, 1) ++ "|" ++ formatCell (1, 2) ++ "|" ++ formatCell (1, 3) ++ "|"
putStrLn "+--+--+--+--+"
putStrLn $ "|" ++ formatCell (2, 0) ++ "|" ++ formatCell (2, 1) ++ "|" ++ formatCell (2, 2) ++ "|" ++ formatCell (2, 3) ++ "|"
putStrLn "+--+--+--+--+"
putStrLn $ "|" ++ formatCell (3, 0) ++ "|" ++ formatCell (3, 1) ++ "|" ++ formatCell (3, 2) ++ "|" ++ formatCell (3, 3) ++ "|"
putStrLn "+--+--+--+--+"
where formatCell idx
| i == 16 = " "
| i > 9 = show i
| otherwise = " " ++ show i
where i = puzzle ! idx
solvedPuzzle :: Puzzle
solvedPuzzle = listArray ((0, 0), (3, 3)) [1..16]
shufflePuzzle :: Int -> Puzzle -> IO Puzzle
shufflePuzzle 0 puzzle = return puzzle
shufflePuzzle numOfShuffels puzzle = do
let moves = validMoves puzzle
randomIndex <- randomRIO (0, length moves - 1)
let move = moves !! randomIndex
shufflePuzzle (numOfShuffels - 1) (applyMove move puzzle) |
http://rosettacode.org/wiki/2048 | 2048 | Task
Implement a 2D sliding block puzzle game where blocks with numbers are combined to add their values.
Rules of the game
The rules are that on each turn the player must choose a direction (up, down, left or right).
All tiles move as far as possible in that direction, some move more than others.
Two adjacent tiles (in that direction only) with matching numbers combine into one bearing the sum of those numbers.
A move is valid when at least one tile can be moved, if only by combination.
A new tile with the value of 2 is spawned at the end of each turn at a randomly chosen empty square (if there is one).
Adding a new tile on a blank space. Most of the time, a new 2 is to be added, and occasionally (10% of the time), a 4.
To win, the player must create a tile with the number 2048.
The player loses if no valid moves are possible.
The name comes from the popular open-source implementation of this game mechanic, 2048.
Requirements
"Non-greedy" movement.
The tiles that were created by combining other tiles should not be combined again during the same turn (move).
That is to say, that moving the tile row of:
[2][2][2][2]
to the right should result in:
......[4][4]
and not:
.........[8]
"Move direction priority".
If more than one variant of combining is possible, move direction shall indicate which combination will take effect.
For example, moving the tile row of:
...[2][2][2]
to the right should result in:
......[2][4]
and not:
......[4][2]
Check for valid moves. The player shouldn't be able to skip their turn by trying a move that doesn't change the board.
Check for a win condition.
Check for a lose condition.
| #Latitude | Latitude |
use 'format import '[format].
use 'random.
Pos := Object clone tap {
self x := 0.
self y := 0.
self move := {
localize.
case ($1) do {
when 'left do { pos (this x - 1, this y). }.
when 'right do { pos (this x + 1, this y). }.
when 'down do { pos (this x, this y + 1). }.
when 'up do { pos (this x, this y - 1). }.
}.
}.
self == := {
(self x == $1 x) and (self y == $1 y).
}.
self inBounds? := {
(self x >= 0) and (self x < 4) and (self y >= 0) and (self y < 4).
}.
self toString := {
format "pos (~S, ~S)" call (self x, self y).
}.
}.
pos := {
takes '[x, y].
Pos clone tap {
self x := x.
self y := y.
}.
}.
allSquares := [] tap {
localize.
0 upto 4 visit {
takes '[y].
0 upto 4 visit {
takes '[x].
this pushBack (pos (x, y)).
}.
}.
}.
sample := {
$1 nth (random nextInt mod ($1 length)).
}.
Grid ::= Object clone tap {
self grid := 16 times to (Array) map { 0. }.
self clone := {
Parents above (parent self, 'clone) call tap {
self grid := self grid clone.
}.
}.
toIndex := {
$1 x + 4 * $1 y.
}.
self at := {
self grid nth (toIndex).
}.
self at= := {
self grid nth= (toIndex).
}.
self isBlank? := {
self at == 0.
}.
self spawnNew := {
localize.
candidates := allSquares filter { this isBlank?. } to (Array).
if (candidates empty?) then {
'gameover.
} else {
p := sample (candidates).
this at (p) = if (random nextInt mod 10 == 0) then 4 else 2.
'okay.
}.
}.
canMoveCell := {
takes '[grid, src, dir].
dest := src move (dir).
if (dest inBounds?) then {
vs := grid at (src).
vd := grid at (dest).
(vs /= 0) and ((vd == 0) or (vs == vd)).
} else {
False.
}.
}.
self canMove := {
localize.
takes '[dir].
allSquares any { canMoveCell (this, $1, dir). }.
}.
self validMoves := {
'[left, right, up, down] filter { parent self canMove. } to (Array).
}.
;; Calculates the order of iteration for performing the moves
axisCalc := {
takes '[dir, major, minor].
case (dir) do {
when 'left do { pos (major, minor). }.
when 'right do { pos (3 - major, minor). }.
when 'up do { pos (minor, major). }.
when 'down do { pos (minor, 3 - major). }.
}.
}.
moveFrom := {
takes '[grid, src, dir, locked].
dest := src move (dir).
local 'result = Nil.
dest inBounds? ifTrue {
locked contains (dest) ifFalse {
vs := grid at (src).
vd := grid at (dest).
cond {
when (vd == 0) do {
grid at (dest) = vs.
grid at (src) = 0.
result = moveFrom (grid, dest, dir, locked).
}.
when (vd == vs) do {
grid at (dest) = vs + vd.
grid at (src) = 0.
result = moveFrom (grid, dest, dir, locked).
;; We merged, so lock the final result cell.
locked pushBack (result).
}.
}.
}.
}.
(result) or (src).
}.
self doMove := {
localize.
takes '[dir].
locked := [].
0 upto 4 do {
takes '[major].
0 upto 4 do {
takes '[minor].
src := axisCalc (dir, major, minor).
moveFrom: this, src, dir, locked.
}.
}.
}.
self pretty := {
localize.
lines := [].
row := "+----+----+----+----+".
lines pushBack (row).
0 upto 4 visit {
takes '[y].
local 'line = "|".
0 upto 4 visit {
takes '[x].
n := this at (pos (x, y)).
if (n == 0) then {
line = line ++ " |".
} else {
line = line ++ n toString padRight (" ", 4) ++ "|".
}.
}.
lines pushBack (line).
lines pushBack (row).
}.
lines joinText "\n".
}.
self toArray := {
allSquares map { parent self at. }.
}.
}.
grid := Grid clone.
endgame := loop* {
;; Check for victory
(grid toArray any { $1 >= 2048. }) ifTrue {
last 'victory.
}.
;; Check for game over
result := grid spawnNew.
(result == 'gameover) ifTrue {
last 'gameover.
}.
valid := grid validMoves.
valid empty? ifTrue {
last 'gameover.
}.
$stdout putln: grid pretty.
move := loop* {
$stdout puts: "Your move (left, right, up, down)> ".
move := $stdin readln intern.
valid contains (move) ifTrue { last (move). }.
}.
grid doMove (move).
}.
$stdout putln: grid pretty.
if (endgame == 'victory) then {
$stdout putln: "You win!".
} else {
$stdout putln: "Better luck next time!".
}.
|
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
| #Befunge | Befunge | local bot:int = 99
repeat
print string(bot)+" bottles of beer on the wall,"
print string(bot)+" bottles of beer."
print "Take one down, pass it around,"
bot:-1
print string(bot)+" bottles of beer on the wall."
print
until bot = 1
print "1 bottle of beer on the wall,"
print "1 bottle of beer."
print "Take it down, pass it around,"
print "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.
| #Locomotive_Basic | Locomotive Basic | 10 CLS:RANDOMIZE TIME
20 PRINT "The 24 Game"
30 PRINT "===========":PRINT
40 PRINT "Enter an arithmetic expression"
50 PRINT "that evaluates to 24,"
60 PRINT "using only the provided digits"
70 PRINT "and +, -, *, /, (, )."
80 PRINT "(Just hit Return for new digits.)"
90 ' create new digits
100 FOR i=1 TO 4:a(i)=INT(RND*9)+1:NEXT
110 PRINT
120 PRINT "The digits are";a(1);a(2);a(3);a(4)
130 PRINT
140 ' user enters solution
150 INPUT "Your solution";s$
160 IF s$="" THEN PRINT "Creating new digits...":GOTO 100
170 GOTO 300
180 ' a little hack to create something like an EVAL function
190 OPENOUT "exp.bas"
200 PRINT #9,"1000 x="s$":return"
210 CLOSEOUT
220 CHAIN MERGE "exp",240
230 ' now evaluate the expression
240 ON ERROR GOTO 530
250 GOSUB 1000
260 IF x=24 THEN PRINT "Well done!":END
270 PRINT "No, this evaluates to"x:PRINT "Please try again."
280 GOTO 150
290 ' check input for correctness
300 FOR i=1 TO LEN(s$)
310 q=ASC(MID$(s$,i,1))
320 IF q=32 OR (q>39 AND q<44) OR q=45 OR (q>46 AND q<58) THEN NEXT
330 IF i-1=LEN(s$) THEN 370
340 PRINT "Bad character in expression:"CHR$(q)
350 PRINT "Try again":GOTO 150
360 ' new numbers in solution?
370 FOR i=1 TO LEN(s$)-1
380 q=ASC(MID$(s$,i,1)):p=ASC(MID$(s$,i+1,1))
390 IF q>47 AND q<58 AND p>47 AND p<58 THEN PRINT "No forming of new numbers, please!":GOTO 150
400 NEXT
410 FOR i=1 TO 9:orig(i)=0:guess(i)=0:NEXT
420 FOR i=1 TO 4:orig(a(i))=orig(a(i))+1:NEXT
430 FOR i=1 TO LEN(s$)
440 v$=MID$(s$,i,1)
450 va=ASC(v$)-48
460 IF va>0 AND va<10 THEN guess(va)=guess(va)+1
470 NEXT
480 FOR i=1 TO 9
490 IF guess(i)<>orig(i) THEN PRINT "Only use all the provided digits!":GOTO 150
500 NEXT
510 GOTO 190
520 ' syntax error, e.g. non-matching parentheses
530 PRINT "Error in expression, please try again."
540 RESUME 150 |
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
| #Elixir | Elixir | IO.gets("Enter two numbers seperated by a space: ")
|> String.split
|> Enum.map(&String.to_integer(&1))
|> Enum.sum
|> IO.puts |
http://rosettacode.org/wiki/ABC_problem | ABC problem | ABC problem
You are encouraged to solve this task according to the task description, using any language you may know.
You are given a collection of ABC blocks (maybe like the ones you had when you were a kid).
There are twenty blocks with two letters on each block.
A complete alphabet is guaranteed amongst all 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
| #Mercury | Mercury | :- module abc.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
:- import_module list, string, char.
:- type block == {char, char}.
:- pred take(char, list(block), list(block)).
:- mode take(in, in, out) is nondet.
take(C, !Blocks) :-
list.delete(!.Blocks, {A, B}, !:Blocks),
( A = C ; B = C ).
:- pred can_make_word(list(char)::in, list(block)::in) is semidet.
can_make_word([], _).
can_make_word([C|Cs], !.Blocks) :-
take(C, !Blocks),
can_make_word(Cs, !.Blocks).
main(!IO) :-
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'}
],
Words = ["A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "CONFUSE"],
foldl((pred(W::in, !.IO::di, !:IO::uo) is det :-
P = can_make_word(to_char_list(W), Blocks),
io.format("can_make_word(""%s"") :- %s.\n",
[s(W), s(if P then "true" else "fail")], !IO)),
Words, !IO). |
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.
| #MATLAB | MATLAB | function [randSuccess,idealSuccess]=prisoners(numP,numG,numT)
%numP is the number of prisoners
%numG is the number of guesses
%numT is the number of trials
randSuccess=0;
%Random
for trial=1:numT
drawers=randperm(numP);
won=1;
for i=1:numP
correct=0;
notopened=drawers;
for j=1:numG
ind=randi(numel(notopened));
m=notopened(ind);
if m==i
correct=1;
break;
end
notopened(ind)=[];
end
if correct==0
won=0;
break;
end
end
randSuccess=randSuccess*(trial-1)/trial+won/trial;
end
%Ideal
idealSuccess=0;
for trial=1:numT
drawers=randperm(numP);
won=1;
for i=1:numP
correct=0;
guess=i;
for j=1:numG
m=drawers(guess);
if m==i
correct=1;
break;
end
guess=m;
end
if correct==0
won=0;
break;
end
end
idealSuccess=idealSuccess*(trial-1)/trial+won/trial;
end
disp(['Probability of success with random strategy: ' num2str(randSuccess*100) '%']);
disp(['Probability of success with ideal strategy: ' num2str(idealSuccess*100) '%']);
end |
http://rosettacode.org/wiki/24_game/Solve | 24 game/Solve | task
Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the 24 game.
Show examples of solutions generated by the program.
Related task
Arithmetic Evaluator
| #Racket | Racket |
(define (in-variants n1 o1 n2 o2 n3 o3 n4)
(let ([o1n (object-name o1)]
[o2n (object-name o2)]
[o3n (object-name o3)])
(with-handlers ((exn:fail:contract:divide-by-zero? (λ (_) empty-sequence)))
(in-parallel
(list (o1 (o2 (o3 n1 n2) n3) n4)
(o1 (o2 n1 (o3 n2 n3)) n4)
(o1 (o2 n1 n2) (o3 n3 n4))
(o1 n1 (o2 (o3 n2 n3) n4))
(o1 n1 (o2 n2 (o3 n3 n4))))
(list `(((,n1 ,o3n ,n2) ,o2n ,n3) ,o1n ,n4)
`((,n1 ,o2n (,n2 ,o3n ,n3)) ,o1n ,n4)
`((,n1 ,o2n ,n2) ,o1n (,n3 ,o3n ,n4))
`(,n1 ,o1n ((,n2 ,o3n ,n3) ,o2n ,n4))
`(,n1 ,o1n (,n2 ,o2n (,n3 ,o3n ,n4))))))))
|
http://rosettacode.org/wiki/15_puzzle_game | 15 puzzle game |
Task
Implement the Fifteen Puzzle Game.
The 15-puzzle is also known as:
Fifteen Puzzle
Gem Puzzle
Boss Puzzle
Game of Fifteen
Mystic Square
14-15 Puzzle
and some others.
Related Tasks
15 Puzzle Solver
16 Puzzle Game
| #J | J | require'general/misc/prompt'
genboard=:3 :0
b=. ?~16
if. 0<C.!.2 b do.
b=. (<0 _1)C. b
end.
a: (b i.0)} <"0 b
)
done=: (<"0]1+i.15),a:
shift=: |.!._"0 2
taxi=: |:,/"2(_1 1 shift i.4 4),_1 1 shift"0 1/ i.4 4
showboard=:3 :0
echo 'current board:'
echo 4 4$y
)
help=:0 :0
Slide a number block into the empty space
until you get:
┌──┬──┬──┬──┐
│1 │2 │3 │4 │
├──┼──┼──┼──┤
│5 │6 │7 │8 │
├──┼──┼──┼──┤
│9 │10│11│12│
├──┼──┼──┼──┤
│13│14│15│ │
└──┴──┴──┴──┘
Or type 'q' to quit.
)
getmove=:3 :0
showboard y
blank=. y i. a:
options=. /:~ ;y {~ _ -.~ blank { taxi
whilst. -. n e. options do.
echo 'Valid moves: ',":options
t=. prompt 'move which number? '
if. 'q' e. t do.
echo 'giving up'
throw.
elseif. 'h' e. t do.
echo help
showboard y
end.
n=. {._".t
end.
(<blank,y i.<n) C. y
)
game=: 3 :0
echo '15 puzzle'
echo 'h for help, q to quit'
board=. genboard''
whilst. -. done-:board do.
board=. getmove board
end.
showboard board
echo 'You win.'
) |
http://rosettacode.org/wiki/2048 | 2048 | Task
Implement a 2D sliding block puzzle game where blocks with numbers are combined to add their values.
Rules of the game
The rules are that on each turn the player must choose a direction (up, down, left or right).
All tiles move as far as possible in that direction, some move more than others.
Two adjacent tiles (in that direction only) with matching numbers combine into one bearing the sum of those numbers.
A move is valid when at least one tile can be moved, if only by combination.
A new tile with the value of 2 is spawned at the end of each turn at a randomly chosen empty square (if there is one).
Adding a new tile on a blank space. Most of the time, a new 2 is to be added, and occasionally (10% of the time), a 4.
To win, the player must create a tile with the number 2048.
The player loses if no valid moves are possible.
The name comes from the popular open-source implementation of this game mechanic, 2048.
Requirements
"Non-greedy" movement.
The tiles that were created by combining other tiles should not be combined again during the same turn (move).
That is to say, that moving the tile row of:
[2][2][2][2]
to the right should result in:
......[4][4]
and not:
.........[8]
"Move direction priority".
If more than one variant of combining is possible, move direction shall indicate which combination will take effect.
For example, moving the tile row of:
...[2][2][2]
to the right should result in:
......[2][4]
and not:
......[4][2]
Check for valid moves. The player shouldn't be able to skip their turn by trying a move that doesn't change the board.
Check for a win condition.
Check for a lose condition.
| #Lua | Lua | -- 2048 for Lua 5.1-5.4, 12/3/2020 db
local unpack = unpack or table.unpack -- for 5.3 +/- compatibility
game = {
cell = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
best = 0,
draw = function(self)
local t = self.cell
print("+----+----+----+----+")
for r=0,12,4 do
print(string.format("|%4d|%4d|%4d|%4d|\n+----+----+----+----+",t[r+1],t[r+2],t[r+3],t[r+4]))
end
end,
incr = function(self)
local t,open = self.cell,{}
for i=1,16 do if t[i]==0 then open[#open+1]=i end end
t[open[math.random(#open)]] = math.random()<0.1 and 4 or 2
end,
pack = function(self,ofr,oto,ost,ifr,ito,ist)
local t = self.cell
for outer=ofr,oto,ost do
local skip = 0
for inner=ifr,ito,ist do
local i = outer+inner
if t[i]==0 then skip=skip+1 else if skip>0 then t[i-skip*ist],t[i],self.diff = t[i],0,true end end
end
end
end,
comb = function(self,ofr,oto,ost,ifr,ito,ist)
local t = self.cell
for outer=ofr,oto,ost do
for inner=ifr,ito-ist,ist do
local i,j = outer+inner,outer+inner+ist
if t[i]>0 and t[i]==t[j] then t[i],t[j],self.diff,self.best = t[i]*2,0,true,math.max(self.best,t[i]*2) end
end
end
end,
move = function(self,dir)
local loopdata = {{0,12,4,1,4,1},{0,12,4,4,1,-1},{1,4,1,0,12,4},{1,4,1,12,0,-4}}
local ofr,oto,ost,ifr,ito,ist = unpack(loopdata[dir])
self:pack(ofr,oto,ost,ifr,ito,ist)
self:comb(ofr,oto,ost,ifr,ito,ist)
self:pack(ofr,oto,ost,ifr,ito,ist)
end,
full = function(self)
local t = self.cell
for r=0,12,4 do
for c=1,4 do
local i,v = r+c,t[r+c]
if (v==0) or (c>1 and t[i-1]==v) or (c<4 and t[i+1]==v) or (r>0 and t[i-4]==v) or (r<12 and t[i+4]==v) then
return false
end
end
end
return true
end,
play = function(self)
math.randomseed(os.time())
self:incr()
self:incr()
while true do
self:draw()
if self.best==2048 then print("WIN!") break end
if self:full() then print("LOSE!") break end
io.write("Your move (wasd + enter, or q + enter to quit): ")
local char = io.read()
self.diff = false
if (char=="a") then self:move(1)
elseif (char=="d") then self:move(2)
elseif (char=="w") then self:move(3)
elseif (char=="s") then self:move(4)
elseif (char=="q") then break end
if self.diff then self:incr() end
end
end
}
game:play() |
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
| #BlitzMax | BlitzMax | local bot:int = 99
repeat
print string(bot)+" bottles of beer on the wall,"
print string(bot)+" bottles of beer."
print "Take one down, pass it around,"
bot:-1
print string(bot)+" bottles of beer on the wall."
print
until bot = 1
print "1 bottle of beer on the wall,"
print "1 bottle of beer."
print "Take it down, pass it around,"
print "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.
| #Logo | Logo | ; useful constants
make "false 1=0
make "true 1=1
make "lf char 10
make "sp char 32
; non-digits legal in expression
make "operators (lput sp [+ - * / \( \)])
; display help message
to show_help :digits
type lf
print sentence quoted [Using only these digits:] :digits
print sentence quoted [and these operators:] [* / + -]
print quoted [\(and parentheses as needed\),]
print quoted [enter an arithmetic expression
which evaluates to exactly 24.]
type lf
print quoted [Enter \"!\" to get fresh numbers.]
print quoted [Enter \"q\" to quit.]
type lf
end
make "digits []
make "done false
until [done] [
if empty? digits [
make "digits (map [(random 9) + 1] [1 2 3 4])
]
(type "Solution sp "for sp digits "? sp )
make "expression readrawline
ifelse [expression = "?] [
show_help digits
] [ifelse [expression = "q] [
print "Bye!
make "done true
] [ifelse [expression = "!] [
make "digits []
] [
make "exprchars ` expression
make "allowed (sentence digits operators)
ifelse (member? false (map [[c] member? c allowed] exprchars)) [
(print quoted [Illegal character in input.])
] [
catch "error [
make "syntax_error true
make "testval (run expression)
make "syntax_error false
]
ifelse syntax_error [
(print quoted [Invalid expression.])
] [
ifelse (testval = 24) [
print quoted [You win!]
make "done true
] [
(print (sentence
quoted [Incorrect \(got ] testval quoted [instead of 24\).]))
]
]
]
]]]
]
bye |
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
| #Elm | Elm |
--To write this function directly run cmd
--Type elm-repl to start
--Next enter this code
sum x y=x+y
--This creates a sum function
--When you enter sum A B
--You get output as A+B : number
--Task done!
--END
|
http://rosettacode.org/wiki/ABC_problem | ABC problem | ABC problem
You are encouraged to solve this task according to the task description, using any language you may know.
You are given a collection of ABC blocks (maybe like the ones you had when you were a kid).
There are twenty blocks with two letters on each block.
A complete alphabet is guaranteed amongst all 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
| #MiniScript | MiniScript | allBlocks = ["BO", "XK", "DQ", "CP", "NA", "GT", "RE", "TG", "QD", "FS", "JW", "HU", "VI", "AN", "OB", "ER", "FS", "LY", "PC", "ZM"]
swap = function(list, index1, index2)
tmp = list[index1]
list[index1] = list[index2]
list[index2] = tmp
end function
canMakeWord = function(str, blocks)
if str == "" then return true
c = str[0].upper
for i in range(0, blocks.len - 1)
bl = blocks[i]
if c != bl[0] and c != bl[1] then continue
swap blocks, 0, i
if canMakeWord(str[1:], blocks[1:]) then return true
swap blocks, 0, i
end for
return false
end function
for val in ["", "A", "BARK", "book", "Treat", "COMMON", "sQuAD", "CONFUSE"]
out = """"""
if val.len != 0 then out = val
print out + ": " + canMakeWord(val, allBlocks)
end for
|
http://rosettacode.org/wiki/100_prisoners | 100 prisoners |
The Problem
100 prisoners are individually numbered 1 to 100
A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside.
Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start.
Prisoners start outside the room
They can decide some strategy before any enter the room.
Prisoners enter the room one by one, can open a drawer, inspect the card number in the drawer, then close the drawer.
A prisoner can open no more than 50 drawers.
A prisoner tries to find his own number.
A prisoner finding his own number is then held apart from the others.
If all 100 prisoners find their own numbers then they will all be pardoned. If any don't then all sentences stand.
The task
Simulate several thousand instances of the game where the prisoners randomly open drawers
Simulate several thousand instances of the game where the prisoners use the optimal strategy mentioned in the Wikipedia article, of:
First opening the drawer whose outside number is his prisoner number.
If the card within has his number then he succeeds otherwise he opens the drawer with the same number as that of the revealed card. (until he opens his maximum).
Show and compare the computed probabilities of success for the two strategies, here, on this page.
References
The unbelievable solution to the 100 prisoner puzzle standupmaths (Video).
wp:100 prisoners problem
100 Prisoners Escape Puzzle DataGenetics.
Random permutation statistics#One hundred prisoners on Wikipedia.
| #MiniScript | MiniScript | playRandom = function(n)
// using 0-99 instead of 1-100
pardoned = 0
numInDrawer = range(99)
choiceOrder = range(99)
for round in range(1, n)
numInDrawer.shuffle
choiceOrder.shuffle
for prisoner in range(99)
found = false
for card in choiceOrder[:50]
if card == prisoner then
found = true
break
end if
end for
if not found then break
end for
if found then pardoned = pardoned + 1
end for
return pardoned / n * 100
end function
playOptimal = function(n)
// using 0-99 instead of 1-100
pardoned = 0
numInDrawer = range(99)
for round in range(1, n)
numInDrawer.shuffle
for prisoner in range(99)
found = false
drawer = prisoner
for i in range(1,50)
card = numInDrawer[drawer]
if card == prisoner then
found = true
break
end if
drawer = card
end for
if not found then break
end for
if found then pardoned = pardoned + 1
end for
return pardoned / n * 100
end function
print "Random: " + playRandom(10000) + "%"
print "Optimal: " + playOptimal(10000) + "%" |
http://rosettacode.org/wiki/24_game/Solve | 24 game/Solve | task
Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the 24 game.
Show examples of solutions generated by the program.
Related task
Arithmetic Evaluator
| #Raku | Raku | use MONKEY-SEE-NO-EVAL;
my @digits;
my $amount = 4;
# Get $amount digits from the user,
# ask for more if they don't supply enough
while @digits.elems < $amount {
@digits.append: (prompt "Enter {$amount - @digits} digits from 1 to 9, "
~ '(repeats allowed): ').comb(/<[1..9]>/);
}
# Throw away any extras
@digits = @digits[^$amount];
# Generate combinations of operators
my @ops = [X,] <+ - * /> xx 3;
# Enough sprintf formats to cover most precedence orderings
my @formats = (
'%d %s %d %s %d %s %d',
'(%d %s %d) %s %d %s %d',
'(%d %s %d %s %d) %s %d',
'((%d %s %d) %s %d) %s %d',
'(%d %s %d) %s (%d %s %d)',
'%d %s (%d %s %d %s %d)',
'%d %s (%d %s (%d %s %d))',
);
# Brute force test the different permutations
(unique @digits.permutations).race.map: -> @p {
for @ops -> @o {
for @formats -> $format {
my $string = sprintf $format, flat roundrobin(|@p; |@o);
my $result = EVAL($string);
say "$string = 24" and last if $result and $result == 24;
}
}
}
# Only return unique sub-arrays
sub unique (@array) {
my %h = map { $_.Str => $_ }, @array;
%h.values;
} |
http://rosettacode.org/wiki/15_puzzle_game | 15 puzzle game |
Task
Implement the Fifteen Puzzle Game.
The 15-puzzle is also known as:
Fifteen Puzzle
Gem Puzzle
Boss Puzzle
Game of Fifteen
Mystic Square
14-15 Puzzle
and some others.
Related Tasks
15 Puzzle Solver
16 Puzzle Game
| #Java | Java | package fifteenpuzzle;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import javax.swing.*;
class FifteenPuzzle extends JPanel {
private final int side = 4;
private final int numTiles = side * side - 1;
private final Random rand = new Random();
private final int[] tiles = new int[numTiles + 1];
private final int tileSize;
private int blankPos;
private final int margin;
private final int gridSize;
private boolean gameOver;
private FifteenPuzzle() {
final int dim = 640;
margin = 80;
tileSize = (dim - 2 * margin) / side;
gridSize = tileSize * side;
setPreferredSize(new Dimension(dim, dim + margin));
setBackground(Color.WHITE);
setForeground(new Color(0x6495ED)); // cornflowerblue
setFont(new Font("SansSerif", Font.BOLD, 60));
gameOver = true;
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
if (gameOver) {
newGame();
} else {
int ex = e.getX() - margin;
int ey = e.getY() - margin;
if (ex < 0 || ex > gridSize || ey < 0 || ey > gridSize) {
return;
}
int c1 = ex / tileSize;
int r1 = ey / tileSize;
int c2 = blankPos % side;
int r2 = blankPos / side;
int clickPos = r1 * side + c1;
int dir = 0;
if (c1 == c2 && Math.abs(r1 - r2) > 0) {
dir = (r1 - r2) > 0 ? 4 : -4;
} else if (r1 == r2 && Math.abs(c1 - c2) > 0) {
dir = (c1 - c2) > 0 ? 1 : -1;
}
if (dir != 0) {
do {
int newBlankPos = blankPos + dir;
tiles[blankPos] = tiles[newBlankPos];
blankPos = newBlankPos;
} while (blankPos != clickPos);
tiles[blankPos] = 0;
}
gameOver = isSolved();
}
repaint();
}
});
newGame();
}
private void newGame() {
do {
reset();
shuffle();
} while (!isSolvable());
gameOver = false;
}
private void reset() {
for (int i = 0; i < tiles.length; i++) {
tiles[i] = (i + 1) % tiles.length;
}
blankPos = tiles.length - 1;
}
private void shuffle() {
// don't include the blank space in the shuffle, leave it
// in the home position
int n = numTiles;
while (n > 1) {
int r = rand.nextInt(n--);
int tmp = tiles[r];
tiles[r] = tiles[n];
tiles[n] = tmp;
}
}
/* 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
*/
private boolean isSolvable() {
int countInversions = 0;
for (int i = 0; i < numTiles; i++) {
for (int j = 0; j < i; j++) {
if (tiles[j] > tiles[i]) {
countInversions++;
}
}
}
return countInversions % 2 == 0;
}
private boolean isSolved() {
if (tiles[tiles.length - 1] != 0) {
return false;
}
for (int i = numTiles - 1; i >= 0; i--) {
if (tiles[i] != i + 1) {
return false;
}
}
return true;
}
private void drawGrid(Graphics2D g) {
for (int i = 0; i < tiles.length; i++) {
int r = i / side;
int c = i % side;
int x = margin + c * tileSize;
int y = margin + r * tileSize;
if (tiles[i] == 0) {
if (gameOver) {
g.setColor(Color.GREEN);
drawCenteredString(g, "\u2713", x, y);
}
continue;
}
g.setColor(getForeground());
g.fillRoundRect(x, y, tileSize, tileSize, 25, 25);
g.setColor(Color.blue.darker());
g.drawRoundRect(x, y, tileSize, tileSize, 25, 25);
g.setColor(Color.WHITE);
drawCenteredString(g, String.valueOf(tiles[i]), x, y);
}
}
private void drawStartMessage(Graphics2D g) {
if (gameOver) {
g.setFont(getFont().deriveFont(Font.BOLD, 18));
g.setColor(getForeground());
String s = "click to start a new game";
int x = (getWidth() - g.getFontMetrics().stringWidth(s)) / 2;
int y = getHeight() - margin;
g.drawString(s, x, y);
}
}
private void drawCenteredString(Graphics2D g, String s, int x, int y) {
FontMetrics fm = g.getFontMetrics();
int asc = fm.getAscent();
int des = fm.getDescent();
x = x + (tileSize - fm.stringWidth(s)) / 2;
y = y + (asc + (tileSize - (asc + des)) / 2);
g.drawString(s, x, y);
}
@Override
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
drawGrid(g);
drawStartMessage(g);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Fifteen Puzzle");
f.setResizable(false);
f.add(new FifteenPuzzle(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
} |
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.
| #M2000_Interpreter | M2000 Interpreter |
Module Game2048 {
\\ 10% 4 and 90% 2
Def GetTlleNumber()=If(Random(10)<2->4, 2)
\\ tile
Def Tile$(x)=If$(x=0->"[ ]", format$("[{0::-4}]", x))
\\ empty board
BoardTileRight=lambda (x, y)->x+y*4
BoardTileLeft=lambda (x, y)->3-x+y*4
BoardTileUp=lambda (x, y)->x*4+y
BoardTileDown=lambda (x, y)->(3-x)*4+y
Dim Board(0 to 15)
Inventory EmptyTiles
\\ Score is a statement but we can use it as a variable too.
Score=0
\\ Win is also a statement but we can use it as a variable too.
Win=False
ExitNow=False
BoardDirection=BoardtileRight
Process(BoardDirection)
\\ Split Rem lines to insert start condition to check valid moves
Rem : board(0)=2
Rem : board(1)=2, 2, 2 ' place to (1), (2), (3)
While len(EmptyTiles) {
NewTile()
DrawBoard()
Action=False
do {
a$=key$
if len(a$)=2 then {
Action=true
Select case Asc(mid$(a$,2))
Case 72
BoardDirection=BoardTileUp
Case 75
BoardDirection=BoardTileRight
Case 77
BoardDirection=BoardTileLeft
Case 80
BoardDirection=BoardTileDown
Case 79 ' End key
ExitNow=True
Else
Action=false
end select
}
} until Action
If ExitNow then exit
Process(BoardDirection)
}
If Win then {
Print "You Win"
} Else {
Print "You Loose"
}
End
Sub Process(Boardtile)
Inventory EmptyTiles ' clear inventory
local where, i, j, k
For i=0 to 3
Gravity()
k=boardtile(0,i)
For j=1 to 3
where=boardtile(j,i)
if Board(where)<>0 then {
if board(k)=board(where) then {
board(k)*=2 : score+=board(where): board(where)=0
if board(k)=2048 Then Win=True : ExitNow=true
}
}
k=where
Next j
Gravity()
For j=0 to 3
where=boardtile(j,i)
if board(where)=0 then Append EmptyTiles, where
Next j
Next i
End Sub
Sub NewTile()
local m=EmptyTiles(Random(0, len(EmptyTiles)-1)!)
Board(m)=GetTlleNumber()
Delete EmptyTiles, m
End Sub
Sub DrawBoard()
Refresh 2000
Cls
Cursor 0, 10
Local Doc$, line$
Document Doc$
Doc$=Format$("Game 2048 Score {0}", score)
\\ Using Report 2 we use rendering as text, with center justify
Report 2, Doc$
Doc$={
}
Local i, j
For i=0 to 3
line$=""
For j=0 to 3
line$+=Tile$(Board(BoardTileRight(j, i)))
Next j
Print Over $(2), Line$
Print
Doc$=Line$+{
}
Next i
Report 2, "Next:Use Arrows | Exit: Press End"
Refresh
ClipBoard Doc$
End Sub
Sub Gravity()
k=-1
for j=0 to 3 {
where=boardtile(j,i)
if k=-1 then if board(where)=0 then k=j : continue
if board(where)=0 then continue
if k=-1 then continue
board(boardtile(k,i))=board(where)
board(where)=0
k++
}
End Sub
}
Game2048
|
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
| #BlooP | BlooP |
DEFINE PROCEDURE ''MINUS'' [A,B]:
BLOCK 0: BEGIN
IF A < B, THEN:
QUIT BLOCK 0;
LOOP AT MOST A TIMES:
BLOCK 1: BEGIN
IF OUTPUT + B = A, THEN:
QUIT BLOCK 0;
OUTPUT <= OUTPUT + 1;
BLOCK 1: END;
BLOCK 0: END.
DEFINE PROCEDURE ''BOTTLES'' [COUNT]:
BLOCK 0: BEGIN
CELL(0) <= COUNT;
LOOP COUNT + 1 TIMES:
BLOCK 1: BEGIN
IF CELL(0) > 1, THEN:
PRINT[CELL(0), ' bottles of beer on the wall, ', CELL(0), ' bottles of beer. Take one down, pass it around, ', MINUS[CELL(0), 1], ' bottles of beer on the wall.'];
IF CELL(0) = 1, THEN:
PRINT['1 botle of beer on the wall, 1 bottle of beer. Take one down, pass it around, No more bottles of beer on the wall.'];
IF CELL(0) = 0, THEN:
PRINT['No more bottles of beer on the wall, no more bottles of beer. Go to the store, buy 99 more, 99 bottles of beer on the wall!'];
CELL(0) <= MINUS[CELL(0), 1];
BLOCK 1: END;
BLOCK 0: END.
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.
| #Lua | Lua |
local function help()
print [[
The 24 Game
Given any four digits in the range 1 to 9, which may have repetitions,
Using just the +, -, *, and / operators; and the possible use of
brackets, (), show how to make an answer of 24.
An answer of "q" will quit the game.
An answer of "!" will generate a new set of four digits.
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.
]]
end
local function generate(n)
result = {}
for i=1,n do
result[i] = math.random(1,9)
end
return result
end
local function check(answer, digits)
local adig = {}
local ddig = {}
local index
local lastWasDigit = false
for i=1,9 do adig[i] = 0 ddig[i] = 0 end
allowed = {['(']=true,[')']=true,[' ']=true,['+']=true,['-']=true,['*']=true,['/']=true,['\t']=true,['1']=true,['2']=true,['3']=true,['4']=true,['5']=true,['6']=true,['7']=true,['8']=true,['9']=true}
for i=1,string.len(answer) do
if not allowed[string.sub(answer,i,i)] then
return false
end
index = string.byte(answer,i)-48
if index > 0 and index < 10 then
if lastWasDigit then
return false
end
lastWasDigit = true
adig[index] = adig[index] + 1
else
lastWasDigit = false
end
end
for i,digit in next,digits do
ddig[digit] = ddig[digit]+1
end
for i=1,9 do
if adig[i] ~= ddig[i] then
return false
end
end
return loadstring('return '..answer)()
end
local function game24()
help()
math.randomseed(os.time())
math.random()
local digits = generate(4)
local trial = 0
local answer = 0
local ans = false
io.write 'Your four digits:'
for i,digit in next,digits do
io.write (' ' .. digit)
end
print()
while ans ~= 24 do
trial = trial + 1
io.write("Expression "..trial..": ")
answer = io.read()
if string.lower(answer) == 'q' then
break
end
if answer == '!' then
digits = generate(4)
io.write ("New digits:")
for i,digit in next,digits do
io.write (' ' .. digit)
end
print()
else
ans = check(answer,digits)
if ans == false then
print ('The input '.. answer ..' was wonky!')
else
print (' = '.. ans)
if ans == 24 then
print ("Thats right!")
end
end
end
end
end
game24() |
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
| #Emacs_Lisp | Emacs Lisp | (let* ((input (read-from-minibuffer ""))
(numbers (mapcar #'string-to-number (split-string input)))
(a (car numbers))
(b (cadr numbers)))
(message "%d" (+ a b))) |
http://rosettacode.org/wiki/ABC_problem | ABC problem | ABC problem
You are encouraged to solve this task according to the task description, using any language you may know.
You are given a collection of ABC blocks (maybe like the ones you had when you were a kid).
There are twenty blocks with two letters on each block.
A complete alphabet is guaranteed amongst all 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
| #Nim | Nim | import std / strutils
func canMakeWord(blocks: seq[string]; word: string): bool =
if blocks.len < word.len: return false
if word.len == 0: return true
let ch = word[0].toUpperAscii
for i, pair in blocks:
if ch in pair and
(blocks[0..<i] & blocks[i+1..^1]).canMakeWord(word[1..^1]):
return true
proc main =
for (blocks, words) in [
("BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM".splitWhitespace,
@["A", "bArK", "BOOK", "treat", "common", "sQuAd", "CONFUSE"]),
("AB AB AC AC".splitWhitespace, @["ABBa"]),
("US TZ AO QA".splitWhitespace, @["Auto"])
]:
echo "Using the blocks ", blocks.join(" ")
for word in words:
echo " can we make the word '$#'? $#" % [
word, if blocks.canMakeWord(word): "yes" else: "no"]
echo()
when isMainModule: main() |
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.
| #Nim | Nim | import random, sequtils, strutils
type
Sample = tuple
succ: int
fail: int
const
numPrisoners = 100
numDrawsEachPrisoner = numPrisoners div 2
numDrawings: Positive = 1_000_000 div 1
proc `$`(s: Sample): string =
"Succs: $#\tFails: $#\tTotal: $#\tSuccess Rate: $#%." % [$s.succ, $s.fail, $(s.succ + s.fail), $(s.succ.float / (s.succ + s.fail).float * 100.0)]
proc prisonersWillBeReleasedSmart(): bool =
result = true
var drawers = toSeq(0..<numPrisoners)
drawers.shuffle
for prisoner in 0..<numPrisoners:
var drawer = prisoner
block inner:
for _ in 0..<numDrawsEachPrisoner:
if drawers[drawer] == prisoner: break inner
drawer = drawers[drawer]
return false
proc prisonersWillBeReleasedRandom(): bool =
result = true
var drawers = toSeq(0..<numPrisoners)
drawers.shuffle
for prisoner in 0..<numPrisoners:
var selectDrawer = toSeq(0..<numPrisoners)
selectDrawer.shuffle
block inner:
for i in 0..<numDrawsEachPrisoner:
if drawers[selectDrawer[i]] == prisoner: break inner
return false
proc massDrawings(prisonersWillBeReleased: proc(): bool): Sample =
var success = 0
for i in 1..numDrawings:
if prisonersWillBeReleased():
inc(success)
return (success, numDrawings - success)
randomize()
echo $massDrawings(prisonersWillBeReleasedSmart)
echo $massDrawings(prisonersWillBeReleasedRandom) |
http://rosettacode.org/wiki/24_game/Solve | 24 game/Solve | task
Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the 24 game.
Show examples of solutions generated by the program.
Related task
Arithmetic Evaluator
| #REXX | REXX | /*REXX program helps the user find solutions to the game of 24. */
/* start-of-help
┌───────────────────────────────────────────────────────────────────────┐
│ Argument is either of three forms: (blank) │~
│ ssss │~
│ ssss,tot │~
│ ssss-ffff │~
│ ssss-ffff,tot │~
│ -ssss │~
│ +ssss │~
│ │~
│ where SSSS and/or FFFF must be exactly four numerals (digits) │~
│ comprised soley of the numerals (digits) 1 ──> 9 (no zeroes). │~
│ │~
│ SSSS is the start, │~
│ FFFF is the start. │~
│ │~
│ │~
│ If ssss has a leading plus (+) sign, it is used as the number, and │~
│ the user is prompted to find a solution. │~
│ │~
│ If ssss has a leading minus (-) sign, a solution is looked for and │~
│ the user is told there is a solution (but no solutions are shown). │~
│ │~
│ If no argument is specified, this program finds a four digits (no │~
│ zeroes) which has at least one solution, and shows the digits to │~
│ the user, requesting that they enter a solution. │~
│ │~
│ If tot is entered, it is the desired answer. The default is 24. │~
│ │~
│ 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) │
└───────────────────────────────────────────────────────────────────────┘
end-of-help */
numeric digits 12 /*where rational arithmetic is needed. */
parse arg orig /*get the guess from the command line*/
orig= space(orig, 0) /*remove all blanks from ORIG. */
negatory= left(orig,1)=='-' /*=1, suppresses showing. */
pository= left(orig,1)=='+' /*=1, force $24 to use specific number.*/
if pository | negatory then orig=substr(orig,2) /*now, just use the absolute vaue. */
parse var orig orig ',' ?? /*get ?? (if specified, def=24). */
parse var orig start '-' finish /*get start and finish (maybe). */
opers= '*' || "/+-" /*legal arith. opers;order is important*/
ops= length(opers) /*the number of arithmetic operators. */
groupsym= '()[]{}' /*allowed grouping symbols. */
indent= left('', 30) /*indents display of solutions. */
show= 1 /*=1, shows solutions (semifore). */
digs= 123456789 /*numerals/digs that can be used. */
abuttals = 0 /*=1, allows digit abutal: 12+12 */
if ??=='' then ??= 24 /*the name of the game. */
??= ?? / 1 /*normalize the answer. */
@abc= 'abcdefghijklmnopqrstuvwxyz' /*the Latin alphabet in order. */
@abcu= @abc; upper @abcu /*an uppercase version of @abc. */
x.= 0 /*method used to not re-interpret. */
do j=1 for ops; o.j=substr(opers, j, 1)
end /*j*/ /*used for fast execution. */
y= ??
if \datatype(??,'N') then do; call ger "isn't numeric"; exit 13; end
if start\=='' & \pository then do; call ranger start,finish; exit 13; end
show= 0 /*stop SOLVE blabbing solutions. */
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*/
if left(orig,1)=='+' then rrrr=start /*use what's specified. */
show= 1 /*enable SOLVE to show solutions. */
rrrr= sortc(rrrr) /*sort four elements. */
rd.= 0
do j=1 for 9 /*count for each digit in RRRR. */
_= substr(rrrr, j, 1); rd._= countchars(rrrr, _)
end
do guesses=1; say
say 'Using the digits' rrrr", enter an expression that equals" ?? ' (? or QUIT):'
pull y; y= space(y, 0)
if countchars(y, @abcu)>2 then exit /*the user must be desperate. */
helpstart= 0
if y=='?' then do j=1 for sourceline() /*use a lazy way to show help. */
_= sourceline(j)
if p(_)=='start-of-help' then do; helpstart=1; iterate; end
if p(_)=='end-of-help' then iterate guesses
if \helpstart then iterate
if right(_,1)=='~' then iterate
say ' ' _
end
_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 digits adjacent. */
if \datatype(substr(y,j,1), 'W') then iterate
if 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*/
yd= countchars(y, digs) /*count of legal digits 123456789 */
if yd<4 then do; call ger 'not enough digits entered.'; iterate guesses; end
if yd>4 then do; call ger 'too many digits entered.' ; iterate guesses; end
do j=1 for length(groupsym) by 2
if countchars(y,substr(groupsym,j ,1))\==,
countchars(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)
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= countchars(y, j)
if _d==rd.j then iterate
if _d<rd.j then call ger 'not enough' j "digits, must be" rd.j
else call ger 'too many' j "digits, must be" rd.j
iterate guesses
end /*j*/
y= translate(y, '()()', "[]{}")
interpret 'ans=(' y ") / 1"
if ans==?? then leave guesses
say right('incorrect, ' y'='ans, 50)
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. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
countchars: procedure; arg x,c /*count of characters in X. */
return length(x) - length( space( translate(x, ,c ), 0) )
/*──────────────────────────────────────────────────────────────────────────────────────*/
ranger: parse arg ssss,ffff /*parse args passed to this sub. */
ffff= p(ffff ssss) /*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 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? */
say
say wols 'solution's(sols) "found for" g
if ??\==24 then say 'for answers that equal' ??
end
return
/*──────────────────────────────────────────────────────────────────────────────────────*/
solve: parse arg qqqq; finds= 0 /*parse args passed to this sub. */
if \validate(qqqq) then return -1
parse value '( (( )) )' with L LL RR R /*assign some static variables. */
nq.= 0
do jq=1 for 4; _= substr(qqqq,jq,1) /*count the number of each digit. */
nq._= nq._ + 1
end /*jq*/
do gggg=1111 to 9999
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) /*count the number of each digit. */
g.jg= _; ng._= ng._ + 1
end /*jg*/
do kg=1 for 9 /*verify each number has same # digits.*/
if nq.kg\==ng.kg then iterate gggg
end /*kg*/
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
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; !.1=L; !.2=L; !.6=RR; end
when m==5 then do; !.1=LL; !.5=R; !.6=R; end
when m==6 then do; !.2=L; !.5=R; end
when m==7 then do; !.2=L; !.6=R; end
when m==8 then do; !.2=L; !.4=L; !.6=RR; end
when m==9 then do; !.2=LL; !.5=R; !.6=R; 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. */
/*(below) change the expression: /(yyy) ===> /div(yyy) */
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 last right ) */
lm= pos('-', e, pd+1) /*find - 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, '][', ")(") /*show [], not (). */
if show then say indent 'a solution for' g':' ??"=" _ /*show solution.*/
end /*m*/
end /*k*/
end /*j*/
end /*i*/
end /*gggg*/
return finds
/*──────────────────────────────────────────────────────────────────────────────────────*/
sortc: procedure; arg nnnn; L= length(nnnn) /*sorts the chars NNNN */
do i=1 for L /*build array of digs from NNNN, */
a.i= substr(nnnn, i, 1) /*enabling SORT to sort an array. */
end /*i*/
do j=1 for L /*very simple sort, it's a small array*/
_= a.j
do k=j+1 to L
if a.k<_ then do; a.j= a.k; a.k= _; _= a.k; end
end /*k*/
end /*j*/
v= a.1
do m=2 to L; v= v || a.m /*build a string of digs from A.m */
end /*m*/
return v
/*──────────────────────────────────────────────────────────────────────────────────────*/
validate: parse arg y; errCode= 0; _v= verify(y, digs)
select
when y=='' then call ger 'no digits 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*/
return \errCode
/*──────────────────────────────────────────────────────────────────────────────────────*/
div: procedure; parse arg q; if q=0 then q=1e9; return q /*tests if dividing by zero.*/
ger: say= '***error*** for argument:' y; say arg(1); errCode= 1; return 0
p: return word( arg(1), 1)
s: if arg(1)==1 then return arg(3); return word( arg(2) 's', 1) |
http://rosettacode.org/wiki/15_puzzle_game | 15 puzzle game |
Task
Implement the Fifteen Puzzle Game.
The 15-puzzle is also known as:
Fifteen Puzzle
Gem Puzzle
Boss Puzzle
Game of Fifteen
Mystic Square
14-15 Puzzle
and some others.
Related Tasks
15 Puzzle Solver
16 Puzzle Game
| #JavaScript | JavaScript |
var board, zx, zy, clicks, possibles, clickCounter, oldzx = -1, oldzy = -1;
function getPossibles() {
var ii, jj, cx = [-1, 0, 1, 0], cy = [0, -1, 0, 1];
possibles = [];
for( var i = 0; i < 4; i++ ) {
ii = zx + cx[i]; jj = zy + cy[i];
if( ii < 0 || ii > 3 || jj < 0 || jj > 3 ) continue;
possibles.push( { x: ii, y: jj } );
}
}
function updateBtns() {
var b, v, id;
for( var j = 0; j < 4; j++ ) {
for( var i = 0; i < 4; i++ ) {
id = "btn" + ( i + j * 4 );
b = document.getElementById( id );
v = board[i][j];
if( v < 16 ) {
b.innerHTML = ( "" + v );
b.className = "button"
}
else {
b.innerHTML = ( "" );
b.className = "empty";
}
}
}
clickCounter.innerHTML = "Clicks: " + clicks;
}
function shuffle() {
var v = 0, t;
do {
getPossibles();
while( true ) {
t = possibles[Math.floor( Math.random() * possibles.length )];
console.log( t.x, oldzx, t.y, oldzy )
if( t.x != oldzx || t.y != oldzy ) break;
}
oldzx = zx; oldzy = zy;
board[zx][zy] = board[t.x][t.y];
zx = t.x; zy = t.y;
board[zx][zy] = 16;
} while( ++v < 200 );
}
function restart() {
shuffle();
clicks = 0;
updateBtns();
}
function checkFinished() {
var a = 0;
for( var j = 0; j < 4; j++ ) {
for( var i = 0; i < 4; i++ ) {
if( board[i][j] < a ) return false;
a = board[i][j];
}
}
return true;
}
function btnHandle( e ) {
getPossibles();
var c = e.target.i, r = e.target.j, p = -1;
for( var i = 0; i < possibles.length; i++ ) {
if( possibles[i].x == c && possibles[i].y == r ) {
p = i;
break;
}
}
if( p > -1 ) {
clicks++;
var t = possibles[p];
board[zx][zy] = board[t.x][t.y];
zx = t.x; zy = t.y;
board[zx][zy] = 16;
updateBtns();
if( checkFinished() ) {
setTimeout(function(){
alert( "WELL DONE!" );
restart();
}, 1);
}
}
}
function createBoard() {
board = new Array( 4 );
for( var i = 0; i < 4; i++ ) {
board[i] = new Array( 4 );
}
for( var j = 0; j < 4; j++ ) {
for( var i = 0; i < 4; i++ ) {
board[i][j] = ( i + j * 4 ) + 1;
}
}
zx = zy = 3; board[zx][zy] = 16;
}
function createBtns() {
var b, d = document.createElement( "div" );
d.className += "board";
document.body.appendChild( d );
for( var j = 0; j < 4; j++ ) {
for( var i = 0; i < 4; i++ ) {
b = document.createElement( "button" );
b.id = "btn" + ( i + j * 4 );
b.i = i; b.j = j;
b.addEventListener( "click", btnHandle, false );
b.appendChild( document.createTextNode( "" ) );
d.appendChild( b );
}
}
clickCounter = document.createElement( "p" );
clickCounter.className += "txt";
document.body.appendChild( clickCounter );
}
function start() {
createBtns();
createBoard();
restart();
}
|
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.
| #Maple | Maple |
macro(SP=DocumentTools:-SetProperty, GP=DocumentTools:-GetProperty);
G := module()
export reset,f,getname;
local a:=Matrix(4):
local buttonpress:="False";
local score:=0;
local highscoreM,highscore,hscore,hname,M,j,k,z,e,move,r,c,q,w,checklose,loss,matrixtotextarea;
getname:=proc();
hname:=GP("Name",value);
buttonpress:="True";
if score>hscore then
M:=Matrix(1, 2, [[score, hname]]):
ExportMatrix("this:///Score.csv",M);
reset();
else
reset();
end if;
end proc;
matrixtotextarea:=proc(m)
local m2,colors;
colors:=["White","Beige","LightGrey",ColorTools:-Color("RGB", [255/255, 127/255, 80/255]),ColorTools:-Color("RGB", [255/255, 99/255, 71/255]),ColorTools:-Color("RGB", [255/255, 69/255, 0/255]),ColorTools:-Color("RGB", [255/255, 0/255, 0/255]),ColorTools:-Color("RGB", [255/255, 215/255, 0/255]), ColorTools:-Color("RGB", [255/255, 255/255, 0/255]),ColorTools:-Color("RGB", [204/255, 204/255, 0/255]),ColorTools:-Color("RGB", [153/255, 153/255, 0/255]),ColorTools:-Color("RGB", [102/255, 102/255, 0/255]), ColorTools:-Color("RGB", [0/255, 0/255, 0/255])];
m2 := ArrayTools:-Reshape(m^%T, [16,1]):
SP(seq([cat("TextArea",i),value,m2[i+1,1]],i=0..15));
SP(seq(["Table1",fillcolor[(`if`(i+1<5,1,`if`(i+1<9 and i+1>4,2,`if`(i+1<13 and i+1>8,3, `if`(i+1<17 and i+1>12,4,1))))),(i mod 4)+1],`if`(m2[i+1,1]=0,colors[1],`if`(m2[i+1,1]=2,colors[2],`if`(m2[i+1,1]=4,colors[3],`if`(m2[i+1,1]=8,colors[4],`if`(m2[i+1,1]=16,colors[5],`if`(m2[i+1,1]=32,colors[6],`if`(m2[i+1,1]=64,colors[7],`if`(m2[i+1,1]=128,colors[8],`if`(m2[i+1,1]=256,colors[9],`if`(m2[i+1,1]=512,colors[10],`if`(m2[i+1,1]=1024,colors[11],`if`(m2[i+1,1]=2048,colors[12],`if`(m2[i+1,1]>2048,colors[13],"White")))))))))))))],i=0..15));
SP(seq([cat("TextArea",i),fillcolor,`if`(m2[i+1,1]=0,colors[1],`if`(m2[i+1,1]=2,colors[2],`if`(m2[i+1,1]=4,colors[3],`if`(m2[i+1,1]=8,colors[4],`if`(m2[i+1,1]=16,colors[5],`if`(m2[i+1,1]=32,colors[6],`if`(m2[i+1,1]=64,colors[7],`if`(m2[i+1,1]=128,colors[8],`if`(m2[i+1,1]=256,colors[9],`if`(m2[i+1,1]=512,colors[10],`if`(m2[i+1,1]=1024,colors[11],`if`(m2[i+1,1]=2048,colors[12],`if`(m2[i+1,1]>2048,colors[13],"White")))))))))))))],i=0..15),refresh);
SP(seq([cat("TextArea",i),fontcolor,`if`(m2[i+1,1]=0,colors[1],`if`(m2[i+1,1]=2,colors[13],`if`(m2[i+1,1]=4,colors[13],"White")))],i=0..15),refresh);
end proc:
reset:=proc();
highscoreM := Import("this:///Score.csv", output = Matrix);
hscore := highscoreM[1,1];
hname := highscoreM[1,2];
highscore:=sprintf("%s",cat(hscore,"\n",hname));
buttonpress:="False";
a:=Matrix(4, 4, [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]):
score:=0;
matrixtotextarea(a);
SP("Score/Lose",visible,true);
SP("Score/Lose",enabled,true);
SP("Score/Lose",caption,"Click an Arrow to begin.");
SP("Score",value,score);
SP("Highscore",value,highscore);
SP(seq([j, enabled, false], j in ["Name","Enter"]));
SP(seq([j, visible, false], j in ["Name","Enter"]));
SP(seq([j, enabled, true], j in ["Score","Highscore", seq(cat("Button",k),k=0..4)]));
SP(seq([j, visible, true], j in ["Score","Highscore", seq(cat("Button",k),k=0..4)]));
end proc;
checklose:=proc();
for q from 2 to 4 do
for w from 4 to 1 by -1 do
if a[q,w]=a[q-1,w] then
loss:="False";
return loss;
end if;
end do;
end do;
return loss;
end proc;
f:=proc(keypress);
SP("Score/Lose",visible,false);
SP("Score/Lose",enabled,false);
j := rand(1 .. 4);
k := rand(1 .. 4);
z := rand(1 .. 10);
e := 0;
move:=proc();
for q from 4 to 2 by -1 do
for w from 4 to 1 by -1 do
if a[q,w]=a[q-1,w] then
a[q-1,w]:=a[q-1,w]+a[q,w];
score:=score+a[q-1,w];
a[q,w]:=0;
if q-1>1 and a[q-2,w]=0 then
a[q-2,w]:=a[q-1,w];
a[q-1,w]:=0;
if q-2>1 and a[q-3,w]=0 then
a[q-3,w]:=a[q-2,w];
a[q-2,w]:=0;
end if;
end if;
elif q-1>1 and a[q,w]=a[q-2,w] and a[q-1,w]=0 then
a[q-2,w]:=a[q-2,w]+a[q,w];
score:=score+a[q-2,w];
a[q,w]:=0;
if q-2>1 and a[q-3,w]=0 then
a[q-3,w]:=a[q-2,w];
a[q-2,w]:=0;
end if;
elif q-2>1 and a[q,w]=a[q-3,w] and a[q-1,w]=0 and a[q-2,w]=0 then
a[q-3,w]:=a[q-3,w]+a[q,w];
score:=score+a[q-3,w];
a[q,w]:=0;
elif a[q-1,w]=0 then
a[q-1,w]:=a[q-1,w]+a[q,w];
a[q,w]:=0;
if q-1>1 and a[q-2,w]=0 then
a[q-2,w]:=a[q-1,w];
a[q-1,w]:=0;
if q-2>1 and a[q-3,w]=0 then
a[q-3,w]:=a[q-2,w];
a[q-2,w]:=0;
end if;
end if;
elif q-1>1 and a[q-2,w]=0 and a[q-1,w]=0 then
a[q-2,w]:=a[q-2,w]+a[q,w];
a[q,w]:=0;
if q-2>1 and a[q-3,w]=0 then
a[q-3,w]:=a[q-2,w];
a[q-2,w]:=0;
end if;
elif q-2>1 and a[q-3,w]=0 and a[q-1,w]=0 and a[q-2,w]=0 then
a[q-3,w]:=a[q-3,w]+a[q,w];
a[q,w]:=0;
end if;
end do;
end do;
end proc;
r := j();
c := k();
if keypress="Up" then
move();
elif keypress="Left" then
a:=LinearAlgebra:-Transpose(a);
move();
a:=LinearAlgebra:-Transpose(a);
elif keypress="Right" then
a := ArrayTools:-FlipDimension(LinearAlgebra:-Transpose(a),1);
move();
a := LinearAlgebra:-Transpose(ArrayTools:-FlipDimension(a,1));
elif keypress="Down" then
a := ArrayTools:-FlipDimension(a, 1);
move();
a := ArrayTools:-FlipDimension(a, 1);
end if;
if a[r, c] = 0 then
if z() > 3 then
a[r, c] := 2;
else;
a[r, c] := 4;
end if;
else
for q to 4 do
for w to 4 do
if a[q, w] <> 0 then;
e:=e+1;
end if;
end do;
end do;
if e = 16 then
loss:="True";
checklose();
a:=LinearAlgebra:-Transpose(a);
checklose();
a:=LinearAlgebra:-Transpose(a);
a := ArrayTools:-FlipDimension(LinearAlgebra:-Transpose(a),1);
checklose();
a := LinearAlgebra:-Transpose(ArrayTools:-FlipDimension(a,1));
a := ArrayTools:-FlipDimension(a, 1);
checklose();
a := ArrayTools:-FlipDimension(a, 1);
if loss="True" then
SP("Score/Lose",visible,"True");
SP("Score/Lose",enabled,"True");
SP("Score/Lose",caption,"You Lose!");
if score>hscore then
SP("Score/Lose",caption,"Highscore! Enter your name below!");
SP("Enter",caption,"Confirm");
SP(seq([j, enabled, true], j in ["Name","Enter","Score/Lose"]));
SP(seq([j, visible, true], j in ["Name","Enter","Score/Lose"]));
SP(seq([j, enabled, false], j in [seq(cat("Button",k),k=0..4)]));
SP(seq([j, visible, false], j in [seq(cat("Button",k),k=0..4)]));
if buttonpress="True" then
M:=Matrix(1, 2, [[score, hname]]):
ExportMatrix("this:///Score.csv",M);
buttonpress:="False";
reset();
end if;
else
SP("Score/Lose",caption,"Sorry, please try again.");
SP("Enter",caption,"Restart");
SP("Enter",visible,"True");
SP("Enter",enabled,"True");
SP(seq([j, enabled, false], j in [seq(cat("Button",k),k=0..4)]));
SP(seq([j, visible, false], j in [seq(cat("Button",k),k=0..4)]));
if buttonpress="True" then
buttonpress:="False";
reset();
end if;
end if;
end if;
else
e:=0;
while a[r, c] <> 0 do
r := j();
c := k();
end do;
if z() > 1 then
a[r, c] := 2;
else
a[r, c] := 4;
end if;
end if;
end if;
matrixtotextarea(a);
SP("Score",value,score,refresh);
return a;
end proc;
end module;
G:-reset();SP("Score/Lose",caption,"Click an Arrow to begin.");
|
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
| #Bracmat | Bracmat | No more bottles of beer on the wall, no more bottles of beer.
Go to the store and buy some more, 99 bottles of beer on the wall. |
http://rosettacode.org/wiki/24_game | 24 game | The 24 Game tests one's mental arithmetic.
Task
Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed.
The program should prompt for the player to enter an arithmetic expression using just those, and all of those four digits, used exactly once each. 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.
| #Maple | Maple | play24 := module()
export ModuleApply;
local cheating;
cheating := proc(input, digits)
local i, j, stringDigits;
use StringTools in
stringDigits := Implode([seq(convert(i, string), i in digits)]);
for i in digits do
for j in digits do
if Search(cat(convert(i, string), j), input) > 0 then
return true, ": Please don't combine digits to form another number."
end if;
end do;
end do;
for i in digits do
if CountCharacterOccurrences(input, convert(i, string)) < CountCharacterOccurrences(stringDigits, convert(i, string)) then
return true, ": Please use all digits.";
end if;
end do;
for i in digits do
if CountCharacterOccurrences(input, convert(i, string)) > CountCharacterOccurrences(stringDigits, convert(i, string)) then
return true, ": Please only use a digit once.";
end if;
end do;
for i in input do
try
if type(parse(i), numeric) and not member(parse(i), digits) then
return true, ": Please only use the digits you were given.";
end if;
catch:
end try;
end do;
return false, "";
end use;
end proc:
ModuleApply := proc()
local replay, digits, err, message, answer;
randomize():
replay := "":
while not replay = "END" do
if not replay = "YES" then
digits := [seq(rand(1..9)(), i = 1..4)]:
end if;
err := true:
while err do
message := "";
printf("Please make 24 from the digits: %a. Press enter for a new set of numbers or type END to quit\n", digits);
answer := StringTools[UpperCase](readline());
if not answer = "" and not answer = "END" then
try
if not type(parse(answer), numeric) then
error;
elif cheating(answer, digits)[1] then
message := cheating(answer, digits)[2];
error;
end if;
err := false;
catch:
printf("Invalid Input%s\n\n", message);
end try;
else
err := false;
end if;
end do:
if not answer = "" and not answer = "END" then
if parse(answer) = 24 then
printf("You win! Do you wish to play another game? (Press enter for a new set of numbers or END to quit.)\n");
replay := StringTools[UpperCase](readline());
else
printf("Your expression evaluated to %a. Try again!\n", parse(answer));
replay := "YES";
end if;
else
replay := answer;
end if;
printf("\n");
end do:
printf("GAME OVER\n");
end proc:
end module:
play24(); |
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
| #Emojicode | Emojicode | 🏁🍇
🆕🔡▶️👂🏼❗️ ➡️ input 💭 Get numbers as input string
🔫 input 🔤 🔤❗ ➡️ nums 💭 Split numbers by space
🍺🔢 🐽 nums 0❗ 10❗ ➡️ A 💭 Retrieve first number
🍺🔢 🐽 nums 1❗ 10❗ ➡️ B 💭 Retrieve second number
😀 🔤🧲A➕B🧲🔤 ❗ 💭 Output sum
🍉️ |
http://rosettacode.org/wiki/ABC_problem | ABC problem | ABC problem
You are encouraged to solve this task according to the task description, using any language you may know.
You are given a collection of ABC blocks (maybe like the ones you had when you were a kid).
There are twenty blocks with two letters on each block.
A complete alphabet is guaranteed amongst all 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
| #Oberon-2 | Oberon-2 |
MODULE ABCBlocks;
IMPORT
Object,
Out;
VAR
blocks: ARRAY 20 OF STRING;
PROCEDURE CanMakeWord(w: STRING): BOOLEAN;
VAR
used: ARRAY 20 OF LONGINT;
wChars: Object.CharsLatin1;
i,j: LONGINT;
PROCEDURE IsUsed(i: LONGINT): BOOLEAN;
VAR
b: LONGINT;
BEGIN
b := 0;
WHILE (b < LEN(used) - 1) & (used[b] # -1) DO
IF used[b] = i THEN RETURN TRUE END;
INC(b)
END;
RETURN FALSE
END IsUsed;
PROCEDURE GetBlockFor(blocks: ARRAY OF STRING; c: CHAR): LONGINT;
VAR
i: LONGINT;
BEGIN
i := 0;
WHILE (i < LEN(blocks)) DO
IF (blocks[i].IndexOf(c,0) >= 0) & (~IsUsed(i)) THEN RETURN i END;
INC(i)
END;
RETURN -1;
END GetBlockFor;
BEGIN
FOR i := 0 TO LEN(used) - 1 DO used[i] := -1 END;
wChars := w(Object.String8).CharsLatin1();
i := 0;
WHILE (i < LEN(wChars^) - 1) DO
j := GetBlockFor(blocks,CAP(wChars[i]));
IF j < 0 THEN RETURN FALSE END;
used[i] := j;
INC(i)
END;
RETURN TRUE
END CanMakeWord;
BEGIN
blocks[0] := "BO";
blocks[1] := "XK";
blocks[2] := "DQ";
blocks[3] := "CP";
blocks[4] := "NA";
blocks[5] := "GT";
blocks[6] := "RE";
blocks[7] := "TG";
blocks[8] := "QD";
blocks[9] := "FS";
blocks[10] := "JW";
blocks[11] := "HU";
blocks[12] := "VI";
blocks[13] := "AN";
blocks[14] := "OB";
blocks[15] := "ER";
blocks[16] := "FS";
blocks[17] := "LY";
blocks[18] := "PC";
blocks[19] := "ZM";
Out.String("A: ");Out.Bool(CanMakeWord("A"));Out.Ln;
Out.String("BARK: ");Out.Bool(CanMakeWord("BARK"));Out.Ln;
Out.String("BOOK: ");Out.Bool(CanMakeWord("BOOK"));Out.Ln;
Out.String("TREAT: ");Out.Bool(CanMakeWord("TREAT"));Out.Ln;
Out.String("COMMON: ");Out.Bool(CanMakeWord("COMMON"));Out.Ln;
Out.String("SQAD: ");Out.Bool(CanMakeWord("SQUAD"));Out.Ln;
Out.String("confuse: ");Out.Bool(CanMakeWord("confuse"));Out.Ln;
END ABCBlocks.
|
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.
| #Pascal | Pascal | program Prisoners100;
const
rounds = 100000;
type
tValue = Uint32;
tPrisNum = array of tValue;
var
drawers,
PrisonersChoice : tPrisNum;
procedure shuffle(var N:tPrisNum);
var
i,j,lmt : nativeInt;
tmp: tValue;
Begin
lmt := High(N);
For i := lmt downto 1 do
begin
//take on from index i..limit
j := random(i+1);
//exchange with i
tmp := N[i];N[i]:= N[j];N[j]:= tmp;
end;
end;
function PardonedRandom(maxTestNum: NativeInt):boolean;
var
PrisNum,TestNum,Lmt : NativeUint;
Pardoned : boolean;
Begin
IF maxTestNum <=0 then
Begin
PardonedRandom := false;
EXIT;
end;
Lmt := High(drawers);
IF (maxTestNum >= Lmt) then
Begin
PardonedRandom := true;
EXIT;
end;
shuffle(drawers);
PrisNum := 0;
repeat
//every prisoner uses his own list of drawers
shuffle(PrisonersChoice);
TestNum := 0;
repeat
Pardoned := drawers[PrisonersChoice[TestNum]] = PrisNum;
inc(TestNum);
until Pardoned OR (TestNum>=maxTestNum);
IF Not(Pardoned) then
BREAK;
inc(PrisNum);
until PrisNum>=Lmt;
PardonedRandom:= Pardoned;
end;
function PardonedOptimized(maxTestNum: NativeUint):boolean;
var
PrisNum,TestNum,NextNum,Cnt,Lmt : NativeUint;
Pardoned : boolean;
Begin
IF maxTestNum <=0 then
Begin
PardonedOptimized := false;
EXIT;
end;
Lmt := High(drawers);
IF (maxTestNum >= Lmt) then
Begin
PardonedOptimized := true;
EXIT;
end;
shuffle(drawers);
Lmt := High(drawers);
IF maxTestNum >= Lmt then
Begin
PardonedOptimized := true;
EXIT;
end;
PrisNum := 0;
repeat
Cnt := 0;
NextNum := PrisNum;
repeat
TestNum := NextNum;
NextNum := drawers[TestNum];
inc(cnt);
Pardoned := NextNum = PrisNum;
until Pardoned OR (cnt >=maxTestNum);
IF Not(Pardoned) then
BREAK;
inc(PrisNum);
until PrisNum>Lmt;
PardonedOptimized := Pardoned;
end;
procedure CheckRandom(testCount : NativeUint);
var
i,cnt : NativeInt;
Begin
cnt := 0;
For i := 1 to rounds do
IF PardonedRandom(TestCount) then
inc(cnt);
writeln('Randomly ',cnt/rounds*100:7:2,'% get pardoned out of ',rounds,' checking max ',TestCount);
end;
procedure CheckOptimized(testCount : NativeUint);
var
i,cnt : NativeInt;
Begin
cnt := 0;
For i := 1 to rounds do
IF PardonedOptimized(TestCount) then
inc(cnt);
writeln('Optimized ',cnt/rounds*100:7:2,'% get pardoned out of ',rounds,' checking max ',TestCount);
end;
procedure OneCompareRun(PrisCnt:NativeInt);
var
i,lmt :nativeInt;
begin
setlength(drawers,PrisCnt);
For i := 0 to PrisCnt-1 do
drawers[i] := i;
PrisonersChoice := copy(drawers);
//test
writeln('Checking ',PrisCnt,' prisoners');
lmt := PrisCnt;
repeat
CheckOptimized(lmt);
dec(lmt,PrisCnt DIV 10);
until lmt < 0;
writeln;
lmt := PrisCnt;
repeat
CheckRandom(lmt);
dec(lmt,PrisCnt DIV 10);
until lmt < 0;
writeln;
writeln;
end;
Begin
//init
randomize;
OneCompareRun(20);
OneCompareRun(100);
end. |
http://rosettacode.org/wiki/24_game/Solve | 24 game/Solve | task
Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the 24 game.
Show examples of solutions generated by the program.
Related task
Arithmetic Evaluator
| #Ruby | Ruby | class TwentyFourGame
EXPRESSIONS = [
'((%dr %s %dr) %s %dr) %s %dr',
'(%dr %s (%dr %s %dr)) %s %dr',
'(%dr %s %dr) %s (%dr %s %dr)',
'%dr %s ((%dr %s %dr) %s %dr)',
'%dr %s (%dr %s (%dr %s %dr))',
]
OPERATORS = [:+, :-, :*, :/].repeated_permutation(3).to_a
def self.solve(digits)
solutions = []
perms = digits.permutation.to_a.uniq
perms.product(OPERATORS, EXPRESSIONS) do |(a,b,c,d), (op1,op2,op3), expr|
# evaluate using rational arithmetic
text = expr % [a, op1, b, op2, c, op3, d]
value = eval(text) rescue next # catch division by zero
solutions << text.delete("r") if value == 24
end
solutions
end
end
# validate user input
digits = ARGV.map do |arg|
begin
Integer(arg)
rescue ArgumentError
raise "error: not an integer: '#{arg}'"
end
end
digits.size == 4 or raise "error: need 4 digits, only have #{digits.size}"
solutions = TwentyFourGame.solve(digits)
if solutions.empty?
puts "no solutions"
else
puts "found #{solutions.size} solutions, including #{solutions.first}"
puts solutions.sort
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
| #Julia | Julia |
using Random
const size = 4
const puzzle = string.(reshape(1:16, size, size))
puzzle[16] = " "
rng = MersenneTwister(Int64(round(time())))
shufflepuzzle() = (puzzle .= shuffle(rng, puzzle))
findtile(t) = findfirst(x->x == t, puzzle)
findhole() = findtile(" ")
function issolvable()
inversioncount = 1
asint(x) = (puzzle[x] == " ") ? 0 : parse(Int64, puzzle[x])
for i in 1:size^2-1, j in i:size^2
if puzzle[i] == " " || puzzle[j] == " "
continue
end
if parse(Int, puzzle[i]) < parse(Int, puzzle[j])
inversioncount += 1
end
end
if size % 2 == 1
return inversioncount % 2 == 0
end
pos = findhole()
inversioncount += pos[2]
return inversioncount & 1 == 0
end
function nexttohole()
holepos = findhole()
row = holepos[1]
col = holepos[2]
if row == 1
if col == 1
return [[row, col + 1], [row + 1, col]]
elseif col == size
return [[row, col - 1], [row + 1, col]]
else
return [[row, col - 1], [row, col + 1], [row + 1, col]]
end
elseif row == size
if col == 1
return [[row - 1, col], [row, col + 1]]
elseif col == size
return [[row - 1, col], [row, col - 1]]
else
return [[row - 1, col], [row, col - 1], [row, col + 1]]
end
else
if col == 1
return [[row - 1, col], [row, col + 1], [row + 1, col]]
elseif col == size
return [[row - 1, col], [row, col - 1], [row + 1, col]]
else
return [[row - 1, col], [row, col - 1], [row, col + 1], [row + 1, col]]
end
end
end
possiblemoves() = map(pos->puzzle[pos[1], pos[2]], nexttohole())
function movehole(tiletofill)
if tiletofill in possiblemoves()
curpos = findtile(tiletofill)
holepos = findhole()
puzzle[holepos] = tiletofill
puzzle[curpos] = " "
else
println("Bad tile move $tiletofill.\nPossible moves are $(possiblemoves()).")
end
end
function printboard()
ppuz(x,y) = print(lpad(rpad(puzzle[x,y], 3), 4), "|")
print("+----+----+----+----+\n|")
for j in 1:size, i in 1:size
ppuz(i,j)
if i == size
print("\n")
if j < size
print("|")
end
end
end
println("+----+----+----+----+")
end
function puzzle15play()
solved() = (puzzle[1:15] == string.(1:15))
shufflepuzzle()
println("This puzzle is", issolvable() ? " " : " not ", "solvable.")
while !solved()
printboard()
print("Possible moves are: $(possiblemoves()), 0 to exit. Your move? => ")
s = readline()
if s == "0"
exit(0)
end
movehole(s)
end
printboard()
println("Puzzle solved.")
end
puzzle15play()
|
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.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | SetOptions[InputNotebook[],NotebookEventActions->{
"LeftArrowKeyDown":>(stat=Coalesce[stat];AddNew[]),
"RightArrowKeyDown":>(stat=Reverse/@Coalesce[Reverse/@stat];AddNew[]),
"UpArrowKeyDown":>(stat=Coalesce[stat\[Transpose]]\[Transpose];AddNew[]),
"DownArrowKeyDown":>(stat=(Reverse/@(Coalesce[Reverse/@(stat\[Transpose])]))\[Transpose];AddNew[])
}
];
n=4;
bgcolor=GrayLevel[0.84];
colorfunc=Blend[{{0,Gray},{1/2,Red},{1,Blend[{Yellow,Orange}]}},#]&;
ClearAll[AddNew,PrintStat,Coalesce,SubCoalesce,AddRandomNumber]
AddNew[]:=(stat=AddRandomNumber[stat])
PrintStat[stat_]:=Module[{gr1,gr2,gr3,dr=0.2,cols,nstat=stat,positions},
gr1={bgcolor,Rectangle[-dr{1,1},n+dr{1,1},RoundingRadius->dr]};
cols=Map[If[#==0,0,Log2[#]]&,nstat,{2}];
cols=Map[If[#==0,Lighter@bgcolor,colorfunc[#/Max[cols]]]&,cols,{2}];
positions=Table[{i,n-j+1},{j,n},{i,n}];
gr2=MapThread[{#2,Rectangle[#3-{1,1}(1-dr/3),#3-{1,1}dr/3,RoundingRadius->dr/2]}&,{stat,cols,positions},2];
gr3=MapThread[If[#1>0,Style[Text[#1,#2-0.5{1,1}],20,White],{}]&,{stat,positions},2];
Graphics[{gr1,gr2,gr3},PlotRange->{{-0.5,n+0.5},{-0.5,n+0.5}},ImageSize->500]
]
Coalesce[stat_]:=SubCoalesce/@stat
SubCoalesce[statlist_]:=Module[{st=statlist,n=Length[statlist],pairs},
st=Split[DeleteCases[st,0]];
st=Partition[#,2,2,1,{}]&/@st;
st=Map[If[Length[#]==2,Total[#],#]&,st,{2}];
Join[Flatten[st],ConstantArray[0,n-Length[Flatten[st]]]]
]
AddRandomNumber[stat_,n_:2]:=With[{pos=Position[stat,0,{2}]},If[Length[pos]>0,ReplacePart[stat,RandomChoice[pos]->n],stat]]
stat=Nest[AddRandomNumber[#,RandomChoice[{2,4}]]&,ConstantArray[0,{n,n}],4];
Dynamic[PrintStat@stat] |
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
| #Brainf.2A.2A.2A | Brainf*** | 99.to 2 { n |
p "#{n} bottles of beer on the wall, #{n} bottles of beer!"
p "Take one down, pass it around, #{n - 1} bottle#{true? n > 2 's' ''} of beer on the wall."
}
p "One bottle of beer on the wall, one bottle of beer!"
p "Take one down, pass it around, no more bottles of beer on the wall." |
http://rosettacode.org/wiki/24_game | 24 game | The 24 Game tests one's mental arithmetic.
Task
Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed.
The program should prompt for the player to enter an arithmetic expression using just those, and all of those four digits, used exactly once each. 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.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | isLegal[n_List, x_String] :=
Quiet[Check[
With[{h = ToExpression[x, StandardForm, HoldForm]},
If[Cases[Level[h, {2, \[Infinity]}, Hold, Heads -> True],
Except[_Integer | Plus | _Plus | Times | _Times | Power |
Power[_, -1]]] === {} &&
Sort[Level[h /. Power[q_, -1] -> q, {-1}] /.
q_Integer -> Abs[q]] === Sort[n], ReleaseHold[h]]], Null]]
Grid[{{Button[
"new numbers", {a, b, c, d} = Table[RandomInteger[{1, 9}], {4}]],
InputField[Dynamic[x], String]}, {Dynamic[{a, b, c, d}],
Dynamic[Switch[isLegal[{a, b, c, d}, x], Null,
"Sorry, that is invalid.", 24, "Congrats! That's 24!", _,
"Sorry, that makes " <> ToString[ToExpression@x, InputForm] <>
", 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
| #Erlang | Erlang | -module(aplusb).
-export([start/0]).
start() ->
case io:fread("","~d~d") of
eof -> ok;
{ok, [A,B]} ->
io:format("~w~n",[A+B]),
start()
end. |
http://rosettacode.org/wiki/ABC_problem | ABC problem | ABC problem
You are encouraged to solve this task according to the task description, using any language you may know.
You are given a collection of ABC blocks (maybe like the ones you had when you were a kid).
There are twenty blocks with two letters on each block.
A complete alphabet is guaranteed amongst all 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
| #Objeck | Objeck | class Abc {
function : Main(args : String[]) ~ Nil {
blocks := ["BO", "XK", "DQ", "CP", "NA",
"GT", "RE", "TG", "QD", "FS",
"JW", "HU", "VI", "AN", "OB",
"ER", "FS", "LY", "PC", "ZM"];
IO.Console->Print("\"\": ")->PrintLine(CanMakeWord("", blocks));
IO.Console->Print("A: ")->PrintLine(CanMakeWord("A", blocks));
IO.Console->Print("BARK: ")->PrintLine(CanMakeWord("BARK", blocks));
IO.Console->Print("book: ")->PrintLine(CanMakeWord("book", blocks));
IO.Console->Print("treat: ")->PrintLine(CanMakeWord("treat", blocks));
IO.Console->Print("COMMON: ")->PrintLine(CanMakeWord("COMMON", blocks));
IO.Console->Print("SQuAd: ")->PrintLine(CanMakeWord("SQuAd", blocks));
IO.Console->Print("CONFUSE: ")->PrintLine(CanMakeWord("CONFUSE", blocks));
}
function : CanMakeWord(word : String, blocks : String[]) ~ Bool {
if(word->Size() = 0) {
return true;
};
c := word->Get(0)->ToUpper();
for(i := 0; i < blocks->Size(); i++;) {
b := blocks[i];
if(<>(b->Get(0)->ToUpper() <> c & b->Get(1)->ToUpper() <> c)) {
Swap(0, i, blocks);
new_word := word->SubString(1, word->Size() - 1);
new_blocks := String->New[blocks->Size() - 1];
Runtime->Copy(new_blocks, 0, blocks, 1, blocks->Size() - 1);
if(CanMakeWord(new_word, new_blocks)) {
return true;
};
Swap(0, i, blocks);
};
};
return false;
}
function : native : Swap(i : Int, j : Int, arr : String[]) ~ Nil {
tmp := arr[i];
arr[i] := arr[j];
arr[j] := tmp;
}
} |
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.
| #Perl | Perl | use strict;
use warnings;
use feature 'say';
use List::Util 'shuffle';
sub simulation {
my($population,$trials,$strategy) = @_;
my $optimal = $strategy =~ /^o/i ? 1 : 0;
my @prisoners = 0..$population-1;
my $half = int $population / 2;
my $pardoned = 0;
for (1..$trials) {
my @drawers = shuffle @prisoners;
my $total = 0;
for my $prisoner (@prisoners) {
my $found = 0;
if ($optimal) {
my $card = $drawers[$prisoner];
if ($card == $prisoner) {
$found = 1;
} else {
for (1..$half-1) {
$card = $drawers[$card];
($found = 1, last) if $card == $prisoner
}
}
} else {
for my $card ( (shuffle @drawers)[0..$half]) {
($found = 1, last) if $card == $prisoner
}
}
last unless $found;
$total++;
}
$pardoned++ if $total == $population;
}
$pardoned / $trials * 100
}
my $population = 100;
my $trials = 10000;
say " Simulation count: $trials\n" .
(sprintf " Random strategy pardons: %6.3f%% of simulations\n", simulation $population, $trials, 'random' ) .
(sprintf "Optimal strategy pardons: %6.3f%% of simulations\n", simulation $population, $trials, 'optimal');
$population = 10;
$trials = 100000;
say " Simulation count: $trials\n" .
(sprintf " Random strategy pardons: %6.3f%% of simulations\n", simulation $population, $trials, 'random' ) .
(sprintf "Optimal strategy pardons: %6.3f%% of simulations\n", simulation $population, $trials, 'optimal'); |
http://rosettacode.org/wiki/24_game/Solve | 24 game/Solve | task
Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the 24 game.
Show examples of solutions generated by the program.
Related task
Arithmetic Evaluator
| #Rust | Rust | #[derive(Clone, Copy, Debug)]
enum Operator {
Sub,
Plus,
Mul,
Div,
}
#[derive(Clone, Debug)]
struct Factor {
content: String,
value: i32,
}
fn apply(op: Operator, left: &[Factor], right: &[Factor]) -> Vec<Factor> {
let mut ret = Vec::new();
for l in left.iter() {
for r in right.iter() {
use Operator::*;
ret.push(match op {
Sub if l.value > r.value => Factor {
content: format!("({} - {})", l.content, r.content),
value: l.value - r.value,
},
Plus => Factor {
content: format!("({} + {})", l.content, r.content),
value: l.value + r.value,
},
Mul => Factor {
content: format!("({} x {})", l.content, r.content),
value: l.value * r.value,
},
Div if l.value >= r.value && r.value > 0 && l.value % r.value == 0 => Factor {
content: format!("({} / {})", l.content, r.content),
value: l.value / r.value,
},
_ => continue,
})
}
}
ret
}
fn calc(op: [Operator; 3], numbers: [i32; 4]) -> Vec<Factor> {
fn calc(op: &[Operator], numbers: &[i32], acc: &[Factor]) -> Vec<Factor> {
use Operator::*;
if op.is_empty() {
return Vec::from(acc)
}
let mut ret = Vec::new();
let mono_factor = [Factor {
content: numbers[0].to_string(),
value: numbers[0],
}];
match op[0] {
Mul => ret.extend_from_slice(&apply(op[0], acc, &mono_factor)),
Div => {
ret.extend_from_slice(&apply(op[0], acc, &mono_factor));
ret.extend_from_slice(&apply(op[0], &mono_factor, acc));
},
Sub => {
ret.extend_from_slice(&apply(op[0], acc, &mono_factor));
ret.extend_from_slice(&apply(op[0], &mono_factor, acc));
},
Plus => ret.extend_from_slice(&apply(op[0], acc, &mono_factor)),
}
calc(&op[1..], &numbers[1..], &ret)
}
calc(&op, &numbers[1..], &[Factor { content: numbers[0].to_string(), value: numbers[0] }])
}
fn solutions(numbers: [i32; 4]) -> Vec<Factor> {
use std::collections::hash_set::HashSet;
let mut ret = Vec::new();
let mut hash_set = HashSet::new();
for ops in OpIter(0) {
for o in orders().iter() {
let numbers = apply_order(numbers, o);
let r = calc(ops, numbers);
ret.extend(r.into_iter().filter(|&Factor { value, ref content }| value == 24 && hash_set.insert(content.to_owned())))
}
}
ret
}
fn main() {
let mut numbers = Vec::new();
if let Some(input) = std::env::args().skip(1).next() {
for c in input.chars() {
if let Ok(n) = c.to_string().parse() {
numbers.push(n)
}
if numbers.len() == 4 {
let numbers = [numbers[0], numbers[1], numbers[2], numbers[3]];
let solutions = solutions(numbers);
let len = solutions.len();
if len == 0 {
println!("no solution for {}, {}, {}, {}", numbers[0], numbers[1], numbers[2], numbers[3]);
return
}
println!("solutions for {}, {}, {}, {}", numbers[0], numbers[1], numbers[2], numbers[3]);
for s in solutions {
println!("{}", s.content)
}
println!("{} solutions found", len);
return
}
}
} else {
println!("empty input")
}
}
struct OpIter (usize);
impl Iterator for OpIter {
type Item = [Operator; 3];
fn next(&mut self) -> Option<[Operator; 3]> {
use Operator::*;
const OPTIONS: [Operator; 4] = [Mul, Sub, Plus, Div];
if self.0 >= 1 << 6 {
return None
}
let f1 = OPTIONS[(self.0 & (3 << 4)) >> 4];
let f2 = OPTIONS[(self.0 & (3 << 2)) >> 2];
let f3 = OPTIONS[(self.0 & (3 << 0)) >> 0];
self.0 += 1;
Some([f1, f2, f3])
}
}
fn orders() -> [[usize; 4]; 24] {
[
[0, 1, 2, 3],
[0, 1, 3, 2],
[0, 2, 1, 3],
[0, 2, 3, 1],
[0, 3, 1, 2],
[0, 3, 2, 1],
[1, 0, 2, 3],
[1, 0, 3, 2],
[1, 2, 0, 3],
[1, 2, 3, 0],
[1, 3, 0, 2],
[1, 3, 2, 0],
[2, 0, 1, 3],
[2, 0, 3, 1],
[2, 1, 0, 3],
[2, 1, 3, 0],
[2, 3, 0, 1],
[2, 3, 1, 0],
[3, 0, 1, 2],
[3, 0, 2, 1],
[3, 1, 0, 2],
[3, 1, 2, 0],
[3, 2, 0, 1],
[3, 2, 1, 0]
]
}
fn apply_order(numbers: [i32; 4], order: &[usize; 4]) -> [i32; 4] {
[numbers[order[0]], numbers[order[1]], numbers[order[2]], numbers[order[3]]]
}
|
http://rosettacode.org/wiki/15_puzzle_game | 15 puzzle game |
Task
Implement the Fifteen Puzzle Game.
The 15-puzzle is also known as:
Fifteen Puzzle
Gem Puzzle
Boss Puzzle
Game of Fifteen
Mystic Square
14-15 Puzzle
and some others.
Related Tasks
15 Puzzle Solver
16 Puzzle Game
| #Kotlin | Kotlin | // version 1.1.3
import java.awt.BorderLayout
import java.awt.Color
import java.awt.Dimension
import java.awt.Font
import java.awt.Graphics
import java.awt.Graphics2D
import java.awt.RenderingHints
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
import java.util.Random
import javax.swing.JFrame
import javax.swing.JPanel
import javax.swing.SwingUtilities
class FifteenPuzzle(dim: Int, val margin: Int) : JPanel() {
private val rand = Random()
private val tiles = IntArray(16)
private val tileSize = (dim - 2 * margin) / 4
private val gridSize = tileSize * 4
private var blankPos = 0
init {
preferredSize = Dimension(dim, dim)
background = Color.white
val cornflowerBlue = 0x6495ED
foreground = Color(cornflowerBlue)
font = Font("SansSerif", Font.BOLD, 60)
addMouseListener(object : MouseAdapter() {
override fun mousePressed(e: MouseEvent) {
val ex = e.x - margin
val ey = e.y - margin
if (ex !in 0..gridSize || ey !in 0..gridSize) return
val c1 = ex / tileSize
val r1 = ey / tileSize
val c2 = blankPos % 4
val r2 = blankPos / 4
if ((c1 == c2 && Math.abs(r1 - r2) == 1) ||
(r1 == r2 && Math.abs(c1 - c2) == 1)) {
val clickPos = r1 * 4 + c1
tiles[blankPos] = tiles[clickPos]
tiles[clickPos] = 0
blankPos = clickPos
}
repaint()
}
})
shuffle()
}
private fun shuffle() {
do {
reset()
// don't include the blank space in the shuffle,
// leave it in the home position
var n = 15
while (n > 1) {
val r = rand.nextInt(n--)
val tmp = tiles[r]
tiles[r] = tiles[n]
tiles[n] = tmp
}
} while (!isSolvable())
}
private fun reset() {
for (i in 0 until tiles.size) {
tiles[i] = (i + 1) % tiles.size
}
blankPos = 15
}
/* 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.
*/
private fun isSolvable(): Boolean {
var countInversions = 0
for (i in 0 until 15) {
(0 until i)
.filter { tiles[it] > tiles[i] }
.forEach { countInversions++ }
}
return countInversions % 2 == 0
}
private fun drawGrid(g: Graphics2D) {
for (i in 0 until tiles.size) {
if (tiles[i] == 0) continue
val r = i / 4
val c = i % 4
val x = margin + c * tileSize
val y = margin + r * tileSize
with(g) {
color = foreground
fillRoundRect(x, y, tileSize, tileSize, 25, 25)
color = Color.black
drawRoundRect(x, y, tileSize, tileSize, 25, 25)
color = Color.white
}
drawCenteredString(g, tiles[i].toString(), x, y)
}
}
private fun drawCenteredString(g: Graphics2D, s: String, x: Int, y: Int) {
val fm = g.fontMetrics
val asc = fm.ascent
val des = fm.descent
val xx = x + (tileSize - fm.stringWidth(s)) / 2
val yy = y + (asc + (tileSize - (asc + des)) / 2)
g.drawString(s, xx, yy)
}
override fun paintComponent(gg: Graphics) {
super.paintComponent(gg)
val g = gg as Graphics2D
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON)
drawGrid(g)
}
}
fun main(args: Array<String>) {
SwingUtilities.invokeLater {
val f = JFrame()
with(f) {
defaultCloseOperation = JFrame.EXIT_ON_CLOSE
title = "Fifteen Puzzle"
isResizable = false
add(FifteenPuzzle(640, 80), BorderLayout.CENTER)
pack()
setLocationRelativeTo(null)
isVisible = true
}
}
} |
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.
| #MATLAB | MATLAB | function field = puzzle2048(field)
if nargin < 1 || isempty(field)
field = zeros(4);
field = addTile(field);
end
clc
rng('shuffle')
while true
oldField = field;
clc
score = displayField(field);
% check losing condition
if isGameLost(field)
sprintf('You lose with a score of %g.',score)
return
end
direction = input('Which direction? (w,a,s,d) (x for exit)\n','s');
switch direction
case 'w'
field = moveUp(field);
case 'a'
field = rot90( moveUp( rot90(field,-1) ) );
case 's'
field = flipud( moveUp( flipud(field) ) );
case 'd'
field = rot90( moveUp( rot90(field) ), -1);
case 'x'
return
end
if any(field>=2048,'all')
disp('You win!')
return
end
if ~all(field==oldField,'all')
field = addTile(field);
end
end
end
function gameIsLost = isGameLost(field)
if all(field,'all') && ...
all(conv2(field,[1, -1],'same'),'all') && ...
all(conv2(field,[1; -1],'same'),'all')
gameIsLost = true;
else
gameIsLost = false;
end
end
function field = addTile(field)
freeIndices = find(~field);
newIndex = freeIndices( randi(length(freeIndices)) );
newNumber = 2 + 2 * (rand < 0.1);
field(newIndex) = newNumber;
end
function score = displayField(field)
% Unicode characters for box drawings
% 9484: U+250C Box Drawings Light Down and Right
% 9472: U+2500 Box Drawings Light Horizontal
% 9474: U+2502 Box Drawings Light Vertical
% 9488: U+2510 Box Drawings Light Down and Left
% 9492: U+2515 Box Drawings Light Up and Right
% 9496: U+2518 Box Drawings Light Up and Left
% 9500: U+251C Box Drawings Light Vertical and Right
% 9508: U+2524 Box Drawings Light Vertical and Left
% 9516: U+252C Box Drawings Light Down and Horizontal
% 9524: U+2534 Box Drawings Light Up and Horizontal
% 9532: U+253C Box Drawings Light Vertical and Horizontal
score = sum(field(:));
cellField = arrayfun(@num2str, field, 'UniformOutput', false);
cellField = cellfun(@(x) [ char(9474) blanks(5-length(x)) x ' ' ], ...
cellField, 'UniformOutput', false);
topRow = repmat('-',1,7*size(field,2)+1);
topRow(1:7:end) = char(9516);
topRow([1 end]) = [ char(9484) char(9488) ];
midRow = topRow;
midRow(1:7:end) = char(9532);
midRow([1 end]) = [ char(9500) char(9508) ];
botRow = topRow;
botRow(1:7:end) = char(9524);
botRow([1 end]) = [ char(9492) char(9496) ];
charField = topRow;
for iRow = cellField'
charField = [ charField; iRow{:} char(9474); midRow ];
end
charField(end,:) = botRow;
charField(charField == '0') = ' ';
disp(charField)
fprintf('\nYour score: %g\n', score)
end
function field = moveUp(field)
for iCol = 1:size(field,2)
col = field(:,iCol);
col = removeZeros(col);
for iRow = 1:length(col)-1
if col(iRow)==col(iRow+1)
col(iRow:iRow+1) = [ 2*col(iRow); 0 ];
end
end
col = removeZeros(col);
if length(col) < length(field)
col(end+1:length(field)) = 0;
end
field(:,iCol) = col;
end
end
function vector = removeZeros(vector)
vector(vector==0) = [];
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
| #Brat | Brat | 99.to 2 { n |
p "#{n} bottles of beer on the wall, #{n} bottles of beer!"
p "Take one down, pass it around, #{n - 1} bottle#{true? n > 2 's' ''} of beer on the wall."
}
p "One bottle of beer on the wall, one bottle of beer!"
p "Take one down, pass it around, no more bottles of beer on the wall." |
http://rosettacode.org/wiki/24_game | 24 game | The 24 Game tests one's mental arithmetic.
Task
Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed.
The program should prompt for the player to enter an arithmetic expression using just those, and all of those four digits, used exactly once each. 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.
| #MATLAB_.2F_Octave | MATLAB / Octave | function twentyfour()
N = 4;
n = ceil(rand(1,N)*9);
printf('Generate a equation with the numbers %i, %i, %i, %i and +, -, *, /, () operators ! \n',n);
s = input(': ','s');
t = s;
for k = 1:N,
[x,t] = strtok(t,'+-*/() \t');
if length(x)~=1,
error('invalid sign %s\n',x);
end;
y = x-'0';
if ~(0 < y & y < 10)
error('invalid sign %s\n',x);
end;
z(1,k) = y;
end;
if any(sort(z)-sort(n))
error('numbers do not match.\n');
end;
val = eval(s);
if val==24,
fprintf('expression "%s" results in %i.\n',s,val);
else
fprintf('expression "%s" does not result in 24 but %i.\n',s,val);
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
| #ERRE | ERRE |
PROGRAM SUM2
BEGIN
LOOP
INPUT(LINE,Q$)
EXIT IF Q$=""
SP%=INSTR(Q$," ")
PRINT(VAL(LEFT$(Q$,SP%-1))+VAL(MID$(Q$,SP%+1)))
END LOOP
END PROGRAM
|
http://rosettacode.org/wiki/ABC_problem | ABC problem | ABC problem
You are encouraged to solve this task according to the task description, using any language you may know.
You are given a collection of ABC blocks (maybe like the ones you had when you were a kid).
There are twenty blocks with two letters on each block.
A complete alphabet is guaranteed amongst all 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
| #OCaml | OCaml | let blocks = [
('B', 'O'); ('X', 'K'); ('D', 'Q'); ('C', 'P');
('N', 'A'); ('G', 'T'); ('R', 'E'); ('T', 'G');
('Q', 'D'); ('F', 'S'); ('J', 'W'); ('H', 'U');
('V', 'I'); ('A', 'N'); ('O', 'B'); ('E', 'R');
('F', 'S'); ('L', 'Y'); ('P', 'C'); ('Z', 'M');
]
let find_letter blocks c =
let found, remaining =
List.partition (fun (c1, c2) -> c1 = c || c2 = c) blocks
in
match found with
| _ :: res -> Some (res @ remaining)
| _ -> None
let can_make_word w =
let n = String.length w in
let rec aux i _blocks =
if i >= n then true else
match find_letter _blocks w.[i] with
| None -> false
| Some rem_blocks ->
aux (succ i) rem_blocks
in
aux 0 blocks
let test label f (word, should) =
Printf.printf "- %s %S = %B (should: %B)\n" label word (f word) should
let () =
List.iter (test "can make word" can_make_word) [
"A", true;
"BARK", true;
"BOOK", false;
"TREAT", true;
"COMMON", false;
"SQUAD", true;
"CONFUSE", 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.
| #PicoLisp | PicoLisp | (de shuffle (Lst)
(by '(NIL (rand)) sort Lst) )
# Extend this class with a `next-guess>` method and a `str>` method.
(class +Strategy +Entity)
(dm prev-drawer> (Num)
(=: prev Num) )
(class +Random +Strategy)
(dm T (Prisoner)
(=: guesses (nth (shuffle (range 1 100)) 51)) )
(dm next-guess> ()
(pop (:: guesses)) )
(dm str> ()
"Random" )
(class +Optimal +Strategy)
(dm T (Prisoner)
(=: prisoner-id Prisoner) )
(dm next-guess> ()
(or (: prev) (: prisoner-id)) )
(dm str> ()
"Optimal/Wikipedia" )
(de test-strategy (Strategy)
"Simulate one round of 100 prisoners who use `Strategy`"
(let Drawers (shuffle (range 1 100))
(for Prisoner (range 1 100)
(NIL # Break and return NIL if any prisoner fails their test.
(let Strat (new (list Strategy) Prisoner)
(do 50 # Try 50 iterations of `Strat`. Break and return T iff success.
(T (= Prisoner (prev-drawer> Strat (get Drawers (next-guess> Strat))))
T ) ) ) )
T ) ) )
(de test-strategy-n-times (Strategy N)
"Simulate `N` rounds of 100 prisoners who use `Strategy`"
(let Successes 0
(do N
(when (test-strategy Strategy)
(inc 'Successes) ) )
(prinl "We have a " (/ (* 100 Successes) N) "% success rate with " N " trials.")
(prinl "This is using the " (str> Strategy) " strategy.") ) ) |
http://rosettacode.org/wiki/24_game/Solve | 24 game/Solve | task
Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the 24 game.
Show examples of solutions generated by the program.
Related task
Arithmetic Evaluator
| #Scala | Scala | def permute(l: List[Double]): List[List[Double]] = l match {
case Nil => List(Nil)
case x :: xs =>
for {
ys <- permute(xs)
position <- 0 to ys.length
(left, right) = ys splitAt position
} yield left ::: (x :: right)
}
def computeAllOperations(l: List[Double]): List[(Double,String)] = l match {
case Nil => Nil
case x :: Nil => List((x, "%1.0f" format x))
case x :: xs =>
for {
(y, ops) <- computeAllOperations(xs)
(z, op) <-
if (y == 0)
List((x*y, "*"), (x+y, "+"), (x-y, "-"))
else
List((x*y, "*"), (x/y, "/"), (x+y, "+"), (x-y, "-"))
} yield (z, "(%1.0f%s%s)" format (x,op,ops))
}
def hasSolution(l: List[Double]) = permute(l) flatMap computeAllOperations filter (_._1 == 24) map (_._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
| #Liberty_BASIC | Liberty BASIC |
' 15-PUZZLE GAME
' ********************************
dim d(16)
dim ds$(16) ' Board pieces
dim sh(3)
call buildBoard introAndLevel()
call printPuzzle
do
print "To move a piece, enter its number: "
input x
while isMoveValid(x, y, z) = 0
print "Wrong move."
call printPuzzle
print "To move a piece, enter its number: "
input x
wend
d(z) = x
d(y) = 0
call printPuzzle
loop until isPuzzleComplete()
print "YOU WON!"
end
sub printPuzzle
for p = 1 to 16
if d(p) = 0 then
ds$(p) = " "
else
ds$(p) = using("###", d(p)) + " "
end if
next p
print "+-----+-----+-----+-----+"
print "|"; ds$(1); "|"; ds$(2); "|"; ds$(3); "|"; ds$(4); "|"
print "+-----+-----+-----+-----+"
print "|"; ds$(5); "|"; ds$(6); "|"; ds$(7); "|"; ds$(8); "|"
print "+-----+-----+-----+-----+"
print "|"; ds$(9); "|"; ds$(10); "|";ds$(11); "|"; ds$(12); "|"
print "+-----+-----+-----+-----+"
print "|"; ds$(13); "|"; ds$(14); "|"; ds$(15); "|"; ds$(16); "|"
print "+-----+-----+-----+-----+"
end sub
function introAndLevel()
cls
sh(1) = 10
sh(2) = 50
sh(3) = 100
print "15 PUZZLE GAME"
print
print
print "Please enter level of difficulty,"
do
print "1 (easy), 2 (medium) or 3 (hard): ";
input level
loop while (level < 1) or (level > 3)
introAndLevel = level
end function
sub buildBoard level
' Set pieces in correct order first
for p = 1 to 15
d(p) = p
next p
d(16) = 0 ' 0 = empty piece/slot
z = 16 ' z = empty position
print
print "Shuffling pieces";
for n = 1 to sh(level)
print ".";
do
x = int(rnd(0) * 4) + 1
select case x
case 1
r = z - 4
case 2
r = z + 4
case 3
if (z - 1) mod 4 <> 0 then
r = z - 1
end if
case 4
if z mod 4 <> 0 then
r = z + 1
end if
end select
loop while (r < 1) or (r > 16)
d(z) = d(r)
z = r
d(z) = 0
next n
cls
end sub
function isMoveValid(piece, byref piecePos, byref emptyPos)
mv = 0
if (piece >= 1) and (piece <= 15) then
piecePos = piecePosition(piece)
emptyPos = piecePosition(0)
' Check if empty piece is above, below, left or right to piece
if (piecePos - 4 = emptyPos) or _
(piecePos + 4 = emptyPos) or _
((piecePos - 1 = emptyPos) and (emptyPos mod 4 <> 0)) or _
((piecePos + 1 = emptyPos) and (piecePos mod 4 <> 0)) then
mv = 1
end if
end if
isMoveValid = mv
end function
function piecePosition(piece)
p = 1
while d(p) <> piece
p = p + 1
if p > 16 then
print "UH OH!"
stop
end if
wend
piecePosition = p
end function
function isPuzzleComplete()
pc = 0
p = 1
while (p < 16) and (d(p) = p)
p = p + 1
wend
if p = 16 then
pc = 1
end if
isPuzzleComplete = pc
end function
|
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.
| #Nim | Nim | import random, strutils, terminal
const
BoardLength = 4
BoardSize = BoardLength * BoardLength
Target = 2048
type
Operation = enum
opInvalid
opUp
opDown
opLeft
opRight
opQuit
opRestart
Board = object
len: Natural
largestNumber: Natural
score: Natural
rows: array[BoardLength, array[BoardLength, Natural]]
func handleKey(c: char): Operation =
case c
of 'w', 'W': opUp
of 'a', 'A': opLeft
of 's', 'S': opDown
of 'd', 'D': opRight
of 'q', 'Q': opQuit
of 'r', 'R': opRestart
else: opInvalid
proc getKey(): Operation =
var c = getch()
if c == '\e':
c = getch()
if c == '[':
case getch()
of 'A': opUp
of 'D': opLeft
of 'B': opDown
of 'C': opRight
else: opInvalid
else: handleKey c
else: handleKey c
proc spawnRandom(b: var Board) =
if b.len < BoardSize:
var
x = rand 0..<BoardLength
y = rand 0..<BoardLength
while b.rows[y][x] != 0:
x = rand 0..<BoardLength
y = rand 0..<BoardLength
b.rows[y][x] = if rand(1.0) < 0.9: 2 else: 4
inc b.len
b.largestNumber = max(b.rows[y][x], b.largestNumber)
proc initBoard(): Board =
spawnRandom result
func `$`(b: Board): string =
result = "┌────┬────┬────┬────┐\n"
for idx, val in b.rows:
for v in val:
result.add "│"
result.add center(if v != 0: $v else: "", 4)
result.add "│\n"
if idx < high(b.rows):
result.add "├────┼────┼────┼────┤\n"
else:
result.add "└────┴────┴────┴────┘"
func shift(b: var Board; o: Operation; merge = true): bool =
const BoardRange = 0..<BoardLength
var
x = 0
y = 0
vecX: range[-1..1] = 0
vecY: range[-1..1] = 0
case o
of opUp:
vecY = 1
of opDown:
vecY = -1
y = BoardLength - 1
of opLeft: vecX = 1
of opRight:
vecX = -1
x = BoardLength - 1
else: return
let
startX = x
startY = y
while x in BoardRange and y in BoardRange:
while b.len < BoardSize and x in BoardRange and y in BoardRange:
let
nextX = x + vecX
nextY = y + vecY
prevX = x - vecX
prevY = y - vecY
if b.rows[y][x] == 0:
if nextX in BoardRange and nextY in BoardRange and
b.rows[nextY][nextX] != 0:
result = true
swap b.rows[y][x], b.rows[nextY][nextX]
if prevX in BoardRange and prevY in BoardRange:
x = prevX
y = prevY
continue
x = nextX
y = nextY
if merge:
x = if vecX != 0: startX else: x
y = if vecY != 0: startY else: y
while x in BoardRange and y in BoardRange:
let
nextX = x + vecX
nextY = y + vecY
if b.rows[y][x] != 0:
if nextX in BoardRange and nextY in BoardRange and
b.rows[nextY][nextX] == b.rows[y][x]:
result = true
b.rows[y][x] *= 2
b.largestNumber = max(b.rows[y][x], b.largestNumber)
b.score += b.rows[y][x]
b.rows[nextY][nextX] = 0
dec b.len
x = nextX
y = nextY
if vecX == 0:
inc x
y = startY
elif vecY == 0:
inc y
x = startX
if merge and result: discard b.shift(o, false)
func shiftable(b: Board): bool =
for row in 0..<BoardLength:
for col in 0..<BoardLength:
result = result or b.rows[row][col] == 0
if result: break
if row < BoardLength - 1:
result = result or b.rows[row][col] == b.rows[row + 1][col]
if col < BoardLength - 1:
result = result or b.rows[row][col] == b.rows[row][col + 1]
when isMainModule:
randomize()
var
board = initBoard()
highscore = 0
block gameLoop:
while true:
let gameover = not board.shiftable or board.largestNumber >= Target
echo board
highscore = max(highscore, board.score)
echo "Score = ", board.score, " Highscore = ", highscore
if not gameover:
echo "Press arrow keys or WASD to move, R to Restart, Q to Quit"
elif board.largestNumber >= Target:
echo "You win! Press R to Restart, Q to Quit"
else:
echo "Game over! Press R to Restart, Q to Quit"
while true:
let op = getKey()
case op
of opRestart:
board = initBoard()
break
of opQuit: break gameLoop
of opInvalid: continue
elif gameover: continue
else:
if board.shift op:
board.spawnRandom
break
for i in 1..BoardLength + 7:
eraseLine()
cursorUp() |
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
| #BQN | BQN | Pl ← {(𝕩≠1)/"s"}
{𝕨∾(@+10)∾𝕩}´{(•Fmt 𝕨)∾" "∾𝕩}´¨∾{
⟨
⟨𝕩,"bottle"∾(Pl 𝕩)∾" of beer on the wall"⟩
⟨𝕩,"bottle"∾(Pl 𝕩)∾" of beer"⟩
⟨"Take one down, pass it around"⟩
⟨𝕩-1,"bottle"∾(Pl 𝕩-1)∾" of beer on the wall"∾@+10⟩
⟩
}¨⌽1+↕99 |
http://rosettacode.org/wiki/24_game | 24 game | The 24 Game tests one's mental arithmetic.
Task
Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed.
The program should prompt for the player to enter an arithmetic expression using just those, and all of those four digits, used exactly once each. 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.
| #MiniScript | MiniScript | evalAddSub = function()
result = evalMultDiv
while true
if not tokens then return result
op = tokens[0]
if op != "+" and op != "-" then return result
tokens.pull // (discard operator)
rhs = evalMultDiv
if result == null or rhs == null then return null
if op == "+" then result = result + rhs
if op == "-" then result = result - rhs
end while
end function
evalMultDiv = function()
result = evalAtom
while true
if not tokens then return result
op = tokens[0]
if op != "*" and op != "/" then return result
tokens.pull // (discard operator)
rhs = evalAtom
if result == null or rhs == null then return null
if op == "*" then result = result * rhs
if op == "/" then result = result / rhs
end while
end function
evalAtom = function()
if tokens[0] == "(" then
tokens.pull
result = evalAddSub
if not tokens or tokens.pull != ")" then
print "Unbalanced parantheses"
return null
end if
return result
end if
num = val(tokens.pull)
idx = availableDigits.indexOf(num)
if idx == null then
print str(num) + " is not available"
return null
else
availableDigits.remove idx
end if
return num
end function
choices = []
for i in range(1, 4)
choices.push ceil(rnd*9)
end for
result = null
while result != 24
availableDigits = choices[0:] // (clones the list)
print "Using only the digits " + availableDigits + ","
tokens = input("enter an expression that comes to 24: ").replace(" ","").values
result = evalAddSub
if availableDigits then
print "You forgot to use: " + availableDigits
result = null
end if
if result != null then print "That equals " + result + "."
end while
print "Great job!" |
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
| #Euler_Math_Toolbox | Euler Math Toolbox |
>s=lineinput("Two numbers seperated by a blank");
Two numbers seperated by a blank? >4 5
>vs=strtokens(s)
4
5
>vs[1]()+vs[2]()
9
|
http://rosettacode.org/wiki/ABC_problem | ABC problem | ABC problem
You are encouraged to solve this task according to the task description, using any language you may know.
You are given a collection of ABC blocks (maybe like the ones you had when you were a kid).
There are twenty blocks with two letters on each block.
A complete alphabet is guaranteed amongst all 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
| #Oforth | Oforth | import: mapping
["BO","XK","DQ","CP","NA","GT","RE","TG","QD","FS","JW","HU","VI","AN","OB","ER","FS","LY","PC","ZM"]
const: ABCBlocks
: canMakeWord(w, blocks)
| i |
w empty? ifTrue: [ true return ]
blocks size loop: i [
w first >upper blocks at(i) include? ifFalse: [ continue ]
canMakeWord( w right( w size 1- ), blocks del(i, i) ) ifTrue: [ true return ]
]
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.
| #Phix | Phix | function play(integer prisoners, iterations, bool optimal)
sequence drawers = shuffle(tagset(prisoners))
integer pardoned = 0
bool found = false
for i=1 to iterations do
drawers = shuffle(drawers)
for prisoner=1 to prisoners do
found = false
integer drawer = iff(optimal?prisoner:rand(prisoners))
for j=1 to prisoners/2 do
drawer = drawers[drawer]
if drawer==prisoner then found = true exit end if
if not optimal then drawer = rand(prisoners) end if
end for
if not found then exit end if
end for
pardoned += found
end for
return 100*pardoned/iterations
end function
constant iterations = 100_000
printf(1,"Simulation count: %d\n",iterations)
for prisoners=10 to 100 by 90 do
atom random = play(prisoners,iterations,false),
optimal = play(prisoners,iterations,true)
printf(1,"Prisoners:%d, random:%g, optimal:%g\n",{prisoners,random,optimal})
end for
|
http://rosettacode.org/wiki/24_game/Solve | 24 game/Solve | task
Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the 24 game.
Show examples of solutions generated by the program.
Related task
Arithmetic Evaluator
| #Scheme | Scheme |
#!r6rs
(import (rnrs)
(rnrs eval)
(only (srfi :1 lists) append-map delete-duplicates iota))
(define (map* fn . lis)
(if (null? lis)
(list (fn))
(append-map (lambda (x)
(apply map*
(lambda xs (apply fn x xs))
(cdr lis)))
(car lis))))
(define (insert x li n)
(if (= n 0)
(cons x li)
(cons (car li) (insert x (cdr li) (- n 1)))))
(define (permutations li)
(if (null? li)
(list ())
(map* insert (list (car li)) (permutations (cdr li)) (iota (length li)))))
(define (evaluates-to-24 expr)
(guard (e ((assertion-violation? e) #f))
(= 24 (eval expr (environment '(rnrs base))))))
(define (tree n o0 o1 o2 xs)
(list-ref
(list
`(,o0 (,o1 (,o2 ,(car xs) ,(cadr xs)) ,(caddr xs)) ,(cadddr xs))
`(,o0 (,o1 (,o2 ,(car xs) ,(cadr xs)) ,(caddr xs)) ,(cadddr xs))
`(,o0 (,o1 ,(car xs) (,o2 ,(cadr xs) ,(caddr xs))) ,(cadddr xs))
`(,o0 (,o1 ,(car xs) ,(cadr xs)) (,o2 ,(caddr xs) ,(cadddr xs)))
`(,o0 ,(car xs) (,o1 (,o2 ,(cadr xs) ,(caddr xs)) ,(cadddr xs)))
`(,o0 ,(car xs) (,o1 ,(cadr xs) (,o2 ,(caddr xs) ,(cadddr xs)))))
n))
(define (solve a b c d)
(define ops '(+ - * /))
(define perms (delete-duplicates (permutations (list a b c d))))
(delete-duplicates
(filter evaluates-to-24
(map* tree (iota 6) ops ops ops perms))))
|
http://rosettacode.org/wiki/15_puzzle_game | 15 puzzle game |
Task
Implement the Fifteen Puzzle Game.
The 15-puzzle is also known as:
Fifteen Puzzle
Gem Puzzle
Boss Puzzle
Game of Fifteen
Mystic Square
14-15 Puzzle
and some others.
Related Tasks
15 Puzzle Solver
16 Puzzle Game
| #LiveCode | LiveCode |
#Please note that all this code can be performed in livecode with just few mouse clicks
#This is just a pure script exampe
on OpenStack
show me #Usually not necessary
#tile creation
set the width of the templateButton to 50
set the height of the templateButton to 50
repeat with i=1 to 16
create button
set the label of button i to i
if i =1 then
set the top of button 1 to 0
set the left of button 1 to 0
end if
if i > 1 and 1 <=4 then
set the left of button i to the right of button (i-1)
set the top of button i to the top of button 1
end if
if i >= 5 and i <= 8 then
set the top of button i to the bottom of button 1
if i = 5 then
set the left of button i to the left of button 1
else
set the left of button i to the right of button (i - 1)
end if
end if
if i >= 9 and i <= 12 then
set the top of button i to the bottom of button 5
if i = 9 then
set the left of button i to the left of button 1
else
set the left of button i to the right of button (i - 1)
end if
end if
if i >= 13 and i <= 16 then
set the top of button i to the bottom of button 9
if i = 13 then
set the left of button i to the left of button 1
else
set the left of button i to the right of button (i - 1)
end if
end if
#this is usally the script directly wirtten in the objects, it's really weird this way
put "on MouseUp" &CR& "if checkDistance(the label of me) then" & CR &"put the loc of me into temp" into ts
put CR& "set the loc of me to the loc of button 16" after ts
put CR& "set the loc of button 16 to temp" & Cr & "end if " &CR &"End MouseUp" after ts
set the script of button i to ts
end repeat
#graphic adjustements
set the visible of button 16 to false
set the width of this stack to the right of button 16
set the height of this stack to the bottom of button 16
end openStack
function checkDistance i
if (((the top of button i - the bottom of button 16) = 0 OR (the top of button 16 - the bottom of button i) = 0) AND the left of button i = the left of button 16) OR (((the left of button i - the right of button 16) = 0 OR (the right of button i - the left of button 16) = 0) AND the top of button i = the top of button 16) then
return true
else
return false
end if
end checkDistance
|
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.
| #OCaml | OCaml |
let list_make x v =
let rec aux acc i =
if i <= 0 then acc else aux (v::acc) (i-1)
in
aux [] x
let pad_right n line =
let len = List.length line in
let x = n - len in
line @ (list_make x 0)
let _move_left line =
let n = List.length line in
let line = List.filter ((<>) 0) line in
let rec aux acc = function
| x::y::tl ->
if x = y
then aux (x+y::acc) tl
else aux (x::acc) (y::tl)
| x::[] ->
aux (x::acc) []
| [] ->
List.rev acc
in
pad_right n (aux [] line)
let move_left grid =
List.map _move_left grid
let move_right grid =
grid
|> List.map List.rev
|> List.map _move_left
|> List.map List.rev
let rec replace g n v =
match g with
| x::xs -> if n = 0 then v::xs else x::(replace xs (n-1) v)
| [] -> raise (Invalid_argument "replace")
(* add a new value in a random cell containing zero *)
let rec new_value grid =
let zeros = ref [] in
List.iteri (fun y line ->
List.iteri (fun x v ->
if v = 0 then zeros := (x, y) :: !zeros
) line;
) grid;
let n = List.length !zeros in
if n = 0 then raise Exit;
let x, y = List.nth !zeros (Random.int n) in
let v = if Random.int 10 = 0 then 4 else 2 in
let line = List.nth grid y in
let new_line = replace line x v in
replace grid y new_line
(* turn counterclockwise *)
let turn_ccw grid =
let y = List.length grid in
let x = List.length (List.nth grid 0) in
List.init x (fun i ->
List.init y (fun j ->
List.nth (List.nth grid j) (x-i-1)
)
)
(* turn clockwise *)
let turn_cw grid =
let y = List.length grid in
let x = List.length (List.nth grid 0) in
List.init x (fun i ->
List.init y (fun j ->
List.nth (List.nth grid (y-j-1)) (i)
)
)
let move_up grid =
grid
|> turn_ccw
|> move_left
|> turn_cw
let move_down grid =
grid
|> turn_cw
|> move_left
|> turn_ccw
let display grid =
List.iter (fun line ->
print_string " [";
line
|> List.map (Printf.sprintf "%4d")
|> String.concat "; "
|> print_string;
print_endline "]"
) grid
let () =
Random.self_init ();
let width =
try int_of_string Sys.argv.(1)
with _ -> 4
in
let line = list_make width 0 in
let grid = list_make width line in
let grid = new_value grid in
let grid = new_value grid in
print_endline {|
s -> left
f -> right
e -> up
d -> down
q -> quit
|};
let rec loop grid =
display grid;
let grid =
match read_line () with
| "s" -> move_left grid
| "f" -> move_right grid
| "e" -> move_up grid
| "d" -> move_down grid
| "q" -> exit 0
| _ -> grid
in
let grid =
try new_value grid
with Exit ->
print_endline "Game Over";
exit 0
in
loop grid
in
loop grid |
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
| #C | C | /*
* 99 Bottles, C, KISS (i.e. keep it simple and straightforward) version
*/
#include <stdio.h>
int main(void)
{
int n;
for( n = 99; n > 2; n-- )
printf(
"%d bottles of beer on the wall, %d bottles of beer.\n"
"Take one down and pass it around, %d bottles of beer on the wall.\n\n",
n, n, n - 1);
printf(
"2 bottles of beer on the wall, 2 bottles of beer.\n"
"Take one down and pass it around, 1 bottle of beer on the wall.\n\n"
"1 bottle of beer on the wall, 1 bottle of beer.\n"
"Take one down and pass it around, no more bottles of beer on the wall.\n\n"
"No more bottles of beer on the wall, no more bottles of beer.\n"
"Go to the store and buy some more, 99 bottles of beer on the wall.\n");
return 0;
} |
http://rosettacode.org/wiki/24_game | 24 game | The 24 Game tests one's mental arithmetic.
Task
Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed.
The program should prompt for the player to enter an arithmetic expression using just those, and all of those four digits, used exactly once each. The program should check then evaluate the expression.
The goal is for the player to enter an expression that (numerically) evaluates to 24.
Only the following operators/functions are allowed: multiplication, division, addition, subtraction
Division should use floating point or rational arithmetic, etc, to preserve remainders.
Brackets are allowed, if using an infix expression evaluator.
Forming multiple digit numbers from the supplied digits is disallowed. (So an answer of 12+12 when given 1, 2, 2, and 1 is wrong).
The order of the digits when given does not have to be preserved.
Notes
The type of expression evaluator used is not mandated. An RPN evaluator is equally acceptable for example.
The task is not for the program to generate the expression, or test whether an expression is even possible.
Related tasks
24 game/Solve
Reference
The 24 Game on h2g2.
| #mIRC_Scripting_Language | mIRC Scripting Language | alias 24 {
dialog -m 24-Game 24-Game
}
dialog 24-Game {
title "24-Game"
size -1 -1 100 70
option dbu
text "", 1, 29 7 42 8
text "Equation", 2, 20 21 21 8
edit "", 3, 45 20 40 10
text "Status", 4, 10 34 80 8, center
button "Calculate", 5, 5 45 40 20
button "New", 6, 57 47 35 15
}
on *:DIALOG:24-Game:init:*: {
did -o 24-Game 1 1 Numbers: $rand(1,9) $rand(1,9) $rand(1,9) $rand(1,9)
}
on *:DIALOG:24-Game:sclick:*: {
if ($did == 5) {
if ($regex($did(3),/^[ (]*\d *[-+*/][ (]*\d[ ()]*[-+*/][ ()]*\d[ )]*[-+*/] *\d[ )]*$/)) && ($sorttok($regsubex($did(3),/[^\d]+/g,$chr(32)),32) == $sorttok($remove($did(1),Numbers:),32)) {
did -o 24-Game 4 1 $iif($calc($did(3)) == 24,Correct,Wrong)
}
else {
did -o 24-Game 4 1 Wrong Numbers or Syntax
}
}
elseif ($did == 6) {
did -o 24-Game 1 1 Numbers: $rand(1,9) $rand(1,9) $rand(1,9) $rand(1,9)
}
} |
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
| #Euphoria | Euphoria | include get.e
function snd(sequence s)
return s[2]
end function
integer a,b
a = snd(get(0))
b = snd(get(0))
printf(1," %d\n",a+b) |
http://rosettacode.org/wiki/ABC_problem | ABC problem | ABC problem
You are encouraged to solve this task according to the task description, using any language you may know.
You are given a collection of ABC blocks (maybe like the ones you had when you were a kid).
There are twenty blocks with two letters on each block.
A complete alphabet is guaranteed amongst all 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
| #OpenEdge.2FProgress | OpenEdge/Progress | FUNCTION canMakeWord RETURNS LOGICAL (INPUT pWord AS CHARACTER) FORWARD.
/* List of blocks */
DEFINE TEMP-TABLE ttBlocks NO-UNDO
FIELD ttFaces AS CHARACTER FORMAT "x(1)" EXTENT 2
FIELD ttUsed AS LOGICAL.
/* Fill in list of blocks */
RUN AddBlock("BO").
RUN AddBlock("XK").
RUN AddBlock("DQ").
RUN AddBlock("CP").
RUN AddBlock("NA").
RUN AddBlock("GT").
RUN AddBlock("Re").
RUN AddBlock("TG").
RUN AddBlock("QD").
RUN AddBlock("FS").
RUN AddBlock("JW").
RUN AddBlock("HU").
RUN AddBlock("VI").
RUN AddBlock("AN").
RUN AddBlock("OB").
RUN AddBlock("ER").
RUN AddBlock("FS").
RUN AddBlock("LY").
RUN AddBlock("PC").
RUN AddBlock("ZM").
DEFINE VARIABLE chWords AS CHARACTER EXTENT 7 NO-UNDO.
ASSIGN chWords[1] = "A"
chWords[2] = "BARK"
chWords[3] = "BOOK"
chWords[4] = "TREAT"
chWords[5] = "COMMON"
chWords[6] = "SQUAD"
chWords[7] = "CONFUSE".
DEFINE FRAME frmResult
WITH NO-LABELS 7 DOWN USE-TEXT.
DEFINE VARIABLE i AS INTEGER NO-UNDO.
DO i = 1 TO 7:
DISPLAY chWords[i] + " = " + STRING(canMakeWord(chWords[i])) FORMAT "x(25)" WITH FRAME frmResult.
DOWN WITH FRAME frmResult.
END.
PROCEDURE AddBlock:
DEFINE INPUT PARAMETER i-chBlockvalue AS CHARACTER NO-UNDO.
IF (LENGTH(i-chBlockValue) <> 2)
THEN RETURN ERROR.
CREATE ttBlocks.
ASSIGN ttBlocks.ttFaces[1] = SUBSTRING(i-chBlockValue, 1, 1)
ttBlocks.ttFaces[2] = SUBSTRING(i-chBlockValue, 2, 1).
END PROCEDURE.
FUNCTION blockInList RETURNS LOGICAL (pChar AS CHARACTER):
/* Find first unused block in list */
FIND FIRST ttBlocks WHERE (ttBlocks.ttFaces[1] = pChar
OR ttBlocks.ttFaces[2] = pChar)
AND NOT ttBlocks.ttUsed NO-ERROR.
IF (AVAILABLE ttBlocks) THEN DO:
/* found it! set to used and return true */
ASSIGN ttBlocks.ttUsed = TRUE.
RETURN TRUE.
END.
ELSE RETURN FALSE.
END FUNCTION.
FUNCTION canMakeWord RETURNS LOGICAL (INPUT pWord AS CHARACTER):
DEFINE VARIABLE i AS INTEGER NO-UNDO.
DEFINE VARIABLE chChar AS CHARACTER NO-UNDO.
/* Word has to be valid */
IF (LENGTH(pWord) = 0)
THEN RETURN FALSE.
DO i = 1 TO LENGTH(pWord):
/* get the char */
chChar = SUBSTRING(pWord, i, 1).
/* Check to see if this is a letter? */
IF ((ASC(chChar) < 65) OR (ASC(chChar) > 90) AND
(ASC(chChar) < 97) OR (ASC(chChar) > 122))
THEN RETURN FALSE.
/* Is block is list (and unused) */
IF NOT blockInList(chChar)
THEN RETURN FALSE.
END.
/* Reset all blocks */
FOR EACH ttBlocks:
ASSIGN ttUsed = FALSE.
END.
RETURN TRUE.
END FUNCTION.
|
http://rosettacode.org/wiki/100_prisoners | 100 prisoners |
The Problem
100 prisoners are individually numbered 1 to 100
A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside.
Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start.
Prisoners start outside the room
They can decide some strategy before any enter the room.
Prisoners enter the room one by one, can open a drawer, inspect the card number in the drawer, then close the drawer.
A prisoner can open no more than 50 drawers.
A prisoner tries to find his own number.
A prisoner finding his own number is then held apart from the others.
If all 100 prisoners find their own numbers then they will all be pardoned. If any don't then all sentences stand.
The task
Simulate several thousand instances of the game where the prisoners randomly open drawers
Simulate several thousand instances of the game where the prisoners use the optimal strategy mentioned in the Wikipedia article, of:
First opening the drawer whose outside number is his prisoner number.
If the card within has his number then he succeeds otherwise he opens the drawer with the same number as that of the revealed card. (until he opens his maximum).
Show and compare the computed probabilities of success for the two strategies, here, on this page.
References
The unbelievable solution to the 100 prisoner puzzle standupmaths (Video).
wp:100 prisoners problem
100 Prisoners Escape Puzzle DataGenetics.
Random permutation statistics#One hundred prisoners on Wikipedia.
| #Phixmonti | Phixmonti | /# Rosetta Code problem: http://rosettacode.org/wiki/100_prisoners
by Galileo, 05/2022 #/
include ..\Utilitys.pmt
def random rand * 1 + int enddef
def shuffle
len var l
l for var a
l random var b
b get var p
a get b set
p a set
endfor
enddef
def play var optimal var iterations var prisoners
0 var pardoned
( prisoners for endfor )
iterations for drop
shuffle
prisoners for var prisoner
false var found
optimal if prisoner else prisoners random endif
prisoners 2 / int for drop
get dup prisoner == if true var found exitfor
else
optimal not if drop prisoners random endif
endif
endfor
found not if exitfor endif
drop
endfor
pardoned found + var pardoned
endfor
drop
pardoned 100 * iterations /
enddef
"Please, be patient ..." ?
( "Optimal: " 100 10000 true play
" Random: " 100 10000 false play
" Prisoners: " prisoners ) lprint |
http://rosettacode.org/wiki/24_game/Solve | 24 game/Solve | task
Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the 24 game.
Show examples of solutions generated by the program.
Related task
Arithmetic Evaluator
| #Sidef | Sidef | var formats = [
'((%d %s %d) %s %d) %s %d',
'(%d %s (%d %s %d)) %s %d',
'(%d %s %d) %s (%d %s %d)',
'%d %s ((%d %s %d) %s %d)',
'%d %s (%d %s (%d %s %d))',
]
var op = %w( + - * / )
var operators = op.map { |a| op.map {|b| op.map {|c| "#{a} #{b} #{c}" } } }.flat
loop {
var input = read("Enter four integers or 'q' to exit: ", String)
input == 'q' && break
if (input !~ /^\h*[1-9]\h+[1-9]\h+[1-9]\h+[1-9]\h*$/) {
say "Invalid input!"
next
}
var n = input.split.map{.to_n}
var numbers = n.permutations
formats.each { |format|
numbers.each { |n|
operators.each { |operator|
var o = operator.split;
var str = (format % (n[0],o[0],n[1],o[1],n[2],o[2],n[3]))
eval(str) == 24 && say str
}
}
}
} |
http://rosettacode.org/wiki/15_puzzle_game | 15 puzzle game |
Task
Implement the Fifteen Puzzle Game.
The 15-puzzle is also known as:
Fifteen Puzzle
Gem Puzzle
Boss Puzzle
Game of Fifteen
Mystic Square
14-15 Puzzle
and some others.
Related Tasks
15 Puzzle Solver
16 Puzzle Game
| #Lua | Lua |
math.randomseed( os.time() )
local puz = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0 }
local dir = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } }
local sx, sy = 4, 4
function isValid( tx, ty )
return tx > 0 and tx < 5 and ty > 0 and ty < 5
end
function display()
io.write( "\n\n" )
for j = 1, 4 do
io.write( "+----+----+----+----+\n" )
for i = 1, 4 do
local d = puz[i + j * 4 - 4]
io.write( ": " )
if d < 10 then io.write( " " ) end
if d < 1 then
io.write( " " )
else
io.write( string.format( "%d ", d ) )
end
end
io.write( ":\n" )
end
io.write( "+----+----+----+----+\n\n" )
end
function getUserNove()
local moves, r, tx, ty = {}
for d = 1, 4 do
tx = sx; ty = sy
tx = tx + dir[d][1]; ty = ty + dir[d][2]
if isValid( tx, ty ) then
table.insert( moves, puz[tx + ty * 4 - 4] )
end
end
io.write( "Your possible moves are: " )
for i = 1, #moves do
io.write( string.format( "%d ", moves[i] ) )
end
io.write ( "\nYour move: " ); r = tonumber( io.read() )
if r ~= nil then
for i = 1, #moves do
if moves[i] == r then return r end
end
end
print( "Invalid move!" )
return -1
end
function checked( r )
for i = 1, #puz do
if puz[i] == r then
puz[i] = 0
sx = 1 + ( i - 1 ) % 4; sy = math.floor( ( i + 3 ) / 4 )
elseif puz[i] == 0 then
puz[i] = r
end
end
for i = 2, #puz - 1 do
if puz[i - 1] + 1 ~= puz[i] then return false end
end
return true
end
function beginGame()
local r, d, tx, ty
while( true ) do
for i = 1, 100 do
while( true ) do
tx = sx; ty = sy; d = math.random( 4 )
tx = tx + dir[d][1]; ty = ty + dir[d][2]
if isValid( tx, ty ) then break end
end
puz[sx + sy * 4 - 4] = puz[tx + ty * 4 - 4]
puz[tx + ty * 4 - 4] = 0; sx = tx; sy = ty
end
while( true ) do
display(); r = getUserNove()
if r > 0 then
if checked( r ) then
display()
io.write( "\nDone!\n\nPlay again (Y/N)?" )
r = io.read()
if r ~= "Y" and r ~= "y" then
return
else
break
end
end
end
end
end
end
-- [ entry point ] --
beginGame()
|
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.
| #Pascal | Pascal |
program game2048;
uses Crt;
const
SIZE_MAP = 4;
SIZETOPBOT = SIZE_MAP*6+6; (* Calculate the length of the top and bottom to create a box around the game *)
NOTHING = 0;
UP = 93;
RIGHT = 92;
LEFT = 91;
DOWN = 90;
type
type_vector = array [1..SIZE_MAP] of integer;
type_game = record
lin,col:integer;
map: array [1..SIZE_MAP,1..SIZE_MAP] of integer;
score:integer;
end;
type_coord = record
lin,col:integer;
end;
var
game:type_game;
end_game,movement:boolean;
procedure Create_Number(var game:type_game);
(* Create the number(2 or 4) in a random position on the map *)
(* The number 4 had a 10% of chance to be created *)
var
number:integer;
RanP:type_coord;
begin
randomize;
if random(9) = 1 then
number:=4
else
number:=2;
RanP.lin:=random(game.lin)+1;
RanP.col:=random(game.col)+1;
while game.map[RanP.lin,RanP.col] <> NOTHING do
begin
RanP.lin:=random(game.lin)+1;
RanP.col:=random(game.col)+1;
end;
game.map[RanP.lin,Ranp.Col]:=number;
end;
procedure initializing_game(var game:type_game);
var i,j:integer;
begin
game.lin:=SIZE_MAP;
game.col:=SIZE_MAP;
game.score:=0;
for i:=1 to game.lin do
for j:=1 to game.col do
game.map[i,j]:=NOTHING;
Create_Number(game);
Create_Number(game);
end;
function CountDigit(number:integer):integer;
begin
if number <> 0 then
begin
CountDigit:=0;
while number <> 0 do
begin
CountDigit:=CountDigit+1;
number:=number div 10;
end;
end
else
CountDigit:=1;
end;
procedure print_number(number:integer);
(* Print the number aligned with other numbers in the matrix *)
var k,hwdigit:integer;
begin
hwdigit:=CountDigit(number);
write(' ');
write(number);
(* The 4 is used to aling the numbers because the greatest number *)
(* possible is 2048, which have 4 digits *)
for k:=1 to 4-hwdigit do
write(' ');
write(' ');
end;
procedure print_line(lengthL:integer; ch:string);
var i:integer;
begin
write('+');
for i:=1 to (lengthL-2) do
begin
if i mod 7 = 0 then
write('+')
else
write(ch);
end;
writeln;
end;
procedure print_map(var game:type_game);
var i,j:integer;
begin
print_line(SIZETOPBOT,'-');
for i:=1 to game.lin do
begin
write('|');
for j:=1 to game.col do
if game.map[i,j] >= 0 then
begin
print_number(game.map[i,j]);
write('|');
end;
writeln;
print_line(SIZETOPBOT,'-');
end;
end;
function CanMove(var v_lin:type_vector; i:integer):integer;
(* Returns 1 if the next position is free *)
(* Returns 2 if the next position has an equal number *)
(* Returns 0 if the next position is not free *)
begin
if v_lin[i-1] = NOTHING then
CanMove:=1
else if v_lin[i] = v_lin[i-1] then
CanMove:=2
else
CanMove:=0;
end;
function MoveAndSum(var game:type_game; var v_lin:type_vector; size:integer):boolean;
(* Move and Sum the elements of the vector *)
(* The direction of the move is to the left *)
(* Returns TRUE if a number was moved *)
(* Returns FALSE if a number was not moved *)
var
i,e,ResultM:integer;
v:type_vector;
begin
MoveAndSum:=FALSE;
(* Initializing the vector *)
(* This Vector is to know what number sum and what not sum *)
for i:=1 to size do
v[i]:=0;
for i:=2 to size do
begin
if v_lin[i] <> 0 then
begin
(* Move the number in v_lin[i] to the left as much as possible *)
e:=i;
ResultM:=CanMove(v_lin,e);
while (ResultM <> 0)and(e>1) do
begin
case ResultM of
1:begin
v_lin[e-1]:=v_lin[e];
v_lin[e]:=NOTHING;
end;
2:begin
if v[e] = 0 then
begin
v_lin[e-1]:=v_lin[e-1]*2;
game.score:=game.score+v_lin[e-1];
v_lin[e]:=NOTHING;
(* This number will not be sum again *)
v[e-1]:=1;
end;
end;
end;
e:=e-1;
ResultM:=CanMove(v_lin,e);
end;
if e <> i then
MoveAndSum:=TRUE;
v[e-1]:=1;
end;
end;
end;
function move_left(var game:type_game):boolean;
var
i,j:integer;
v:type_vector;
begin
move_left:=FALSE;
for i:=1 to game.lin do
begin
for j:=1 to game.col do
v[j]:=game.map[i,j];
if MoveAndSum(game,v,game.lin) then
move_left:=TRUE;
for j:=1 to game.col do
game.map[i,j]:=v[j];
end;
end;
function move_right(var game:type_game):boolean;
var
i,j,k:integer;
v:type_vector;
begin
move_right:=FALSE;
for i:=1 to game.lin do
begin
(* The side which will be move had to be at the beginning of the vector *)
(* For example, I want to move this line to the right: 0 2 0 3 6 *)
(* The procedure "MoveAndSum" has to receive this vector: 6 3 0 2 0 *)
k:=1;
for j:=game.col downto 1 do
begin
v[k]:=game.map[i,j];
k:=k+1;
end;
if MoveAndSum(game,v,game.lin) then
move_right:=TRUE;
(* Copy to the right place in the matrix *)
k:=1;
for j:=game.col downto 1 do
begin
game.map[i,k]:=v[j];
k:=k+1;
end;
end;
end;
function move_down(var game:type_game):boolean;
var
i,j,k:integer;
v:type_vector;
begin
move_down:=FALSE;
for j:=1 to game.col do
begin
k:=1;
for i:=game.lin downto 1 do
begin
v[k]:=game.map[i,j];
k:=k+1;
end;
if MoveAndSum(game,v,game.lin) then
move_down:=TRUE;
k:=1;
for i:=game.lin downto 1 do
begin
game.map[k,j]:=v[i];
k:=k+1;
end;
end;
end;
function move_up(var game:type_game):boolean;
var
i,j:integer;
v:type_vector;
begin
move_up:=FALSE;
for j:=1 to game.col do
begin
for i:=1 to game.lin do
v[i]:=game.map[i,j];
if MoveAndSum(game,v,game.lin) then
move_up:=TRUE;
for i:=1 to game.lin do
game.map[i,j]:=v[i];
end;
end;
function CheckWinLose(var game:type_game):integer;
(* Returns 2 if the player win the game *)
(* Returns 1 if the player lose the game *)
(* Returns 0 if has a valid move*)
var i,j:integer;
begin
with game do
begin
CheckWinLose:=1;
i:=1;
while (i<=game.lin)and(CheckWinLose<>2) do
begin
j:=1;
while (j<=game.col)and(CheckWinLose<>2) do
begin
if map[i,j] = 2048 then
CheckWinLose:=2
else
if map[i,j] = NOTHING then
CheckWinLose:=0
else
if (map[i,j] = map[i,j+1])and(j<>col) then
CheckWinLose:=0
else
if (map[i,j] = map[i,j-1])and(j<>1) then
CheckWinLose:=0
else
if (map[i,j] = map[i+1,j])and(i<>lin) then
CheckWinLose:=0
else
if (map[i,j] = map[i-1,j])and(i<>1) then
CheckWinLose:=0;
j:=j+1;
end;
i:=i+1;
end;
end;
end;
begin
movement:=false;
end_game:=false;
initializing_game(game);
repeat
ClrScr;
if movement then
Create_Number(game);
movement:=false;
writeln('SCORE: ',game.score);
print_map(game);
writeln(' Use the arrow keys to move ');
writeln(' Press ESC to quit the game ');
case CheckWinLose(game) of
1:begin
print_line(SIZETOPBOT,'-');
writeln('| Game Over! |');
print_line(SIZETOPBOT,'-');
end_game:=TRUE;
end;
2:begin
print_line(SIZETOPBOT,'-');
writeln('| You Win! |');
print_line(SIZETOPBOT,'-');
end_game:=TRUE;
end;
end;
repeat
until KeyPressed;
case ReadKey of
#0:begin
case ReadKey of
#72:movement:=move_up(game);
#77:movement:=move_right(game);
#75:movement:=move_left(game);
#80:movement:=move_down(game);
end;
end;
#27:end_game:=true;
end;
until end_game;
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
| #C.23 | C# | using System;
class Program
{
static void Main(string[] args)
{
for (int i = 99; i > -1; i--)
{
if (i == 0)
{
Console.WriteLine("No more bottles of beer on the wall, no more bottles of beer.");
Console.WriteLine("Go to the store and buy some more, 99 bottles of beer on the wall.");
break;
}
if (i == 1)
{
Console.WriteLine("1 bottle of beer on the wall, 1 bottle of beer.");
Console.WriteLine("Take one down and pass it around, no more bottles of beer on the wall.");
Console.WriteLine();
}
else
{
Console.WriteLine("{0} bottles of beer on the wall, {0} bottles of beer.", i);
Console.WriteLine("Take one down and pass it around, {0} bottles of beer on the wall.", i - 1);
Console.WriteLine();
}
}
}
} |
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.
| #Modula-2 | Modula-2 | MODULE TwentyFour;
FROM InOut IMPORT WriteString, WriteLn, Write, ReadString, WriteInt;
FROM RandomGenerator IMPORT Random;
TYPE operator_t = (add, sub, mul, div);
expr_t = RECORD
operand : ARRAY[0..3] OF CARDINAL;
operator : ARRAY[1..3] OF operator_t;
END;(*of RECORD*)
numbers_t = SET OF CHAR;
VAR expr : expr_t;
numbers : numbers_t;
(*******************************************************************createExpr*)
(*analyse the input string *)
PROCEDURE createExpr(s: ARRAY OF CHAR);
VAR index, counter : INTEGER;
token : CHAR;
temp_expr : expr_t;
operand : CARDINAL;
operator : operator_t;
(************************************nextToken*)
(* returns the next CHAR that isn`t a space *)
PROCEDURE nextToken(): CHAR;
BEGIN
INC(index);
WHILE (s[index] = ' ') DO
INC(index);
END;(*of WHILE*)
RETURN(s[index]);
END nextToken;
(***********************************set_operand*)
(* checks if the CHAR o inerhits a valid number*)
(* and sets 'operand' to its value *)
PROCEDURE set_operand(o: CHAR);
BEGIN
CASE o OF
'0'..'9': IF o IN numbers THEN
operand := ORD(o)-48;
numbers := numbers - numbers_t{o};
ELSE
WriteString("ERROR: '");
Write( o);
WriteString( "' isn`t a available number ");
WriteLn;
HALT;
END;(*of IF*)|
0 : WriteString("ERROR: error in input ");
WriteLn;
HALT;
ELSE
WriteString("ERROR: '");
Write( o);
WriteString( "' isn`t a number ");
WriteLn;
HALT;
END;(*of CASE*)
END set_operand;
(**********************************set_operator*)
(* checks if the CHAR o inerhits a valid *)
(* operator and sets 'operator' to its value *)
PROCEDURE set_operator(o: CHAR);
BEGIN
CASE o OF
'+' : operator := add;|
'-' : operator := sub;|
'*' : operator := mul;|
'/' : operator := div;|
0 : WriteString("ERROR: error in input ");
WriteLn;
HALT;
ELSE
WriteString("ERROR: '");
Write( o);
WriteString( "' isn`t a operator ");
WriteLn;
HALT;
END;(*of CASE*)
END set_operator;
(************************************************)
BEGIN
index := -1;
token := nextToken();
set_operand(token);
expr.operand[0] := operand;
token := nextToken();
set_operator(token);
expr.operator[1] := operator;
token := nextToken();
set_operand(token);
expr.operand[1] := operand;
token := nextToken();
set_operator(token);
expr.operator[2] := operator;
token := nextToken();
set_operand(token);
expr.operand[2] := operand;
token := nextToken();
set_operator(token);
expr.operator[3] := operator;
token := nextToken();
set_operand(token);
expr.operand[3] := operand;
END createExpr;
(*****************************************************************evaluateExpr*)
(* evaluate the expresion that was createt by 'createExpr' *)
PROCEDURE evaluateExpr(VAR num: REAL);
VAR index : INTEGER;
BEGIN
WITH expr DO
num := VAL(REAL,operand[0]);
FOR index := 1 TO 3 DO
CASE operator[index] OF
add : num := num + VAL(REAL,operand[index]);|
sub : num := num - VAL(REAL,operand[index]);|
mul : num := num * VAL(REAL,operand[index]);|
div : num := num / VAL(REAL,operand[index]);
END;(*of CASE*)
END;(*of FOR*)
END;(*of WITH*)
END evaluateExpr;
(**************************************************************generateNumbers*)
(* generates the 4 random numbers ond write them *)
PROCEDURE generateNumbers;
VAR index,ran : INTEGER;
BEGIN
numbers := numbers_t{};
ran := Random(0,9);
FOR index := 1 TO 4 DO
WHILE (CHR(ran+48) IN numbers )DO
ran := Random(0,9);
END;(*of While*)
Write(CHR(ran+48));
WriteLn;
numbers := numbers + numbers_t{CHR(ran+48)}
END;(*of FOR*)
END generateNumbers;
(****************************************************************Main Programm*)
VAR str : ARRAY[0..255] OF CHAR;
sum : REAL;
BEGIN
WriteString("Welcome to the 24 game in MODULA-2");
WriteLn;
WriteString("Here are your numbers:");
WriteLn;
generateNumbers;
WriteString("Enter your equation(This implementation dosn`t support brackets yet): ");
WriteLn;
ReadString(str);
createExpr(str);
evaluateExpr(sum);
WriteLn;
WriteString("Result:");
WriteLn;
WriteInt(TRUNC(sum),0);
WriteLn;
CASE (TRUNC(sum) - 24) OF
0 : WriteString("Perfect!");|
1 : WriteString("Almost perfect.");
ELSE
WriteString("You loose!");
END;(*of CASE*)
WriteLn;
END TwentyFour. |
http://rosettacode.org/wiki/A%2BB | A+B | A+B ─── a classic problem in programming contests, it's given so contestants can gain familiarity with the online judging system being used.
Task
Given two integers, A and B.
Their sum needs to be calculated.
Input data
Two integers are written in the input stream, separated by space(s):
(
−
1000
≤
A
,
B
≤
+
1000
)
{\displaystyle (-1000\leq A,B\leq +1000)}
Output data
The required output is one integer: the sum of A and B.
Example
input
output
2 2
4
3 2
5
| #Excel | Excel |
=A1+B1
|
http://rosettacode.org/wiki/ABC_problem | ABC problem | ABC problem
You are encouraged to solve this task according to the task description, using any language you may know.
You are given a collection of ABC blocks (maybe like the ones you had when you were a kid).
There are twenty blocks with two letters on each block.
A complete alphabet is guaranteed amongst all 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
| #Order | Order | #include <order/interpreter.h>
#include <order/lib.h>
// Because of technical limitations, characters within a "string" must be separated by white spaces.
// For the sake of simplicity, only upper-case characters are supported here.
// A few lines of boiler-plate oriented programming are needed to enable character parsing and comparison.
#define ORDER_PP_TOKEN_A (A)
#define ORDER_PP_TOKEN_B (B)
#define ORDER_PP_TOKEN_C (C)
#define ORDER_PP_TOKEN_D (D)
#define ORDER_PP_TOKEN_E (E)
#define ORDER_PP_TOKEN_F (F)
#define ORDER_PP_TOKEN_G (G)
#define ORDER_PP_TOKEN_H (H)
#define ORDER_PP_TOKEN_I (I)
#define ORDER_PP_TOKEN_J (J)
#define ORDER_PP_TOKEN_K (K)
#define ORDER_PP_TOKEN_L (L)
#define ORDER_PP_TOKEN_M (M)
#define ORDER_PP_TOKEN_N (N)
#define ORDER_PP_TOKEN_O (O)
#define ORDER_PP_TOKEN_P (P)
#define ORDER_PP_TOKEN_Q (Q)
#define ORDER_PP_TOKEN_R (R)
#define ORDER_PP_TOKEN_S (S)
#define ORDER_PP_TOKEN_T (T)
#define ORDER_PP_TOKEN_U (U)
#define ORDER_PP_TOKEN_V (V)
#define ORDER_PP_TOKEN_W (W)
#define ORDER_PP_TOKEN_X (X)
#define ORDER_PP_TOKEN_Y (Y)
#define ORDER_PP_TOKEN_Z (Z)
#define ORDER_PP_SYM_A(...) __VA_ARGS__
#define ORDER_PP_SYM_B(...) __VA_ARGS__
#define ORDER_PP_SYM_C(...) __VA_ARGS__
#define ORDER_PP_SYM_D(...) __VA_ARGS__
#define ORDER_PP_SYM_E(...) __VA_ARGS__
#define ORDER_PP_SYM_F(...) __VA_ARGS__
#define ORDER_PP_SYM_G(...) __VA_ARGS__
#define ORDER_PP_SYM_H(...) __VA_ARGS__
#define ORDER_PP_SYM_I(...) __VA_ARGS__
#define ORDER_PP_SYM_J(...) __VA_ARGS__
#define ORDER_PP_SYM_K(...) __VA_ARGS__
#define ORDER_PP_SYM_L(...) __VA_ARGS__
#define ORDER_PP_SYM_M(...) __VA_ARGS__
#define ORDER_PP_SYM_N(...) __VA_ARGS__
#define ORDER_PP_SYM_O(...) __VA_ARGS__
#define ORDER_PP_SYM_P(...) __VA_ARGS__
#define ORDER_PP_SYM_Q(...) __VA_ARGS__
#define ORDER_PP_SYM_R(...) __VA_ARGS__
#define ORDER_PP_SYM_S(...) __VA_ARGS__
#define ORDER_PP_SYM_T(...) __VA_ARGS__
#define ORDER_PP_SYM_U(...) __VA_ARGS__
#define ORDER_PP_SYM_V(...) __VA_ARGS__
#define ORDER_PP_SYM_W(...) __VA_ARGS__
#define ORDER_PP_SYM_X(...) __VA_ARGS__
#define ORDER_PP_SYM_Y(...) __VA_ARGS__
#define ORDER_PP_SYM_Z(...) __VA_ARGS__
/// 8blocks_lexer (string) : Seq String -> Seq (Seq Sym)
#define ORDER_PP_DEF_8blocks_lexer ORDER_PP_FN \
(8fn (8S \
,8seq_map (8tokens_to_seq \
,8S \
) \
) \
)
// Keying the blocks makes filtering them way more efficient than by comparing their letters.
/// 8seq_keyed (sequence) : Seq a -> Seq (Pair Num a)
#define ORDER_PP_DEF_8seq_keyed ORDER_PP_FN \
(8fn (8S \
,8stream_to_seq (8stream_pair_with (8pair \
,8stream_of_naturals \
,8seq_to_stream (8S) \
) \
) \
) \
)
/// 8abc_internal (blocks, word) : Seq (Pair Num (Seq Token)) -> Seq Token -> Bool
#define ORDER_PP_DEF_8abc_internal ORDER_PP_FN \
(8fn (8B, 8W \
,8if (8seq_is_nil (8W) \
,8true \
,8lets ((8C, 8seq_head (8W)) \
(8S, 8seq_filter (8chain (8seq_exists (8same (8C)) \
,8tuple_at_1 \
) \
,8B \
) \
) \
(8T, 8seq_map (8chain (8flip (8seq_filter \
,8B \
) \
,8bin_pr (8not_eq \
,8tuple_at_0 \
) \
) \
,8S \
) \
) \
,8seq_exists (8flip (8abc_internal \
,8seq_tail (8W) \
) \
,8T \
) \
) \
) \
) \
)
/// 8abc (blocks, word) : Seq (String) -> String -> Bool
#define ORDER_PP_DEF_8abc ORDER_PP_FN \
(8fn (8B, 8W \
,8abc_internal (8seq_keyed (8blocks_lexer (8B)) \
,8tokens_to_seq (8W) \
) \
) \
)
#define ORDER_PP_DEF_8blocks ORDER_PP_CONST ( \
(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) \
)
ORDER_PP
(8seq_map (8step (8pair (8identity
,8abc (8blocks)
)
)
,8quote ((A)
(B A R K)
(B O O K)
(T R E A T)
(C O M M O N)
(S Q U A D)
(C O N F U S E)
)
)
)
|
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.
| #PL.2FM | PL/M | 100H:
/* PARAMETERS */
DECLARE N$DRAWERS LITERALLY '100'; /* AMOUNT OF DRAWERS */
DECLARE N$ATTEMPTS LITERALLY '50'; /* ATTEMPTS PER PRISONER */
DECLARE N$SIMS LITERALLY '2000'; /* N. OF SIMULATIONS TO RUN */
DECLARE RAND$SEED LITERALLY '193'; /* RANDOM SEED */
/* CP/M CALLS */
BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS;
EXIT: PROCEDURE; CALL BDOS(0, 0); END EXIT;
PRINT: PROCEDURE (S); DECLARE S ADDRESS; CALL BDOS(9, S); END PRINT;
/* PRINT NUMBER */
PRINT$NUMBER: PROCEDURE (N);
DECLARE S (6) BYTE INITIAL ('.....$');
DECLARE (P, N) ADDRESS, C BASED P BYTE;
P = .S(5);
DIGIT:
P = P - 1;
C = N MOD 10 + '0';
N = N / 10;
IF N > 0 THEN GO TO DIGIT;
CALL PRINT(P);
END PRINT$NUMBER;
/* RANDOM NUMBER GENERATOR */
RAND$BYTE: PROCEDURE BYTE;
DECLARE (X, A, B, C) BYTE
INITIAL (RAND$SEED, RAND$SEED, RAND$SEED, RAND$SEED);
X = X+1;
A = A XOR C XOR X;
B = B+A;
C = C+SHR(B,1)+A;
RETURN C;
END RAND$BYTE;
/* GENERATE RANDOM NUMBER FROM 0 TO MAX */
RAND$MAX: PROCEDURE (MAX) BYTE;
DECLARE (X, R, MAX) BYTE;
X = 1;
DO WHILE X < MAX;
X = SHL(X,1);
END;
X = X-1;
DO WHILE 1;
R = RAND$BYTE AND X;
IF R < MAX THEN RETURN R;
END;
END RAND$MAX;
/* PLACE CARDS RANDOMLY IN DRAWERS */
INIT$DRAWERS: PROCEDURE (DRAWERS);
DECLARE DRAWERS ADDRESS, (D BASED DRAWERS, I, J, K) BYTE;
DO I=0 TO N$DRAWERS-1;
D(I) = I;
END;
DO I=0 TO N$DRAWERS-1;
J = I + RAND$MAX(N$DRAWERS-I);
K = D(I);
D(I) = D(J);
D(J) = K;
END;
END INIT$DRAWERS;
/* PRISONER OPENS RANDOM DRAWERS */
RANDOM$STRATEGY: PROCEDURE (DRAWERS, P) BYTE;
DECLARE DRAWERS ADDRESS, D BASED DRAWERS BYTE;
DECLARE (P, I, TRIES) BYTE;
/* KEEP TRACK OF WHICH DRAWERS HAVE BEEN OPENED */
DECLARE OPEN (N$DRAWERS) BYTE;
DO I=0 TO N$DRAWERS-1;
OPEN(I) = 0;
END;
/* OPEN RANDOM DRAWERS */
TRIES = N$ATTEMPTS;
DO WHILE TRIES > 0;
IF NOT OPEN(I := RAND$MAX(N$DRAWERS)) THEN DO;
/* IF WE FIND OUR NUMBER, SUCCESS */
IF D(I) = P THEN RETURN 1;
OPEN(I) = 1;
TRIES = TRIES - 1;
END;
END;
RETURN 0; /* WE DID NOT FIND OUR NUMBER */
END RANDOM$STRATEGY;
/* PRISONER USES OPTIMAL STRATEGY */
OPTIMAL$STRATEGY: PROCEDURE (DRAWERS, P) BYTE;
DECLARE DRAWERS ADDRESS, D BASED DRAWERS BYTE;
DECLARE (P, I, TRIES) BYTE;
TRIES = N$ATTEMPTS;
I = P;
DO WHILE TRIES > 0;
I = D(I); /* OPEN DRAWER W/ CURRENT NUMBER */
IF I = P THEN RETURN 1; /* DID WE FIND IT? */
TRIES = TRIES - 1;
END;
RETURN 0;
END OPTIMAL$STRATEGY;
/* RUN A SIMULATION */
DECLARE RANDOM LITERALLY '0';
DECLARE OPTIMAL LITERALLY '1';
SIMULATE: PROCEDURE (STRAT) BYTE;
DECLARE (STRAT, P, R) BYTE;
/* PLACE CARDS IN DRAWERS */
DECLARE DRAWERS (N$DRAWERS) BYTE;
CALL INIT$DRAWERS(.DRAWERS);
/* TRY EACH PRISONER */
DO P=0 TO N$DRAWERS-1;
DO CASE STRAT;
R = RANDOM$STRATEGY(.DRAWERS, P);
R = OPTIMAL$STRATEGY(.DRAWERS, P);
END;
/* IF ONE PRISONER FAILS THEY ALL HANG */
IF NOT R THEN RETURN 0;
END;
RETURN 1; /* IF THEY ALL SUCCEED NONE HANG */
END SIMULATE;
/* RUN MANY SIMULATIONS AND COUNT THE SUCCESSES */
RUN$SIMULATIONS: PROCEDURE (N, STRAT) ADDRESS;
DECLARE STRAT BYTE, (I, N, SUCC) ADDRESS;
SUCC = 0;
DO I=1 TO N;
SUCC = SUCC + SIMULATE(STRAT);
END;
RETURN SUCC;
END RUN$SIMULATIONS;
/* RUN AND PRINT SIMULATIONS */
RUN$AND$PRINT: PROCEDURE (NAME, STRAT, N);
DECLARE (NAME, N, S) ADDRESS, STRAT BYTE;
CALL PRINT(NAME);
CALL PRINT(.' STRATEGY: $');
S = RUN$SIMULATIONS(N, STRAT);
CALL PRINT$NUMBER(S);
CALL PRINT(.' OUT OF $');
CALL PRINT$NUMBER(N);
CALL PRINT(.' - $');
CALL PRINT$NUMBER( S*10 / (N/10) );
CALL PRINT(.(37,13,10,'$'));
END RUN$AND$PRINT;
CALL RUN$AND$PRINT(.'RANDOM$', RANDOM, N$SIMS);
CALL RUN$AND$PRINT(.'OPTIMAL$', OPTIMAL, N$SIMS);
CALL EXIT;
EOF |
http://rosettacode.org/wiki/24_game/Solve | 24 game/Solve | task
Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the 24 game.
Show examples of solutions generated by the program.
Related task
Arithmetic Evaluator
| #Simula | Simula | BEGIN
CLASS EXPR;
BEGIN
REAL PROCEDURE POP;
BEGIN
IF STACKPOS > 0 THEN
BEGIN STACKPOS := STACKPOS - 1; POP := STACK(STACKPOS); END;
END POP;
PROCEDURE PUSH(NEWTOP); REAL NEWTOP;
BEGIN
STACK(STACKPOS) := NEWTOP;
STACKPOS := STACKPOS + 1;
END PUSH;
REAL PROCEDURE CALC(OPERATOR, ERR); CHARACTER OPERATOR; LABEL ERR;
BEGIN
REAL X, Y; X := POP; Y := POP;
IF OPERATOR = '+' THEN PUSH(Y + X)
ELSE IF OPERATOR = '-' THEN PUSH(Y - X)
ELSE IF OPERATOR = '*' THEN PUSH(Y * X)
ELSE IF OPERATOR = '/' THEN BEGIN
IF X = 0 THEN
BEGIN
EVALUATEDERR :- "DIV BY ZERO";
GOTO ERR;
END;
PUSH(Y / X);
END
ELSE
BEGIN
EVALUATEDERR :- "UNKNOWN OPERATOR";
GOTO ERR;
END
END CALC;
PROCEDURE READCHAR(CH); NAME CH; CHARACTER CH;
BEGIN
IF T.MORE THEN CH := T.GETCHAR ELSE CH := EOT;
END READCHAR;
PROCEDURE SKIPWHITESPACE(CH); NAME CH; CHARACTER CH;
BEGIN
WHILE (CH = SPACE) OR (CH = TAB) OR (CH = CR) OR (CH = LF) DO
READCHAR(CH);
END SKIPWHITESPACE;
PROCEDURE BUSYBOX(OP, ERR); INTEGER OP; LABEL ERR;
BEGIN
CHARACTER OPERATOR;
REAL NUMBR;
BOOLEAN NEGATIVE;
SKIPWHITESPACE(CH);
IF OP = EXPRESSION THEN
BEGIN
NEGATIVE := FALSE;
WHILE (CH = '+') OR (CH = '-') DO
BEGIN
IF CH = '-' THEN NEGATIVE := NOT NEGATIVE;
READCHAR(CH);
END;
BUSYBOX(TERM, ERR);
IF NEGATIVE THEN
BEGIN
NUMBR := POP; PUSH(0 - NUMBR);
END;
WHILE (CH = '+') OR (CH = '-') DO
BEGIN
OPERATOR := CH; READCHAR(CH);
BUSYBOX(TERM, ERR); CALC(OPERATOR, ERR);
END;
END
ELSE IF OP = TERM THEN
BEGIN
BUSYBOX(FACTOR, ERR);
WHILE (CH = '*') OR (CH = '/') DO
BEGIN
OPERATOR := CH; READCHAR(CH);
BUSYBOX(FACTOR, ERR); CALC(OPERATOR, ERR)
END
END
ELSE IF OP = FACTOR THEN
BEGIN
IF (CH = '+') OR (CH = '-') THEN
BUSYBOX(EXPRESSION, ERR)
ELSE IF (CH >= '0') AND (CH <= '9') THEN
BUSYBOX(NUMBER, ERR)
ELSE IF CH = '(' THEN
BEGIN
READCHAR(CH);
BUSYBOX(EXPRESSION, ERR);
IF CH = ')' THEN READCHAR(CH) ELSE GOTO ERR;
END
ELSE GOTO ERR;
END
ELSE IF OP = NUMBER THEN
BEGIN
NUMBR := 0;
WHILE (CH >= '0') AND (CH <= '9') DO
BEGIN
NUMBR := 10 * NUMBR + RANK(CH) - RANK('0'); READCHAR(CH);
END;
IF CH = '.' THEN
BEGIN
REAL FAKTOR;
READCHAR(CH);
FAKTOR := 10;
WHILE (CH >= '0') AND (CH <= '9') DO
BEGIN
NUMBR := NUMBR + (RANK(CH) - RANK('0')) / FAKTOR;
FAKTOR := 10 * FAKTOR;
READCHAR(CH);
END;
END;
PUSH(NUMBR);
END;
SKIPWHITESPACE(CH);
END BUSYBOX;
BOOLEAN PROCEDURE EVAL(INP); TEXT INP;
BEGIN
EVALUATEDERR :- NOTEXT;
STACKPOS := 0;
T :- COPY(INP.STRIP);
READCHAR(CH);
BUSYBOX(EXPRESSION, ERRORLABEL);
IF NOT T.MORE AND STACKPOS = 1 AND CH = EOT THEN
BEGIN
EVALUATED := POP;
EVAL := TRUE;
GOTO NOERRORLABEL;
END;
ERRORLABEL:
EVAL := FALSE;
IF EVALUATEDERR = NOTEXT THEN
EVALUATEDERR :- "INVALID EXPRESSION: " & INP;
NOERRORLABEL:
END EVAL;
REAL PROCEDURE RESULT;
RESULT := EVALUATED;
TEXT PROCEDURE ERR;
ERR :- EVALUATEDERR;
TEXT T;
INTEGER EXPRESSION;
INTEGER TERM;
INTEGER FACTOR;
INTEGER NUMBER;
CHARACTER TAB;
CHARACTER LF;
CHARACTER CR;
CHARACTER SPACE;
CHARACTER EOT;
CHARACTER CH;
REAL ARRAY STACK(0:31);
INTEGER STACKPOS;
REAL EVALUATED;
TEXT EVALUATEDERR;
EXPRESSION := 1;
TERM := 2;
FACTOR := 3;
NUMBER := 4;
TAB := CHAR(9);
LF := CHAR(10);
CR := CHAR(13);
SPACE := CHAR(32);
EOT := CHAR(0);
END EXPR;
INTEGER ARRAY DIGITS(1:4);
INTEGER SEED, I;
REF(EXPR) E;
INTEGER SOLUTION;
INTEGER D1,D2,D3,D4;
INTEGER O1,O2,O3;
TEXT OPS;
OPS :- "+-*/";
E :- NEW EXPR;
OUTTEXT("ENTER FOUR INTEGERS: ");
OUTIMAGE;
FOR I := 1 STEP 1 UNTIL 4 DO DIGITS(I) := ININT; !RANDINT(0, 9, SEED);
! DIGITS ;
FOR D1 := 1 STEP 1 UNTIL 4 DO
FOR D2 := 1 STEP 1 UNTIL 4 DO IF D2 <> D1 THEN
FOR D3 := 1 STEP 1 UNTIL 4 DO IF D3 <> D2 AND
D3 <> D1 THEN
FOR D4 := 1 STEP 1 UNTIL 4 DO IF D4 <> D3 AND
D4 <> D2 AND
D4 <> D1 THEN
! OPERATORS ;
FOR O1 := 1 STEP 1 UNTIL 4 DO
FOR O2 := 1 STEP 1 UNTIL 4 DO
FOR O3 := 1 STEP 1 UNTIL 4 DO
BEGIN
PROCEDURE P(FMT); TEXT FMT;
BEGIN
INTEGER PLUS;
TRY.SETPOS(1);
WHILE FMT.MORE DO
BEGIN
CHARACTER C;
C := FMT.GETCHAR;
IF (C >= '1') AND (C <= '4') THEN
BEGIN
INTEGER DIG; CHARACTER NCH;
DIG := IF C = '1' THEN DIGITS(D1)
ELSE IF C = '2' THEN DIGITS(D2)
ELSE IF C = '3' THEN DIGITS(D3)
ELSE DIGITS(D4);
NCH := CHAR( DIG + RANK('0') );
TRY.PUTCHAR(NCH);
END
ELSE IF C = '+' THEN
BEGIN
PLUS := PLUS + 1;
OPS.SETPOS(IF PLUS = 1 THEN O1 ELSE
IF PLUS = 2 THEN O2
ELSE O3);
TRY.PUTCHAR(OPS.GETCHAR);
END
ELSE IF (C = '(') OR (C = ')') OR (C = ' ') THEN
TRY.PUTCHAR(C)
ELSE
ERROR("ILLEGAL EXPRESSION");
END;
IF E.EVAL(TRY) THEN
BEGIN
IF ABS(E.RESULT - 24) < 0.001 THEN
BEGIN
SOLUTION := SOLUTION + 1;
OUTTEXT(TRY); OUTTEXT(" = ");
OUTFIX(E.RESULT, 4, 10);
OUTIMAGE;
END;
END
ELSE
BEGIN
IF E.ERR <> "DIV BY ZERO" THEN
BEGIN
OUTTEXT(TRY); OUTIMAGE;
OUTTEXT(E.ERR); OUTIMAGE;
END;
END;
END P;
TEXT TRY;
TRY :- BLANKS(17);
P("(1 + 2) + (3 + 4)");
P("(1 + (2 + 3)) + 4");
P("((1 + 2) + 3) + 4");
P("1 + ((2 + 3) + 4)");
P("1 + (2 + (3 + 4))");
END;
OUTINT(SOLUTION, 0);
OUTTEXT(" SOLUTIONS FOUND");
OUTIMAGE;
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
| #M2000_Interpreter | M2000 Interpreter |
Module Puzzle15 {
00 BASE 1 : DEF RND(X)=RND
10 REM 15-PUZZLE GAME
20 REM COMMODORE BASIC 2.0
30 REM ********************************
40 GOSUB 400 : REM INTRO AND LEVEL
50 GOSUB 510 : REM SETUP BOARD
60 GOSUB 210 : REM PRINT PUZZLE
70 PRINT "TO MOVE A PIECE, ENTER ITS NUMBER:"
80 INPUT X
90 GOSUB 730 : REM CHECK IF MOVE IS VALID
100 IF MV=0 THEN PRINT "WRONG MOVE" : GOSUB 1050 : GOTO 60
110 D(Z)=X : D(Y)=0
120 GOSUB 210 : REM PRINT PUZZLE
130 GOSUB 950 : REM CHECK IF PUZZLE COMPLETE
140 IF PC THEN 160
150 GOTO 70
160 PRINT"YOU WON!"
170 END
180 REM
190 REM *******************************
200 REM PRINT/DRAW THE PUZZLE
210 FOR P=1 TO 16
220 IF D(P)=0 THEN D$(P)=" " : GOTO 260
230 S$=STR$(D(P))
240 N=LEN(S$)
250 D$(P) = LEFT$(" ",3-N)+S$+" "
260 NEXT P
270 PRINT "+-----+-----+-----+-----+"
280 PRINT "!";D$(1);"!";D$(2);"!";D$(3);"!";D$(4);"!"
290 PRINT "+-----+-----+-----+-----+"
300 PRINT "!";D$(5);"!";D$(6);"!";D$(7);"!";D$(8);"!"
310 PRINT "+-----+-----+-----+-----+"
320 PRINT "!";D$(9);"!";D$(10);"!";D$(11);"!";D$(12);"!"
330 PRINT "+-----+-----+-----+-----+"
340 PRINT "!";D$(13);"!";D$(14);"!";D$(15);"!";D$(16);"!"
350 PRINT "+-----+-----+-----+-----+"
360 RETURN
370 REM
380 REM *******************************
390 REM INTRO AND LEVEL OF DIFFICULTY
400 PRINT CHR$(147)
410 DIM SH(3) : SH(1)=10 : SH(2)=50 : SH(3)=100
420 PRINT "15 PUZZLE GAME FOR COMMODORE BASIC 2.0" : PRINT : PRINT
430 PRINT "PLEASE ENTER LEVEL OF DIFFICULTY,"
440 PRINT "1(EASY), 2(MEDIUM) OR 3(HARD):";
450 INPUT V
460 IF V<1 OR V>3 THEN 440
470 RETURN
480 REM
490 REM *******************************
500 REM BUILD THE BOARD
510 DIM D(16) : DIM D$(16) : REM BOARD PIECES
520 REM SET PIECES IN CORRECT ORDER FIRST
530 FOR P=1 TO 15
540 D(P) = P
550 NEXT P
560 D(16) = 0 : REM 0 = EMPTY PIECE/SLOT
570 Z=16 : REM Z = EMPTY POSITION
580 PRINT: PRINT "SHUFFLING PIECES";
590 FOR N=1 TO SH(V)
600 PRINT".";
610 X = INT(RND(0)*4)+1
620 R = Z+(X=1)*4-(X=2)*4+(X=3)-(X=4)
630 IF R<1 OR R>16 THEN 610
640 D(Z)=D(R)
650 Z=R
660 D(Z)=0
670 NEXT N
680 PRINT CHR$(147)
690 RETURN
700 REM
710 REM *******************************
720 REM CHECK IF MOVE IS VALID
730 MV = 0
740 IF X<1 OR X>15 THEN RETURN
750 REM FIND POSITION OF PIECE X
760 P=1
770 IF D(P)=X THEN Y=P : GOTO 810
780 P=P+1 : IF P>16 THEN PRINT "UH OH!" : STOP
790 GOTO 770
800 REM FIND POSITION OF EMPTY PIECE
810 P=1
820 IF D(P)=0 THEN Z=P : GOTO 860
830 P=P+1 : IF P>16 THEN PRINT "UH OH!" : STOP
840 GOTO 820
850 PRINT Y;Z
860 REM CHECK IF EMPTY PIECE IS ABOVE, BELOW, LEFT OR RIGHT TO PIECE X
870 IF Y-4=Z THEN MV=1 : RETURN
880 IF Y+4=Z THEN MV=1 : RETURN
890 IF Y-1=Z THEN MV=1 : RETURN
900 IF Y+1=Z THEN MV=1 : RETURN
910 RETURN
920 REM
930 REM *******************************
940 REM CHECK IF PUZZLE IS COMPLETE / GAME OVER
950 PC = 0
960 P=1
970 IF D(P)<>P THEN RETURN
980 P=P+1
990 IF P<16 THEN 970
1000 PC = 1
1010 RETURN
1020 REM
1030 REM ******************************
1040 REM A SMALL DELAY
1050 FOR T=0 TO 400
1060 NEXT T
1070 RETURN
}
Puzzle15
|
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.
| #Perl | Perl | #!/usr/bin/perl
use strict; # https://rosettacode.org/wiki/2048
use warnings;
use Tk;
my $N = shift // 4;
$N < 2 and $N = 2;
my @squares = 1 .. $N*$N;
my %n2ch = (' ' => ' ');
@n2ch{ map 2**$_, 1..26} = 'a'..'z';
my %ch2n = reverse %n2ch;
my $winner = '';
my @arow = 0 .. $N - 1;
my @acol = map $_ * $N, @arow;
my $mw = MainWindow->new;
$mw->geometry( '+300+0' );
$mw->title( 2048 );
$mw->focus;
$mw->bind('<KeyPress-Left>' => sub { arrow($N, @arow) } );
$mw->bind('<KeyPress-Right>' => sub { arrow($N, reverse @arow) } );
$mw->bind('<KeyPress-Up>' => sub { arrow(1, @acol) } );
$mw->bind('<KeyPress-Down>' => sub { arrow(1, reverse @acol) } );
my $grid = $mw->Frame()->pack;
for my $i ( 0 .. $#squares )
{
$grid->Label(-textvariable => \$squares[$i],
-width => 5, -height => 2, -font => 'courierbold 30',
-relief => 'ridge', -borderwidth => 5,
)->grid(-row => int $i / $N, -column => $i % $N );
}
my $buttons = $mw->Frame()->pack(-fill => 'x', -expand => 1);
$buttons->Button(-text => 'Exit', -command => sub {$mw->destroy},
-font => 'courierbold 14',
)->pack(-side => 'right');
$buttons->Button(-text => 'New Game', -command => \&newgame,
-font => 'courierbold 14',
)->pack(-side => 'left');
$buttons->Label(-textvariable => \$winner,
-font => 'courierbold 18', -fg => 'red2',
)->pack;
newgame();
MainLoop;
-M $0 < 0 and exec $0;
sub losecheck
{
local $_ = join '', @n2ch{ @squares };
/ / || ($_ ^ substr $_, $N) =~ tr/\0// and return;
/(.)\1/ and return for /.{$N}/g;
$winner = 'You Lost';
}
sub arrow
{
$winner and return; # you won, no more play
my ($inc, @ix) = @_;
my $oldboard = "@squares";
for ( 1 .. $N )
{
local $_ = join '', @n2ch{ @squares[@ix] }; # extract 4 squares
tr/ //d; # force left
s/(\w)\1/ chr 1 + ord $1 /ge; # group by twos
@squares[@ix] = @ch2n{ split //, $_ . ' ' x $N }; # replace
$_ += $inc for @ix; # next row or col
}
$oldboard eq "@squares" and return;
add2();
losecheck();
grep $_ eq 2048, @squares and $winner = 'WINNER !!';
}
sub add2
{
my @blanks = grep $squares[$_] eq ' ', 0 .. $#squares;
@blanks and $squares[ $blanks[rand @blanks] ] =
$_[0] // (rand() < 0.1 ? 4 : 2);
}
sub newgame
{
$_ = ' ' for @squares;
add2(2) for 1, 2;
$winner = '';
} |
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
| #C.2B.2B | C++ | #include <iostream>
using std::cout;
int main()
{
for(int bottles(99); bottles > 0; bottles -= 1){
cout << bottles << " bottles of beer on the wall\n"
<< bottles << " bottles of beer\n"
<< "Take one down, pass it around\n"
<< bottles - 1 << " bottles of beer on the wall\n\n";
}
} |
http://rosettacode.org/wiki/24_game | 24 game | The 24 Game tests one's mental arithmetic.
Task
Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed.
The program should prompt for the player to enter an arithmetic expression using just those, and all of those four digits, used exactly once each. 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.
| #MUMPS | MUMPS | 24Game
k number, operator, bracket
; generate 4 random numbers each between 1 & 9
; duplicates allowed!
s n1=$r(9)+1, n2=$r(9)+1, n3=$r(9)+1, n4=$r(9)+1
; save a copy of them so that we can keep restarting
; if the user gets it wrong
s s1=n1,s2=n2,s3=n3,s4=n4
Question
s (numcount,opcount,lbrackcount,rbrackcount)=0
; restart with the random numbers already found
s n1=s1,n2=s2,n3=s3,n4=s4
w !,"Enter an arithmetic expression that evaluates to 24 using (",
n1," ",n2," ",n3," ",n4,"): "
r !,expr
q:expr=""
; validate numbers and operators
s error=""
f n=1:1:$l(expr) {
s char=$e(expr,n)
if char?1n {
s number($i(numcount))=char
w !
zw char
}
elseif char?1(1"*",1"/",1"+",1"-") {
s operator($i(opcount))=char
}
elseif char?1"(" {
s bracket($i(lbrackcount))=char
}
elseif char?1")" {
s bracket($i(rbrackcount))=char
}
else {
s error="That ain't no character I wanted to see"
q
}
}
if error'="" w error g Question
if numcount'=4 {
w "Does not have 4 numbers, do it again."
g Question
}
s error=""
f n=1:1:4 {
if number(n)=n1 {
s n1="dont use again" continue
}
if number(n)=n2 {
s n2="dont use again" continue
}
if number(n)=n3 {
s n3="dont use again" continue
}
if number(n)=n4 {
s n4="dont use again" continue
}
s error="Numbers entered do not match all of the randomly generated numbers."
q
}
if error'="" {
w error
g Question
}
if opcount'=3 {
w "Does not have 3 operators."
g Question
}
if lbrackcount'=rbrackcount {
w "brackets must be in pairs."
g Question
}
x "s x="_expr
if x'=24 {
w !,"Answer does not = 24"
g Question
}
w x
q
|
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
| #F.23 | F# | open System
let SumOf(str : string) =
str.Split() |> Array.sumBy(int)
[<EntryPoint>]
let main argv =
Console.WriteLine(SumOf(Console.ReadLine()))
0 |
http://rosettacode.org/wiki/ABC_problem | ABC problem | ABC problem
You are encouraged to solve this task according to the task description, using any language you may know.
You are given a collection of ABC blocks (maybe like the ones you had when you were a kid).
There are twenty blocks with two letters on each block.
A complete alphabet is guaranteed amongst all 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
| #PARI.2FGP | PARI/GP | BLOCKS = "BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM";
WORDS = ["A","Bark","BOOK","Treat","COMMON","SQUAD","conFUSE"];
can_make_word(w) = check(Vecsmall(BLOCKS), Vecsmall(w))
check(B,W,l=1,n=1) =
{
if (l > #W, return(1), n > #B, return(0));
forstep (i = 1, #B-2, 2,
if (B[i] != bitand(W[l],223) && B[i+1] != bitand(W[l],223), next());
B[i] = B[i+1] = 0;
if (check(B, W, l+1, n+2), return(1))
);
0
}
for (i = 1, #WORDS, printf("%s\t%d\n", WORDS[i], can_make_word(WORDS[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.
| #Pointless | Pointless | optimalSeq(drawers, n) =
iterate(ind => drawers[ind - 1], n)
|> takeUntil(ind => drawers[ind - 1] == n)
optimalTrial(drawers) =
range(1, 100)
|> map(optimalSeq(drawers))
randomSeq(drawers, n) =
iterate(ind => randRange(1, 100), randRange(1, 100))
|> takeUntil(ind => drawers[ind - 1] == n)
randomTrial(drawers) =
range(1, 100)
|> map(randomSeq(drawers))
checkLength(seq) =
length(take(51, seq)) <= 50
numTrials = 3000
runTrials(trialFunc) =
for t in range(1, numTrials)
yield
range(1, 100)
|> shuffle
|> toArray
|> trialFunc
|> map(checkLength)
|> all
countSuccess(trialFunc) =
runTrials(trialFunc)
|> filter(id)
|> length
optimalCount = countSuccess(optimalTrial)
randomCount = countSuccess(randomTrial)
output =
format("optimal: {} / {} = {} prob\nrandom: {} / {} = {} prob", [
optimalCount, numTrials, optimalCount / numTrials,
randomCount, numTrials, randomCount / numTrials,
])
|> println |
http://rosettacode.org/wiki/24_game/Solve | 24 game/Solve | task
Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the 24 game.
Show examples of solutions generated by the program.
Related task
Arithmetic Evaluator
| #Swift | Swift |
import Darwin
import Foundation
var solution = ""
println("24 Game")
println("Generating 4 digits...")
func randomDigits() -> [Int] {
var result = [Int]()
for i in 0 ..< 4 {
result.append(Int(arc4random_uniform(9)+1))
}
return result
}
// Choose 4 digits
let digits = randomDigits()
print("Make 24 using these digits : ")
for digit in digits {
print("\(digit) ")
}
println()
// get input from operator
var input = NSString(data:NSFileHandle.fileHandleWithStandardInput().availableData, encoding:NSUTF8StringEncoding)!
var enteredDigits = [Double]()
var enteredOperations = [Character]()
let inputString = input as String
// store input in the appropriate table
for character in inputString {
switch character {
case "1", "2", "3", "4", "5", "6", "7", "8", "9":
let digit = String(character)
enteredDigits.append(Double(digit.toInt()!))
case "+", "-", "*", "/":
enteredOperations.append(character)
case "\n":
println()
default:
println("Invalid expression")
}
}
// check value of expression provided by the operator
var value = 0.0
if enteredDigits.count == 4 && enteredOperations.count == 3 {
value = enteredDigits[0]
for (i, operation) in enumerate(enteredOperations) {
switch operation {
case "+":
value = value + enteredDigits[i+1]
case "-":
value = value - enteredDigits[i+1]
case "*":
value = value * enteredDigits[i+1]
case "/":
value = value / enteredDigits[i+1]
default:
println("This message should never happen!")
}
}
}
func evaluate(dPerm: [Double], oPerm: [String]) -> Bool {
var value = 0.0
if dPerm.count == 4 && oPerm.count == 3 {
value = dPerm[0]
for (i, operation) in enumerate(oPerm) {
switch operation {
case "+":
value = value + dPerm[i+1]
case "-":
value = value - dPerm[i+1]
case "*":
value = value * dPerm[i+1]
case "/":
value = value / dPerm[i+1]
default:
println("This message should never happen!")
}
}
}
return (abs(24 - value) < 0.001)
}
func isSolvable(inout digits: [Double]) -> Bool {
var result = false
var dPerms = [[Double]]()
permute(&digits, &dPerms, 0)
let total = 4 * 4 * 4
var oPerms = [[String]]()
permuteOperators(&oPerms, 4, total)
for dig in dPerms {
for opr in oPerms {
var expression = ""
if evaluate(dig, opr) {
for digit in dig {
expression += "\(digit)"
}
for oper in opr {
expression += oper
}
solution = beautify(expression)
result = true
}
}
}
return result
}
func permute(inout lst: [Double], inout res: [[Double]], k: Int) -> Void {
for i in k ..< lst.count {
swap(&lst[i], &lst[k])
permute(&lst, &res, k + 1)
swap(&lst[k], &lst[i])
}
if k == lst.count {
res.append(lst)
}
}
// n=4, total=64, npow=16
func permuteOperators(inout res: [[String]], n: Int, total: Int) -> Void {
let posOperations = ["+", "-", "*", "/"]
let npow = n * n
for i in 0 ..< total {
res.append([posOperations[(i / npow)], posOperations[((i % npow) / n)], posOperations[(i % n)]])
}
}
func beautify(infix: String) -> String {
let newString = infix as NSString
var solution = ""
solution += newString.substringWithRange(NSMakeRange(0, 1))
solution += newString.substringWithRange(NSMakeRange(12, 1))
solution += newString.substringWithRange(NSMakeRange(3, 1))
solution += newString.substringWithRange(NSMakeRange(13, 1))
solution += newString.substringWithRange(NSMakeRange(6, 1))
solution += newString.substringWithRange(NSMakeRange(14, 1))
solution += newString.substringWithRange(NSMakeRange(9, 1))
return solution
}
if value != 24 {
println("The value of the provided expression is \(value) instead of 24!")
if isSolvable(&enteredDigits) {
println("A possible solution could have been " + solution)
} else {
println("Anyway, there was no known solution to this one.")
}
} else {
println("Congratulations, you found a solution!")
} |
http://rosettacode.org/wiki/15_puzzle_game | 15 puzzle game |
Task
Implement the Fifteen Puzzle Game.
The 15-puzzle is also known as:
Fifteen Puzzle
Gem Puzzle
Boss Puzzle
Game of Fifteen
Mystic Square
14-15 Puzzle
and some others.
Related Tasks
15 Puzzle Solver
16 Puzzle Game
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | grid = MapThread[{#1,#2} &, {Range @ 16, Range @ 16}]
Move[x_] := (empty = Select[grid, #[[1]]==16 &][[1,2]];
If[(empty == x+4) || (empty == x-4) ||
(Mod[empty,4] != 0 && empty == x-1) ||
(Mod[empty,4] != 1 && empty == x+1),
oldEmpty = grid[[empty]][[1]];
grid[[empty]][[1]] = grid[[x]][[1]];
grid[[x]][[1]] = oldEmpty])
CButton[{x_,loc_}] := If[x==16, Null, Button[x,Move @ loc]]
Dynamic @ Grid @ Partition[CButton /@ grid,4] |
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.
| #Phix | Phix | -- demo\rosetta\2048.exw
with javascript_semantics
include pGUI.e
Ihandle canvas, dialog
cdCanvas cddbuffer, cdcanvas
constant tile_colours = {#CCC0B4, -- blank
#EEE4DA, -- 2
#EDE0C8, -- 4
#F2B179, -- 8
#F59563, -- 16
#F67C5F, -- 32
#F65E3B, -- 64
#EDCF72, -- 128
#EDCC61, -- 256
#EDC850, -- 512
#EDC53F, -- 1024
#EDC22E} -- 2048
-- the 4x4 board.
-- note that values are [1..12] for [blank,2,4,8,..2048].
-- (merging two eights is not 8+8->16 but 4+1->5, internally)
sequence board
integer newgame = 1,
valid = 0,
prev, nxt
procedure add_rand(integer count)
-- (nb infinite loop if board is full)
while count do
integer x = rand(4),
y = rand(4)
if board[y][x]=1 then -- blank
board[y][x] = 2+(rand(10)=10)
count -= 1
end if
end while
end procedure
procedure move_x(integer x, y, d)
integer bxy = board[x][y]
if bxy!=1 then -- (not blank)
if bxy=prev then
board[x][y] = 1
bxy += 1
board[x][nxt] = bxy
nxt += d
prev = 13
valid = 1
else
if prev=1 -- (blank)
or y!=nxt then
if prev!=1
and prev!=13 then
nxt += d
end if
if y!=nxt then
board[x][y] = 1
board[x][nxt] = bxy
valid = 1
end if
end if
prev = bxy
end if
end if
end procedure
procedure move_y(integer x, y, d)
integer bxy = board[x][y]
if bxy!=1 then -- (not blank)
if bxy=prev then
board[x][y] = 1
bxy += 1
board[nxt][y] = bxy
nxt += d
prev = 13
valid = 1
else
if prev=1 -- (blank)
or x!=nxt then
if prev!=1
and prev!=13 then
nxt += d
end if
if x!=nxt then
board[x][y] = 1
board[nxt][y] = bxy
valid = 1
end if
end if
prev = bxy
end if
end if
end procedure
function move(integer key)
-- a non-zero result means it changed something.
valid = 0
if key=K_LEFT then
for x=1 to 4 do
prev = 13
nxt = 1
for y=1 to 4 do
move_x(x,y,+1)
end for
end for
elsif key=K_UP then
for y=1 to 4 do
prev = 13
nxt = 4
for x=4 to 1 by -1 do
move_y(x,y,-1)
end for
end for
elsif key=K_RIGHT then
for x=1 to 4 do
prev = 13
nxt = 4
for y=4 to 1 by -1 do
move_x(x,y,-1)
end for
end for
elsif key=K_DOWN then
for y=1 to 4 do
prev = 13
nxt = 1
for x=1 to 4 do
move_y(x,y,+1)
end for
end for
end if
return valid
end function
function game_won()
for i=1 to length(board) do
if find(12,board[i]) then return 1 end if
end for
return 0
end function
constant valid_keys = {K_LEFT,K_DOWN,K_RIGHT,K_UP}
function no_valid_moves()
sequence saved_board = deep_copy(board)
for i=1 to length(valid_keys) do
if move(valid_keys[i]) then
board = saved_board
return 0 -- OK
end if
end for
return 1 -- game over...
end function
function redraw_cb(Ihandle /*ih*/)
integer ox,oy, -- top right coords
os,ts, -- overall and tile size
ts2, -- half tile, for number positioning
{dw,dh} = IupGetIntInt(canvas, "DRAWSIZE")
if dw>=dh then
ox = floor((dw-dh)/2)
oy = 0
os = dh
else
ox = 0
oy = floor((dh-dw)/2)
os = dw
end if
ts = floor((os-10)/4-7)
ts2 = floor(ts/2+5)-10
if newgame then
board = repeat(repeat(1,4),4)
add_rand(2)
newgame = 0
end if
cdCanvasActivate(cddbuffer)
cdCanvasSetBackground(cddbuffer, #FAF8EF)
cdCanvasClear(cddbuffer)
cdCanvasSetForeground(cddbuffer, #BBADA0)
cdCanvasRoundedBox(cddbuffer, ox+5, ox+os-5, oy+5, oy+os-5, 10, 10)
integer tx = ox+15
for y=1 to 4 do
integer ty = oy+15
for x=1 to 4 do
integer bxy = board[x][y]
cdCanvasSetForeground(cddbuffer, tile_colours[bxy])
cdCanvasRoundedBox(cddbuffer, tx, tx+ts-10, ty, ty+ts-10, 5, 5)
if bxy>1 then
cdCanvasSetForeground(cddbuffer, iff(bxy<=3?#776E65:#F9F6F2))
cdCanvasFont(cddbuffer, "Calibri", CD_BOLD, iff(bxy>10?32:40))
cdCanvasText(cddbuffer, tx+ts2, ty+ts2-25-iff(bxy<11?7:0), sprint(power(2,bxy-1)))
end if
ty += ts+5
end for
tx += ts+5
end for
cdCanvasFlush(cddbuffer)
return IUP_DEFAULT
end function
function map_cb(Ihandle ih)
cdcanvas = cdCreateCanvas(CD_IUP, ih)
cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas)
cdCanvasSetTextAlignment(cddbuffer, CD_SOUTH)
return IUP_DEFAULT
end function
function key_cb(Ihandle /*ih*/, atom c)
if c=K_ESC then return IUP_CLOSE end if
if find(c,valid_keys) then
if move(c) then
IupUpdate(canvas)
string mbmsg = ""
if game_won() then
mbmsg = "!!!YOU WON!!!\n\nAnother Go?"
else
add_rand(1)
IupUpdate(canvas)
if no_valid_moves() then
mbmsg = "You Lost.\n\nAnother Go?"
end if
end if
if length(mbmsg) then
if platform()=JS then
IupMessage("Game Over",mbmsg);
newgame=1
else
if IupAlarm("Game Over",mbmsg,"Yes","No")=1 then
newgame=1
else
return IUP_CLOSE
end if
end if
end if
end if
IupUpdate(canvas)
end if
return IUP_CONTINUE
end function
procedure main()
IupOpen()
canvas = IupCanvas("RASTERSIZE=520x540")
IupSetCallback(canvas, "MAP_CB", Icallback("map_cb"))
IupSetCallback(canvas, "ACTION", Icallback("redraw_cb"))
dialog = IupDialog(canvas,"MINSIZE=440x450")
IupSetAttribute(dialog,"TITLE","2048");
IupSetCallback(dialog, "K_ANY", Icallback("key_cb"));
IupShow(dialog)
IupSetAttribute(canvas, "RASTERSIZE", NULL)
if platform()!=JS then
IupMainLoop()
IupClose()
end if
end procedure
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
| #Ceylon | Ceylon | shared void ninetyNineBottles() {
String bottles(Integer count) =>
"``count == 0 then "No" else count``
bottle``count == 1 then "" else "s"``".normalized;
for(i in 99..1) {
print("``bottles(i)`` of beer on the wall
``bottles(i)`` of beer!
Take one down, pass it around
``bottles(i - 1)`` of beer on the wall!\n");
}
} |
http://rosettacode.org/wiki/24_game | 24 game | The 24 Game tests one's mental arithmetic.
Task
Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed.
The program should prompt for the player to enter an arithmetic expression using just those, and all of those four digits, used exactly once each. 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.
| #Nanoquery | Nanoquery | import Nanoquery.Lang
import Nanoquery.Util
// a function to get the digits from an arithmetic expression
def extract_digits(input)
input = str(input)
digits = {}
loc = 0
digit = ""
while (loc < len(input))
if input[loc] in "0123456789"
digit += input[loc]
else
if len(digit) > 0
digits.append(int(digit))
digit = ""
end
end
loc += 1
end
// check if there's a final digit
if len(digit) > 0
digits.append(int(digit))
end
return digits
end
// a function to duplicate a digit list
def dup(list)
nlist = {}
for n in list
nlist.append(new(Integer, n))
end
return nlist
end
// generate four random digits and output them
random = new(Random)
randDigits = {}
for i in range(1, 4)
randDigits.append(random.getInt(8) + 1)
end
println "Your digits are: " + randDigits + "\n"
// get expressions from the user until a valid one is found
won = false
while !won
print "> "
expr = input()
tempDigits = dup(randDigits)
// check for invalid digits in the expression
invalid = false
digits = extract_digits(expr)
for (i = 0) (!invalid and (i < len(digits))) (i += 1)
if not digits[i] in tempDigits
invalid = true
println "Invalid digit " + digits[i]
else
tempDigits.remove(tempDigits)
end
end
// if there were no invalid digits, check if the expression
// evaluates to 24
if !invalid
a = null
try
exec("a = " + expr)
catch
println "Invalid expression " + expr
end
println a
if a = 24
println "Success!"
won = true
end
end
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
| #Factor | Factor | USING: math.parser splitting ;
: a+b ( -- )
readln " " split1
[ string>number ] bi@ +
number>string print ; |
http://rosettacode.org/wiki/ABC_problem | ABC problem | ABC problem
You are encouraged to solve this task according to the task description, using any language you may know.
You are given a collection of ABC blocks (maybe like the ones you had when you were a kid).
There are twenty blocks with two letters on each block.
A complete alphabet is guaranteed amongst all 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
| #Pascal | Pascal |
#!/usr/bin/instantfpc
//program ABCProblem;
{$mode objfpc}{$H+}
uses SysUtils, Classes;
const
// every couple of chars is a block
// remove one by replacing its 2 chars by 2 spaces
Blocks = 'BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM';
BlockSize = 3;
function can_make_word(Str: String): boolean;
var
wkBlocks: string = Blocks;
c: Char;
iPos : Integer;
begin
// all chars to uppercase
Str := UpperCase(Str);
Result := Str <> '';
if Result then
begin
for c in Str do
begin
iPos := Pos(c, wkBlocks);
if (iPos > 0) then
begin
// Char found
wkBlocks[iPos] := ' ';
// Remove the other face
if (iPos mod BlockSize = 1) then
wkBlocks[iPos + 1] := ' '
else
wkBlocks[iPos - 1] := ' ';
end
else
begin
// missed
Result := False;
break;
end;
end;
end;
// Debug...
//WriteLn(Blocks);
//WriteLn(wkBlocks);
End;
procedure TestABCProblem(Str: String);
const
boolStr : array[boolean] of String = ('False', 'True');
begin
WriteLn(Format('>>> can_make_word("%s")%s%s', [Str, LineEnding, boolStr[can_make_word(Str)]]));
End;
begin
TestABCProblem('A');
TestABCProblem('BARK');
TestABCProblem('BOOK');
TestABCProblem('TREAT');
TestABCProblem('COMMON');
TestABCProblem('SQUAD');
TestABCProblem('CONFUSE');
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.
| #PowerShell | PowerShell |
### Clear Screen from old Output
Clear-Host
Function RandomOpening ()
{
$Prisoners = 1..100 | Sort-Object {Get-Random}
$Cupboard = 1..100 | Sort-Object {Get-Random}
## Loop for the Prisoners
$Survived = $true
for ($I=1;$I -le 100;$i++)
{
$OpeningListe = 1..100 | Sort-Object {Get-Random}
$Gefunden = $false
## Loop for the trys of every prisoner
for ($X=1;$X -le 50;$X++)
{
$OpenNumber = $OpeningListe[$X]
IF ($Cupboard[$OpenNumber] -eq $Prisoners[$I])
{
$Gefunden = $true
}
## Cancel loop if prisoner found his number (yeah i know, dirty way ^^ )
IF ($Gefunden)
{
$X = 55
}
}
IF ($Gefunden -eq $false)
{
$I = 120
$Survived = $false
}
}
Return $Survived
}
Function StrategyOpening ()
{
$Prisoners = 1..100 | Sort-Object {Get-Random}
$Cupboard = 1..100 | Sort-Object {Get-Random}
$Survived = $true
for ($I=1;$I -le 100;$i++)
{
$Gefunden = $false
$OpeningNumber = $Prisoners[$I-1]
for ($X=1;$X -le 50;$X++)
{
IF ($Cupboard[$OpeningNumber-1] -eq $Prisoners[$I-1])
{
$Gefunden = $true
}
else
{
$OpeningNumber = $Cupboard[$OpeningNumber-1]
}
IF ($Gefunden)
{
$X = 55
}
}
IF ($Gefunden -eq $false)
{
$I = 120
$Survived = $false
}
}
Return $Survived
}
$MaxRounds = 10000
Function TestRandom
{
$WinnerRandom = 0
for ($Round = 1; $Round -le $MaxRounds;$Round++)
{
IF (($Round%1000) -eq 0)
{
$Time = Get-Date
Write-Host "Currently we are at rount $Round at $Time"
}
$Rueckgabewert = RandomOpening
IF ($Rueckgabewert)
{
$WinnerRandom++
}
}
$Prozent = (100/$MaxRounds)*$WinnerRandom
Write-Host "There are $WinnerRandom survivors whit random opening. This is $Prozent percent"
}
Function TestStrategy
{
$WinnersStrategy = 0
for ($Round = 1; $Round -le $MaxRounds;$Round++)
{
IF (($Round%1000) -eq 0)
{
$Time = Get-Date
Write-Host "Currently we are at $Round at $Time"
}
$Rueckgabewert = StrategyOpening
IF ($Rueckgabewert)
{
$WinnersStrategy++
}
}
$Prozent = (100/$MaxRounds)*$WinnersStrategy
Write-Host "There are $WinnersStrategy survivors whit strategic opening. This is $Prozent percent"
}
Function Main ()
{
Clear-Host
TestRandom
TestStrategy
}
Main
|
http://rosettacode.org/wiki/24_game/Solve | 24 game/Solve | task
Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the 24 game.
Show examples of solutions generated by the program.
Related task
Arithmetic Evaluator
| #Tcl | Tcl | package require struct::list
# Encoding the various expression trees that are possible
set patterns {
{((A x B) y C) z D}
{(A x (B y C)) z D}
{(A x B) y (C z D)}
{A x ((B y C) z D)}
{A x (B y (C z D))}
}
# Encoding the various permutations of digits
set permutations [struct::list map [struct::list permutations {a b c d}] \
{apply {v {lassign $v a b c d; list A $a B $b C $c D $d}}}]
# The permitted operations
set operations {+ - * /}
# Given a list of four integers (precondition not checked!)
# return a list of solutions to the 24 game using those four integers.
proc find24GameSolutions {values} {
global operations patterns permutations
set found {}
# For each possible structure with numbers at the leaves...
foreach pattern $patterns {
foreach permutation $permutations {
set p [string map [subst {
a [lindex $values 0].0
b [lindex $values 1].0
c [lindex $values 2].0
d [lindex $values 3].0
}] [string map $permutation $pattern]]
# For each possible structure with operators at the branches...
foreach x $operations {
foreach y $operations {
foreach z $operations {
set e [string map [subst {x $x y $y z $z}] $p]
# Try to evaluate (div-zero is an issue!) and add it to
# the result if it is 24
catch {
if {[expr $e] == 24.0} {
lappend found [string map {.0 {}} $e]
}
}
}
}
}
}
}
return $found
}
# Wrap the solution finder into a player
proc print24GameSolutionFor {values} {
set found [lsort -unique [find24GameSolutions $values]]
if {![llength $found]} {
puts "No solution possible"
} else {
puts "Total [llength $found] solutions (may include logical duplicates)"
puts "First solution: [lindex $found 0]"
}
}
print24GameSolutionFor $argv |
http://rosettacode.org/wiki/15_puzzle_game | 15 puzzle game |
Task
Implement the Fifteen Puzzle Game.
The 15-puzzle is also known as:
Fifteen Puzzle
Gem Puzzle
Boss Puzzle
Game of Fifteen
Mystic Square
14-15 Puzzle
and some others.
Related Tasks
15 Puzzle Solver
16 Puzzle Game
| #Mercury | Mercury | :- module fifteen.
:- interface.
:- use_module random, io.
:- type board.
:- type invalid_board
---> invalid_board(board).
:- type move
---> up
; down
; left
; right.
% init(Board):
% Board is fifteen game in its initial state
%
:- pred init(board::out) is det.
% print(Board, !IO)
:- pred print(board::in, io.io::di, io.io::uo) is det.
% Shuffled(Board, !RS):
% Board is a fifteen game in a random (but valid) state.
%
:- pred shuffled(board::out, random.supply::mdi, random.supply::muo) is det.
% space(Board) = I:
% I is the index of the blank space in the board.
% Throws invalid_board iff there is no blank.
%
:- func space(board) = int.
% move(Move, !Board):
% Move the blank space in a board in the given direction.
% Fails if this is an invalid move to make.
%
:- pred move(move::in, board::in, board::out) is semidet.
:- implementation.
:- import_module bt_array, int, list, string.
:- use_module array, exception.
:- type board == bt_array(int).
init(B) :- from_list(0, (1 .. 15) ++ [0], B).
print(B, !IO) :-
Tile = (func(N) = ( if N = 0 then s(" ") else s(string.format("%2d", [i(N)])) )),
io.format("\
|----+----+----+----|
| %s | %s | %s | %s |
| %s | %s | %s | %s |
| %s | %s | %s | %s |
| %s | %s | %s | %s |
|----+----+----+----|
",
map(Tile, to_list(B)), !IO).
shuffled(!:B, !RS) :-
init(!:B),
some [!A] (
array.from_list(to_list(!.B), !:A),
array.random_permutation(!A, !RS),
from_list(0, array.to_list(!.A), !:B)
).
space(Board) = I :- space(0, Board, I).
:- pred space(int::in, board::in, int::out) is det.
space(N, Board, I) :-
( if semidet_lookup(Board, N, X) then
( if X = 0 then
N = I
else
space(N + 1, Board, I)
)
else
exception.throw(invalid_board(Board))
).
:- pred swap(int::in, int::in, board::in, board::out) is det.
swap(I, J, !B) :-
X = !.B ^ elem(I),
Y = !.B ^ elem(J),
!B ^ elem(I) := Y,
!B ^ elem(J) := X.
move(M, !B) :- move(space(!.B), M, !B).
:- pred move(int::in, move::in, board::in, board::out) is semidet.
move(I, up, !B) :-
I >= 4,
swap(I, I - 4, !B).
move(I, down, !B) :-
I < 12,
swap(I, I + 4, !B).
move(I, left, !B) :-
not (I = 0 ; I = 4 ; I = 8 ; I = 12),
swap(I, I - 1, !B).
move(I, right, !B) :-
not (I = 3 ; I = 7 ; I = 11 ; I = 15),
swap(I, I + 1, !B). |
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.
| #PHP | PHP |
<?php
$game = new Game();
while(true) {
$game->cycle();
}
class Game {
private $field;
private $fieldSize;
private $command;
private $error;
private $lastIndexX, $lastIndexY;
private $score;
private $finishScore;
function __construct() {
$this->field = array();
$this->fieldSize = 4;
$this->finishScore = 2048;
$this->score = 0;
$this->addNumber();
$this->render();
}
public function cycle() {
$this->command = strtolower($this->readchar('Use WASD, q exits'));
$this->cls();
if($this->processCommand()) {
$this->addNumber();
} else {
if(count($this->getFreeList()) == 0 ) {
$this->error = 'No options left!, You Lose!!';
} else {
$this->error = 'Invalid move, try again!';
}
}
$this->render();
}
private function readchar($prompt) {
readline_callback_handler_install($prompt, function() {});
$char = stream_get_contents(STDIN, 1);
readline_callback_handler_remove();
return $char;
}
/**
* Insert a number in an empty spot on the field
*/
private function addNumber() {
$freeList = $this->getFreeList();
if(count($freeList) == 0) {
return;
}
$index = mt_rand(0, count($freeList)-1);
$nr = (mt_rand(0,9) == 0)? 4 : 2;
$this->field[$freeList[$index]['x']][$freeList[$index]['y']] = $nr;
return;
}
/**
* @return array(array('x' => <x>, 'y' => <y>)) with empty positions in the field
*/
private function getFreeList() {
$freeList = array();
for($y =0; $y< $this->fieldSize;$y++) {
for($x=0; $x < $this->fieldSize; $x++) {
if(!isset($this->field[$x][$y])) {
$freeList[] = array('x' => $x, 'y' => $y);
} elseif($this->field[$x][$y] == $this->finishScore) {
$this->error = 'You Win!!';
}
}
}
return $freeList;
}
/**
* Process a command:
* @return is the command valid (Did it cause a change in the field)
*/
private function processCommand() {
if(!in_array($this->command, array('w','a','s','d','q'))) {
$this->error = 'Invalid Command';
return false;
}
if($this->command == 'q') {
echo PHP_EOL. 'Bye!'. PHP_EOL;
exit;
}
// Determine over which axis and in which direction we move:
$axis = 'x';
$sDir = 1;
switch($this->command) {
case 'w':
$axis = 'y';
$sDir = -1;
break;
case 'a':
$sDir = -1;
break;
case 's':
$axis = 'y';
break;
case 'd':
break;
}
$done = 0;
// shift all numbers in that direction
$done += $this->shift($axis, $sDir);
// merge equal numbers in opposite direction
$done += $this->merge($axis, $sDir * -1);
// shift merged numbers in that direction
$done += $this->shift($axis, $sDir);
return $done >0;
}
private function shift($axis, $dir) {
$totalDone = 0;
for($i = 0; $i <$this->fieldSize; $i++) {
$done = 0;
foreach($this->iterate($axis,$dir) as $xy) {
if($xy['vDest'] === NULL && $xy['vSrc'] !== NULL) {
$this->field[$xy['dX']][$xy['dY']] = $xy['vSrc'];
$this->field[$xy['sX']][$xy['sY']] = NULL;
$done++;
}
}
$totalDone += $done;
if($done == 0) {
// nothing to shift anymore
break;
}
}
return $totalDone;
}
private function merge($axis, $dir) {
$done = 0;
foreach($this->iterate($axis,$dir) as $xy) {
if($xy['vDest'] !== NULL && $xy['vDest'] === $xy['vSrc']) {
$this->field[$xy['sX']][$xy['sY']] += $xy['vDest'];
$this->field[$xy['dX']][$xy['dY']] = NULL;
$this->score += $this->field[$xy['sX']][$xy['sY']];
$done ++;
}
}
return $done;
}
/**
* @return array List of src, dest pairs and their values to iterate over.
*/
private function iterate($axis, $dir) {
$res = array();
for($y = 0; $y < $this->fieldSize; $y++) {
for($x=0; $x < $this->fieldSize; $x++) {
$item = array('sX'=> $x,'sY' => $y, 'dX' => $x, 'dY' => $y, 'vDest' => NULL,'vSrc' => NULL);
if($axis == 'x') {
$item['dX'] += $dir;
} else {
$item['dY'] += $dir;
}
if($item['dX'] >= $this->fieldSize || $item['dY'] >=$this->fieldSize || $item['dX'] < 0 || $item['dY'] < 0) {
continue;
}
$item['vDest'] = (isset($this->field[$item['dX']][$item['dY']]))? $this->field[$item['dX']][$item['dY']] : NULL;
$item['vSrc'] = (isset($this->field[$item['sX']][$item['sY']]))? $this->field[$item['sX']][$item['sY']] : NULL;
$res[] = $item;
}
}
if($dir < 0) {
$res = array_reverse($res);
}
return $res;
}
/// RENDER ///
/**
* Clear terminal screen
*/
private function cls() {
echo chr(27).chr(91).'H'.chr(27).chr(91).'J';
}
private function render() {
echo $this->finishScore . '! Current score: '. $this->score .PHP_EOL;
if(!empty($this->error)) {
echo $this->error . PHP_EOL;
$this->error = NULL;
}
$this->renderField();
}
private function renderField() {
$width = 5;
$this->renderVSeperator($width);
for($y =0; $y < $this->fieldSize; $y ++) {
for($x = 0;$x < $this->fieldSize; $x++) {
echo '|';
if(!isset($this->field[$x][$y])) {
echo str_repeat(' ', $width);
continue;
}
printf('%'.$width.'s', $this->field[$x][$y]);
}
echo '|'. PHP_EOL;
$this->renderVSeperator($width);
}
}
private function renderVSeperator($width) {
echo str_repeat('+'. str_repeat('-', $width), $this->fieldSize) .'+' .PHP_EOL;
}
}
|
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
| #Chapel | Chapel |
/***********************************************************************
* Chapel implementation of "99 bottles of beer"
*
* by Brad Chamberlain and Steve Deitz
* 07/13/2006 in Knoxville airport while waiting for flight home from
* HPLS workshop
* compiles and runs with chpl compiler version 1.7.0
* for more information, contact: [email protected]
*
*
* Notes:
* o as in all good parallel computations, boundary conditions
* constitute the vast bulk of complexity in this code (invite Brad to
* tell you about his zany boundary condition simplification scheme)
* o uses type inference for variables, arguments
* o relies on integer->string coercions
* o uses named argument passing (for documentation purposes only)
***********************************************************************/
// allow executable command-line specification of number of bottles
// (e.g., ./a.out -snumBottles=999999)
config const numBottles = 99;
const numVerses = numBottles+1;
// a domain to describe the space of lyrics
var LyricsSpace: domain(1) = {1..numVerses};
// array of lyrics
var Lyrics: [LyricsSpace] string;
// parallel computation of lyrics array
[verse in LyricsSpace] Lyrics(verse) = computeLyric(verse);
// as in any good parallel language, I/O to stdout is serialized.
// (Note that I/O to a file could be parallelized using a parallel
// prefix computation on the verse strings' lengths with file seeking)
writeln(Lyrics);
// HELPER FUNCTIONS:
proc computeLyric(verseNum) {
var bottleNum = numBottles - (verseNum - 1);
var nextBottle = (bottleNum + numVerses - 1)%numVerses;
return "\n" // disguise space used to separate elements in array I/O
+ describeBottles(bottleNum, startOfVerse=true) + " on the wall, "
+ describeBottles(bottleNum) + ".\n"
+ computeAction(bottleNum)
+ describeBottles(nextBottle) + " on the wall.\n";
}
proc describeBottles(bottleNum, startOfVerse:bool = false) {
// NOTE: bool should not be necessary here (^^^^); working around bug
var bottleDescription = if (bottleNum) then bottleNum:string
else (if startOfVerse then "N"
else "n")
+ "o more";
return bottleDescription
+ " bottle" + (if (bottleNum == 1) then "" else "s")
+ " of beer";
}
proc computeAction(bottleNum) {
return if (bottleNum == 0) then "Go to the store and buy some more, "
else "Take one down and pass it around, ";
}
|
http://rosettacode.org/wiki/24_game | 24 game | The 24 Game tests one's mental arithmetic.
Task
Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed.
The program should prompt for the player to enter an arithmetic expression using just those, and all of those four digits, used exactly once each. 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.
| #Nim | Nim | from random import randomize, rand
from strutils import Whitespace
from algorithm import sort
from sequtils import newSeqWith
randomize()
var
problem = newSeqWith(4, rand(1..9))
stack: seq[float]
digits: seq[int]
echo "Make 24 with the digits: ", problem
template op(c: untyped) =
let a = stack.pop
stack.add c(stack.pop, a)
for c in stdin.readLine:
case c
of '1'..'9':
digits.add c.ord - '0'.ord
stack.add float(c.ord - '0'.ord)
of '+': op `+`
of '*': op `*`
of '-': op `-`
of '/': op `/`
of Whitespace: discard
else: raise newException(ValueError, "Wrong char: " & c)
sort digits
sort problem
if digits != problem:
raise newException(ValueError, "Not using the given digits.")
if stack.len != 1:
raise newException(ValueError, "Wrong expression.")
echo "Result: ", stack[0]
echo if abs(stack[0] - 24) < 0.001: "Good job!" else: "Try again." |
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
| #FALSE | FALSE | [0[^$$'9>'0@>|~]['0-\10*+]#%]n: {read an integer}
n;!n;!+. |
http://rosettacode.org/wiki/ABC_problem | ABC problem | ABC problem
You are encouraged to solve this task according to the task description, using any language you may know.
You are given a collection of ABC blocks (maybe like the ones you had when you were a kid).
There are twenty blocks with two letters on each block.
A complete alphabet is guaranteed amongst all 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
| #Perl | Perl | #!/usr/bin/perl
use warnings;
use strict;
sub can_make_word {
my ($word, @blocks) = @_;
$_ = uc join q(), sort split // for @blocks;
my %blocks;
$blocks{$_}++ for @blocks;
return _can_make_word(uc $word, %blocks)
}
sub _can_make_word {
my ($word, %blocks) = @_;
my $char = substr $word, 0, 1, q();
my @candidates = grep 0 <= index($_, $char), keys %blocks;
for my $candidate (@candidates) {
next if $blocks{$candidate} <= 0;
local $blocks{$candidate} = $blocks{$candidate} - 1;
return 1 if q() eq $word or _can_make_word($word, %blocks);
}
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.
| #Processing | Processing | IntList drawers = new IntList();
int trials = 100000;
int succes_count;
void setup() {
for (int i = 0; i < 100; i++) {
drawers.append(i);
}
println(trials + " trials\n");
//Random strategy
println("Random strategy");
succes_count = trials;
for (int i = 0; i < trials; i++) {
drawers.shuffle();
for (int prisoner = 0; prisoner < 100; prisoner++) {
boolean found = false;
for (int attempt = 0; attempt < 50; attempt++) {
if (drawers.get(int(random(drawers.size()))) == prisoner) {
found = true;
break;
}
}
if (!found) {
succes_count--;
break;
}
}
}
println(" Succeses: " + succes_count);
println(" Succes rate: " + 100.0 * succes_count / trials + "%\n");
//Optimal strategy
println("Optimal strategy");
succes_count = trials;
for (int i = 0; i < trials; i++) {
drawers.shuffle();
for (int prisoner = 0; prisoner < 100; prisoner++) {
boolean found = false;
int next = prisoner;
for (int attempt = 0; attempt < 50; attempt++) {
next = drawers.get(next);
if (next == prisoner) {
found = true;
break;
}
}
if (!found) {
succes_count--;
break;
}
}
}
println(" Succeses: " + succes_count);
print(" Succes rate: " + 100.0 * succes_count / trials + "%");
} |
http://rosettacode.org/wiki/24_game/Solve | 24 game/Solve | task
Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the 24 game.
Show examples of solutions generated by the program.
Related task
Arithmetic Evaluator
| #Ursala | Ursala | #import std
#import nat
#import rat
tree_shapes = "n". (@vLPiYo //eql iota "n")*~ (rep"n" ~&iiiK0NlrNCCVSPTs) {0^:<>}
with_leaves = ^|DrlDrlK34SPSL/permutations ~&
with_roots = ^DrlDrlK35dlPvVoPSPSL\~&r @lrhvdNCBvLPTo2DlS @hiNCSPtCx ~&K0=>
value = *^ ~&v?\(@d ~&\1) ^|H\~&hthPX '+-*/'-$<sum,difference,product,quotient>
format = *^ ~&v?\-+~&h,%zP@d+- ^H/mat@d *v ~&t?\~& :/`(+ --')'
game"n" "d" = format* value==("n",1)*~ with_roots/'+-*/' with_leaves/"d"*-1 tree_shapes length "d" |
http://rosettacode.org/wiki/15_puzzle_game | 15 puzzle game |
Task
Implement the Fifteen Puzzle Game.
The 15-puzzle is also known as:
Fifteen Puzzle
Gem Puzzle
Boss Puzzle
Game of Fifteen
Mystic Square
14-15 Puzzle
and some others.
Related Tasks
15 Puzzle Solver
16 Puzzle Game
| #MUMPS | MUMPS | 15Game ;
; setting the layout
f i=1:1:15 s box(i)=16-i
; no number for box 16
s box(16)=""
f {
; initialise i for incrementation
s i=0
; write out the 4-by-4 box
f row=1:1:4 {
w !?20
f column=1:1:4 {
s i=$i(i)
w $j(box(i),2)," "
}
}
r !!,"Enter number to move (q to quit): ",number
q:number="q"
f i=1:1:16 q:box(i)=""
if box(i)="" {
if i>4,number=box(i-4) {
s box(i)=number,box(i-4)=""
w !!
}
elseif i>1,i'=5,i'=9,i'=13,number=box(i-1) {
s box(i)=number,box(i-1)=""
w !!
}
elseif i<16,i'=4,i'=8,i'=12,number=box(i+1) {
s box(i)=number,box(i+1)=""
w !!
}
elseif i<13,number=box(i+4) {
s box(i)=number,box(i+4)=""
w !!
}
else {
w !,"You have to enter a number either above, below, left or right of the empty space."
}
}
}
q
|
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.
| #PicoLisp | PicoLisp | (load "@lib/simul.l")
(symbols 'simul 'pico)
(seed (in "/dev/urandom" (rd 8)))
(setq *G (grid 4 4) *D NIL)
(de cell ()
(use This
(while
(get
(setq This
(intern
(pack
(char (+ 96 (rand 1 4)))
(rand 1 4) ) ) )
'N ) )
(=: N (if (> 90 (rand 1 100)) 2 4) ) )
(setq *D (fish '((This) (: N)) *G)) )
(de redraw (G S D)
# zeroize *G
(mapc
'((I)
(mapc '((This) (=: N NIL)) I) )
*G )
# draw again
(mapc
'((X This)
(while (and This X)
(=: N (pop 'X))
(setq This (D This)) ) )
G
S ) )
(de summ (Lst)
(mapcar
'((L)
(make
(while L
(ifn (= (car L) (cadr L))
(link (car L))
(link (+ (car L) (cadr L)))
(pop 'L) )
(pop 'L) ) ) )
Lst ) )
(de vertical ()
(mapcar
'((X) (extract '((This) (: N)) X))
*G ) )
(de horizontal ()
(mapcar
'((This)
(make
(while This
(when (: N) (link @))
(setq This (east This)) ) ) )
(car *G) ) )
(de finish? ()
(nor
(fish
'((This)
(when (atom This) (= NIL (: N))) )
*G )
(find
'((L)
(find
'((This)
(when (: N)
(find
'((D)
(= (: N) (get (D This) 'N)) )
(quote north south west east) ) ) )
L ) )
*G ) ) )
(de board (D)
(space 3)
(prin '+)
(for I G
(prin (if (D (car I)) " +" "---+")) )
(prinl) )
(de display ()
(let G (mapcar reverse *G)
(board north)
(while (caar G)
(space 3)
(prin '|)
(for I G
(with (car I)
(prin
(if (: N) (align 3 (: N)) " ")
(if (east This) " " '|) ) ) )
(prinl)
(board south)
(map pop G) )
(do 2
(prinl) ) ) )
(do 2
(cell) )
(display)
(loop
(case
(pack
(make
(link (key))
(while (key 100)
(link @) ) ) )
("^[[D" #left
(redraw (summ (horizontal)) '(a1 a2 a3 a4) east) )
("^[[C" #rigth
(redraw
(summ (mapcar reverse (horizontal)))
'(d1 d2 d3 d4)
west) )
("^[[B" #down
(redraw (summ (vertical)) '(a1 b1 c1 d1) north) )
("^[[A" #up
(redraw
(summ (mapcar reverse (vertical)))
'(a4 b4 c4 d4)
south) ) )
(when (diff *D (fish '((This) (: N)) *G))
(cell) )
(display)
(T (finish?) (println 'Finish))
(T (fish '((This) (= 512 (: N))) *G)
(println 'Maximum) ) )
(bye) |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.