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/4-rings_or_4-squares_puzzle | 4-rings or 4-squares puzzle | 4-rings or 4-squares puzzle
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Replace a, b, c, d, e, f, and
g with the decimal
digits LOW ───► HIGH
such that the sum of the letters inside of each of the four large squares add up to
the same sum.
╔══════════════╗ ╔══════════════╗
║ ║ ║ ║
║ a ║ ║ e ║
║ ║ ║ ║
║ ┌───╫──────╫───┐ ┌───╫─────────┐
║ │ ║ ║ │ │ ║ │
║ │ b ║ ║ d │ │ f ║ │
║ │ ║ ║ │ │ ║ │
║ │ ║ ║ │ │ ║ │
╚══════════╪═══╝ ╚═══╪══════╪═══╝ │
│ c │ │ g │
│ │ │ │
│ │ │ │
└──────────────┘ └─────────────┘
Show all output here.
Show all solutions for each letter being unique with
LOW=1 HIGH=7
Show all solutions for each letter being unique with
LOW=3 HIGH=9
Show only the number of solutions when each letter can be non-unique
LOW=0 HIGH=9
Related task
Solve the no connection puzzle
| #VBA | VBA | Dim a As Integer, b As Integer, c As Integer, d As Integer
Dim e As Integer, f As Integer, g As Integer
Dim lo As Integer, hi As Integer, unique As Boolean, show As Boolean
Dim solutions As Integer
Private Sub bf()
For f = lo To hi
If ((Not unique) Or _
((f <> a And f <> c And f <> d And f <> g And f <> e))) Then
b = e + f - c
If ((b >= lo) And (b <= hi) And _
((Not unique) Or ((b <> a) And (b <> c) And _
(b <> d) And (b <> g) And (b <> e) And (b <> f)))) Then
solutions = solutions + 1
If show Then Debug.Print a; b; c; d; e; f; g
End If
End If
Next
End Sub
Private Sub ge()
For e = lo To hi
If ((Not unique) Or ((e <> a) And (e <> c) And (e <> d))) Then
g = d + e
If ((g >= lo) And (g <= hi) And _
((Not unique) Or ((g <> a) And (g <> c) And _
(g <> d) And (g <> e)))) Then
bf
End If
End If
Next
End Sub
Private Sub acd()
For c = lo To hi
For d = lo To hi
If ((Not unique) Or (c <> d)) Then
a = c + d
If ((a >= lo) And (a <= hi) And _
((Not unique) Or ((c <> 0) And (d <> 0)))) Then
ge
End If
End If
Next d
Next c
End Sub
Private Sub foursquares(plo As Integer, phi As Integer, punique As Boolean, pshow As Boolean)
lo = plo
hi = phi
unique = punique
show = pshow
solutions = 0
acd
Debug.Print
If unique Then
Debug.Print solutions; " unique solutions in"; lo; "to"; hi
Else
Debug.Print solutions; " non-unique solutions in"; lo; "to"; hi
End If
End Sub
Public Sub program()
Call foursquares(1, 7, True, True)
Debug.Print
Call foursquares(3, 9, True, True)
Call foursquares(0, 9, False, False)
End Sub
|
http://rosettacode.org/wiki/99_bottles_of_beer | 99 bottles of beer | Task
Display the complete lyrics for the song: 99 Bottles of Beer on the Wall.
The beer song
The lyrics follow this form:
99 bottles of beer on the wall
99 bottles of beer
Take one down, pass it around
98 bottles of beer on the wall
98 bottles of beer on the wall
98 bottles of beer
Take one down, pass it around
97 bottles of beer on the wall
... and so on, until reaching 0 (zero).
Grammatical support for 1 bottle of beer is optional.
As with any puzzle, try to do it in as creative/concise/comical a way
as possible (simple, obvious solutions allowed, too).
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
See also
http://99-bottles-of-beer.net/
Category:99_Bottles_of_Beer
Category:Programming language families
Wikipedia 99 bottles of beer
| #AutoHotkey | AutoHotkey | # usage: gawk -v i=6 -f beersong.awk
function bb(n) {
b = " bottles of beer"
if( n==1 ) { sub("s","",b) }
if( n==0 ) { n="No more" }
return n b
}
BEGIN {
if( !i ) { i = 99 }
ow = "on the wall"
td = "Take one down, pass it around."
print "The beersong:\n"
while (i > 0) {
printf( "%s %s,\n%s.\n%s\n%s %s.\n\n",
bb(i), ow, bb(i), td, bb(--i), ow )
if( i==1 ) sub( "one","it", td )
}
print "Go to the store and buy some more!"
} |
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.
| #HicEst | HicEst | DIMENSION digits(4), input_digits(100), difference(4)
CHARACTER expression*100, prompt*100, answers='Wrong,Correct,', protocol='24 game.txt'
1 digits = CEILING( RAN(9) )
2 DLG(Edit=expression, Text=digits, TItle=prompt)
READ(Text=expression, ItemS=n) input_digits
IF(n == 4) THEN
ALIAS(input_digits,1, input,4)
SORT(Vector=digits, Sorted=digits)
SORT(Vector=input, Sorted=input)
difference = ABS(digits - input)
IF( SUM(difference) == 0 ) THEN
EDIT(Text=expression, ScaNnot='123456789+-*/ ()', GetPos=i, CoPyto=prompt)
IF( i > 0 ) THEN
prompt = TRIM(expression) // ': ' //TRIM(prompt) // ' is an illegal character'
ELSE
prompt = TRIM(expression) // ': Syntax error'
result = XEQ(expression, *2) ! on error branch to label 2
EDIT(Text=answers, ITeM=(result==24)+1, Parse=answer)
WRITE(Text=prompt, Name) TRIM(expression)//': ', answer, result
ENDIF
ELSE
WRITE(Text=prompt) TRIM(expression), ': You used ', input, ' instead ', digits
ENDIF
ELSE
prompt = TRIM(expression) // ': Instead 4 digits you used ' // n
ENDIF
OPEN(FIle=protocol, APPend)
WRITE(FIle=protocol, CLoSe=1) prompt
DLG(TItle=prompt, Button='>2:Try again', B='>1:New game', B='Quit')
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
| #DMS | DMS | number a = GetNumber( "Please input 'a'", a, a ) // prompts for 'a'
number b = GetNumber( "Please input 'b'", b, b ) // prompts for 'b'
Result( a + b + "\n" ) |
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #XPL0 | XPL0 | include c:\cxpl\codes;
func Ackermann(M, N);
int M, N;
[if M=0 then return N+1;
if N=0 then return Ackermann(M-1, 1);
return Ackermann(M-1, Ackermann(M, N-1));
]; \Ackermann
int M, N;
[for M:= 0 to 3 do
[for N:= 0 to 7 do
[IntOut(0, Ackermann(M, N)); ChOut(0,9\tab\)];
CrLf(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
| #Jsish | Jsish | #!/usr/bin/env jsish
/* ABC problem, in Jsish. Can word be spelled with the given letter blocks. */
var blocks = "BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM";
function CheckWord(blocks, word) {
var re = /([a-z]*)/i;
if (word !== re.exec(word)[0]) return false;
for (var i = 0; i < word.length; i++) {
var letter = word.charAt(i);
var length = blocks.length;
// trying both sides
var reg = new RegExp("([a-z]"+letter + "|" + letter+"[a-z])", "i");
// remove block once a letter is used
blocks = blocks.replace(reg, "");
if (blocks.length === length) return false;
}
return true;
};
var words = [ "A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "CONFUSE" ];
puts("Using blocks:", blocks);
for(var i = 0; i<words.length; i++)
puts(CheckWord(blocks, words[i]) ? "can" : "can't", "spell", words[i]);
/*
=!EXPECTSTART!=
Using blocks: BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM
can spell A
can spell BARK
can't spell BOOK
can spell TREAT
can't spell COMMON
can spell SQUAD
can spell CONFUSE
=!EXPECTEND!=
*/ |
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.
| #Haskell | Haskell | import System.Random
import Control.Monad.State
numRuns = 10000
numPrisoners = 100
numDrawerTries = 50
type Drawers = [Int]
type Prisoner = Int
type Prisoners = [Int]
main = do
gen <- getStdGen
putStrLn $ "Chance of winning when choosing randomly: " ++ (show $ evalState runRandomly gen)
putStrLn $ "Chance of winning when choosing optimally: " ++ (show $ evalState runOptimally gen)
runRandomly :: State StdGen Double
runRandomly =
let runResults = replicateM numRuns $ do
drawers <- state $ shuffle [1..numPrisoners]
allM (\prisoner -> openDrawersRandomly drawers prisoner numDrawerTries) [1..numPrisoners]
in ((/ fromIntegral numRuns) . fromIntegral . sum . map fromEnum) `liftM` runResults
openDrawersRandomly :: Drawers -> Prisoner -> Int -> State StdGen Bool
openDrawersRandomly drawers prisoner triesLeft = go triesLeft []
where go 0 _ = return False
go triesLeft seenDrawers = do
try <- state $ randomR (1, numPrisoners)
case try of
x | x == prisoner -> return True
| x `elem` seenDrawers -> go triesLeft seenDrawers
| otherwise -> go (triesLeft - 1) (x:seenDrawers)
runOptimally :: State StdGen Double
runOptimally =
let runResults = replicateM numRuns $ do
drawers <- state $ shuffle [1..numPrisoners]
return $ all (\prisoner -> openDrawersOptimally drawers prisoner numDrawerTries) [1..numPrisoners]
in ((/ fromIntegral numRuns) . fromIntegral . sum . map fromEnum) `liftM` runResults
openDrawersOptimally :: Drawers -> Prisoner -> Int -> Bool
openDrawersOptimally drawers prisoner triesLeft = go triesLeft prisoner
where go 0 _ = False
go triesLeft drawerToTry =
let thisDrawer = drawers !! (drawerToTry - 1)
in if thisDrawer == prisoner then True else go (triesLeft - 1) thisDrawer
-- Haskel stdlib is lacking big time, so here some necessary 'library' functions
-- make a list of 'len' random values in range 'range' from 'gen'
randomLR :: Integral a => Random b => a -> (b, b) -> StdGen -> ([b], StdGen)
randomLR 0 range gen = ([], gen)
randomLR len range gen =
let (x, newGen) = randomR range gen
(xs, lastGen) = randomLR (len - 1) range newGen
in (x : xs, lastGen)
-- shuffle a list by a generator
shuffle :: [a] -> StdGen -> ([a], StdGen)
shuffle list gen = (shuffleByNumbers numbers list, finalGen)
where
n = length list
(numbers, finalGen) = randomLR n (0, n-1) gen
shuffleByNumbers :: [Int] -> [a] -> [a]
shuffleByNumbers [] _ = []
shuffleByNumbers _ [] = []
shuffleByNumbers (i:is) xs = let (start, x:rest) = splitAt (i `mod` length xs) xs
in x : shuffleByNumbers is (start ++ rest)
-- short-circuit monadic all
allM :: Monad m => (a -> m Bool) -> [a] -> m Bool
allM func [] = return True
allM func (x:xs) = func x >>= \res -> if res then allM func xs else return False
|
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
| #Nim | Nim | import algorithm, sequtils, strformat
type
Operation = enum
opAdd = "+"
opSub = "-"
opMul = "*"
opDiv = "/"
const Ops = @[opAdd, opSub, opMul, opDiv]
func opr(o: Operation, a, b: float): float =
case o
of opAdd: a + b
of opSub: a - b
of opMul: a * b
of opDiv: a / b
func solve(nums: array[4, int]): string =
func `~=`(a, b: float): bool =
abs(a - b) <= 1e-5
result = "not found"
let sortedNums = nums.sorted.mapIt float it
for i in product Ops.repeat 3:
let (x, y, z) = (i[0], i[1], i[2])
var nums = sortedNums
while true:
let (a, b, c, d) = (nums[0], nums[1], nums[2], nums[3])
if x.opr(y.opr(a, b), z.opr(c, d)) ~= 24.0:
return fmt"({a:0} {y} {b:0}) {x} ({c:0} {z} {d:0})"
if x.opr(a, y.opr(b, z.opr(c, d))) ~= 24.0:
return fmt"{a:0} {x} ({b:0} {y} ({c:0} {z} {d:0}))"
if x.opr(y.opr(z.opr(c, d), b), a) ~= 24.0:
return fmt"(({c:0} {z} {d:0}) {y} {b:0}) {x} {a:0}"
if x.opr(y.opr(b, z.opr(c, d)), a) ~= 24.0:
return fmt"({b:0} {y} ({c:0} {z} {d:0})) {x} {a:0}"
if not nextPermutation(nums): break
proc main() =
for nums in [
[9, 4, 4, 5],
[1, 7, 2, 7],
[5, 7, 5, 4],
[1, 4, 6, 6],
[2, 3, 7, 3],
[8, 7, 9, 7],
[1, 6, 2, 6],
[7, 9, 4, 1],
[6, 4, 2, 2],
[5, 7, 9, 7],
[3, 3, 8, 8], # Difficult case requiring precise division
]:
echo fmt"solve({nums}) -> {solve(nums)}"
when isMainModule: main() |
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
| #Common_Lisp | Common Lisp | |15|::main |
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.
| #Forth | Forth | \ in Forth, you do many things on your own. This word is used to define 2D arrays
: 2D-ARRAY ( height width )
CREATE DUP ,
* CELLS ALLOT
DOES> ( y x baseaddress )
ROT ( x baseaddress y )
OVER @ ( x baseaddress y width )
* ( x baseaddress y*width )
ROT ( baseaddress y*width x )
+ 1+ CELLS +
;
require random.fs
HERE SEED !
0 CONSTANT D-INVALID
1 CONSTANT D-UP
2 CONSTANT D-DOWN
3 CONSTANT D-LEFT
4 CONSTANT D-RIGHT
4 CONSTANT NROWS
4 CONSTANT NCOLS
NROWS NCOLS * CONSTANT GRIDSIZE
NROWS NCOLS 2D-ARRAY GRID
CREATE HAVE-MOVED CELL ALLOT
CREATE TOTAL-SCORE CELL ALLOT
CREATE MOVE-SCORE CELL ALLOT
: DIE-DIRECTIONCONST ." Unknown direction constant:" . BYE ;
: ESC #ESC EMIT ;
: CLS
ESC ." [2J"
ESC ." [H"
;
: GRID-VALUE 1 SWAP LSHIFT ;
: DASHES 0 ?DO [CHAR] - EMIT LOOP ;
: DRAW ( -- )
CLS ." Score: "
TOTAL-SCORE @ 0 U.R
MOVE-SCORE @ ?DUP IF
." (+" 0 U.R ." )"
THEN
CR 25 DASHES CR
NROWS 0 ?DO
." |"
NCOLS 0 ?DO
J I GRID @ ?DUP IF
GRID-VALUE 4 U.R
ELSE
4 SPACES
THEN
." |"
LOOP
CR
LOOP
25 DASHES CR
;
: COUNT-FREE-SPACES ( -- free-spaces )
0 ( count )
NROWS 0 ?DO
NCOLS 0 ?DO
J I GRID @ 0= IF 1+ THEN
LOOP
LOOP
;
: GET-FREE-SPACE ( index -- addr )
0 0 GRID SWAP ( curr-addr index )
0 0 GRID @ 0<> IF 1+ THEN
0 ?DO ( find the next free space index times )
BEGIN
CELL+ DUP @ 0=
UNTIL
LOOP
;
: NEW-BLOCK ( -- )
COUNT-FREE-SPACES
DUP 0<= IF DROP EXIT THEN
RANDOM GET-FREE-SPACE
10 RANDOM 0= IF 2 ELSE 1 THEN SWAP !
;
: 2GRID ( a-y a-x b-y b-x -- a-addr b-addr ) GRID -ROT GRID SWAP ;
: CAN-MERGE ( dest-addr other-addr -- can-merge? )
@ SWAP @ ( other-val dest-val )
DUP 0<> -ROT = AND
;
: CAN-GRAVITY ( dest-addr other-addr -- can-gravity? )
@ SWAP @ ( other-val dest-val )
0= SWAP 0<> AND
;
: TRY-MERGE ( dest-y dest-x other-y other-x -- )
2GRID ( dest-addr other-addr )
2DUP CAN-MERGE IF
TRUE HAVE-MOVED !
0 SWAP ! ( dest-addr )
DUP @ 1+ DUP ( dest-addr dest-val dest-val )
ROT ! ( dest-val )
GRID-VALUE DUP ( score-diff score-diff )
MOVE-SCORE +!
TOTAL-SCORE +!
ELSE
2DROP
THEN
;
: TRY-GRAVITY ( did-something-before operator dest-y dest-x other-y other-x -- did-something-after operator )
2GRID ( ... dest-addr other-addr )
2DUP CAN-GRAVITY IF
TRUE HAVE-MOVED !
DUP @ ( ... dest-addr other-addr other-val )
ROT ( ... other-addr other-val dest-addr ) ! ( ... other-addr )
0 SWAP !
NIP TRUE SWAP
ELSE
2DROP
THEN
;
: TRY-LOST? ( lost-before operator dy dx oy ox -- lost-after operator )
2GRID CAN-MERGE INVERT ( lost-before operator lost-now )
ROT AND SWAP ( lost-after operator )
;
: MOVEMENT-LOOP ( direction operator -- ) CASE
SWAP
D-UP OF NROWS 1- 0 ?DO
NCOLS 0 ?DO
J I J 1+ I 4 PICK EXECUTE
LOOP
LOOP ENDOF
D-DOWN OF 1 NROWS 1- ?DO
NCOLS 0 ?DO
J I J 1- I 4 PICK EXECUTE
LOOP
-1 +LOOP ENDOF
D-LEFT OF NCOLS 1- 0 ?DO
NROWS 0 ?DO
I J I J 1+ 4 PICK EXECUTE
LOOP
LOOP ENDOF
D-RIGHT OF 1 NCOLS 1- ?DO
NROWS 0 ?DO
I J I J 1- 4 PICK EXECUTE
LOOP
-1 +LOOP ENDOF
DIE-DIRECTIONCONST
ENDCASE DROP ;
: MERGE ( move -- ) ['] TRY-MERGE MOVEMENT-LOOP ;
: GRAVITY-ONCE ( move -- success? ) FALSE SWAP ['] TRY-GRAVITY MOVEMENT-LOOP ;
: GRAVITY ( move -- )
BEGIN
DUP GRAVITY-ONCE INVERT
UNTIL DROP
;
: MOVE-LOST? ( move -- lost? ) TRUE SWAP ['] TRY-LOST? MOVEMENT-LOOP ;
: END-IF-LOST ( -- lost? )
COUNT-FREE-SPACES 0= IF
TRUE
5 1 DO I MOVE-LOST? AND LOOP
IF ." You lose!" CR BYE THEN
THEN
;
: END-IF-WON ( -- )
NROWS 0 ?DO
NCOLS 0 ?DO
J I GRID @ GRID-VALUE 2048 = IF ." You win!" CR BYE THEN
LOOP
LOOP
;
: TICK ( move -- )
FALSE HAVE-MOVED !
0 MOVE-SCORE !
DUP GRAVITY DUP MERGE GRAVITY
HAVE-MOVED @ IF NEW-BLOCK DRAW THEN
END-IF-WON
END-IF-LOST
;
: GET-MOVE ( -- move )
BEGIN
KEY CASE
#EOF OF BYE ENDOF
#ESC OF BYE ENDOF
[CHAR] q OF BYE ENDOF
[CHAR] Q OF BYE ENDOF
[CHAR] k OF D-UP TRUE ENDOF
[CHAR] K OF D-UP TRUE ENDOF
[CHAR] j OF D-DOWN TRUE ENDOF
[CHAR] J OF D-DOWN TRUE ENDOF
[CHAR] h OF D-LEFT TRUE ENDOF
[CHAR] H OF D-LEFT TRUE ENDOF
[CHAR] l OF D-RIGHT TRUE ENDOF
[CHAR] L OF D-RIGHT TRUE ENDOF
FALSE SWAP
ENDCASE
UNTIL
;
: INIT ( -- )
NROWS 0 ?DO
NCOLS 0 ?DO
0 J I GRID !
LOOP
LOOP
0 TOTAL-SCORE !
0 MOVE-SCORE !
NEW-BLOCK
NEW-BLOCK
DRAW
;
: MAIN-LOOP ( -- )
BEGIN
GET-MOVE TICK
AGAIN
;
INIT
MAIN-LOOP |
http://rosettacode.org/wiki/4-rings_or_4-squares_puzzle | 4-rings or 4-squares puzzle | 4-rings or 4-squares puzzle
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Replace a, b, c, d, e, f, and
g with the decimal
digits LOW ───► HIGH
such that the sum of the letters inside of each of the four large squares add up to
the same sum.
╔══════════════╗ ╔══════════════╗
║ ║ ║ ║
║ a ║ ║ e ║
║ ║ ║ ║
║ ┌───╫──────╫───┐ ┌───╫─────────┐
║ │ ║ ║ │ │ ║ │
║ │ b ║ ║ d │ │ f ║ │
║ │ ║ ║ │ │ ║ │
║ │ ║ ║ │ │ ║ │
╚══════════╪═══╝ ╚═══╪══════╪═══╝ │
│ c │ │ g │
│ │ │ │
│ │ │ │
└──────────────┘ └─────────────┘
Show all output here.
Show all solutions for each letter being unique with
LOW=1 HIGH=7
Show all solutions for each letter being unique with
LOW=3 HIGH=9
Show only the number of solutions when each letter can be non-unique
LOW=0 HIGH=9
Related task
Solve the no connection puzzle
| #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Dim CA As Char() = "0123456789ABC".ToCharArray()
Sub FourSquare(lo As Integer, hi As Integer, uni As Boolean, sy As Char())
If sy IsNot Nothing Then Console.WriteLine("a b c d e f g" & vbLf & "-------------")
Dim r = Enumerable.Range(lo, hi - lo + 1).ToList(), u As New List(Of Integer),
t As Integer, cn As Integer = 0
For Each a In r
u.Add(a)
For Each b In r
If uni AndAlso u.Contains(b) Then Continue For
u.Add(b)
t = a + b
For Each c In r : If uni AndAlso u.Contains(c) Then Continue For
u.Add(c)
For d = a - c To a - c
If d < lo OrElse d > hi OrElse uni AndAlso u.Contains(d) OrElse
t <> b + c + d Then Continue For
u.Add(d)
For Each e In r
If uni AndAlso u.Contains(e) Then Continue For
u.Add(e)
For f = b + c - e To b + c - e
If f < lo OrElse f > hi OrElse uni AndAlso u.Contains(f) OrElse
t <> d + e + f Then Continue For
u.Add(f)
For g = t - f To t - f : If g < lo OrElse g > hi OrElse
uni AndAlso u.Contains(g) Then Continue For
cn += 1 : If sy IsNot Nothing Then _
Console.WriteLine("{0} {1} {2} {3} {4} {5} {6}",
sy(a), sy(b), sy(c), sy(d), sy(e), sy(f), sy(g))
Next : u.Remove(f) : Next : u.Remove(e) : Next : u.Remove(d)
Next : u.Remove(c) : Next : u.Remove(b) : Next : u.Remove(a)
Next : Console.WriteLine("{0} {1}unique solutions for [{2},{3}]{4}",
cn, If(uni, "", "non-"), lo, hi, vbLf)
End Sub
Sub main()
fourSquare(1, 7, True, CA)
fourSquare(3, 9, True, CA)
fourSquare(0, 9, False, Nothing)
fourSquare(5, 12, True, CA)
End Sub
End Module |
http://rosettacode.org/wiki/99_bottles_of_beer | 99 bottles of beer | Task
Display the complete lyrics for the song: 99 Bottles of Beer on the Wall.
The beer song
The lyrics follow this form:
99 bottles of beer on the wall
99 bottles of beer
Take one down, pass it around
98 bottles of beer on the wall
98 bottles of beer on the wall
98 bottles of beer
Take one down, pass it around
97 bottles of beer on the wall
... and so on, until reaching 0 (zero).
Grammatical support for 1 bottle of beer is optional.
As with any puzzle, try to do it in as creative/concise/comical a way
as possible (simple, obvious solutions allowed, too).
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
See also
http://99-bottles-of-beer.net/
Category:99_Bottles_of_Beer
Category:Programming language families
Wikipedia 99 bottles of beer
| #AutoIt | AutoIt | # usage: gawk -v i=6 -f beersong.awk
function bb(n) {
b = " bottles of beer"
if( n==1 ) { sub("s","",b) }
if( n==0 ) { n="No more" }
return n b
}
BEGIN {
if( !i ) { i = 99 }
ow = "on the wall"
td = "Take one down, pass it around."
print "The beersong:\n"
while (i > 0) {
printf( "%s %s,\n%s.\n%s\n%s %s.\n\n",
bb(i), ow, bb(i), td, bb(--i), ow )
if( i==1 ) sub( "one","it", td )
}
print "Go to the store and buy some more!"
} |
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.
| #Huginn | Huginn | #! /bin/sh
exec huginn --no-argv -E "${0}"
#! huginn
import Algorithms as algo;
import Mathematics as math;
import RegularExpressions as re;
make_game( rndGen_ ) {
board = "";
for ( i : algo.range( 4 ) ) {
board += ( " " + string( character( rndGen_.next() + integer( '1' ) ) ) );
}
return ( board.strip() );
}
main() {
rndGen = math.randomizer( 9 );
no = 0;
dd = re.compile( "\\d\\d" );
while ( true ) {
no += 1;
board = make_game( rndGen );
print( "Your four digits: {}\nExpression {}: ".format( board, no ) );
line = input();
if ( line == none ) {
print( "\n" );
break;
}
line = line.strip();
try {
if ( line == "q" ) {
break;
}
if ( ( pos = line.find_other_than( "{}+-*/() ".format( board ) ) ) >= 0 ) {
print( "Invalid input found at: {}, `{}`\n".format( pos, line ) );
continue;
}
if ( dd.match( line ).matched() ) {
print( "Digit concatenation is forbidden.\n" );
continue;
}
res = real( line );
if ( res == 24.0 ) {
print( "Thats right!\n" );
} else {
print( "Bad answer!\n" );
}
} catch ( Exception e ) {
print( "Not an expression: {}\n".format( e.what() ) );
}
}
return ( 0 );
} |
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
| #Dragon | Dragon |
select "graphic"
select "types"
a = int(prompt("Enter A number"))
b = int(prompt("Enter B number"))
showln a + b
|
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #XSLT | XSLT |
<xsl:template name="ackermann">
<xsl:param name="m"/>
<xsl:param name="n"/>
<xsl:choose>
<xsl:when test="$m = 0">
<xsl:value-of select="$n+1"/>
</xsl:when>
<xsl:when test="$n = 0">
<xsl:call-template name="ackermann">
<xsl:with-param name="m" select="$m - 1"/>
<xsl:with-param name="n" select="'1'"/>
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:variable name="p">
<xsl:call-template name="ackermann">
<xsl:with-param name="m" select="$m"/>
<xsl:with-param name="n" select="$n - 1"/>
</xsl:call-template>
</xsl:variable>
<xsl:call-template name="ackermann">
<xsl:with-param name="m" select="$m - 1"/>
<xsl:with-param name="n" select="$p"/>
</xsl:call-template>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
|
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
| #Julia | Julia | using Printf
function abc(str::AbstractString, list)
isempty(str) && return true
for i in eachindex(list)
str[end] in list[i] &&
any([abc(str[1:end-1], deleteat!(copy(list), i))]) &&
return true
end
return false
end
let test = ["A", "BARK","BOOK","TREAT","COMMON","SQUAD","CONFUSE"],
list = ["BO","XK","DQ","CP","NA","GT","RE","TG","QD","FS",
"JW","HU","VI","AN","OB","ER","FS","LY","PC","ZM"]
for str in test
@printf("%-8s | %s\n", str, abc(str, list))
end
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.
| #J | J |
NB. game is solvable by optimal strategy when the length (#) of the
NB. longest (>./) cycle (C.) is at most 50.
opt=: 50 >: [: >./ [: > [: #&.> C.
NB. for each prisoner randomly open 50 boxes ((50?100){y) and see if
NB. the right card is there (p&e.). if not return 0.
rand=: monad define
for_p. i.100 do. if. -.p e.(50?100){y do. 0 return. end.
end. 1
)
NB. use both strategies on the same shuffles y times.
simulate=: monad define
'o r'=. y %~ 100 * +/ ((rand,opt)@?~)"0 y # 100
('strategy';'win rate'),('random';(":o),'%'),:'optimal';(":r),'%'
) |
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
| #OCaml | OCaml | type expression =
| Const of float
| Sum of expression * expression (* e1 + e2 *)
| Diff of expression * expression (* e1 - e2 *)
| Prod of expression * expression (* e1 * e2 *)
| Quot of expression * expression (* e1 / e2 *)
let rec eval = function
| Const c -> c
| Sum (f, g) -> eval f +. eval g
| Diff(f, g) -> eval f -. eval g
| Prod(f, g) -> eval f *. eval g
| Quot(f, g) -> eval f /. eval g
let print_expr expr =
let open_paren prec op_prec =
if prec > op_prec then print_string "(" in
let close_paren prec op_prec =
if prec > op_prec then print_string ")" in
let rec print prec = function (* prec is the current precedence *)
| Const c -> Printf.printf "%g" c
| Sum(f, g) ->
open_paren prec 0;
print 0 f; print_string " + "; print 0 g;
close_paren prec 0
| Diff(f, g) ->
open_paren prec 0;
print 0 f; print_string " - "; print 1 g;
close_paren prec 0
| Prod(f, g) ->
open_paren prec 2;
print 2 f; print_string " * "; print 2 g;
close_paren prec 2
| Quot(f, g) ->
open_paren prec 2;
print 2 f; print_string " / "; print 3 g;
close_paren prec 2
in
print 0 expr
let rec insert v = function
| [] -> [[v]]
| x::xs as li -> (v::li) :: (List.map (fun y -> x::y) (insert v xs))
let permutations li =
List.fold_right (fun x z -> List.concat (List.map (insert x) z)) li [[]]
let rec comp expr = function
| x::xs ->
comp (Sum (expr, x)) xs;
comp (Diff(expr, x)) xs;
comp (Prod(expr, x)) xs;
comp (Quot(expr, x)) xs;
| [] ->
if (eval expr) = 24.0
then (print_expr expr; print_newline())
;;
let () =
Random.self_init();
let digits = Array.init 4 (fun _ -> 1 + Random.int 9) in
print_string "Input digits: ";
Array.iter (Printf.printf " %d") digits; print_newline();
let digits = Array.to_list(Array.map float_of_int digits) in
let digits = List.map (fun v -> Const v) digits in
let all = permutations digits in
List.iter (function
| x::xs -> comp x xs
| [] -> assert false
) all |
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
| #EasyLang | EasyLang | background 432
textsize 13
len f[] 16
func draw . .
clear
for i range 16
h = f[i]
if h < 16
x = i mod 4 * 24 + 3
y = i div 4 * 24 + 3
color 210
move x y
rect 22 22
move x + 4 y + 5
if h < 10
move x + 6 y + 5
.
color 885
text h
.
.
.
global done .
func init . .
done = 0
for i range 16
f[i] = i + 1
.
# shuffle
for i = 14 downto 1
r = random (i + 1)
swap f[r] f[i]
.
# make it solvable
inv = 0
for i range 15
for j range i
if f[j] > f[i]
inv += 1
.
.
.
if inv mod 2 <> 0
swap f[0] f[1]
.
textsize 12
call draw
.
func move_tile . .
c = mouse_x div 25
r = mouse_y div 25
i = r * 4 + c
if c > 0 and f[i - 1] = 16
swap f[i] f[i - 1]
elif r > 0 and f[i - 4] = 16
swap f[i] f[i - 4]
elif r < 3 and f[i + 4] = 16
swap f[i] f[i + 4]
elif c < 3 and f[i + 1] = 16
swap f[i] f[i + 1]
.
call draw
done = 1
for i range 15
if f[i] > f[i + 1]
done = 0
.
.
if done = 1
clear
move 10 30
text "Well done!"
.
.
on mouse_down
if done = 1
call init
else
call move_tile
.
.
call init |
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.
| #Fortran | Fortran |
WRITE (MSG,1) !Roll forth a top/bottom boundary. No corner characters (etc.), damnit.
1 FORMAT ("|",<NC>(<W>("-"),"|")) !Heavy reliance on runtime values in NC and W. But see FORMAT 22.
2 FORMAT ("|",<NC>(<W>(" "),"|")) !No horizontal markings within a tile. See FORMAT 1.
WRITE (MSG,22) ((" ",L1 = 1,W),"|",C = 1,NC) !Compare to FORMAT 2.
22 FORMAT ("|",666A1) !A constant FORMAT, a tricky WRITE.
4 FORMAT ("|",<NC - 1>(<W>("-"),"+"),<W>("-"),"|") !With internal + rather than |. |
http://rosettacode.org/wiki/4-rings_or_4-squares_puzzle | 4-rings or 4-squares puzzle | 4-rings or 4-squares puzzle
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Replace a, b, c, d, e, f, and
g with the decimal
digits LOW ───► HIGH
such that the sum of the letters inside of each of the four large squares add up to
the same sum.
╔══════════════╗ ╔══════════════╗
║ ║ ║ ║
║ a ║ ║ e ║
║ ║ ║ ║
║ ┌───╫──────╫───┐ ┌───╫─────────┐
║ │ ║ ║ │ │ ║ │
║ │ b ║ ║ d │ │ f ║ │
║ │ ║ ║ │ │ ║ │
║ │ ║ ║ │ │ ║ │
╚══════════╪═══╝ ╚═══╪══════╪═══╝ │
│ c │ │ g │
│ │ │ │
│ │ │ │
└──────────────┘ └─────────────┘
Show all output here.
Show all solutions for each letter being unique with
LOW=1 HIGH=7
Show all solutions for each letter being unique with
LOW=3 HIGH=9
Show only the number of solutions when each letter can be non-unique
LOW=0 HIGH=9
Related task
Solve the no connection puzzle
| #Vlang | Vlang | fn main(){
mut n, mut c := get_combs(1,7,true)
println("$n unique solutions in 1 to 7")
println(c)
n, c = get_combs(3,9,true)
println("$n unique solutions in 3 to 9")
println(c)
n, _ = get_combs(0,9,false)
println("$n non-unique solutions in 0 to 9")
}
fn get_combs(low int,high int,unique bool) (int, [][]int) {
mut num := 0
mut valid_combs := [][]int{}
for a := low; a <= high; a++ {
for b := low; b <= high; b++ {
for c := low; c <= high; c++ {
for d := low; d <= high; d++ {
for e := low; e <= high; e++ {
for f := low; f <= high; f++ {
for g := low; g <= high; g++ {
if valid_comb(a,b,c,d,e,f,g) {
if !unique || is_unique(a,b,c,d,e,f,g) {
num++
valid_combs << [a,b,c,d,e,f,g]
}
}
}
}
}
}
}
}
}
return num, valid_combs
}
fn is_unique(a int,b int,c int,d int,e int,f int,g int) bool {
mut data := map[int]int{}
data[a]++
data[b]++
data[c]++
data[d]++
data[e]++
data[f]++
data[g]++
return data.len == 7
}
fn valid_comb(a int,b int,c int,d int,e int,f int,g int) bool {
square1 := a + b
square2 := b + c + d
square3 := d + e + f
square4 := f + g
return square1 == square2 && square2 == square3 && square3 == square4
} |
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
| #AWK | AWK | # usage: gawk -v i=6 -f beersong.awk
function bb(n) {
b = " bottles of beer"
if( n==1 ) { sub("s","",b) }
if( n==0 ) { n="No more" }
return n b
}
BEGIN {
if( !i ) { i = 99 }
ow = "on the wall"
td = "Take one down, pass it around."
print "The beersong:\n"
while (i > 0) {
printf( "%s %s,\n%s.\n%s\n%s %s.\n\n",
bb(i), ow, bb(i), td, bb(--i), ow )
if( i==1 ) sub( "one","it", td )
}
print "Go to the store and buy some more!"
} |
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.
| #Icon_and_Unicon | Icon and Unicon | invocable all
link strings # for csort, deletec
procedure main()
help()
repeat {
every (n := "") ||:= (1 to 4, string(1+?8))
writes("Your four digits are : ")
every writes(!n," ")
write()
e := trim(read()) | fail
case e of {
"q"|"quit": return
"?"|"help": help()
default: {
e := deletec(e,' \t') # no whitespace
d := deletec(e,~&digits) # just digits
if csort(n) ~== csort(d) then # and only the 4 given digits
write("Invalid repsonse.") & next
if e ? (ans := eval(E()), pos(0)) then # parse and evaluate
if ans = 24 then write("Congratulations you win!")
else write("Your answer was ",ans,". Try again.")
else write("Invalid expression.")
}
}
}
end
procedure eval(X) #: return the evaluated AST
if type(X) == "list" then {
x := eval(get(X))
while x := get(X)(real(x), real(eval(get(X) | stop("Malformed expression."))))
}
return \x | X
end
procedure E() #: expression
put(lex := [],T())
while put(lex,tab(any('+-*/'))) do
put(lex,T())
suspend if *lex = 1 then lex[1] else lex # strip useless []
end
procedure T() #: Term
suspend 2(="(", E(), =")") | # parenthesized subexpression, or ...
tab(any(&digits)) # just a value
end
procedure help()
return write(
"Welcome to 24\n\n",
"Combine the 4 given digits to make 24 using only + - * / and ( ).\n ",
"All operations have equal precedence and are evaluated left to right.\n",
"Combining (concatenating) digits is not allowed.\n",
"Enter 'help', 'quit', or an expression.\n")
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
| #DWScript | DWScript | var a := StrToInt(InputBox('A+B', 'Enter 1st number', '0'));
var b := StrToInt(InputBox('A+B', 'Enter 2nd number', '0'));
ShowMessage('Sum is '+IntToStr(a+b)); |
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #Yabasic | Yabasic | sub ack(M,N)
if M = 0 return N + 1
if N = 0 return ack(M-1,1)
return ack(M-1,ack(M, N-1))
end sub
print ack(3, 4)
|
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
| #Kotlin | Kotlin | object ABC_block_checker {
fun run() {
println("\"\": " + blocks.canMakeWord(""))
for (w in words) println("$w: " + blocks.canMakeWord(w))
}
private fun Array<String>.swap(i: Int, j: Int) {
val tmp = this[i]
this[i] = this[j]
this[j] = tmp
}
private fun Array<String>.canMakeWord(word: String): Boolean {
if (word.isEmpty())
return true
val c = word.first().toUpperCase()
var i = 0
forEach { b ->
if (b.first().toUpperCase() == c || b[1].toUpperCase() == c) {
swap(0, i)
if (drop(1).toTypedArray().canMakeWord(word.substring(1)))
return true
swap(0, i)
}
i++
}
return false
}
private val blocks = arrayOf(
"BO", "XK", "DQ", "CP", "NA", "GT", "RE", "TG", "QD", "FS",
"JW", "HU", "VI", "AN", "OB", "ER", "FS", "LY", "PC", "ZM"
)
private val words = arrayOf("A", "BARK", "book", "treat", "COMMON", "SQuAd", "CONFUSE")
}
fun main(args: Array<String>) = ABC_block_checker.run() |
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.
| #Janet | Janet |
(math/seedrandom (os/cryptorand 8))
(defn drawers
"create list and shuffle it"
[prisoners]
(var x (seq [i :range [0 prisoners]] i))
(loop [i :down [(- prisoners 1) 0]]
(var j (math/floor (* (math/random) (+ i 1))))
(var k (get x i))
(put x i (get x j))
(put x j k))
x)
(defn optimal-play
"optimal decision path"
[prisoners drawers]
(var result 0)
(loop [i :range [0 prisoners]]
(var choice i)
(loop [j :range [0 50] :until (= (get drawers choice) i)]
(set choice (get drawers choice)))
(cond
(= (get drawers choice) i) (++ result)
(break)))
result)
(defn random-play
"random decision path"
[prisoners d]
(var result 0)
(var options (drawers prisoners))
(loop [i :range [0 prisoners]]
(var choice 0)
(loop [j :range [0 (/ prisoners 2)] :until (= (get d j) (get options i))]
(set choice j))
(cond
(= (get d choice) (get options i)) (++ result)
(break)))
result)
(defn main [& args]
(def prisoners 100)
(var optimal-success 0)
(var random-success 0)
(var sims 10000)
(for i 0 sims
(var d (drawers prisoners))
(if (= (optimal-play prisoners d) prisoners)
(++ optimal-success))
(if (= (random-play prisoners d) prisoners)
(++ random-success)))
(printf "Simulation count: %d" sims)
(printf "Optimal play wins: %.1f%%" (* (/ optimal-success sims) 100))
(printf "Random play wins: %.1f%%" (* (/ random-success sims) 100)))
|
http://rosettacode.org/wiki/24_game/Solve | 24 game/Solve | task
Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the 24 game.
Show examples of solutions generated by the program.
Related task
Arithmetic Evaluator
| #Perl | Perl | # Fischer-Krause ordered permutation generator
# http://faq.perl.org/perlfaq4.html#How_do_I_permute_N_e
sub permute (&@) {
my $code = shift;
my @idx = 0..$#_;
while ( $code->(@_[@idx]) ) {
my $p = $#idx;
--$p while $idx[$p-1] > $idx[$p];
my $q = $p or return;
push @idx, reverse splice @idx, $p;
++$q while $idx[$p-1] > $idx[$q];
@idx[$p-1,$q]=@idx[$q,$p-1];
}
}
@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))',
);
# generate all possible combinations of operators
@op = qw( + - * / );
@operators = map{ $a=$_; map{ $b=$_; map{ "$a $b $_" }@op }@op }@op;
while(1)
{
print "Enter four integers or 'q' to exit: ";
chomp($ent = <>);
last if $ent eq 'q';
if($ent !~ /^[1-9] [1-9] [1-9] [1-9]$/){ print "invalid input\n"; next }
@n = split / /,$ent;
permute { push @numbers,join ' ',@_ }@n;
for $format (@formats)
{
for(@numbers)
{
@n = split;
for(@operators)
{
@o = split;
$str = sprintf $format,$n[0],$o[0],$n[1],$o[1],$n[2],$o[2],$n[3];
$r = eval($str);
print "$str\n" if $r == 24;
}
}
}
} |
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
| #F.23 | F# |
// 15 Puzzle Game. Nigel Galloway: August 9th., 2020
let Nr,Nc,RA,rnd=[|3;0;0;0;0;1;1;1;1;2;2;2;2;3;3;3|],[|3;0;1;2;3;0;1;2;3;0;1;2;3;0;1;2|],[|for n in [1..16]->n%16|],System.Random()
let rec fN g Σ=function h::t->fN g (Σ+List.sumBy(fun n->if h>n then 1 else 0)t) t|_->(Σ-g/4)%2=1
let rec fI g=match if System.Console.IsInputRedirected then char(System.Console.Read()) else System.Console.ReadKey(true).KeyChar with
n when Seq.contains n g->printf "%c" n; (match n with 'l'-> -1|'r'->1|'d'->4|_-> -4)|_->System.Console.Beep(); fI g
let rec fG n Σ=function 0->(List.findIndex((=)0)Σ,Σ)|g->let i=List.item(rnd.Next(g)) n in fG(List.except [i] n)(i::Σ)(g-1)
let rec fE()=let n,g=fG [0..15] [] 16 in if fN n 0 (List.except [0] g) then (n,Array.ofList g) else fE()
let rec fL(n,g) Σ=let fa=printfn "";Array.chunkBySize 4 g|>Array.iter(fun n->Array.iter(printf "%3d")n;printfn "")
match g=RA with true->printfn "Solved in %d moves" Σ; fa; 0
|_->let vM=match n/4,n%4 with (0,0)->"rd"|(0,3)->"ld"|(0,_)->"lrd"|(3,0)->"ru"|(3,3)->"lu"|(3,_)->"lru"|(_,0)->"rud"|(_,3)->"lud"|_->"lrud"
fa; printf "Move Number: %2d; Manhatten Distance: %2d; Choose move from %4s: " Σ
([0..15]|>List.sumBy(fun n->match g.[n] with 0->0 |i->(abs(n/4-Nr.[i]))+(abs(n%4-Nc.[i])))) vM
let v=fI vM in g.[n]<-g.[n+v];g.[n+v]<-0;fL(n+v,g)(Σ+1)
[<EntryPoint>]
let main n = fL(match n with [|n|]->let g=[|let g=uint64 n in for n in 60..-4..0->int((g>>>n)&&&15UL)|] in (Array.findIndex((=)0)g,g) |_->fE()) 0
|
http://rosettacode.org/wiki/2048 | 2048 | Task
Implement a 2D sliding block puzzle game where blocks with numbers are combined to add their values.
Rules of the game
The rules are that on each turn the player must choose a direction (up, down, left or right).
All tiles move as far as possible in that direction, some move more than others.
Two adjacent tiles (in that direction only) with matching numbers combine into one bearing the sum of those numbers.
A move is valid when at least one tile can be moved, if only by combination.
A new tile with the value of 2 is spawned at the end of each turn at a randomly chosen empty square (if there is one).
Adding a new tile on a blank space. Most of the time, a new 2 is to be added, and occasionally (10% of the time), a 4.
To win, the player must create a tile with the number 2048.
The player loses if no valid moves are possible.
The name comes from the popular open-source implementation of this game mechanic, 2048.
Requirements
"Non-greedy" movement.
The tiles that were created by combining other tiles should not be combined again during the same turn (move).
That is to say, that moving the tile row of:
[2][2][2][2]
to the right should result in:
......[4][4]
and not:
.........[8]
"Move direction priority".
If more than one variant of combining is possible, move direction shall indicate which combination will take effect.
For example, moving the tile row of:
...[2][2][2]
to the right should result in:
......[2][4]
and not:
......[4][2]
Check for valid moves. The player shouldn't be able to skip their turn by trying a move that doesn't change the board.
Check for a win condition.
Check for a lose condition.
| #FreeBASIC | FreeBASIC | #define EXTCHAR Chr(255)
'--- Declaration of global variables ---
Dim Shared As Integer gGridSize = 4 'grid size (4 -> 4x4)
Dim Shared As Integer gGrid(gGridSize, gGridSize)
Dim Shared As Integer gScore
Dim Shared As Integer curX, curY
Dim Shared As Integer hasMoved, wasMerge
' Don't touch these numbers, seriously
Dim Shared As Integer gOriginX, gOriginY
gOriginX = 75 'pixel X of top left of grid
gOriginY = 12 'pixel Y of top right of grida
Dim Shared As Integer gTextOriginX, gTextOriginY, gSquareSide
gTextOriginX = 11
gTextOriginY = 3
gSquareSide = 38 'width/height of block in pixels
'set up all the things!
Dim Shared As Integer gDebug = 0
'--- SUBroutines and FUNCtions ---
Sub addblock
Dim As Integer emptyCells(gGridSize * gGridSize, 2)
Dim As Integer emptyCellCount = 0
Dim As Integer x, y, index, num
For x = 0 To gGridSize - 1
For y = 0 To gGridSize - 1
If gGrid(x, y) = 0 Then
emptyCells(emptyCellCount, 0) = x
emptyCells(emptyCellCount, 1) = y
emptyCellCount += 1
End If
Next y
Next x
If emptyCellCount > 0 Then
index = Int(Rnd * emptyCellCount)
num = Cint(Rnd + 1) * 2
gGrid(emptyCells(index, 0), emptyCells(index, 1)) = num
End If
End Sub
Function pad(num As Integer) As String
Dim As String strNum = Ltrim(Str(num))
Select Case Len(strNum)
Case 1: Return " " + strNum + " "
Case 2: Return " " + strNum + " "
Case 3: Return " " + strNum
Case 4: Return strNum
End Select
End Function
Sub drawNumber(num As Integer, xPos As Integer, yPos As Integer)
Dim As Integer c, x, y
Select Case num
Case 0: c = 16
Case 2: c = 2
Case 4: c = 3
Case 8: c = 4
Case 16: c = 5
Case 32: c = 6
Case 64: c = 7
Case 128: c = 8
Case 256: c = 9
Case 512: c = 10
Case 1024: c = 11
Case 2048: c = 12
Case 4096: c = 13
Case 8192: c = 13
Case Else: c = 13
End Select
x = xPos *(gSquareSide + 2) + gOriginX + 1
y = yPos *(gSquareSide + 2) + gOriginY + 1
Line(x + 1, y + 1)-(x + gSquareSide - 1, y + gSquareSide - 1), c, BF
If num > 0 Then
Locate gTextOriginY + 1 +(yPos * 5), gTextOriginX +(xPos * 5) : Print " "
Locate gTextOriginY + 2 +(yPos * 5), gTextOriginX +(xPos * 5) : Print pad(num)
Locate gTextOriginY + 3 +(yPos * 5), gTextOriginX +(xPos * 5)
End If
End Sub
Function getAdjacentCell(x As Integer, y As Integer, d As String) As Integer
If (d = "l" And x = 0) Or (d = "r" And x = gGridSize - 1) Or (d = "u" And y = 0) Or (d = "d" And y = gGridSize - 1) Then
getAdjacentCell = -1
Else
Select Case d
Case "l": getAdjacentCell = gGrid(x - 1, y)
Case "r": getAdjacentCell = gGrid(x + 1, y)
Case "u": getAdjacentCell = gGrid(x, y - 1)
Case "d": getAdjacentCell = gGrid(x, y + 1)
End Select
End If
End Function
'Draws the outside grid(doesn't render tiles)
Sub initGraphicGrid
Dim As Integer x, y, gridSide =(gSquareSide + 2) * gGridSize
Line(gOriginX, gOriginY)-(gOriginX + gridSide, gOriginY + gridSide), 14, BF 'outer square, 3 thick
Line(gOriginX, gOriginY)-(gOriginX + gridSide, gOriginY + gridSide), 1, B 'outer square, 3 thick
Line(gOriginX - 1, gOriginY - 1)-(gOriginX + gridSide + 1, gOriginY + gridSide + 1), 1, B
Line(gOriginX - 2, gOriginY - 2)-(gOriginX + gridSide + 2, gOriginY + gridSide + 2), 1, B
For x = gOriginX + gSquareSide + 2 To gOriginX +(gSquareSide + 2) * gGridSize Step gSquareSide + 2 ' horizontal lines
Line(x, gOriginY)-(x, gOriginY + gridSide), 1
Next x
For y = gOriginY + gSquareSide + 2 To gOriginY +(gSquareSide + 2) * gGridSize Step gSquareSide + 2 ' vertical lines
Line(gOriginX, y)-(gOriginX + gridSide, y), 1
Next y
End Sub
'Init the(data) grid with 0s
Sub initGrid
Dim As Integer x, y
For x = 0 To 3
For y = 0 To 3
gGrid(x, y) = 0
Next y
Next x
addblock
addblock
End Sub
Sub moveBlock(sourceX As Integer, sourceY As Integer, targetX As Integer, targetY As Integer, merge As Integer)
If sourceX < 0 Or sourceX >= gGridSize Or sourceY < 0 Or sourceY >= gGridSize And gDebug = 1 Then
Locate 0, 0 : Print "moveBlock: source coords out of bounds"
End If
If targetX < 0 Or targetX >= gGridSize Or targetY < 0 Or targetY >= gGridSize And gDebug = 1 Then
Locate 0, 0 : Print "moveBlock: source coords out of bounds"
End If
Dim As Integer sourceSquareValue = gGrid(sourceX, sourceY)
Dim As Integer targetSquareValue = gGrid(targetX, targetY)
If merge = 1 Then
If sourceSquareValue = targetSquareValue Then
gGrid(sourceX, sourceY) = 0
gGrid(targetX, targetY) = targetSquareValue * 2
gScore += targetSquareValue * 2 ' Points!
Elseif gDebug = 1 Then
Locate 0, 0 : Print "moveBlock: Attempted to merge unequal sqs"
End If
Else
If targetSquareValue = 0 Then
gGrid(sourceX, sourceY) = 0
gGrid(targetX, targetY) = sourceSquareValue
Elseif gDebug = 1 Then
Locate 0, 0 : Print "moveBlock: Attempted to move to non-empty block"
End If
End If
End Sub
Function pColor(r As Integer, g As Integer, b As Integer) As Integer
Return (r + g * 256 + b * 65536)
End Function
Sub moveToObstacle(x As Integer, y As Integer, direcc As String)
curX = x : curY = y
Do While getAdjacentCell(curX, curY, direcc) = 0
Select Case direcc
Case "l": curX -= 1
Case "r": curX += 1
Case "u": curY -= 1
Case "d": curY += 1
End Select
Loop
End Sub
Sub processBlock(x As Integer, y As Integer, direcc As String)
Dim As Integer merge = 0, mergeDirX, mergeDirY
If gGrid(x, y) <> 0 Then ' have block
moveToObstacle(x, y, direcc) ' figure out where it can be moved to
If getAdjacentCell(curX, curY, direcc) = gGrid(x, y) And wasMerge = 0 Then ' obstacle can be merged with
merge = 1
wasMerge = 1
Else
wasMerge = 0
End If
If curX <> x Or curY <> y Or merge = 1 Then
mergeDirX = 0
mergeDirY = 0
If merge = 1 Then
Select Case direcc
Case "l": mergeDirX = -1
Case "r": mergeDirX = 1
Case "u": mergeDirY = -1
Case "d": mergeDirY = 1
End Select
End If
moveBlock(x, y, curX + mergeDirX, curY + mergeDirY, merge) ' move to before obstacle or merge
hasMoved = 1
End If
End If
End Sub
Sub renderGrid
Dim As Integer x, y
For x = 0 To gGridSize - 1
For y = 0 To gGridSize - 1
drawNumber(gGrid(x, y), x, y)
Next y
Next x
End Sub
Sub updateScore
Locate 1, 10 : Print Using "Score: #####"; gScore
End Sub
Sub processMove(direcc As String) '' direcc can be 'l', 'r', 'u', or 'd'
Dim As Integer x, y
hasMoved = 0
If direcc = "l" Then
For y = 0 To gGridSize - 1
wasMerge = 0
For x = 0 To gGridSize - 1
processBlock(x,y,direcc)
Next x
Next y
Elseif direcc = "r" Then
For y = 0 To gGridSize - 1
wasMerge = 0
For x = gGridSize - 1 To 0 Step -1
processBlock(x,y,direcc)
Next x
Next y
Elseif direcc = "u" Then
For x = 0 To gGridSize - 1
wasMerge = 0
For y = 0 To gGridSize - 1
processBlock(x,y,direcc)
Next y
Next x
Elseif direcc = "d" Then
For x = 0 To gGridSize - 1
wasMerge = 0
For y = gGridSize - 1 To 0 Step -1
processBlock(x,y,direcc)
Next y
Next x
End If
If hasMoved = 1 Then addblock
renderGrid
updateScore
End Sub
'--- Main Program ---
Screen 8
Windowtitle "2048"
Palette 1, pColor(35, 33, 31)
Palette 2, pColor(46, 46, 51)
Palette 3, pColor(59, 56, 50)
Palette 4, pColor(61, 44, 30)
Palette 5, pColor(61, 37, 25)
Palette 6, pColor(62, 31, 24)
Palette 7, pColor(62, 24, 15)
Palette 8, pColor(59, 52, 29)
Palette 9, pColor(59, 51, 24)
Palette 10, pColor(59, 50, 20)
Palette 11, pColor(59, 49, 16)
Palette 12, pColor(59, 49, 12)
Palette 13, pColor(15, 15, 13)
Palette 14, pColor(23, 22, 20)
Randomize Timer
Cls
Do
initGrid
initGraphicGrid
renderGrid
updateScore
gScore = 0
Locate 23, 10 : Print "Move with arrow keys."
Locate 24, 12 : Print "(R)estart, (Q)uit"
Dim As String k
Do
Do
k = Inkey
Loop Until k <> ""
Select Case k
Case EXTCHAR + Chr(72) 'up
processMove("u")
Case EXTCHAR + Chr(80) 'down
processMove("d")
Case EXTCHAR + Chr(77) 'right
processMove("r")
Case EXTCHAR + Chr(75) 'left
processMove("l")
Case "q", "Q", Chr(27) 'escape
End
Case "r", "R"
Exit Do
End Select
Loop
Loop |
http://rosettacode.org/wiki/4-rings_or_4-squares_puzzle | 4-rings or 4-squares puzzle | 4-rings or 4-squares puzzle
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Replace a, b, c, d, e, f, and
g with the decimal
digits LOW ───► HIGH
such that the sum of the letters inside of each of the four large squares add up to
the same sum.
╔══════════════╗ ╔══════════════╗
║ ║ ║ ║
║ a ║ ║ e ║
║ ║ ║ ║
║ ┌───╫──────╫───┐ ┌───╫─────────┐
║ │ ║ ║ │ │ ║ │
║ │ b ║ ║ d │ │ f ║ │
║ │ ║ ║ │ │ ║ │
║ │ ║ ║ │ │ ║ │
╚══════════╪═══╝ ╚═══╪══════╪═══╝ │
│ c │ │ g │
│ │ │ │
│ │ │ │
└──────────────┘ └─────────────┘
Show all output here.
Show all solutions for each letter being unique with
LOW=1 HIGH=7
Show all solutions for each letter being unique with
LOW=3 HIGH=9
Show only the number of solutions when each letter can be non-unique
LOW=0 HIGH=9
Related task
Solve the no connection puzzle
| #Wren | Wren | import "/fmt" for Fmt
var a = 0
var b = 0
var c = 0
var d = 0
var e = 0
var f = 0
var g = 0
var lo
var hi
var unique
var show
var solutions
var bf = Fn.new {
f = lo
while (f <= hi) {
if (!unique || (f != a && f != c && f != d && f != e && f != g)) {
b = e + f - c
if (b >= lo && b <= hi &&
(!unique || (b != a && b != c && b != d && b != e && b != f && b != g))) {
solutions = solutions + 1
if (show) Fmt.lprint("$d $d $d $d $d $d $d", [a, b, c, d, e, f, g])
}
}
f = f + 1
}
}
var ge = Fn.new {
e = lo
while (e <= hi) {
if (!unique || (e != a && e != c && e != d)) {
g = d + e
if (g >= lo && g <= hi &&
(!unique || (g != a && g != c && g != d && g != e))) bf.call()
}
e = e + 1
}
}
var acd = Fn.new {
c = lo
while (c <= hi) {
d = lo
while (d <= hi) {
if (!unique || c != d) {
a = c + d
if (a >= lo && a <= hi && (!unique || (c != 0 && d != 0))) ge.call()
}
d = d + 1
}
c = c + 1
}
}
var foursquares = Fn.new { |plo, phi, punique, pshow|
lo = plo
hi = phi
unique = punique
show = pshow
solutions = 0
if (show) {
System.print("\na b c d e f g")
System.print("-------------")
}
acd.call()
if (unique) {
Fmt.print("\n$d unique solutions in $d to $d", solutions, lo, hi)
} else {
Fmt.print("\n$d non-unique solutions in $d to $d\n", solutions, lo, hi)
}
}
foursquares.call(1, 7, true, true)
foursquares.call(3, 9, true, true)
foursquares.call(0, 9, false, false) |
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
| #Axe | Axe | 99→B
While B
Disp B▶Dec," BOTTLES OF","BEER ON THE WALL"
Disp B▶Dec," BOTTLES OF","BEER",i,i
getKeyʳ
Disp "TAKE ONE DOWN",i,"PASS IT AROUND",i
B--
Disp B▶Dec," BOTTLES OF","BEER ON THE WALL",i
getKeyʳ
End |
http://rosettacode.org/wiki/24_game | 24 game | The 24 Game tests one's mental arithmetic.
Task
Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed.
The program should prompt for the player to enter an arithmetic expression using just those, and all of those four digits, used exactly once each. The program should check then evaluate the expression.
The goal is for the player to enter an expression that (numerically) evaluates to 24.
Only the following operators/functions are allowed: multiplication, division, addition, subtraction
Division should use floating point or rational arithmetic, etc, to preserve remainders.
Brackets are allowed, if using an infix expression evaluator.
Forming multiple digit numbers from the supplied digits is disallowed. (So an answer of 12+12 when given 1, 2, 2, and 1 is wrong).
The order of the digits when given does not have to be preserved.
Notes
The type of expression evaluator used is not mandated. An RPN evaluator is equally acceptable for example.
The task is not for the program to generate the expression, or test whether an expression is even possible.
Related tasks
24 game/Solve
Reference
The 24 Game on h2g2.
| #J | J | require'misc'
deal=: 1 + ? bind 9 9 9 9
rules=: smoutput bind 'see http://en.wikipedia.org/wiki/24_Game'
input=: prompt @ ('enter 24 expression using ', ":, ': '"_)
wellformed=: (' '<;._1@, ":@[) -:&(/:~) '(+-*%)' -.&;:~ ]
is24=: 24 -: ". ::0:@]
respond=: (;:'no yes') {::~ wellformed * is24
game24=: (respond input)@deal@rules |
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
| #D.C3.A9j.C3.A0_Vu | Déjà Vu | 0
for k in split !prompt "" " ":
+ to-num k
!print |
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #Yorick | Yorick | func ack(m, n) {
if(m == 0)
return n + 1;
else if(n == 0)
return ack(m - 1, 1);
else
return ack(m - 1, ack(m, n - 1));
} |
http://rosettacode.org/wiki/ABC_problem | ABC problem | ABC problem
You are encouraged to solve this task according to the task description, using any language you may know.
You are given a collection of ABC blocks (maybe like the ones you had when you were a kid).
There are twenty blocks with two letters on each block.
A complete alphabet is guaranteed amongst all 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
| #Liberty_BASIC | Liberty BASIC |
print "Rosetta Code - ABC problem (recursive solution)"
print
blocks$="BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM"
data "A"
data "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "CONFUSE"
data "XYZZY"
do
read text$
if text$="XYZZY" then exit do
print ">>> can_make_word("; chr$(34); text$; chr$(34); ")"
if canDo(text$,blocks$) then print "True" else print "False"
loop while 1
print "Program complete."
end
function canDo(text$,blocks$)
'endcase
if len(text$)=1 then canDo=(instr(blocks$,text$)<>0): exit function
'get next letter
ltr$=left$(text$,1)
'cut
if instr(blocks$,ltr$)=0 then canDo=0: exit function
'recursion
text$=mid$(text$,2) 'rest
'loop by all word in blocks. Need to make "newBlocks" - all but taken
'optimisation: take only fitting blocks
wrd$="*"
i=0
while wrd$<>""
i=i+1
wrd$=word$(blocks$, i)
if instr(wrd$, ltr$) then
'newblocks without wrd$
pos=instr(blocks$,wrd$)
newblocks$=left$(blocks$, pos-1)+mid$(blocks$, pos+3)
canDo=canDo(text$,newblocks$)
'first found cuts
if canDo then exit while
end if
wend
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.
| #Java | Java | import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Main {
private static boolean playOptimal(int n) {
List<Integer> secretList = IntStream.range(0, n).boxed().collect(Collectors.toList());
Collections.shuffle(secretList);
prisoner:
for (int i = 0; i < secretList.size(); ++i) {
int prev = i;
for (int j = 0; j < secretList.size() / 2; ++j) {
if (secretList.get(prev) == i) {
continue prisoner;
}
prev = secretList.get(prev);
}
return false;
}
return true;
}
private static boolean playRandom(int n) {
List<Integer> secretList = IntStream.range(0, n).boxed().collect(Collectors.toList());
Collections.shuffle(secretList);
prisoner:
for (Integer i : secretList) {
List<Integer> trialList = IntStream.range(0, n).boxed().collect(Collectors.toList());
Collections.shuffle(trialList);
for (int j = 0; j < trialList.size() / 2; ++j) {
if (Objects.equals(trialList.get(j), i)) {
continue prisoner;
}
}
return false;
}
return true;
}
private static double exec(int n, int p, Function<Integer, Boolean> play) {
int succ = 0;
for (int i = 0; i < n; ++i) {
if (play.apply(p)) {
succ++;
}
}
return (succ * 100.0) / n;
}
public static void main(String[] args) {
final int n = 100_000;
final int p = 100;
System.out.printf("# of executions: %d\n", n);
System.out.printf("Optimal play success rate: %f%%\n", exec(n, p, Main::playOptimal));
System.out.printf("Random play success rate: %f%%\n", exec(n, p, Main::playRandom));
}
} |
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
| #Phix | Phix | -- demo\rosetta\24_game_solve.exw
with javascript_semantics
-- The following 5 parse expressions are possible.
-- Obviously numbers 1234 represent 24 permutations from
-- {1,2,3,4} to {4,3,2,1} of indexes to the real numbers.
-- Likewise "+-*" is like "123" representing 64 combinations
-- from {1,1,1} to {4,4,4} of indexes to "+-*/".
-- Both will be replaced if/when the strings get printed.
-- Last hint is because of no precedence, just parenthesis.
--
constant OPS = "+-*/"
constant expressions = {"1+(2-(3*4))",
"1+((2-3)*4)",
"(1+2)-(3*4)",
"(1+(2-3))*4",
"((1+2)-3)*4"} -- (equivalent to "1+2-3*4")
-- The above represented as three sequential operations (the result gets
-- left in <(map)1>, ie vars[perms[operations[i][3][1]]] aka vars[lhs]):
constant operations = {{{3,'*',4},{2,'-',3},{1,'+',2}}, --3*=4; 2-=3; 1+=2
{{2,'-',3},{2,'*',4},{1,'+',2}}, --2-=3; 2*=4; 1+=2
{{1,'+',2},{3,'*',4},{1,'-',3}}, --1+=2; 3*=4; 1-=3
{{2,'-',3},{1,'+',2},{1,'*',4}}, --2-=3; 1+=2; 1*=4
{{1,'+',2},{1,'-',3},{1,'*',4}}} --1+=2; 1-=3; 1*=4
function evalopset(sequence opset, perms, ops, vars)
-- invoked 5*24*64 = 7680 times, to try all possible expressions/vars/operators
-- (btw, vars is copy-on-write, like all parameters not explicitly returned, so
-- we can safely re-use it without clobbering the callee version.)
-- (update: with js made that illegal and reported it correctly and forced the
-- addition of the deep_copy(), all exactly the way it should.)
integer lhs,op,rhs
vars = deep_copy(vars)
for i=1 to length(opset) do
{lhs,op,rhs} = opset[i]
lhs = perms[lhs]
op = ops[find(op,OPS)]
rhs = perms[rhs]
if op='+' then
vars[lhs] += vars[rhs]
elsif op='-' then
vars[lhs] -= vars[rhs]
elsif op='*' then
vars[lhs] *= vars[rhs]
elsif op='/' then
if vars[rhs]=0 then return 1e300*1e300 end if
vars[lhs] /= vars[rhs]
end if
end for
return vars[lhs]
end function
integer nSolutions
sequence xSolutions
procedure success(string expr, sequence perms, ops, vars, atom r)
for i=1 to length(expr) do
integer ch = expr[i]
if ch>='1' and ch<='9' then
expr[i] = vars[perms[ch-'0']]+'0'
else
ch = find(ch,OPS)
if ch then
expr[i] = ops[ch]
end if
end if
end for
if not find(expr,xSolutions) then
-- avoid duplicates for eg {1,1,2,7} because this has found
-- the "same" solution but with the 1st and 2nd 1s swapped,
-- and likewise whenever an operator is used more than once.
printf(1,"success: %s = %s\n",{expr,sprint(r)})
nSolutions += 1
xSolutions = append(xSolutions,expr)
end if
end procedure
procedure tryperms(sequence perms, ops, vars)
for i=1 to length(operations) do
-- 5 parse expressions
atom r = evalopset(operations[i], perms, ops, vars)
r = round(r,1e9) -- fudge tricky 8/(3-(8/3)) case
if r=24 then
success(expressions[i], perms, ops, vars, r)
end if
end for
end procedure
procedure tryops(sequence ops, vars)
for p=1 to factorial(4) do
-- 24 var permutations
tryperms(permute(p,{1,2,3,4}),ops, vars)
end for
end procedure
global procedure solve24(sequence vars)
nSolutions = 0
xSolutions = {}
for op1=1 to 4 do
for op2=1 to 4 do
for op3=1 to 4 do
-- 64 operator combinations
tryops({OPS[op1],OPS[op2],OPS[op3]},vars)
end for
end for
end for
printf(1,"\n%d solutions\n",{nSolutions})
end procedure
solve24({1,1,2,7})
--solve24({6,4,6,1})
--solve24({3,3,8,8})
--solve24({6,9,7,4})
{} = wait_key()
|
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
| #Factor | Factor | USING: accessors combinators combinators.extras
combinators.short-circuit grouping io kernel literals math
math.matrices math.order math.parser math.vectors prettyprint qw
random sequences sequences.extras ;
IN: rosetta-code.15-puzzle-game
<<
TUPLE: board matrix zero ;
: <board> ( -- board )
16 <iota> 1 rotate 4 group { 3 3 } board boa ;
>>
CONSTANT: winning $[ <board> matrix>> ]
: input>dir ( str -- pair )
{
{ "u" [ { 1 0 } ] }
{ "d" [ { -1 0 } ] }
{ "l" [ { 0 1 } ] }
{ "r" [ { 0 -1 } ] }
} case ;
: get-index ( loc matrix -- elt ) [ first2 swap ] dip nth nth ;
: mexchange ( loc1 loc2 matrix -- )
tuck [ [ [ get-index ] keepd ] 2bi@ ] keep [ spin ] 2dip
[ set-index ] keep set-index ;
: vclamp+ ( seq1 seq2 -- seq ) v+ { 0 0 } { 3 3 } vclamp ;
: slide-piece ( board str -- )
over zero>> [ vclamp+ ] keep rot matrix>> mexchange ;
: move-zero ( board str -- )
[ vclamp+ ] curry change-zero drop ;
: move ( board str -- )
input>dir [ slide-piece ] [ move-zero ] 2bi ;
: rand-move ( board -- ) qw{ u d l r } random move ;
: shuffle-board ( board n -- board' ) [ dup rand-move ] times ;
: .board ( board -- ) matrix>> simple-table. ;
: get-input ( -- str )
"Your move? (u/d/l/r/q) " write flush readln dup
qw{ u d l r q } member? [ drop get-input ] unless ;
: won? ( board -- ? ) matrix>> winning = ;
DEFER: game
: process-input ( board -- board' )
get-input dup "q" = [ drop ] [ game ] if ;
: check-win ( board -- board' )
dup won? [ "You won!" print ] [ process-input ] if ;
: game ( board str -- board' )
[ move ] keepd dup .board check-win ;
: valid-difficulty? ( obj -- ? )
{ [ fixnum? ] [ 3 100 between? ] } 1&& ;
: choose-difficulty ( -- n )
"How many shuffles? (3-100) " write flush readln
string>number dup valid-difficulty?
[ drop choose-difficulty ] unless ;
: main ( -- )
<board> choose-difficulty shuffle-board dup .board check-win
drop ;
MAIN: main |
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.
| #Go | Go | package main
import (
"bufio"
"fmt"
"log"
"math/rand"
"os"
"os/exec"
"strconv"
"strings"
"text/template"
"time"
"unicode"
"golang.org/x/crypto/ssh/terminal"
)
const maxPoints = 2048
const (
fieldSizeX = 4
fieldSizeY = 4
)
const tilesAtStart = 2
const probFor2 = 0.9
type button int
const (
_ button = iota
up
down
right
left
quit
)
var labels = func() map[button]rune {
m := make(map[button]rune, 4)
m[up] = 'W'
m[down] = 'S'
m[right] = 'D'
m[left] = 'A'
return m
}()
var keybinding = func() map[rune]button {
m := make(map[rune]button, 8)
for b, r := range labels {
m[r] = b
if unicode.IsUpper(r) {
r = unicode.ToLower(r)
} else {
r = unicode.ToUpper(r)
}
m[r] = b
}
m[0x03] = quit
return m
}()
var model = struct {
Score int
Field [fieldSizeY][fieldSizeX]int
}{}
var view = func() *template.Template {
maxWidth := 1
for i := maxPoints; i >= 10; i /= 10 {
maxWidth++
}
w := maxWidth + 3
r := make([]byte, fieldSizeX*w+1)
for i := range r {
if i%w == 0 {
r[i] = '+'
} else {
r[i] = '-'
}
}
rawBorder := string(r)
v, err := template.New("").Parse(`SCORE: {{.Score}}
{{range .Field}}
` + rawBorder + `
|{{range .}} {{if .}}{{printf "%` + strconv.Itoa(maxWidth) + `d" .}}{{else}}` +
strings.Repeat(" ", maxWidth) + `{{end}} |{{end}}{{end}}
` + rawBorder + `
(` + string(labels[up]) + `)Up (` +
string(labels[down]) + `)Down (` +
string(labels[left]) + `)Left (` +
string(labels[right]) + `)Right
`)
check(err)
return v
}()
func check(err error) {
if err != nil {
log.Panicln(err)
}
}
func clear() {
c := exec.Command("clear")
c.Stdout = os.Stdout
check(c.Run())
}
func draw() {
clear()
check(view.Execute(os.Stdout, model))
}
func addRandTile() (full bool) {
free := make([]*int, 0, fieldSizeX*fieldSizeY)
for x := 0; x < fieldSizeX; x++ {
for y := 0; y < fieldSizeY; y++ {
if model.Field[y][x] == 0 {
free = append(free, &model.Field[y][x])
}
}
}
val := 4
if rand.Float64() < probFor2 {
val = 2
}
*free[rand.Intn(len(free))] = val
return len(free) == 1
}
type point struct{ x, y int }
func (p point) get() int { return model.Field[p.y][p.x] }
func (p point) set(n int) { model.Field[p.y][p.x] = n }
func (p point) inField() bool { return p.x >= 0 && p.y >= 0 && p.x < fieldSizeX && p.y < fieldSizeY }
func (p *point) next(n point) { p.x += n.x; p.y += n.y }
func controller(key rune) (gameOver bool) {
b := keybinding[key]
if b == 0 {
return false
}
if b == quit {
return true
}
var starts []point
var next point
switch b {
case up:
next = point{0, 1}
starts = make([]point, fieldSizeX)
for x := 0; x < fieldSizeX; x++ {
starts[x] = point{x, 0}
}
case down:
next = point{0, -1}
starts = make([]point, fieldSizeX)
for x := 0; x < fieldSizeX; x++ {
starts[x] = point{x, fieldSizeY - 1}
}
case right:
next = point{-1, 0}
starts = make([]point, fieldSizeY)
for y := 0; y < fieldSizeY; y++ {
starts[y] = point{fieldSizeX - 1, y}
}
case left:
next = point{1, 0}
starts = make([]point, fieldSizeY)
for y := 0; y < fieldSizeY; y++ {
starts[y] = point{0, y}
}
}
moved := false
winning := false
for _, s := range starts {
n := s
move := func(set int) {
moved = true
s.set(set)
n.set(0)
}
for n.next(next); n.inField(); n.next(next) {
if s.get() != 0 {
if n.get() == s.get() {
score := s.get() * 2
model.Score += score
winning = score >= maxPoints
move(score)
s.next(next)
} else if n.get() != 0 {
s.next(next)
if s.get() == 0 {
move(n.get())
}
}
} else if n.get() != 0 {
move(n.get())
}
}
}
if !moved {
return false
}
lost := false
if addRandTile() {
lost = true
Out:
for x := 0; x < fieldSizeX; x++ {
for y := 0; y < fieldSizeY; y++ {
if (y > 0 && model.Field[y][x] == model.Field[y-1][x]) ||
(x > 0 && model.Field[y][x] == model.Field[y][x-1]) {
lost = false
break Out
}
}
}
}
draw()
if winning {
fmt.Println("You win!")
return true
}
if lost {
fmt.Println("Game Over")
return true
}
return false
}
func main() {
oldState, err := terminal.MakeRaw(0)
check(err)
defer terminal.Restore(0, oldState)
rand.Seed(time.Now().Unix())
for i := tilesAtStart; i > 0; i-- {
addRandTile()
}
draw()
stdin := bufio.NewReader(os.Stdin)
readKey := func() rune {
r, _, err := stdin.ReadRune()
check(err)
return r
}
for !controller(readKey()) {
}
}
|
http://rosettacode.org/wiki/4-rings_or_4-squares_puzzle | 4-rings or 4-squares puzzle | 4-rings or 4-squares puzzle
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Replace a, b, c, d, e, f, and
g with the decimal
digits LOW ───► HIGH
such that the sum of the letters inside of each of the four large squares add up to
the same sum.
╔══════════════╗ ╔══════════════╗
║ ║ ║ ║
║ a ║ ║ e ║
║ ║ ║ ║
║ ┌───╫──────╫───┐ ┌───╫─────────┐
║ │ ║ ║ │ │ ║ │
║ │ b ║ ║ d │ │ f ║ │
║ │ ║ ║ │ │ ║ │
║ │ ║ ║ │ │ ║ │
╚══════════╪═══╝ ╚═══╪══════╪═══╝ │
│ c │ │ g │
│ │ │ │
│ │ │ │
└──────────────┘ └─────────────┘
Show all output here.
Show all solutions for each letter being unique with
LOW=1 HIGH=7
Show all solutions for each letter being unique with
LOW=3 HIGH=9
Show only the number of solutions when each letter can be non-unique
LOW=0 HIGH=9
Related task
Solve the no connection puzzle
| #X86_Assembly | X86 Assembly | int Show, Low, High, Digit(7\a..g\), Count;
proc Rings(Level);
int Level; \of recursion
int D, Temp, I, Set;
[for D:= Low to High do
[Digit(Level):= D;
if Level < 7-1 then Rings(Level+1)
else [ Temp:= Digit(0) + Digit(1); \solution?
if Temp = Digit(1) + Digit(2) + Digit(3) and
Temp = Digit(3) + Digit(4) + Digit(5) and
Temp = Digit(5) + Digit(6) then
[Count:= Count+1;
if Show then
[Set:= 0; \digits must be unique
for I:= 0 to 7-1 do
Set:= Set ! 1<<Digit(I);
if Set = %111_1111 << Low then
[for I:= 0 to 7-1 do
[IntOut(0, Digit(I)); ChOut(0, ^ )];
CrLf(0);
];
];
];
];
];
];
[Show:= true;
Low:= 1; High:= 7;
Rings(0);
CrLf(0);
Low:= 3; High:= 9;
Rings(0);
CrLf(0);
Show:= false;
Low:= 0; High:= 9; Count:= 0;
Rings(0);
IntOut(0, Count);
CrLf(0);
] |
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
| #Babel | Babel | -- beer.sp
{b " bottles of beer" <
bi { itoa << } <
bb { bi ! b << w << "\n" << } <
w " on the wall" <
beer
{<-
{ iter 1 + dup
<- bb ! ->
bi ! b << "\n" <<
"Take one down, pass it around\n" <<
iter bb ! "\n" << }
->
times}
< }
-- At the prompt, type 'N beer !' (no quotes), where N is the number of stanzas you desire |
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.
| #Java | Java | import java.util.*;
public class Game24 {
static Random r = new Random();
public static void main(String[] args) {
int[] digits = randomDigits();
Scanner in = new Scanner(System.in);
System.out.print("Make 24 using these digits: ");
System.out.println(Arrays.toString(digits));
System.out.print("> ");
Stack<Float> s = new Stack<>();
long total = 0;
for (char c : in.nextLine().toCharArray()) {
if ('0' <= c && c <= '9') {
int d = c - '0';
total += (1 << (d * 5));
s.push((float) d);
} else if ("+/-*".indexOf(c) != -1) {
s.push(applyOperator(s.pop(), s.pop(), c));
}
}
if (tallyDigits(digits) != total)
System.out.print("Not the same digits. ");
else if (Math.abs(24 - s.peek()) < 0.001F)
System.out.println("Correct!");
else
System.out.print("Not correct.");
}
static float applyOperator(float a, float b, char c) {
switch (c) {
case '+':
return a + b;
case '-':
return b - a;
case '*':
return a * b;
case '/':
return b / a;
default:
return Float.NaN;
}
}
static long tallyDigits(int[] a) {
long total = 0;
for (int i = 0; i < 4; i++)
total += (1 << (a[i] * 5));
return total;
}
static int[] randomDigits() {
int[] result = new int[4];
for (int i = 0; i < 4; i++)
result[i] = r.nextInt(9) + 1;
return result;
}
} |
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
| #EasyLang | EasyLang | a$ = input
while i < len a$ and substr a$ i 1 <> " "
i += 1
.
a = number substr a$ 0 i
b = number substr a$ i -1
print a + b
|
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #Z80_Assembly | Z80 Assembly | OPT --syntax=abf : OUTPUT "ackerman.com"
ORG $100
jr demo_start
;--------------------------------------------------------------------------------------------------------------------
; entry: ackermann_fn
; input: bc = m, hl = n
; output: hl = A(m,n) (16bit only)
ackermann_fn.inc_n:
inc hl
ackermann_fn:
inc hl
ld a,c
or b
ret z ; m == 0 -> return n+1
; m > 0 case ; bc = m, hl = n+1
dec bc
dec hl ; m-1, n restored
ld a,l
or h
jr z,.inc_n ; n == 0 -> return A(m-1, 1)
; m > 0, n > 0 ; bc = m-1, hl = n
push bc
inc bc
dec hl
call ackermann_fn ; n = A(m, n-1)
pop bc
jp ackermann_fn ; return A(m-1,A(m, n-1))
;--------------------------------------------------------------------------------------------------------------------
; helper functions for demo printing 4x9 table
print_str:
push bc
push hl
ld c,9
.call_cpm:
call 5
pop hl
pop bc
ret
print_hl:
ld b,' '
ld e,b
call print_char
ld de,-10000
call extract_digit
ld de,-1000
call extract_digit
ld de,-100
call extract_digit
ld de,-10
call extract_digit
ld a,l
print_digit:
ld b,'0'
add a,b
ld e,a
print_char:
push bc
push hl
ld c,2
jr print_str.call_cpm
extract_digit:
ld a,-1
.digit_loop:
inc a
add hl,de
jr c,.digit_loop
sbc hl,de
or a
jr nz,print_digit
ld e,b
jr print_char
;--------------------------------------------------------------------------------------------------------------------
demo_start: ; do m: [0,4) cross n: [0,9) table
ld bc,0
.loop_m:
ld hl,0 ; bc = m, hl = n = 0
ld de,txt_m_is
call print_str
ld a,c
or '0'
ld e,a
call print_char
ld e,':'
call print_char
.loop_n:
push bc
push hl
call ackermann_fn
call print_hl
pop hl
pop bc
inc hl
ld a,l
cp 9
jr c,.loop_n
ld de,crlf
call print_str
inc bc
ld a,c
cp 4
jr c,.loop_m
rst 0 ; return to CP/M
txt_m_is: db "m=$"
crlf: db 10,13,'$' |
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
| #Logo | Logo | make "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]]
to can_make? :word [:avail :blocks]
if empty? :word [output "true]
local "letter make "letter first :word
foreach :avail [
local "i make "i #
local "block make "block ?
if member? :letter :block [
if (can_make? bf :word filter [notequal? # :i] :avail) [output "true]
]
]
output "false
end
foreach [A BARK BOOK TREAT COMMON SQUAD CONFUSE] [
print sentence word ? ": can_make? ?
]
bye |
http://rosettacode.org/wiki/100_prisoners | 100 prisoners |
The Problem
100 prisoners are individually numbered 1 to 100
A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside.
Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start.
Prisoners start outside the room
They can decide some strategy before any enter the room.
Prisoners enter the room one by one, can open a drawer, inspect the card number in the drawer, then close the drawer.
A prisoner can open no more than 50 drawers.
A prisoner tries to find his own number.
A prisoner finding his own number is then held apart from the others.
If all 100 prisoners find their own numbers then they will all be pardoned. If any don't then all sentences stand.
The task
Simulate several thousand instances of the game where the prisoners randomly open drawers
Simulate several thousand instances of the game where the prisoners use the optimal strategy mentioned in the Wikipedia article, of:
First opening the drawer whose outside number is his prisoner number.
If the card within has his number then he succeeds otherwise he opens the drawer with the same number as that of the revealed card. (until he opens his maximum).
Show and compare the computed probabilities of success for the two strategies, here, on this page.
References
The unbelievable solution to the 100 prisoner puzzle standupmaths (Video).
wp:100 prisoners problem
100 Prisoners Escape Puzzle DataGenetics.
Random permutation statistics#One hundred prisoners on Wikipedia.
| #JavaScript | JavaScript |
const _ = require('lodash');
const numPlays = 100000;
const setupSecrets = () => {
// setup the drawers with random cards
let secrets = [];
for (let i = 0; i < 100; i++) {
secrets.push(i);
}
return _.shuffle(secrets);
}
const playOptimal = () => {
let secrets = setupSecrets();
// Iterate once per prisoner
loop1:
for (let p = 0; p < 100; p++) {
// whether the prisoner succeedss
let success = false;
// the drawer number the prisoner chose
let choice = p;
// The prisoner can choose up to 50 cards
loop2:
for (let i = 0; i < 50; i++) {
// if the card in the drawer that the prisoner chose is his card
if (secrets[choice] === p){
success = true;
break loop2;
}
// the next drawer the prisoner chooses will be the number of the card he has.
choice = secrets[choice];
} // each prisoner gets 50 chances
if (!success) return false;
} // iterate for each prisoner
return true;
}
const playRandom = () => {
let secrets = setupSecrets();
// iterate for each prisoner
for (let p = 0; p < 100; p++) {
let choices = setupSecrets();
let success = false;
for (let i = 0; i < 50; i++) {
if (choices[i] === p) {
success = true;
break;
}
}
if (!success) return false;
}
return true;
}
const execOptimal = () => {
let success = 0;
for (let i = 0; i < numPlays; i++) {
if (playOptimal()) success++;
}
return 100.0 * success / 100000;
}
const execRandom = () => {
let success = 0;
for (let i = 0; i < numPlays; i++) {
if (playRandom()) success++;
}
return 100.0 * success / 100000;
}
console.log("# of executions: " + numPlays);
console.log("Optimal Play Success Rate: " + execOptimal());
console.log("Random Play Success Rate: " + execRandom());
|
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
| #Picat | Picat | main =>
foreach (_ in 1..10)
Nums = [D : _ in 1..4, D = random() mod 9 + 1],
NumExps = [(D,D) : D in Nums],
println(Nums),
(solve(NumExps) -> true; println("No solution")),
nl
end.
solve([(Num,Exp)]), Num =:= 24 =>
println(Exp).
solve(NumExps) =>
select((Num1,Exp1),NumExps,NumExps1),
select((Num2,Exp2),NumExps1,NumExps2),
member(Op, ['+','-','*','/']),
(Op == '/' -> Num2 =\= 0; true),
Num3 = apply(Op,Num1,Num2),
Exp3 =.. [Op,Exp1,Exp2],
solve([(Num3,Exp3)|NumExps2]).
|
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
| #Forth | Forth | #! /usr/bin/gforth
cell 8 <> [if] s" 64-bit system required" exception throw [then]
\ In the stack comments below,
\ "h" stands for the hole position (0..15),
\ "s" for a 64-bit integer representing a board state,
\ "t" a tile value (0..15, 0 is the hole),
\ "b" for a bit offset of a position within a state,
\ "m" for a masked value (4 bits selected out of a 64-bit state),
\ "w" for a weight of a current path,
\ "d" for a direction constant (0..3)
\ Utility
: 3dup 2 pick 2 pick 2 pick ;
: 4dup 2over 2over ;
: shift dup 0 > if lshift else negate rshift then ;
hex 123456789abcdef0 decimal constant solution
: row 2 rshift ; : col 3 and ;
: up-valid? ( h -- f ) row 0 > ;
: down-valid? ( h -- f ) row 3 < ;
: left-valid? ( h -- f ) col 0 > ;
: right-valid? ( h -- f ) col 3 < ;
\ To iterate over all possible directions, put direction-related functions into arrays:
: ith ( u addr -- w ) swap cells + @ ;
create valid? ' up-valid? , ' left-valid? , ' right-valid? , ' down-valid? , does> ith execute ;
create step -4 , -1 , 1 , 4 , does> ith ;
\ Advance from a single state to another:
: bits ( h -- b ) 15 swap - 4 * ;
: tile ( s b -- t ) rshift 15 and ;
: new-state ( s h d -- s' ) step dup >r + bits 2dup tile ( s b t ) swap lshift tuck - swap r> 4 * shift + ;
: hole? ( s u -- f ) bits tile 0= ;
: hole ( s -- h ) 16 0 do dup i hole? if drop i unloop exit then loop drop ;
0 constant up 1 constant left 2 constant right 3 constant down
\ Print a board:
: .hole space space space ;
: .tile ( u -- ) ?dup-0=-if .hole else dup 10 < if space then . then ;
: .board ( s -- ) 4 0 do cr 4 0 do dup j 4 * i + bits tile .tile loop loop drop ;
: .help cr ." ijkl move, q quit" ;
\ Pseudorandom number generator:
create (rnd) utime drop ,
: rnd (rnd) @ dup 13 lshift xor dup 17 rshift xor dup dup 5 lshift xor (rnd) ! ;
: move ( s u -- s' ) >r dup hole r> new-state ;
: ?move ( s u -- s' ) >r dup hole r@ valid? if r> move else rdrop then ;
: shuffle ( s u -- s' ) 0 do rnd 3 and ?move loop ;
: win cr ." you won!" bye ;
: turn ( s -- )
page dup .board .help
key case
[char] q of bye endof
[char] i of down ?move endof
[char] j of right ?move endof
[char] k of up ?move endof
[char] l of left ?move endof
endcase ;
: play begin dup solution <> while turn repeat win ;
solution 1000 shuffle play
|
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.
| #Haskell | Haskell | import System.IO
import Data.List
import Data.Maybe
import Control.Monad
import Data.Random
import Data.Random.Distribution.Categorical
import System.Console.ANSI
import Control.Lens
-- Logic
-- probability to get a 4
prob4 :: Double
prob4 = 0.1
type Position = [[Int]]
combine, shift :: [Int]->[Int]
combine (x:y:l) | x==y = (2*x) : combine l
combine (x:l) = x : combine l
combine [] = []
shift l = take (length l) $ combine (filter (>0) l) ++ [0,0..]
reflect :: [[a]] ->[[a]]
reflect = map reverse
type Move = Position -> Position
left, right, up, down :: Move
left = map shift
right = reflect . left . reflect
up = transpose . left . transpose
down = transpose . right . transpose
progress :: Eq a => (a -> a) -> a -> Maybe a
progress f pos = if pos==next_pos then Nothing else Just next_pos where next_pos= f pos
lost, win:: Position -> Bool
lost pos = all isNothing [progress move pos| move<-[left,right,up,down] ]
win = any $ any (>=2048)
go :: Position -> Maybe Move -> Maybe Position
go pos move = move >>= flip progress pos
{-
-- Adding 2 or 4 without lens:
update l i a = l1 ++ a : l2 where (l1,_:l2)=splitAt i l
indicesOf l = [0..length l-1]
add a x y pos = update pos y $ update (pos !! y) x a
add2or4 :: Position -> RVar Position
add2or4 pos = do
(x,y) <- randomElement [(x,y) | y<-indicesOf pos, x<-indicesOf (pos!!y), pos!!y!!x ==0 ]
a <- categorical [(0.9::Double,2), (0.1,4) ]
return $ add a x y pos
-}
-- or with lens:
indicesOf :: [a] -> [ReifiedTraversal' [a] a]
indicesOf l = [ Traversal $ ix i | i <- [0..length l - 1] ]
indices2Of :: [[a]] -> [ReifiedTraversal' [[a]] a]
indices2Of ls = [ Traversal $ i.j | Traversal i <- indicesOf ls, let Just l = ls ^? i, Traversal j <- indicesOf l]
add2or4 :: Position -> RVar Position
add2or4 pos = do
xy <- randomElement [ xy | Traversal xy <- indices2Of pos, pos ^? xy == Just 0 ]
a <- categorical [(1-prob4, 2), (prob4, 4) ]
return $ pos & xy .~ a
-- Easy, is'n it'?
-- Main loop
play :: Position -> IO ()
play pos = do
c <- getChar
case go pos $ lookup c [('D',left),('C',right),('A',up),('B',down)] of
Nothing -> play pos
Just pos1 -> do
pos2 <- sample $ add2or4 pos1
draw pos2
when (win pos2 && not (win pos)) $ putStrLn $ "You win! You may keep going."
if lost pos2 then putStrLn "You lost!"
else play pos2
main :: IO ()
main = do
pos <- sample $ add2or4 $ replicate 4 (replicate 4 0)
draw pos
play pos
-- Rendering
-- See https://en.wikipedia.org/wiki/ANSI_escape_code#Colors
colors =
[(0,"\ESC[38;5;234;48;5;250m ")
,(2,"\ESC[38;5;234;48;5;255m 2 ")
,(4,"\ESC[38;5;234;48;5;230m 4 ")
,(8,"\ESC[38;5;15;48;5;208m 8 ")
,(16,"\ESC[38;5;15;48;5;209m 16 ")
,(32,"\ESC[38;5;15;48;5;203m 32 ")
,(64,"\ESC[38;5;15;48;5;9m 64 ")
,(128,"\ESC[38;5;15;48;5;228m 128 ")
,(256,"\ESC[38;5;15;48;5;227m 256 ")
,(512,"\ESC[38;5;15;48;5;226m 512 ")
,(1024,"\ESC[38;5;15;48;5;221m 1024")
,(2048,"\ESC[38;5;15;48;5;220m 2048")
,(4096,"\ESC[38;5;15;48;5;0m 4096")
,(8192,"\ESC[38;5;15;48;5;0m 8192")
,(16384,"\ESC[38;5;15;48;5;0m16384")
,(32768,"\ESC[38;5;15;48;5;0m32768")
,(65536,"\ESC[38;5;15;48;5;0m65536")
,(131072,"\ESC[38;5;15;48;5;90m131072")
]
showTile x = fromJust (lookup x colors) ++ "\ESC[B\^H\^H\^H\^H\^H \ESC[A\ESC[C"
draw :: Position -> IO ()
draw pos = do
setSGR [Reset]
clearScreen
hideCursor
hSetEcho stdin False
hSetBuffering stdin NoBuffering
setSGR [SetConsoleIntensity BoldIntensity]
putStr "\ESC[38;5;234;48;5;248m" -- set board color
setCursorPosition 0 0
replicateM_ 13 $ putStrLn $ replicate 26 ' '
setCursorPosition 1 1
putStrLn $ intercalate "\n\n\n\ESC[C" $ concatMap showTile `map` pos
|
http://rosettacode.org/wiki/4-rings_or_4-squares_puzzle | 4-rings or 4-squares puzzle | 4-rings or 4-squares puzzle
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Replace a, b, c, d, e, f, and
g with the decimal
digits LOW ───► HIGH
such that the sum of the letters inside of each of the four large squares add up to
the same sum.
╔══════════════╗ ╔══════════════╗
║ ║ ║ ║
║ a ║ ║ e ║
║ ║ ║ ║
║ ┌───╫──────╫───┐ ┌───╫─────────┐
║ │ ║ ║ │ │ ║ │
║ │ b ║ ║ d │ │ f ║ │
║ │ ║ ║ │ │ ║ │
║ │ ║ ║ │ │ ║ │
╚══════════╪═══╝ ╚═══╪══════╪═══╝ │
│ c │ │ g │
│ │ │ │
│ │ │ │
└──────────────┘ └─────────────┘
Show all output here.
Show all solutions for each letter being unique with
LOW=1 HIGH=7
Show all solutions for each letter being unique with
LOW=3 HIGH=9
Show only the number of solutions when each letter can be non-unique
LOW=0 HIGH=9
Related task
Solve the no connection puzzle
| #XPL0 | XPL0 | int Show, Low, High, Digit(7\a..g\), Count;
proc Rings(Level);
int Level; \of recursion
int D, Temp, I, Set;
[for D:= Low to High do
[Digit(Level):= D;
if Level < 7-1 then Rings(Level+1)
else [ Temp:= Digit(0) + Digit(1); \solution?
if Temp = Digit(1) + Digit(2) + Digit(3) and
Temp = Digit(3) + Digit(4) + Digit(5) and
Temp = Digit(5) + Digit(6) then
[Count:= Count+1;
if Show then
[Set:= 0; \digits must be unique
for I:= 0 to 7-1 do
Set:= Set ! 1<<Digit(I);
if Set = %111_1111 << Low then
[for I:= 0 to 7-1 do
[IntOut(0, Digit(I)); ChOut(0, ^ )];
CrLf(0);
];
];
];
];
];
];
[Show:= true;
Low:= 1; High:= 7;
Rings(0);
CrLf(0);
Low:= 3; High:= 9;
Rings(0);
CrLf(0);
Show:= false;
Low:= 0; High:= 9; Count:= 0;
Rings(0);
IntOut(0, Count);
CrLf(0);
] |
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
| #BASIC | BASIC |
const bottle = " bottle"
const plural = "s"
const ofbeer = " of beer"
const wall = " on the wall"
const sep = ", "
const takedown = "Take one down and pass it around, "
const u_no = "No"
const l_no = "no"
const more = " more bottles of beer"
const store = "Go to the store and buy some more, "
const dotnl = ".\n"
const nl = "\n"
// Reserve 1024 bytes in the .bss section
var x 1024
// Write two digits, based on the value in a
fun printnum
b = a
a >= 10
a /= 10
// modulo is in the d register after idiv
b = d
a += 48 // ASCII value for '0'
print(chr(a))
end
a = b
a += 48 // ASCII value for '0'
print(chr(a))
end
fun main
loop 99
// Save loop counter for later, twice
c -> stack
c -> stack
// Print the loop counter (passed in the a register)
a = c
printnum()
// N, "bottles of beer on the wall, "
x = bottle
x += plural
x += ofbeer
x += wall
x += sep
print(x)
// Retrieve and print the number
stack -> a
printnum()
// N, "bottles of beer.\nTake one down and pass it around,"
x = bottle
x += plural
x += ofbeer
x += dotnl
x += takedown
print(x)
// N-1, "bottles of beer on the wall."
stack -> a
a--
// Store N-1, used just a few lines down
a -> stack
printnum()
print(bottle)
// Retrieve N-1
stack -> a
// Write an "s" if the count is not 1
a != 1
print(plural)
end
// Write the rest + a blank line
x = ofbeer
x += wall
x += dotnl
x += nl
print(x)
// Skip to the top of the loop while the counter is >= 2
continue (c >= 2)
// At the last two
// "1 bottle of beer on the wall,"
a = 1
printnum()
x = bottle
x += ofbeer
x += wall
x += sep
print(x)
// "1"
a = 1
printnum()
// "bottle of beer. Take one down and pass it around,"
// "no more bottles of beer on the wall."
// Blank line
// "No more bottles of beer on the wall,"
// "no more bottles of beer."
// "Go to the store and buy some more,"
x = bottle
x += ofbeer
x += dotnl
x += takedown
x += l_no
x += more
x += wall
x += dotnl
x += nl
x += u_no
x += more
x += wall
x += sep
x += l_no
x += more
x += dotnl
x += store
print(x)
// "99"
a = 99
printnum()
// "bottles of beer on the wall."
x = bottle
x += plural
x += ofbeer
x += wall
x += dotnl
print(x)
end
end
// vim: set syntax=c ts=4 sw=4 et:
|
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.
| #JavaScript | JavaScript |
function twentyfour(numbers, input) {
var invalidChars = /[^\d\+\*\/\s-\(\)]/;
var validNums = function(str) {
// Create a duplicate of our input numbers, so that
// both lists will be sorted.
var mnums = numbers.slice();
mnums.sort();
// Sort after mapping to numbers, to make comparisons valid.
return str.replace(/[^\d\s]/g, " ")
.trim()
.split(/\s+/)
.map(function(n) { return parseInt(n, 10); })
.sort()
.every(function(v, i) { return v === mnums[i]; });
};
var validEval = function(input) {
try {
return eval(input);
} catch (e) {
return {error: e.toString()};
}
};
if (input.trim() === "") return "You must enter a value.";
if (input.match(invalidChars)) return "Invalid chars used, try again. Use only:\n + - * / ( )";
if (!validNums(input)) return "Wrong numbers used, try again.";
var calc = validEval(input);
if (typeof calc !== 'number') return "That is not a valid input; please try again.";
if (calc !== 24) return "Wrong answer: " + String(calc) + "; please try again.";
return input + " == 24. Congratulations!";
};
// I/O below.
while (true) {
var numbers = [1, 2, 3, 4].map(function() {
return Math.floor(Math.random() * 8 + 1);
});
var input = prompt(
"Your numbers are:\n" + numbers.join(" ") +
"\nEnter expression. (use only + - * / and parens).\n", +"'x' to exit.", "");
if (input === 'x') {
break;
}
alert(twentyfour(numbers, input));
}
|
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
| #EchoLisp | EchoLisp |
(+ (read-number 1 "value for A") (read-number 2 "value for B"))
|
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #ZED | ZED | (A) m n
comment:
(=) m 0
(add1) n
(A) m n
comment:
(=) n 0
(A) (sub1) m 1
(A) m n
comment:
#true
(A) (sub1) m (A) m (sub1) n
(add1) n
comment:
#true
(003) "+" n 1
(sub1) n
comment:
#true
(003) "-" n 1
(=) n1 n2
comment:
#true
(003) "=" n1 n2 |
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
| #Lua | Lua | 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"};
};
function canUse(table, letter)
for i,v in pairs(blocks) do
if (v[1] == letter:upper() or v[2] == letter:upper()) and table[i] then
table[i] = false;
return true;
end
end
return false;
end
function canMake(Word)
local Taken = {};
for i,v in pairs(blocks) do
table.insert(Taken,true);
end
local found = true;
for i = 1,#Word do
if not canUse(Taken,Word:sub(i,i)) then
found = false;
end
end
print(found)
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.
| #jq | jq | export LC_ALL=C
< /dev/urandom tr -cd '0-9' | fold -w 1 | jq -MRcnr -f 100-prisoners.jq |
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
| #PicoLisp | PicoLisp | (be play24 (@Lst @Expr) # Define Pilog rule
(permute @Lst (@A @B @C @D))
(member @Op1 (+ - * /))
(member @Op2 (+ - * /))
(member @Op3 (+ - * /))
(or
((equal @Expr (@Op1 (@Op2 @A @B) (@Op3 @C @D))))
((equal @Expr (@Op1 @A (@Op2 @B (@Op3 @C @D))))) )
(^ @ (= 24 (catch '("Div/0") (eval (-> @Expr))))) )
(de play24 (A B C D) # Define PicoLisp function
(pilog
(quote
@L (list A B C D)
(play24 @L @X) )
(println @X) ) )
(play24 5 6 7 8) # Call 'play24' function |
http://rosettacode.org/wiki/15_puzzle_game | 15 puzzle game |
Task
Implement the Fifteen Puzzle Game.
The 15-puzzle is also known as:
Fifteen Puzzle
Gem Puzzle
Boss Puzzle
Game of Fifteen
Mystic Square
14-15 Puzzle
and some others.
Related Tasks
15 Puzzle Solver
16 Puzzle Game
| #Fortran | Fortran | LOCZ = MINLOC(BOARD) !Find the zero. 0 = BOARD(LOCZ(1),LOCZ(2)) == BOARD(ZC,ZR) |
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.
| #J | J | NB. 2048.ijs script
NB. =========================================================
NB. 2048 game engine
require 'guid'
([ 9!:1) _2 (3!:4) , guids 1 NB. randomly set initial random seed
coclass 'g2048'
Target=: 2048
new2048=: verb define
Gridsz=: 4 4
Points=: Score=: 0
Grid=: newnum^:2 ] Gridsz $ 0
)
newnum=: verb define
num=. 2 4 {~ 0.1 > ?0 NB. 10% chance of 4
idx=. 4 $. $. 0 = y NB. indicies of 0s
if. #idx do. NB. handle full grid
idx=. ,/ ({~ 1 ? #) idx NB. choose an index
num (<idx)} y
else. return. y
end.
)
mskmerge=: [: >/\.&.|. 2 =/\ ,&_1
mergerow=: ((* >:) #~ _1 |. -.@]) mskmerge
scorerow=: +/@(+: #~ mskmerge)
compress=: -.&0
toLeft=: 1 :'4&{.@(u@compress)"1'
toRight=: 1 : '_4&{.@(u@compress&.|.)"1'
toUp=: 1 : '(4&{.@(u@compress)"1)&.|:'
toDown=: 1 : '(_4&{.@(u@compress&.|.)"1)&.|:'
move=: conjunction define
Points=: +/@, v Grid
update newnum^:(Grid -.@-: ]) u Grid
)
noMoves=: (0 -.@e. ,)@(mergerow toRight , mergerow toLeft , mergerow toUp ,: mergerow toDown)
hasWon=: Target e. ,
eval=: verb define
Score=: Score + Points
isend=. (noMoves , hasWon) y
msg=. isend # 'You lost!!';'You Won!!'
if. -. isend=. +./ isend do.
Points=: 0
msg=. 'Score is ',(": Score)
end.
isend;msg
)
showGrid=: echo
NB. =========================================================
NB. Console user interface
g2048Con_z_=: conew&'g2048con'
coclass 'g2048con'
coinsert 'g2048'
create=: verb define
echo Instructions
startnew y
)
destroy=: codestroy
quit=: destroy
startnew=: update@new2048
left=: 3 :'mergerow toLeft move (scorerow toLeft)'
right=: 3 :'mergerow toRight move (scorerow toRight)'
up=: 3 :'mergerow toUp move (scorerow toUp)'
down=: 3 :'mergerow toDown move (scorerow toDown)'
update=: verb define
Grid=: y NB. update global Grid
'isend msg'=. eval y
echo msg
showGrid y
if. isend do. destroy '' end.
empty''
)
Instructions=: noun define
=== 2048 ===
Object:
Create the number 2048 by merging numbers.
How to play:
When 2 numbers the same touch, they merge.
- move numbers using the commands below:
right__grd ''
left__grd ''
up__grd ''
down__grd ''
- quit a game:
quit__grd ''
- start a new game:
grd=: g2048Con ''
) |
http://rosettacode.org/wiki/4-rings_or_4-squares_puzzle | 4-rings or 4-squares puzzle | 4-rings or 4-squares puzzle
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Replace a, b, c, d, e, f, and
g with the decimal
digits LOW ───► HIGH
such that the sum of the letters inside of each of the four large squares add up to
the same sum.
╔══════════════╗ ╔══════════════╗
║ ║ ║ ║
║ a ║ ║ e ║
║ ║ ║ ║
║ ┌───╫──────╫───┐ ┌───╫─────────┐
║ │ ║ ║ │ │ ║ │
║ │ b ║ ║ d │ │ f ║ │
║ │ ║ ║ │ │ ║ │
║ │ ║ ║ │ │ ║ │
╚══════════╪═══╝ ╚═══╪══════╪═══╝ │
│ c │ │ g │
│ │ │ │
│ │ │ │
└──────────────┘ └─────────────┘
Show all output here.
Show all solutions for each letter being unique with
LOW=1 HIGH=7
Show all solutions for each letter being unique with
LOW=3 HIGH=9
Show only the number of solutions when each letter can be non-unique
LOW=0 HIGH=9
Related task
Solve the no connection puzzle
| #Yabasic | Yabasic | fourSquare(1,7,true,true)
fourSquare(3,9,true,true)
fourSquare(0,9,false,false)
sub fourSquare(low, high, unique, prin)
local count, a, b, c, d, e, f, g, fp
if (prin) print "a b c d e f g"
for a = low to high
for b = low to high
if (not valid(unique, a, b)) continue
fp = a+b
for c = low to high
if (not valid(unique, c, a, b)) continue
for d = low to high
if (not valid(unique, d, a, b, c)) continue
if (fp <> b+c+d) continue
for e = low to high
if (not valid(unique, e, a, b, c, d)) continue
for f = low to high
if (not valid(unique, f, a, b, c, d, e)) continue
if (fp <> d+e+f) continue
for g = low to high
if (not valid(unique, g, a, b, c, d, e, f)) continue
if (fp <> f+g) continue
count = count + 1
if (prin) print a," ",b," ",c," ",d," ",e," ",f," ",g
next
next
next
next
next
next
next
if (unique) then
print "There are ", count, " unique solutions in [",low,",",high,"]"
else
print "There are ", count, " non-unique solutions in [",low,",",high,"]"
end if
end sub
sub valid(unique, needle, n1, n2, n3, n4, n5, n6)
local i
if (unique) then
for i = 1 to numparams - 2
switch i
case 1: if needle = n1 return false : break
case 2: if needle = n2 return false : break
case 3: if needle = n3 return false : break
case 4: if needle = n4 return false : break
case 5: if needle = n5 return false : break
case 6: if needle = n6 return false : break
end switch
next
end if
return true
end sub |
http://rosettacode.org/wiki/99_bottles_of_beer | 99 bottles of beer | Task
Display the complete lyrics for the song: 99 Bottles of Beer on the Wall.
The beer song
The lyrics follow this form:
99 bottles of beer on the wall
99 bottles of beer
Take one down, pass it around
98 bottles of beer on the wall
98 bottles of beer on the wall
98 bottles of beer
Take one down, pass it around
97 bottles of beer on the wall
... and so on, until reaching 0 (zero).
Grammatical support for 1 bottle of beer is optional.
As with any puzzle, try to do it in as creative/concise/comical a way
as possible (simple, obvious solutions allowed, too).
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
See also
http://99-bottles-of-beer.net/
Category:99_Bottles_of_Beer
Category:Programming language families
Wikipedia 99 bottles of beer
| #Batch_File | Batch File |
const bottle = " bottle"
const plural = "s"
const ofbeer = " of beer"
const wall = " on the wall"
const sep = ", "
const takedown = "Take one down and pass it around, "
const u_no = "No"
const l_no = "no"
const more = " more bottles of beer"
const store = "Go to the store and buy some more, "
const dotnl = ".\n"
const nl = "\n"
// Reserve 1024 bytes in the .bss section
var x 1024
// Write two digits, based on the value in a
fun printnum
b = a
a >= 10
a /= 10
// modulo is in the d register after idiv
b = d
a += 48 // ASCII value for '0'
print(chr(a))
end
a = b
a += 48 // ASCII value for '0'
print(chr(a))
end
fun main
loop 99
// Save loop counter for later, twice
c -> stack
c -> stack
// Print the loop counter (passed in the a register)
a = c
printnum()
// N, "bottles of beer on the wall, "
x = bottle
x += plural
x += ofbeer
x += wall
x += sep
print(x)
// Retrieve and print the number
stack -> a
printnum()
// N, "bottles of beer.\nTake one down and pass it around,"
x = bottle
x += plural
x += ofbeer
x += dotnl
x += takedown
print(x)
// N-1, "bottles of beer on the wall."
stack -> a
a--
// Store N-1, used just a few lines down
a -> stack
printnum()
print(bottle)
// Retrieve N-1
stack -> a
// Write an "s" if the count is not 1
a != 1
print(plural)
end
// Write the rest + a blank line
x = ofbeer
x += wall
x += dotnl
x += nl
print(x)
// Skip to the top of the loop while the counter is >= 2
continue (c >= 2)
// At the last two
// "1 bottle of beer on the wall,"
a = 1
printnum()
x = bottle
x += ofbeer
x += wall
x += sep
print(x)
// "1"
a = 1
printnum()
// "bottle of beer. Take one down and pass it around,"
// "no more bottles of beer on the wall."
// Blank line
// "No more bottles of beer on the wall,"
// "no more bottles of beer."
// "Go to the store and buy some more,"
x = bottle
x += ofbeer
x += dotnl
x += takedown
x += l_no
x += more
x += wall
x += dotnl
x += nl
x += u_no
x += more
x += wall
x += sep
x += l_no
x += more
x += dotnl
x += store
print(x)
// "99"
a = 99
printnum()
// "bottles of beer on the wall."
x = bottle
x += plural
x += ofbeer
x += wall
x += dotnl
print(x)
end
end
// vim: set syntax=c ts=4 sw=4 et:
|
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.
| #Julia | Julia | validexpr(ex::Expr) = ex.head == :call && ex.args[1] in [:*,:/,:+,:-] && all(validexpr, ex.args[2:end])
validexpr(ex::Int) = true
validexpr(ex::Any) = false
findnumbers(ex::Number) = Int[ex]
findnumbers(ex::Expr) = vcat(map(findnumbers, ex.args)...)
findnumbers(ex::Any) = Int[]
function twentyfour()
digits = sort!(rand(1:9, 4))
while true
print("enter expression using $digits => ")
ex = parse(readline())
try
validexpr(ex) || error("only *, /, +, - of integers is allowed")
nums = sort!(findnumbers(ex))
nums == digits || error("expression $ex used numbers $nums != $digits")
val = eval(ex)
val == 24 || error("expression $ex evaluated to $val, not 24")
println("you won!")
return
catch e
if isa(e, ErrorException)
println("incorrect: ", e.msg)
else
rethrow()
end
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
| #EDSAC_order_code | EDSAC order code | [ A plus B
========
A program for the EDSAC
Adds two integers & displays
the sum at the top of storage
tank 3
Works with Initial Orders 2 ]
[ Set load point & base address ]
T56K [ Load at address 56 ]
GK [ Base addr (theta) here ]
[ Orders ]
T96F [ Clear accumulator ]
A5@ [ Acc += C(theta + 5) ]
A6@ [ Acc += C(theta + 6) ]
T96F [ C(96) = Acc; Acc = 0 ]
ZF [ Halt ]
[ Pseudo-orders (data) ]
P18D [ 5@: 18*2 + 1 = 37 ]
P14F [ 6@: 14*2 + 0 = 28 ]
[ When loading is finished: ]
EZPF [ Branch to load point ] |
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #Zig | Zig | pub fn ack(m: u64, n: u64) u64 {
if (m == 0) return n + 1;
if (n == 0) return ack(m - 1, 1);
return ack(m - 1, ack(m, n - 1));
}
pub fn main() !void {
const stdout = @import("std").io.getStdOut().writer();
var m: u8 = 0;
while (m <= 3) : (m += 1) {
var n: u8 = 0;
while (n <= 8) : (n += 1)
try stdout.print("{d:>8}", .{ack(m, n)});
try stdout.print("\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
| #M2000_Interpreter | M2000 Interpreter |
Module ABC {
can_make_word("A")
can_make_word("BaRk")
can_make_word("BOOK")
can_make_word("TREAT")
can_make_word("CommoN")
can_make_word("SQUAD")
Gosub can_make_word("CONFUSE") ' we can use Gosub before
Sub can_make_word(c$)
local b$=ucase$(c$)
local i, a$="BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM", m
for i=1 to len(b$)
m=Instr(a$,mid$(b$, i, 1))
If m=0 Then Exit for
Insert binary.or(m-1, 1),2 a$="" ' delete 2 chars
Next i
Print c$, m<>0
End Sub
}
ABC
|
http://rosettacode.org/wiki/100_prisoners | 100 prisoners |
The Problem
100 prisoners are individually numbered 1 to 100
A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside.
Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start.
Prisoners start outside the room
They can decide some strategy before any enter the room.
Prisoners enter the room one by one, can open a drawer, inspect the card number in the drawer, then close the drawer.
A prisoner can open no more than 50 drawers.
A prisoner tries to find his own number.
A prisoner finding his own number is then held apart from the others.
If all 100 prisoners find their own numbers then they will all be pardoned. If any don't then all sentences stand.
The task
Simulate several thousand instances of the game where the prisoners randomly open drawers
Simulate several thousand instances of the game where the prisoners use the optimal strategy mentioned in the Wikipedia article, of:
First opening the drawer whose outside number is his prisoner number.
If the card within has his number then he succeeds otherwise he opens the drawer with the same number as that of the revealed card. (until he opens his maximum).
Show and compare the computed probabilities of success for the two strategies, here, on this page.
References
The unbelievable solution to the 100 prisoner puzzle standupmaths (Video).
wp:100 prisoners problem
100 Prisoners Escape Puzzle DataGenetics.
Random permutation statistics#One hundred prisoners on Wikipedia.
| #Julia | Julia | using Random, Formatting
function randomplay(n, numprisoners=100)
pardoned, indrawer, found = 0, collect(1:numprisoners), false
for i in 1:n
shuffle!(indrawer)
for prisoner in 1:numprisoners
found = false
for reveal in randperm(numprisoners)[1:div(numprisoners, 2)]
indrawer[reveal] == prisoner && (found = true) && break
end
!found && break
end
found && (pardoned += 1)
end
return 100.0 * pardoned / n
end
function optimalplay(n, numprisoners=100)
pardoned, indrawer, found = 0, collect(1:numprisoners), false
for i in 1:n
shuffle!(indrawer)
for prisoner in 1:numprisoners
reveal = prisoner
found = false
for j in 1:div(numprisoners, 2)
card = indrawer[reveal]
card == prisoner && (found = true) && break
reveal = card
end
!found && break
end
found && (pardoned += 1)
end
return 100.0 * pardoned / n
end
const N = 100_000
println("Simulation count: $N")
println("Random play wins: ", format(randomplay(N), precision=8), "% of simulations.")
println("Optimal play wins: ", format(optimalplay(N), precision=8), "% of simulations.")
|
http://rosettacode.org/wiki/24_game/Solve | 24 game/Solve | task
Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the 24 game.
Show examples of solutions generated by the program.
Related task
Arithmetic Evaluator
| #ProDOS | ProDOS | editvar /modify -random- = <10
:a
editvar /newvar /withothervar /value=-random- /title=1
editvar /newvar /withothervar /value=-random- /title=2
editvar /newvar /withothervar /value=-random- /title=3
editvar /newvar /withothervar /value=-random- /title=4
printline These are your four digits: -1- -2- -3- -4-
printline Use an algorithm to make the number 24.
editvar /newvar /value=a /userinput=1 /title=Algorithm:
do -a-
if -a- /hasvalue 24 printline Your algorithm worked! & goto :b (
) else printline Your algorithm did not work.
editvar /newvar /value=b /userinput=1 /title=Do you want to see how you could have done it?
if -b- /hasvalue y goto :c else goto :b
:b
editvar /newvar /value=c /userinput=1 /title=Do you want to play again?
if -c- /hasvalue y goto :a else exitcurrentprogram
:c
editvar /newvar /value=do -1- + -2- + -3- + -4- /title=c & do -c- >d & if -d- /hasvalue 24 goto :solve
editvar /newvar /value=do -1- - -2- + -3- + -4- /title=c & do -c- >d & if -d- /hasvalue 24 goto :solve
editvar /newvar /value=do -1- / -2- + -3- + -4- /title=c & do -c- >d & if -d- /hasvalue 24 goto :solve
editvar /newvar /value=do -1- * -2- + -3- + -4- /title=c & do -c- >d & if -d- /hasvalue 24 goto :solve
editvar /newvar /value=do -1- + -2- - -3- + -4- /title=c & do -c- >d & if -d- /hasvalue 24 goto :solve
editvar /newvar /value=do -1- + -2- / -3- + -4- /title=c & do -c- >d & if -d- /hasvalue 24 goto :solve
editvar /newvar /value=do -1- + -2- * -3- + -4- /title=c & do -c- >d & if -d- /hasvalue 24 goto :solve
editvar /newvar /value=do -1- + -2- + -3- - -4- /title=c & do -c- >d & if -d- /hasvalue 24 goto :solve
editvar /newvar /value=do -1- + -2- + -3- / -4- /title=c & do -c- >d & if -d- /hasvalue 24 goto :solve
editvar /newvar /value=do -1- + -2- + -3- * -4- /title=c & do -c- >d & if -d- /hasvalue 24 goto :solve
editvar /newvar /value=do -1- - -2- - -3- - -4- /title=c & do -c- >d & if -d- /hasvalue 24 goto :solve
editvar /newvar /value=do -1- / -2- / -3- / -4- /title=c & do -c- >d & if -d- /hasvalue 24 goto :solve
editvar /newvar /value=do -1- * -2- * -3- * -4- /title=c & do -c- >d & if -d- /hasvalue 24 goto :solve
:solve
printline you could have done it by doing -c-
stoptask
goto :b |
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
| #FreeBASIC | FreeBASIC | sub drawboard( B() as ubyte )
dim as string outstr = ""
for i as ubyte = 0 to 15
if B(i) = 0 then
outstr = outstr + " XX "
elseif B(i) < 10 then
outstr = outstr + " "+str(B(i))+" "
else
outstr = outstr + " " +str(B(i))+" "
end if
if i mod 4 = 3 then
print outstr
print
outstr = ""
end if
next i
print
end sub
function move( B() as ubyte, byref gap as ubyte, direction as ubyte ) as ubyte
dim as integer targ = gap
select case direction
case 1 'UP
targ = gap - 4
case 2 'RIGHT
if gap mod 4 = 3 then return gap
targ = gap + 1
case 3 'DOWN
targ = gap + 4
case 4
if gap mod 4 = 0 then return gap
targ = gap - 1
case else
return gap
end select
if targ > 15 or targ < 0 then return gap
swap B(targ), B(gap)
return targ
end function
sub shuffle( B() as ubyte, byref gap as ubyte )
for i as ubyte = 0 to 100
gap = move(B(), gap, int(rnd*4) + 1)
next i
end sub
function solved( B() as ubyte ) as boolean
dim as integer i
for i = 0 to 14
if B(i)>B(i+1) then return false
next i
return true
end function
dim as ubyte i, B(15), direction, gap
for i = 0 to 15
B(i) = i
next i
shuffle B(), gap
while not solved( B() )
cls
drawboard B()
print gap
print "1 = up, 2=right, 3=down, 4=left"
input direction
gap = move( B(), gap, direction )
wend
cls
print "Congratulations! You win!"
print
drawboard 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.
| #Java | Java | import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import javax.swing.*;
public class Game2048 extends JPanel {
enum State {
start, won, running, over
}
final Color[] colorTable = {
new Color(0x701710), new Color(0xFFE4C3), new Color(0xfff4d3),
new Color(0xffdac3), new Color(0xe7b08e), new Color(0xe7bf8e),
new Color(0xffc4c3), new Color(0xE7948e), new Color(0xbe7e56),
new Color(0xbe5e56), new Color(0x9c3931), new Color(0x701710)};
final static int target = 2048;
static int highest;
static int score;
private Color gridColor = new Color(0xBBADA0);
private Color emptyColor = new Color(0xCDC1B4);
private Color startColor = new Color(0xFFEBCD);
private Random rand = new Random();
private Tile[][] tiles;
private int side = 4;
private State gamestate = State.start;
private boolean checkingAvailableMoves;
public Game2048() {
setPreferredSize(new Dimension(900, 700));
setBackground(new Color(0xFAF8EF));
setFont(new Font("SansSerif", Font.BOLD, 48));
setFocusable(true);
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
startGame();
repaint();
}
});
addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_UP:
moveUp();
break;
case KeyEvent.VK_DOWN:
moveDown();
break;
case KeyEvent.VK_LEFT:
moveLeft();
break;
case KeyEvent.VK_RIGHT:
moveRight();
break;
}
repaint();
}
});
}
@Override
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
drawGrid(g);
}
void startGame() {
if (gamestate != State.running) {
score = 0;
highest = 0;
gamestate = State.running;
tiles = new Tile[side][side];
addRandomTile();
addRandomTile();
}
}
void drawGrid(Graphics2D g) {
g.setColor(gridColor);
g.fillRoundRect(200, 100, 499, 499, 15, 15);
if (gamestate == State.running) {
for (int r = 0; r < side; r++) {
for (int c = 0; c < side; c++) {
if (tiles[r][c] == null) {
g.setColor(emptyColor);
g.fillRoundRect(215 + c * 121, 115 + r * 121, 106, 106, 7, 7);
} else {
drawTile(g, r, c);
}
}
}
} else {
g.setColor(startColor);
g.fillRoundRect(215, 115, 469, 469, 7, 7);
g.setColor(gridColor.darker());
g.setFont(new Font("SansSerif", Font.BOLD, 128));
g.drawString("2048", 310, 270);
g.setFont(new Font("SansSerif", Font.BOLD, 20));
if (gamestate == State.won) {
g.drawString("you made it!", 390, 350);
} else if (gamestate == State.over)
g.drawString("game over", 400, 350);
g.setColor(gridColor);
g.drawString("click to start a new game", 330, 470);
g.drawString("(use arrow keys to move tiles)", 310, 530);
}
}
void drawTile(Graphics2D g, int r, int c) {
int value = tiles[r][c].getValue();
g.setColor(colorTable[(int) (Math.log(value) / Math.log(2)) + 1]);
g.fillRoundRect(215 + c * 121, 115 + r * 121, 106, 106, 7, 7);
String s = String.valueOf(value);
g.setColor(value < 128 ? colorTable[0] : colorTable[1]);
FontMetrics fm = g.getFontMetrics();
int asc = fm.getAscent();
int dec = fm.getDescent();
int x = 215 + c * 121 + (106 - fm.stringWidth(s)) / 2;
int y = 115 + r * 121 + (asc + (106 - (asc + dec)) / 2);
g.drawString(s, x, y);
}
private void addRandomTile() {
int pos = rand.nextInt(side * side);
int row, col;
do {
pos = (pos + 1) % (side * side);
row = pos / side;
col = pos % side;
} while (tiles[row][col] != null);
int val = rand.nextInt(10) == 0 ? 4 : 2;
tiles[row][col] = new Tile(val);
}
private boolean move(int countDownFrom, int yIncr, int xIncr) {
boolean moved = false;
for (int i = 0; i < side * side; i++) {
int j = Math.abs(countDownFrom - i);
int r = j / side;
int c = j % side;
if (tiles[r][c] == null)
continue;
int nextR = r + yIncr;
int nextC = c + xIncr;
while (nextR >= 0 && nextR < side && nextC >= 0 && nextC < side) {
Tile next = tiles[nextR][nextC];
Tile curr = tiles[r][c];
if (next == null) {
if (checkingAvailableMoves)
return true;
tiles[nextR][nextC] = curr;
tiles[r][c] = null;
r = nextR;
c = nextC;
nextR += yIncr;
nextC += xIncr;
moved = true;
} else if (next.canMergeWith(curr)) {
if (checkingAvailableMoves)
return true;
int value = next.mergeWith(curr);
if (value > highest)
highest = value;
score += value;
tiles[r][c] = null;
moved = true;
break;
} else
break;
}
}
if (moved) {
if (highest < target) {
clearMerged();
addRandomTile();
if (!movesAvailable()) {
gamestate = State.over;
}
} else if (highest == target)
gamestate = State.won;
}
return moved;
}
boolean moveUp() {
return move(0, -1, 0);
}
boolean moveDown() {
return move(side * side - 1, 1, 0);
}
boolean moveLeft() {
return move(0, 0, -1);
}
boolean moveRight() {
return move(side * side - 1, 0, 1);
}
void clearMerged() {
for (Tile[] row : tiles)
for (Tile tile : row)
if (tile != null)
tile.setMerged(false);
}
boolean movesAvailable() {
checkingAvailableMoves = true;
boolean hasMoves = moveUp() || moveDown() || moveLeft() || moveRight();
checkingAvailableMoves = false;
return hasMoves;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("2048");
f.setResizable(true);
f.add(new Game2048(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}
class Tile {
private boolean merged;
private int value;
Tile(int val) {
value = val;
}
int getValue() {
return value;
}
void setMerged(boolean m) {
merged = m;
}
boolean canMergeWith(Tile other) {
return !merged && other != null && !other.merged && value == other.getValue();
}
int mergeWith(Tile other) {
if (canMergeWith(other)) {
value *= 2;
merged = true;
return value;
}
return -1;
}
} |
http://rosettacode.org/wiki/4-rings_or_4-squares_puzzle | 4-rings or 4-squares puzzle | 4-rings or 4-squares puzzle
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Replace a, b, c, d, e, f, and
g with the decimal
digits LOW ───► HIGH
such that the sum of the letters inside of each of the four large squares add up to
the same sum.
╔══════════════╗ ╔══════════════╗
║ ║ ║ ║
║ a ║ ║ e ║
║ ║ ║ ║
║ ┌───╫──────╫───┐ ┌───╫─────────┐
║ │ ║ ║ │ │ ║ │
║ │ b ║ ║ d │ │ f ║ │
║ │ ║ ║ │ │ ║ │
║ │ ║ ║ │ │ ║ │
╚══════════╪═══╝ ╚═══╪══════╪═══╝ │
│ c │ │ g │
│ │ │ │
│ │ │ │
└──────────────┘ └─────────────┘
Show all output here.
Show all solutions for each letter being unique with
LOW=1 HIGH=7
Show all solutions for each letter being unique with
LOW=3 HIGH=9
Show only the number of solutions when each letter can be non-unique
LOW=0 HIGH=9
Related task
Solve the no connection puzzle
| #zkl | zkl | // unique: No repeated numbers in solution
fcn fourSquaresPuzzle(lo=1,hi=7,unique=True){ //-->list of solutions
_assert_(0<=lo and hi<36);
notUnic:=fcn(a,b,c,etc){ abc:=vm.arglist; // use base 36, any repeated character?
abc.apply("toString",36).concat().unique().len()!=abc.len()
};
s:=List(); // solutions
foreach a,b,c in ([lo..hi],[lo..hi],[lo..hi]){ // chunk to reduce unique
if(unique and notUnic(a,b,c)) continue; // solution space. Slow VM
foreach d,e in ([lo..hi],[lo..hi]){ // -->for d { for e {} }
if(unique and notUnic(a,b,c,d,e)) continue;
foreach f,g in ([lo..hi],[lo..hi]){
if(unique and notUnic(a,b,c,d,e,f,g)) continue;
sqr1,sqr2,sqr3,sqr4 := a+b,b+c+d,d+e+f,f+g;
if((sqr1==sqr2==sqr3) and sqr1==sqr4) s.append(T(a,b,c,d,e,f,g));
}
}
}
s
} |
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
| #Battlestar | Battlestar |
const bottle = " bottle"
const plural = "s"
const ofbeer = " of beer"
const wall = " on the wall"
const sep = ", "
const takedown = "Take one down and pass it around, "
const u_no = "No"
const l_no = "no"
const more = " more bottles of beer"
const store = "Go to the store and buy some more, "
const dotnl = ".\n"
const nl = "\n"
// Reserve 1024 bytes in the .bss section
var x 1024
// Write two digits, based on the value in a
fun printnum
b = a
a >= 10
a /= 10
// modulo is in the d register after idiv
b = d
a += 48 // ASCII value for '0'
print(chr(a))
end
a = b
a += 48 // ASCII value for '0'
print(chr(a))
end
fun main
loop 99
// Save loop counter for later, twice
c -> stack
c -> stack
// Print the loop counter (passed in the a register)
a = c
printnum()
// N, "bottles of beer on the wall, "
x = bottle
x += plural
x += ofbeer
x += wall
x += sep
print(x)
// Retrieve and print the number
stack -> a
printnum()
// N, "bottles of beer.\nTake one down and pass it around,"
x = bottle
x += plural
x += ofbeer
x += dotnl
x += takedown
print(x)
// N-1, "bottles of beer on the wall."
stack -> a
a--
// Store N-1, used just a few lines down
a -> stack
printnum()
print(bottle)
// Retrieve N-1
stack -> a
// Write an "s" if the count is not 1
a != 1
print(plural)
end
// Write the rest + a blank line
x = ofbeer
x += wall
x += dotnl
x += nl
print(x)
// Skip to the top of the loop while the counter is >= 2
continue (c >= 2)
// At the last two
// "1 bottle of beer on the wall,"
a = 1
printnum()
x = bottle
x += ofbeer
x += wall
x += sep
print(x)
// "1"
a = 1
printnum()
// "bottle of beer. Take one down and pass it around,"
// "no more bottles of beer on the wall."
// Blank line
// "No more bottles of beer on the wall,"
// "no more bottles of beer."
// "Go to the store and buy some more,"
x = bottle
x += ofbeer
x += dotnl
x += takedown
x += l_no
x += more
x += wall
x += dotnl
x += nl
x += u_no
x += more
x += wall
x += sep
x += l_no
x += more
x += dotnl
x += store
print(x)
// "99"
a = 99
printnum()
// "bottles of beer on the wall."
x = bottle
x += plural
x += ofbeer
x += wall
x += dotnl
print(x)
end
end
// vim: set syntax=c ts=4 sw=4 et:
|
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.
| #Kotlin | Kotlin | import java.util.Random
import java.util.Scanner
import java.util.Stack
internal object Game24 {
fun run() {
val r = Random()
val digits = IntArray(4).map { r.nextInt(9) + 1 }
println("Make 24 using these digits: $digits")
print("> ")
val s = Stack<Float>()
var total = 0L
val cin = Scanner(System.`in`)
for (c in cin.nextLine()) {
when (c) {
in '0'..'9' -> {
val d = c - '0'
total += (1 shl (d * 5)).toLong()
s += d.toFloat()
}
else ->
if ("+/-*".indexOf(c) != -1) {
s += c.applyOperator(s.pop(), s.pop())
}
}
}
when {
tally(digits) != total ->
print("Not the same digits. ")
s.peek().compareTo(target) == 0 ->
println("Correct!")
else ->
print("Not correct.")
}
}
private fun Char.applyOperator(a: Float, b: Float) = when (this) {
'+' -> a + b
'-' -> b - a
'*' -> a * b
'/' -> b / a
else -> Float.NaN
}
private fun tally(a: List<Int>): Long = a.reduce({ t, i -> t + (1 shl (i * 5)) }).toLong()
private val target = 24
}
fun main(args: Array<String>) = Game24.run() |
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
| #EGL | EGL |
package programs;
// basic program
//
program AplusB type BasicProgram {}
function main()
try
arg1 string = SysLib.getCmdLineArg(1);
arg2 string = SysLib.getCmdLineArg(2);
int1 int = arg1;
int2 int = arg2;
sum int = int1 + int2;
SysLib.writeStdout("sum1: " + sum);
onException(exception AnyException)
SysLib.writeStdout("No valid input. Provide 2 integer numbers as arguments to the program.");
end
end
end
|
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
−
1
,
1
)
if
m
>
0
and
n
=
0
A
(
m
−
1
,
A
(
m
,
n
−
1
)
)
if
m
>
0
and
n
>
0.
{\displaystyle A(m,n)={\begin{cases}n+1&{\mbox{if }}m=0\\A(m-1,1)&{\mbox{if }}m>0{\mbox{ and }}n=0\\A(m-1,A(m,n-1))&{\mbox{if }}m>0{\mbox{ and }}n>0.\end{cases}}}
Its arguments are never negative and it always terminates.
Task
Write a function which returns the value of
A
(
m
,
n
)
{\displaystyle A(m,n)}
. Arbitrary precision is preferred (since the function grows so quickly), but not required.
See also
Conway chained arrow notation for the Ackermann function.
| #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 DIM s(2000,3)
20 LET s(1,1)=3: REM M
30 LET s(1,2)=7: REM N
40 LET lev=1
50 GO SUB 100
60 PRINT "A(";s(1,1);",";s(1,2);") = ";s(1,3)
70 STOP
100 IF s(lev,1)=0 THEN LET s(lev,3)=s(lev,2)+1: RETURN
110 IF s(lev,2)=0 THEN LET lev=lev+1: LET s(lev,1)=s(lev-1,1)-1: LET s(lev,2)=1: GO SUB 100: LET s(lev-1,3)=s(lev,3): LET lev=lev-1: RETURN
120 LET lev=lev+1
130 LET s(lev,1)=s(lev-1,1)
140 LET s(lev,2)=s(lev-1,2)-1
150 GO SUB 100
160 LET s(lev,1)=s(lev-1,1)-1
170 LET s(lev,2)=s(lev,3)
180 GO SUB 100
190 LET s(lev-1,3)=s(lev,3)
200 LET lev=lev-1
210 RETURN |
http://rosettacode.org/wiki/ABC_problem | ABC problem | ABC problem
You are encouraged to solve this task according to the task description, using any language you may know.
You are given a collection of ABC blocks (maybe like the ones you had when you were a kid).
There are twenty blocks with two letters on each block.
A complete alphabet is guaranteed amongst all sides of the blocks.
The sample collection of blocks:
(B O)
(X K)
(D Q)
(C P)
(N A)
(G T)
(R E)
(T G)
(Q D)
(F S)
(J W)
(H U)
(V I)
(A N)
(O B)
(E R)
(F S)
(L Y)
(P C)
(Z M)
Task
Write a function that takes a string (word) and determines whether the word can be spelled with the given collection of blocks.
The rules are simple:
Once a letter on a block is used that block cannot be used again
The function should be case-insensitive
Show the output on this page for the following 7 words in the following example
Example
>>> can_make_word("A")
True
>>> can_make_word("BARK")
True
>>> can_make_word("BOOK")
False
>>> can_make_word("TREAT")
True
>>> can_make_word("COMMON")
False
>>> can_make_word("SQUAD")
True
>>> can_make_word("CONFUSE")
True
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Maple | Maple | canSpell := proc(w)
local blocks, i, j, word, letterFound;
blocks := Array([["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"]]);
word := StringTools[UpperCase](convert(w, string));
for i to length(word) do
letterFound := false;
for j to numelems(blocks)/2 do
if not letterFound and (substring(word, i) = blocks[j,1] or substring(word, i) = blocks[j,2]) then
blocks[j,1] := undefined;
blocks[j,2] := undefined;
letterFound := true;
end if;
end do;
if not letterFound then
return false;
end if;
end do;
return true;
end proc:
seq(printf("%a: %a\n", i, canSpell(i)), i in [a, Bark, bOok, treat, COMMON, squad, confuse]); |
http://rosettacode.org/wiki/100_prisoners | 100 prisoners |
The Problem
100 prisoners are individually numbered 1 to 100
A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside.
Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start.
Prisoners start outside the room
They can decide some strategy before any enter the room.
Prisoners enter the room one by one, can open a drawer, inspect the card number in the drawer, then close the drawer.
A prisoner can open no more than 50 drawers.
A prisoner tries to find his own number.
A prisoner finding his own number is then held apart from the others.
If all 100 prisoners find their own numbers then they will all be pardoned. If any don't then all sentences stand.
The task
Simulate several thousand instances of the game where the prisoners randomly open drawers
Simulate several thousand instances of the game where the prisoners use the optimal strategy mentioned in the Wikipedia article, of:
First opening the drawer whose outside number is his prisoner number.
If the card within has his number then he succeeds otherwise he opens the drawer with the same number as that of the revealed card. (until he opens his maximum).
Show and compare the computed probabilities of success for the two strategies, here, on this page.
References
The unbelievable solution to the 100 prisoner puzzle standupmaths (Video).
wp:100 prisoners problem
100 Prisoners Escape Puzzle DataGenetics.
Random permutation statistics#One hundred prisoners on Wikipedia.
| #Kotlin | Kotlin | val playOptimal: () -> Boolean = {
val secrets = (0..99).toMutableList()
var ret = true
secrets.shuffle()
prisoner@ for(i in 0 until 100){
var prev = i
draw@ for(j in 0 until 50){
if (secrets[prev] == i) continue@prisoner
prev = secrets[prev]
}
ret = false
break@prisoner
}
ret
}
val playRandom: ()->Boolean = {
var ret = true
val secrets = (0..99).toMutableList()
secrets.shuffle()
prisoner@ for(i in 0 until 100){
val opened = mutableListOf<Int>()
val genNum : () ->Int = {
var r = (0..99).random()
while (opened.contains(r)) {
r = (0..99).random()
}
r
}
for(j in 0 until 50){
val draw = genNum()
if ( secrets[draw] == i) continue@prisoner
opened.add(draw)
}
ret = false
break@prisoner
}
ret
}
fun exec(n:Int, play:()->Boolean):Double{
var succ = 0
for (i in IntRange(0, n-1)){
succ += if(play()) 1 else 0
}
return (succ*100.0)/n
}
fun main() {
val N = 100_000
println("# of executions: $N")
println("Optimal play success rate: ${exec(N, playOptimal)}%")
println("Random play success rate: ${exec(N, playRandom)}%")
} |
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
| #Prolog | Prolog | play24(Len, Range, Goal) :-
game(Len, Range, Goal, L, S),
maplist(my_write, L),
format(': ~w~n', [S]).
game(Len, Range, Value, L, S) :-
length(L, Len),
maplist(choose(Range), L),
compute(L, Value, [], S).
choose(Range, V) :-
V is random(Range) + 1.
write_tree([M], [M]).
write_tree([+, M, N], S) :-
write_tree(M, MS),
write_tree(N, NS),
append(MS, [+ | NS], S).
write_tree([-, M, N], S) :-
write_tree(M, MS),
write_tree(N, NS),
( is_add(N) -> append(MS, [-, '(' | NS], Temp), append(Temp, ')', S)
; append(MS, [- | NS], S)).
write_tree([Op, M, N], S) :-
member(Op, [*, /]),
write_tree(M, MS),
write_tree(N, NS),
( is_add(M) -> append(['(' | MS], [')'], TempM)
; TempM = MS),
( is_add(N) -> append(['(' | NS], [')'], TempN)
; TempN = NS),
append(TempM, [Op | TempN], S).
is_add([Op, _, _]) :-
member(Op, [+, -]).
compute([Value], Value, [[_R-S1]], S) :-
write_tree(S1, S2),
with_output_to(atom(S), maplist(write, S2)).
compute(L, Value, CS, S) :-
select(M, L, L1),
select(N, L1, L2),
next_value(M, N, R, CS, Expr),
compute([R|L2], Value, Expr, S).
next_value(M, N, R, CS,[[R - [+, M1, N1]] | CS2]) :-
R is M+N,
( member([M-ExprM], CS) -> select([M-ExprM], CS, CS1), M1 = ExprM
; M1 = [M], CS1 = CS
),
( member([N-ExprN], CS1) -> select([N-ExprN], CS1, CS2), N1 = ExprN
; N1 = [N], CS2 = CS1
).
next_value(M, N, R, CS,[[R - [-, M1, N1]] | CS2]) :-
R is M-N,
( member([M-ExprM], CS) -> select([M-ExprM], CS, CS1), M1 = ExprM
; M1 = [M], CS1 = CS
),
( member([N-ExprN], CS1) -> select([N-ExprN], CS1, CS2), N1 = ExprN
; N1 = [N], CS2 = CS1
).
next_value(M, N, R, CS,[[R - [*, M1, N1]] | CS2]) :-
R is M*N,
( member([M-ExprM], CS) -> select([M-ExprM], CS, CS1), M1 = ExprM
; M1 = [M], CS1 = CS
),
( member([N-ExprN], CS1) -> select([N-ExprN], CS1, CS2), N1 = ExprN
; N1 = [N], CS2 = CS1
).
next_value(M, N, R, CS,[[R - [/, M1, N1]] | CS2]) :-
N \= 0,
R is rdiv(M,N),
( member([M-ExprM], CS) -> select([M-ExprM], CS, CS1), M1 = ExprM
; M1 = [M], CS1 = CS
),
( member([N-ExprN], CS1) -> select([N-ExprN], CS1, CS2), N1 = ExprN
; N1 = [N], CS2 = CS1
).
my_write(V) :-
format('~w ', [V]). |
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
| #Gambas | Gambas | 'Charlie Ogier (C) 15PuzzleGame 24/04/2017 V0.1.0 Licenced under MIT
'Inspiration came from: -
''http://rosettacode.org/wiki/15_Puzzle_Game
''Bugs or comments to [email protected]
'Written in Gambas 3.9.2 - Updated on the Gambas Farm 01/05/2017
'Updated so that the message and the Title show the same amount of moves 01/06/2017
'Form now expandable. Font height automated. Form size and position saved 06/06/2107
'Simulate playing the 15 - game(puzzle) Yes in GUI
'Generate a random start position Yes
'Prompt the user for which piece To move No
'Validate if the move is legal(possible) Yes
'Display the game(puzzle) as pieces are moved Yes in GUI
'Announce when the puzzle is solved Yes
'Possibly keep track of the number of moves Yes
byPos As New Byte[] 'Stores the position of the 'Tiles'
siMoves As Short 'Stores the amount of moves
hTimer As Timer 'Timer
dTimerStart As Date 'Stores the start time
dTimerDiff As Date 'Stores the time from the start to now
bTimerOn As Boolean 'To know if the Timer is running
Public Sub Form_Open() 'Form opens
Settings.read(Me, "Window") 'Get details of the last window position and size
With Me 'With the Form..
.Padding = 5 'Pad the edges
.Arrangement = Arrange.Row 'Arrange the Form
.Title = "15PuzzleGame v0.3.0" 'Set the Form Title
End With
BuildForm 'Go to the BuildForm routine
End
Public Sub BuildForm() 'To add items to the Form
Dim hButton As Button 'We need some Buttons
Dim byRand, byTest As Byte 'Various variables
Dim bOK As Boolean 'Used to stop duplicate numbers being added
Dim bSolvable As Boolean
Repeat 'Repeat until the puzzle is solvable
Do 'Start of a Do loop to create 0 to 15 in random order
byRand = Rand(0, 15) 'Get a random number between 0 and 15
If byRand = 0 Then byRand = 99 'Change 0 to 99 for the Blank space
bOK = True 'Set bOK to True
For Each byTest In byPos 'For each number stored in the array byPos
If byRand = byTest Then bOK = False 'Check to see if it already exists, if it does set bOK to False
Next
If bOK Then byPos.Add(byRand) 'If not a duplicate then add it to the array
If byPos.max = 15 Then Break 'Once the array has 16 numbers get out of here. 99 is used for the blank space
Loop
bSolvable = IsItSolvable() 'Go to the 'check if puzzle is solvable' routine
If Not bSolvable Then byPos.clear 'If it's not solvable then clear byPos
Until bSolvable = True 'Repeat until the puzzle is solvable
For byRand = 0 To 15 'Loop
If byPos[byRand] = 99 Then 'Check if value is 99 as this is where the blank space will go
AddPanel 'Go to the AddPanel routine to add the blank space
Continue 'Skip to the end of the loop
Endif
hButton = New Button(Me) As "AllButtons" 'Add a new button to the Form, all buttons grouped as 'AllButtons'
With hButton 'With the following properties
.Text = Str(byPos[byRand]) 'Add Button text
.Tag = Str(byPos[byRand]) 'Add a Tag
.Height = (Me.Height - 10) / 4 'Set the Button height
.Width = (Me.Width - 10) / 4 'Set the Button width
.Font.Bold = True 'Set the font to Bold
.Font.Size = 16 'Set Font size
End With
Next
AddTimer 'Go to the AddTimer routine
End
Public Sub AddPanel() 'Routine to add an invisible panel that is the blank area
Dim hPanel As Panel 'We need a Panel
HPanel = New Panel(Me) 'Add the Panel to the Form
With HPanel 'With the following Properties
.Tag = 99 'Set a Tag to 99
.Height = (Me.Height - 10) / 4 'Set the height
.Width = (Me.Width - 10) / 4 'Set the width
End With
End
Public Sub AddTimer() 'To add a Timer
hTimer = New Timer As "MyTimer" 'Add a Timer
hTimer.Delay = 1000 'Set the timer delay
End
Public Sub MyTimer_Timer() 'Timer
Me.Title = siMoves & " Moves " 'Set the Form Title to show the amount of moves taken
If dTimerStart Then 'If a start time has been set then
dTimerDiff = Time(Now) - dTimerStart 'Calculate the time difference between StartTime and Now
Me.Title &= " - " & Str(dTimerDiff) 'Add the time taken to the Form Title
End If
End
Public Sub AllButtons_Click() 'What to do when a Button is clicked
Dim byLast As Byte = Last.Tag 'Get the Tag of the Button clicked
Dim byTemp, byCount As Byte 'Various variables
Dim byCheck As Byte[] = [88, 88, 88, 88] 'Used for checking for the blank space
Dim byWChgeck As New Byte[16, 4]
Dim oObj As Object 'We need to enumerate Objects
For Each oObj In Me.Children 'For each Object (Buttons in this case) that are Children of the Form..
If oObj.Tag = byLast Then Break 'If the Tag of the Button matches then we know the position of the Button on the form so get out of here
Inc byCount 'Increase the value of byCount
Next
Select Case byCount 'Depending on the position of the Button
Case 0 'e.g 0 then we need to check positions 1 & 4 for the blank
byCheck[0] = 1
byCheck[1] = 4
Case 1
byCheck[0] = 0
byCheck[1] = 2
byCheck[2] = 5
Case 2
byCheck[0] = 1
byCheck[1] = 3
byCheck[2] = 6
Case 3
byCheck[0] = 2
byCheck[1] = 7
Case 4
byCheck[0] = 0
byCheck[1] = 5
byCheck[2] = 8
Case 5 'e.g 5 then we need to check positions 1, 4, 6 & 9 for the blank
byCheck[0] = 1
byCheck[1] = 4
byCheck[2] = 6
byCheck[3] = 9
Case 6
byCheck[0] = 2
byCheck[1] = 5
byCheck[2] = 7
byCheck[3] = 10
Case 7
byCheck[0] = 3
byCheck[1] = 6
byCheck[2] = 11
Case 8
byCheck[0] = 4
byCheck[1] = 9
byCheck[2] = 12
Case 9
byCheck[0] = 5
byCheck[1] = 8
byCheck[2] = 10
byCheck[3] = 13
Case 10
byCheck[0] = 6
byCheck[1] = 9
byCheck[2] = 11
byCheck[3] = 14
Case 11
byCheck[0] = 7
byCheck[1] = 10
byCheck[2] = 15
Case 12
byCheck[0] = 8
byCheck[1] = 13
Case 13
byCheck[0] = 9
byCheck[1] = 12
byCheck[2] = 14
Case 14
byCheck[0] = 10
byCheck[1] = 13
byCheck[2] = 15
Case 15
byCheck[0] = 11
byCheck[1] = 14
End Select
For Each byTemp In byCheck 'For each value in byCheck
If byTemp = 88 Then Break 'If byTemp = 88 then get out of here
If byPos[byTemp] = 99 Then 'If the position checked is 99 (the blank) then..
byPos[byTemp] = Last.Text 'Set the new position of the Tile in byPos
byPos[byCount] = 99 'Set the existing Tile position to = 99 (blank)
Inc siMoves 'Inc the amount of moves made
If Not bTimerOn Then 'If the Timer is now needed then
dTimerStart = Time(Now) 'Set the Start time to NOW
hTimer.start 'Start the Timer
bTimerOn = True 'Set bTimerOn to True
Endif
Break 'Get out of here
End If
Next
RebuildForm 'Go to the RebuilForm routine
CheckIfPuzzleCompleted 'Check to see if the puzzle has been solved
End
Public Sub CheckIfPuzzleCompleted() 'Is the puzzle is complete
Dim byTest As Byte[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 99] 'byPos will equal this if it is completed
Dim siCount As Short 'Counter
Dim bCompleted As Boolean = True 'Completed?
Dim sMessage As String 'String to store the display message
For siCount = 0 To 15 'Loop through the byPos
If byPos[siCount] <> byTest[siCount] Then 'If the position does not match the completed position then..
bCompleted = False 'Set bCompleted to False
Break 'Get out of here
Endif
Next
If bCompleted Then 'If the puzzle is completed then
hTimer.Stop 'Stop the timer
Me.Title = siMoves & " Moves " 'Set the Form Title to show the amount of moves taken
sMessage = "Congratulations!!\n" 'Build sMessage
sMessage &= Str(siMoves) & " Moves\n" 'Build sMessage
sMessage &= "Time = " & Str(dTimerDiff) 'Build sMessage
Message(sMessage, "OK") 'Put up a congratulatory message
Me.Close 'Close the form
Endif
End
Public Sub RebuildForm() 'To clear the Form and rebuild with the Tiles in the new postion
Dim hButton As Button 'We need Buttons
Dim byCount, byTemp As Byte 'Various variables
Dim siFontH As Short
Me.Children.clear 'Clear the Form of all Objects
For Each byTemp In byPos 'For each 'Position'
If byTemp = 99 Then 'If the Position's value is 99 then it's the space
AddPanel 'Go to the AddPanel routine
Else 'If the Position's value is NOT 99 then
hButton = New Button(Me) As "AllButtons" 'Create a new Button
With hButton 'With the following properties
.Text = Str(byPos[byCount]) 'Text as stored in byPos
.Tag = Str(byPos[byCount]) 'Tag as stored in byPos
.Height = (Me.Height - 10) / 4 'Set the Button height
.Width = (Me.Width - 10) / 4 'Set the Button width
.Font.Bold = True 'Set the Font to Bold
End With
If Me.Width > Me.Height Then 'If Form Width is greater than Form Width then..
siFontH = Me.Height 'siFontH = Form Height
Else 'Else..
siFontH = Me.Width 'siFontH = Form Width
End If
hButton.Font.size = siFontH / 16 'Set Font height
Endif
Inc byCount 'Increase counter
Next
End
Public Sub Form_Resize() 'If the form is resized
RebuildForm 'Rebuild the Form
End
Public Sub IsItSolvable() As Boolean 'To check if the puzzle is solvable
Dim bSolvable, bBlankOnEven As Boolean 'Triggers
Dim siCount0, siCount1, siInversion As Short 'Counters
For siCount0 = 0 To byPos.Max 'Loop through the positions
If byPos[siCount0] = 99 Then 'The blank
If InStr("0,1,2,3,8,9,10,11,", Str(siCount0 & ",")) Then 'Is the blank on an even row (counting from the bottom) if so..
bBlankOnEven = True 'bBlankOnEven = True
End If
Continue 'Go to the end of the loop
End If
For siCount1 = siCount0 + 1 To byPos.Max 'Loop through the positions
If byPos[siCount0] > byPos[siCount1] Then Inc siInversion 'Counts the inversions
Next 'See https://www.cs.bham.ac.uk/~mdr/teaching/modules04/java2/TilesSolvability.html
Next
If bBlankOnEven And Odd(siInversion) Then bSolvable = True 'Blank is on an even row (counting from the bottom) then the number of inversions in a solvable situation is odd
If Not bBlankOnEven And Even(siInversion) Then bSolvable = True 'Blank is on an odd row (counting from the bottom) then the number of inversions in a solvable situation is even
Return bSolvable 'Return the value
End
Public Sub Form_Close()
Settings.Write(Me, "Window") 'Store the window position and size
End
|
http://rosettacode.org/wiki/2048 | 2048 | Task
Implement a 2D sliding block puzzle game where blocks with numbers are combined to add their values.
Rules of the game
The rules are that on each turn the player must choose a direction (up, down, left or right).
All tiles move as far as possible in that direction, some move more than others.
Two adjacent tiles (in that direction only) with matching numbers combine into one bearing the sum of those numbers.
A move is valid when at least one tile can be moved, if only by combination.
A new tile with the value of 2 is spawned at the end of each turn at a randomly chosen empty square (if there is one).
Adding a new tile on a blank space. Most of the time, a new 2 is to be added, and occasionally (10% of the time), a 4.
To win, the player must create a tile with the number 2048.
The player loses if no valid moves are possible.
The name comes from the popular open-source implementation of this game mechanic, 2048.
Requirements
"Non-greedy" movement.
The tiles that were created by combining other tiles should not be combined again during the same turn (move).
That is to say, that moving the tile row of:
[2][2][2][2]
to the right should result in:
......[4][4]
and not:
.........[8]
"Move direction priority".
If more than one variant of combining is possible, move direction shall indicate which combination will take effect.
For example, moving the tile row of:
...[2][2][2]
to the right should result in:
......[2][4]
and not:
......[4][2]
Check for valid moves. The player shouldn't be able to skip their turn by trying a move that doesn't change the board.
Check for a win condition.
Check for a lose condition.
| #JavaScript | JavaScript |
/* Tile object: */
function Tile(pos, val, puzzle){
this.pos = pos;
this.val = val;
this.puzzle = puzzle;
this.merging = false;
this.getCol = () => Math.round(this.pos % 4);
this.getRow = () => Math.floor(this.pos / 4);
/* draw tile on a P5.js canvas: */
this.show = function(){
let padding = this.merging ? 0 : 5;
let size = 0.25*width;
noStroke();
colorMode(HSB, 255);
fill(10*(11 - Math.log2(this.val)), 50 + 15*Math.log2(this.val), 200);
rect(this.getCol()*size + padding, this.getRow()*size + padding, size - 2*padding, size - 2*padding);
fill(255);
textSize(0.1*width);
textAlign(CENTER, CENTER);
text(this.val, (this.getCol() + 0.5)*size, (this.getRow() + 0.5)*size);
}
/* move tile in a given direction: */
this.move = function(dir){
let col = this.getCol() + (1 - 2*(dir < 0))*Math.abs(dir)%4;
let row = this.getRow() + (1 - 2*(dir < 0))*Math.floor(Math.abs(dir)/4);
let target = this.puzzle.getTile(this.pos + dir);
if (col < 0 || col > 3 || row < 0 || row > 3) {
/* target position out of bounds */
return false;
} else if (target){
/* tile blocked by other tile */
if(this.merging || target.merging || target.val !== this.val)
return false;
/* merge with target tile (equal values):*/
target.val += this.val;
target.merging = true;
this.puzzle.score += target.val;
this.puzzle.removeTile(this);
return true;
}
/* move tile: */
this.pos += dir;
return true;
}
}
/* Puzzle object: */
function Puzzle(){
this.tiles = [];
this.dir = 0;
this.score = 0;
this.hasMoved = false;
this.validPositions = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
this.getOpenPositions = () => this.validPositions.filter(i => this.tiles.map(x => x.pos).indexOf(i) === -1);
this.getTile = pos => this.tiles.filter(x => x.pos === pos)[0];
this.removeTile = tile => this.tiles.splice(this.tiles.indexOf(tile), 1);
this.winCondition = () => this.tiles.some(x => x.val === 2048);
/* check for valid moves: */
this.validMoves = function(){
/* return true if there are empty spaces */
if(this.tiles.length < 16)
return true;
/* otherwise check for neighboring tiles with the same value */
let res = false;
this.tiles.sort((x,y) => x.pos - y.pos);
for(let i = 0; i < 16; i++)
res = res || ( (i%4 < 3) ? this.tiles[i].val === this.tiles[i+1].val : false )
|| ( (i < 12) ? this.tiles[i].val === this.tiles[i+4].val : false );
return res;
}
/* check win and lose condition: */
this.checkGameState = function(){
if(this.winCondition()){
alert('You win!');
} else if (!this.validMoves()){
alert('You Lose!');
this.restart();
}
}
this.restart = function(){
this.tiles = [];
this.dir = 0;
this.score = 0;
this.hasMoved = false;
this.generateTile();
this.generateTile();
}
/* draw the board on the p5.js canvas: */
this.show = function(){
background(200);
fill(255);
textSize(0.05*width);
textAlign(CENTER, TOP);
text("SCORE: " + this.score, 0.5*width, width);
for(let tile of this.tiles)
tile.show();
}
/* update the board: */
this.animate = function(){
if(this.dir === 0)
return;
/* move all tiles in a given direction */
let moving = false;
this.tiles.sort((x,y) => this.dir*(y.pos - x.pos));
for(let tile of this.tiles)
moving = moving || tile.move(this.dir);
/* check if the move is finished and generate a new tile */
if(this.hasMoved && !moving){
this.dir = 0;
this.generateTile();
for(let tile of this.tiles)
tile.merging = false;
}
this.hasMoved = moving;
}
this.generateTile = function(){
let positions = this.getOpenPositions();
let pos = positions[Math.floor(Math.random()*positions.length)];
let val = 2 + 2*Math.floor(Math.random()*1.11);
this.tiles.push(new Tile(pos, val, this));
}
this.generateTile();
this.generateTile();
/* process key inputs: */
this.keyHandler = function(key){
if (key === UP_ARROW) this.dir = -4
else if (key === DOWN_ARROW) this.dir = 4
else if (key === RIGHT_ARROW) this.dir = 1
else if (key === LEFT_ARROW) this.dir = -1;
}
}
let game;
function setup() {
createCanvas(400, 420);
game = new Puzzle();
}
/* game loop: */
function draw() {
game.checkGameState();
game.animate();
game.show();
}
function keyPressed(){
game.keyHandler(keyCode);
}
|
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
| #Bc | Bc | i = 99;
while ( 1 ) {
print i , " bottles of beer on the wall\n";
print i , " bottles of beer\nTake one down, pass it around\n";
if (i == 2) {
break
}
print --i , " bottles of beer on the wall\n";
}
print --i , " bottle of beer on the wall\n";
print i , " bottle of beer on the wall\n";
print i , " bottle of beer\nTake it down, pass it around\nno more bottles of beer on the wall\n";
quit |
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.
| #Lasso | Lasso | [
if(sys_listunboundmethods !>> 'randoms') => {
define randoms()::array => {
local(out = array)
loop(4) => { #out->insert(math_random(9,1)) }
return #out
}
}
if(sys_listunboundmethods !>> 'checkvalid') => {
define checkvalid(str::string, nums::array)::boolean => {
local(chk = array('*','/','+','-','(',')',' '), chknums = array, lastintpos = -1, poscounter = 0)
loop(9) => { #chk->insert(loop_count) }
with s in #str->values do => {
#poscounter++
#chk !>> #s && #chk !>> integer(#s) ? return false
integer(#s) > 0 && #lastintpos + 1 >= #poscounter ? return false
integer(#s) > 0 ? #chknums->insert(integer(#s))
integer(#s) > 0 ? #lastintpos = #poscounter
}
#chknums->size != 4 ? return false
#nums->sort
#chknums->sort
loop(4) => { #nums->get(loop_count) != #chknums(loop_count) ? return false }
return true
}
}
if(sys_listunboundmethods !>> 'executeexpr') => {
define executeexpr(expr::string)::integer => {
local(keep = string)
with i in #expr->values do => {
if(array('*','/','+','-','(',')') >> #i) => {
#keep->append(#i)
else
integer(#i) > 0 ? #keep->append(decimal(#i))
}
}
return integer(sourcefile('['+#keep+']','24game',true,true)->invoke)
}
}
local(numbers = array, exprsafe = true, exprcorrect = false, exprresult = 0)
if(web_request->param('nums')->asString->size) => {
with n in web_request->param('nums')->asString->split(',') do => { #numbers->insert(integer(#n->trim&)) }
}
#numbers->size != 4 ? #numbers = randoms()
if(web_request->param('nums')->asString->size) => {
#exprsafe = checkvalid(web_request->param('expr')->asString,#numbers)
if(#exprsafe) => {
#exprresult = executeexpr(web_request->param('expr')->asString)
#exprresult == 24 ? #exprcorrect = true
}
}
]<h1>24 Game</h1>
<p><b>Rules:</b><br>
Enter an expression that evaluates to 24</p>
<ul>
<li>Only multiplication, division, addition, and subtraction operators/functions are allowed.</li>
<li>Brackets are allowed.</li>
<li>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).</li>
<li>The order of the digits when given does not have to be preserved.</li>
</ul>
<h2>Numbers</h2>
<p>[#numbers->join(', ')] (<a href="?">Reload</a>)</p>
[!#exprsafe ? '<p>Please provide a valid expression</p>']
<form><input type="hidden" value="[#numbers->join(',')]" name="nums"><input type="text" name="expr" value="[web_request->param('expr')->asString]"><input type="submit" name="submit" value="submit"></form>
[if(#exprsafe)]
<p>Result: <b>[#exprresult]</b> [#exprcorrect ? 'is CORRECT!' | 'is incorrect']</p>
[/if] |
http://rosettacode.org/wiki/A%2BB | A+B | A+B ─── a classic problem in programming contests, it's given so contestants can gain familiarity with the online judging system being used.
Task
Given two integers, A and B.
Their sum needs to be calculated.
Input data
Two integers are written in the input stream, separated by space(s):
(
−
1000
≤
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
| #Eiffel | Eiffel |
class
APPLICATION
inherit
ARGUMENTS
create
make
feature {NONE} -- Initialization
make
-- Run application.
do
print(argument(1).to_integer + argument(2).to_integer)
end
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
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language |
blocks=Partition[Characters[ToLowerCase["BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM"]],2];
ClearAll[DoStep,ABCBlockQ]
DoStep[chars_List,blcks_List,chosen_List]:=Module[{opts},
If[chars=!={},
opts=Select[blcks,MemberQ[#,First[chars]]&];
{Rest[chars],DeleteCases[blcks,#,1,1],Append[chosen,#]}&/@opts
,
{{chars,blcks,chosen}}
]
]
DoStep[opts_List]:=Flatten[DoStep@@@opts,1]
ABCBlockQ[str_String]:=(FixedPoint[DoStep,{{Characters[ToLowerCase[str]],blocks,{}}}]=!={})
|
http://rosettacode.org/wiki/100_prisoners | 100 prisoners |
The Problem
100 prisoners are individually numbered 1 to 100
A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside.
Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start.
Prisoners start outside the room
They can decide some strategy before any enter the room.
Prisoners enter the room one by one, can open a drawer, inspect the card number in the drawer, then close the drawer.
A prisoner can open no more than 50 drawers.
A prisoner tries to find his own number.
A prisoner finding his own number is then held apart from the others.
If all 100 prisoners find their own numbers then they will all be pardoned. If any don't then all sentences stand.
The task
Simulate several thousand instances of the game where the prisoners randomly open drawers
Simulate several thousand instances of the game where the prisoners use the optimal strategy mentioned in the Wikipedia article, of:
First opening the drawer whose outside number is his prisoner number.
If the card within has his number then he succeeds otherwise he opens the drawer with the same number as that of the revealed card. (until he opens his maximum).
Show and compare the computed probabilities of success for the two strategies, here, on this page.
References
The unbelievable solution to the 100 prisoner puzzle standupmaths (Video).
wp:100 prisoners problem
100 Prisoners Escape Puzzle DataGenetics.
Random permutation statistics#One hundred prisoners on Wikipedia.
| #Lua | Lua | function shuffle(tbl)
for i = #tbl, 2, -1 do
local j = math.random(i)
tbl[i], tbl[j] = tbl[j], tbl[i]
end
return tbl
end
function playOptimal()
local secrets = {}
for i=1,100 do
secrets[i] = i
end
shuffle(secrets)
for p=1,100 do
local success = false
local choice = p
for i=1,50 do
if secrets[choice] == p then
success = true
break
end
choice = secrets[choice]
end
if not success then
return false
end
end
return true
end
function playRandom()
local secrets = {}
for i=1,100 do
secrets[i] = i
end
shuffle(secrets)
for p=1,100 do
local choices = {}
for i=1,100 do
choices[i] = i
end
shuffle(choices)
local success = false
for i=1,50 do
if choices[i] == p then
success = true
break
end
end
if not success then
return false
end
end
return true
end
function exec(n,play)
local success = 0
for i=1,n do
if play() then
success = success + 1
end
end
return 100.0 * success / n
end
function main()
local N = 1000000
print("# of executions: "..N)
print(string.format("Optimal play success rate: %f", exec(N, playOptimal)))
print(string.format("Random play success rate: %f", exec(N, playRandom)))
end
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
| #Python | Python | '''
The 24 Game Player
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.
An answer of "!!" will ask you for a new set of four digits.
An answer of "?" will compute an expression for the current digits.
Otherwise you are repeatedly asked for an expression until it evaluates to 24
Note: you cannot form multiple digit numbers from the supplied digits,
so an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.
'''
from __future__ import division, print_function
from itertools import permutations, combinations, product, \
chain
from pprint import pprint as pp
from fractions import Fraction as F
import random, ast, re
import sys
if sys.version_info[0] < 3:
input = raw_input
from itertools import izip_longest as zip_longest
else:
from itertools import zip_longest
def choose4():
'four random digits >0 as characters'
return [str(random.randint(1,9)) for i in range(4)]
def ask4():
'get four random digits >0 from the player'
digits = ''
while len(digits) != 4 or not all(d in '123456789' for d in digits):
digits = input('Enter the digits to solve for: ')
digits = ''.join(digits.strip().split())
return list(digits)
def welcome(digits):
print (__doc__)
print ("Your four digits: " + ' '.join(digits))
def check(answer, digits):
allowed = set('() +-*/\t'+''.join(digits))
ok = all(ch in allowed for ch in answer) and \
all(digits.count(dig) == answer.count(dig) for dig in set(digits)) \
and not re.search('\d\d', answer)
if ok:
try:
ast.parse(answer)
except:
ok = False
return ok
def solve(digits):
"""\
>>> for digits in '3246 4788 1111 123456 1127 3838'.split():
solve(list(digits))
Solution found: 2 + 3 * 6 + 4
'2 + 3 * 6 + 4'
Solution found: ( 4 + 7 - 8 ) * 8
'( 4 + 7 - 8 ) * 8'
No solution found for: 1 1 1 1
'!'
Solution found: 1 + 2 + 3 * ( 4 + 5 ) - 6
'1 + 2 + 3 * ( 4 + 5 ) - 6'
Solution found: ( 1 + 2 ) * ( 1 + 7 )
'( 1 + 2 ) * ( 1 + 7 )'
Solution found: 8 / ( 3 - 8 / 3 )
'8 / ( 3 - 8 / 3 )'
>>> """
digilen = len(digits)
# length of an exp without brackets
exprlen = 2 * digilen - 1
# permute all the digits
digiperm = sorted(set(permutations(digits)))
# All the possible operator combinations
opcomb = list(product('+-*/', repeat=digilen-1))
# All the bracket insertion points:
brackets = ( [()] + [(x,y)
for x in range(0, exprlen, 2)
for y in range(x+4, exprlen+2, 2)
if (x,y) != (0,exprlen+1)]
+ [(0, 3+1, 4+2, 7+3)] ) # double brackets case
for d in digiperm:
for ops in opcomb:
if '/' in ops:
d2 = [('F(%s)' % i) for i in d] # Use Fractions for accuracy
else:
d2 = d
ex = list(chain.from_iterable(zip_longest(d2, ops, fillvalue='')))
for b in brackets:
exp = ex[::]
for insertpoint, bracket in zip(b, '()'*(len(b)//2)):
exp.insert(insertpoint, bracket)
txt = ''.join(exp)
try:
num = eval(txt)
except ZeroDivisionError:
continue
if num == 24:
if '/' in ops:
exp = [ (term if not term.startswith('F(') else term[2])
for term in exp ]
ans = ' '.join(exp).rstrip()
print ("Solution found:",ans)
return ans
print ("No solution found for:", ' '.join(digits))
return '!'
def main():
digits = choose4()
welcome(digits)
trial = 0
answer = ''
chk = ans = False
while not (chk and ans == 24):
trial +=1
answer = input("Expression %i: " % trial)
chk = check(answer, digits)
if answer == '?':
solve(digits)
answer = '!'
if answer.lower() == 'q':
break
if answer == '!':
digits = choose4()
trial = 0
print ("\nNew digits:", ' '.join(digits))
continue
if answer == '!!':
digits = ask4()
trial = 0
print ("\nNew digits:", ' '.join(digits))
continue
if not chk:
print ("The input '%s' was wonky!" % answer)
else:
if '/' in answer:
# Use Fractions for accuracy in divisions
answer = ''.join( (('F(%s)' % char) if char in '123456789' else char)
for char in answer )
ans = eval(answer)
print (" = ", ans)
if ans == 24:
print ("Thats right!")
print ("Thank you and goodbye")
main() |
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
| #Go | Go | package main
import (
"fmt"
"math/rand"
"strings"
"time"
)
func main() {
rand.Seed(time.Now().UnixNano())
p := newPuzzle()
p.play()
}
type board [16]cell
type cell uint8
type move uint8
const (
up move = iota
down
right
left
)
func randMove() move { return move(rand.Intn(4)) }
var solvedBoard = board{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0}
func (b *board) String() string {
var buf strings.Builder
for i, c := range b {
if c == 0 {
buf.WriteString(" .")
} else {
_, _ = fmt.Fprintf(&buf, "%3d", c)
}
if i%4 == 3 {
buf.WriteString("\n")
}
}
return buf.String()
}
type puzzle struct {
board board
empty int // board[empty] == 0
moves int
quit bool
}
func newPuzzle() *puzzle {
p := &puzzle{
board: solvedBoard,
empty: 15,
}
// Could make this configurable, 10==easy, 50==normal, 100==hard
p.shuffle(50)
return p
}
func (p *puzzle) shuffle(moves int) {
// As with other Rosetta solutions, we use some number
// of random moves to "shuffle" the board.
for i := 0; i < moves || p.board == solvedBoard; {
if p.doMove(randMove()) {
i++
}
}
}
func (p *puzzle) isValidMove(m move) (newIndex int, ok bool) {
switch m {
case up:
return p.empty - 4, p.empty/4 > 0
case down:
return p.empty + 4, p.empty/4 < 3
case right:
return p.empty + 1, p.empty%4 < 3
case left:
return p.empty - 1, p.empty%4 > 0
default:
panic("not reached")
}
}
func (p *puzzle) doMove(m move) bool {
i := p.empty
j, ok := p.isValidMove(m)
if ok {
p.board[i], p.board[j] = p.board[j], p.board[i]
p.empty = j
p.moves++
}
return ok
}
func (p *puzzle) play() {
fmt.Printf("Starting board:")
for p.board != solvedBoard && !p.quit {
fmt.Printf("\n%v\n", &p.board)
p.playOneMove()
}
if p.board == solvedBoard {
fmt.Printf("You solved the puzzle in %d moves.\n", p.moves)
}
}
func (p *puzzle) playOneMove() {
for {
fmt.Printf("Enter move #%d (U, D, L, R, or Q): ", p.moves+1)
var s string
if n, err := fmt.Scanln(&s); err != nil || n != 1 {
continue
}
s = strings.TrimSpace(s)
if s == "" {
continue
}
var m move
switch s[0] {
case 'U', 'u':
m = up
case 'D', 'd':
m = down
case 'L', 'l':
m = left
case 'R', 'r':
m = right
case 'Q', 'q':
fmt.Printf("Quiting after %d moves.\n", p.moves)
p.quit = true
return
default:
fmt.Println(`
Please enter "U", "D", "L", or "R" to move the empty cell
up, down, left, or right. You can also enter "Q" to quit.
Upper or lowercase is accepted and only the first non-blank
character is important (i.e. you may enter "up" if you like).
`)
continue
}
if !p.doMove(m) {
fmt.Println("That is not a valid move at the moment.")
continue
}
return
}
} |
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.
| #Julia | Julia | using Gtk.ShortNames
@enum Direction2048 Right Left Up Down
"""
shifttiles!
The adding and condensing code is for a leftward shift, so if the move is not
leftward, this will rotate matrix to make move leftward, move, then undo rotation.
"""
function shifttiles!(b, siz, direction)
if direction == Right
tmpb = rot180(b); points, winner = leftshift!(tmpb, siz); tmpb = rot180(tmpb)
elseif direction == Up
tmpb = rotl90(b); points, winner = leftshift!(tmpb, siz); tmpb = rotr90(tmpb)
elseif direction == Down
tmpb = rotr90(b); points, winner = leftshift!(tmpb, siz); tmpb = rotl90(tmpb)
else # left movement function as coded
return leftshift!(b, siz)
end
for i in 1:siz, j in 1:siz
b[i,j] = tmpb[i,j] # copy tmpb contents back to b (modifies b)
end
points, winner
end
function compactleft!(b, siz, row)
tmprow = zeros(Int, siz)
tmppos = 1
for j in 1:siz
if b[row,j] != 0
tmprow[tmppos] = b[row,j]
tmppos += 1
end
end
b[row,:] = tmprow
end
"""
leftshift!
Work row by row. First, compact tiles to the left if possible. Second, find and
replace paired tiles in the row, then re-compact. Keep score of merges and return
as pointsgained. If a 2048 value tile is created, return a winner true value.
"""
function leftshift!(b, siz)
pointsgained = 0
winner = false
for i in 1:siz
compactleft!(b, siz, i)
tmprow = zeros(Int, siz)
tmppos = 1
for j in 1:siz-1
if b[i,j] == b[i,j+1]
b[i,j] = 2 * b[i,j]
b[i,j+1] = 0
pointsgained += b[i,j]
if b[i,j] == 2048 # made a 2048 tile, which wins game
winner = true
end
end
if b[i,j] != 0
tmprow[tmppos] = b[i,j]
tmppos += 1
end
end
tmprow[siz] = b[i,siz]
b[i,:] = tmprow
compactleft!(b, siz, i)
end
pointsgained, winner
end
"""
app2048
Run game app, with boardsize (choose 4 for original game) as an argument.
"""
function app2048(bsize)
win = Window("2048 Game", 400, 400) |> (Frame() |> (box = Box(:v)))
toolbar = Toolbar()
newgame = ToolButton("New Game")
set_gtk_property!(newgame, :label, "New Game")
set_gtk_property!(newgame, :is_important, true)
undomove = ToolButton("Undo Move")
set_gtk_property!(undomove, :label, "Undo Move")
set_gtk_property!(undomove, :is_important, true)
map(w->push!(toolbar,w),[newgame,undomove])
grid = Grid()
map(w -> push!(box, w),[toolbar, grid])
buttons = Array{Gtk.GtkButtonLeaf,2}(undef, bsize, bsize)
for i in 1:bsize, j in 1:bsize
grid[i,j] = buttons[i,j] = Button()
set_gtk_property!(buttons[i,j], :expand, true)
end
board = zeros(Int, (bsize,bsize))
pastboardstates = []
score = 0
gameover = false
condition = Condition()
won = ""
function update!()
for i in 1:bsize, j in 1:bsize
label = (board[i,j] > 0) ? board[i,j] : " "
set_gtk_property!(buttons[i,j], :label, label)
end
set_gtk_property!(win, :title, "$won 2048 Game (Score: $score)")
end
function newrandomtile!()
blanks = Array{Tuple{Int,Int},1}()
for i in 1:bsize, j in 1:bsize
if board[i,j] == 0
push!(blanks, (i,j))
end
end
if length(blanks) == 0
gameover = true
else
i,j = rand(blanks)
board[i,j] = (rand() > 0.8) ? 4 : 2
end
end
function initialize!(w)
won = ""
gameover = false
for i in 1:bsize, j in 1:bsize
board[i,j] = 0
set_gtk_property!(buttons[i,j], :label, " ")
end
newrandomtile!()
update!()
end
function undo!(w)
if gameover == false
board = pop!(pastboardstates)
update!()
end
end
function keypress(w, event)
presses = Dict(37 => Up, # code rotated 90 degrees
38 => Left, # because of Gtk coordinates
39 => Down, # y is downward positive
40 => Right)
keycode = event.hardware_keycode
if haskey(presses, keycode) && gameover == false
push!(pastboardstates, copy(board))
newpoints, havewon = shifttiles!(board, bsize, presses[keycode])
score += newpoints
if havewon && won != "Winning"
won = "Winning"
info_dialog("You have won the game.")
end
newrandomtile!()
update!()
if gameover
info_dialog("Game over.\nScore: $score")
end
end
end
endit(w) = notify(condition)
initialize!(win)
signal_connect(initialize!, newgame, :clicked)
signal_connect(undo!,undomove, :clicked)
signal_connect(endit, win, :destroy)
signal_connect(keypress, win, "key-press-event")
Gtk.showall(win)
wait(condition)
end
const boardsize = 4
app2048(boardsize)
|
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
| #BCPL | BCPL | get "libhdr"
let number(n) be
test n=0
then writes("No more")
else writen(n)
let plural(n) be
test n=1
then writes(" bottle")
else writes(" bottles")
let bottles(n) be
$( number(n)
plural(n)
$)
let verse(n) be
$( bottles(n)
writes(" of beer on the wall,*N")
bottles(n)
writes(" of beer,*NTake ")
test n=1
then writes("it")
else writes("one")
writes(" down and pass it around,*N")
bottles(n-1)
writes(" of beer on the wall!*N*N")
$)
let start() be
for n = 99 to 1 by -1 do verse(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.
| #Liberty_BASIC | Liberty BASIC | dim d(4)
dim chk(4)
print "The 24 Game"
print
print "Given four digits and using just the +, -, *, and / operators; and the"
print "possible use of brackets, (), enter an expression that equates to 24."
do
d$=""
for i = 1 to 4
d(i)=int(rnd(1)*9)+1 '1..9
chk(i)=d(i)
d$=d$;d(i) 'valid digits, to check with Instr
next
print
print "These are your four digits: ";
for i = 1 to 4
print d(i);left$(",",i<>4);
next
print
Print "Enter expression:"
Input "24 = ";expr$
'check expr$ for validity
'check right digits used
failed = 0
for i = 1 to len(expr$)
c$=mid$(expr$,i,1)
if instr("123456789", c$)<>0 then 'digit
if instr(d$, c$)=0 then failed = 1: exit for
if i>1 and instr("123456789", mid$(expr$,i-1,1))<>0 then failed = 2: exit for
for j =1 to 4
if chk(j)=val(c$) then chk(j)=0: exit for
next
end if
next
if failed=1 then
print "Wrong digit (";c$;")"
goto [fail]
end if
if failed=2 then
print "Multiple digit numbers is disallowed."
goto [fail]
end if
'check all digits used
if chk(1)+ chk(2)+ chk(3)+ chk(4)<>0 then
print "Not all digits used"
goto [fail]
end if
'check valid operations
failed = 0
for i = 1 to len(expr$)
c$=mid$(expr$,i,1)
if instr("+-*/()"+d$, c$)=0 then failed = 1: exit for
next
if failed then
print "Wrong operation (";c$;")"
goto [fail]
end if
'some errors (like brackets) trapped by error handler
Err$=""
res=evalWithErrCheck(expr$)
if Err$<>"" then
print "Error in expression"
goto [fail]
end if
if res = 24 then
print "Correct!"
else
print "Wrong! (you got ";res ;")"
end if
[fail]
Input "Play again (y/n)? "; ans$
loop while ans$="y"
end
function evalWithErrCheck(expr$)
on error goto [handler]
evalWithErrCheck=eval(expr$)
exit function
[handler]
end function |
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
| #Ela | Ela | open monad io string list
a'b() = do
str <- readStr
putStrLn <| show <| sum <| map gread <| string.split " " <| str
a'b() ::: IO |
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
| #MATLAB_.2F_Octave | MATLAB / Octave | function testABC
combos = ['BO' ; 'XK' ; 'DQ' ; 'CP' ; 'NA' ; 'GT' ; 'RE' ; 'TG' ; 'QD' ; ...
'FS' ; 'JW' ; 'HU' ; 'VI' ; 'AN' ; 'OB' ; 'ER' ; 'FS' ; 'LY' ; ...
'PC' ; 'ZM'];
words = {'A' 'BARK' 'BOOK' 'TREAT' 'COMMON' 'SQUAD' 'CONFUSE'};
for k = 1:length(words)
possible = canMakeWord(words{k}, combos);
fprintf('Can%s make word %s.\n', char(~possible.*'NOT'), words{k})
end
end
function isPossible = canMakeWord(word, combos)
word = lower(word);
combos = lower(combos);
isPossible = true;
k = 1;
while isPossible && k <= length(word)
[r, c] = find(combos == word(k), 1);
if ~isempty(r)
combos(r, :) = '';
else
isPossible = false;
end
k = k+1;
end
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.
| #Maple | Maple | p:=simplify(1-product(1-1/(2*n-k),k=0..n-1));
# p=1/2 |
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
| #Quackery | Quackery | [ ' [ 0 1 2 3 ]
permutations ] constant is numorders ( --> [ )
[ []
4 3 ** times
[ [] i^
3 times
[ 4 /mod 4 +
rot join swap ]
drop
nested join ] ] constant is oporders ( --> [ )
[ [] numorders witheach
[ oporders witheach
[ dip dup join nested
rot swap join swap ]
drop ] ] constant is allorders ( --> [ )
[ [] unrot witheach
[ dip dup peek
swap dip [ nested join ] ]
drop ] is reorder ( [ [ --> [ )
[ ' [ [ 0 1 4 2 5 3 6 ]
[ 0 1 4 2 3 5 6 ]
[ 0 1 2 4 3 5 6 ] ]
witheach
[ dip dup reorder swap ]
4 pack ] is orderings ( [ --> [ )
[ witheach
[ dup number? iff n->v done
dup ' + = iff
[ drop v+ ] done
dup ' - = iff
[ drop v- ] done
' * = iff v* done
v/ ]
24 n->v v- v0= ] is 24= ( [ --> b )
[ 4 pack sort
[] swap
' [ + - * / ] join
allorders witheach
[ dip dup reorder orderings
witheach
[ dup 24= iff
[ rot swap
nested join swap ]
else drop ] ]
drop
uniquewith
[ dip unbuild unbuild $> ]
dup size
dup 0 = iff
[ 2drop say "No solutions." ]
done
dup 1 = iff
[ drop say "1 solution." ]
else
[ echo say " solutions." ]
unbuild
2 split nip
-2 split drop nest$ 90 wrap$ ] is solve ( n n n n --> ) |
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
| #Harbour | Harbour |
#include "inkey.ch"
#include "Box.ch"
procedure Main()
// console init
SET SCOREBOARD OFF
SetMode(30,80)
ret := 0
// main loop
yn := .F.
DO WHILE yn == .F.
// draw console
cls
@ 0, 0 TO MaxRow(), MaxCol() DOUBLE
SetColor("BG+/B,W/N")
@ 0, 4 SAY " Slidng puzzle game "
SetColor()
// input size of grid
tam := 0
@ MaxRow() - 2, 4 SAY "Size of grid: " GET tam PICTURE "9"
READ
// Initialize numbers
lista := ARRAY (tam * tam)
FOR z := 1 TO tam * tam
lista[z] := z
NEXT
lista1 := lista
grid := ARRAY (tam,tam)
// populate grid with numbers
FOR i := 1 TO tam
FOR j := 1 TO tam
grid[i,j] := lista1[ (i-1) * tam + j]
NEXT
NEXT
Mostra(@grid)
InKey(0)
// initialize the game
n := 0
t := 0
lista := lista1 // lista for scrambling, lista1 preserve numbers in order
DO WHILE .T.
// scrambling numbers
FOR i := 1 TO tam*tam
n := Int ( ft_Rand1(tam * tam - 1) + 1 )
t := lista[n]
lista[n] := lista[i]
lista[i] := t
NEXT
// have solution?
possp := 0
invct := 0 // change counter
FOR i := 1 TO tam * tam -1
IF lista[i] != tam*tam
FOR j := i + 1 TO tam * tam
IF lista[j] != tam*tam
IF lista[i] > lista[j]
invct++
ENDIF
ENDIF
NEXT
ELSE
possp := i
ENDIF
NEXT
linv := If( ( (invct % 2) == 0 ), .T., .F.)
lkin := If( ( (tam - Int( (possp -1) / tam )) % 2) == 0, .T., .F. )
IF ( (tam % 2) != 0) // if grid size is odd
IF linv // if number of positions changes is even, solvable
EXIT
ELSE
LOOP // if is odd, not solvable, scramble more
ENDIF // if grid size is even
ELSE
// If changes is even and space position is in odd line
// or changes is odd and space position is in even line
// (XOR condition) is solvable
IF (linv .AND. !lkin) .OR. (!linv .AND. lkin) // XOR !!!
EXIT
ElSE // else scramble more
LOOP
ENDIF
ENDIF
ENDDO
// populate the grid with scrambled numbers
FOR i := 1 TO tam
FOR j := 1 TO tam
grid[i,j] := lista[ (i-1) * tam + j]
NEXT
NEXT
ret := Mostra(@grid)
// play
key := 0
DO WHILE LastKey() != K_ESC
key := 0
// find the space coords
xe := 0
ye := 0
lv := tam*tam
FOR i := 1 TO tam
FOR j := 1 TO tam
IF grid[i,j] == lv
xe :=i
ye :=j
ENDIF
NEXT
NEXT
// the direction keys
key := inkey(0)
DO CASE
CASE key == K_UP
IF xe > 1
grid[xe,ye] := grid[xe-1,ye]
grid[xe-1,ye] := lv
ENDIF
ret := Mostra(@grid)
CASE key == K_DOWN
IF xe < tam
grid[xe,ye] := grid[xe+1,ye]
grid[xe+1,ye] := lv
ENDIF
ret := Mostra(@grid)
CASE key == K_LEFT
IF ye > 1
grid[xe,ye] := grid[xe,ye-1]
grid[xe,ye-1] := lv
ENDIF
ret := Mostra(@grid)
CASE key == K_RIGHT
IF ye < tam
grid[xe,ye] := grid[xe,ye+1]
grid[xe,ye+1] := lv
ENDIF
ret := Mostra(@grid)
ENDCASE
IF ret == tam*tam-1 // ret is qtty numbers in position
@ MaxRow() - 3, 4 SAY "Fim de jogo!" // if ret == (size*size) -1
key := K_ESC // all numbers in position
EXIT // game solved
ENDIF
ENDDO
@ MaxRow() - 2, 4 SAY "Deseja sair? (yn): " GET yn PICTURE "Y"
READ
@ MaxRow() - 3, 4 SAY " "
ENDDO
return NIL
FUNCTION Mostra(grid)
// Show the gris
fim := 0 // how many numbers in position?
SetColor("BG+/B,W/N")
@ 5,10 , 5 + tam * 2, 9 + tam * 4 BOX B_SINGLE + Space(1)
i := 0
FOR y := 1 TO tam
FOR x := 1 TO tam
IF grid[x,y] == tam * tam // show space
SetColor(" B/GR+, W/N")
@ x*2 + 4, i + 11 SAY " "
SetColor("BG+/B,W/N")
ELSE
IF ( (x-1) * tam + y ) == grid[x,y] // show number in position
SetColor("W/G,W/N")
@ x*2 + 4, i + 11 SAY grid[x,y] PICTURE "99"
fim++
ELSE // show number out position
SetColor("BG+/B,W/N")
@ x*2 + 4, i + 11 SAY grid[x,y] PICTURE "99"
ENDIF
ENDIF
NEXT
i = i + 4
NEXT
SetColor(" W/N, BG+/B")
RETURN fim
|
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.
| #Kotlin | Kotlin | import java.io.BufferedReader
import java.io.InputStreamReader
const val positiveGameOverMessage = "So sorry, but you won the game."
const val negativeGameOverMessage = "So sorry, but you lost the game."
fun main(args: Array<String>) {
val grid = arrayOf(
arrayOf(0, 0, 0, 0),
arrayOf(0, 0, 0, 0),
arrayOf(0, 0, 0, 0),
arrayOf(0, 0, 0, 0)
)
val gameOverMessage = run2048(grid)
println(gameOverMessage)
}
fun run2048(grid: Array<Array<Int>>): String {
if (isGridSolved(grid)) return positiveGameOverMessage
else if (isGridFull(grid)) return negativeGameOverMessage
val populatedGrid = spawnNumber(grid)
display(populatedGrid)
return run2048(manipulateGrid(populatedGrid, waitForValidInput()))
}
fun isGridSolved(grid: Array<Array<Int>>): Boolean = grid.any { row -> row.contains(2048) }
fun isGridFull(grid: Array<Array<Int>>): Boolean = grid.all { row -> !row.contains(0) }
fun spawnNumber(grid: Array<Array<Int>>): Array<Array<Int>> {
val coordinates = locateSpawnCoordinates(grid)
val number = generateNumber()
return updateGrid(grid, coordinates, number)
}
fun locateSpawnCoordinates(grid: Array<Array<Int>>): Pair<Int, Int> {
val emptyCells = arrayListOf<Pair<Int, Int>>()
grid.forEachIndexed { x, row ->
row.forEachIndexed { y, cell ->
if (cell == 0) emptyCells.add(Pair(x, y))
}
}
return emptyCells[(Math.random() * (emptyCells.size - 1)).toInt()]
}
fun generateNumber(): Int = if (Math.random() > 0.10) 2 else 4
fun updateGrid(grid: Array<Array<Int>>, at: Pair<Int, Int>, value: Int): Array<Array<Int>> {
val updatedGrid = grid.copyOf()
updatedGrid[at.first][at.second] = value
return updatedGrid
}
fun waitForValidInput(): String {
val input = waitForInput()
return if (isValidInput(input)) input else waitForValidInput()
}
fun isValidInput(input: String): Boolean = arrayOf("a", "s", "d", "w").contains(input)
fun waitForInput(): String {
val reader = BufferedReader(InputStreamReader(System.`in`))
println("Direction? ")
return reader.readLine()
}
fun manipulateGrid(grid: Array<Array<Int>>, input: String): Array<Array<Int>> = when (input) {
"a" -> shiftCellsLeft(grid)
"s" -> shiftCellsDown(grid)
"d" -> shiftCellsRight(grid)
"w" -> shiftCellsUp(grid)
else -> throw IllegalArgumentException("Expected one of [a, s, d, w]")
}
fun shiftCellsLeft(grid: Array<Array<Int>>): Array<Array<Int>> =
grid.map(::mergeAndOrganizeCells).toTypedArray()
fun shiftCellsRight(grid: Array<Array<Int>>): Array<Array<Int>> =
grid.map { row -> mergeAndOrganizeCells(row.reversed().toTypedArray()).reversed().toTypedArray() }.toTypedArray()
fun shiftCellsUp(grid: Array<Array<Int>>): Array<Array<Int>> {
val rows: Array<Array<Int>> = arrayOf(
arrayOf(grid[0][0], grid[1][0], grid[2][0], grid[3][0]),
arrayOf(grid[0][1], grid[1][1], grid[2][1], grid[3][1]),
arrayOf(grid[0][2], grid[1][2], grid[2][2], grid[3][2]),
arrayOf(grid[0][3], grid[1][3], grid[2][3], grid[3][3])
)
val updatedGrid = grid.copyOf()
rows.map(::mergeAndOrganizeCells).forEachIndexed { rowIdx, row ->
updatedGrid[0][rowIdx] = row[0]
updatedGrid[1][rowIdx] = row[1]
updatedGrid[2][rowIdx] = row[2]
updatedGrid[3][rowIdx] = row[3]
}
return updatedGrid
}
fun shiftCellsDown(grid: Array<Array<Int>>): Array<Array<Int>> {
val rows: Array<Array<Int>> = arrayOf(
arrayOf(grid[3][0], grid[2][0], grid[1][0], grid[0][0]),
arrayOf(grid[3][1], grid[2][1], grid[1][1], grid[0][1]),
arrayOf(grid[3][2], grid[2][2], grid[1][2], grid[0][2]),
arrayOf(grid[3][3], grid[2][3], grid[1][3], grid[0][3])
)
val updatedGrid = grid.copyOf()
rows.map(::mergeAndOrganizeCells).forEachIndexed { rowIdx, row ->
updatedGrid[3][rowIdx] = row[0]
updatedGrid[2][rowIdx] = row[1]
updatedGrid[1][rowIdx] = row[2]
updatedGrid[0][rowIdx] = row[3]
}
return updatedGrid
}
fun mergeAndOrganizeCells(row: Array<Int>): Array<Int> = organize(merge(row.copyOf()))
fun merge(row: Array<Int>, idxToMatch: Int = 0, idxToCompare: Int = 1): Array<Int> {
if (idxToMatch >= row.size) return row
if (idxToCompare >= row.size) return merge(row, idxToMatch + 1, idxToMatch + 2)
if (row[idxToMatch] == 0) return merge(row, idxToMatch + 1, idxToMatch + 2)
return if (row[idxToMatch] == row[idxToCompare]) {
row[idxToMatch] *= 2
row[idxToCompare] = 0
merge(row, idxToMatch + 1, idxToMatch + 2)
} else {
if (row[idxToCompare] != 0) merge(row, idxToMatch + 1, idxToMatch + 2)
else merge(row, idxToMatch, idxToCompare + 1)
}
}
fun organize(row: Array<Int>, idxToMatch: Int = 0, idxToCompare: Int = 1): Array<Int> {
if (idxToMatch >= row.size) return row
if (idxToCompare >= row.size) return organize(row, idxToMatch + 1, idxToMatch + 2)
if (row[idxToMatch] != 0) return organize(row, idxToMatch + 1, idxToMatch + 2)
return if (row[idxToCompare] != 0) {
row[idxToMatch] = row[idxToCompare]
row[idxToCompare] = 0
organize(row, idxToMatch + 1, idxToMatch + 2)
} else {
organize(row, idxToMatch, idxToCompare + 1)
}
}
fun display(grid: Array<Array<Int>>) {
val prettyPrintableGrid = grid.map { row ->
row.map { cell ->
if (cell == 0) " " else java.lang.String.format("%4d", cell)
}
}
println("New Grid:")
prettyPrintableGrid.forEach { row ->
println("+----+----+----+----+")
row.forEach { print("|$it") }
println("|")
}
println("+----+----+----+----+")
} |
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
| #beeswax | beeswax |
> NN p
> d#_8~2~(P~3~.~1~>{` bottles of beer on the wall, `{` bottles of beer.`q
d`.llaw eht no reeb fo selttob `{pLM` ,dnuora ti ssap dna nwod eno ekaT`N<
q`.llaw eht no reeb fo elttob ` {<
> NN >{` bottle of beer on the wall, `{` bottle of beer.`N q
pN `.llaw eht no reeb fo selttob erom on ,dnuora ti ssap dna nwod eno ekaT`<
>N`No more bottles of beer on the wall, no more bottles of beer.`N q
;`.llaw eht no reeb fo selttob 99 ,erom emos yub dna erots eht ot oG`<
|
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.
| #LiveCode | LiveCode | on mouseUp
put empty into fld "EvalField"
put empty into fld "AnswerField"
put random(9) & comma & random(9) & comma & random(9) & comma & random(9) into fld "YourNumbersField"
end mouseUp |
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
| #Elena | Elena | import extensions;
public program()
{
var A := Integer.new();
var B := Integer.new();
console.loadLine(A,B).printLine(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
| #MAXScript | MAXScript |
-- This is the blocks array
global GlobalBlocks = #("BO","XK","DQ","CP","NA", \
"GT","RE","TG","QD","FS", \
"JW","HU","VI","AN","OB", \
"ER","FS","LY","PC","ZM")
-- This function returns true if "_str" is part of "_word", false otherwise
fn occurs _str _word =
(
if _str != undefined and _word != undefined then
(
matchpattern _word pattern:("*"+_str+"*")
) else return false
)
-- This is the main function
fn isWordPossible word blocks: = -- blocks is a keyword argument
(
word = toupper word -- convert the string to upper case, to make it case insensitive
if blocks == unsupplied do blocks = GlobalBlocks
-- if blocks (keyword argument) is unsupplied, use the global blocks array (this is for recursion)
blocks = deepcopy blocks
local pos = 1 -- start at the beginning of the word
local solvedLetters = #() -- this array stores the indices of solved letters
while pos <= word.count do -- loop through every character in the word
(
local possibleBlocks = #() -- this array stores the blocks which can be used to make that letter
for b = 1 to Blocks.count do -- this loop finds all the possible blocks that can be used to make that letter
(
if occurs word[pos] blocks[b] do
(
appendifunique possibleBlocks b
)
)
if possibleBlocks.count > 0 then -- if it found any blocks
(
if possibleBlocks.count == 1 then -- if it found one block, then continue
(
appendifunique solvedLetters pos
deleteitem blocks possibleblocks[1]
pos += 1
)
else -- if it found more than one
(
for b = 1 to possibleBlocks.count do -- loop through every possible block
(
local possibleBlock = blocks[possibleBlocks[b]]
local blockFirstLetter = possibleBlock[1]
local blockSecondLetter = possibleBlock[2]
local matchingLetter = if blockFirstLetter == word[pos] then 1 else 2
-- ^ this is the index of the matching letter on the block
local notMatchingIndex = if matchingLetter == 1 then 2 else 1
local notMatchingLetter = possibleBlock[notMatchingIndex]
-- ^ this is the other letter on the block
if occurs notMatchingLetter (substring word (pos+1) -1) then
( -- if the other letter occurs in the rest of the word
local removedBlocks = deepcopy blocks -- copy the current blocks array
deleteitem removedBlocks possibleBlocks[b] -- remove the item from the copied array
-- recursively check if the word is possible if that block is taken away from the array:
if (isWordPossible (substring word (pos+1) -1) blocks:removedBlocks) then
( -- if it is, then remove the block and move to next character
appendifunique solvedLetters pos
deleteitem blocks possibleblocks[1]
pos += 1
exit
)
else
( -- if it isn't and it looped through every possible block, then the word is not possible
if b == possibleBlocks.count do return false
)
)
else
( -- if the other letter on this block doesn't occur in the rest of the word, then the letter is solved, continue
appendifunique solvedLetters pos
deleteitem blocks possibleblocks[b]
pos += 1
exit
)
)
)
) else return false -- if it didn't find any blocks, then return false
)
makeuniquearray solvedLetters -- make sure there are no duplicates in the solved array
if solvedLetters.count != word.count then return false -- if number of solved letters is not equal to word length
else
( -- this checks if all the solved letters are the same as the word
check = ""
for bit in solvedLetters do append check word[bit]
if check == word then return true else return false
)
)
|