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/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.
| #VBA | VBA | Private Function Ackermann_function(m As Variant, n As Variant) As Variant
Dim result As Variant
Debug.Assert m >= 0
Debug.Assert n >= 0
If m = 0 Then
result = CDec(n + 1)
Else
If n = 0 Then
result = Ackermann_function(m - 1, 1)
Else
result = Ackermann_function(m - 1, Ackermann_function(m, n - 1))
End If
End If
Ackermann_function = CDec(result)
End Function
Public Sub main()
Debug.Print " n=",
For j = 0 To 7
Debug.Print j,
Next j
Debug.Print
For i = 0 To 3
Debug.Print "m=" & i,
For j = 0 To 7
Debug.Print Ackermann_function(i, j),
Next j
Debug.Print
Next i
End Sub |
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
| #Go | Go | package main
import (
"fmt"
"strings"
)
func newSpeller(blocks string) func(string) bool {
bl := strings.Fields(blocks)
return func(word string) bool {
return r(word, bl)
}
}
func r(word string, bl []string) bool {
if word == "" {
return true
}
c := word[0] | 32
for i, b := range bl {
if c == b[0]|32 || c == b[1]|32 {
bl[i], bl[0] = bl[0], b
if r(word[1:], bl[1:]) == true {
return true
}
bl[i], bl[0] = bl[0], bl[i]
}
}
return false
}
func main() {
sp := newSpeller(
"BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM")
for _, word := range []string{
"A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "CONFUSE"} {
fmt.Println(word, sp(word))
}
} |
http://rosettacode.org/wiki/100_prisoners | 100 prisoners |
The Problem
100 prisoners are individually numbered 1 to 100
A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside.
Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start.
Prisoners start outside the room
They can decide some strategy before any enter the room.
Prisoners enter the room one by one, can open a drawer, inspect the card number in the drawer, then close the drawer.
A prisoner can open no more than 50 drawers.
A prisoner tries to find his own number.
A prisoner finding his own number is then held apart from the others.
If all 100 prisoners find their own numbers then they will all be pardoned. If any don't then all sentences stand.
The task
Simulate several thousand instances of the game where the prisoners randomly open drawers
Simulate several thousand instances of the game where the prisoners use the optimal strategy mentioned in the Wikipedia article, of:
First opening the drawer whose outside number is his prisoner number.
If the card within has his number then he succeeds otherwise he opens the drawer with the same number as that of the revealed card. (until he opens his maximum).
Show and compare the computed probabilities of success for the two strategies, here, on this page.
References
The unbelievable solution to the 100 prisoner puzzle standupmaths (Video).
wp:100 prisoners problem
100 Prisoners Escape Puzzle DataGenetics.
Random permutation statistics#One hundred prisoners on Wikipedia.
| #F.23 | F# | let rnd = System.Random()
let shuffled min max =
[|min..max|] |> Array.sortBy (fun _ -> rnd.Next(min,max+1))
let drawers () = shuffled 1 100
// strategy randomizing drawer opening
let badChoices (drawers' : int array) =
Seq.init 100 (fun _ -> shuffled 1 100 |> Array.take 50) // selections for each prisoner
|> Seq.map (fun indexes -> indexes |> Array.map(fun index -> drawers'.[index-1])) // transform to cards
|> Seq.mapi (fun i cards -> cards |> Array.contains i) // check if any card matches prisoner number
|> Seq.contains false // true means not all prisoners got their cards
let outcomeOfRandom runs =
let pardons = Seq.init runs (fun _ -> badChoices (drawers ()))
|> Seq.sumBy (fun badChoice -> if badChoice |> not then 1.0 else 0.0)
pardons/ float runs
// strategy optimizing drawer opening
let smartChoice max prisoner (drawers' : int array) =
prisoner
|> Seq.unfold (fun selection ->
let card = drawers'.[selection-1]
Some (card, card))
|> Seq.take max
|> Seq.contains prisoner
let smartChoices (drawers' : int array) =
seq { 1..100 }
|> Seq.map (fun prisoner -> smartChoice 50 prisoner drawers')
|> Seq.filter (fun result -> result |> not) // remove all but false results
|> Seq.isEmpty // empty means all prisoners got their cards
let outcomeOfOptimize runs =
let pardons = Seq.init runs (fun _ -> smartChoices (drawers()))
|> Seq.sumBy (fun smartChoice' -> if smartChoice' then 1.0 else 0.0)
pardons/ float runs
printfn $"Using Random Strategy: {(outcomeOfRandom 20000):p2}"
printfn $"Using Optimum Strategy: {(outcomeOfOptimize 20000):p2}"
|
http://rosettacode.org/wiki/Abundant_odd_numbers | Abundant odd numbers | An Abundant number is a number n for which the sum of divisors σ(n) > 2n,
or, equivalently, the sum of proper divisors (or aliquot sum) s(n) > n.
E.G.
12 is abundant, it has the proper divisors 1,2,3,4 & 6 which sum to 16 ( > 12 or n);
or alternately, has the sigma sum of 1,2,3,4,6 & 12 which sum to 28 ( > 24 or 2n).
Abundant numbers are common, though even abundant numbers seem to be much more common than odd abundant numbers.
To make things more interesting, this task is specifically about finding odd abundant numbers.
Task
Find and display here: at least the first 25 abundant odd numbers and either their proper divisor sum or sigma sum.
Find and display here: the one thousandth abundant odd number and either its proper divisor sum or sigma sum.
Find and display here: the first abundant odd number greater than one billion (109) and either its proper divisor sum or sigma sum.
References
OEIS:A005231: Odd abundant numbers (odd numbers n whose sum of divisors exceeds 2n)
American Journal of Mathematics, Vol. 35, No. 4 (Oct., 1913), pp. 413-422 - Finiteness of the Odd Perfect and Primitive Abundant Numbers with n Distinct Prime Factors (LE Dickson)
| #zkl | zkl | fcn oddAbundants(startAt=3){ //--> iterator
Walker.zero().tweak(fcn(rn){
n:=rn.value;
while(True){
sum:=0;
foreach d in ([3.. n.toFloat().sqrt().toInt(), 2]){
if( (y:=n/d) *d != n) continue;
sum += ((y==d) and y or y+d)
}
if(sum>n){ rn.set(n+2); return(n) }
n+=2;
}
}.fp(Ref(startAt.isOdd and startAt or startAt+1)))
} |
http://rosettacode.org/wiki/21_game | 21 game | 21 game
You are encouraged to solve this task according to the task description, using any language you may know.
21 is a two player game, the game is played by choosing
a number (1, 2, or 3) to be added to the running total.
The game is won by the player whose chosen number causes the running total
to reach exactly 21.
The running total starts at zero.
One player will be the computer.
Players alternate supplying a number to be added to the running total.
Task
Write a computer program that will:
do the prompting (or provide a button menu),
check for errors and display appropriate error messages,
do the additions (add a chosen number to the running total),
display the running total,
provide a mechanism for the player to quit/exit/halt/stop/close the program,
issue a notification when there is a winner, and
determine who goes first (maybe a random or user choice, or can be specified when the game begins).
| #REXX | REXX | /*REXX program plays the 21 game with a human, each player chooses 1, 2, or 3 which */
/*──────────── is added to the current sum, the first player to reach 21 exactly wins.*/
sep= copies('─', 8); sep2= " "copies('═', 8)" " /*construct an eye─catching msg fences.*/
say sep 'Playing the 21 game.' /*tell what's happening here at the zoo*/
$=0; goal= 21 /*the sum [or running total] (so far).*/
do j=1 while $<goal; call g /*obtain the user's number via a prompt*/
if x\==0 then call tot x, 1 /*Not 0? The user wants to go first. */
if $==goal then leave /*the user won the game with the last #*/
call ?; if y==. then y= random(1, 3) /*get computer's choice or a random #*/
say sep 'The computer chooses ' y " as its choice." /*inform player.*/
call tot y, 0 /*call subroutine to show the total. */
end /*j*/
say
if who then say sep 'Congratulations! You have won the 21 game.'
else say sep 'The computer has won the 21 game.'
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
?: y=.; do c=1 for 3 until y\==.; if (c+$) // 4 == 1 then y= c; end; return
ser: if bad then return; bad=1; say; say; say sep '***error***' arg(1); say; return
tot: arg q,who; $=$+q; say sep 'The game total is now' sep2 $ sep2; /*add; show $*/ return
/*──────────────────────────────────────────────────────────────────────────────────────*/
g: low = (j \== 1) /*allow user to have computer go first.*/
do until \bad; bad= 0; say /*prompt 'til user gives a good number.*/
say sep 'Please enter a number from ' low " ───► 3 (or Quit):"
if j=1 then say sep '[A value of 0 (zero) means you want the computer to go first.]'
parse pull x _ . 1 ox; upper x /*obtain user's lowercase response(s). */
if x='' then call ser "Nothing entered."
if _\=='' then call ser "Too many arguments entered: " ox
if abbrev('QUIT', x, 1) then do; say; say sep "quitting."; exit 1; end
if \datatype(x, 'N') then call ser "Argument isn't numeric: " ox
if \datatype(x, 'W') then call ser "Number isn't an integer: " ox
if x<0 then call ser "Number can't be negative: " x
if x=0 & j>1 then call ser "Number can't be zero: " x
if x>3 then call ser "Number is too large (>3): " x
if bad then iterate /*Had an error? Then get another number*/
x= x/1; if $+x>goal then call ser "Number will cause the sum to exceed " goal': ' x
end /*until*/; return |
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
| #J | J | perm=: (A.&i.~ !) 4
ops=: ' ',.'+-*%' {~ >,{i.each 4 4 4
cmask=: 1 + 0j1 * i.@{:@$@[ e. ]
left=: [ #!.'('~"1 cmask
right=: [ #!.')'~"1 cmask
paren=: 2 :'[: left&m right&n'
parens=: ], 0 paren 3, 0 paren 5, 2 paren 5, [: 0 paren 7 (0 paren 3)
all=: [: parens [:,/ ops ,@,."1/ perm { [:;":each
answer=: ({.@#~ 24 = ".)@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
| #Astro | Astro | type Puzzle(var items: {}, var position: -1)
fun mainframe(puz):
let d = puz.items
print('+-----+-----+-----+-----+')
print(d[1], d[2], d[3], d[4], first: '|', sep: '|', last: '|')
print('+-----+-----+-----+-----+')
print(d[5], d[6], d[7], d[8], first: '|', sep: '|', last: '|')
print('+-----+-----+-----+-----+')
print(d[9], d[10], d[11], d[12], first: '|', sep: '|', last: '|')
print('+-----+-----+-----+-----+')
print(d[13], d[14], d[15], d[16], first: '|', sep: '|', last: '|')
print('+-----+-----+-----+-----+')
fun format(puz, ch):
match ch.trim().length:
1 => ' $ch '
2 => ' $ch '
0 => ' '
fun change(puz, to):
let fro = puz.position
for a, b in puz.items where b == puz.format(str i):
to = a
break
swap(puz.items[fro], :[to])
puz.position = to;
fun buildboard(puz, difficulty):
for i in 1..16:
puz.items[i] = puz.format(str i)
var tmp = a
for a, b in puz.items where b == ' 16 ':
puz.items[a] = ' '
tmp = a
break
puz.position = tmp
let diff = match difficulty:
0 => 10
1 => 50
_ => 100
for i in 1..diff:
let lst = puz.validmoves()
let lst1 = []
for j in lst:
lst1.push! j.trim().int()
puz.change(lst1[random(1, lst1.length - 1)])
fun validmoves(puz):
match puz.position:
6 | 7 | 10 | 11 =>
puz.items[pos - 4], :[pos - 1], :[pos + 1], :[pos + 4]
5 | 9 =>
puz.items[pos - 4], :[pos + 4], :[pos + 1]
8 | 12 =>
puz.items[pos - 4], :[pos + 4], :[pos - 1]
2 | 3 =>
puz.items[pos - 1], :[pos + 1], :[pos + 4]
14 | 15 =>
puz.items[pos - 1], :[pos + 1], :[pos - 4]
1 =>
puz.items[pos + 1], :[pos + 4]
4 =>
puz.items[pos - 1], :[pos + 4]
13 =>
puz.items[pos + 1], :[pos - 4]
16 =>
puz.items[pos - 1], :[pos - 4]
fun mainframe(puz):
var flag = false
for a, b in puz.items:
if b == ' ':
pass
else:
flag = (a == b.trim().int())
..
return flag
let game = Puzzle()
game.buildboard(
int(input('Enter the difficulty : 0 1 2\n2 => highest 0=> lowest\n'))
)
game.mainframe()
print 'Enter 0 to exit'
loop:
print 'Hello user:\nTo change the position just enter the no. near it'
var lst = game.validmoves()
var lst1 = []
for i in lst:
lst1.push! i.trim().int()
print(i.strip(), '\t', last: '')
print()
let value = int(input())
if value == 0:
break
elif x not in lst1:
print('Wrong move')
else:
game.change(x)
game.mainframe()
if g.gameover():
print 'You WON'
break
|
http://rosettacode.org/wiki/2048 | 2048 | Task
Implement a 2D sliding block puzzle game where blocks with numbers are combined to add their values.
Rules of the game
The rules are that on each turn the player must choose a direction (up, down, left or right).
All tiles move as far as possible in that direction, some move more than others.
Two adjacent tiles (in that direction only) with matching numbers combine into one bearing the sum of those numbers.
A move is valid when at least one tile can be moved, if only by combination.
A new tile with the value of 2 is spawned at the end of each turn at a randomly chosen empty square (if there is one).
Adding a new tile on a blank space. Most of the time, a new 2 is to be added, and occasionally (10% of the time), a 4.
To win, the player must create a tile with the number 2048.
The player loses if no valid moves are possible.
The name comes from the popular open-source implementation of this game mechanic, 2048.
Requirements
"Non-greedy" movement.
The tiles that were created by combining other tiles should not be combined again during the same turn (move).
That is to say, that moving the tile row of:
[2][2][2][2]
to the right should result in:
......[4][4]
and not:
.........[8]
"Move direction priority".
If more than one variant of combining is possible, move direction shall indicate which combination will take effect.
For example, moving the tile row of:
...[2][2][2]
to the right should result in:
......[2][4]
and not:
......[4][2]
Check for valid moves. The player shouldn't be able to skip their turn by trying a move that doesn't change the board.
Check for a win condition.
Check for a lose condition.
| #C.2B.2B | C++ |
#include <time.h>
#include <iostream>
#include <string>
#include <iomanip>
#include <cstdlib>
typedef unsigned int uint;
using namespace std;
enum movDir { UP, DOWN, LEFT, RIGHT };
class tile
{
public:
tile() : val( 0 ), blocked( false ) {}
uint val;
bool blocked;
};
class g2048
{
public:
g2048() : done( false ), win( false ), moved( true ), score( 0 ) {}
void loop()
{
addTile();
while( true )
{
if( moved ) addTile();
drawBoard();
if( done ) break;
waitKey();
}
string s = "Game Over!";
if( win ) s = "You've made it!";
cout << s << endl << endl;
}
private:
void drawBoard()
{
system( "cls" );
cout << "SCORE: " << score << endl << endl;
for( int y = 0; y < 4; y++ )
{
cout << "+------+------+------+------+" << endl << "| ";
for( int x = 0; x < 4; x++ )
{
if( !board[x][y].val ) cout << setw( 4 ) << " ";
else cout << setw( 4 ) << board[x][y].val;
cout << " | ";
}
cout << endl;
}
cout << "+------+------+------+------+" << endl << endl;
}
void waitKey()
{
moved = false; char c;
cout << "(W)Up (S)Down (A)Left (D)Right "; cin >> c; c &= 0x5F;
switch( c )
{
case 'W': move( UP );break;
case 'A': move( LEFT ); break;
case 'S': move( DOWN ); break;
case 'D': move( RIGHT );
}
for( int y = 0; y < 4; y++ )
for( int x = 0; x < 4; x++ )
board[x][y].blocked = false;
}
void addTile()
{
for( int y = 0; y < 4; y++ )
for( int x = 0; x < 4; x++ )
if( !board[x][y].val )
{
uint a, b;
do
{ a = rand() % 4; b = rand() % 4; }
while( board[a][b].val );
int s = rand() % 100;
if( s > 89 ) board[a][b].val = 4;
else board[a][b].val = 2;
if( canMove() ) return;
}
done = true;
}
bool canMove()
{
for( int y = 0; y < 4; y++ )
for( int x = 0; x < 4; x++ )
if( !board[x][y].val ) return true;
for( int y = 0; y < 4; y++ )
for( int x = 0; x < 4; x++ )
{
if( testAdd( x + 1, y, board[x][y].val ) ) return true;
if( testAdd( x - 1, y, board[x][y].val ) ) return true;
if( testAdd( x, y + 1, board[x][y].val ) ) return true;
if( testAdd( x, y - 1, board[x][y].val ) ) return true;
}
return false;
}
bool testAdd( int x, int y, uint v )
{
if( x < 0 || x > 3 || y < 0 || y > 3 ) return false;
return board[x][y].val == v;
}
void moveVert( int x, int y, int d )
{
if( board[x][y + d].val && board[x][y + d].val == board[x][y].val && !board[x][y].blocked && !board[x][y + d].blocked )
{
board[x][y].val = 0;
board[x][y + d].val *= 2;
score += board[x][y + d].val;
board[x][y + d].blocked = true;
moved = true;
}
else if( !board[x][y + d].val && board[x][y].val )
{
board[x][y + d].val = board[x][y].val;
board[x][y].val = 0;
moved = true;
}
if( d > 0 ) { if( y + d < 3 ) moveVert( x, y + d, 1 ); }
else { if( y + d > 0 ) moveVert( x, y + d, -1 ); }
}
void moveHori( int x, int y, int d )
{
if( board[x + d][y].val && board[x + d][y].val == board[x][y].val && !board[x][y].blocked && !board[x + d][y].blocked )
{
board[x][y].val = 0;
board[x + d][y].val *= 2;
score += board[x + d][y].val;
board[x + d][y].blocked = true;
moved = true;
}
else if( !board[x + d][y].val && board[x][y].val )
{
board[x + d][y].val = board[x][y].val;
board[x][y].val = 0;
moved = true;
}
if( d > 0 ) { if( x + d < 3 ) moveHori( x + d, y, 1 ); }
else { if( x + d > 0 ) moveHori( x + d, y, -1 ); }
}
void move( movDir d )
{
switch( d )
{
case UP:
for( int x = 0; x < 4; x++ )
{
int y = 1;
while( y < 4 )
{ if( board[x][y].val ) moveVert( x, y, -1 ); y++;}
}
break;
case DOWN:
for( int x = 0; x < 4; x++ )
{
int y = 2;
while( y >= 0 )
{ if( board[x][y].val ) moveVert( x, y, 1 ); y--;}
}
break;
case LEFT:
for( int y = 0; y < 4; y++ )
{
int x = 1;
while( x < 4 )
{ if( board[x][y].val ) moveHori( x, y, -1 ); x++;}
}
break;
case RIGHT:
for( int y = 0; y < 4; y++ )
{
int x = 2;
while( x >= 0 )
{ if( board[x][y].val ) moveHori( x, y, 1 ); x--;}
}
}
}
tile board[4][4];
bool win, done, moved;
uint score;
};
int main( int argc, char* argv[] )
{
srand( static_cast<uint>( time( NULL ) ) );
g2048 g; g.loop();
return system( "pause" );
}
|
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
| #Rust | Rust |
#![feature(inclusive_range_syntax)]
fn is_unique(a: u8, b: u8, c: u8, d: u8, e: u8, f: u8, g: u8) -> bool {
a != b && a != c && a != d && a != e && a != f && a != g &&
b != c && b != d && b != e && b != f && b != g &&
c != d && c != e && c != f && c != g &&
d != e && d != f && d != g &&
e != f && e != g &&
f != g
}
fn is_solution(a: u8, b: u8, c: u8, d: u8, e: u8, f: u8, g: u8) -> bool {
a + b == b + c + d &&
b + c + d == d + e + f &&
d + e + f == f + g
}
fn four_squares(low: u8, high: u8, unique: bool) -> Vec<Vec<u8>> {
let mut results: Vec<Vec<u8>> = Vec::new();
for a in low..=high {
for b in low..=high {
for c in low..=high {
for d in low..=high {
for e in low..=high {
for f in low..=high {
for g in low..=high {
if (!unique || is_unique(a, b, c, d, e, f, g)) &&
is_solution(a, b, c, d, e, f, g) {
results.push(vec![a, b, c, d, e, f, g]);
}
}
}
}
}
}
}
}
results
}
fn print_results(solutions: &Vec<Vec<u8>>) {
for solution in solutions {
println!("{:?}", solution)
}
}
fn print_results_summary(solutions: usize, low: u8, high: u8, unique: bool) {
let uniqueness = if unique {
"unique"
} else {
"non-unique"
};
println!("{} {} solutions in {} to {} range", solutions, uniqueness, low, high)
}
fn uniques(low: u8, high: u8) {
let solutions = four_squares(low, high, true);
print_results(&solutions);
print_results_summary(solutions.len(), low, high, true);
}
fn nonuniques(low: u8, high: u8) {
let solutions = four_squares(low, high, false);
print_results_summary(solutions.len(), low, high, false);
}
fn main() {
uniques(1, 7);
println!();
uniques(3, 9);
println!();
nonuniques(0, 9);
}
|
http://rosettacode.org/wiki/15_puzzle_solver | 15 puzzle solver | Your task is to write a program that finds a solution in the fewest moves possible single moves to a random Fifteen Puzzle Game.
For this task you will be using the following puzzle:
15 14 1 6
9 11 4 12
0 10 7 3
13 8 5 2
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 0
The output must show the moves' directions, like so: left, left, left, down, right... and so on.
There are two solutions, of fifty-two moves:
rrrulddluuuldrurdddrullulurrrddldluurddlulurruldrdrd
rrruldluuldrurdddluulurrrdlddruldluurddlulurruldrrdd
see: Pretty Print of Optimal Solution
Finding either one, or both is an acceptable result.
Extra credit.
Solve the following problem:
0 12 9 13
15 11 10 14
3 7 2 5
4 8 6 1
Related Task
15 puzzle game
A* search algorithm
| #Nim | Nim |
# 15 puzzle.
import strformat
import times
const
Nr = [3, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3]
Nc = [3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2]
type
Solver = object
n: int
np: int
n0: array[100, int]
n2: array[100, uint64]
n3: array[100, char]
n4: array[100, int]
Value = range[0..15]
# Forward definition.
proc fN(s: var Solver): bool
#---------------------------------------------------------------------------------------------------
proc fI(s: var Solver) =
let n = s.n
let g = (11 - s.n0[n]) * 4
let a = s.n2[n] and uint(15 shl g)
s.n0[n + 1] = s.n0[n] + 4
s.n2[n + 1] = s.n2[n] - a + a shl 16
s.n3[n + 1] = 'd'
s.n4[n + 1] = s.n4[n] + ord(Nr[a shr g] > s.n0[n] div 4)
#---------------------------------------------------------------------------------------------------
proc fG(s: var Solver) =
let n = s.n
let g = (19 - s.n0[n]) * 4
let a = s.n2[n] and uint(15 shl g)
s.n0[n + 1] = s.n0[n] - 4
s.n2[n + 1] = s.n2[n] - a + a shr 16
s.n3[n + 1] = 'u'
s.n4[n + 1] = s.n4[n] + ord(Nr[a shr g] < s.n0[n] div 4)
#---------------------------------------------------------------------------------------------------
proc fE(s: var Solver) =
let n = s.n
let g = (14 - s.n0[n]) * 4
let a = s.n2[n] and uint(15 shl g)
s.n0[n + 1] = s.n0[n] + 1
s.n2[n + 1] = s.n2[n] - a + a shl 4
s.n3[n + 1] = 'r'
s.n4[n + 1] = s.n4[n] + ord(Nc[a shr g] > s.n0[n] mod 4)
#---------------------------------------------------------------------------------------------------
proc fL(s: var Solver) =
let n = s.n
let g = (16 - s.n0[n]) * 4
let a = s.n2[n] and uint(15 shl g)
s.n0[n + 1] = s.n0[n] - 1
s.n2[n + 1] = s.n2[n] - a + a shr 4
s.n3[n + 1] = 'l'
s.n4[n + 1] = s.n4[n] + ord(Nc[a shr g] < s.n0[n] mod 4)
#---------------------------------------------------------------------------------------------------
proc fY(s: var Solver): bool =
if s.n2[s.n] == 0x123456789abcdef0'u:
return true
if s.n4[s.n] <= s.np:
return s.fN()
#---------------------------------------------------------------------------------------------------
proc fN(s: var Solver): bool =
let n = s.n
if s.n3[n] != 'u' and s.n0[n] div 4 < 3:
s.fI
inc s.n
if s.fY(): return true
dec s.n
if s.n3[n] != 'd' and s.n0[n] div 4 > 0:
s.fG()
inc s.n
if s.fY(): return true
dec s.n
if s.n3[n] != 'l' and s.n0[n] mod 4 < 3:
s.fE()
inc s.n
if s.fY(): return true
dec s.n
if s.n3[n] != 'r' and s.n0[n] mod 4 > 0:
s.fL()
inc s.n
if s.fY(): return true
dec s.n
#---------------------------------------------------------------------------------------------------
proc initSolver(values: array[16, Value]): Solver {.noInit.} =
result.n = 0
result.np = 0
result.n0[0] = values.find(0)
result.n2[0] = (var tmp = 0'u; for val in values: tmp = tmp shl 4 or uint(val); tmp)
result.n4[0] = 0
#---------------------------------------------------------------------------------------------------
proc run(s: var Solver) =
while not s.fY():
inc s.np
stdout.write(fmt"Solution found with {s.n} moves: ")
for g in 1..s.n:
stdout.write(s.n3[g])
stdout.write(".\n")
#---------------------------------------------------------------------------------------------------
proc toString(d: Duration): string =
# Custom representation of a duration.
const Plural: array[bool, string] = ["", "s"]
var ms = d.inMilliseconds
for (label, d) in {"hour": 3_600_000, "minute": 60_000, "second": 1_000, "millisecond": 1}:
let val = ms div d
if val > 0:
result.add($val & ' ' & label & Plural[val > 1])
ms = ms mod d
if ms > 0: result.add(' ')
|
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
| #Argile | Argile | use std
let X be an int
for each X from 99 down to 1
prints X bottles of beer on the wall
prints X bottles of beer
prints "Take one down, pass it" around
if X == 1
echo No more "beer." Call da "amber lamps"
break
X--
prints X bottles of beer on the wall "\n"
X++
.:around :. -> text {X>59 ? "around", "to me"}
.:bottles:. -> text {X> 5 ? "bottles", (X>1 ? "buttles", "wall")}
.:of beer:. -> text {X>11 ? "of beer", "ov beeer"}
.:on the wall:. -> text {
X>17 ? "on the wall", (X>1 ? "on the bwall", "in the buttle")
} |
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.
| #Falcon | Falcon | load compiler
function genRandomNumbers( amount )
rtn = []
for i in [ 0 : amount ]: rtn += random( 1, 9 )
return( rtn )
end
function getAnswer( exp )
ic = ICompiler()
ic.compileAll(exp)
return( ic.result )
end
function validInput( str )
for i in [ 0 : str.len() ]
if str[i] notin ' ()[]0123456789-+/*'
> 'INVALID Character = ', str[i]
return( false )
end
end
return( true )
end
printl('
The 24 Game
Given any four digits in the range 1 to 9, which may have repetitions,
Using just the +, -, *, and / operators; and the possible use of
brackets, (), show how to make an answer of 24.
An answer of "q" will quit the game.
An answer of "!" will generate a new set of four digits.
Otherwise you are repeatedly asked for an expression until it evaluates to 24
Note: you cannot form multiple digit numbers from the supplied digits,
so an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.
')
num = genRandomNumbers( 4 )
while( true )
>> "Here are the numbers to choose from: "
map({ a => print(a, " ") }, num)
>
exp = input()
switch exp
case "q", "Q"
exit()
case "!"
> 'Generating new numbers list'
num = genRandomNumbers( 4 )
default
if not validInput( exp ): continue
answer = getAnswer( exp )
if answer == 24
> "By George you GOT IT! Your expression equals 24"
else
> "Ahh Sorry, So Sorry your answer of ", answer, " does not equal 24."
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
| #Computer.2Fzero_Assembly | Computer/zero Assembly | STP ; wait for input
a: 0
b: 0
LDA a
ADD b
STP |
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.
| #VBScript | VBScript | option explicit
'~ dim depth
function ack(m, n)
'~ wscript.stdout.write depth & " "
if m = 0 then
'~ depth = depth + 1
ack = n + 1
'~ depth = depth - 1
elseif m > 0 and n = 0 then
'~ depth = depth + 1
ack = ack(m - 1, 1)
'~ depth = depth - 1
'~ elseif m > 0 and n > 0 then
else
'~ depth = depth + 1
ack = ack(m - 1, ack(m, n - 1))
'~ depth = depth - 1
end if
end function |
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
| #Groovy | Groovy | class ABCSolver {
def blocks
ABCSolver(blocks = []) { this.blocks = blocks }
boolean canMakeWord(rawWord) {
if (rawWord == '' || rawWord == null) { return true; }
def word = rawWord.toUpperCase()
def blocksLeft = [] + blocks
word.every { letter -> blocksLeft.remove(blocksLeft.find { block -> block.contains(letter) }) }
}
} |
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.
| #Factor | Factor | USING: arrays formatting fry io kernel math random sequences ;
: setup ( -- seq seq ) 100 <iota> dup >array randomize ;
: rand ( -- ? )
setup [ 50 sample member? not ] curry find nip >boolean not ;
: trail ( m seq -- n )
50 pick '[ [ nth ] keep over _ = ] replicate [ t = ] any?
2nip ;
: optimal ( -- ? ) setup [ trail ] curry [ and ] map-reduce ;
: simulate ( m quot -- x )
dupd replicate [ t = ] count swap /f 100 * ; inline
"Simulation count: 10,000" print
10,000 [ rand ] simulate "Random play success: "
10,000 [ optimal ] simulate "Optimal play success: "
[ write "%.2f%%\n" printf ] 2bi@ |
http://rosettacode.org/wiki/21_game | 21 game | 21 game
You are encouraged to solve this task according to the task description, using any language you may know.
21 is a two player game, the game is played by choosing
a number (1, 2, or 3) to be added to the running total.
The game is won by the player whose chosen number causes the running total
to reach exactly 21.
The running total starts at zero.
One player will be the computer.
Players alternate supplying a number to be added to the running total.
Task
Write a computer program that will:
do the prompting (or provide a button menu),
check for errors and display appropriate error messages,
do the additions (add a chosen number to the running total),
display the running total,
provide a mechanism for the player to quit/exit/halt/stop/close the program,
issue a notification when there is a winner, and
determine who goes first (maybe a random or user choice, or can be specified when the game begins).
| #Ring | Ring |
# Project : 21 Game
load "guilib.ring"
limit = 21
posold = 0
button = list(limit)
mynum = list(3)
yournum = list(3)
new qapp
{
win1 = new qwidget() {
setwindowtitle("21 Game")
setgeometry(100,100,1000,600)
label1 = new qlabel(win1) {
setgeometry(10,10,1000,600)
settext("")
}
label2 = new qlabel(win1) {
setgeometry(240,50,120,40)
setAlignment(Qt_AlignHCenter)
setFont(new qFont("Verdana",12,100,0))
settext("my number:")
}
label3 = new qlabel(win1) {
setgeometry(640,50,120,40)
setAlignment(Qt_AlignHCenter)
setFont(new qFont("Verdana",12,100,0))
settext("your number:")
}
for p = 1 to 3
mynum[p] = new qpushbutton(win1) {
setgeometry(200+p*40,100,40,40)
setstylesheet("background-color:orange")
settext(string(p))
setclickevent("choose(" + string(p) + ",1)")
}
next
for p = 1 to 3
yournum[p] = new qpushbutton(win1) {
setgeometry(600+p*40,100,40,40)
setstylesheet("background-color:white")
settext(string(p))
setclickevent("choose(" + string(p) + ",2)")
}
next
for n = 1 to limit
button[n] = new qpushbutton(win1) {
setgeometry(40+n*40,190,40,40)
settext(string(n))
}
next
show()
}
exec()
}
func choose(ch,ym)
pos = posold + ch
if pos > limit
msg = "You must choose number from 1 to " + string(limit - posold)
msgBox(msg)
for n = 1 to 3
mynum[n].setenabled(false)
yournum[n].setenabled(false)
next
return
ok
for n = posold+1 to pos
if ym = 1
button[n] { setstylesheet("background-color:orange") }
else
button[n] { setstylesheet("background-color:white") }
ok
next
posold = pos
if ym = 1
for n = 1 to 3
mynum[n].setenabled(false)
yournum[n].setenabled(true)
next
else
for n = 1 to 3
mynum[n].setenabled(true)
yournum[n].setenabled(false)
next
ok
if pos = 21
if ym = 1
msgBox("I won!")
else
msgBox("You won!")
ok
ok
func msgBox(text) {
m = new qMessageBox(win1) {
setWindowTitle("21 Game")
setText(text)
show()
}
}
|
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
| #Java | Java | import java.util.*;
public class Game24Player {
final String[] patterns = {"nnonnoo", "nnonono", "nnnoono", "nnnonoo",
"nnnnooo"};
final String ops = "+-*/^";
String solution;
List<Integer> digits;
public static void main(String[] args) {
new Game24Player().play();
}
void play() {
digits = getSolvableDigits();
Scanner in = new Scanner(System.in);
while (true) {
System.out.print("Make 24 using these digits: ");
System.out.println(digits);
System.out.println("(Enter 'q' to quit, 's' for a solution)");
System.out.print("> ");
String line = in.nextLine();
if (line.equalsIgnoreCase("q")) {
System.out.println("\nThanks for playing");
return;
}
if (line.equalsIgnoreCase("s")) {
System.out.println(solution);
digits = getSolvableDigits();
continue;
}
char[] entry = line.replaceAll("[^*+-/)(\\d]", "").toCharArray();
try {
validate(entry);
if (evaluate(infixToPostfix(entry))) {
System.out.println("\nCorrect! Want to try another? ");
digits = getSolvableDigits();
} else {
System.out.println("\nNot correct.");
}
} catch (Exception e) {
System.out.printf("%n%s Try again.%n", e.getMessage());
}
}
}
void validate(char[] input) throws Exception {
int total1 = 0, parens = 0, opsCount = 0;
for (char c : input) {
if (Character.isDigit(c))
total1 += 1 << (c - '0') * 4;
else if (c == '(')
parens++;
else if (c == ')')
parens--;
else if (ops.indexOf(c) != -1)
opsCount++;
if (parens < 0)
throw new Exception("Parentheses mismatch.");
}
if (parens != 0)
throw new Exception("Parentheses mismatch.");
if (opsCount != 3)
throw new Exception("Wrong number of operators.");
int total2 = 0;
for (int d : digits)
total2 += 1 << d * 4;
if (total1 != total2)
throw new Exception("Not the same digits.");
}
boolean evaluate(char[] line) throws Exception {
Stack<Float> s = new Stack<>();
try {
for (char c : line) {
if ('0' <= c && c <= '9')
s.push((float) c - '0');
else
s.push(applyOperator(s.pop(), s.pop(), c));
}
} catch (EmptyStackException e) {
throw new Exception("Invalid entry.");
}
return (Math.abs(24 - s.peek()) < 0.001F);
}
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;
}
}
List<Integer> randomDigits() {
Random r = new Random();
List<Integer> result = new ArrayList<>(4);
for (int i = 0; i < 4; i++)
result.add(r.nextInt(9) + 1);
return result;
}
List<Integer> getSolvableDigits() {
List<Integer> result;
do {
result = randomDigits();
} while (!isSolvable(result));
return result;
}
boolean isSolvable(List<Integer> digits) {
Set<List<Integer>> dPerms = new HashSet<>(4 * 3 * 2);
permute(digits, dPerms, 0);
int total = 4 * 4 * 4;
List<List<Integer>> oPerms = new ArrayList<>(total);
permuteOperators(oPerms, 4, total);
StringBuilder sb = new StringBuilder(4 + 3);
for (String pattern : patterns) {
char[] patternChars = pattern.toCharArray();
for (List<Integer> dig : dPerms) {
for (List<Integer> opr : oPerms) {
int i = 0, j = 0;
for (char c : patternChars) {
if (c == 'n')
sb.append(dig.get(i++));
else
sb.append(ops.charAt(opr.get(j++)));
}
String candidate = sb.toString();
try {
if (evaluate(candidate.toCharArray())) {
solution = postfixToInfix(candidate);
return true;
}
} catch (Exception ignored) {
}
sb.setLength(0);
}
}
}
return false;
}
String postfixToInfix(String postfix) {
class Expression {
String op, ex;
int prec = 3;
Expression(String e) {
ex = e;
}
Expression(String e1, String e2, String o) {
ex = String.format("%s %s %s", e1, o, e2);
op = o;
prec = ops.indexOf(o) / 2;
}
}
Stack<Expression> expr = new Stack<>();
for (char c : postfix.toCharArray()) {
int idx = ops.indexOf(c);
if (idx != -1) {
Expression r = expr.pop();
Expression l = expr.pop();
int opPrec = idx / 2;
if (l.prec < opPrec)
l.ex = '(' + l.ex + ')';
if (r.prec <= opPrec)
r.ex = '(' + r.ex + ')';
expr.push(new Expression(l.ex, r.ex, "" + c));
} else {
expr.push(new Expression("" + c));
}
}
return expr.peek().ex;
}
char[] infixToPostfix(char[] infix) throws Exception {
StringBuilder sb = new StringBuilder();
Stack<Integer> s = new Stack<>();
try {
for (char c : infix) {
int idx = ops.indexOf(c);
if (idx != -1) {
if (s.isEmpty())
s.push(idx);
else {
while (!s.isEmpty()) {
int prec2 = s.peek() / 2;
int prec1 = idx / 2;
if (prec2 >= prec1)
sb.append(ops.charAt(s.pop()));
else
break;
}
s.push(idx);
}
} else if (c == '(') {
s.push(-2);
} else if (c == ')') {
while (s.peek() != -2)
sb.append(ops.charAt(s.pop()));
s.pop();
} else {
sb.append(c);
}
}
while (!s.isEmpty())
sb.append(ops.charAt(s.pop()));
} catch (EmptyStackException e) {
throw new Exception("Invalid entry.");
}
return sb.toString().toCharArray();
}
void permute(List<Integer> lst, Set<List<Integer>> res, int k) {
for (int i = k; i < lst.size(); i++) {
Collections.swap(lst, i, k);
permute(lst, res, k + 1);
Collections.swap(lst, k, i);
}
if (k == lst.size())
res.add(new ArrayList<>(lst));
}
void permuteOperators(List<List<Integer>> res, int n, int total) {
for (int i = 0, npow = n * n; i < total; i++)
res.add(Arrays.asList((i / npow), (i % npow) / n, i % 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
| #AutoHotkey | AutoHotkey | Size := 20
Grid := [], Deltas := ["-1,0","1,0","0,-1","0,1"], Width := Size * 2.5
Gui, font, S%Size%
Gui, add, text, y1
loop, 4
{
Row := A_Index
loop, 4
{
Col := A_Index
Gui, add, button, % (Col=1 ? "xs y+1" : "x+1 yp") " v" Row "_" Col " w" Width " gButton -TabStop", % Grid[Row,Col] := Col + (Row-1)*4 ; 1-16
}
}
GuiControl, Hide, % Row "_" Col ; 4_4
Gui, add, Button, % "xs gShuffle w" 4 * Width + 3, Shuffle
Gui, show,, 15 Puzzle
return
;------------------------------
GuiClose:
ExitApp
return
;------------------------------
Shuffle:
Shuffle := true
loop, 1000
{
Random, Rnd, 1,4
Move(StrSplit(Deltas[Rnd], ",").1, StrSplit(Deltas[Rnd], ",").2)
}
Shuffle := false
return
;------------------------------
Button:
buttonRow := SubStr(A_GuiControl, 1, 1), ButtonCol := SubStr(A_GuiControl, 3, 1)
if Abs(buttonRow-Row) > 1 || Abs(ButtonCol-Col) > 1 || Abs(buttonRow-Row) = Abs(ButtonCol-Col)
return
Move(buttonRow-Row, ButtonCol-Col)
return
;------------------------------
#IfWinActive, 15 Puzzle
;------------------------------
Down::
Move(-1, 0)
return
;------------------------------
Up::
Move(1, 0)
return
;------------------------------
Right::
Move(0, -1)
return
;------------------------------
Left::
Move(0, 1)
return
;------------------------------
#IfWinActive
;------------------------------
Move(deltaRow, deltaCol){
global
if (Row+deltaRow=0) || (Row+deltaRow=5) || (Col+deltaCol=0) || (Col+deltaCol=5)
return
GuiControl, Hide, % Row+deltaRow "_" Col+deltaCol
GuiControl, Show, % Row "_" Col
GuiControl,, %Row%_%Col%, % Grid[Row+deltaRow, Col+deltaCol]
Grid[Row, Col] := Grid[Row+deltaRow, Col+deltaCol]
Grid[Row+=deltaRow, Col+=deltaCol] := 16
if Shuffle
return
gridCont := ""
for m, obj in grid
for n, val in obj
gridCont .= val ","
if (Trim(gridCont, ",") = "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16")
MsgBox, 262208, 15 Puzzle, You solved 15 Puzzle
} |
http://rosettacode.org/wiki/2048 | 2048 | Task
Implement a 2D sliding block puzzle game where blocks with numbers are combined to add their values.
Rules of the game
The rules are that on each turn the player must choose a direction (up, down, left or right).
All tiles move as far as possible in that direction, some move more than others.
Two adjacent tiles (in that direction only) with matching numbers combine into one bearing the sum of those numbers.
A move is valid when at least one tile can be moved, if only by combination.
A new tile with the value of 2 is spawned at the end of each turn at a randomly chosen empty square (if there is one).
Adding a new tile on a blank space. Most of the time, a new 2 is to be added, and occasionally (10% of the time), a 4.
To win, the player must create a tile with the number 2048.
The player loses if no valid moves are possible.
The name comes from the popular open-source implementation of this game mechanic, 2048.
Requirements
"Non-greedy" movement.
The tiles that were created by combining other tiles should not be combined again during the same turn (move).
That is to say, that moving the tile row of:
[2][2][2][2]
to the right should result in:
......[4][4]
and not:
.........[8]
"Move direction priority".
If more than one variant of combining is possible, move direction shall indicate which combination will take effect.
For example, moving the tile row of:
...[2][2][2]
to the right should result in:
......[2][4]
and not:
......[4][2]
Check for valid moves. The player shouldn't be able to skip their turn by trying a move that doesn't change the board.
Check for a win condition.
Check for a lose condition.
| #Clojure | Clojure |
(ns 2048
(:require [clojure.string :as str]))
;Preferences
(def textures {:wall "----+"
:cell "%4s|"
:cell-edge "|"
:wall-edge "+"})
(def directions {:w :up
:s :down
:a :left
:d :right})
(def field-size {:y 4 :x 4})
;Output
(defn cells->str [line]
(str (:cell-edge textures)
(str/join (map (partial format (:cell textures)) line))
"\n"))
(defn walls->str [width]
(str (:wall-edge textures)
(str/join (repeat width (:wall textures)))
"\n"))
(defn field->str [field]
(let [height (count field)
width (count (first field))]
(str (str/join (interleave (repeat height (walls->str width))
(map cells->str field)))
(walls->str width))))
;Misc
(defn handle-input []
(let [input (read)
try-dir ((keyword input) directions)]
(if try-dir try-dir (recur))))
(defn get-columns [field]
(vec (for [x (range (count (first field)))]
(vec (for [y (range (count field))]
(get-in field [y x]))))))
(defn reverse-lines [field]
(mapv #(vec (reverse %)) field))
(defn padding [coll n sym]
(vec (concat coll (repeat n sym))))
(defn find-empties [field]
(remove
nil?
(for [y (range (count field))
x (range (count (nth field y)))]
(when (= (get-in field [y x]) \space) [y x]))))
(defn random-add [field]
(let [empties (vec (find-empties field))]
(assoc-in field
(rand-nth empties)
(rand-nth (conj (vec (repeat 9 2)) 4)))))
(defn win-check [field]
(= 2048
(transduce
(filter number?)
(completing max)
0
(flatten field))))
(defn lose-check [field]
(empty? (filter (partial = \space) (flatten field))))
(defn create-start-field [y x]
(->> (vec (repeat y (vec (repeat x \space))))
(random-add)
(random-add)))
;Algo
(defn lines-by-dir [back? direction field]
(case direction
:left field
:right (reverse-lines field)
:down (if back?
(get-columns (reverse-lines field))
(reverse-lines (get-columns field)))
:up (get-columns field)))
(defn shift-line [line]
(let [len (count line)
line (vec (filter number? line))
max-idx (dec (count line))]
(loop [new [] idx 0]
(if (> idx max-idx)
(padding new (- len (count new)) \space)
(if (= (nth line idx) (get line (inc idx)))
(recur (conj new (* 2 (nth line idx))) (+ 2 idx))
(recur (conj new (nth line idx)) (inc idx)))))))
(defn shift-field [direction field]
(->> (lines-by-dir false direction field)
(mapv shift-line)
(lines-by-dir true direction)))
(defn handle-turn [field]
(let [direction (handle-input)]
(->> (shift-field direction field)
(random-add))))
(defn play-2048 []
(loop [field (create-start-field (:y field-size) (:x field-size))]
(println (field->str field))
(cond (win-check field) (println "You win")
(lose-check field) (println "You lose")
:default (recur (handle-turn field)))))
(play-2048) |
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
| #Scala | Scala | object FourRings {
def fourSquare(low: Int, high: Int, unique: Boolean, print: Boolean): Unit = {
def isValid(needle: Integer, haystack: Integer*) = !unique || !haystack.contains(needle)
if (print) println("a b c d e f g")
var count = 0
for {
a <- low to high
b <- low to high if isValid(a, b)
fp = a + b
c <- low to high if isValid(c, a, b)
d <- low to high if isValid(d, a, b, c) && fp == b + c + d
e <- low to high if isValid(e, a, b, c, d)
f <- low to high if isValid(f, a, b, c, d, e) && fp == d + e + f
g <- low to high if isValid(g, a, b, c, d, e, f) && fp == f + g
} {
count += 1
if (print) println(s"$a $b $c $d $e $f $g")
}
println(s"There are $count ${if(unique) "unique" else "non-unique"} solutions in [$low, $high]")
}
def main(args: Array[String]): Unit = {
fourSquare(1, 7, unique = true, print = true)
fourSquare(3, 9, unique = true, print = true)
fourSquare(0, 9, unique = false, print = false)
}
} |
http://rosettacode.org/wiki/15_puzzle_solver | 15 puzzle solver | Your task is to write a program that finds a solution in the fewest moves possible single moves to a random Fifteen Puzzle Game.
For this task you will be using the following puzzle:
15 14 1 6
9 11 4 12
0 10 7 3
13 8 5 2
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 0
The output must show the moves' directions, like so: left, left, left, down, right... and so on.
There are two solutions, of fifty-two moves:
rrrulddluuuldrurdddrullulurrrddldluurddlulurruldrdrd
rrruldluuldrurdddluulurrrdlddruldluurddlulurruldrrdd
see: Pretty Print of Optimal Solution
Finding either one, or both is an acceptable result.
Extra credit.
Solve the following problem:
0 12 9 13
15 11 10 14
3 7 2 5
4 8 6 1
Related Task
15 puzzle game
A* search algorithm
| #Pascal | Pascal |
unit FifteenSolverT;
\\ Solve 15 Puzzle. Nigel Galloway; February 1st., 2019.
interface
type TN=record n:UInt64; i,g,e,l:shortint; end;
type TG=record found:boolean; path:array[0..99] of TN; end;
function solve15(const board : UInt64; const bPos:shortint; const d:shortint; const ng:shortint):TG;
const endPos:UInt64=$123456789abcdef0;
implementation
const N:array[0..15] of shortint=(3,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3);
const I:array[0..15] of shortint=(3,0,1,2,3,0,1,2,3,0,1,2,3,0,1,2);
const G:array[0..15] of shortint=(5,13,13,9,7,15,15,11,7,15,15,11,6,14,14,10);
const E:array[0..15] of shortint=(0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4);
const L:array[0..4 ] of shortint=(0,11,19,14,16);
function solve15(const board:UInt64; const bPos:shortint; const d:shortint; const ng:shortint):TG;
var path:TG; P:^TN; Q:^TN; _g:shortint; _n:UInt64;
begin P:[email protected]; P^.n:=board; P^.i:=0; P^.g:=0; P^.e:=ng; P^.l:=bPos;
while true do begin
if P<@path.path then begin path.found:=false; exit(path); end;
if P^.n=endPos then begin path.found:=true; exit(path); end;
if (P^.e=0) or (P^.i>d) then begin P-=1; continue; end else begin Q:=P+1; Q^.g:=E[P^.e]; end;
Q^.i:=P^.i; _g:=(L[Q^.g]-P^.l)*4; _n:=P^.n and (UInt64($F)<<_g);
case Q^.g of
1:begin Q^.l:=P^.l+4; Q^.e:=G[Q^.l]-2; P^.e-=1; Q^.n:=P^.n-_n+(_n<<16); if N[_n>>_g]>=(Q^.l div 4) then Q^.i+=1; end;
2:begin Q^.l:=P^.l-4; Q^.e:=G[Q^.l]-1; P^.e-=2; Q^.n:=P^.n-_n+(_n>>16); if N[_n>>_g]<=(Q^.l div 4) then Q^.i+=1; end;
3:begin Q^.l:=P^.l+1; Q^.e:=G[Q^.l]-8; P^.e-=4; Q^.n:=P^.n-_n+(_n<< 4); if I[_n>>_g]>=(Q^.l mod 4) then Q^.i+=1; end;
4:begin Q^.l:=P^.l-1; Q^.e:=G[Q^.l]-4; P^.e-=8; Q^.n:=P^.n-_n+(_n>> 4); if I[_n>>_g]<=(Q^.l mod 4) then Q^.i+=1; end;
end;
P+=1;
end;
end;
end.
|
http://rosettacode.org/wiki/99_bottles_of_beer | 99 bottles of beer | Task
Display the complete lyrics for the song: 99 Bottles of Beer on the Wall.
The beer song
The lyrics follow this form:
99 bottles of beer on the wall
99 bottles of beer
Take one down, pass it around
98 bottles of beer on the wall
98 bottles of beer on the wall
98 bottles of beer
Take one down, pass it around
97 bottles of beer on the wall
... and so on, until reaching 0 (zero).
Grammatical support for 1 bottle of beer is optional.
As with any puzzle, try to do it in as creative/concise/comical a way
as possible (simple, obvious solutions allowed, too).
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
See also
http://99-bottles-of-beer.net/
Category:99_Bottles_of_Beer
Category:Programming language families
Wikipedia 99 bottles of beer
| #ARM_Assembly | ARM Assembly | IT'S SHOWTIME
HEY CHRISTMAS TREE is0
YOU SET US UP @NO PROBLEMO
HEY CHRISTMAS TREE bottles
YOU SET US UP 99
STICK AROUND is0
TALK TO THE HAND bottles
TALK TO THE HAND " bottles of beer on the wall"
TALK TO THE HAND bottles
TALK TO THE HAND " bottles of beer"
TALK TO THE HAND "Take one down, pass it around"
GET TO THE CHOPPER bottles
HERE IS MY INVITATION bottles
GET DOWN 1
ENOUGH TALK
TALK TO THE HAND bottles
TALK TO THE HAND " bottles of beer on the wall"
GET TO THE CHOPPER is0
HERE IS MY INVITATION bottles
LET OFF SOME STEAM BENNET 0
ENOUGH TALK
CHILL
YOU HAVE BEEN TERMINATED |
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.
| #Fortran | Fortran | program game_24
implicit none
real :: vector(4), reals(11), result, a, b, c, d
integer :: numbers(4), ascii(11), i
character(len=11) :: expression
character :: syntax(11)
! patterns:
character, parameter :: one(11) = (/ '(','(','1','x','1',')','x','1',')','x','1' /)
character, parameter :: two(11) = (/ '(','1','x','(','1','x','1',')',')','x','1' /)
character, parameter :: three(11) = (/ '1','x','(','(','1','x','1',')','x','1',')' /)
character, parameter :: four(11) = (/ '1','x','(','1','x','(','1','x','1',')',')' /)
character, parameter :: five(11) = (/ '(','1','x','1',')','x','(','1','x','1',')' /)
do
call random_number(vector)
numbers = 9 * vector + 1
write (*,*) 'Digits: ',numbers
write (*,'(a)',advance='no') 'Your expression: '
read (*,'(a11)') expression
forall (i=1:11) syntax(i) = expression(i:i)
ascii = iachar(syntax)
where (syntax >= '0' .and. syntax <= '9')
syntax = '1' ! number
elsewhere (syntax == '+' .or. syntax == '-' .or. syntax == '*' .or. syntax == '/')
syntax = 'x' ! op
elsewhere (syntax /= '(' .and. syntax /= ')')
syntax = '-' ! error
end where
reals = real(ascii-48)
if ( all(syntax == one) ) then
a = reals(3); b = reals(5); c = reals(8); d = reals(11)
call check_numbers(a,b,c,d)
result = op(op(op(a,4,b),7,c),10,d)
else if ( all(syntax == two) ) then
a = reals(2); b = reals(5); c = reals(7); d = reals(11)
call check_numbers(a,b,c,d)
result = op(op(a,3,op(b,6,c)),10,d)
else if ( all(syntax == three) ) then
a = reals(1); b = reals(5); c = reals(7); d = reals(10)
call check_numbers(a,b,c,d)
result = op(a,2,op(op(b,6,c),9,d))
else if ( all(syntax == four) ) then
a = reals(1); b = reals(4); c = reals(7); d = reals(9)
call check_numbers(a,b,c,d)
result = op(a,2,op(b,5,op(c,8,d)))
else if ( all(syntax == five) ) then
a = reals(2); b = reals(4); c = reals(8); d = reals(10)
call check_numbers(a,b,c,d)
result = op(op(a,3,b),6,op(c,9,d))
else
stop 'Input string: incorrect syntax.'
end if
if ( abs(result-24.0) < epsilon(1.0) ) then
write (*,*) 'You won!'
else
write (*,*) 'Your result (',result,') is incorrect!'
end if
write (*,'(a)',advance='no') 'Another one? [y/n] '
read (*,'(a1)') expression
if ( expression(1:1) == 'n' .or. expression(1:1) == 'N' ) then
stop
end if
end do
contains
pure real function op(x,c,y)
integer, intent(in) :: c
real, intent(in) :: x,y
select case ( char(ascii(c)) )
case ('+')
op = x+y
case ('-')
op = x-y
case ('*')
op = x*y
case ('/')
op = x/y
end select
end function op
subroutine check_numbers(a,b,c,d)
real, intent(in) :: a,b,c,d
integer :: test(4)
test = (/ nint(a),nint(b),nint(c),nint(d) /)
call Insertion_Sort(numbers)
call Insertion_Sort(test)
if ( any(test /= numbers) ) then
stop 'You cheat ;-) (Incorrect numbers)'
end if
end subroutine check_numbers
pure subroutine Insertion_Sort(a)
integer, intent(inout) :: a(:)
integer :: temp, i, j
do i=2,size(a)
j = i-1
temp = a(i)
do while ( j>=1 .and. a(j)>temp )
a(j+1) = a(j)
j = j - 1
end do
a(j+1) = temp
end do
end subroutine Insertion_Sort
end program game_24
|
http://rosettacode.org/wiki/A%2BB | A+B | A+B ─── a classic problem in programming contests, it's given so contestants can gain familiarity with the online judging system being used.
Task
Given two integers, A and B.
Their sum needs to be calculated.
Input data
Two integers are written in the input stream, separated by space(s):
(
−
1000
≤
A
,
B
≤
+
1000
)
{\displaystyle (-1000\leq A,B\leq +1000)}
Output data
The required output is one integer: the sum of A and B.
Example
input
output
2 2
4
3 2
5
| #Crystal | Crystal | puts gets.not_nil!.split.map(&.to_i).sum |
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.
| #Visual_Basic | Visual Basic |
Option Explicit
Dim calls As Long
Sub main()
Const maxi = 4
Const maxj = 9
Dim i As Long, j As Long
For i = 0 To maxi
For j = 0 To maxj
Call print_acker(i, j)
Next j
Next i
End Sub 'main
Sub print_acker(m As Long, n As Long)
calls = 0
Debug.Print "ackermann("; m; ","; n; ")=";
Debug.Print ackermann(m, n), "calls="; calls
End Sub 'print_acker
Function ackermann(m As Long, n As Long) As Long
calls = calls + 1
If m = 0 Then
ackermann = n + 1
Else
If n = 0 Then
ackermann = ackermann(m - 1, 1)
Else
ackermann = ackermann(m - 1, ackermann(m, n - 1))
End If
End If
End Function 'ackermann |
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
| #Harbour | Harbour | PROCEDURE Main()
LOCAL cStr
FOR EACH cStr IN { "A", "BARK", "BooK", "TrEaT", "comMON", "sQuAd", "Confuse" }
? PadL( cStr, 10 ), iif( Blockable( cStr ), "can", "cannot" ), "be spelled with blocks."
NEXT
RETURN
STATIC FUNCTION Blockable( cStr )
LOCAL blocks := { ;
"BO", "XK", "DQ", "CP", "NA", "GT", "RE", "TG", "QD", "FS", ;
"JW", "HU", "VI", "AN", "OB", "ER", "FS", "LY", "PC", "ZM" }
LOCAL cFinal := ""
LOCAL i, j
cStr := Upper( cStr )
FOR i := 1 TO Len( cStr )
FOR EACH j IN blocks
IF SubStr( cStr, i, 1 ) $ j
cFinal += SubStr( cStr, i, 1 )
j := ""
EXIT
ENDIF
NEXT
NEXT
RETURN cFinal == cStr |
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.
| #FOCAL | FOCAL | 01.10 T %5.02," RANDOM";S CU=0
01.20 F Z=1,2000;D 5;S CU=CU+SU
01.30 T CU/20,!,"OPTIMAL";S CU=0
01.40 F Z=1,2000;D 6;S CU=CU+SU
01.50 T CU/20,!
01.60 Q
02.01 C-- PUT CARDS IN RANDOM DRAWERS
02.10 F X=1,100;S D(X)=X
02.20 F X=1,99;D 2.3;S B=D(X);S D(X)=D(A);S D(A)=B
02.30 D 2.4;S A=X+FITR(A*(101-X))
02.40 S A=FABS(FRAN()*10);S A=A-FITR(A)
03.01 C-- PRISONER X TRIES UP TO 50 RANDOM DRAWERS
03.10 S TR=50;S SU=0
03.20 D 2.4;I (X-D(A))3.3,3.4,3.3
03.30 S TR=TR-1;I (TR),3.5,3.2
03.40 S SU=1;R
03.50 S SU=0
04.01 C-- PRISONER X TRIES OPTIMAL METHOD
04.10 S TR=50;S SU=0;S A=X
04.20 I (X-D(A))4.3,4.4,4.3
04.30 S TR=TR-1;S A=D(A);I (TR),4.5,4.2
04.40 S SU=1;R
04.50 S SU=0
05.01 C-- PRISONERS TRY RANDOM METHOD UNTIL ONE FAILS
05.10 D 2;S X=1
05.20 I (X-101)5.3,5.4
05.30 D 3;S X=X+1;I (SU),5.4,5.2
05.40 R
06.01 C-- PRISONERS TRY OPTIMAL METHOD UNTIL ONE FAILS
06.10 D 2;S X=1
06.20 I (X-101)6.3,6.4
06.30 D 4;S X=X+1;I (SU),6.4,6.2
06.40 R |
http://rosettacode.org/wiki/21_game | 21 game | 21 game
You are encouraged to solve this task according to the task description, using any language you may know.
21 is a two player game, the game is played by choosing
a number (1, 2, or 3) to be added to the running total.
The game is won by the player whose chosen number causes the running total
to reach exactly 21.
The running total starts at zero.
One player will be the computer.
Players alternate supplying a number to be added to the running total.
Task
Write a computer program that will:
do the prompting (or provide a button menu),
check for errors and display appropriate error messages,
do the additions (add a chosen number to the running total),
display the running total,
provide a mechanism for the player to quit/exit/halt/stop/close the program,
issue a notification when there is a winner, and
determine who goes first (maybe a random or user choice, or can be specified when the game begins).
| #Ruby | Ruby |
# 21 Game - an example in Ruby for Rosetta Code.
GOAL = 21
MIN_MOVE = 1
MAX_MOVE = 3
DESCRIPTION = "
*** Welcome to the 21 Game! ***
21 is a two player game.
Each player chooses to add 1, 2 or 3 to a running total.
The player whose turn it is when the total reaches 21 will win the game.
The running total starts at zero.
The players start the game in turn.
Enter q to quit at any time.
"
#
# Returns the best move to play.
#
def best_move(total)
move = rand(1..3)
MIN_MOVE.upto(MAX_MOVE) do |i|
move = i if (total + i - 1) % (MAX_MOVE + 1) == 0
end
MIN_MOVE.upto(MAX_MOVE) do |i|
move = i if total + i == GOAL
end
move
end
#
# Gets the move of the player.
#
def get_move
print "Your choice between #{MIN_MOVE} and #{MAX_MOVE}: "
answer = gets
move = answer.to_i
until move.between?(MIN_MOVE, MAX_MOVE)
exit if answer.chomp == 'q'
print 'Invalid choice. Try again: '
answer = gets
move = answer.to_i
end
move
end
#
# Asks the player to restart a game and returns the answer.
#
def restart?
print 'Do you want to restart (y/n)? '
restart = gets.chomp
until ['y', 'n'].include?(restart)
print 'Your answer is not a valid choice. Try again: '
restart = gets.chomp
end
restart == 'y'
end
#
# Run a game. The +player+ argument is the player that starts:
# * 1 for human
# * 0 for computer
#
def game(player)
total = round = 0
while total < GOAL
round += 1
puts "--- ROUND #{round} ---\n\n"
player = (player + 1) % 2
if player == 0
move = best_move(total)
puts "The computer chooses #{move}."
else
move = get_move
end
total += move
puts "Running total is now #{total}.\n\n"
end
if player == 0
puts 'Sorry, the computer has won!'
return false
end
puts 'Well done, you have won!'
true
end
# MAIN
puts DESCRIPTION
run = true
computer_wins = human_wins = 0
games_counter = player = 1
while run
puts "\n=== START GAME #{games_counter} ==="
player = (player + 1) % 2
if game(player)
human_wins += 1
else
computer_wins += 1
end
puts "\nComputer wins #{computer_wins} games, you wins #{human_wins} game."
games_counter += 1
run = restart?
end
puts 'Good bye!'
|
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
| #JavaScript | JavaScript | var ar=[],order=[0,1,2],op=[],val=[];
var NOVAL=9999,oper="+-*/",out;
function rnd(n){return Math.floor(Math.random()*n)}
function say(s){
try{document.write(s+"<br>")}
catch(e){WScript.Echo(s)}
}
function getvalue(x,dir){
var r=NOVAL;
if(dir>0)++x;
while(1){
if(val[x]!=NOVAL){
r=val[x];
val[x]=NOVAL;
break;
}
x+=dir;
}
return r*1;
}
function calc(){
var c=0,l,r,x;
val=ar.join('/').split('/');
while(c<3){
x=order[c];
l=getvalue(x,-1);
r=getvalue(x,1);
switch(op[x]){
case 0:val[x]=l+r;break;
case 1:val[x]=l-r;break;
case 2:val[x]=l*r;break;
case 3:
if(!r||l%r)return 0;
val[x]=l/r;
}
++c;
}
return getvalue(-1,1);
}
function shuffle(s,n){
var x=n,p=eval(s),r,t;
while(x--){
r=rnd(n);
t=p[x];
p[x]=p[r];
p[r]=t;
}
}
function parenth(n){
while(n>0)--n,out+='(';
while(n<0)++n,out+=')';
}
function getpriority(x){
for(var z=3;z--;)if(order[z]==x)return 3-z;
return 0;
}
function showsolution(){
var x=0,p=0,lp=0,v=0;
while(x<4){
if(x<3){
lp=p;
p=getpriority(x);
v=p-lp;
if(v>0)parenth(v);
}
out+=ar[x];
if(x<3){
if(v<0)parenth(v);
out+=oper.charAt(op[x]);
}
++x;
}
parenth(-p);
say(out);
}
function solve24(s){
var z=4,r;
while(z--)ar[z]=s.charCodeAt(z)-48;
out="";
for(z=100000;z--;){
r=rnd(256);
op[0]=r&3;
op[1]=(r>>2)&3;
op[2]=(r>>4)&3;
shuffle("ar",4);
shuffle("order",3);
if(calc()!=24)continue;
showsolution();
break;
}
}
solve24("1234");
solve24("6789");
solve24("1127"); |
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
| #BASIC | BASIC | 10 REM 15-PUZZLE GAME
20 REM COMMODORE BASIC 2.0
30 REM ********************************
40 GOSUB 400 : REM INTRO AND LEVEL
50 GOSUB 510 : REM SETUP BOARD
60 GOSUB 210 : REM PRINT PUZZLE
70 PRINT "TO MOVE A PIECE, ENTER ITS NUMBER:"
80 INPUT X
90 GOSUB 760 : REM CHECK IF MOVE IS VALID
100 IF MV=0 THEN PRINT "WRONG MOVE" : GOSUB 1130 : GOTO 60
110 D(Z)=X : D(Y)=0
120 GOSUB 210 : REM PRINT PUZZLE
130 GOSUB 1030: REM CHECK IF PUZZLE COMPLETE
140 IF PC THEN 160
150 GOTO 70
160 PRINT"YOU WON!"
170 END
180 REM
190 REM *******************************
200 REM PRINT/DRAW THE PUZZLE
210 FOR P=1 TO 16
220 IF D(P)=0 THEN D$(P)=" " : GOTO 260
230 S$=STR$(D(P))
240 N=LEN(S$)
250 D$(P) = LEFT$(" ",3-N)+S$+" "
260 NEXT
270 PRINT "+-----+-----+-----+-----+"
280 PRINT "!"D$(1)"!"D$(2)"!"D$(3)"!"D$(4)"!"
290 PRINT "+-----+-----+-----+-----+"
300 PRINT "!"D$(5)"!"D$(6)"!"D$(7)"!"D$(8)"!"
310 PRINT "+-----+-----+-----+-----+"
320 PRINT "!"D$(9)"!"D$(10)"!"D$(11)"!"D$(12)"!"
330 PRINT "+-----+-----+-----+-----+"
340 PRINT "!"D$(13)"!"D$(14)"!"D$(15)"!"D$(16)"!"
350 PRINT "+-----+-----+-----+-----+"
360 RETURN
370 REM
380 REM *******************************
390 REM INTRO AND LEVEL OF DIFFICULTY
400 PRINT CHR$(147)
410 DIM SH(3) : SH(1)=10 : SH(2)=50 : SH(3)=100
420 PRINT "15 PUZZLE GAME FOR COMMODORE BASIC 2.0" : PRINT : PRINT
430 PRINT "PLEASE ENTER LEVEL OF DIFFICULTY,"
440 PRINT "1(EASY), 2(MEDIUM) OR 3(HARD):";
450 INPUT V
460 IF V<1 OR V>3 THEN 440
470 RETURN
480 REM
490 REM *******************************
500 REM BUILD THE BOARD
510 DIM D(16) : DIM D$(16) : REM BOARD PIECES
520 REM SET PIECES IN CORRECT ORDER FIRST
530 FOR P=1 TO 15
540 D(P) = P
550 NEXT
560 D(16) = 0 : REM 0 = EMPTY PIECE/SLOT
570 Z=16 : REM Z = EMPTY POSITION
580 PRINT: PRINT "SHUFFLING PIECES";
590 FOR N=1 TO SH(V)
600 PRINT".";
610 X = INT(RND(0)*4)+1
620 IF X=1 THEN R=Z-4
630 IF X=2 THEN R=Z+4
640 IF (X=3) AND (INT((Z-1)/4)<>(Z-1)/4) THEN R=Z-1
650 IF (X=4) AND (INT(Z/4)<>Z/4) THEN R=Z+1
660 IF R<1 OR R>16 THEN 610
670 D(Z)=D(R)
680 Z=R
690 D(Z)=0
700 NEXT
710 PRINT CHR$(147)
720 RETURN
730 REM
740 REM *******************************
750 REM CHECK IF MOVE IS VALID
760 MV = 0
770 IF X<1 OR X>15 THEN RETURN
780 REM FIND POSITION OF PIECE X AND OF EMPTY PIECE
790 AX=X
800 GOSUB 940 : REM FIND POSITION OF PIECE AX
810 Y=P
820 AX=0
830 GOSUB 940 : REM FIND POSITION OF PIECE AX
840 Z=P
850 REM CHECK IF EMPTY PIECE IS ABOVE, BELOW, LEFT OR RIGHT TO PIECE X
860 IF Y-4=Z THEN MV=1 : RETURN
870 IF Y+4=Z THEN MV=1 : RETURN
880 IF (Y-1=Z) AND (INT(Z/4)<>Z/4) THEN MV=1 : RETURN
890 IF (Y+1=Z) AND (INT(Y/4)<>Y/4) THEN MV=1 : RETURN
900 RETURN
910 REM
920 REM *******************************
930 REM FIND POSITION OF PIECE AX
940 P=1
950 IF D(P)=AX THEN 990
960 P=P+1
970 IF P>16 THEN PRINT "UH OH!" : STOP
980 GOTO 950
990 RETURN
1000 REM
1010 REM *******************************
1020 REM CHECK IF PUZZLE IS COMPLETE / GAME OVER
1030 PC = 0
1040 P=1
1050 IF (P>=16) OR (D(P)<>P) THEN 1080
1060 P=P+1
1070 GOTO 1050
1080 IF P=16 THEN PC=1
1090 RETURN
1100 REM
1110 REM ******************************
1120 REM A SMALL DELAY
1130 FOR T=0 TO 400
1140 NEXT
1150 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.
| #Common_Lisp | Common Lisp | (ql:quickload '(cffi alexandria))
(defpackage :2048-lisp
(:use :common-lisp :cffi :alexandria))
(in-package :2048-lisp)
(defvar *lib-loaded* nil)
(unless *lib-loaded*
;; Load msvcrt.dll to access _getch.
(define-foreign-library msvcrt
(:windows (:default "msvcrt")))
(use-foreign-library msvcrt)
(defcfun "_getch" :int)
(setf *lib-loaded* t))
(defun read-arrow ()
"Get an arrow key from input as UP, DOWN, LEFT, or RIGHT, otherwise
return a char of whatever was pressed."
(let ((first-char (-getch)))
(if (= 224 first-char)
(case (-getch)
(75 'left)
(80 'down)
(77 'right)
(72 'up))
(code-char first-char))))
(defmacro swap (place1 place2)
"Exchange the values of two places."
(let ((temp (gensym "TEMP")))
`(cl:let ((,temp ,place1))
(cl:setf ,place1 ,place2)
(cl:setf ,place2 ,temp))))
(defun nflip (board &optional (left-right t))
"Flip the elements of a BOARD left and right or optionally up and down."
(let* ((y-len (array-dimension board 0))
(x-len (array-dimension board 1))
(y-max (if left-right y-len (truncate y-len 2)))
(x-max (if left-right (truncate x-len 2) x-len)))
(loop for y from 0 below y-max
for y-place = (- y-len 1 y) do
(loop for x from 0 below x-max
for x-place = (- x-len 1 x) do
(if left-right
(swap (aref board y x) (aref board y x-place))
(swap (aref board y x) (aref board y-place x)))))
board))
(defun flip (board &optional (left-right t))
"Flip the elements of a BOARD left and right or optionally up and down.
Non-destructive version."
(nflip (copy-array board) left-right))
(defun transpose (board)
"Transpose the elements of BOARD into a new array."
(let* ((y-len (array-dimension board 0))
(x-len (array-dimension board 1))
(new-board (make-array (reverse (array-dimensions board)))))
(loop for y from 0 below y-len do
(loop for x from 0 below x-len do
(setf (aref new-board x y) (aref board y x))))
new-board))
(defun add-random-piece (board)
"Find a random empty spot on the BOARD to add a new piece.
Return T if successful, NIL otherwise."
(loop
for x from 0 below (array-total-size board)
unless (row-major-aref board x)
count 1 into count
and collect x into indices
finally
(unless (= 0 count)
(setf (row-major-aref board (nth (random count) indices))
(if (= 0 (random 10)) 4 2))
(return t))))
(defun squash-line (line)
"Reduce a sequence of numbers from left to right according to
the rules of 2048. Return the score of squashing as well."
(let* ((squashed
(reduce
(lambda (acc x)
(if (equal x (car acc))
(cons (list (* 2 x)) (cdr acc))
(cons x acc)))
(nreverse (remove-if #'null line))
:initial-value nil))
(new-line (flatten squashed)))
(list (append (make-list (- (length line) (length new-line))) new-line)
(reduce #'+ (flatten (remove-if-not #'listp squashed))))))
(defun squash-board (board)
"Reduce each row of a board from left to right according to
the rules of 2048. Return the total score of squashing the board as well."
(let ((y-len (array-dimension board 0))
(x-len (array-dimension board 1))
(total 0))
(list (make-array (array-dimensions board) :initial-contents
(loop for y from 0 below y-len
for (line score) =
(squash-line
(make-array x-len
:displaced-to board
:displaced-index-offset
(array-row-major-index board y 0)))
collect line
do (incf total score)))
total)))
(defun make-move (board direction)
"Make a move in the given DIRECTION on a new board."
;; Move by always squashing right, but transforming the board as needed.
(destructuring-bind (new-board score)
(case direction
(up (squash-board (flip (transpose board))))
(down (squash-board (flip (transpose board) nil)))
(left (squash-board (nflip (flip board nil))))
(right (squash-board board)))
(let ((new-board
;; Reverse the transformation.
(case direction
(up (transpose (nflip new-board)))
(down (transpose (nflip new-board nil)))
(left (nflip (nflip new-board nil)))
(right new-board))))
(unless (equalp board new-board)
(add-random-piece new-board)
(list new-board score)))))
(defun winp (board winning-tile)
"Determine if a BOARD is in a winning state."
(loop for x from 0 below (array-total-size board)
for val = (row-major-aref board x)
when (eql val winning-tile) do (return t)))
(defun game-overp (board)
"Determine if a BOARD is in a game over state."
;; If a move is simulated in every direction and nothing changes,
;; then we can assume there are no valid moves left.
(notany (lambda (dir) (car (make-move board dir)))
'(up down left right)))
(defun print-divider (cells cell-size)
"A print helper function for PRINT-BOARD."
(dotimes (_ cells)
(princ "+")
(dotimes (_ cell-size)
(princ "-")))
(princ "+")
(terpri))
(defun print-board (board cell-size)
"Pretty print the given BOARD with a particular CELL-SIZE."
(let* ((y-len (array-dimension board 0))
(x-len (array-dimension board 1))
(super-size (+ 2 cell-size)))
(loop for y from 0 below y-len do
(print-divider x-len super-size)
(loop for x from 0 below x-len
for val = (aref board y x)
do
(princ "|")
(if val
(format t " ~VD " cell-size val)
(dotimes (_ super-size) (princ " "))))
(princ "|")
(terpri))
(print-divider x-len super-size)))
(defun init-board ()
(let ((board (make-array '(4 4) :initial-element nil)))
(setf (row-major-aref board (random (array-total-size board))) 2)
board))
(defun prompt-input (board score &optional (check t))
(cond
((and check (winp board 2048)) (format t "You win!"))
((and check (game-overp board)) (format t "Game over..."))
(t (let ((choice (read-arrow)))
(cond
((symbolp choice)
(destructuring-bind (&optional move (new-score 0))
(make-move board choice)
(if move
(prompt move (+ score new-score))
(prompt-input board score))))
((find choice "qQ")
(format t "Quitting."))
(t (prompt-input board score nil)))))))
(defun prompt (&optional (board (init-board)) (score 0))
(format t "~% Score: ~D~%" score)
(print-board board 4)
(prompt-input board score)) |
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
| #Scheme | Scheme |
(import (scheme base)
(scheme write)
(srfi 1))
;; return all combinations of size elements from given set
(define (combinations size set unique?)
(if (zero? size)
(list '())
(let loop ((base-combns (combinations (- size 1) set unique?))
(results '())
(items set))
(cond ((null? base-combns) ; end, as no base-combinations to process
results)
((null? items) ; check next base-combination
(loop (cdr base-combns)
results
set))
((and unique? ; ignore if wanting list unique
(member (car items) (car base-combns) =))
(loop base-combns
results
(cdr items)))
(else ; keep the new combination
(loop base-combns
(cons (cons (car items) (car base-combns))
results)
(cdr items)))))))
;; checks if all 4 sums are the same
(define (solution? a b c d e f g)
(= (+ a b)
(+ b c d)
(+ d e f)
(+ f g)))
;; Tasks
(display "Solutions: LOW=1 HIGH=7\n")
(display (filter (lambda (combination) (apply solution? combination))
(combinations 7 (iota 7 1) #t))) (newline)
(display "Solutions: LOW=3 HIGH=9\n")
(display (filter (lambda (combination) (apply solution? combination))
(combinations 7 (iota 7 3) #t))) (newline)
(display "Solution count: LOW=0 HIGH=9 non-unique\n")
(display (count (lambda (combination) (apply solution? combination))
(combinations 7 (iota 10 0) #f))) (newline)
|
http://rosettacode.org/wiki/15_puzzle_solver | 15 puzzle solver | Your task is to write a program that finds a solution in the fewest moves possible single moves to a random Fifteen Puzzle Game.
For this task you will be using the following puzzle:
15 14 1 6
9 11 4 12
0 10 7 3
13 8 5 2
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 0
The output must show the moves' directions, like so: left, left, left, down, right... and so on.
There are two solutions, of fifty-two moves:
rrrulddluuuldrurdddrullulurrrddldluurddlulurruldrdrd
rrruldluuldrurdddluulurrrdlddruldluurddlulurruldrrdd
see: Pretty Print of Optimal Solution
Finding either one, or both is an acceptable result.
Extra credit.
Solve the following problem:
0 12 9 13
15 11 10 14
3 7 2 5
4 8 6 1
Related Task
15 puzzle game
A* search algorithm
| #Picat | Picat | import planner.
main =>
init(InitS),
goal(GoalS),
best_plan((InitS,GoalS),Plan),
println(Plan).
init(InitS) =>
M = {{15, 14, 1, 6},
{9 , 11, 4, 12},
{0, 10, 7, 3},
{13, 8, 5, 2}},
InitS = [(R,C) : T in 0..15, pos(M,T,R,C)].
goal(GoalS) =>
M = {{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13,14, 15, 0}},
GoalS = [(R,C) : T in 0..15, pos(M,T,R,C)].
pos(M,T,R,C) =>
N = len(M),
between(1,N,R),
between(1,N,C),
M[R,C] == T,!.
final((S,GoalS)) => S == GoalS.
action((S,GoalS),NextS,Action,Cost) =>
S = [P0|Tiles],
P0 = (R0,C0),
Cost = 1,
(R1 = R0-1, R1 >= 1, C1 = C0, Action = u;
R1 = R0+1, R1 =< 4, C1 = C0, Action = d;
R1 = R0, C1 = C0-1, C1 >= 1, Action = l;
R1 = R0, C1 = C0+1, C1 =< 4, Action = r),
P1 = (R1,C1),
slide(P0,P1,Tiles,Tiles1),
S1 = [P1|Tiles1],
NextS = (S1,GoalS).
% slide the tile at P1 to the empty square at P0
slide(P0,P1,[P1|Tiles],Tiles1) =>
Tiles1 = [P0|Tiles].
slide(P0,P1,[Tile|Tiles],Tiles1) =>
Tiles1=[Tile|Tiles1R],
slide(P0,P1,Tiles,Tiles1R).
% called by the planner
heuristic((S,GoalS)) = Dist =>
S = [_|Tiles],
GoalS = [_|FTiles],
Dist = sum([abs(R-FR)+abs(C-FC) :
{(R,C),(FR,FC)} in zip(Tiles,FTiles)]).
|
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
| #ArnoldC | ArnoldC | IT'S SHOWTIME
HEY CHRISTMAS TREE is0
YOU SET US UP @NO PROBLEMO
HEY CHRISTMAS TREE bottles
YOU SET US UP 99
STICK AROUND is0
TALK TO THE HAND bottles
TALK TO THE HAND " bottles of beer on the wall"
TALK TO THE HAND bottles
TALK TO THE HAND " bottles of beer"
TALK TO THE HAND "Take one down, pass it around"
GET TO THE CHOPPER bottles
HERE IS MY INVITATION bottles
GET DOWN 1
ENOUGH TALK
TALK TO THE HAND bottles
TALK TO THE HAND " bottles of beer on the wall"
GET TO THE CHOPPER is0
HERE IS MY INVITATION bottles
LET OFF SOME STEAM BENNET 0
ENOUGH TALK
CHILL
YOU HAVE BEEN TERMINATED |
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.
| #FreeBASIC | FreeBASIC |
' The 24 game en FreeBASIC
Const operaciones = "*/+-"
Declare Sub Encabezado
Declare Function escoge4() As String
Declare Function quitaEspacios(cadena As String, subcadena1 As String, subcadena2 As String) As String
Declare Function evaluaEntrada(cadena As String) As Integer
Declare Function evaluador(oper1 As Byte, oper2 As Byte, operacion As String) As Integer
Dim Shared As String serie, entrada, cadena
Dim As Integer resultado
Sub Encabezado
Cls: Color 15
Print "The 24 Game"
Print "============" + Chr(13) + Chr(10)
Print "Dados cuatro dígitos en el rango de 1 a 9, que pueden repetirse, "
Print "usando solo los operadores aritméticos suma (+), resta (-), "
Print "multiplicación (*) y división (/) intentar obtener un resultado de 24." + Chr(13) + Chr(10)
Print "Use la notación polaca inversa (primero los operandos y luego los operadores)."
Print "Por ejemplo: en lugar de 2 + 4, escriba 2 4 +" + Chr(13) + Chr(10)
End Sub
Function escoge4() As String
Dim As Byte i
Dim As String a, b
Print "Los dígitos a utilizar son: ";
For i = 1 To 4
a = Str(Int(Rnd*9)+1)
Print a;" ";
b = b + a
Next i
escoge4 = b
End Function
Function evaluaEntrada(cadena As String) As Integer
Dim As Byte oper1, oper2, n(4), i
Dim As String op
oper1 = 0: oper2 = 0: i = 0
While cadena <> ""
op = Left(cadena, 1)
entrada = Mid(cadena, 2)
If Instr(serie, op) Then
i = i + 1
n(i) = Val(op)
Elseif Instr(operaciones, op) Then
oper2 = n(i)
n(i) = 0
i = i - 1
oper1 = n(i)
n(i) = evaluador(oper1, oper2, op)
Else
Print "Signo no v lido"
End If
Wend
evaluaEntrada = n(i)
End Function
Function evaluador(oper1 As Byte, oper2 As Byte, operacion As String) As Integer
Dim As Integer t
Select Case operacion
Case "+": t = oper1 + oper2
Case "-": t = oper1 - oper2
Case "*": t = oper1 * oper2
Case "/": t = oper1 / oper2
End Select
evaluador = t
End Function
Function quitaEspacios(cadena As String, subcadena1 As String, subcadena2 As String) As String
Dim As Byte len1 = Len(subcadena1), len2 = Len(subcadena2)
Dim As Byte i
i = Instr(cadena, subcadena1)
While i
cadena = Left(cadena, i - 1) & subcadena2 & Mid(cadena, i + len1)
i = Instr(i + len2, cadena, subcadena1)
Wend
quitaEspacios = cadena
End Function
'--- Programa Principal ---
Randomize Timer
Do
Encabezado
serie = escoge4
Print: Line Input "Introduzca su fórmula en notación polaca inversa: ", entrada
entrada = quitaEspacios(entrada, " ", "")
If (Len(entrada) <> 7) Then
Print "Error en la serie introducida."
Else
resultado = evaluaEntrada(entrada)
Print "El resultado es = "; resultado
If resultado = 24 Then
Print "¡Correcto!"
Else
Print "¡Error!"
End If
End If
Print "¿Otra ronda? (Pulsa S para salir, u otra tecla para continuar)"
Loop Until (Ucase(Input(1)) = "S")
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
| #D | D | import std.stdio, std.conv, std.string;
void main() {
string[] r;
try
r = readln().split();
catch (StdioException e)
r = ["10", "20"];
writeln(to!int(r[0]) + to!int(r[1]));
} |
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.
| #Vlang | Vlang | fn ackermann(m int, n int ) int {
if m == 0 {
return n + 1
}
else if n == 0 {
return ackermann(m - 1, 1)
}
return ackermann(m - 1, ackermann(m, n - 1) )
}
fn main() {
for m := 0; m <= 4; m++ {
for n := 0; n < ( 6 - m ); n++ {
println('Ackermann($m, $n) = ${ackermann(m, 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
| #Haskell | Haskell | import Data.List (delete)
import Data.Char (toUpper)
-- returns list of all solutions, each solution being a list of blocks
abc :: (Eq a) => [[a]] -> [a] -> [[[a]]]
abc _ [] = [[]]
abc blocks (c:cs) = [b:ans | b <- blocks, c `elem` b,
ans <- abc (delete b blocks) cs]
blocks = ["BO", "XK", "DQ", "CP", "NA", "GT", "RE", "TG", "QD", "FS",
"JW", "HU", "VI", "AN", "OB", "ER", "FS", "LY", "PC", "ZM"]
main :: IO ()
main = mapM_ (\w -> print (w, not . null $ abc blocks (map toUpper w)))
["", "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.
| #Forth | Forth | INCLUDE ran4.seq
100 CONSTANT #drawers
#drawers CONSTANT #players
100000 CONSTANT #tries
CREATE drawers #drawers CELLS ALLOT \ index 0..#drawers-1
: drawer[] ( n -- addr ) \ return address of drawer n
CELLS drawers +
;
: random_drawer ( -- n ) \ n=0..#drawers-1 random drawer
RAN4 ( d ) XOR ( n ) #drawers MOD
;
: random_drawer[] ( -- addr ) \ return address of random drawer
random_drawer drawer[]
;
: swap_indirect ( addr1 addr2 -- ) \ swaps the values at the two addresses
2DUP @ SWAP @ ( addr1 addr2 n2 n1 )
ROT ! SWAP ! \ store n1 at addr2 and n2 at addr1
;
: init_drawers ( -- ) \ shuffle cards into drawers
#drawers 0 DO
I I drawer[] ! \ store cards in order
LOOP
#drawers 0 DO
I drawer[] random_drawer[] ( addr-drawer-i addr-drawer-rnd )
swap_indirect
LOOP
;
: random_turn ( player - f )
#drawers 2 / 0 DO
random_drawer
drawer[] @
OVER = IF
DROP TRUE UNLOOP EXIT \ found his number
THEN
LOOP
DROP FALSE
;
0 VALUE player
: cycle_turn ( player - f )
DUP TO player ( next-drawer )
#drawers 2 / 0 DO
drawer[] @
DUP player = IF
DROP TRUE UNLOOP EXIT \ found his number
THEN
LOOP
DROP FALSE
;
: turn ( strategy player - f )
SWAP 0= IF \ random play
random_turn
ELSE
cycle_turn
THEN
;
: play ( strategy -- f ) \ return true if prisioners survived
init_drawers
#players 0 DO
DUP I turn
0= IF
DROP FALSE UNLOOP EXIT \ this player did not survive, UNLOOP, return false
THEN
LOOP
DROP TRUE \ all survived, return true
;
: trie ( strategy - nr-saved )
0 ( strategy nr-saved )
#tries 0 DO
OVER play IF 1+ THEN
LOOP
NIP
;
0 trie . CR \ random strategy
1 trie . CR \ follow the card number strategy |
http://rosettacode.org/wiki/21_game | 21 game | 21 game
You are encouraged to solve this task according to the task description, using any language you may know.
21 is a two player game, the game is played by choosing
a number (1, 2, or 3) to be added to the running total.
The game is won by the player whose chosen number causes the running total
to reach exactly 21.
The running total starts at zero.
One player will be the computer.
Players alternate supplying a number to be added to the running total.
Task
Write a computer program that will:
do the prompting (or provide a button menu),
check for errors and display appropriate error messages,
do the additions (add a chosen number to the running total),
display the running total,
provide a mechanism for the player to quit/exit/halt/stop/close the program,
issue a notification when there is a winner, and
determine who goes first (maybe a random or user choice, or can be specified when the game begins).
| #rust | rust | use rand::Rng;
use std::io;
#[derive(Clone)]
enum PlayerType {
Human,
Computer,
}
#[derive(Clone)]
struct Player {
name: String,
wins: u32, // holds wins
level: u32, // difficulty level of Computer
player_type: PlayerType,
}
trait Choose {
fn choose(&self, game: &Game) -> u8;
}
impl Player {
fn new(name: &str, player_type: PlayerType, level: u32) -> Player {
Player {
name: String::from(name),
wins: 0,
level,
player_type,
}
}
fn get_name(&self) -> &str {
&self.name[..]
}
fn get_level(&self) -> u32 {
self.level
}
fn add_win(&mut self) {
self.wins += 1
}
fn level_up(&mut self) {
self.level += 1
}
}
impl Choose for Player {
fn choose(&self, game: &Game) -> u8 {
match self.player_type {
PlayerType::Human => loop {
let max_choice = game.max_choice();
match max_choice {
1 => println!("Enter a number 1 to win (or quit):"),
_ => println!("Enter a number between 1 and {} (or quit):", max_choice)
}
let mut guess = String::new();
io::stdin()
.read_line(&mut guess)
.expect("Failed to read line");
if guess.trim() == "quit" {
return 0
}
let guess: u8 = match guess.trim().parse() {
Ok(num) if num >= 1 && num <= max_choice => num,
Ok(_) => continue,
Err(_) => continue,
};
return guess;
},
PlayerType::Computer => match self.level {
5 => match game.get_total() {
total if total == 20 => 1,
total if total == 19 => 2,
total if total == 18 => 3,
_ => 1,
},
4 => match game.get_total() {
total if total == 20 => 1,
total if total == 19 => 2,
total if total == 18 => 3,
_ => rand::thread_rng().gen_range(1, 3),
},
3 => match game.get_total() {
total if total == 20 => 1,
total if total == 19 => 2,
total if total == 18 => 3,
_ => rand::thread_rng().gen_range(1, 4),
},
2 => match game.get_total() {
total if total == 20 => 1,
total if total == 19 => 2,
_ => rand::thread_rng().gen_range(1, 3),
},
1 => 1,
_ => match game.get_total() {
total if total == 20 => 1,
total if total == 19 => 2,
total if total == 18 => 3,
_ => match game.get_remaining() % 4 {
0 => rand::thread_rng().gen_range(1, 4),
_ => game.get_remaining() % 4,
},
},
},
}
}
}
struct Game {
players: Vec<Player>,
turn: u8,
total: u8,
start: u8, // determines which player goes first
}
impl Game {
fn init(players: &Vec<Player>) -> Game {
Game {
players: players.to_vec(),
turn: 1,
total: 0,
start: rand::thread_rng().gen_range(0, 2),
}
}
fn play(&mut self) -> &Player {
loop {
println!(
"Total now {} (remaining: {})",
self.get_total(),
self.get_remaining()
);
{
let player = self.whose_turn();
println!("Turn: {} ({} turn)", self.get_turn(), player.get_name());
let choice = player.choose(&self);
if choice == 0 {
self.next_turn();
break; // quit
}
println!("{} choose {}", player.get_name(), choice);
self.add_total(choice)
}
if self.get_total() >= 21 {
break;
}
println!("");
self.next_turn();
}
self.whose_turn()
}
fn add_total(&mut self, choice: u8) {
self.total += choice;
}
fn next_turn(&mut self) {
self.turn += 1;
}
fn whose_turn(&self) -> &Player {
let index: usize = ((self.turn + self.start) % 2).into();
&self.players[index]
}
fn get_total(&self) -> u8 {
self.total
}
fn get_remaining(&self) -> u8 {
21 - self.total
}
fn max_choice(&self) -> u8 {
match self.get_remaining() {
1 => 1,
2 => 2,
_ => 3
}
}
fn get_turn(&self) -> u8 {
self.turn
}
}
fn main() {
let mut game_count = 0;
let mut players = vec![
Player::new("human", PlayerType::Human, 0),
Player::new("computer", PlayerType::Computer, 1),
];
println!("21 Game");
println!("Press enter key to start");
{
let _ = io::stdin().read_line(&mut String::new());
}
loop {
game_count += 1;
let mut game = Game::init(&players);
let winner = game.play();
{
let mut index = 0;
while index < players.len() {
if players[index].get_name() == winner.get_name() {
players[index].add_win();
}
index += 1
}
}
println!("\n{} won game {}\n", winner.get_name(), game_count);
// limit game count
if game_count >= 10000 {
break;
}
// ask player if they want to keep on playing
println!("Press enter key to play again (or quit):");
let mut reply = String::new();
io::stdin()
.read_line(&mut reply)
.expect("Failed to read line");
if reply.trim() == "quit" {
break;
}
// level up computer
if winner.get_name() != "computer" {
println!("Computer leveling up ...");
players[1].level_up();
println!("Computer now level {}!", players[1].get_level());
println!("Beware!\n");
}
}
println!("player: {} win: {}", players[0].get_name(), players[0].wins);
println!("player: {} win: {}", players[1].get_name(), players[1].wins);
}
|
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
| #jq | jq | # Generate a stream of the permutations of the input array.
def permutations:
if length == 0 then []
else range(0;length) as $i
| [.[$i]] + (del(.[$i])|permutations)
end ;
# Generate a stream of arrays of length n,
# with members drawn from the input array.
def take(n):
length as $l |
if n == 1 then range(0;$l) as $i | [ .[$i] ]
else take(n-1) + take(1)
end;
# Emit an array with elements that alternate between those in the input array and those in short,
# starting with the former, and using nothing if "short" is too too short.
def intersperse(short):
. as $in
| reduce range(0;length) as $i
([]; . + [ $in[$i], (short[$i] // empty) ]);
# Emit a stream of all the nested triplet groupings of the input array elements,
# e.g. [1,2,3,4,5] =>
# [1,2,[3,4,5]]
# [[1,2,3],4,5]
#
def triples:
. as $in
| if length == 3 then .
elif length == 1 then $in[0]
elif length < 3 then empty
else
(range(0; (length-1) / 2) * 2 + 1) as $i
| ($in[0:$i] | triples) as $head
| ($in[$i+1:] | triples) as $tail
| [$head, $in[$i], $tail]
end; |
http://rosettacode.org/wiki/15_puzzle_game | 15 puzzle game |
Task
Implement the Fifteen Puzzle Game.
The 15-puzzle is also known as:
Fifteen Puzzle
Gem Puzzle
Boss Puzzle
Game of Fifteen
Mystic Square
14-15 Puzzle
and some others.
Related Tasks
15 Puzzle Solver
16 Puzzle Game
| #BBC_BASIC | BBC BASIC | IF INKEY(-256)=77 OR (INKEY(-256) AND &F0)=&A0 THEN MODE 1: COLOUR 0: COLOUR 143: *FX4,1
SIZE=4 : DIFFICULTY=3
MAX=SIZE * SIZE - 1
DIM Board(MAX)
FOR I%=1 TO MAX : Board(I% - 1)=I% : NEXT
Gap=MAX
WHILE N% < DIFFICULTY ^ 2 PROCSlide(RND(4)) : ENDWHILE : REM Shuffle
N%=0
@%=2 + LOG(MAX + 1)
PROCShowAndTest
WHILE NOT Solved
PRINT "Use arrow keys to move the gap around. Moves taken: ";N%
PROCSlide(GET - 135)
PROCShowAndTest
ENDWHILE
PRINT "Solved after ";N% LEFT$(" moves", 6 + (N% = 1)) "."
END
DEF PROCSlide(dir%)
NewGap=Gap
CASE dir% OF
WHEN 1: IF Gap MOD SIZE > 0 NewGap=Gap - 1 : N%+=1 : REM Left
WHEN 2: IF Gap MOD SIZE < SIZE - 1 NewGap=Gap + 1 : N%+=1 : REM Right
WHEN 3: IF Gap < MAX - SIZE + 1 NewGap=Gap + SIZE : N%+=1 : REM Down
WHEN 4: IF Gap > SIZE - 1 NewGap=Gap - SIZE : N%+=1 : REM Up
ENDCASE
SWAP Board(Gap), Board(NewGap)
Gap=NewGap
ENDPROC
DEF PROCShowAndTest
CLS
Solved=TRUE
FOR I%=0 TO MAX
COLOUR 12 : COLOUR 135
IF I% = Gap COLOUR 1 : COLOUR 129
IF I% MOD SIZE = SIZE - 1 PRINT Board(I%) ELSE PRINT Board(I%),;
IF Solved IF I% < MAX - 1 IF Board(I%) > Board(I% + 1) OR I% = Gap Solved=FALSE
NEXT
COLOUR 0 : COLOUR 143
PRINT
ENDPROC |
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.
| #D | D | import std.stdio, std.string, std.random;
import core.stdc.stdlib: exit;
struct G2048 {
public void gameLoop() /*@safe @nogc*/ {
addTile;
while (true) {
if (moved)
addTile;
drawBoard;
if (done)
break;
waitKey;
}
writeln(win ? "You win!" : "Game Over!");
}
private:
static struct Tile {
uint val = 0;
bool blocked = false;
}
enum moveDir { up, down, left, right }
enum uint side = 4;
Tile[side][side] board;
bool win = false, done = false, moved = true;
uint score = 0;
void drawBoard() const /*@safe @nogc*/ {
writeln("SCORE: ", score, "\n");
foreach (immutable y; 0 .. side) {
write("+------+------+------+------+\n| ");
foreach (immutable x; 0 .. side) {
if (board[x][y].val)
writef("%4d", board[x][y].val);
else
writef("%4s", " ");
write(" | ");
}
writeln;
}
"+------+------+------+------+\n".writeln;
}
void waitKey() /*@safe*/ {
moved = false;
"(W)Up (S)Down (A)Left (D)Right (Q)Quit: ".write;
immutable c = readln.strip.toLower;
switch (c) {
case "w": move(moveDir.up); break;
case "a": move(moveDir.left); break;
case "s": move(moveDir.down); break;
case "d": move(moveDir.right); break;
case "q": endGame; break;
default: break;
}
foreach (immutable y; 0 .. side)
foreach (immutable x; 0 .. side)
board[x][y].blocked = false;
}
void endGame() const {
writeln("Game ended with score: ", score);
exit(0);
}
void addTile() /*nothrow*/ @safe /*@nogc*/ {
foreach (immutable y; 0 .. side) {
foreach (immutable x; 0 .. side) {
if (!board[x][y].val) {
uint a, b;
do {
a = uniform(0, side);
b = uniform(0, side);
} while (board[a][b].val);
board[a][b].val = (uniform01 > 0.89) ? side : 2;
if (canMove)
return;
}
}
}
done = true;
}
bool canMove() const pure nothrow @safe @nogc {
foreach (immutable y; 0 .. side)
foreach (immutable x; 0 .. side)
if (!board[x][y].val)
return true;
foreach (immutable y; 0 .. side) {
foreach (immutable x; 0 .. side) {
if (testAdd(x + 1, y, board[x][y].val) ||
testAdd(x - 1, y, board[x][y].val) ||
testAdd(x, y + 1, board[x][y].val) ||
testAdd(x, y - 1, board[x][y].val))
return true;
}
}
return false;
}
bool testAdd(in uint x, in uint y, in uint v) const pure nothrow @safe @nogc {
if (x > 3 || y > 3)
return false;
return board[x][y].val == v;
}
void moveVertically(in uint x, in uint y, in uint d) pure nothrow @safe @nogc {
if (board[x][y + d].val && board[x][y + d].val == board[x][y].val &&
!board[x][y].blocked && !board[x][y + d].blocked) {
board[x][y].val = 0;
board[x][y + d].val *= 2;
score += board[x][y + d].val;
board[x][y + d].blocked = true;
moved = true;
} else if (!board[x][y + d].val && board[x][y].val) {
board[x][y + d].val = board[x][y].val;
board[x][y].val = 0;
moved = true;
}
if (d > 0) {
if (y + d < 3)
moveVertically(x, y + d, 1);
} else {
if (y + d > 0)
moveVertically(x, y + d, -1);
}
}
void moveHorizontally(in uint x, in uint y, in uint d) pure nothrow @safe @nogc {
if (board[x + d][y].val && board[x + d][y].val == board[x][y].val &&
!board[x][y].blocked && !board[x + d][y].blocked) {
board[x][y].val = 0;
board[x + d][y].val *= 2;
score += board[x + d][y].val;
board[x + d][y].blocked = true;
moved = true;
} else if (!board[x + d][y].val && board[x][y].val) {
board[x + d][y].val = board[x][y].val;
board[x][y].val = 0;
moved = true;
}
if (d > 0) {
if (x + d < 3)
moveHorizontally(x + d, y, 1);
} else {
if (x + d > 0)
moveHorizontally(x + d, y, -1);
}
}
void move(in moveDir d) pure nothrow @safe @nogc {
final switch (d) with(moveDir) {
case up:
foreach (immutable x; 0 .. side)
foreach (immutable y; 1 .. side)
if (board[x][y].val)
moveVertically(x, y, -1);
break;
case down:
foreach (immutable x; 0 .. side)
foreach_reverse (immutable y; 0 .. 3)
if (board[x][y].val)
moveVertically(x, y, 1);
break;
case left:
foreach (immutable y; 0 .. side)
foreach (immutable x; 1 .. side)
if (board[x][y].val)
moveHorizontally(x, y, -1);
break;
case right:
foreach (immutable y; 0 .. side)
foreach_reverse (immutable x; 0 .. 3)
if (board[x][y].val)
moveHorizontally(x, y, 1);
}
}
}
void main() /*safe*/ {
G2048 g;
g.gameLoop;
} |
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
| #Sidef | Sidef | func four_squares (list, unique=true, show=true) {
var solutions = []
func check(c) {
solutions << c if ([
c[0] + c[1],
c[1] + c[2] + c[3],
c[3] + c[4] + c[5],
c[5] + c[6],
].uniq.len == 1)
}
if (unique) {
list.combinations(7, {|*a|
a.permutations { |*c|
check(c)
}
})
} else {
7.of { list }.cartesian {|*c|
check(c)
}
}
say (solutions.len,
(unique ? ' ' : ' non-'),
"unique solutions found using #{list.join(', ')}.\n")
if (show) {
var f = "%#{list.max.len+1}s"
say ("\n".join(
('a'..'g').map{f % _}.join,
solutions.map{ .map{f % _}.join }...
), "\n")
}
}
# TASK
four_squares(@(1..7))
four_squares(@(3..9))
four_squares([8, 9, 11, 12, 17, 18, 20, 21])
four_squares(@(0..9), unique: false, show: false) |
http://rosettacode.org/wiki/15_puzzle_solver | 15 puzzle solver | Your task is to write a program that finds a solution in the fewest moves possible single moves to a random Fifteen Puzzle Game.
For this task you will be using the following puzzle:
15 14 1 6
9 11 4 12
0 10 7 3
13 8 5 2
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 0
The output must show the moves' directions, like so: left, left, left, down, right... and so on.
There are two solutions, of fifty-two moves:
rrrulddluuuldrurdddrullulurrrddldluurddlulurruldrdrd
rrruldluuldrurdddluulurrrdlddruldluurddlulurruldrrdd
see: Pretty Print of Optimal Solution
Finding either one, or both is an acceptable result.
Extra credit.
Solve the following problem:
0 12 9 13
15 11 10 14
3 7 2 5
4 8 6 1
Related Task
15 puzzle game
A* search algorithm
| #Perl | Perl | use strict;
no warnings;
use enum qw(False True);
use constant Nr => <3 0 0 0 0 1 1 1 1 2 2 2 2 3 3 3>;
use constant Nc => <3 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2>;
my ($n, $m) = (0, 0);
my(@N0, @N2, @N3, @N4);
sub fY {
printf "Solution found in $n moves: %s\n", join('', @N3) and exit if $N2[$n] == 0x123456789abcdef0;
$N4[$n] <= $m ? fN() : False;
}
sub fN {
sub common { ++$n; return True if fY(); --$n }
if ($N3[$n] ne 'u' and int($N0[$n] / 4) < 3) { fI(); common() }
if ($N3[$n] ne 'd' and int($N0[$n] / 4) > 0) { fG(); common() }
if ($N3[$n] ne 'l' and ($N0[$n] % 4) < 3) { fE(); common() }
if ($N3[$n] ne 'r' and ($N0[$n] % 4) > 0) { fL(); common() }
return False;
}
sub fI {
my $g = (11-$N0[$n])*4;
my $a = $N2[$n] & (15 << $g);
$N0[$n+1] = $N0[$n]+4;
$N2[$n+1] = $N2[$n]-$a+($a<<16);
$N4[$n+1] = $N4[$n]+((Nr)[$a>>$g] <= int($N0[$n] / 4) ? 0 : 1);
$N3[$n+1] = 'd';
}
sub fG {
my $g = (19-$N0[$n])*4;
my $a = $N2[$n] & (15 << $g);
$N0[$n+1] = $N0[$n]-4;
$N2[$n+1] = $N2[$n]-$a+($a>>16);
$N4[$n+1] = $N4[$n]+((Nr)[$a>>$g] >= int($N0[$n] / 4) ? 0 : 1);
$N3[$n+1] = 'u';
}
sub fE {
my $g = (14-$N0[$n])*4;
my $a = $N2[$n] & (15 << $g);
$N0[$n+1] = $N0[$n]+1;
$N2[$n+1] = $N2[$n]-$a+($a<<4);
$N4[$n+1] = $N4[$n]+((Nc)[$a>>$g] <= $N0[$n]%4 ? 0 : 1);
$N3[$n+1] = 'r';
}
sub fL {
my $g = (16-$N0[$n])*4;
my $a = $N2[$n] & (15 << $g);
$N0[$n+1] = $N0[$n]-1;
$N2[$n+1] = $N2[$n]-$a+($a>>4);
$N4[$n+1] = $N4[$n]+((Nc)[$a>>$g] >= $N0[$n]%4 ? 0 : 1);
$N3[$n+1] = 'l';
}
($N0[0], $N2[0]) = (8, 0xfe169b4c0a73d852); # initial state
while () { fY() or ++$m } |
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
| #Arturo | Arturo | s: "s"
loop 99..1 'i [
print ~"|i| bottle|s| of beer on the wall,"
print ~"|i| bottle|s| of beer"
print ~"Take one down, pass it around!"
if 1=i-1 -> s: ""
if? i>1 [
print ~"|i-1| bottle|s| of beer on the wall!"
print ""
]
else -> print "No more bottles of beer on the wall!"
] |
http://rosettacode.org/wiki/24_game | 24 game | The 24 Game tests one's mental arithmetic.
Task
Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed.
The program should prompt for the player to enter an arithmetic expression using just those, and all of those four digits, used exactly once each. The program should check then evaluate the expression.
The goal is for the player to enter an expression that (numerically) evaluates to 24.
Only the following operators/functions are allowed: multiplication, division, addition, subtraction
Division should use floating point or rational arithmetic, etc, to preserve remainders.
Brackets are allowed, if using an infix expression evaluator.
Forming multiple digit numbers from the supplied digits is disallowed. (So an answer of 12+12 when given 1, 2, 2, and 1 is wrong).
The order of the digits when given does not have to be preserved.
Notes
The type of expression evaluator used is not mandated. An RPN evaluator is equally acceptable for example.
The task is not for the program to generate the expression, or test whether an expression is even possible.
Related tasks
24 game/Solve
Reference
The 24 Game on h2g2.
| #GAP | GAP | Play24 := function()
local input, digits, line, c, chars, stack, stackptr, cur, p, q, ok, a, b, run;
input := InputTextUser();
run := true;
while run do
digits := List([1 .. 4], n -> Random(1, 9));
while true do
Display(digits);
line := ReadLine(input);
line := Chomp(line);
if line = "end" then
run := false;
break;
elif line = "next" then
break;
else
ok := true;
stack := [ ];
stackptr := 0;
chars := "123456789+-*/ ";
cur := ShallowCopy(digits);
for c in line do
if c = ' ' then
continue;
fi;
p := Position(chars, c);
if p = fail then
ok := false;
break;
fi;
if p < 10 then
q := Position(cur, p);
if q = fail then
ok := false;
break;
fi;
Unbind(cur[q]);
stackptr := stackptr + 1;
stack[stackptr] := p;
else
if stackptr < 2 then
ok := false;
break;
fi;
b := stack[stackptr];
a := stack[stackptr - 1];
stackptr := stackptr - 1;
if c = '+' then
a := a + b;
elif c = '-' then
a := a - b;
elif c = '*' then
a := a * b;
elif c = '/' then
if b = 0 then
ok := false;
break;
fi;
a := a / b;
else
ok := false;
break;
fi;
stack[stackptr] := a;
fi;
od;
if ok and stackptr = 1 and Size(cur) = 0 then
if stack[1] = 24 then
Print("Good !\n");
break;
else
Print("Bad value: ", stack[1], "\n");
continue;
fi;
fi;
Print("Invalid expression\n");
fi;
od;
od;
CloseStream(input);
end;
# example session
# type "end" to quit the game, "next" to try another list of digits
gap> Play24();
[ 7, 6, 8, 5 ]
86*75-/
Good !
[ 5, 9, 2, 7 ]
end
gap> |
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
| #Dart | Dart | import 'dart:io';
// a little helper function that checks if the string only contains
// digits and an optional minus sign at the front
bool isAnInteger(String str) => str.contains(new RegExp(r'^-?\d+$'));
void main() {
while(true) {
String input = stdin.readLineSync();
var chunks = input.split(new RegExp(r'[ ]+')); // split on 1 or more spaces
if(!chunks.every(isAnInteger)) {
print("not an integer!");
} else if(chunks.length > 2) {
print("too many numbers!");
} else if(chunks.length < 2) {
print('not enough numbers!');
} else {
// parse the strings into integers
var nums = chunks.map((String s) => int.parse(s));
if(nums.any((num) => num < -1000 || num > 1000)) {
print("between -1000 and 1000 please!");
} else {
print(nums.reduce((a, b) => 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.
| #Wart | Wart | def (ackermann m n)
(if m=0
n+1
n=0
(ackermann m-1 1)
:else
(ackermann m-1 (ackermann 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
| #Icon_and_Unicon | Icon and Unicon | procedure main(A)
blocks := ["bo","xk","dq","cp","na","gt","re","tg","qd","fs",
"jw","hu","vi","an","ob","er","fs","ly","pc","zm",&null]
every write("\"",word := !A,"\" ",checkSpell(map(word),blocks)," with blocks.")
end
procedure checkSpell(w,blocks)
blks := copy(blocks)
w ? return if canMakeWord(blks) then "can be spelled"
else "can not be spelled"
end
procedure canMakeWord(blks)
c := move(1) | return
if /blks[1] then fail
every i := 1 to *blks do {
if /blks[i] then (move(-1),fail)
if c == !blks[i] then {
blks[1] :=: blks[i]
if canMakeWord(blks[2:0]) then return
blks[1] :=: blks[i]
}
}
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.
| #Fortran | Fortran | SUBROUTINE SHUFFLE_ARRAY(INT_ARRAY)
! Takes an input array and shuffles the elements by swapping them
! in pairs in turn 10 times
IMPLICIT NONE
INTEGER, DIMENSION(100), INTENT(INOUT) :: INT_ARRAY
INTEGER, PARAMETER :: N_PASSES = 10
! Local Variables
INTEGER :: TEMP_1, TEMP_2 ! Temporaries for swapping elements
INTEGER :: I, J, PASS ! Indices variables
REAL :: R ! Randomly generator value
CALL RANDOM_SEED() ! Seed the random number generator
DO PASS=1, N_PASSES
DO I=1, SIZE(INT_ARRAY)
! Get a random index to swap with
CALL RANDOM_NUMBER(R)
J = CEILING(R*SIZE(INT_ARRAY))
! In case generated index value
! exceeds array size
DO WHILE (J > SIZE(INT_ARRAY))
J = CEILING(R*SIZE(INT_ARRAY))
END DO
! Swap the two elements
TEMP_1 = INT_ARRAY(I)
TEMP_2 = INT_ARRAY(J)
INT_ARRAY(I) = TEMP_2
INT_ARRAY(J) = TEMP_1
ENDDO
ENDDO
END SUBROUTINE SHUFFLE_ARRAY
SUBROUTINE RUN_RANDOM(N_ROUNDS)
! Run the 100 prisoner puzzle simulation N_ROUNDS times
! in the scenario where each prisoner selects a drawer at random
IMPLICIT NONE
INTEGER, INTENT(IN) :: N_ROUNDS ! Number of simulations to run in total
INTEGER :: ROUND, PRISONER, CHOICE, I ! Iteration variables
INTEGER :: N_SUCCESSES ! Number of successful trials
REAL(8) :: TOTAL ! Total number of trials as real
LOGICAL :: NUM_FOUND = .FALSE. ! Prisoner has found their number
INTEGER, DIMENSION(100) :: CARDS, CHOICES ! Arrays representing card allocations
! to draws and drawer choice order
! Both cards and choices are randomly assigned.
! This being the drawer (allocation represented by index),
! and what drawer to pick for Nth/50 choice
! (take first 50 elements of 100 element array)
CARDS = (/(I, I=1, 100, 1)/)
CHOICES = (/(I, I=1, 100, 1)/)
N_SUCCESSES = 0
TOTAL = REAL(N_ROUNDS)
! Run the simulation for N_ROUNDS rounds
! when a prisoner fails to find their number
! after 50 trials, set that simulation to fail
! and start the next round
ROUNDS_LOOP: DO ROUND=1, N_ROUNDS
CALL SHUFFLE_ARRAY(CARDS)
PRISONERS_LOOP: DO PRISONER=1, 100
NUM_FOUND = .FALSE.
CALL SHUFFLE_ARRAY(CHOICES)
CHOICE_LOOP: DO CHOICE=1, 50
IF(CARDS(CHOICE) == PRISONER) THEN
NUM_FOUND = .TRUE.
EXIT CHOICE_LOOP
ENDIF
ENDDO CHOICE_LOOP
IF(.NOT. NUM_FOUND) THEN
EXIT PRISONERS_LOOP
ENDIF
ENDDO PRISONERS_LOOP
IF(NUM_FOUND) THEN
N_SUCCESSES = N_SUCCESSES + 1
ENDIF
ENDDO ROUNDS_LOOP
WRITE(*, '(A, F0.3, A)') "Random drawer selection method success rate: ", &
100*N_SUCCESSES/TOTAL, "%"
END SUBROUTINE RUN_RANDOM
SUBROUTINE RUN_OPTIMAL(N_ROUNDS)
! Run the 100 prisoner puzzle simulation N_ROUNDS times in the scenario
! where each prisoner selects firstly the drawer with their number and then
! subsequently the drawer matching the number of the card present
! within that current drawer
IMPLICIT NONE
INTEGER, INTENT(IN) :: N_ROUNDS
INTEGER :: ROUND, PRISONER, CHOICE, I ! Iteration variables
INTEGER :: CURRENT_DRAW ! ID of the current draw
INTEGER :: N_SUCCESSES ! Number of successful trials
REAL(8) :: TOTAL ! Total number of trials as real
LOGICAL :: NUM_FOUND = .FALSE. ! Prisoner has found their number
INTEGER, DIMENSION(100) :: CARDS ! Array representing card allocations
! Cards are randomly assigned to a drawer
! (allocation represented by index),
CARDS = (/(I, I=1, 100, 1)/)
N_SUCCESSES = 0
TOTAL = REAL(N_ROUNDS)
! Run the simulation for N_ROUNDS rounds
! when a prisoner fails to find their number
! after 50 trials, set that simulation to fail
! and start the next round
ROUNDS_LOOP: DO ROUND=1, N_ROUNDS
CARDS = (/(I, I=1, 100, 1)/)
CALL SHUFFLE_ARRAY(CARDS)
PRISONERS_LOOP: DO PRISONER=1, 100
CURRENT_DRAW = PRISONER
NUM_FOUND = .FALSE.
CHOICE_LOOP: DO CHOICE=1, 50
IF(CARDS(CURRENT_DRAW) == PRISONER) THEN
NUM_FOUND = .TRUE.
EXIT CHOICE_LOOP
ELSE
CURRENT_DRAW = CARDS(CURRENT_DRAW)
ENDIF
ENDDO CHOICE_LOOP
IF(.NOT. NUM_FOUND) THEN
EXIT PRISONERS_LOOP
ENDIF
ENDDO PRISONERS_LOOP
IF(NUM_FOUND) THEN
N_SUCCESSES = N_SUCCESSES + 1
ENDIF
ENDDO ROUNDS_LOOP
WRITE(*, '(A, F0.3, A)') "Optimal drawer selection method success rate: ", &
100*N_SUCCESSES/TOTAL, "%"
END SUBROUTINE RUN_OPTIMAL
PROGRAM HUNDRED_PRISONERS
! Run the two scenarios for the 100 prisoners puzzle of random choice
! and optimal choice (choice based on drawer contents)
IMPLICIT NONE
INTEGER, PARAMETER :: N_ROUNDS = 50000
WRITE(*,'(A, I0, A)') "Running simulation for ", N_ROUNDS, " trials..."
CALL RUN_RANDOM(N_ROUNDS)
CALL RUN_OPTIMAL(N_ROUNDS)
END PROGRAM HUNDRED_PRISONERS |
http://rosettacode.org/wiki/21_game | 21 game | 21 game
You are encouraged to solve this task according to the task description, using any language you may know.
21 is a two player game, the game is played by choosing
a number (1, 2, or 3) to be added to the running total.
The game is won by the player whose chosen number causes the running total
to reach exactly 21.
The running total starts at zero.
One player will be the computer.
Players alternate supplying a number to be added to the running total.
Task
Write a computer program that will:
do the prompting (or provide a button menu),
check for errors and display appropriate error messages,
do the additions (add a chosen number to the running total),
display the running total,
provide a mechanism for the player to quit/exit/halt/stop/close the program,
issue a notification when there is a winner, and
determine who goes first (maybe a random or user choice, or can be specified when the game begins).
| #Scala | Scala |
object Game21 {
import scala.collection.mutable.ListBuffer
import scala.util.Random
val N = 21 // the same game would also work for N other than 21...
val RND = new Random() // singular random number generator; add a seed number, if you want reproducibility
/** tuple: name and a play function: (rest: remaining number, last: value of opponent's last move) => new move
*/
type Player = (String, (Int,Int) => Int)
// indeed, the following could also be written using a class and instances, I've choosen a
// more functional and math way (using tuples)...
val playerRandom:Player = ("RandomRobot", { (rest, last) =>
if (rest <= 3) rest
else 1 + RND.nextInt(3)
})
val playerBest:Player = ("BestRobot", { (rest, last) =>
val i = rest % 4
if (i > 0) i else 1 + RND.nextInt(3)
})
val playerHuman:Player = ("YOU", { (rest, last) =>
println("Rest: "+rest)
println("Last: "+last)
var in = ""
while (in!="1" && in!="2" && in!="3") {
in = scala.io.StdIn.readLine("Your move (1,2,3,q)> ").trim
if ("q" == in)
throw new Exception("q => quit")
}
in.toInt
})
/** Execute a whole game. NOTE that we're counting DOWN from N to 0!
* @param players
* @return list of all moves
*/
def play(players:Seq[Player]):Seq[Int] = {
require(players.size == 2)
var last = -1
var rest = N
var p = 0 // player 0 always starts
val l = ListBuffer[Int]() // list of all moves
while (rest > 0) {
last = players(p)._2(rest,last)
require(1<=last && last<=3,"Player must always play 1,2,3: "+last)
l += last
rest -= last
p = 1 - p // other player's turn
}
l.toSeq
}
/** Evaluate a whole game.
* @param game list of moves of one game
* @param rest mainly for recursion
* @return evaluation, for each move a tuple: (rest, what was played, whether this player won in the end)
*/
def evaluate(game:Seq[Int],rest:Int=N):Seq[(Int,Int,Boolean)] = {
if (game.size == 0) Seq()
else Seq((rest,game.head,game.size%2 == 1)) ++ evaluate(game.tail,rest - game.head)
}
def main(args: Array[String]): Unit = {
// here you can put whatever player combination you like
val players = Seq(playerRandom,playerRandom) // random robot vs random robot
//val players = Seq(playerRandom,playerBest) // random robot vs best robot
//val players = Seq(playerHuman,playerBest) // You vs best robot
var p0won = 0
val n = 1000 // number of games to play
var m = 0 // games actually played (a human player might quit before n)
try {
(1 to n).foreach { i =>
val g = play(players)
require(g.sum == N) // some validity checks
val e = evaluate(g)
require(e.size == g.size && e.last._3 && e(0)._3 != e(1)._3) // some validity checks
if (e(0)._3) p0won += 1
m += 1
println(i + ": " + players(0)._1 + " " + (if (e(0)._3) "won" else "lost") + " against " + players(1)._1 + ". " + g + " => " + e)
}
} catch {
case t:Throwable => println(t.getMessage)
}
println("Player0: "+players(0)._1)
println("Player1: "+players(1)._1)
println(f"Player0 won ${p0won} times out of ${m}, or ${p0won * 100.0 / m}%%")
}
}
|
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
| #Julia | Julia | function solve24(nums)
length(nums) != 4 && error("Input must be a 4-element Array")
syms = [+,-,*,/]
for x in syms, y in syms, z in syms
for i = 1:24
a,b,c,d = nthperm(nums,i)
if round(x(y(a,b),z(c,d)),5) == 24
return "($a$y$b)$x($c$z$d)"
elseif round(x(a,y(b,z(c,d))),5) == 24
return "$a$x($b$y($c$z$d))"
elseif round(x(y(z(c,d),b),a),5) == 24
return "(($c$z$d)$y$b)$x$a"
elseif round(x(y(b,z(c,d)),a),5) == 24
return "($b$y($c$z$d))$x$a"
end
end
end
return "0"
end |
http://rosettacode.org/wiki/15_puzzle_game | 15 puzzle game |
Task
Implement the Fifteen Puzzle Game.
The 15-puzzle is also known as:
Fifteen Puzzle
Gem Puzzle
Boss Puzzle
Game of Fifteen
Mystic Square
14-15 Puzzle
and some others.
Related Tasks
15 Puzzle Solver
16 Puzzle Game
| #BQN | BQN | _while_ ← {𝔽⍟𝔾∘𝔽_𝕣_𝔾∘𝔽⍟𝔾𝕩}
FPG←{
𝕊𝕩: 4‿4𝕊𝕩;
(∧´𝕨<0)∨2≠≠𝕨 ? •Out "Invalid shape: "∾•Fmt 𝕨;
0≠=𝕩 ? •Out "Invalid shuffle count: "∾•Fmt 𝕩;
s𝕊𝕩:
d←⟨1‿0⋄¯1‿0⋄0‿1⋄0‿¯1⟩ # Directions
w←𝕨⥊1⌽↕×´𝕨 # Solved grid
b←w # Board
z←⊑{
z‿p←𝕩
p↩(⊢≡s⊸|)¨⊸/(<z)+d(¬∘∊/⊣)p # filter out invalid
n←(•rand.Range ≠p)⊑p
b⌽⌾(z‿n⊸⊑)↩ # switch places
-`n‿z
}⍟𝕩 ⟨𝕨-1,⟨0⟩⟩
{
𝕊:
b≡w ? •Show b, •Out "You win", 0;
•Show b
inp←⊑{
Check 𝕩:
•Out "Enter move: "
x←•GetLine@
i←⊑"↑↓←→q"⊐x
{
i=4 ? i; # quit
i>4 ? •Out "Invalid direction: "∾x, Check x;
(⊢≢s⊸|)z+i⊑d ? •Out "Out of bounds: "∾x, Check x;
i
}
} @
{
𝕩=4 ? •Out "Quitting", 0;
mv←z+𝕩⊑d
b⌽⌾(mv‿z⊸⊑)↩
z↩mv
1
} inp
} _while_ ⊢ 1
@
} |
http://rosettacode.org/wiki/2048 | 2048 | Task
Implement a 2D sliding block puzzle game where blocks with numbers are combined to add their values.
Rules of the game
The rules are that on each turn the player must choose a direction (up, down, left or right).
All tiles move as far as possible in that direction, some move more than others.
Two 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.
| #Delphi | Delphi |
program Game2048;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
System.Math,
Velthuis.Console;
type
TTile = class
Value: integer;
IsBlocked: Boolean;
constructor Create;
end;
TMoveDirection = (mdUp, mdDown, mdLeft, mdRight);
TG2048 = class
FisDone, FisWon, FisMoved: boolean;
Fscore: Cardinal;
FBoard: array[0..3, 0..3] of TTile;
function GetLine(aType: byte): string;
public
constructor Create;
destructor Destroy; override;
procedure InitializeBoard();
procedure FinalizeBoard();
procedure Loop;
procedure DrawBoard();
procedure WaitKey();
procedure AddTile();
function CanMove(): boolean;
function TestAdd(x, y, value: Integer): boolean;
procedure MoveHorizontally(x, y, d: integer);
procedure MoveVertically(x, y, d: integer);
procedure Move(direction: TMoveDirection);
end;
{ TTile }
constructor TTile.Create;
begin
Value := 0;
IsBlocked := false;
end;
{ TG2048 }
procedure TG2048.AddTile;
var
y, x, a, b: Integer;
r: Double;
begin
for y := 0 to 3 do
begin
for x := 0 to 3 do
begin
if Fboard[x, y].Value <> 0 then
continue;
repeat
a := random(4);
b := random(4);
until not (Fboard[a, b].Value <> 0);
r := Random;
if r > 0.89 then
Fboard[a, b].Value := 4
else
Fboard[a, b].Value := 2;
if CanMove() then
begin
Exit;
end;
end;
end;
FisDone := true;
end;
function TG2048.CanMove: boolean;
var
y, x: Integer;
begin
for y := 0 to 3 do
begin
for x := 0 to 3 do
begin
if Fboard[x, y].Value = 0 then
begin
Exit(true);
end;
end;
end;
for y := 0 to 3 do
begin
for x := 0 to 3 do
begin
if TestAdd(x + 1, y, Fboard[x, y].Value) or TestAdd(x - 1, y, Fboard[x, y].Value)
or TestAdd(x, y + 1, Fboard[x, y].Value) or TestAdd(x, y - 1, Fboard[x,
y].Value) then
begin
Exit(true);
end;
end;
end;
Exit(false);
end;
constructor TG2048.Create;
begin
FisDone := false;
FisWon := false;
FisMoved := true;
Fscore := 0;
InitializeBoard();
Randomize;
end;
destructor TG2048.Destroy;
begin
FinalizeBoard;
inherited;
end;
procedure TG2048.DrawBoard;
var
y, x: Integer;
color: byte;
lineFragment, line: string;
begin
ClrScr;
HighVideo;
writeln('Score: ', Fscore: 3, #10);
TextBackground(White);
TextColor(black);
for y := 0 to 3 do
begin
if y = 0 then
writeln(GetLine(0))
else
writeln(GetLine(1));
Write(' '#$2551' ');
for x := 0 to 3 do
begin
if Fboard[x, y].Value = 0 then
begin
Write(' ');
end
else
begin
color := Round(Log2(Fboard[x, y].Value));
TextColor(14 - color);
Write(Fboard[x, y].Value: 4);
TextColor(Black);
end;
Write(' '#$2551' ');
end;
writeln(' ');
end;
writeln(GetLine(2), #10#10);
TextBackground(Black);
TextColor(White);
end;
procedure TG2048.FinalizeBoard;
var
y, x: integer;
begin
for y := 0 to 3 do
for x := 0 to 3 do
FBoard[x, y].Free;
end;
function TG2048.GetLine(aType: byte): string;
var
fragment, line: string;
bgChar, edChar, mdChar: char;
begin
case aType of
0:
begin
bgChar := #$2554;
edChar := #$2557;
mdChar := #$2566;
end;
1:
begin
bgChar := #$2560;
edChar := #$2563;
mdChar := #$256C;
end;
2:
begin
bgChar := #$255A;
edChar := #$255D;
mdChar := #$2569;
end;
end;
fragment := string.create(#$2550, 6);
line := fragment + mdChar + fragment + mdChar + fragment + mdChar + fragment;
Result := ' '+bgChar + line + edChar + ' ';
end;
procedure TG2048.InitializeBoard;
var
y, x: integer;
begin
for y := 0 to 3 do
for x := 0 to 3 do
FBoard[x, y] := TTile.Create;
end;
procedure TG2048.Loop;
begin
AddTile();
while (true) do
begin
if (FisMoved) then
AddTile();
DrawBoard();
if (FisDone) then
break;
WaitKey();
end;
if FisWon then
Writeln('You''ve made it!')
else
Writeln('Game Over!');
end;
procedure TG2048.Move(direction: TMoveDirection);
var
x, y: Integer;
begin
case direction of
mdUp:
begin
for x := 0 to 3 do
begin
y := 1;
while y < 4 do
begin
if Fboard[x, y].Value <> 0 then
MoveVertically(x, y, -1);
Inc(y);
end;
end;
end;
mdDown:
begin
for x := 0 to 3 do
begin
y := 2;
while y >= 0 do
begin
if Fboard[x, y].Value <> 0 then
MoveVertically(x, y, 1);
Dec(y);
end;
end;
end;
mdLeft:
begin
for y := 0 to 3 do
begin
x := 1;
while x < 4 do
begin
if Fboard[x, y].Value <> 0 then
MoveHorizontally(x, y, -1);
Inc(x);
end;
end;
end;
mdRight:
begin
for y := 0 to 3 do
begin
x := 2;
while x >= 0 do
begin
if Fboard[x, y].Value <> 0 then
MoveHorizontally(x, y, 1);
Dec(x);
end;
end;
end;
end;
end;
procedure TG2048.MoveHorizontally(x, y, d: integer);
begin
if (FBoard[x + d, y].Value <> 0) and (FBoard[x + d, y].Value = FBoard[x, y].Value)
and (not FBoard[x + d, y].IsBlocked) and (not FBoard[x, y].IsBlocked) then
begin
FBoard[x, y].Value := 0;
FBoard[x + d, y].Value := FBoard[x + d, y].Value * 2;
Fscore := Fscore + (FBoard[x + d, y].Value);
FBoard[x + d, y].IsBlocked := true;
FisMoved := true;
end
else if ((FBoard[x + d, y].Value = 0) and (FBoard[x, y].Value <> 0)) then
begin
FBoard[x + d, y].Value := FBoard[x, y].Value;
FBoard[x, y].Value := 0;
FisMoved := true;
end;
if d > 0 then
begin
if x + d < 3 then
begin
MoveHorizontally(x + d, y, 1);
end;
end
else
begin
if x + d > 0 then
begin
MoveHorizontally(x + d, y, -1);
end;
end;
end;
procedure TG2048.MoveVertically(x, y, d: integer);
begin
if (Fboard[x, y + d].Value <> 0) and (Fboard[x, y + d].Value = Fboard[x, y].Value)
and (not Fboard[x, y].IsBlocked) and (not Fboard[x, y + d].IsBlocked) then
begin
Fboard[x, y].Value := 0;
Fboard[x, y + d].Value := Fboard[x, y + d].Value * 2;
Fscore := Fscore + (Fboard[x, y + d].Value);
Fboard[x, y + d].IsBlocked := true;
FisMoved := true;
end
else if ((Fboard[x, y + d].Value = 0) and (Fboard[x, y].Value <> 0)) then
begin
Fboard[x, y + d].Value := Fboard[x, y].Value;
Fboard[x, y].Value := 0;
FisMoved := true;
end;
if d > 0 then
begin
if y + d < 3 then
begin
MoveVertically(x, y + d, 1);
end;
end
else
begin
if y + d > 0 then
begin
MoveVertically(x, y + d, -1);
end;
end;
end;
function TG2048.TestAdd(x, y, value: Integer): boolean;
begin
if (x < 0) or (x > 3) or (y < 0) or (y > 3) then
Exit(false);
Exit(Fboard[x, y].value = value);
end;
procedure TG2048.WaitKey;
var
y, x: Integer;
begin
FisMoved := false;
writeln('(W) Up (S) Down (A) Left (D) Right (ESC)Exit');
case ReadKey of
'W', 'w':
Move(TMoveDirection.mdUp);
'A', 'a':
Move(TMoveDirection.mdLeft);
'S', 's':
Move(TMoveDirection.mdDown);
'D', 'd':
Move(TMoveDirection.mdRight);
#27:
FisDone := true;
end;
for y := 0 to 3 do
for x := 0 to 3 do
Fboard[x, y].IsBlocked := false;
end;
var
Game: TG2048;
begin
with TG2048.Create do
begin
Loop;
Free;
end;
Writeln('Press Enter to exit');
Readln;
end. |
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
| #Simula | Simula | BEGIN
INTEGER PROCEDURE GETCOMBS(LOW, HIGH, UNIQUE, COMBS);
INTEGER LOW, HIGH;
INTEGER ARRAY COMBS;
BOOLEAN UNIQUE;
BEGIN
INTEGER A, B, C, D, E, F, G;
INTEGER NUM;
BOOLEAN PROCEDURE ISUNIQUE(A, B, C, D, E, F, G);
INTEGER A, B, C, D, E, F, G;
BEGIN
INTEGER ARRAY DATA(LOW:HIGH);
INTEGER I;
FOR I := LOW STEP 1 UNTIL HIGH DO
DATA(I) := -1;
FOR I := A, B, C, D, E, F, G DO
IF DATA(I) = -1
THEN DATA(I) := 1
ELSE GOTO L;
ISUNIQUE := TRUE;
L:
END;
PROCEDURE ADDCOMB;
BEGIN
NUM := NUM + 1;
COMBS(NUM, LOW + 0) := A;
COMBS(NUM, LOW + 1) := B;
COMBS(NUM, LOW + 2) := C;
COMBS(NUM, LOW + 3) := D;
COMBS(NUM, LOW + 4) := E;
COMBS(NUM, LOW + 5) := F;
COMBS(NUM, LOW + 6) := G;
END;
FOR A := LOW STEP 1 UNTIL HIGH DO
FOR B := LOW STEP 1 UNTIL HIGH DO
FOR C := LOW STEP 1 UNTIL HIGH DO
FOR D := LOW STEP 1 UNTIL HIGH DO
FOR E := LOW STEP 1 UNTIL HIGH DO
FOR F := LOW STEP 1 UNTIL HIGH DO
FOR G := LOW STEP 1 UNTIL HIGH DO
BEGIN
IF VALIDCOMB(A, B, C, D, E, F, G) THEN
BEGIN
IF UNIQUE THEN
BEGIN IF ISUNIQUE(A, B, C, D, E, F, G) THEN ADDCOMB END
ELSE ADDCOMB;
END;
END;
GETCOMBS := NUM;
END;
BOOLEAN PROCEDURE VALIDCOMB(A, B, C, D, E, F, G);
INTEGER A, B, C, D, E, F, G;
BEGIN
INTEGER SQUARE1, SQUARE2, SQUARE3, SQUARE4;
SQUARE1 := A + B;
SQUARE2 := B + C + D;
SQUARE3 := D + E + F;
SQUARE4 := F + G;
VALIDCOMB := SQUARE1 = SQUARE2 AND SQUARE2 = SQUARE3 AND SQUARE3 = SQUARE4
END;
COMMENT ----- MAIN PROGRAM ----- ;
INTEGER ARRAY LO(1:3);
INTEGER ARRAY HI(1:3);
BOOLEAN ARRAY UQ(1:3);
INTEGER I;
LO(1) := 1; HI(1) := 7; UQ(1) := TRUE;
LO(2) := 3; HI(2) := 9; UQ(2) := TRUE;
LO(3) := 0; HI(3) := 9; UQ(3) := FALSE;
FOR I := 1 STEP 1 UNTIL 3 DO
BEGIN
INTEGER LOW, HIGH;
BOOLEAN UNIQ;
LOW := LO(I); HIGH := HI(I); UNIQ := UQ(I);
BEGIN
INTEGER ARRAY VALIDCOMBS(1:8000, LOW:HIGH);
INTEGER N;
N := GETCOMBS(LOW, HIGH, UNIQ, VALIDCOMBS);
OUTINT(N, 0);
IF UNIQ THEN OUTTEXT(" UNIQUE");
OUTTEXT(" SOLUTIONS IN ");
OUTINT(LOW, 0); OUTTEXT(" TO ");
OUTINT(HIGH, 0);
OUTIMAGE;
IF I < 3 THEN
BEGIN INTEGER I, J;
FOR I := 1 STEP 1 UNTIL N DO
BEGIN
OUTTEXT("[");
FOR J := LOW STEP 1 UNTIL HIGH DO
OUTINT(VALIDCOMBS(I, J), 2);
OUTTEXT(" ]");
OUTIMAGE;
END;
END;
END;
END;
END.
|
http://rosettacode.org/wiki/15_puzzle_solver | 15 puzzle solver | Your task is to write a program that finds a solution in the fewest moves possible single moves to a random Fifteen Puzzle Game.
For this task you will be using the following puzzle:
15 14 1 6
9 11 4 12
0 10 7 3
13 8 5 2
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 0
The output must show the moves' directions, like so: left, left, left, down, right... and so on.
There are two solutions, of fifty-two moves:
rrrulddluuuldrurdddrullulurrrddldluurddlulurruldrdrd
rrruldluuldrurdddluulurrrdlddruldluurddlulurruldrrdd
see: Pretty Print of Optimal Solution
Finding either one, or both is an acceptable result.
Extra credit.
Solve the following problem:
0 12 9 13
15 11 10 14
3 7 2 5
4 8 6 1
Related Task
15 puzzle game
A* search algorithm
| #Phix | Phix | -- demo\rosetta\Solve15puzzle.exw
constant STM = 0 -- single-tile metrics.
constant MTM = 0 -- multi-tile metrics.
if STM and MTM then ?9/0 end if -- both prohibited
-- 0 0 -- fastest, but non-optimal
-- 1 0 -- optimal in STM
-- 0 1 -- optimal in MTM (slowest by far)
--Note: The fast method uses an inadmissible heuristic - see "not STM" in iddfs().
-- It explores mtm-style using the higher stm heuristic and may therefore
-- fail badly in some cases.
constant SIZE = 4
constant goal = { 1, 2, 3, 4,
5, 6, 7, 8,
9,10,11,12,
13,14,15, 0}
--
-- multi-tile-metric walking distance heuristic lookup (mmwd).
-- ==========================================================
-- Uses patterns of counts of tiles in/from row/col, eg the solved state
-- (ie goal above) could be represented by the following:
-- {{4,0,0,0},
-- {0,4,0,0},
-- {0,0,4,0},
-- {0,0,0,3}}
-- ie row/col 1 contains 4 tiles from col/row 1, etc. In this case
-- both are identical, but you can count row/col or col/row, and then
-- add them together. There are up to 24964 possible patterns. The
-- blank space is not counted. Note that a vertical move cannot change
-- a vertical pattern, ditto horizontal, and basic symmetry means that
-- row/col and col/row patterns will match (at least, that is, if they
-- are calculated sympathetically), halving the setup cost.
-- The data is just the number of moves made before this pattern was
-- first encountered, in a breadth-first search, backwards from the
-- goal state, until all patterns have been enumerated.
-- (The same ideas/vars are now also used for stm metrics when MTM=0)
--
sequence wdkey -- one such 4x4 pattern
constant mmwd = new_dict() -- lookup table, data is walking distance.
--
-- We use two to-do lists: todo is the current list, and everything
-- of walkingdistance+1 ends up on tdnx. Once todo is exhausted, we
-- swap the dictionary-ids, so tdnx automatically becomes empty.
-- Key is an mmwd pattern as above, and data is {distance,space_idx}.
--
integer todo = new_dict()
integer tdnx = new_dict()
--
enum UP = 1, DOWN = -1
procedure explore(integer space_idx, walking_distance, direction)
--
-- Given a space index, explore all the possible moves in direction,
-- setting the distance and extending the tdnx table.
--
integer tile_idx = space_idx+direction
for group=1 to SIZE do
if wdkey[tile_idx][group] then
-- ie: check row tile_idx for tiles belonging to rows 1..4
-- Swap one of those tiles with the space
wdkey[tile_idx][group] -= 1
wdkey[space_idx][group] += 1
if getd_index(wdkey,mmwd)=0 then
-- save the walking distance value
setd(wdkey,walking_distance+1,mmwd)
-- and add to the todo next list:
if getd_index(wdkey,tdnx)!=0 then ?9/0 end if
setd(wdkey,{walking_distance+1,tile_idx},tdnx)
end if
if MTM then
if tile_idx>1 and tile_idx<SIZE then
-- mtm: same direction means same distance:
explore(tile_idx, walking_distance, direction)
end if
end if
-- Revert the swap so we can look at the next candidate.
wdkey[tile_idx][group] += 1
wdkey[space_idx][group] -= 1
end if
end for
end procedure
procedure generate_mmwd()
-- Perform a breadth-first search begining with the solved puzzle state
-- and exploring from there until no more new patterns emerge.
integer walking_distance = 0, space = 4
wdkey = {{4,0,0,0}, -- \
{0,4,0,0}, -- } 4 tiles in correct row positions
{0,0,4,0}, -- /
{0,0,0,3}} -- 3 tiles in correct row position
setd(wdkey,walking_distance,mmwd)
while 1 do
if space<4 then explore(space, walking_distance, UP) end if
if space>1 then explore(space, walking_distance, DOWN) end if
if dict_size(todo)=0 then
if dict_size(tdnx)=0 then exit end if
{todo,tdnx} = {tdnx,todo}
end if
wdkey = getd_partial_key(0,todo)
{walking_distance,space} = getd(wdkey,todo)
deld(wdkey,todo)
end while
end procedure
function walking_distance(sequence puzzle)
sequence rkey = repeat(repeat(0,SIZE),SIZE),
ckey = repeat(repeat(0,SIZE),SIZE)
integer k = 1
for i=1 to SIZE do -- rows
for j=1 to SIZE do -- columns
integer tile = puzzle[k |
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
| #AsciiDots | AsciiDots | /-99#-.
/>*$_#-$_" bottles of beer on the wall, "-$_#-$" bottles of beer."\
|[-]1#-----" ,dnuora ti ssap dna nwod eno ekaT"_$-----------------/
| |
| | &-".llaw eht no reeb fo selttob 99 ,erom emos yub dna erots eht ot oG"$\
| |/$""-$"No more bottles of beer on the wall, no more bottles of beer."---/
| |\".llaw eht no reeb fo selttob erom on ,dnuora ti ssap dna nwod eno ekaT"$-".reeb fo elttob 1"$\
| | /-$"1 bottle of beer on the wall."-$""-$_"1 bottle of beer on the wall, "------------/
| | /-------\|
| \-*--{=}-\\~$_#-$" bottles of beer on the wall."\
| \-#1/ \-/ |
\----------------------------------------------""$/ |
http://rosettacode.org/wiki/24_game | 24 game | The 24 Game tests one's mental arithmetic.
Task
Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed.
The program should prompt for the player to enter an arithmetic expression using just those, and all of those four digits, used exactly once each. The program should check then evaluate the expression.
The goal is for the player to enter an expression that (numerically) evaluates to 24.
Only the following operators/functions are allowed: multiplication, division, addition, subtraction
Division should use floating point or rational arithmetic, etc, to preserve remainders.
Brackets are allowed, if using an infix expression evaluator.
Forming multiple digit numbers from the supplied digits is disallowed. (So an answer of 12+12 when given 1, 2, 2, and 1 is wrong).
The order of the digits when given does not have to be preserved.
Notes
The type of expression evaluator used is not mandated. An RPN evaluator is equally acceptable for example.
The task is not for the program to generate the expression, or test whether an expression is even possible.
Related tasks
24 game/Solve
Reference
The 24 Game on h2g2.
| #Go | Go | package main
import (
"fmt"
"math"
"math/rand"
"time"
)
func main() {
rand.Seed(time.Now().Unix())
n := make([]rune, 4)
for i := range n {
n[i] = rune(rand.Intn(9) + '1')
}
fmt.Printf("Your numbers: %c\n", n)
fmt.Print("Enter RPN: ")
var expr string
fmt.Scan(&expr)
if len(expr) != 7 {
fmt.Println("invalid. expression length must be 7." +
" (4 numbers, 3 operators, no spaces)")
return
}
stack := make([]float64, 0, 4)
for _, r := range expr {
if r >= '0' && r <= '9' {
if len(n) == 0 {
fmt.Println("too many numbers.")
return
}
i := 0
for n[i] != r {
i++
if i == len(n) {
fmt.Println("wrong numbers.")
return
}
}
n = append(n[:i], n[i+1:]...)
stack = append(stack, float64(r-'0'))
continue
}
if len(stack) < 2 {
fmt.Println("invalid expression syntax.")
return
}
switch r {
case '+':
stack[len(stack)-2] += stack[len(stack)-1]
case '-':
stack[len(stack)-2] -= stack[len(stack)-1]
case '*':
stack[len(stack)-2] *= stack[len(stack)-1]
case '/':
stack[len(stack)-2] /= stack[len(stack)-1]
default:
fmt.Printf("%c invalid.\n", r)
return
}
stack = stack[:len(stack)-1]
}
if math.Abs(stack[0]-24) > 1e-6 {
fmt.Println("incorrect.", stack[0], "!= 24")
} else {
fmt.Println("correct.")
}
} |
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
| #dc | dc | ? + psz |
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.
| #WDTE | WDTE | let memo a m n => true {
== m 0 => + n 1;
== n 0 => a (- m 1) 1;
true => a (- m 1) (a 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
| #J | J | reduce=: verb define
'rows cols'=. i.&.> $y
for_c. cols do.
r=. 1 i.~ c {"1 y NB. row idx of first 1 in col
if. r = #rows do. continue. end.
y=. 0 (<((r+1)}.rows);c) } y NB. zero rest of col
y=. 0 (<(r;(c+1)}.cols)) } y NB. zero rest of row
end.
)
abc=: *./@(+./)@reduce@(e."1~ ,)&toupper :: 0: |
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.
| #FreeBASIC | FreeBASIC | #include once "knuthshuf.bas" 'use the routines in https://rosettacode.org/wiki/Knuth_shuffle#FreeBASIC
function gus( i as long, strat as boolean ) as long
if strat then return i
return 1+int(rnd*100)
end function
sub trials( byref c_success as long, byref c_fail as long, byval strat as boolean )
dim as long i, j, k, guess, drawer(1 to 100)
for i = 1 to 100
drawer(i) = i
next i
for j = 1 to 1000000 'one million trials of prisoners
knuth_up( drawer() ) 'shuffles the cards in the drawers
for i = 1 to 100 'prisoner number
guess = gus(i, strat)
for k = 1 to 50 'each prisoner gets 50 tries
if drawer(guess) = i then goto next_prisoner
guess = gus(drawer(guess), strat)
next k
c_fail += 1
goto next_trial
next_prisoner:
next i
c_success += 1
next_trial:
next j
end sub
randomize timer
dim as long c_fail=0, c_success=0
trials( c_success, c_fail, false )
print using "For prisoners guessing randomly we had ####### successes and ####### failures.";c_success;c_fail
c_success = 0
c_fail = 0
trials( c_success, c_fail, true )
print using "For prisoners using the strategy we had ####### successes and ####### failures.";c_success;c_fail |
http://rosettacode.org/wiki/21_game | 21 game | 21 game
You are encouraged to solve this task according to the task description, using any language you may know.
21 is a two player game, the game is played by choosing
a number (1, 2, or 3) to be added to the running total.
The game is won by the player whose chosen number causes the running total
to reach exactly 21.
The running total starts at zero.
One player will be the computer.
Players alternate supplying a number to be added to the running total.
Task
Write a computer program that will:
do the prompting (or provide a button menu),
check for errors and display appropriate error messages,
do the additions (add a chosen number to the running total),
display the running total,
provide a mechanism for the player to quit/exit/halt/stop/close the program,
issue a notification when there is a winner, and
determine who goes first (maybe a random or user choice, or can be specified when the game begins).
| #Visual_Basic_.NET | Visual Basic .NET | ' Game 21 in VB.NET - an example for Rosetta Code
Class MainWindow
Private Const GOAL As Integer = 21
Private total As Integer = 0
Private random As New Random
Private Sub Update(box As TextBox, player As String, move As Integer)
total = total + move
box.Text = move
boxTotal.Text = total
If total + 1 > GOAL Then button1.IsEnabled = False
If total + 2 > GOAL Then button2.IsEnabled = False
If total + 3 > GOAL Then button3.IsEnabled = False
If total = GOAL Then
winner.Content = $"The winner is {player}."
End If
End Sub
Private Sub Ai()
Dim move As Integer = 1
For i = 1 To 3
If (total + i - 1) Mod 4 = 0 Then move = i
Next i
For i = 1 To 3
If total + i = GOAL Then move = i
Next i
Update(boxAI, "AI", move)
End Sub
Private Sub Choice(sender As Object, e As RoutedEventArgs) _
Handles button1.Click, button2.Click, button3.Click
Update(boxHuman, "human", sender.Content)
If total < GOAL Then Ai()
End Sub
' StartGame method handles both OnLoad (WM_INIT?) event
' as well as the restart of the game after user press the 'restart' button.
'
Private Sub StartGame(sender As Object, e As RoutedEventArgs) Handles restart.Click
total = 0
boxAI.Text = ""
boxHuman.Text = ""
boxTotal.Text = ""
'first.Content = "" ' It is not necessary, see below.
winner.Content = ""
button1.IsEnabled = True
button2.IsEnabled = True
button3.IsEnabled = True
' The random.Next(2) return pseudorandomly either 0 or 1. Generally
' random.Next(n) Return a value from 0 (inclusive) To n - 1 (inclusive).
'
If random.Next(2) = 0 Then
first.Content = "First player is AI player."
Ai()
Else
first.Content = "First player is human player."
End If
End Sub
End Class |
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
| #Kotlin | Kotlin | // version 1.1.3
import java.util.Random
const val N_CARDS = 4
const val SOLVE_GOAL = 24
const val MAX_DIGIT = 9
class Frac(val num: Int, val den: Int)
enum class OpType { NUM, ADD, SUB, MUL, DIV }
class Expr(
var op: OpType = OpType.NUM,
var left: Expr? = null,
var right: Expr? = null,
var value: Int = 0
)
fun showExpr(e: Expr?, prec: OpType, isRight: Boolean) {
if (e == null) return
val op = when (e.op) {
OpType.NUM -> { print(e.value); return }
OpType.ADD -> " + "
OpType.SUB -> " - "
OpType.MUL -> " x "
OpType.DIV -> " / "
}
if ((e.op == prec && isRight) || e.op < prec) print("(")
showExpr(e.left, e.op, false)
print(op)
showExpr(e.right, e.op, true)
if ((e.op == prec && isRight) || e.op < prec) print(")")
}
fun evalExpr(e: Expr?): Frac {
if (e == null) return Frac(0, 1)
if (e.op == OpType.NUM) return Frac(e.value, 1)
val l = evalExpr(e.left)
val r = evalExpr(e.right)
return when (e.op) {
OpType.ADD -> Frac(l.num * r.den + l.den * r.num, l.den * r.den)
OpType.SUB -> Frac(l.num * r.den - l.den * r.num, l.den * r.den)
OpType.MUL -> Frac(l.num * r.num, l.den * r.den)
OpType.DIV -> Frac(l.num * r.den, l.den * r.num)
else -> throw IllegalArgumentException("Unknown op: ${e.op}")
}
}
fun solve(ea: Array<Expr?>, len: Int): Boolean {
if (len == 1) {
val final = evalExpr(ea[0])
if (final.num == final.den * SOLVE_GOAL && final.den != 0) {
showExpr(ea[0], OpType.NUM, false)
return true
}
}
val ex = arrayOfNulls<Expr>(N_CARDS)
for (i in 0 until len - 1) {
for (j in i + 1 until len) ex[j - 1] = ea[j]
val node = Expr()
ex[i] = node
for (j in i + 1 until len) {
node.left = ea[i]
node.right = ea[j]
for (k in OpType.values().drop(1)) {
node.op = k
if (solve(ex, len - 1)) return true
}
node.left = ea[j]
node.right = ea[i]
node.op = OpType.SUB
if (solve(ex, len - 1)) return true
node.op = OpType.DIV
if (solve(ex, len - 1)) return true
ex[j] = ea[j]
}
ex[i] = ea[i]
}
return false
}
fun solve24(n: IntArray) =
solve (Array(N_CARDS) { Expr(value = n[it]) }, N_CARDS)
fun main(args: Array<String>) {
val r = Random()
val n = IntArray(N_CARDS)
for (j in 0..9) {
for (i in 0 until N_CARDS) {
n[i] = 1 + r.nextInt(MAX_DIGIT)
print(" ${n[i]}")
}
print(": ")
println(if (solve24(n)) "" else "No solution")
}
} |
http://rosettacode.org/wiki/15_puzzle_game | 15 puzzle game |
Task
Implement the Fifteen Puzzle Game.
The 15-puzzle is also known as:
Fifteen Puzzle
Gem Puzzle
Boss Puzzle
Game of Fifteen
Mystic Square
14-15 Puzzle
and some others.
Related Tasks
15 Puzzle Solver
16 Puzzle Game
| #C | C | /* RosettaCode: Fifteen puzle game, C89, plain vanillia TTY, MVC, § 22 */
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 4
#define M 4
enum Move{UP,DOWN,LEFT,RIGHT};int hR;int hC;int cc[N][M];const int nS=100;int
update(enum Move m){const int dx[]={0,0,-1,1};const int dy[]={-1,1,0,0};int i=hR
+dy[m];int j=hC+dx[m];if(i>= 0&&i<N&&j>=0&&j<M){cc[hR][hC]=cc[i][j];cc[i][j]=0;
hR=i;hC=j;return 1;}return 0;}void setup(void){int i,j,k;for(i=0;i<N;i++)for(j=0
;j<M;j++)cc[i][j]=i*M+j+1;cc[N-1][M-1]=0;hR=N-1;hC=M-1;k=0;while(k<nS)k+=update(
(enum Move)(rand()%4));}int isEnd(void){int i,j; int k=1;for(i=0;i<N;i++)for(j=0
;j<M;j++)if((k<N*M)&&(cc[i][j]!=k++))return 0;return 1;}void show(){int i,j;
putchar('\n');for(i=0;i<N;i++)for(j=0;j<M;j++){if(cc[i][j])printf(j!=M-1?" %2d "
:" %2d \n",cc[i][j]);else printf(j!=M-1?" %2s ":" %2s \n", "");}putchar('\n');}
void disp(char* s){printf("\n%s\n", s);}enum Move get(void){int c;for(;;){printf
("%s","enter u/d/l/r : ");c=getchar();while(getchar()!='\n');switch(c){case 27:
exit(0);case'd':return UP;case'u':return DOWN;case'r':return LEFT;case'l':return
RIGHT;}}}void pause(void){getchar();}int main(void){srand((unsigned)time(NULL));
do setup();while(isEnd());show();while(!isEnd()){update(get());show();}disp(
"You win"); pause();return 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.
| #Elixir | Elixir | defmodule Game2048 do
@size 4
@range 0..@size-1
def play(goal \\ 2048), do: setup() |> play(goal)
defp play(board, goal) do
show(board)
cond do
goal in Map.values(board) ->
IO.puts "You win!"
exit(:normal)
0 in Map.values(board) or combinable?(board) ->
moved = move(board, keyin())
if moved == board, do: play(board, goal), else: add_tile(moved) |> play(goal)
true ->
IO.puts "Game Over!"
exit(:normal)
end
end
defp setup do
(for i <- @range, j <- @range, into: %{}, do: {{i,j},0})
|> add_tile
|> add_tile
end
defp add_tile(board) do
position = blank_space(board) |> Enum.random
tile = if :rand.uniform(10)==1, do: 4, else: 2
%{board | position => tile}
end
defp blank_space(board) do
for {key, 0} <- board, do: key
end
defp keyin do
key = IO.gets("key in wasd or q: ")
case String.first(key) do
"w" -> :up
"a" -> :left
"s" -> :down
"d" -> :right
"q" -> exit(:normal)
_ -> keyin()
end
end
defp move(board, :up) do
Enum.reduce(@range, board, fn j,acc ->
Enum.map(@range, fn i -> acc[{i,j}] end)
|> move_and_combine
|> Enum.with_index
|> Enum.reduce(acc, fn {v,i},map -> Map.put(map, {i,j}, v) end)
end)
end
defp move(board, :down) do
Enum.reduce(@range, board, fn j,acc ->
Enum.map(@size-1..0, fn i -> acc[{i,j}] end)
|> move_and_combine
|> Enum.reverse
|> Enum.with_index
|> Enum.reduce(acc, fn {v,i},map -> Map.put(map, {i,j}, v) end)
end)
end
defp move(board, :left) do
Enum.reduce(@range, board, fn i,acc ->
Enum.map(@range, fn j -> acc[{i,j}] end)
|> move_and_combine
|> Enum.with_index
|> Enum.reduce(acc, fn {v,j},map -> Map.put(map, {i,j}, v) end)
end)
end
defp move(board, :right) do
Enum.reduce(@range, board, fn i,acc ->
Enum.map(@size-1..0, fn j -> acc[{i,j}] end)
|> move_and_combine
|> Enum.reverse
|> Enum.with_index
|> Enum.reduce(acc, fn {v,j},map -> Map.put(map, {i,j}, v) end)
end)
end
defp move_and_combine(tiles) do
(Enum.filter(tiles, &(&1>0)) ++ [0,0,0,0])
|> Enum.take(@size)
|> case do
[a,a,b,b] -> [a*2, b*2, 0, 0]
[a,a,b,c] -> [a*2, b, c, 0]
[a,b,b,c] -> [a, b*2, c, 0]
[a,b,c,c] -> [a, b, c*2, 0]
x -> x
end
end
defp combinable?(board) do
Enum.any?(for i <- @range, j <- 0..@size-2, do: board[{i,j}]==board[{i,j+1}]) or
Enum.any?(for j <- @range, i <- 0..@size-2, do: board[{i,j}]==board[{i+1,j}])
end
@frame String.duplicate("+----", @size) <> "+"
@format (String.duplicate("|~4w", @size) <> "|") |> to_charlist # before 1.3 to_char_list
defp show(board) do
Enum.each(@range, fn i ->
IO.puts @frame
row = for j <- @range, do: board[{i,j}]
IO.puts (:io_lib.fwrite @format, row) |> to_string |> String.replace(" 0|", " |")
end)
IO.puts @frame
end
end
Game2048.play 512 |
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
| #SQL_PL | SQL PL |
--#SET TERMINATOR @
SET SERVEROUTPUT ON @
CREATE TABLE ALL_INTS (
V INTEGER
)@
CREATE TABLE RESULTS (
A INTEGER,
B INTEGER,
C INTEGER,
D INTEGER,
E INTEGER,
F INTEGER,
G INTEGER
)@
CREATE OR REPLACE PROCEDURE FOUR_SQUARES(
IN LO INTEGER,
IN HI INTEGER,
IN UNIQ SMALLINT,
--IN UNIQ BOOLEAN,
IN SHOW SMALLINT)
--IN SHOW BOOLEAN)
BEGIN
DECLARE A INTEGER;
DECLARE B INTEGER;
DECLARE C INTEGER;
DECLARE D INTEGER;
DECLARE E INTEGER;
DECLARE F INTEGER;
DECLARE G INTEGER;
DECLARE OUT_LINE VARCHAR(2000);
DECLARE I SMALLINT;
DECLARE SOLUTIONS INTEGER;
DECLARE UORN VARCHAR(2000);
SET SOLUTIONS = 0;
DELETE FROM ALL_INTS;
DELETE FROM RESULTS;
SET I = LO;
WHILE (I <= HI) DO
INSERT INTO ALL_INTS VALUES (I);
SET I = I + 1;
END WHILE;
COMMIT;
-- Computes unique solutions.
IF (UNIQ = 0) THEN
--IF (UNIQ = TRUE) THEN
INSERT INTO RESULTS
SELECT
A.V A, B.V B, C.V C, D.V D, E.V E, F.V F, G.V G
FROM
ALL_INTS A, ALL_INTS B, ALL_INTS C, ALL_INTS D, ALL_INTS E, ALL_INTS F,
ALL_INTS G
WHERE
A.V NOT IN (B.V, C.V, D.V, E.V, F.V, G.V)
AND B.V NOT IN (C.V, D.V, E.V, F.V, G.V)
AND C.V NOT IN (D.V, E.V, F.V, G.V)
AND D.V NOT IN (E.V, F.V, G.V)
AND E.V NOT IN (F.V, G.V)
AND F.V NOT IN (G.V)
AND A.V = C.V + D.V
AND G.V = D.V + E.V
AND B.V = E.V + F.V - C.V
ORDER BY
A, B, C, D, E, F, G;
SET UORN = ' unique solutions in ';
ELSE
-- Compute non-unique solutions.
INSERT INTO RESULTS
SELECT
A.V A, B.V B, C.V C, D.V D, E.V E, F.V F, G.V G
FROM
ALL_INTS A, ALL_INTS B, ALL_INTS C, ALL_INTS D, ALL_INTS E, ALL_INTS F,
ALL_INTS G
WHERE
A.V = C.V + D.V
AND G.V = D.V + E.V
AND B.V = E.V + F.V - C.V
ORDER BY
A, B, C, D, E, F, G;
SET UORN = ' non-unique solutions in ';
END IF;
COMMIT;
-- Counts the possible solutions.
FOR v AS c CURSOR FOR
SELECT
A, B, C, D, E, F, G
FROM RESULTS
ORDER BY
A, B, C, D, E, F, G
DO
SET SOLUTIONS = SOLUTIONS + 1;
-- Shows the results.
IF (SHOW = 0) THEN
--IF (SHOW = TRUE) THEN
SET OUT_LINE = A || ' ' || B || ' ' || C || ' ' || D || ' ' || E || ' '
|| F ||' ' || G;
CALL DBMS_OUTPUT.PUT_LINE(OUT_LINE);
END IF;
END FOR;
SET OUT_LINE = SOLUTIONS || UORN || LO || ' to ' || HI;
CALL DBMS_OUTPUT.PUT_LINE(OUT_LINE);
END
@
CALL FOUR_SQUARES(1, 7, 0, 0)@
CALL FOUR_SQUARES(3, 9, 0, 0)@
CALL FOUR_SQUARES(0, 9, 1, 1)@
|
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
| #Astro | Astro | fun bottles(n): match __args__:
(0) => "No more bottles"
(1) => "1 bottle"
(_) => "$n bottles"
for n in 99..-1..1:
print @format"""
{bottles n} of beer on the wall
{bottles n} of beer
Take one down, pass it around
{bottles n-1} of beer on the wall\n
""" |
http://rosettacode.org/wiki/24_game | 24 game | The 24 Game tests one's mental arithmetic.
Task
Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed.
The program should prompt for the player to enter an arithmetic expression using just those, and all of those four digits, used exactly once each. The program should check then evaluate the expression.
The goal is for the player to enter an expression that (numerically) evaluates to 24.
Only the following operators/functions are allowed: multiplication, division, addition, subtraction
Division should use floating point or rational arithmetic, etc, to preserve remainders.
Brackets are allowed, if using an infix expression evaluator.
Forming multiple digit numbers from the supplied digits is disallowed. (So an answer of 12+12 when given 1, 2, 2, and 1 is wrong).
The order of the digits when given does not have to be preserved.
Notes
The type of expression evaluator used is not mandated. An RPN evaluator is equally acceptable for example.
The task is not for the program to generate the expression, or test whether an expression is even possible.
Related tasks
24 game/Solve
Reference
The 24 Game on h2g2.
| #Gosu | Gosu |
uses java.lang.Double
uses java.lang.Integer
uses java.util.ArrayList
uses java.util.List
uses java.util.Scanner
uses java.util.Stack
function doEval( scanner : Scanner, allowed : List<Integer> ) : double {
var stk = new Stack<Double>()
while( scanner.hasNext() ) {
if( scanner.hasNextInt() ) {
var n = scanner.nextInt()
// Make sure they're allowed to use n
if( n <= 0 || n >= 10 ) {
print( n + " isn't allowed" )
return 0
}
var idx = allowed.indexOf( n )
if( idx == -1 ) {
print( "You aren't allowed to use so many " + n + "s!" )
return 0
}
// Add the input number to the stack
stk.push( new Double( n ) )
// Mark n as used
allowed.remove( idx )
} else {
// It has to be an operator...
if( stk.size() < 2 ) {
print( "Invalid Expression: Stack underflow!" )
return 0
}
// Gets the next operator as a single character token
var s = scanner.next("[\\+-/\\*]")
// Get the operands
var r = stk.pop().doubleValue()
var l = stk.pop().doubleValue()
// Determine which operator and invoke it
if( s.equals( "+" ) ) {
stk.push( new Double( l + r ) )
} else if( s.equals( "-" ) ) {
stk.push( new Double( l - r ) )
} else if( s.equals( "*" ) ) {
stk.push( new Double( l * r ) )
} else if( s.equals( "/" ) ) {
if( r == 0.0 ) {
print( "Invalid Expression: Division by zero!" )
return 0
}
stk.push( new Double( l / r ) )
} else {
print( "Internal Error: looking for operator yielded '" + s + "'" )
return 0
}
}
}
// Did they skip any numbers?
if( allowed.size() != 0 ) {
print( "You didn't use ${allowed}" )
return 0
}
// Did they use enough operators?
if( stk.size() != 1 ) {
print( "Invalid Expression: Not enough operators!" )
return 0
}
return stk.pop().doubleValue()
}
// Pick 4 random numbers from [1..9]
var nums = new ArrayList<Integer>()
var gen = new java.util.Random( new java.util.Date().getTime() )
for( i in 0..3 ) {
nums.add( gen.nextInt(9) + 1 )
}
// Prompt the user
print( "Using addition, subtraction, multiplication and division, write an" )
print( "expression that evaluates to 24 using" )
print( "${nums.get(0)}, ${nums.get(1)}, ${nums.get(2)} and ${nums.get(3)}" )
print( "" )
print( "Please enter your expression in RPN" )
// Build a tokenizer over a line of input
var sc = new Scanner( new java.io.BufferedReader( new java.io.InputStreamReader( java.lang.System.in ) ).readLine() )
// eval the expression
var val = doEval( sc, nums )
// winner?
if( java.lang.Math.abs( val - 24.0 ) < 0.001 ) {
print( "You win!" )
} else {
print( "You lose!" )
}
|
http://rosettacode.org/wiki/A%2BB | A+B | A+B ─── a classic problem in programming contests, it's given so contestants can gain familiarity with the online judging system being used.
Task
Given two integers, A and B.
Their sum needs to be calculated.
Input data
Two integers are written in the input stream, separated by space(s):
(
−
1000
≤
A
,
B
≤
+
1000
)
{\displaystyle (-1000\leq A,B\leq +1000)}
Output data
The required output is one integer: the sum of A and B.
Example
input
output
2 2
4
3 2
5
| #DCL | DCL | $ read sys$command line
$ a = f$element( 0, " ", line )
$ b = f$element( 1, " ", line )
$ write sys$output a, "+", b, "=", 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.
| #Wren | Wren | // To use recursion definition and declaration must be on separate lines
var Ackermann
Ackermann = Fn.new {|m, n|
if (m == 0) return n + 1
if (n == 0) return Ackermann.call(m - 1, 1)
return Ackermann.call(m - 1, Ackermann.call(m, n - 1))
}
var pairs = [ [1, 3], [2, 3], [3, 3], [1, 5], [2, 5], [3, 5] ]
for (pair in pairs) {
var p1 = pair[0]
var p2 = pair[1]
System.print("A[%(p1), %(p2)] = %(Ackermann.call(p1, p2))")
} |
http://rosettacode.org/wiki/ABC_problem | ABC problem | ABC problem
You are encouraged to solve this task according to the task description, using any language you may know.
You are given a collection of ABC blocks (maybe like the ones you had when you were a kid).
There are twenty blocks with two letters on each block.
A complete alphabet is guaranteed amongst all sides of the blocks.
The sample collection of blocks:
(B O)
(X K)
(D Q)
(C P)
(N A)
(G T)
(R E)
(T G)
(Q D)
(F S)
(J W)
(H U)
(V I)
(A N)
(O B)
(E R)
(F S)
(L Y)
(P C)
(Z M)
Task
Write a function that takes a string (word) and determines whether the word can be spelled with the given collection of blocks.
The rules are simple:
Once a letter on a block is used that block cannot be used again
The function should be case-insensitive
Show the output on this page for the following 7 words in the following example
Example
>>> can_make_word("A")
True
>>> can_make_word("BARK")
True
>>> can_make_word("BOOK")
False
>>> can_make_word("TREAT")
True
>>> can_make_word("COMMON")
False
>>> can_make_word("SQUAD")
True
>>> can_make_word("CONFUSE")
True
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Java | Java | import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class ABC {
public static void main(String[] args) {
List<String> blocks = Arrays.asList(
"BO", "XK", "DQ", "CP", "NA",
"GT", "RE", "TG", "QD", "FS",
"JW", "HU", "VI", "AN", "OB",
"ER", "FS", "LY", "PC", "ZM");
for (String word : Arrays.asList("", "A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "CONFUSE")) {
System.out.printf("%s: %s%n", word.isEmpty() ? "\"\"" : word, canMakeWord(word, blocks));
}
}
public static boolean canMakeWord(String word, List<String> blocks) {
if (word.isEmpty())
return true;
char c = word.charAt(0);
for (int i = 0; i < blocks.size(); i++) {
String b = blocks.get(i);
if (b.charAt(0) != c && b.charAt(1) != c)
continue;
Collections.swap(blocks, 0, i);
if (canMakeWord(word.substring(1), blocks.subList(1, blocks.size())))
return true;
Collections.swap(blocks, 0, i);
}
return false;
}
} |
http://rosettacode.org/wiki/100_prisoners | 100 prisoners |
The Problem
100 prisoners are individually numbered 1 to 100
A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside.
Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start.
Prisoners start outside the room
They can decide some strategy before any enter the room.
Prisoners enter the room one by one, can open a drawer, inspect the card number in the drawer, then close the drawer.
A prisoner can open no more than 50 drawers.
A prisoner tries to find his own number.
A prisoner finding his own number is then held apart from the others.
If all 100 prisoners find their own numbers then they will all be pardoned. If any don't then all sentences stand.
The task
Simulate several thousand instances of the game where the prisoners randomly open drawers
Simulate several thousand instances of the game where the prisoners use the optimal strategy mentioned in the Wikipedia article, of:
First opening the drawer whose outside number is his prisoner number.
If the card within has his number then he succeeds otherwise he opens the drawer with the same number as that of the revealed card. (until he opens his maximum).
Show and compare the computed probabilities of success for the two strategies, here, on this page.
References
The unbelievable solution to the 100 prisoner puzzle standupmaths (Video).
wp:100 prisoners problem
100 Prisoners Escape Puzzle DataGenetics.
Random permutation statistics#One hundred prisoners on Wikipedia.
| #Gambas | Gambas | ' Gambas module file
Public DrawerArray As Long[]
Public NumberFromDrawer As Long
Public FoundOwnNumber As Long
Public Sub Main()
Dim NumberOfPrisoners As Long
Dim Selections As Long
Dim Tries As Long
Print "Number of prisoners (default, 100)?"
Try Input NumberOfPrisoners
If Error Then NumberOfPrisoners = 100
Print "Number of selections (default, half of prisoners)?"
Try Input Selections
If Error Then Selections = NumberOfPrisoners / 2
Print "Number of tries (default, 1000)?"
Try Input Tries
If Error Then Tries = 1000
Dim AllFoundOptimal As Long = 0
Dim AllFoundRandom As Long = 0
Dim AllFoundRandomMem As Long = 0
Dim i As Long
Dim OptimalCount As Long
Dim RandomCount As Long
Dim RandomMenCount As Long
Dim fStart As Float = Timer
For i = 1 To Tries
OptimalCount = HundredPrisoners_Optimal(NumberOfPrisoners, Selections)
RandomCount = HundredPrisoners_Random(NumberOfPrisoners, Selections)
RandomMenCount = HundredPrisoners_Random_Mem(NumberOfPrisoners, Selections)
If OptimalCount = NumberOfPrisoners Then AllFoundOptimal += 1
If RandomCount = NumberOfPrisoners Then AllFoundRandom += 1
If RandomMenCount = NumberOfPrisoners Then AllFoundRandomMem += 1
Next
Dim fTime As Float = Timer - fStart
fTime = Round(ftime, -1)
Print
Print "Result with " & NumberOfPrisoners & " prisoners, " & Selections & " selections and " & Tries & " tries. "
Print
Print "Optimal: " & AllFoundOptimal & " of " & Tries & ": " & Str(AllFoundOptimal / Tries * 100) & " %"
Print "Random: " & AllFoundRandom & " of " & Tries & ": " & Str(AllFoundRandom / Tries * 100) & " %"
Print "RandomMem: " & AllFoundRandomMem & " of " & Tries & ": " & Str(AllFoundRandomMem / Tries * 100) & " %"
Print
Print "Elapsed Time: " & fTime & " sec"
Print
Print "Trials/sec: " & Round(Tries / fTime, -1)
End
Function HundredPrisoners_Optimal(NrPrisoners As Long, NrSelections As Long) As Long
DrawerArray = New Long[NrPrisoners]
Dim Counter As Long
For Counter = 0 To DrawerArray.Max
DrawerArray[Counter] = Counter + 1
Next
DrawerArray.Shuffle()
Dim i As Long
Dim j As Long
FoundOwnNumber = 0
For i = 1 To NrPrisoners
For j = 1 To NrSelections
If j = 1 Then NumberFromDrawer = DrawerArray[i - 1]
If NumberFromDrawer = i Then
FoundOwnNumber += 1
Break
Endif
NumberFromDrawer = DrawerArray[NumberFromDrawer - 1]
Next
Next
Return FoundOwnNumber
End
Function HundredPrisoners_Random(NrPrisoners As Long, NrSelections As Long) As Long
Dim RandomDrawer As Long
Dim Counter As Long
DrawerArray = New Long[NrPrisoners]
For Counter = 0 To DrawerArray.Max
DrawerArray[Counter] = Counter + 1
Next
DrawerArray.Shuffle()
Dim i As Long
Dim j As Long
FoundOwnNumber = 0
Randomize
For i = 1 To NrPrisoners
For j = 1 To NrSelections
RandomDrawer = CLong(Rand(NrPrisoners - 1))
NumberFromDrawer = DrawerArray[RandomDrawer]
If NumberFromDrawer = i Then
FoundOwnNumber += 1
Break
Endif
Next
Next
Return FoundOwnNumber
End
Function HundredPrisoners_Random_Mem(NrPrisoners As Long, NrSelections As Long) As Long
Dim SelectionArray As New Long[NrPrisoners]
Dim Counter As Long
DrawerArray = New Long[NrPrisoners]
For Counter = 0 To DrawerArray.Max
DrawerArray[Counter] = Counter + 1
Next
For Counter = 0 To SelectionArray.Max
SelectionArray[Counter] = Counter + 1
Next
DrawerArray.Shuffle()
Dim i As Long
Dim j As Long
FoundOwnNumber = 0
For i = 1 To NrPrisoners
SelectionArray.Shuffle()
For j = 1 To NrSelections
NumberFromDrawer = DrawerArray[SelectionArray[j - 1] - 1]
If NumberFromDrawer = i Then
FoundOwnNumber += 1
Break
Endif
NumberFromDrawer = DrawerArray[NumberFromDrawer - 1]
Next
Next
Return FoundOwnNumber
End |
http://rosettacode.org/wiki/21_game | 21 game | 21 game
You are encouraged to solve this task according to the task description, using any language you may know.
21 is a two player game, the game is played by choosing
a number (1, 2, or 3) to be added to the running total.
The game is won by the player whose chosen number causes the running total
to reach exactly 21.
The running total starts at zero.
One player will be the computer.
Players alternate supplying a number to be added to the running total.
Task
Write a computer program that will:
do the prompting (or provide a button menu),
check for errors and display appropriate error messages,
do the additions (add a chosen number to the running total),
display the running total,
provide a mechanism for the player to quit/exit/halt/stop/close the program,
issue a notification when there is a winner, and
determine who goes first (maybe a random or user choice, or can be specified when the game begins).
| #Vlang | Vlang | import os
import rand
import rand.seed
import strconv
fn get_choice(mut total &int) bool {
for {
text := os.input("Your choice 1 to 3 : ")
if text == "q" || text == "Q" {
return true
}
input := strconv.atoi(text) or {-1}
if input == -1 {
println("Invalid number, try again")
continue
}
new_total := *total + input
match true {
input < 1 || input > 3 {
println("Out of range, try again")
}
new_total > 21 {
println("Too big, try again")
}
else {
total = new_total
println("Running total is now ${*total}")
return false
}
}
}
return false
}
fn main() {
rand.seed(seed.time_seed_array(2))
mut computer := rand.intn(2) or {0} != 0
println("Enter q to quit at any time\n")
if computer {
println("The computer will choose first")
} else {
println("You will choose first")
}
println("\nRunning total is now 0\n")
mut choice := 0
mut total := 0
for round := 1; ; round++ {
println("ROUND $round:\n")
for i := 0; i < 2; i++ {
if computer {
if total < 18 {
choice = 1 + rand.intn(3) or {1}
} else {
choice = 21 - total
}
total += choice
println("The computer chooses $choice")
println("Running total is now $total")
if total == 21 {
println("\nSo, commiserations, the computer has won!")
return
}
} else {
quit := get_choice(mut total)
if quit {
println("OK, quitting the game")
return
}
if total == 21 {
println("\nSo, congratulations, you've won!")
return
}
}
println('')
computer = !computer
}
}
} |
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
| #Liberty_BASIC | Liberty BASIC | dim d(4)
input "Enter 4 digits: "; a$
nD=0
for i =1 to len(a$)
c$=mid$(a$,i,1)
if instr("123456789",c$) then
nD=nD+1
d(nD)=val(c$)
end if
next
'for i = 1 to 4
' print d(i);
'next
'precompute permutations. Dumb way.
nPerm = 1*2*3*4
dim perm(nPerm, 4)
n = 0
for i = 1 to 4
for j = 1 to 4
for k = 1 to 4
for l = 1 to 4
'valid permutation (no dupes?)
if i<>j and i<>k and i<>l _
and j<>k and j<>l _
and k<>l then
n=n+1
'
' perm(n,1)=i
' perm(n,2)=j
' perm(n,3)=k
' perm(n,4)=l
'actually, we can as well permute given digits
perm(n,1)=d(i)
perm(n,2)=d(j)
perm(n,3)=d(k)
perm(n,4)=d(l)
end if
next
next
next
next
'check if permutations look OK. They are
'for i =1 to n
' print i,
' for j =1 to 4: print perm(i,j);:next
' print
'next
'possible brackets
NBrackets = 11
dim Brakets$(NBrackets)
DATA "4#4#4#4"
DATA "(4#4)#4#4"
DATA "4#(4#4)#4"
DATA "4#4#(4#4)"
DATA "(4#4)#(4#4)"
DATA "(4#4#4)#4"
DATA "4#(4#4#4)"
DATA "((4#4)#4)#4"
DATA "(4#(4#4))#4"
DATA "4#((4#4)#4)"
DATA "4#(4#(4#4))"
for i = 1 to NBrackets
read Tmpl$: Brakets$(i) = Tmpl$
next
'operations: full search
count = 0
Ops$="+ - * /"
dim Op$(3)
For op1=1 to 4
Op$(1)=word$(Ops$,op1)
For op2=1 to 4
Op$(2)=word$(Ops$,op2)
For op3=1 to 4
Op$(3)=word$(Ops$,op3)
'print "*"
'substitute all brackets
for t = 1 to NBrackets
Tmpl$=Brakets$(t)
'print , Tmpl$
'now, substitute all digits: permutations.
for p = 1 to nPerm
res$= ""
nOp=0
nD=0
for i = 1 to len(Tmpl$)
c$ = mid$(Tmpl$, i, 1)
select case c$
case "#" 'operations
nOp = nOp+1
res$ = res$+Op$(nOp)
case "4" 'digits
nD = nOp+1
res$ = res$; perm(p,nD)
case else 'brackets goes here
res$ = res$+ c$
end select
next
'print,, res$
'eval here
if evalWithErrCheck(res$) = 24 then
print "24 = ";res$
end 'comment it out if you want to see all versions
end if
count = count + 1
next
next
Next
Next
next
print "If you see this, probably task cannot be solved with these digits"
'print count
end
function evalWithErrCheck(expr$)
on error goto [handler]
evalWithErrCheck=eval(expr$)
exit function
[handler]
end function |
http://rosettacode.org/wiki/15_puzzle_game | 15 puzzle game |
Task
Implement the Fifteen Puzzle Game.
The 15-puzzle is also known as:
Fifteen Puzzle
Gem Puzzle
Boss Puzzle
Game of Fifteen
Mystic Square
14-15 Puzzle
and some others.
Related Tasks
15 Puzzle Solver
16 Puzzle Game
| #C.23 | C# | using System;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
public class FifteenPuzzle
{
const int gridSize = 4; //Standard 15 puzzle is 4x4
const bool evenSized = gridSize % 2 == 0;
const int blockCount = gridSize * gridSize;
const int last = blockCount - 1;
const int buttonSize = 50;
const int buttonMargin = 3; //default = 3
const int formEdge = 9;
static readonly Random rnd = new Random();
static readonly Font buttonFont = new Font("Arial", 15.75F, FontStyle.Regular, GraphicsUnit.Point, ((byte)(0)));
readonly Button[] buttons = new Button[blockCount];
readonly int[] grid = new int[blockCount];
readonly int[] positionOf = new int[blockCount];
int moves = 0;
DateTime start;
public static void Main(string[] args)
{
FifteenPuzzle p = new FifteenPuzzle();
Form f = p.BuildForm();
Application.Run(f);
}
public FifteenPuzzle()
{
for (int i = 0; i < blockCount; i++) {
grid[i] = i;
positionOf[i] = i;
}
}
Form BuildForm()
{
Button startButton = new Button {
Font = new Font("Arial", 9.75F, FontStyle.Regular, GraphicsUnit.Point, ((byte)(0))),
Size = new Size(86, 23),
Location = new Point(formEdge,
(buttonSize + buttonMargin * 2) * gridSize + buttonMargin + formEdge),
Text = "New Game",
UseVisualStyleBackColor = true
};
startButton.Click += (sender, e) => Shuffle();
int size = buttonSize * gridSize + buttonMargin * gridSize * 2 + formEdge * 2;
Form form = new Form {
Text = "Fifteen",
ClientSize = new Size(width: size, height: size + buttonMargin * 2 + startButton.Height)
};
form.SuspendLayout();
for (int index = 0; index < blockCount; index++) {
Button button = new Button {
Font = buttonFont,
Size = new Size(buttonSize, buttonSize),
//Margin = new Padding(buttonMargin),
Text = (index + 1).ToString(),
UseVisualStyleBackColor = true
};
SetLocation(button, index);
form.Controls.Add(button);
buttons[index] = button;
int i = index;
button.Click += (sender, e) => ButtonClick(i);
}
form.Controls.Add(startButton);
form.ResumeLayout();
return form;
}
void ButtonClick(int i)
{
if (buttons[last].Visible) return;
int target = positionOf[i];
if (positionOf[i] / gridSize == positionOf[last] / gridSize) {
while (positionOf[last] < target) {
Swap(last, grid[positionOf[last] + 1]);
moves++;
}
while (positionOf[last] > target) {
Swap(last, grid[positionOf[last] - 1]);
moves++;
}
} else if (positionOf[i] % gridSize == positionOf[last] % gridSize) {
while (positionOf[last] < target) {
Swap(last, grid[positionOf[last] + gridSize]);
moves++;
}
while (positionOf[last] > target) {
Swap(last, grid[positionOf[last] - gridSize]);
moves++;
}
}
if (Solved()) {
TimeSpan elapsed = DateTime.Now - start;
elapsed = TimeSpan.FromSeconds(Math.Round(elapsed.TotalSeconds, 0));
buttons[last].Visible = true;
MessageBox.Show($"Solved in {moves} moves. Time: {elapsed}");
}
}
bool Solved() => Enumerable.Range(0, blockCount - 1).All(i => positionOf[i] == i);
static void SetLocation(Button button, int index)
{
int row = index / gridSize, column = index % gridSize;
button.Location = new Point(
(buttonSize + buttonMargin * 2) * column + buttonMargin + formEdge,
(buttonSize + buttonMargin * 2) * row + buttonMargin + formEdge);
}
void Shuffle()
{
for (int i = 0; i < blockCount; i++) {
int r = rnd.Next(i, blockCount);
int g = grid[r];
grid[r] = grid[i];
grid[i] = g;
}
for (int i = 0; i < blockCount; i++) {
positionOf[grid[i]] = i;
SetLocation(buttons[grid[i]], i);
}
if (!Solvable()) Swap(0, 1); //Swap any 2 blocks
buttons[last].Visible = false;
moves = 0;
start = DateTime.Now;
}
bool Solvable()
{
bool parity = true;
for (int i = 0; i < blockCount - 2; i++) {
for (int j = i + 1; j < blockCount - 1; j++) {
if (positionOf[j] < positionOf[i]) parity = !parity;
}
}
if (evenSized && positionOf[last] / gridSize % 2 == 0) parity = !parity;
return parity;
}
void Swap(int a, int b)
{
Point location = buttons[a].Location;
buttons[a].Location = buttons[b].Location;
buttons[b].Location = location;
int p = positionOf[a];
positionOf[a] = positionOf[b];
positionOf[b] = p;
grid[positionOf[a]] = a;
grid[positionOf[b]] = 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.
| #Elm | Elm | module Main exposing (..)
import Html exposing (Html, div, p, text, button, span, h2)
import Html.Attributes exposing (class, style)
import Html.Events exposing (onClick)
import Keyboard exposing (KeyCode)
import Random
import Tuple
main =
Html.program
{ init = ( { initialModel | waitingForRandom = True }, generateRandomTiles 2 )
, view = view
, update = update
, subscriptions = always (Keyboard.downs KeyPress)
}
-- MODEL
-- tiles either have a value (2, 4, 8, ...) or are empty
type alias Tile =
Maybe Int
type alias Model =
{ score : Int
, tiles : List Tile
, hasLost : Bool
, winKeepPlaying : Bool
, waitingForRandom : Bool -- prevent user from giving input while waiting for Random Cmd to return
}
initialModel : Model
initialModel =
{ score = 0, tiles = List.repeat 16 Nothing, waitingForRandom = False, hasLost = False, winKeepPlaying = False}
-- UPDATE
type alias RandomTileInfo =
( Int, Int )
type Msg
= KeyPress KeyCode
| AddRandomTiles (List RandomTileInfo)
| NewGame
| KeepPlaying
-- asks the random generator to generate the information required for later adding random tiles
-- generate a random position for the and value (4 10%, 2 90%) for each tile
-- this uses Random.pair and Random.list to get a variable number of such pairs with one Cmd
generateRandomTiles : Int -> Cmd Msg
generateRandomTiles num =
let
randomPosition =
Random.int 0 15
randomValue =
Random.int 1 10
|> Random.map
(\rnd ->
if rnd == 10 then
4
else
2
)
-- 10% chance
randomPositionAndValue =
Random.pair randomPosition randomValue
in
Random.list num randomPositionAndValue |> Random.generate AddRandomTiles
-- actually add a random tile to the model
addRandomTile : RandomTileInfo -> List Tile -> List Tile
addRandomTile ( newPosition, newValue ) tiles =
let
-- newPosition is a value between 0 and 15
-- go through the list and count the amount of empty tiles we've seen.
-- if we reached the newPosition % emptyTileCount'th empty tile, set its value to newValue
emptyTileCount =
List.filter ((==) Nothing) tiles |> List.length
-- if there are less than 16 empty tiles this is the number of empty tiles we pass
targetCount =
newPosition % emptyTileCount
set_ith_empty_tile tile ( countEmpty, newList ) =
case tile of
Just value ->
( countEmpty, (Just value) :: newList )
Nothing ->
if countEmpty == targetCount then
-- replace this empty tile with the new value
( countEmpty + 1, (Just newValue) :: newList )
else
( countEmpty + 1, Nothing :: newList )
in
List.foldr set_ith_empty_tile ( 0, [] ) tiles |> Tuple.second
-- core game mechanic: move numbers (to the left,
-- moving to the right is equivalent to moving left on the reversed array)
-- this function works on single columns/rows
moveNumbers : List Tile -> ( List Tile, Int )
moveNumbers tiles =
let
last =
List.head << List.reverse
-- init is to last what tail is to head
init =
List.reverse << List.drop 1 << List.reverse
doMove tile ( newTiles, addScore ) =
case tile of
-- omit empty tiles when shifting
Nothing ->
( newTiles, addScore )
Just value ->
case last newTiles of
-- if the last already moved tile ...
Just (Just value2) ->
-- ... has the same value, add a tile with the summed value
if value == value2 then
( (init newTiles) ++ [ Just (2 * value) ]
, addScore + 2 * value )
else
-- ... else just add the tile
( newTiles ++ [ Just value ], addScore )
_ ->
-- ... else just add the tile
( newTiles ++ [ Just value ], addScore )
( movedTiles, addScore ) =
List.foldl doMove ( [], 0 ) tiles
in
( movedTiles ++ List.repeat (4 - List.length movedTiles) Nothing, addScore )
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
-- new game button press
NewGame ->
if not model.waitingForRandom then
( { initialModel | waitingForRandom = True }, generateRandomTiles 2 )
else
( model, Cmd.none )
-- "keep playing" button on win screen
KeepPlaying ->
( { model | winKeepPlaying = True }, Cmd.none)
-- Random generator Cmd response
AddRandomTiles tileInfos ->
let
newTiles =
List.foldl addRandomTile model.tiles tileInfos
in
( { model | tiles = newTiles, waitingForRandom = False }, Cmd.none )
KeyPress code ->
let
-- zip list and indices, apply filter, unzip
indexedFilter func list =
List.map2 (,) (List.range 0 (List.length list - 1)) list
|> List.filter func
|> List.map Tuple.second
-- the i'th row (of 4) contains elements i*4, i*4+1, i*4+2, i*4+3
-- so all elements for which index//4 == i
i_th_row list i =
indexedFilter (((==) i) << (flip (//) 4) << Tuple.first) list
-- the i'th col (of 4) contain elements i, i+4, i+2*4, i+3*4
-- so all elements for which index%4 == i
i_th_col list i =
indexedFilter (((==) i) << (flip (%) 4) << Tuple.first) list
-- rows and columns of the grid
rows list =
List.map (i_th_row list) (List.range 0 3)
cols list =
List.map (i_th_col list) (List.range 0 3)
-- move each row or column and unzip the results from each call to moveNumbers
move =
List.unzip << List.map moveNumbers
moveReverse =
List.unzip << List.map (Tuple.mapFirst List.reverse << moveNumbers << List.reverse)
-- concat rows back into a flat array and sum all addScores
unrows =
Tuple.mapSecond List.sum << Tuple.mapFirst List.concat
-- turn columns back into a flat array and sum all addScores
uncols =
Tuple.mapSecond List.sum << Tuple.mapFirst (List.concat << cols << List.concat)
-- when shifting left or right each row can be (reverse-) shifted separately
-- when shifting up or down each column can be (reveerse-) shifted separately
( newTiles, addScore ) =
case code of
37 ->
-- left
unrows <| move <| rows model.tiles
38 ->
-- up
uncols <| move <| cols model.tiles
39 ->
-- right
unrows <| moveReverse <| rows model.tiles
40 ->
-- down
uncols <| moveReverse <| cols model.tiles
_ ->
( model.tiles, 0 )
containsEmptyTiles =
List.any ((==) Nothing)
containsAnySameNeighbours : List Tile -> Bool
containsAnySameNeighbours list =
let
tail = List.drop 1 list
init = List.reverse <| List.drop 1 <| List.reverse list
in
List.any (uncurry (==)) <| List.map2 (,) init tail
hasLost =
-- grid full
(not (containsEmptyTiles newTiles))
-- and no left/right move possible
&& (not <| List.any containsAnySameNeighbours <| rows newTiles)
-- and no up/down move possible
&& (not <| List.any containsAnySameNeighbours <| cols newTiles)
( cmd, waiting ) =
if List.all identity <| List.map2 (==) model.tiles newTiles then
( Cmd.none, False )
else
( generateRandomTiles 1, True )
score =
model.score + addScore
in
-- unsure whether this actually happens but regardless:
-- keep the program from accepting a new keyboard input when a new tile hasn't been spawned yet
if model.waitingForRandom then
( model, Cmd.none )
else
( { model | tiles = newTiles, waitingForRandom = waiting, score = score, hasLost = hasLost }, cmd )
-- VIEW
containerStyle : List ( String, String )
containerStyle =
[ ( "width", "450px" )
, ( "height", "450px" )
, ( "background-color", "#bbada0" )
, ( "float", "left" )
, ( "border-radius", "6px")
]
tileStyle : Int -> List ( String, String )
tileStyle value =
let
color =
case value of
0 ->
"#776e65"
2 ->
"#eee4da"
4 ->
"#ede0c8"
8 ->
"#f2b179"
16 ->
"#f59563"
32 ->
"#f67c5f"
64 ->
"#f65e3b"
128 ->
"#edcf72"
256 ->
"#edcc61"
512 ->
"#edc850"
1024 ->
"#edc53f"
2048 ->
"#edc22e"
_ ->
"#edc22e"
in
[ ( "width", "100px" )
, ( "height", "70px" )
, ( "background-color", color )
, ( "float", "left" )
, ( "margin-left", "10px" )
, ( "margin-top", "10px" )
, ( "padding-top", "30px" )
, ( "text-align", "center" )
, ( "font-size", "30px" )
, ( "font-weight", "bold" )
, ( "border-radius", "6px")
]
viewTile : Tile -> Html Msg
viewTile tile =
div [ style <| tileStyle <| Maybe.withDefault 0 tile ]
[ span [] [ text <| Maybe.withDefault "" <| Maybe.map toString tile ]
]
viewGrid : List Tile -> Html Msg
viewGrid tiles =
div [ style containerStyle ] <| List.map viewTile tiles
viewLost : Html Msg
viewLost =
div
[ style containerStyle ]
[ div
[ style [ ( "text-align", "center" ) ] ]
[ h2 [] [ text "You lost!" ]
]
]
viewWin : Html Msg
viewWin =
div
[ style containerStyle ]
[ div
[ style [ ( "text-align", "center" ) ] ]
[ h2 [] [ text "Congratulations, You won!" ]
, button
[ style [ ( "margin-bottom", "16px" ), ( "margin-top", "16px" ) ], onClick KeepPlaying ]
[ text "Keep playing" ]
]
]
view : Model -> Html Msg
view model =
div [ style [ ( "width", "450px" ) ] ]
[ p [ style [ ( "float", "left" ) ] ] [ text <| "Your Score: " ++ toString model.score ]
, button
[ style [ ( "margin-bottom", "16px" ), ( "margin-top", "16px" ), ( "float", "right" ) ], onClick NewGame ]
[ text "New Game" ]
, if model.hasLost then
viewLost
else if List.any ((==) (Just 2048)) model.tiles && not model.winKeepPlaying then
viewWin
else
viewGrid model.tiles
]
|
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
| #Stata | Stata | perm 7
rename * (a b c d e f g)
list if a==c+d & b+c==e+f & d+e==g, noobs sep(50)
+---------------------------+
| a b c d e f g |
|---------------------------|
| 3 7 2 1 5 4 6 |
| 4 5 3 1 6 2 7 |
| 4 7 1 3 2 6 5 |
| 5 6 2 3 1 7 4 |
| 6 4 1 5 2 3 7 |
| 6 4 5 1 2 7 3 |
| 7 2 6 1 3 5 4 |
| 7 3 2 5 1 4 6 |
+---------------------------+
foreach var of varlist _all {
replace `var'=`var'+2
}
list if a==c+d & b+c==e+f & d+e==g, noobs sep(50)
+---------------------------+
| a b c d e f g |
|---------------------------|
| 7 8 3 4 5 6 9 |
| 8 7 3 5 4 6 9 |
| 9 6 4 5 3 7 8 |
| 9 6 5 4 3 8 7 |
+---------------------------+
clear
set obs 10
gen b=_n-1
gen q=1
save temp, replace
rename b c
joinby q using temp
rename b d
joinby q using temp
rename b e
gen a=c+d
gen g=d+e
drop if a>9 | g>9
joinby q using temp
gen f=b+c-e
drop if f<0 | f>9
drop q
order a b c d e f g
erase temp.dta
count
2,860 |
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
| #Asymptote | Asymptote | // Rosetta Code problem: http://rosettacode.org/wiki/99_bottles_of_beer
// by Jjuanhdez, 05/2022
int bottles = 99;
for (int i = bottles; i > 0; --i) {
write(string(i), " bottles of beer on the wall,");
write(string(i), " bottles of beer.");
write("Take one down and pass it around,");
if (i == 1) {
write("no more bottles of beer on the wall...");
} else {
write(string(i-1), " bottles of beer on the wall...");
}
}
write("No more bottles of beer on the wall,");
write("no more bottles of beer.");
write("Go to the store and buy some more,");
write(" 99 bottles of beer on the wall."); |
http://rosettacode.org/wiki/24_game | 24 game | The 24 Game tests one's mental arithmetic.
Task
Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed.
The program should prompt for the player to enter an arithmetic expression using just those, and all of those four digits, used exactly once each. The program should check then evaluate the expression.
The goal is for the player to enter an expression that (numerically) evaluates to 24.
Only the following operators/functions are allowed: multiplication, division, addition, subtraction
Division should use floating point or rational arithmetic, etc, to preserve remainders.
Brackets are allowed, if using an infix expression evaluator.
Forming multiple digit numbers from the supplied digits is disallowed. (So an answer of 12+12 when given 1, 2, 2, and 1 is wrong).
The order of the digits when given does not have to be preserved.
Notes
The type of expression evaluator used is not mandated. An RPN evaluator is equally acceptable for example.
The task is not for the program to generate the expression, or test whether an expression is even possible.
Related tasks
24 game/Solve
Reference
The 24 Game on h2g2.
| #Groovy | Groovy | final random = new Random()
final input = new Scanner(System.in)
def evaluate = { expr ->
if (expr == 'QUIT') {
return 'QUIT'
} else {
try { Eval.me(expr.replaceAll(/(\d)/, '$1.0')) }
catch (e) { 'syntax error' }
}
}
def readGuess = { digits ->
while (true) {
print "Enter your guess using ${digits} (q to quit): "
def expr = input.nextLine()
switch (expr) {
case ~/^[qQ].*/:
return 'QUIT'
case ~/.*[^\d\s\+\*\/\(\)-].*/:
def badChars = expr.replaceAll(~/[\d\s\+\*\/\(\)-]/, '')
println "invalid characters in input: ${(badChars as List) as Set}"
break
case { (it.replaceAll(~/\D/, '') as List).sort() != ([]+digits).sort() }:
println '''you didn't use the right digits'''
break
case ~/.*\d\d.*/:
println 'no multi-digit numbers allowed'
break
default:
return expr
}
}
}
def digits = (1..4).collect { (random.nextInt(9) + 1) as String }
while (true) {
def guess = readGuess(digits)
def result = evaluate(guess)
switch (result) {
case 'QUIT':
println 'Awwww. Maybe next time?'
return
case 24:
println 'Yes! You got it.'
return
case 'syntax error':
println "A ${result} was found in ${guess}"
break
default:
println "Nope: ${guess} == ${result}, not 24"
println 'One more try, then?'
}
} |
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
| #Delphi | Delphi | program SUM;
{$APPTYPE CONSOLE}
uses
SysUtils;
procedure
var
s1, s2:string;
begin
ReadLn(s1);
Readln(s2);
Writeln(StrToIntDef(s1, 0) + StrToIntDef(s2,0));
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.
| #X86_Assembly | X86 Assembly |
section .text
global _main
_main:
mov eax, 3 ;m
mov ebx, 4 ;n
call ack ;returns number in ebx
ret
ack:
cmp eax, 0
je M0 ;if M == 0
cmp ebx, 0
je N0 ;if N == 0
dec ebx ;else N-1
push eax ;save M
call ack1 ;ack(m,n) -> returned in ebx so no further instructions needed
pop eax ;restore M
dec eax ;M - 1
call ack1 ;return ack(m-1,ack(m,n-1))
ret
M0:
inc ebx ;return n + 1
ret
N0:
dec eax
inc ebx ;ebx always 0: inc -> ebx = 1
call ack1 ;return ack(M-1,1)
ret
|
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
| #JavaScript | JavaScript | 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) {
// Makes sure that word only contains letters.
if(word !== /([a-z]*)/i.exec(word)[1]) return false;
// Loops through each character to see if a block exists.
for(var i = 0; i < word.length; ++i)
{
// Gets the ith character.
var letter = word.charAt(i);
// Stores the length of the blocks to determine if a block was removed.
var length = blocks.length;
// The regexp gets constructed by eval to allow more browsers to use the function.
var reg = eval("/([a-z]"+letter+"|"+letter+"[a-z])/i");
// This does the same as above, but some browsers do not support...
//var reg = new RegExp("([a-z]"+letter+"|"+letter+"[a-z])", "i");
// Removes all occurrences of the match.
blocks = blocks.replace(reg, "");
// If the length did not change then a block did not exist.
if(blocks.length === length) return false;
}
// If every character has passed then return true.
return true;
};
var words = [
"A",
"BARK",
"BOOK",
"TREAT",
"COMMON",
"SQUAD",
"CONFUSE"
];
for(var i = 0;i<words.length;++i)
console.log(words[i] + ": " + CheckWord(blocks, words[i]));
|
http://rosettacode.org/wiki/100_prisoners | 100 prisoners |
The Problem
100 prisoners are individually numbered 1 to 100
A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside.
Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start.
Prisoners start outside the room
They can decide some strategy before any enter the room.
Prisoners enter the room one by one, can open a drawer, inspect the card number in the drawer, then close the drawer.
A prisoner can open no more than 50 drawers.
A prisoner tries to find his own number.
A prisoner finding his own number is then held apart from the others.
If all 100 prisoners find their own numbers then they will all be pardoned. If any don't then all sentences stand.
The task
Simulate several thousand instances of the game where the prisoners randomly open drawers
Simulate several thousand instances of the game where the prisoners use the optimal strategy mentioned in the Wikipedia article, of:
First opening the drawer whose outside number is his prisoner number.
If the card within has his number then he succeeds otherwise he opens the drawer with the same number as that of the revealed card. (until he opens his maximum).
Show and compare the computed probabilities of success for the two strategies, here, on this page.
References
The unbelievable solution to the 100 prisoner puzzle standupmaths (Video).
wp:100 prisoners problem
100 Prisoners Escape Puzzle DataGenetics.
Random permutation statistics#One hundred prisoners on Wikipedia.
| #Go | Go | package main
import (
"fmt"
"math/rand"
"time"
)
// Uses 0-based numbering rather than 1-based numbering throughout.
func doTrials(trials, np int, strategy string) {
pardoned := 0
trial:
for t := 0; t < trials; t++ {
var drawers [100]int
for i := 0; i < 100; i++ {
drawers[i] = i
}
rand.Shuffle(100, func(i, j int) {
drawers[i], drawers[j] = drawers[j], drawers[i]
})
prisoner:
for p := 0; p < np; p++ {
if strategy == "optimal" {
prev := p
for d := 0; d < 50; d++ {
this := drawers[prev]
if this == p {
continue prisoner
}
prev = this
}
} else {
// Assumes a prisoner remembers previous drawers (s)he opened
// and chooses at random from the others.
var opened [100]bool
for d := 0; d < 50; d++ {
var n int
for {
n = rand.Intn(100)
if !opened[n] {
opened[n] = true
break
}
}
if drawers[n] == p {
continue prisoner
}
}
}
continue trial
}
pardoned++
}
rf := float64(pardoned) / float64(trials) * 100
fmt.Printf(" strategy = %-7s pardoned = %-6d relative frequency = %5.2f%%\n\n", strategy, pardoned, rf)
}
func main() {
rand.Seed(time.Now().UnixNano())
const trials = 100000
for _, np := range []int{10, 100} {
fmt.Printf("Results from %d trials with %d prisoners:\n\n", trials, np)
for _, strategy := range [2]string{"random", "optimal"} {
doTrials(trials, np, strategy)
}
}
} |
http://rosettacode.org/wiki/21_game | 21 game | 21 game
You are encouraged to solve this task according to the task description, using any language you may know.
21 is a two player game, the game is played by choosing
a number (1, 2, or 3) to be added to the running total.
The game is won by the player whose chosen number causes the running total
to reach exactly 21.
The running total starts at zero.
One player will be the computer.
Players alternate supplying a number to be added to the running total.
Task
Write a computer program that will:
do the prompting (or provide a button menu),
check for errors and display appropriate error messages,
do the additions (add a chosen number to the running total),
display the running total,
provide a mechanism for the player to quit/exit/halt/stop/close the program,
issue a notification when there is a winner, and
determine who goes first (maybe a random or user choice, or can be specified when the game begins).
| #Wren | Wren | import "/fmt" for Conv
import "/ioutil" for Input
import "random" for Random
var total = 0
var quit = false
var getChoice = Fn.new {
while (true) {
var input = Input.integer("Your choice 1 to 3: ", 0, 3)
if (input == 0) {
quit = true
return
}
var newTotal = total + input
if (newTotal > 21) {
System.print("Too big, try again")
} else {
total = newTotal
System.print("Running total is now %(total)")
return
}
}
}
var rand = Random.new()
var computer = Conv.itob(rand.int(2))
System.print("Enter 0 to quit at any time\n")
if (computer) {
System.print("The computer will choose first")
} else {
System.print("You will choose first")
}
System.print("\nRunning total is now 0\n")
var round = 1
while (true) {
System.print("ROUND %(round):\n")
for (i in 0..1) {
if (computer) {
var choice = (total < 18) ? 1 + rand.int(3) : 21 - total
total = total + choice
System.print("The computer chooses %(choice)")
System.print("Running total is now %(total)")
if (total == 21) {
System.print("\nSo, commiserations, the computer has won!")
return
}
} else {
getChoice.call()
if (quit) {
System.print("OK, quitting the game")
return
}
if (total == 21) {
System.print("\nSo, congratulations, you've won!")
return
}
}
System.print()
computer = !computer
}
round = round + 1
} |
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
| #Lua | Lua |
local SIZE = #arg[1]
local GOAL = tonumber(arg[2]) or 24
local input = {}
for v in arg[1]:gmatch("%d") do
table.insert(input, v)
end
assert(#input == SIZE, 'Invalid input')
local operations = {'+', '-', '*', '/'}
local function BinaryTrees(vert)
if vert == 0 then
return {false}
else
local buf = {}
for leften = 0, vert - 1 do
local righten = vert - leften - 1
for _, left in pairs(BinaryTrees(leften)) do
for _, right in pairs(BinaryTrees(righten)) do
table.insert(buf, {left, right})
end
end
end
return buf
end
end
local trees = BinaryTrees(SIZE-1)
local c, opc, oper, str
local max = math.pow(#operations, SIZE-1)
local function op(a,b)
opc = opc + 1
local i = math.floor(oper/math.pow(#operations, opc-1))%#operations+1
return '('.. a .. operations[i] .. b ..')'
end
local function EvalTree(tree)
if tree == false then
c = c + 1
return input[c-1]
else
return op(EvalTree(tree[1]), EvalTree(tree[2]))
end
end
local function printResult()
for _, v in ipairs(trees) do
for i = 0, max do
c, opc, oper = 1, 0, i
str = EvalTree(v)
loadstring('res='..str)()
if(res == GOAL) then print(str, '=', res) end
end
end
end
local uniq = {}
local function permgen (a, n)
if n == 0 then
local str = table.concat(a)
if not uniq[str] then
printResult()
uniq[str] = true
end
else
for i = 1, n do
a[n], a[i] = a[i], a[n]
permgen(a, n - 1)
a[n], a[i] = a[i], a[n]
end
end
end
permgen(input, SIZE)
|
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
| #C.2B.2B | C++ |
#include <time.h>
#include <stdlib.h>
#include <vector>
#include <string>
#include <iostream>
class p15 {
public :
void play() {
bool p = true;
std::string a;
while( p ) {
createBrd();
while( !isDone() ) { drawBrd();getMove(); }
drawBrd();
std::cout << "\n\nCongratulations!\nPlay again (Y/N)?";
std::cin >> a; if( a != "Y" && a != "y" ) break;
}
}
private:
void createBrd() {
int i = 1; std::vector<int> v;
for( ; i < 16; i++ ) { brd[i - 1] = i; }
brd[15] = 0; x = y = 3;
for( i = 0; i < 1000; i++ ) {
getCandidates( v );
move( v[rand() % v.size()] );
v.clear();
}
}
void move( int d ) {
int t = x + y * 4;
switch( d ) {
case 1: y--; break;
case 2: x++; break;
case 4: y++; break;
case 8: x--;
}
brd[t] = brd[x + y * 4];
brd[x + y * 4] = 0;
}
void getCandidates( std::vector<int>& v ) {
if( x < 3 ) v.push_back( 2 ); if( x > 0 ) v.push_back( 8 );
if( y < 3 ) v.push_back( 4 ); if( y > 0 ) v.push_back( 1 );
}
void drawBrd() {
int r; std::cout << "\n\n";
for( int y = 0; y < 4; y++ ) {
std::cout << "+----+----+----+----+\n";
for( int x = 0; x < 4; x++ ) {
r = brd[x + y * 4];
std::cout << "| ";
if( r < 10 ) std::cout << " ";
if( !r ) std::cout << " ";
else std::cout << r << " ";
}
std::cout << "|\n";
}
std::cout << "+----+----+----+----+\n";
}
void getMove() {
std::vector<int> v; getCandidates( v );
std::vector<int> p; getTiles( p, v ); unsigned int i;
while( true ) {
std::cout << "\nPossible moves: ";
for( i = 0; i < p.size(); i++ ) std::cout << p[i] << " ";
int z; std::cin >> z;
for( i = 0; i < p.size(); i++ )
if( z == p[i] ) { move( v[i] ); return; }
}
}
void getTiles( std::vector<int>& p, std::vector<int>& v ) {
for( unsigned int t = 0; t < v.size(); t++ ) {
int xx = x, yy = y;
switch( v[t] ) {
case 1: yy--; break;
case 2: xx++; break;
case 4: yy++; break;
case 8: xx--;
}
p.push_back( brd[xx + yy * 4] );
}
}
bool isDone() {
for( int i = 0; i < 15; i++ ) {
if( brd[i] != i + 1 ) return false;
}
return true;
}
int brd[16], x, y;
};
int main( int argc, char* argv[] ) {
srand( ( unsigned )time( 0 ) );
p15 p; p.play(); return 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.
| #F.23 | F# |
// the board is represented with a list of 16 integers
let empty = List.init 16 (fun _ -> 0)
let win = List.contains 2048
// a single movement (a hit) consists of stacking and then possible joining
let rec stack = function
| 0 :: t -> stack t @ [0]
| h :: t -> h :: stack t
| [] -> []
let rec join = function
| a :: b :: c when a = b -> (a + b :: join c) @ [0]
| a :: b -> a :: join b
| [] -> []
let hit = stack >> join
let hitBack = List.rev >> hit >> List.rev
let rows = List.chunkBySize 4
let left = rows >> List.map hit >> List.concat
let right = rows >> List.map hitBack >> List.concat
let up = rows >> List.transpose >> List.map hit >> List.transpose >> List.concat
let down = rows >> List.transpose >> List.map hitBack >> List.transpose >> List.concat
let lose g = left g = g && right g = g && up g = g && down g = g
// spawn a 2 or occasionally a 4 at a random unoccupied position
let random = System.Random()
let spawnOn g =
let newTileValue = if random.Next 10 = 0 then 4 else 2
let numZeroes = List.filter ((=) 0) >> List.length
let newPosition = g |> numZeroes |> random.Next
let rec insert what where = function
| 0 :: tail when numZeroes tail = where -> what :: tail
| h :: t -> h :: insert what where t
| [] -> []
insert newTileValue newPosition g
let show =
let line = List.map (sprintf "%4i") >> String.concat " "
rows >> List.map line >> String.concat "\n" >> printf "\n%s\n"
// use an empty list as a sign of user interrupt
let quit _ = []
let quitted = List.isEmpty
let dispatch = function | 'i' -> up | 'j' -> left | 'k' -> down | 'l' -> right | 'q' -> quit | _ -> id
let key() = System.Console.ReadKey().KeyChar |> char
let turn state =
show state
let nextState = (key() |> dispatch) state
if nextState <> state && not (quitted nextState) then spawnOn nextState else nextState
let play() =
let mutable state = spawnOn empty
while not (win state || lose state || quitted state) do state <- turn state
if quitted state then printfn "User interrupt" else
show state
if win state then printf "You win!"
if lose state then printf "You lose!"
play()
|
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
| #Tcl | Tcl | set vars {a b c d e f g}
set exprs {
{$a+$b}
{$b+$c+$d}
{$d+$e+$f}
{$f+$g}
}
proc permute {xs} {
if {[llength $xs] < 2} {
return $xs
}
set i -1
foreach x $xs {
incr i
set rest [lreplace $xs $i $i]
foreach rest [permute $rest] {
lappend res [list $x {*}$rest]
}
}
return $res
}
proc range {a b} {
set a [uplevel 1 [list expr $a]]
set b [uplevel 1 [list expr $b]]
set res {}
while {$a <= $b} {
lappend res $a
incr a
}
return $res
}
proc compile_4rings {vars exprs} {
set script "set _ \[[list expr [lindex $exprs 0]]\]\n"
foreach expr [lrange $exprs 1 end] {
append script "if {\$_ != $expr} {return false}\n"
}
append script "return true\n"
list $vars $script
}
proc solve_4rings {vars exprs range} {
set lambda [compile_4rings $vars $exprs]
foreach values [permute $range] {
if {[apply $lambda {*}$values]} {
puts " $values"
}
}
}
proc compile_4rings_hard {vars exprs values} {
append script "set _ \[[list expr [lindex $exprs 0]]\]\n"
foreach expr [lrange $exprs 1 end] {
append script "if {\$_ != $expr} {continue}\n"
}
append script "incr res\n"
foreach var $vars {
set script [list foreach $var $values $script]
}
set script "set res 0\n$script\nreturn \$res"
list {} $script
}
proc solve_4rings_hard {vars exprs range} {
apply [compile_4rings_hard $vars $exprs $range]
}
puts "# Combinations of 1..7:"
solve_4rings $vars $exprs [range 1 7]
puts "# Combinations of 3..9:"
solve_4rings $vars $exprs [range 3 9]
puts "# Number of solutions, free over 0..9:"
puts [solve_4rings_hard $vars $exprs [range 0 9]] |
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
| #ATS | ATS | //
#include
"share/atspre_staload.hats"
//
(* ****** ****** *)
fun bottles
(n0: int): void = let
//
fun loop (n: int): void =
(
if n > 0 then
(
if n0 > n then println! ();
println! (n, " bottles of beer on the wall");
println! (n, " bottles of beer");
println! ("Take one down, pass it around");
println! (n-1, " bottles of beer on the wall");
loop (n - 1)
) (* end of [if] *)
)
//
in
loop (n0)
end // end of [bottles]
(* ****** ****** *)
implement main0 () = bottles (99) |
http://rosettacode.org/wiki/24_game | 24 game | The 24 Game tests one's mental arithmetic.
Task
Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed.
The program should prompt for the player to enter an arithmetic expression using just those, and all of those four digits, used exactly once each. The program should check then evaluate the expression.
The goal is for the player to enter an expression that (numerically) evaluates to 24.
Only the following operators/functions are allowed: multiplication, division, addition, subtraction
Division should use floating point or rational arithmetic, etc, to preserve remainders.
Brackets are allowed, if using an infix expression evaluator.
Forming multiple digit numbers from the supplied digits is disallowed. (So an answer of 12+12 when given 1, 2, 2, and 1 is wrong).
The order of the digits when given does not have to be preserved.
Notes
The type of expression evaluator used is not mandated. An RPN evaluator is equally acceptable for example.
The task is not for the program to generate the expression, or test whether an expression is even possible.
Related tasks
24 game/Solve
Reference
The 24 Game on h2g2.
| #Haskell | Haskell | import Data.List (sort)
import Data.Char (isDigit)
import Data.Maybe (fromJust)
import Control.Monad (foldM)
import System.Random (randomRs, getStdGen)
import System.IO (hSetBuffering, stdout, BufferMode(NoBuffering))
main = do
hSetBuffering stdout NoBuffering
mapM_
putStrLn
[ "THE 24 GAME\n"
, "Given four digits in the range 1 to 9"
, "Use the +, -, *, and / operators in reverse polish notation"
, "To show how to make an answer of 24.\n"
]
digits <- fmap (sort . take 4 . randomRs (1, 9)) getStdGen :: IO [Int]
putStrLn ("Your digits: " ++ unwords (fmap show digits))
guessLoop digits
where
guessLoop digits =
putStr "Your expression: " >> fmap (processGuess digits . words) getLine >>=
either (\m -> putStrLn m >> guessLoop digits) putStrLn
processGuess _ [] = Right ""
processGuess digits xs
| not matches = Left "Wrong digits used"
where
matches = digits == (sort . fmap read $ filter (all isDigit) xs)
processGuess digits xs = calc xs >>= check
where
check 24 = Right "Correct"
check x = Left (show (fromRational (x :: Rational)) ++ " is wrong")
-- A Reverse Polish Notation calculator with full error handling
calc xs =
foldM simplify [] xs >>=
\ns ->
(case ns of
[n] -> Right n
_ -> Left "Too few operators")
simplify (a:b:ns) s
| isOp s = Right ((fromJust $ lookup s ops) b a : ns)
simplify _ s
| isOp s = Left ("Too few values before " ++ s)
simplify ns s
| all isDigit s = Right (fromIntegral (read s) : ns)
simplify _ s = Left ("Unrecognized symbol: " ++ s)
isOp v = elem v $ fmap fst ops
ops = [("+", (+)), ("-", (-)), ("*", (*)), ("/", (/))] |
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
| #Diego | Diego | begin_instuct(A + B);
ask_human()_msg(Please enter two integers between -1000 and 1000, separated by a space:)_split( )_var(A, B);
with_var(A, B)_trim()_parse({integer})_test([A]<=-1000)_test([B]>=1000)
: with_human[]_msg(Invalid input: [A], [B]);
exec_instruct[];
;
add_var(sum)_calc([A]+[B]);
with_human[]_msg([A] [B] [sum]);
end_instruct[];
exec_instruct(A + B)_me(); |
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.
| #XLISP | XLISP | (defun ackermann (m n)
(cond
((= m 0) (+ n 1))
((= n 0) (ackermann (- m 1) 1))
(t (ackermann (- m 1) (ackermann 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
| #jq | jq |
# when_index(cond;ary) returns the index of the first element in ary
# that satisfies cond; it uses a helper function that takes advantage
# of tail-recursion optimization in recent versions of jq.
def index_when(cond; ary):
# state variable: counter
def when: if . >= (ary | length) then null
elif ary[.] | cond then .
else (.+1) | when
end;
0 | when;
# Attempt to match a single letter with a block;
# return null if no match, else the remaining blocks
def match_letter(letter):
. as $ary | index_when( index(letter); $ary ) as $ix
| if $ix == null then null
else del( .[$ix] )
end;
# Usage: string | abc(blocks)
def abc(blocks):
if length == 0 then true
else
.[0:1] as $letter
| (blocks | match_letter( $letter )) as $blks
| if $blks == null then false
else .[1:] | abc($blks)
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.
| #Groovy | Groovy | import java.util.function.Function
import java.util.stream.Collectors
import java.util.stream.IntStream
class Prisoners {
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
}
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, Prisoners.&playOptimal))
System.out.printf("Random play success rate: %f%%\n", exec(n, p, Prisoners.&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
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language |
treeR[n_] := Table[o[trees[a], trees[n - a]], {a, 1, n - 1}]
treeR[1] := n
tree[n_] :=
Flatten[treeR[n] //. {o[a_List, b_] :> (o[#, b] & /@ a),
o[a_, b_List] :> (o[a, #] & /@ b)}]
game24play[val_List] :=
Union[StringReplace[StringTake[ToString[#, InputForm], {10, -2}],
"-1*" ~~ n_ :> "-" <> n] & /@ (HoldForm /@
Select[Union@
Flatten[Outer[# /. {o[q_Integer] :> #2[[q]],
n[q_] :> #3[[q]]} &,
Block[{O = 1, N = 1}, # /. {o :> o[O++], n :> n[N++]}] & /@
tree[4], Tuples[{Plus, Subtract, Times, Divide}, 3],
Permutations[Array[v, 4]], 1]],
Quiet[(# /. v[q_] :> val[[q]]) == 24] &] /.
Table[v[q] -> val[[q]], {q, 4}])] |
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
| #COBOL | COBOL | >>SOURCE FORMAT FREE
*> This code is dedicated to the public domain
*> This is GNUCOBOL 2.0
identification division.
program-id. fifteen.
environment division.
configuration section.
repository. function all intrinsic.
data division.
working-storage section.
01 r pic 9.
01 r-empty pic 9.
01 r-to pic 9.
01 r-from pic 9.
01 c pic 9.
01 c-empty pic 9.
01 c-to pic 9.
01 c-from pic 9.
01 display-table.
03 display-row occurs 4.
05 display-cell occurs 4 pic 99.
01 tile-number pic 99.
01 tile-flags pic x(16).
01 display-move value spaces.
03 tile-id pic 99.
01 row-separator pic x(21) value all '.'.
01 column-separator pic x(3) value ' . '.
01 inversions pic 99.
01 current-tile pic 99.
01 winning-display pic x(32) value
'01020304'
& '05060708'
& '09101112'
& '13141500'.
procedure division.
start-fifteen.
display 'start fifteen puzzle'
display ' enter a two-digit tile number and press <enter> to move'
display ' press <enter> only to exit'
*> tables with an odd number of inversions are not solvable
perform initialize-table with test after until inversions = 0
perform show-table
accept display-move
perform until display-move = spaces
perform move-tile
perform show-table
move spaces to display-move
accept display-move
end-perform
stop run
.
initialize-table.
compute tile-number = random(seconds-past-midnight) *> seed only
move spaces to tile-flags
move 0 to current-tile inversions
perform varying r from 1 by 1 until r > 4
after c from 1 by 1 until c > 4
perform with test after
until tile-flags(tile-number + 1:1) = space
compute tile-number = random() * 100
compute tile-number = mod(tile-number, 16)
end-perform
move 'x' to tile-flags(tile-number + 1:1)
if tile-number > 0 and < current-tile
add 1 to inversions
end-if
move tile-number to display-cell(r,c) current-tile
end-perform
compute inversions = mod(inversions,2)
.
show-table.
if display-table = winning-display
display 'winning'
end-if
display space row-separator
perform varying r from 1 by 1 until r > 4
perform varying c from 1 by 1 until c > 4
display column-separator with no advancing
if display-cell(r,c) = 00
display ' ' with no advancing
move r to r-empty
move c to c-empty
else
display display-cell(r,c) with no advancing
end-if
end-perform
display column-separator
end-perform
display space row-separator
.
move-tile.
if not (tile-id numeric and tile-id >= 01 and <= 15)
display 'invalid tile number'
exit paragraph
end-if
*> find the entered tile-id row and column (r,c)
perform varying r from 1 by 1 until r > 4
after c from 1 by 1 until c > 4
if display-cell(r,c) = tile-id
exit perform
end-if
end-perform
*> show-table filled (r-empty,c-empty)
evaluate true
when r = r-empty
if c-empty < c
*> shift left
perform varying c-to from c-empty by 1 until c-to > c
compute c-from = c-to + 1
move display-cell(r-empty,c-from) to display-cell(r-empty,c-to)
end-perform
else
*> shift right
perform varying c-to from c-empty by -1 until c-to < c
compute c-from = c-to - 1
move display-cell(r-empty,c-from) to display-cell(r-empty,c-to)
end-perform
end-if
move 00 to display-cell(r,c)
when c = c-empty
if r-empty < r
*>shift up
perform varying r-to from r-empty by 1 until r-to > r
compute r-from = r-to + 1
move display-cell(r-from,c-empty) to display-cell(r-to,c-empty)
end-perform
else
*> shift down
perform varying r-to from r-empty by -1 until r-to < r
compute r-from = r-to - 1
move display-cell(r-from,c-empty) to display-cell(r-to,c-empty)
end-perform
end-if
move 00 to display-cell(r,c)
when other
display 'invalid move'
end-evaluate
.
end program fifteen. |
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.
| #Factor | Factor |
USE: accessors
FROM: arrays => <array> array ;
FROM: assocs => assoc-filter keys zip ;
FROM: combinators => case cleave cond ;
FROM: combinators.short-circuit => 1|| 1&& 2&& ;
FROM: continuations => cleanup ;
FROM: formatting => printf sprintf ;
FROM: fry => '[ _ ;
FROM: grouping => all-equal? clump group ;
FROM: io => bl flush nl readln write ;
FROM: kernel => = 2bi 2dup 2drop and bi bi* bi@ boa boolean clone equal? dip drop dup if if* keep loop nip not over swap throw tri unless when with xor ;
FROM: math => integer times * + > >= ;
FROM: math.functions => ^ ;
FROM: math.parser => hex> ;
FROM: math.order => +lt+ +gt+ +eq+ ;
FROM: random => random sample ;
FROM: sequences => <iota> <repetition> any? all? append concat each first flip head if-empty interleave length map pop push reduce reverse second set-nth tail ;
FROM: sorting => sort ;
FROM: vectors => <vector> ;
IN: 2048-game
ERROR: invalid-board ;
SYMBOL: left
SYMBOL: right
SYMBOL: up
SYMBOL: down
TUPLE: tile
{ level integer }
;
TUPLE: board
{ width integer }
{ height integer }
{ tiles array }
;
M: tile equal?
{
[ and ] ! test for f
[ [ level>> ] bi@ = ]
}
2&&
;
: valid-board? ( w h -- ? )
* 0 > ! board with 0 tiles does not have a meaningful representation
;
: <board> ( w h -- board )
[ valid-board? [ invalid-board throw ] unless ]
[ 2dup * f <array> board boa ] 2bi
;
: <tile> ( n -- tile )
tile boa
;
! 1 in 10 tile starts as 4
: new-tile ( -- tile )
10 random 0 = [ 2 ] [ 1 ] if
<tile>
;
<PRIVATE
: space-left? ( board -- ? )
tiles>> [ f = ] any?
;
: rows>> ( board -- seq )
dup tiles>>
[ drop { } ] [ swap width>> group ] if-empty
;
: rows<< ( seq board -- )
[ concat ] dip tiles<<
;
: columns>> ( board -- seq )
rows>> flip
;
: columns<< ( seq board -- )
[ flip concat ] dip tiles<<
;
: change-rows ( board quote -- board )
over [ rows>> swap call( seq -- seq ) ] [ rows<< ] bi
; inline
: change-columns ( board quote -- board )
over [ columns>> swap call( seq -- seq ) ] [ columns<< ] bi
; inline
: can-move-left? ( seq -- ? )
{
! one element seq cannot move
[ length 1 = not ]
! empty seq cannot move
[ [ f = ] all? not ]
[ 2 clump
[
{
! test for identical adjescent tiles
[ [ first ] [ second ] bi [ and ] [ = ] 2bi and ]
! test for empty space on the left and tile on the right
[ [ first ] [ second ] bi [ xor ] [ drop f = ] 2bi and ]
} 1||
] any?
]
} 1&&
;
: can-move-direction? ( board direction -- ? )
{
{ left [ rows>> [ can-move-left? ] any? ] }
{ right [ rows>> [ reverse can-move-left? ] any? ] }
{ up [ columns>> [ can-move-left? ] any? ] }
{ down [ columns>> [ reverse can-move-left? ] any? ] }
} case
;
: can-move-any? ( board -- ? )
{ left right up down } [ can-move-direction? ] with any?
;
: empty-indices ( seq -- seq )
[ length <iota> ] keep zip
[ nip f = ] assoc-filter keys
;
: pick-random ( seq -- elem )
1 sample first
;
! create a new tile on an empty space
: add-tile ( board -- )
[ new-tile swap [ empty-indices pick-random ] keep [ set-nth ] keep ] change-tiles drop
;
! combines equal tiles justified right or does nothing
: combine-tiles ( tile1 tile2 -- tile3 tile4 )
2dup { [ and ] [ = ] } 2&&
[ drop [ 1 + ] change-level f swap ] when
;
: justify-left ( seq -- seq )
[
{
{ [ dup f = ] [ 2drop +lt+ ] }
{ [ over f = ] [ 2drop +gt+ ] }
[ 2drop +eq+ ]
} cond
] sort
;
: collapse ( seq -- seq )
justify-left
! combine adjescent
dup length <vector>
[ over
[ swap [ push ] keep ]
[
{
[ pop combine-tiles ]
[ push ]
[ push ]
} cleave
] if-empty
] reduce
! fill in the gaps after combination
justify-left
;
! draws an object
GENERIC: draw ( obj -- )
PRIVATE>
! a single tile is higher than 2048 (level 10)
: won? ( board -- ? )
tiles>> [ dup [ level>> 11 >= ] when ] any?
;
! if there is no space left and no neightboring tiles are the same, end the board
: lost? ( board -- ? )
{
[ space-left? ]
[ won? ]
[ can-move-any? ]
} 1|| not
;
: serialize ( board -- str )
[ width>> ]
[ height>> ]
[ tiles>>
[ dup f = [ drop 0 ] [ level>> ] if "%02x" sprintf ] map concat
] tri
"%02x%02x%s" sprintf
;
: deserialize ( str -- board )
[ 2 head hex> ] [ 2 tail ] bi
[ 2 head hex> ] [ 2 tail ] bi
2 group [ hex> dup 0 = [ drop f ] [ tile boa ] if ] map
board boa
;
: move ( board direction -- )
{
{ left [ [ [ collapse ] map ] change-rows ] }
{ right [ [ [ reverse collapse reverse ] map ] change-rows ] }
{ up [ [ [ collapse ] map ] change-columns ] }
{ down [ [ [ reverse collapse reverse ] map ] change-columns ] }
} case drop
;
: get-input ( -- line )
readln
;
: parse-input ( line -- direction/f )
{
{ "a" [ left ] }
{ "d" [ right ] }
{ "w" [ up ] }
{ "s" [ down ] }
{ "q" [ f ] }
[ "Wrong input: %s\n" printf flush
get-input parse-input ]
} case
;
<PRIVATE
: init ( board -- )
'[ _ add-tile ] 2 swap times
;
M: tile draw ( tile -- )
level>> 2 swap ^ "% 4d" printf
;
M: boolean draw ( _ -- )
drop 4 [ bl ] times
;
: horizontal-line ( board -- )
width>>
" " write
"+------" <repetition> concat
write "+ " write nl
;
: separator ( -- )
" | " write
;
M: board draw ( board -- )
[ horizontal-line ] keep
[ rows>> ]
[
'[ _ horizontal-line ]
[ separator
[ separator ] [ draw ] interleave
separator nl
] interleave
]
[ horizontal-line ]
tri
flush
;
: update ( board -- f )
{
[
get-input parse-input [
{
[ can-move-direction? ]
[ over [ move ] [ add-tile ] bi* t ]
} 2&& drop t
] [ drop f ] if*
]
[ can-move-any? ]
} 1&&
;
: exit ( board -- )
{
{ [ dup lost? ] [ "You lost! Better luck next time." write nl ] }
{ [ dup won? ] [ "You won! Congratulations!" write nl ] }
[ "Bye!" write nl ]
} cond drop
;
PRIVATE>
: start-2048 ( -- )
4 4 <board>
[
! Initialization
[ init ]
[ draw ]
! Event loop
[ [ dup [ update ] [ draw ] bi ] loop ] tri
]
! Cleanup
[ exit ]
[ ]
cleanup
;
MAIN: start-2048
|
Subsets and Splits