code
stringlengths 1
46.1k
⌀ | label
class label 1.18k
classes | domain_label
class label 21
classes | index
stringlengths 4
5
|
---|---|---|---|
function Tile(pos, val, puzzle){
this.pos = pos;
this.val = val;
this.puzzle = puzzle;
this.merging = false;
this.getCol = () => Math.round(this.pos % 4);
this.getRow = () => Math.floor(this.pos / 4);
this.show = function(){
let padding = this.merging ? 0 : 5;
let size = 0.25*width;
noStroke();
colorMode(HSB, 255);
fill(10*(11 - Math.log2(this.val)), 50 + 15*Math.log2(this.val), 200);
rect(this.getCol()*size + padding, this.getRow()*size + padding, size - 2*padding, size - 2*padding);
fill(255);
textSize(0.1*width);
textAlign(CENTER, CENTER);
text(this.val, (this.getCol() + 0.5)*size, (this.getRow() + 0.5)*size);
}
this.move = function(dir){
let col = this.getCol() + (1 - 2*(dir < 0))*Math.abs(dir)%4;
let row = this.getRow() + (1 - 2*(dir < 0))*Math.floor(Math.abs(dir)/4);
let target = this.puzzle.getTile(this.pos + dir);
if (col < 0 || col > 3 || row < 0 || row > 3) {
return false;
} else if (target){
if(this.merging || target.merging || target.val !== this.val)
return false;
target.val += this.val;
target.merging = true;
this.puzzle.score += target.val;
this.puzzle.removeTile(this);
return true;
}
this.pos += dir;
return true;
}
}
function Puzzle(){
this.tiles = [];
this.dir = 0;
this.score = 0;
this.hasMoved = false;
this.validPositions = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
this.getOpenPositions = () => this.validPositions.filter(i => this.tiles.map(x => x.pos).indexOf(i) === -1);
this.getTile = pos => this.tiles.filter(x => x.pos === pos)[0];
this.removeTile = tile => this.tiles.splice(this.tiles.indexOf(tile), 1);
this.winCondition = () => this.tiles.some(x => x.val === 2048);
this.validMoves = function(){
if(this.tiles.length < 16)
return true;
let res = false;
this.tiles.sort((x,y) => x.pos - y.pos);
for(let i = 0; i < 16; i++)
res = res || ( (i%4 < 3) ? this.tiles[i].val === this.tiles[i+1].val : false )
|| ( (i < 12) ? this.tiles[i].val === this.tiles[i+4].val : false );
return res;
}
this.checkGameState = function(){
if(this.winCondition()){
alert('You win!');
} else if (!this.validMoves()){
alert('You Lose!');
this.restart();
}
}
this.restart = function(){
this.tiles = [];
this.dir = 0;
this.score = 0;
this.hasMoved = false;
this.generateTile();
this.generateTile();
}
this.show = function(){
background(200);
fill(255);
textSize(0.05*width);
textAlign(CENTER, TOP);
text("SCORE: " + this.score, 0.5*width, width);
for(let tile of this.tiles)
tile.show();
}
this.animate = function(){
if(this.dir === 0)
return;
let moving = false;
this.tiles.sort((x,y) => this.dir*(y.pos - x.pos));
for(let tile of this.tiles)
moving = moving || tile.move(this.dir);
if(this.hasMoved && !moving){
this.dir = 0;
this.generateTile();
for(let tile of this.tiles)
tile.merging = false;
}
this.hasMoved = moving;
}
this.generateTile = function(){
let positions = this.getOpenPositions();
let pos = positions[Math.floor(Math.random()*positions.length)];
let val = 2 + 2*Math.floor(Math.random()*1.11);
this.tiles.push(new Tile(pos, val, this));
}
this.generateTile();
this.generateTile();
this.keyHandler = function(key){
if (key === UP_ARROW) this.dir = -4
else if (key === DOWN_ARROW) this.dir = 4
else if (key === RIGHT_ARROW) this.dir = 1
else if (key === LEFT_ARROW) this.dir = -1;
}
}
let game;
function setup() {
createCanvas(400, 420);
game = new Puzzle();
}
function draw() {
game.checkGameState();
game.animate();
game.show();
}
function keyPressed(){
game.keyHandler(keyCode);
} | 1,1792048
| 10javascript
| 1aop7 |
function shuffle(tbl)
for i = #tbl, 2, -1 do
local j = math.random(i)
tbl[i], tbl[j] = tbl[j], tbl[i]
end
return tbl
end
function playOptimal()
local secrets = {}
for i=1,100 do
secrets[i] = i
end
shuffle(secrets)
for p=1,100 do
local success = false
local choice = p
for i=1,50 do
if secrets[choice] == p then
success = true
break
end
choice = secrets[choice]
end
if not success then
return false
end
end
return true
end
function playRandom()
local secrets = {}
for i=1,100 do
secrets[i] = i
end
shuffle(secrets)
for p=1,100 do
local choices = {}
for i=1,100 do
choices[i] = i
end
shuffle(choices)
local success = false
for i=1,50 do
if choices[i] == p then
success = true
break
end
end
if not success then
return false
end
end
return true
end
function exec(n,play)
local success = 0
for i=1,n do
if play() then
success = success + 1
end
end
return 100.0 * success / n
end
function main()
local N = 1000000
print("# of executions: "..N)
print(string.format("Optimal play success rate:%f", exec(N, playOptimal)))
print(string.format("Random play success rate:%f", exec(N, playRandom)))
end
main() | 1,176100 prisoners
| 1lua
| qs6x0 |
'''
The 24 Game Player
Given any four digits in the range 1 to 9, which may have repetitions,
Using just the +, -, *, and / operators; and the possible use of
brackets, (), show how to make an answer of 24.
An answer of will quit the game.
An answer of will generate a new set of four digits.
An answer of will ask you for a new set of four digits.
An answer of will compute an expression for the current digits.
Otherwise you are repeatedly asked for an expression until it evaluates to 24
Note: you cannot form multiple digit numbers from the supplied digits,
so an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.
'''
from __future__ import division, print_function
from itertools import permutations, combinations, product, \
chain
from pprint import pprint as pp
from fractions import Fraction as F
import random, ast, re
import sys
if sys.version_info[0] < 3:
input = raw_input
from itertools import izip_longest as zip_longest
else:
from itertools import zip_longest
def choose4():
'four random digits >0 as characters'
return [str(random.randint(1,9)) for i in range(4)]
def ask4():
'get four random digits >0 from the player'
digits = ''
while len(digits) != 4 or not all(d in '123456789' for d in digits):
digits = input('Enter the digits to solve for: ')
digits = ''.join(digits.strip().split())
return list(digits)
def welcome(digits):
print (__doc__)
print ( + ' '.join(digits))
def check(answer, digits):
allowed = set('() +-*/\t'+''.join(digits))
ok = all(ch in allowed for ch in answer) and \
all(digits.count(dig) == answer.count(dig) for dig in set(digits)) \
and not re.search('\d\d', answer)
if ok:
try:
ast.parse(answer)
except:
ok = False
return ok
def solve(digits):
digilen = len(digits)
exprlen = 2 * digilen - 1
digiperm = sorted(set(permutations(digits)))
opcomb = list(product('+-*/', repeat=digilen-1))
brackets = ( [()] + [(x,y)
for x in range(0, exprlen, 2)
for y in range(x+4, exprlen+2, 2)
if (x,y) != (0,exprlen+1)]
+ [(0, 3+1, 4+2, 7+3)] )
for d in digiperm:
for ops in opcomb:
if '/' in ops:
d2 = [('F(%s)'% i) for i in d]
else:
d2 = d
ex = list(chain.from_iterable(zip_longest(d2, ops, fillvalue='')))
for b in brackets:
exp = ex[::]
for insertpoint, bracket in zip(b, '()'*(len(b)
exp.insert(insertpoint, bracket)
txt = ''.join(exp)
try:
num = eval(txt)
except ZeroDivisionError:
continue
if num == 24:
if '/' in ops:
exp = [ (term if not term.startswith('F(') else term[2])
for term in exp ]
ans = ' '.join(exp).rstrip()
print (,ans)
return ans
print (, ' '.join(digits))
return '!'
def main():
digits = choose4()
welcome(digits)
trial = 0
answer = ''
chk = ans = False
while not (chk and ans == 24):
trial +=1
answer = input(% trial)
chk = check(answer, digits)
if answer == '?':
solve(digits)
answer = '!'
if answer.lower() == 'q':
break
if answer == '!':
digits = choose4()
trial = 0
print (, ' '.join(digits))
continue
if answer == '!!':
digits = ask4()
trial = 0
print (, ' '.join(digits))
continue
if not chk:
print (% answer)
else:
if '/' in answer:
answer = ''.join( (('F(%s)'% char) if char in '123456789' else char)
for char in answer )
ans = eval(answer)
print (, ans)
if ans == 24:
print ()
print ()
main() | 1,17424 game/Solve
| 3python
| r70gq |
package main
import (
"fmt"
"math/rand"
"strings"
"time"
)
func main() {
rand.Seed(time.Now().UnixNano())
p := newPuzzle()
p.play()
}
type board [16]cell
type cell uint8
type move uint8
const (
up move = iota
down
right
left
)
func randMove() move { return move(rand.Intn(4)) }
var solvedBoard = board{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0}
func (b *board) String() string {
var buf strings.Builder
for i, c := range b {
if c == 0 {
buf.WriteString(" .")
} else {
_, _ = fmt.Fprintf(&buf, "%3d", c)
}
if i%4 == 3 {
buf.WriteString("\n")
}
}
return buf.String()
}
type puzzle struct {
board board
empty int | 1,18015 puzzle game
| 0go
| bpskh |
import java.io.BufferedReader
import java.io.InputStreamReader
const val positiveGameOverMessage = "So sorry, but you won the game."
const val negativeGameOverMessage = "So sorry, but you lost the game."
fun main(args: Array<String>) {
val grid = arrayOf(
arrayOf(0, 0, 0, 0),
arrayOf(0, 0, 0, 0),
arrayOf(0, 0, 0, 0),
arrayOf(0, 0, 0, 0)
)
val gameOverMessage = run2048(grid)
println(gameOverMessage)
}
fun run2048(grid: Array<Array<Int>>): String {
if (isGridSolved(grid)) return positiveGameOverMessage
else if (isGridFull(grid)) return negativeGameOverMessage
val populatedGrid = spawnNumber(grid)
display(populatedGrid)
return run2048(manipulateGrid(populatedGrid, waitForValidInput()))
}
fun isGridSolved(grid: Array<Array<Int>>): Boolean = grid.any { row -> row.contains(2048) }
fun isGridFull(grid: Array<Array<Int>>): Boolean = grid.all { row -> !row.contains(0) }
fun spawnNumber(grid: Array<Array<Int>>): Array<Array<Int>> {
val coordinates = locateSpawnCoordinates(grid)
val number = generateNumber()
return updateGrid(grid, coordinates, number)
}
fun locateSpawnCoordinates(grid: Array<Array<Int>>): Pair<Int, Int> {
val emptyCells = arrayListOf<Pair<Int, Int>>()
grid.forEachIndexed { x, row ->
row.forEachIndexed { y, cell ->
if (cell == 0) emptyCells.add(Pair(x, y))
}
}
return emptyCells[(Math.random() * (emptyCells.size - 1)).toInt()]
}
fun generateNumber(): Int = if (Math.random() > 0.10) 2 else 4
fun updateGrid(grid: Array<Array<Int>>, at: Pair<Int, Int>, value: Int): Array<Array<Int>> {
val updatedGrid = grid.copyOf()
updatedGrid[at.first][at.second] = value
return updatedGrid
}
fun waitForValidInput(): String {
val input = waitForInput()
return if (isValidInput(input)) input else waitForValidInput()
}
fun isValidInput(input: String): Boolean = arrayOf("a", "s", "d", "w").contains(input)
fun waitForInput(): String {
val reader = BufferedReader(InputStreamReader(System.`in`))
println("Direction? ")
return reader.readLine()
}
fun manipulateGrid(grid: Array<Array<Int>>, input: String): Array<Array<Int>> = when (input) {
"a" -> shiftCellsLeft(grid)
"s" -> shiftCellsDown(grid)
"d" -> shiftCellsRight(grid)
"w" -> shiftCellsUp(grid)
else -> throw IllegalArgumentException("Expected one of [a, s, d, w]")
}
fun shiftCellsLeft(grid: Array<Array<Int>>): Array<Array<Int>> =
grid.map(::mergeAndOrganizeCells).toTypedArray()
fun shiftCellsRight(grid: Array<Array<Int>>): Array<Array<Int>> =
grid.map { row -> mergeAndOrganizeCells(row.reversed().toTypedArray()).reversed().toTypedArray() }.toTypedArray()
fun shiftCellsUp(grid: Array<Array<Int>>): Array<Array<Int>> {
val rows: Array<Array<Int>> = arrayOf(
arrayOf(grid[0][0], grid[1][0], grid[2][0], grid[3][0]),
arrayOf(grid[0][1], grid[1][1], grid[2][1], grid[3][1]),
arrayOf(grid[0][2], grid[1][2], grid[2][2], grid[3][2]),
arrayOf(grid[0][3], grid[1][3], grid[2][3], grid[3][3])
)
val updatedGrid = grid.copyOf()
rows.map(::mergeAndOrganizeCells).forEachIndexed { rowIdx, row ->
updatedGrid[0][rowIdx] = row[0]
updatedGrid[1][rowIdx] = row[1]
updatedGrid[2][rowIdx] = row[2]
updatedGrid[3][rowIdx] = row[3]
}
return updatedGrid
}
fun shiftCellsDown(grid: Array<Array<Int>>): Array<Array<Int>> {
val rows: Array<Array<Int>> = arrayOf(
arrayOf(grid[3][0], grid[2][0], grid[1][0], grid[0][0]),
arrayOf(grid[3][1], grid[2][1], grid[1][1], grid[0][1]),
arrayOf(grid[3][2], grid[2][2], grid[1][2], grid[0][2]),
arrayOf(grid[3][3], grid[2][3], grid[1][3], grid[0][3])
)
val updatedGrid = grid.copyOf()
rows.map(::mergeAndOrganizeCells).forEachIndexed { rowIdx, row ->
updatedGrid[3][rowIdx] = row[0]
updatedGrid[2][rowIdx] = row[1]
updatedGrid[1][rowIdx] = row[2]
updatedGrid[0][rowIdx] = row[3]
}
return updatedGrid
}
fun mergeAndOrganizeCells(row: Array<Int>): Array<Int> = organize(merge(row.copyOf()))
fun merge(row: Array<Int>, idxToMatch: Int = 0, idxToCompare: Int = 1): Array<Int> {
if (idxToMatch >= row.size) return row
if (idxToCompare >= row.size) return merge(row, idxToMatch + 1, idxToMatch + 2)
if (row[idxToMatch] == 0) return merge(row, idxToMatch + 1, idxToMatch + 2)
return if (row[idxToMatch] == row[idxToCompare]) {
row[idxToMatch] *= 2
row[idxToCompare] = 0
merge(row, idxToMatch + 1, idxToMatch + 2)
} else {
if (row[idxToCompare] != 0) merge(row, idxToMatch + 1, idxToMatch + 2)
else merge(row, idxToMatch, idxToCompare + 1)
}
}
fun organize(row: Array<Int>, idxToMatch: Int = 0, idxToCompare: Int = 1): Array<Int> {
if (idxToMatch >= row.size) return row
if (idxToCompare >= row.size) return organize(row, idxToMatch + 1, idxToMatch + 2)
if (row[idxToMatch] != 0) return organize(row, idxToMatch + 1, idxToMatch + 2)
return if (row[idxToCompare] != 0) {
row[idxToMatch] = row[idxToCompare]
row[idxToCompare] = 0
organize(row, idxToMatch + 1, idxToMatch + 2)
} else {
organize(row, idxToMatch, idxToCompare + 1)
}
}
fun display(grid: Array<Array<Int>>) {
val prettyPrintableGrid = grid.map { row ->
row.map { cell ->
if (cell == 0) " " else java.lang.String.format("%4d", cell)
}
}
println("New Grid:")
prettyPrintableGrid.forEach { row ->
println("+----+----+----+----+")
row.forEach { print("|$it") }
println("|")
}
println("+----+----+----+----+")
} | 1,1792048
| 11kotlin
| 54pua |
library(gtools)
solve24 <- function(vals=c(8, 4, 2, 1),
goal=24,
ops=c("+", "-", "*", "/")) {
val.perms <- as.data.frame(t(
permutations(length(vals), length(vals))))
nop <- length(vals)-1
op.perms <- as.data.frame(t(
do.call(expand.grid,
replicate(nop, list(ops)))))
ord.perms <- as.data.frame(t(
do.call(expand.grid,
replicate(n <- nop, 1:((n <<- n-1)+1)))))
for (val.perm in val.perms)
for (op.perm in op.perms)
for (ord.perm in ord.perms)
{
expr <- as.list(vals[val.perm])
for (i in 1:nop) {
expr[[ ord.perm[i] ]] <- call(as.character(op.perm[i]),
expr[[ ord.perm[i] ]],
expr[[ ord.perm[i]+1 ]])
expr <- expr[ -(ord.perm[i]+1) ]
}
if (identical(eval(expr[[1]]), goal)) return(expr[[1]])
}
return(NA)
} | 1,17424 game/Solve
| 13r
| u5wvx |
import Data.Array
import System.Random
type Puzzle = Array (Int, Int) Int
main :: IO ()
main = do
putStrLn "Please enter the difficulty level: 0, 1 or 2"
userInput <- getLine
let diffLevel = read userInput
if userInput == "" || any (\c -> c < '0' || c > '9') userInput || diffLevel > 2 || diffLevel < 0
then putStrLn "That is not a valid difficulty level." >> main
else shufflePuzzle ([10, 50, 100] !! diffLevel) solvedPuzzle >>= gameLoop
gameLoop :: Puzzle -> IO ()
gameLoop puzzle
| puzzle == solvedPuzzle = putStrLn "You solved the puzzle!" >> printPuzzle puzzle
| otherwise = do
printPuzzle puzzle
putStrLn "Please enter number to move"
userInput <- getLine
if any (\c -> c < '0' || c > '9') userInput
then putStrLn "That is not a valid number." >> gameLoop puzzle
else let move = read userInput in
if move `notElem` validMoves puzzle
then putStrLn "This move is not available." >> gameLoop puzzle
else gameLoop (applyMove move puzzle)
validMoves :: Puzzle -> [Int]
validMoves puzzle = [puzzle ! (row', column') |
row' <- [rowEmpty-1..rowEmpty+1], column' <- [columnEmpty-1..columnEmpty+1],
row' < 4, row' >= 0, column' < 4, column' >= 0,
(row' == rowEmpty) /= (column' == columnEmpty)]
where (rowEmpty, columnEmpty) = findIndexOfNumber 16 puzzle
applyMove :: Int -> Puzzle -> Puzzle
applyMove numberToMove puzzle = puzzle // [(indexToMove, 16), (emptyIndex, numberToMove)]
where indexToMove = findIndexOfNumber numberToMove puzzle
emptyIndex = findIndexOfNumber 16 puzzle
findIndexOfNumber :: Int -> Puzzle -> (Int, Int)
findIndexOfNumber number puzzle = case filter (\idx -> number == puzzle ! idx)
(indices puzzle) of
[idx] -> idx
_ -> error "BUG: number not in puzzle"
printPuzzle :: Puzzle -> IO ()
printPuzzle puzzle = do
putStrLn "+
putStrLn $ "|" ++ formatCell (0, 0) ++ "|" ++ formatCell (0, 1) ++ "|" ++ formatCell (0, 2) ++ "|" ++ formatCell (0, 3) ++ "|"
putStrLn "+
putStrLn $ "|" ++ formatCell (1, 0) ++ "|" ++ formatCell (1, 1) ++ "|" ++ formatCell (1, 2) ++ "|" ++ formatCell (1, 3) ++ "|"
putStrLn "+
putStrLn $ "|" ++ formatCell (2, 0) ++ "|" ++ formatCell (2, 1) ++ "|" ++ formatCell (2, 2) ++ "|" ++ formatCell (2, 3) ++ "|"
putStrLn "+
putStrLn $ "|" ++ formatCell (3, 0) ++ "|" ++ formatCell (3, 1) ++ "|" ++ formatCell (3, 2) ++ "|" ++ formatCell (3, 3) ++ "|"
putStrLn "+
where formatCell idx
| i == 16 = " "
| i > 9 = show i
| otherwise = " " ++ show i
where i = puzzle ! idx
solvedPuzzle :: Puzzle
solvedPuzzle = listArray ((0, 0), (3, 3)) [1..16]
shufflePuzzle :: Int -> Puzzle -> IO Puzzle
shufflePuzzle 0 puzzle = return puzzle
shufflePuzzle numOfShuffels puzzle = do
let moves = validMoves puzzle
randomIndex <- randomRIO (0, length moves - 1)
let move = moves !! randomIndex
shufflePuzzle (numOfShuffels - 1) (applyMove move puzzle) | 1,18015 puzzle game
| 8haskell
| df9n4 |
null | 1,1792048
| 1lua
| 4g15c |
package fifteenpuzzle;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import javax.swing.*;
class FifteenPuzzle extends JPanel {
private final int side = 4;
private final int numTiles = side * side - 1;
private final Random rand = new Random();
private final int[] tiles = new int[numTiles + 1];
private final int tileSize;
private int blankPos;
private final int margin;
private final int gridSize;
private boolean gameOver;
private FifteenPuzzle() {
final int dim = 640;
margin = 80;
tileSize = (dim - 2 * margin) / side;
gridSize = tileSize * side;
setPreferredSize(new Dimension(dim, dim + margin));
setBackground(Color.WHITE);
setForeground(new Color(0x6495ED)); | 1,18015 puzzle game
| 9java
| s0tq0 |
local function help()
print [[
The 24 Game
Given any four digits in the range 1 to 9, which may have repetitions,
Using just the +, -, *, and / operators; and the possible use of
brackets, (), show how to make an answer of 24.
An answer of "q" will quit the game.
An answer of "!" will generate a new set of four digits.
Note: you cannot form multiple digit numbers from the supplied digits,
so an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.
]]
end
local function generate(n)
result = {}
for i=1,n do
result[i] = math.random(1,9)
end
return result
end
local function check(answer, digits)
local adig = {}
local ddig = {}
local index
local lastWasDigit = false
for i=1,9 do adig[i] = 0 ddig[i] = 0 end
allowed = {['(']=true,[')']=true,[' ']=true,['+']=true,['-']=true,['*']=true,['/']=true,['\t']=true,['1']=true,['2']=true,['3']=true,['4']=true,['5']=true,['6']=true,['7']=true,['8']=true,['9']=true}
for i=1,string.len(answer) do
if not allowed[string.sub(answer,i,i)] then
return false
end
index = string.byte(answer,i)-48
if index > 0 and index < 10 then
if lastWasDigit then
return false
end
lastWasDigit = true
adig[index] = adig[index] + 1
else
lastWasDigit = false
end
end
for i,digit in next,digits do
ddig[digit] = ddig[digit]+1
end
for i=1,9 do
if adig[i] ~= ddig[i] then
return false
end
end
return loadstring('return '..answer)()
end
local function game24()
help()
math.randomseed(os.time())
math.random()
local digits = generate(4)
local trial = 0
local answer = 0
local ans = false
io.write 'Your four digits:'
for i,digit in next,digits do
io.write (' ' .. digit)
end
print()
while ans ~= 24 do
trial = trial + 1
io.write("Expression "..trial..": ")
answer = io.read()
if string.lower(answer) == 'q' then
break
end
if answer == '!' then
digits = generate(4)
io.write ("New digits:")
for i,digit in next,digits do
io.write (' ' .. digit)
end
print()
else
ans = check(answer,digits)
if ans == false then
print ('The input '.. answer ..' was wonky!')
else
print (' = '.. ans)
if ans == 24 then
print ("Thats right!")
end
end
end
end
end
game24() | 1,17524 game
| 1lua
| s0mq8 |
var board, zx, zy, clicks, possibles, clickCounter, oldzx = -1, oldzy = -1;
function getPossibles() {
var ii, jj, cx = [-1, 0, 1, 0], cy = [0, -1, 0, 1];
possibles = [];
for( var i = 0; i < 4; i++ ) {
ii = zx + cx[i]; jj = zy + cy[i];
if( ii < 0 || ii > 3 || jj < 0 || jj > 3 ) continue;
possibles.push( { x: ii, y: jj } );
}
}
function updateBtns() {
var b, v, id;
for( var j = 0; j < 4; j++ ) {
for( var i = 0; i < 4; i++ ) {
id = "btn" + ( i + j * 4 );
b = document.getElementById( id );
v = board[i][j];
if( v < 16 ) {
b.innerHTML = ( "" + v );
b.className = "button"
}
else {
b.innerHTML = ( "" );
b.className = "empty";
}
}
}
clickCounter.innerHTML = "Clicks: " + clicks;
}
function shuffle() {
var v = 0, t;
do {
getPossibles();
while( true ) {
t = possibles[Math.floor( Math.random() * possibles.length )];
console.log( t.x, oldzx, t.y, oldzy )
if( t.x != oldzx || t.y != oldzy ) break;
}
oldzx = zx; oldzy = zy;
board[zx][zy] = board[t.x][t.y];
zx = t.x; zy = t.y;
board[zx][zy] = 16;
} while( ++v < 200 );
}
function restart() {
shuffle();
clicks = 0;
updateBtns();
}
function checkFinished() {
var a = 0;
for( var j = 0; j < 4; j++ ) {
for( var i = 0; i < 4; i++ ) {
if( board[i][j] < a ) return false;
a = board[i][j];
}
}
return true;
}
function btnHandle( e ) {
getPossibles();
var c = e.target.i, r = e.target.j, p = -1;
for( var i = 0; i < possibles.length; i++ ) {
if( possibles[i].x == c && possibles[i].y == r ) {
p = i;
break;
}
}
if( p > -1 ) {
clicks++;
var t = possibles[p];
board[zx][zy] = board[t.x][t.y];
zx = t.x; zy = t.y;
board[zx][zy] = 16;
updateBtns();
if( checkFinished() ) {
setTimeout(function(){
alert( "WELL DONE!" );
restart();
}, 1);
}
}
}
function createBoard() {
board = new Array( 4 );
for( var i = 0; i < 4; i++ ) {
board[i] = new Array( 4 );
}
for( var j = 0; j < 4; j++ ) {
for( var i = 0; i < 4; i++ ) {
board[i][j] = ( i + j * 4 ) + 1;
}
}
zx = zy = 3; board[zx][zy] = 16;
}
function createBtns() {
var b, d = document.createElement( "div" );
d.className += "board";
document.body.appendChild( d );
for( var j = 0; j < 4; j++ ) {
for( var i = 0; i < 4; i++ ) {
b = document.createElement( "button" );
b.id = "btn" + ( i + j * 4 );
b.i = i; b.j = j;
b.addEventListener( "click", btnHandle, false );
b.appendChild( document.createTextNode( "" ) );
d.appendChild( b );
}
}
clickCounter = document.createElement( "p" );
clickCounter.className += "txt";
document.body.appendChild( clickCounter );
}
function start() {
createBtns();
createBoard();
restart();
} | 1,18015 puzzle game
| 10javascript
| ndmiy |
class TwentyFourGame
EXPRESSIONS = [
'((%dr%s%dr)%s%dr)%s%dr',
'(%dr%s (%dr%s%dr))%s%dr',
'(%dr%s%dr)%s (%dr%s%dr)',
'%dr%s ((%dr%s%dr)%s%dr)',
'%dr%s (%dr%s (%dr%s%dr))',
]
OPERATORS = [:+,:-,:*,:/].repeated_permutation(3).to_a
def self.solve(digits)
solutions = []
perms = digits.permutation.to_a.uniq
perms.product(OPERATORS, EXPRESSIONS) do |(a,b,c,d), (op1,op2,op3), expr|
text = expr % [a, op1, b, op2, c, op3, d]
value = eval(text) rescue next
solutions << text.delete() if value == 24
end
solutions
end
end
digits = ARGV.map do |arg|
begin
Integer(arg)
rescue ArgumentError
raise
end
end
digits.size == 4 or raise
solutions = TwentyFourGame.solve(digits)
if solutions.empty?
puts
else
puts
puts solutions.sort
end | 1,17424 game/Solve
| 14ruby
| jho7x |
use strict;
use warnings;
use feature 'say';
use List::Util 'shuffle';
sub simulation {
my($population,$trials,$strategy) = @_;
my $optimal = $strategy =~ /^o/i ? 1 : 0;
my @prisoners = 0..$population-1;
my $half = int $population / 2;
my $pardoned = 0;
for (1..$trials) {
my @drawers = shuffle @prisoners;
my $total = 0;
for my $prisoner (@prisoners) {
my $found = 0;
if ($optimal) {
my $card = $drawers[$prisoner];
if ($card == $prisoner) {
$found = 1;
} else {
for (1..$half-1) {
$card = $drawers[$card];
($found = 1, last) if $card == $prisoner
}
}
} else {
for my $card ( (shuffle @drawers)[0..$half]) {
($found = 1, last) if $card == $prisoner
}
}
last unless $found;
$total++;
}
$pardoned++ if $total == $population;
}
$pardoned / $trials * 100
}
my $population = 100;
my $trials = 10000;
say " Simulation count: $trials\n" .
(sprintf " Random strategy pardons:%6.3f%% of simulations\n", simulation $population, $trials, 'random' ) .
(sprintf "Optimal strategy pardons:%6.3f%% of simulations\n", simulation $population, $trials, 'optimal');
$population = 10;
$trials = 100000;
say " Simulation count: $trials\n" .
(sprintf " Random strategy pardons:%6.3f%% of simulations\n", simulation $population, $trials, 'random' ) .
(sprintf "Optimal strategy pardons:%6.3f%% of simulations\n", simulation $population, $trials, 'optimal'); | 1,176100 prisoners
| 2perl
| 2vplf |
#[derive(Clone, Copy, Debug)]
enum Operator {
Sub,
Plus,
Mul,
Div,
}
#[derive(Clone, Debug)]
struct Factor {
content: String,
value: i32,
}
fn apply(op: Operator, left: &[Factor], right: &[Factor]) -> Vec<Factor> {
let mut ret = Vec::new();
for l in left.iter() {
for r in right.iter() {
use Operator::*;
ret.push(match op {
Sub if l.value > r.value => Factor {
content: format!("({} - {})", l.content, r.content),
value: l.value - r.value,
},
Plus => Factor {
content: format!("({} + {})", l.content, r.content),
value: l.value + r.value,
},
Mul => Factor {
content: format!("({} x {})", l.content, r.content),
value: l.value * r.value,
},
Div if l.value >= r.value && r.value > 0 && l.value% r.value == 0 => Factor {
content: format!("({} / {})", l.content, r.content),
value: l.value / r.value,
},
_ => continue,
})
}
}
ret
}
fn calc(op: [Operator; 3], numbers: [i32; 4]) -> Vec<Factor> {
fn calc(op: &[Operator], numbers: &[i32], acc: &[Factor]) -> Vec<Factor> {
use Operator::*;
if op.is_empty() {
return Vec::from(acc)
}
let mut ret = Vec::new();
let mono_factor = [Factor {
content: numbers[0].to_string(),
value: numbers[0],
}];
match op[0] {
Mul => ret.extend_from_slice(&apply(op[0], acc, &mono_factor)),
Div => {
ret.extend_from_slice(&apply(op[0], acc, &mono_factor));
ret.extend_from_slice(&apply(op[0], &mono_factor, acc));
},
Sub => {
ret.extend_from_slice(&apply(op[0], acc, &mono_factor));
ret.extend_from_slice(&apply(op[0], &mono_factor, acc));
},
Plus => ret.extend_from_slice(&apply(op[0], acc, &mono_factor)),
}
calc(&op[1..], &numbers[1..], &ret)
}
calc(&op, &numbers[1..], &[Factor { content: numbers[0].to_string(), value: numbers[0] }])
}
fn solutions(numbers: [i32; 4]) -> Vec<Factor> {
use std::collections::hash_set::HashSet;
let mut ret = Vec::new();
let mut hash_set = HashSet::new();
for ops in OpIter(0) {
for o in orders().iter() {
let numbers = apply_order(numbers, o);
let r = calc(ops, numbers);
ret.extend(r.into_iter().filter(|&Factor { value, ref content }| value == 24 && hash_set.insert(content.to_owned())))
}
}
ret
}
fn main() {
let mut numbers = Vec::new();
if let Some(input) = std::env::args().skip(1).next() {
for c in input.chars() {
if let Ok(n) = c.to_string().parse() {
numbers.push(n)
}
if numbers.len() == 4 {
let numbers = [numbers[0], numbers[1], numbers[2], numbers[3]];
let solutions = solutions(numbers);
let len = solutions.len();
if len == 0 {
println!("no solution for {}, {}, {}, {}", numbers[0], numbers[1], numbers[2], numbers[3]);
return
}
println!("solutions for {}, {}, {}, {}", numbers[0], numbers[1], numbers[2], numbers[3]);
for s in solutions {
println!("{}", s.content)
}
println!("{} solutions found", len);
return
}
}
} else {
println!("empty input")
}
}
struct OpIter (usize);
impl Iterator for OpIter {
type Item = [Operator; 3];
fn next(&mut self) -> Option<[Operator; 3]> {
use Operator::*;
const OPTIONS: [Operator; 4] = [Mul, Sub, Plus, Div];
if self.0 >= 1 << 6 {
return None
}
let f1 = OPTIONS[(self.0 & (3 << 4)) >> 4];
let f2 = OPTIONS[(self.0 & (3 << 2)) >> 2];
let f3 = OPTIONS[(self.0 & (3 << 0)) >> 0];
self.0 += 1;
Some([f1, f2, f3])
}
}
fn orders() -> [[usize; 4]; 24] {
[
[0, 1, 2, 3],
[0, 1, 3, 2],
[0, 2, 1, 3],
[0, 2, 3, 1],
[0, 3, 1, 2],
[0, 3, 2, 1],
[1, 0, 2, 3],
[1, 0, 3, 2],
[1, 2, 0, 3],
[1, 2, 3, 0],
[1, 3, 0, 2],
[1, 3, 2, 0],
[2, 0, 1, 3],
[2, 0, 3, 1],
[2, 1, 0, 3],
[2, 1, 3, 0],
[2, 3, 0, 1],
[2, 3, 1, 0],
[3, 0, 1, 2],
[3, 0, 2, 1],
[3, 1, 0, 2],
[3, 1, 2, 0],
[3, 2, 0, 1],
[3, 2, 1, 0]
]
}
fn apply_order(numbers: [i32; 4], order: &[usize; 4]) -> [i32; 4] {
[numbers[order[0]], numbers[order[1]], numbers[order[2]], numbers[order[3]]]
} | 1,17424 game/Solve
| 15rust
| hkij2 |
null | 1,18015 puzzle game
| 11kotlin
| aeo13 |
def permute(l: List[Double]): List[List[Double]] = l match {
case Nil => List(Nil)
case x :: xs =>
for {
ys <- permute(xs)
position <- 0 to ys.length
(left, right) = ys splitAt position
} yield left ::: (x :: right)
}
def computeAllOperations(l: List[Double]): List[(Double,String)] = l match {
case Nil => Nil
case x :: Nil => List((x, "%1.0f" format x))
case x :: xs =>
for {
(y, ops) <- computeAllOperations(xs)
(z, op) <-
if (y == 0)
List((x*y, "*"), (x+y, "+"), (x-y, "-"))
else
List((x*y, "*"), (x/y, "/"), (x+y, "+"), (x-y, "-"))
} yield (z, "(%1.0f%s%s)" format (x,op,ops))
}
def hasSolution(l: List[Double]) = permute(l) flatMap computeAllOperations filter (_._1 == 24) map (_._2) | 1,17424 game/Solve
| 16scala
| p1fbj |
int main(void)
{
int n;
for( n = 99; n > 2; n-- )
printf(
,
n, n, n - 1);
printf(
);
return 0;
} | 1,18199 bottles of beer
| 5c
| r71g7 |
math.randomseed( os.time() )
local puz = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0 }
local dir = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } }
local sx, sy = 4, 4
function isValid( tx, ty )
return tx > 0 and tx < 5 and ty > 0 and ty < 5
end
function display()
io.write( "\n\n" )
for j = 1, 4 do
io.write( "+ | 1,18015 puzzle game
| 1lua
| ewiac |
use strict;
use warnings;
use Tk;
my $N = shift // 4;
$N < 2 and $N = 2;
my @squares = 1 .. $N*$N;
my %n2ch = (' ' => ' ');
@n2ch{ map 2**$_, 1..26} = 'a'..'z';
my %ch2n = reverse %n2ch;
my $winner = '';
my @arow = 0 .. $N - 1;
my @acol = map $_ * $N, @arow;
my $mw = MainWindow->new;
$mw->geometry( '+300+0' );
$mw->title( 2048 );
$mw->focus;
$mw->bind('<KeyPress-Left>' => sub { arrow($N, @arow) } );
$mw->bind('<KeyPress-Right>' => sub { arrow($N, reverse @arow) } );
$mw->bind('<KeyPress-Up>' => sub { arrow(1, @acol) } );
$mw->bind('<KeyPress-Down>' => sub { arrow(1, reverse @acol) } );
my $grid = $mw->Frame()->pack;
for my $i ( 0 .. $
{
$grid->Label(-textvariable => \$squares[$i],
-width => 5, -height => 2, -font => 'courierbold 30',
-relief => 'ridge', -borderwidth => 5,
)->grid(-row => int $i / $N, -column => $i % $N );
}
my $buttons = $mw->Frame()->pack(-fill => 'x', -expand => 1);
$buttons->Button(-text => 'Exit', -command => sub {$mw->destroy},
-font => 'courierbold 14',
)->pack(-side => 'right');
$buttons->Button(-text => 'New Game', -command => \&newgame,
-font => 'courierbold 14',
)->pack(-side => 'left');
$buttons->Label(-textvariable => \$winner,
-font => 'courierbold 18', -fg => 'red2',
)->pack;
newgame();
MainLoop;
-M $0 < 0 and exec $0;
sub losecheck
{
local $_ = join '', @n2ch{ @squares };
/ / || ($_ ^ substr $_, $N) =~ tr/\0// and return;
/(.)\1/ and return for /.{$N}/g;
$winner = 'You Lost';
}
sub arrow
{
$winner and return;
my ($inc, @ix) = @_;
my $oldboard = "@squares";
for ( 1 .. $N )
{
local $_ = join '', @n2ch{ @squares[@ix] };
tr/ //d;
s/(\w)\1/ chr 1 + ord $1 /ge;
@squares[@ix] = @ch2n{ split //, $_ . ' ' x $N };
$_ += $inc for @ix;
}
$oldboard eq "@squares" and return;
add2();
losecheck();
grep $_ eq 2048, @squares and $winner = 'WINNER!!';
}
sub add2
{
my @blanks = grep $squares[$_] eq ' ', 0 .. $
@blanks and $squares[ $blanks[rand @blanks] ] =
$_[0] // (rand() < 0.1 ? 4 : 2);
}
sub newgame
{
$_ = ' ' for @squares;
add2(2) for 1, 2;
$winner = '';
} | 1,1792048
| 2perl
| oiy8x |
import Darwin
import Foundation
var solution = ""
println("24 Game")
println("Generating 4 digits...")
func randomDigits() -> [Int] {
var result = [Int]()
for i in 0 ..< 4 {
result.append(Int(arc4random_uniform(9)+1))
}
return result
} | 1,17424 game/Solve
| 17swift
| 7j8rq |
<?php
$game = new Game();
while(true) {
$game->cycle();
}
class Game {
private $field;
private $fieldSize;
private $command;
private $error;
private $lastIndexX, $lastIndexY;
private $score;
private $finishScore;
function __construct() {
$this->field = array();
$this->fieldSize = 4;
$this->finishScore = 2048;
$this->score = 0;
$this->addNumber();
$this->render();
}
public function cycle() {
$this->command = strtolower($this->readchar('Use WASD, q exits'));
$this->cls();
if($this->processCommand()) {
$this->addNumber();
} else {
if(count($this->getFreeList()) == 0 ) {
$this->error = 'No options left!, You Lose!!';
} else {
$this->error = 'Invalid move, try again!';
}
}
$this->render();
}
private function readchar($prompt) {
readline_callback_handler_install($prompt, function() {});
$char = stream_get_contents(STDIN, 1);
readline_callback_handler_remove();
return $char;
}
private function addNumber() {
$freeList = $this->getFreeList();
if(count($freeList) == 0) {
return;
}
$index = mt_rand(0, count($freeList)-1);
$nr = (mt_rand(0,9) == 0)? 4 : 2;
$this->field[$freeList[$index]['x']][$freeList[$index]['y']] = $nr;
return;
}
private function getFreeList() {
$freeList = array();
for($y =0; $y< $this->fieldSize;$y++) {
for($x=0; $x < $this->fieldSize; $x++) {
if(!isset($this->field[$x][$y])) {
$freeList[] = array('x' => $x, 'y' => $y);
} elseif($this->field[$x][$y] == $this->finishScore) {
$this->error = 'You Win!!';
}
}
}
return $freeList;
}
private function processCommand() {
if(!in_array($this->command, array('w','a','s','d','q'))) {
$this->error = 'Invalid Command';
return false;
}
if($this->command == 'q') {
echo PHP_EOL. 'Bye!'. PHP_EOL;
exit;
}
$axis = 'x';
$sDir = 1;
switch($this->command) {
case 'w':
$axis = 'y';
$sDir = -1;
break;
case 'a':
$sDir = -1;
break;
case 's':
$axis = 'y';
break;
case 'd':
break;
}
$done = 0;
$done += $this->shift($axis, $sDir);
$done += $this->merge($axis, $sDir * -1);
$done += $this->shift($axis, $sDir);
return $done >0;
}
private function shift($axis, $dir) {
$totalDone = 0;
for($i = 0; $i <$this->fieldSize; $i++) {
$done = 0;
foreach($this->iterate($axis,$dir) as $xy) {
if($xy['vDest'] === NULL && $xy['vSrc'] !== NULL) {
$this->field[$xy['dX']][$xy['dY']] = $xy['vSrc'];
$this->field[$xy['sX']][$xy['sY']] = NULL;
$done++;
}
}
$totalDone += $done;
if($done == 0) {
break;
}
}
return $totalDone;
}
private function merge($axis, $dir) {
$done = 0;
foreach($this->iterate($axis,$dir) as $xy) {
if($xy['vDest'] !== NULL && $xy['vDest'] === $xy['vSrc']) {
$this->field[$xy['sX']][$xy['sY']] += $xy['vDest'];
$this->field[$xy['dX']][$xy['dY']] = NULL;
$this->score += $this->field[$xy['sX']][$xy['sY']];
$done ++;
}
}
return $done;
}
private function iterate($axis, $dir) {
$res = array();
for($y = 0; $y < $this->fieldSize; $y++) {
for($x=0; $x < $this->fieldSize; $x++) {
$item = array('sX'=> $x,'sY' => $y, 'dX' => $x, 'dY' => $y, 'vDest' => NULL,'vSrc' => NULL);
if($axis == 'x') {
$item['dX'] += $dir;
} else {
$item['dY'] += $dir;
}
if($item['dX'] >= $this->fieldSize || $item['dY'] >=$this->fieldSize || $item['dX'] < 0 || $item['dY'] < 0) {
continue;
}
$item['vDest'] = (isset($this->field[$item['dX']][$item['dY']]))? $this->field[$item['dX']][$item['dY']] : NULL;
$item['vSrc'] = (isset($this->field[$item['sX']][$item['sY']]))? $this->field[$item['sX']][$item['sY']] : NULL;
$res[] = $item;
}
}
if($dir < 0) {
$res = array_reverse($res);
}
return $res;
}
private function cls() {
echo chr(27).chr(91).'H'.chr(27).chr(91).'J';
}
private function render() {
echo $this->finishScore . '! Current score: '. $this->score .PHP_EOL;
if(!empty($this->error)) {
echo $this->error . PHP_EOL;
$this->error = NULL;
}
$this->renderField();
}
private function renderField() {
$width = 5;
$this->renderVSeperator($width);
for($y =0; $y < $this->fieldSize; $y ++) {
for($x = 0;$x < $this->fieldSize; $x++) {
echo '|';
if(!isset($this->field[$x][$y])) {
echo str_repeat(' ', $width);
continue;
}
printf('%'.$width.'s', $this->field[$x][$y]);
}
echo '|'. PHP_EOL;
$this->renderVSeperator($width);
}
}
private function renderVSeperator($width) {
echo str_repeat('+'. str_repeat('-', $width), $this->fieldSize) .'+' .PHP_EOL;
}
} | 1,1792048
| 12php
| gra42 |
use warnings;
use strict;
sub can_make_word {
my ($word, @blocks) = @_;
$_ = uc join q(), sort split // for @blocks;
my %blocks;
$blocks{$_}++ for @blocks;
return _can_make_word(uc $word, %blocks)
}
sub _can_make_word {
my ($word, %blocks) = @_;
my $char = substr $word, 0, 1, q();
my @candidates = grep 0 <= index($_, $char), keys %blocks;
for my $candidate (@candidates) {
next if $blocks{$candidate} <= 0;
local $blocks{$candidate} = $blocks{$candidate} - 1;
return 1 if q() eq $word or _can_make_word($word, %blocks);
}
return
} | 1,173ABC problem
| 2perl
| tzrfg |
<?php
$words = array(, , , , , , );
function canMakeWord($word) {
$word = strtoupper($word);
$blocks = array(
, , , , ,
, , , , ,
, , , , ,
, , , , ,
);
foreach (str_split($word) as $char) {
foreach ($blocks as $k => $block) {
if (strpos($block, $char) !== FALSE) {
unset($blocks[$k]);
continue(2);
}
}
return false;
}
return true;
}
foreach ($words as $word) {
echo $word.': ';
echo canMakeWord($word)? : ;
echo ;
} | 1,173ABC problem
| 12php
| kbdhv |
import random
def play_random(n):
pardoned = 0
in_drawer = list(range(100))
sampler = list(range(100))
for _round in range(n):
random.shuffle(in_drawer)
found = False
for prisoner in range(100):
found = False
for reveal in random.sample(sampler, 50):
card = in_drawer[reveal]
if card == prisoner:
found = True
break
if not found:
break
if found:
pardoned += 1
return pardoned / n * 100
def play_optimal(n):
pardoned = 0
in_drawer = list(range(100))
for _round in range(n):
random.shuffle(in_drawer)
for prisoner in range(100):
reveal = prisoner
found = False
for go in range(50):
card = in_drawer[reveal]
if card == prisoner:
found = True
break
reveal = card
if not found:
break
if found:
pardoned += 1
return pardoned / n * 100
if __name__ == '__main__':
n = 100_000
print(, n)
print(f)
print(f) | 1,176100 prisoners
| 3python
| vu129 |
t = 100000
success.r = rep(0,t)
success.o = rep(0,t)
for(i in 1:t){
escape = rep(F,100)
ticket = sample(1:100)
for(j in 1:length(prisoner)){
escape[j] = j%in% sample(ticket,50)
}
success.r[i] = sum(escape)
}
for(i in 1:t){
escape = rep(F,100)
ticket = sample(1:100)
for(j in 1:100){
boxes = 0
current.box = j
while(boxes<50 &&!escape[j]){
boxes=boxes+1
escape[j] = ticket[current.box]==j
current.box = ticket[current.box]
}
}
success.o[i] = sum(escape)
}
cat("Random method resulted in a success rate of ",100*mean(success.r==100),
"%.\nOptimal method resulted in a success rate of ",100*mean(success.o==100),"%.",sep="") | 1,176100 prisoners
| 13r
| 9chmg |
import curses
from random import randrange, choice
from collections import defaultdict
letter_codes = [ord(ch) for ch in 'WASDRQwasdrq']
actions = ['Up', 'Left', 'Down', 'Right', 'Restart', 'Exit']
actions_dict = dict(zip(letter_codes, actions * 2))
def get_user_action(keyboard):
char =
while char not in actions_dict:
char = keyboard.getch()
return actions_dict[char]
def transpose(field):
return [list(row) for row in zip(*field)]
def invert(field):
return [row[::-1] for row in field]
class GameField(object):
def __init__(self, height=4, width=4, win=2048):
self.height = height
self.width = width
self.win_value = win
self.score = 0
self.highscore = 0
self.reset()
def reset(self):
if self.score > self.highscore:
self.highscore = self.score
self.score = 0
self.field = [[0 for i in range(self.width)] for j in range(self.height)]
self.spawn()
self.spawn()
def move(self, direction):
def move_row_left(row):
def tighten(row):
new_row = [i for i in row if i != 0]
new_row += [0 for i in range(len(row) - len(new_row))]
return new_row
def merge(row):
pair = False
new_row = []
for i in range(len(row)):
if pair:
new_row.append(2 * row[i])
self.score += 2 * row[i]
pair = False
else:
if i + 1 < len(row) and row[i] == row[i + 1]:
pair = True
new_row.append(0)
else:
new_row.append(row[i])
assert len(new_row) == len(row)
return new_row
return tighten(merge(tighten(row)))
moves = {}
moves['Left'] = lambda field: \
[move_row_left(row) for row in field]
moves['Right'] = lambda field: \
invert(moves['Left'](invert(field)))
moves['Up'] = lambda field: \
transpose(moves['Left'](transpose(field)))
moves['Down'] = lambda field: \
transpose(moves['Right'](transpose(field)))
if direction in moves:
if self.move_is_possible(direction):
self.field = moves[direction](self.field)
self.spawn()
return True
else:
return False
def is_win(self):
return any(any(i >= self.win_value for i in row) for row in self.field)
def is_gameover(self):
return not any(self.move_is_possible(move) for move in actions)
def draw(self, screen):
help_string1 = '(W)Up (S)Down (A)Left (D)Right'
help_string2 = ' (R)Restart (Q)Exit'
gameover_string = ' GAME OVER'
win_string = ' YOU WIN!'
def cast(string):
screen.addstr(string + '\n')
def draw_hor_separator():
top = '' + ('' * self.width + '')[1:]
mid = '' + ('' * self.width + '')[1:]
bot = '' + ('' * self.width + '')[1:]
separator = defaultdict(lambda: mid)
separator[0], separator[self.height] = top, bot
if not hasattr(draw_hor_separator, ):
draw_hor_separator.counter = 0
cast(separator[draw_hor_separator.counter])
draw_hor_separator.counter += 1
def draw_row(row):
cast(''.join('{: ^5} '.format(num) if num > 0 else '| ' for num in row) + '')
screen.clear()
cast('SCORE: ' + str(self.score))
if 0 != self.highscore:
cast('HIGHSCORE: ' + str(self.highscore))
for row in self.field:
draw_hor_separator()
draw_row(row)
draw_hor_separator()
if self.is_win():
cast(win_string)
else:
if self.is_gameover():
cast(gameover_string)
else:
cast(help_string1)
cast(help_string2)
def spawn(self):
new_element = 4 if randrange(100) > 89 else 2
(i,j) = choice([(i,j) for i in range(self.width) for j in range(self.height) if self.field[i][j] == 0])
self.field[i][j] = new_element
def move_is_possible(self, direction):
def row_is_left_movable(row):
def change(i):
if row[i] == 0 and row[i + 1] != 0:
return True
if row[i] != 0 and row[i + 1] == row[i]:
return True
return False
return any(change(i) for i in range(len(row) - 1))
check = {}
check['Left'] = lambda field: \
any(row_is_left_movable(row) for row in field)
check['Right'] = lambda field: \
check['Left'](invert(field))
check['Up'] = lambda field: \
check['Left'](transpose(field))
check['Down'] = lambda field: \
check['Right'](transpose(field))
if direction in check:
return check[direction](self.field)
else:
return False
def main(stdscr):
curses.use_default_colors()
game_field = GameField(win=32)
state_actions = {}
def init():
game_field.reset()
return 'Game'
state_actions['Init'] = init
def not_game(state):
game_field.draw(stdscr)
action = get_user_action(stdscr)
responses = defaultdict(lambda: state)
responses['Restart'], responses['Exit'] = 'Init', 'Exit'
return responses[action]
state_actions['Win'] = lambda: not_game('Win')
state_actions['Gameover'] = lambda: not_game('Gameover')
def game():
game_field.draw(stdscr)
action = get_user_action(stdscr)
if action == 'Restart':
return 'Init'
if action == 'Exit':
return 'Exit'
if game_field.move(action):
if game_field.is_win():
return 'Win'
if game_field.is_gameover():
return 'Gameover'
return 'Game'
state_actions['Game'] = game
state = 'Init'
while state != 'Exit':
state = state_actions[state]()
curses.wrapper(main) | 1,1792048
| 3python
| inmof |
use strict;
use warnings;
use Getopt::Long;
use List::Util 1.29 qw(shuffle pairmap first all);
use Tk;
my ($verbose,@fixed,$nocolor,$charsize,$extreme,$solvability);
unless (GetOptions (
'verbose!' => \$verbose,
'tiles|positions=i{16}' => \@fixed,
'nocolor' => \$nocolor,
'charsize|size|c|s=i' => \$charsize,
'extreme|x|perl' => \$extreme,
)
) { die "invalid arguments!";}
@fixed = &check_req_pos(@fixed) if @fixed;
my $mw = Tk::MainWindow->new(-bg=>'black',-title=>'Giuoco del 15');
if ($nocolor){ $mw->optionAdd( '*Button.background', 'ivory' );}
$mw->optionAdd('*Button.font', 'Courier '.($charsize or 16).' bold' );
$mw->bind('<Control-s>', sub{
&shuffle_board});
my $top_frame = $mw->Frame( -borderwidth => 2, -relief => 'groove',
)->pack(-expand => 1, -fill => 'both');
$top_frame->Label( -textvariable=>\$solvability,
)->pack(-expand => 1, -fill => 'both');
my $game_frame = $mw->Frame( -background=>'saddlebrown',
-borderwidth => 10, -relief => 'groove',
)->pack(-expand => 1, -fill => 'both');
my @vic_cond = pairmap {
[$a,$b]
} qw(0 0 0 1 0 2 0 3
1 0 1 1 1 2 1 3
2 0 2 1 2 2 2 3
3 0 3 1 3 2 3 3);
my $board = [];
my $victorious = 0;
&init_board;
if ( $extreme ){ &extreme_perl}
&shuffle_board;
MainLoop;
sub init_board{
for (0..14){
$$board[$_]={
btn=>$game_frame->Button(
-text => $_+1,
-relief => 'raised',
-borderwidth => 3,
-height => 2,
-width => 4,
-background=>$nocolor?'ivory':'gold1',
-activebackground => $nocolor?'ivory':'gold1',
-foreground=> $nocolor?'black':'DarkRed',
-activeforeground=>$nocolor?'black':'DarkRed'
),
name => $_+1,
};
if (($_+1) =~ /^(2|4|5|7|10|12|13|15)$/ and !$nocolor){
$$board[$_]{btn}->configure(
-background=>'DarkRed',
-activebackground => 'DarkRed',
-foreground=> 'gold1',
-activeforeground=>'gold1'
);
}
}
$$board[15]={
btn=>$game_frame->Button(
-relief => 'sunken',
-borderwidth => 3,
-background => 'lavender',
-height => 2,
-width => 4,
),
name => 16,
};
}
sub shuffle_board{
if ($victorious){
$victorious=0;
&init_board;
}
if (@fixed){
my $index = 0;
foreach my $tile(@$board[@fixed]){
my $xy = $vic_cond[$index];
($$tile{x},$$tile{y}) = @$xy;
$$tile{btn}->grid(-row=>$$xy[0], -column=> $$xy[1]);
$$tile{btn}->configure(-command =>[\&move,$$xy[0],$$xy[1]]);
$index++;
}
undef @fixed;
}
else{
my @valid = shuffle (0..15);
foreach my $tile ( @$board ){
my $xy = $vic_cond[shift @valid];
($$tile{x},$$tile{y}) = @$xy;
$$tile{btn}->grid(-row=>$$xy[0], -column=> $$xy[1]);
$$tile{btn}->configure(-command => [ \&move, $$xy[0], $$xy[1] ]);
}
}
my @appear = map {$_->{name}==16?'X':$_->{name}}
sort{$$a{x}<=>$$b{x}||$$a{y}<=>$$b{y}}@$board;
print "\n".('-' x 57)."\n".
"Appearence of the board:\n[@appear]\n".
('-' x 57)."\n".
"current\tfollowers\t less than current\n".
('-' x 57)."\n" if $verbose;
@appear = grep{$_ ne 'X'} @appear;
my $permutation;
foreach my $num (0..$
last if $num == $
my $perm;
$perm += grep {$_ < $appear[$num]} @appear[$num+1..$
if ($verbose){
print "[$appear[$num]]\t@appear[$num+1..$
(" " x (37 - length "@appear[$num+1..$
"\t $perm ".($num == $
}
$permutation+=$perm;
}
print +(' ' x 50)."----\n" if $verbose;
if ($permutation % 2){
print "Impossible game with odd permutations!".(' ' x 13).
"$permutation\n"if $verbose;
$solvability = "Impossible game with odd permutations [$permutation]\n".
"(ctrl-s to shuffle)".
(($verbose or $extreme) ? '' :
" run with --verbose to see more info");
return;
}
my $diff = $permutation == 0 ? 'SOLVED' :
$permutation < 35 ? 'EASY ' :
$permutation < 70 ? 'MEDIUM' : 'HARD ';
print "$diff game with even permutations".(' ' x 17).
"$permutation\n" if $verbose;
$solvability = "$diff game with permutation parity of [$permutation]\n".
"(ctrl-s to shuffle)";
}
sub move{
my ($ox, $oy) = @_;
my $self = first{$_->{x} == $ox and $_->{y} == $oy} @$board;
return if $$self{name}==16;
my $empty = first {$_->{name} == 16 and
( ($_->{x}==$ox-1 and $_->{y}==$oy) or
($_->{x}==$ox+1 and $_->{y}==$oy) or
($_->{x}==$ox and $_->{y}==$oy-1) or
($_->{x}==$ox and $_->{y}==$oy+1)
)
} @$board;
return unless $empty;
my ($ex,$ey) = ($$empty{x},$$empty{y});
$$empty{btn}->grid(-row => $ox, -column => $oy);
$$empty{x}=$ox; $$empty{y}=$oy;
$$self{btn}->grid(-row => $ex, -column => $ey);
$$self{btn}->configure(-command => [ \&move, $ex, $ey ]);
$$self{x}=$ex; $$self{y}=$ey;
&check_win if $$empty{x} == 3 and $$empty{y} == 3;
}
sub check_win{
foreach my $pos (0..$
return unless ( $$board[$pos]->{'x'} == $vic_cond[$pos]->[0] and
$$board[$pos]->{'y'} == $vic_cond[$pos]->[1]);
}
$victorious = 1;
my @text = ('Dis','ci','pu','lus','15th','','','at',
'P','e','r','l','M','o','n','ks*');
foreach my $tile(@$board){
$$tile{btn}->configure( -text=> shift @text,
-command=>sub{return});
$mw->update;
sleep 1;
}
}
sub check_req_pos{
my @wanted = @_;
@wanted = @wanted[0..15];
my @check = (1..16);
unless ( all {$_ == shift @check} sort {$a<=>$b} @wanted ){
die "tiles must be from 1 to 16 (empty tile)\nyou passed [@wanted]\n";
}
return map {$_-1} @wanted;
}
sub extreme_perl {
$verbose = 0;
$mw->optionAdd('*font', 'Courier 20 bold');
my @extreme = (
'if $0',
"\$_=\n()=\n\"foo\"=~/o/g",
"use warnings;\n\$^W?\nint((length\n'Discipulus')/3)\n:'15'",
"length \$1\nif \$^X=~\n\/(?:\\W)(\\w*)\n(?:\\.exe)\$\/",
"use Config;\n\$Config{baserev}",
"(split '',\nvec('JAPH'\n,1,8))[0]",
"scalar map\n{ord(\$_)=~/1/g}\nqw(p e r l)",
"\$_ = () =\n'J A P H'\n=~\/\\b\/g",
"eval join '+',\nsplit '',\n(substr\n'12345',3,2)",
'printf \'%b\',2',
"int(((1+sqrt(5))\n/ 2)** 7 /\nsqrt(5)+0.5)-2",
"split '',\nunpack('V',\n01234567))\n[6,4]",
'J','A','P','H'
);
foreach (0..15){
$$board[$_]{btn}->configure(-text=> $extreme[$_],
-height => 8,
-width => 16, ) if $extreme[$_];
}
@fixed = qw(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15);
$mw->after(5000,\&shuffle_board);
} | 1,18015 puzzle game
| 2perl
| 9cgmn |
GD <- function(vec) {
c(vec[vec!= 0], vec[vec == 0])
}
DG <- function(vec) {
c(vec[vec == 0], vec[vec!= 0])
}
DG_ <- function(vec, v = TRUE) {
if (v)
print(vec)
rev(GD_(rev(vec), v = FALSE))
}
GD_ <- function(vec, v = TRUE) {
if (v) {
print(vec)
}
vec2 <- GD(vec)
pos <- which(vec2 == c(vec2[-1], 9999))
pos[-1][which(abs(pos - c(pos[-1], 999)) == 1)]
av <- which(c(0, c(pos[-1], 9) - pos) == 1)
if (length(av) > 0) {
pos <- pos[-av]
}
vec2[pos] <- vec2[pos] + vec2[pos + 1]
vec2[pos + 1] <- 0
GD(vec2)
}
H_ <- function(base) {
apply(base, MARGIN = 2, FUN = GD_, v = FALSE)
}
B_ <- function(base) {
apply(base, MARGIN = 2, FUN = DG_, v = FALSE)
}
G_ <- function(base) {
t(apply(base, MARGIN = 1, FUN = GD_, v = FALSE))
}
D_ <- function(base) {
t(apply(base, MARGIN = 1, FUN = DG_, v = FALSE))
}
H <- function(base) {
apply(base, MARGIN = 2, FUN = GD, v = FALSE)
}
B <- function(base) {
apply(base, MARGIN = 2, FUN = DG, v = FALSE)
}
G <- function(base) {
t(apply(base, MARGIN = 1, FUN = GD, v = FALSE))
}
D <- function(base) {
t(apply(base, MARGIN = 1, FUN = DG, v = FALSE))
}
add2or4 <- function(base, p = 0.9) {
lw <- which(base == 0)
if (length(lw) > 1) {
tirage <- sample(lw, 1)
} else {
tirage <- lw
}
base[tirage] <- sample(c(2, 4), 1, prob = c(p, 1 - p))
base
}
print.dqh <- function(base) {
cat("\n\n")
for (i in 1:nrow(base)) {
cat(paste(" ", base[i, ], " "))
cat("\n")
}
cat("\n")
}
run_2048 <- function(nrow, ncol, p = 0.9) {
help <- function() {
cat(" *** KEY BINDING *** \n\n")
cat("press ECHAP to quit\n\n")
cat("choose moove E (up); D (down); S (left); F (right) \n")
cat("choose moove 8 (up); 2 (down); 4 (left); 6 (right) \n")
cat("choose moove I (up); K (down); J (left); L (right) \n\n\n")
}
if (missing(nrow) & missing(ncol)) {
nrow <- ncol <- 4
}
if (missing(nrow)) {
nrow <- ncol
}
if (missing(ncol)) {
ncol <- nrow
}
base <- matrix(0, nrow = nrow, ncol = ncol)
while (length(which(base == 2048)) == 0) {
base <- add2or4(base, p = p)
class(base) <- "dqh"
print(base)
flag <- sum((base == rbind(base[-1, ], 0)) + (base == rbind(0,
base[-nrow(base), ])) + (base == cbind(base[, -1], 0)) + (base ==
cbind(0, base[, -nrow(base)])))
if (flag == 0) {
break
}
y <- character(0)
while (length(y) == 0) {
cat("\n", "choose moove E (up); D (down); s (left); f (right) OR H for help",
"\n")
y <- scan(n = 1, what = "character")
}
baseSAVE <- base
base <- switch(EXPR = y, E = H_(base), D = B_(base), S = G_(base),
F = D_(base), e = H_(base), d = B_(base), s = G_(base), f = D_(base),
`8` = H_(base), `2` = B_(base), `4` = G_(base), `6` = D_(base),
H = help(), h = help(), i = H_(base), k = B_(base), j = G_(base),
l = D_(base), I = H_(base), K = B_(base), J = G_(base), L = D_(base))
if (is.null(base)) {
cat(" wrong KEY \n")
base <- baseSAVE
}
}
if (sum(base >= 2048) > 1) {
cat("YOU WIN! \n")
} else {
cat("YOU LOOSE \n")
}
} | 1,1792048
| 13r
| s0zqy |
(defn paragraph [num]
(str num " bottles of beer on the wall\n"
num " bottles of beer\n"
"Take one down, pass it around\n"
(dec num) " bottles of beer on the wall.\n"))
(defn lyrics []
(let [numbers (range 99 0 -1)
paragraphs (map paragraph numbers)]
(clojure.string/join "\n" paragraphs)))
(print (lyrics)) | 1,18199 bottles of beer
| 6clojure
| bpqkz |
<?php
session_start([
=> 0,
=> 0,
=> 1,
]);
class Location
{
protected $column, $row;
function __construct($column, $row){
$this->column = $column;
$this->row = $row;
}
function create_neighbor($direction){
$dx = 0; $dy = 0;
switch ($direction){
case 0: case 'left': $dx = -1; break;
case 1: case 'right': $dx = +1; break;
case 2: case 'up': $dy = -1; break;
case 3: case 'down': $dy = +1; break;
}
return new Location($this->column + $dx, $this->row + $dy);
}
function equals($that){
return $this->column == $that->column && $this->row == $that->row;
}
function is_inside_rectangle($left, $top, $right, $bottom){
return $left <= $this->column && $this->column <= $right
&& $top <= $this->row && $this->row <= $bottom;
}
function is_nearest_neighbor($that){
$s = abs($this->column - $that->column) + abs($this->row - $that->row);
return $s == 1;
}
}
class Tile
{
protected $index;
protected $content;
protected $target_location;
protected $current_location;
function __construct($index, $content, $row, $column){
$this->index = $index;
$this->content = $content;
$this->target_location = new Location($row, $column);
$this->current_location = $this->target_location;
}
function get_content(){
return $this->content;
}
function get_index(){
return $this->index;
}
function get_location(){
return $this->current_location;
}
function is_completed(){
return $this->current_location->equals($this->target_location);
}
function is_empty(){
return $this->content == NULL;
}
function is_nearest_neighbor($that){
$a = $this->current_location;
$b = $that->current_location;
return $a->is_nearest_neighbor($b);
}
function swap_locations($that){
$a = $this->current_location;
$b = $that->current_location;
$this->current_location = $b;
$that->current_location = $a;
}
}
class Model
{
protected $N;
protected $M;
protected $tiles;
function __construct($N, $M){
$this->N = $N;
$this->M = $M;
$this->tiles[0] = new Tile(0, NULL, $N, $M);
for ($k = 1; $k < $N * $M; $k++ ){
$i = 1 + intdiv($k - 1, $M);
$j = 1 + ($k - 1) % $M;
$this->tiles[$k] = new Tile($k, (string)$k, $i, $j);
}
$number_of_shuffles = 1000;
$i = 0;
while ($i < $number_of_shuffles)
if ($this->move_in_direction(random_int(0, 3)))
$i++;
}
function get_N(){
return $this->N;
}
function get_M(){
return $this->M;
}
function get_tile_by_index($index){
return $this->tiles[$index];
}
function get_tile_at_location($location){
foreach($this->tiles as $tile)
if ($location->equals($tile->get_location()))
return $tile;
return NULL;
}
function is_completed(){
foreach($this->tiles as $tile)
if (!$tile->is_completed())
return FALSE;
return TRUE;
}
function move($tile){
if ($tile != NULL)
foreach($this->tiles as $target){
if ($target->is_empty() && $target->is_nearest_neighbor($tile)){
$tile->swap_locations($target);
break;
}
}
}
function move_in_direction($direction){
foreach($this->tiles as $tile)
if ($tile->is_empty())
break;
$location = $tile->get_location()->create_neighbor($direction);
if ($location->is_inside_rectangle(0, 0, $this->M, $this->N)){
$tile = $this->get_tile_at_location($location);
$this->move($tile);
return TRUE;
}
return FALSE;
}
}
class View
{
protected $model;
function __construct($model){
$this->model = $model;
}
function show(){
$N = $this->model->get_N();
$M = $this->model->get_M();
echo ;
for ($i = 1; $i <= $N; $i++){
for ($j = 1; $j <= $M; $j++){
$tile = $this->model->get_tile_at_location(new Location($i, $j));
$content = $tile->get_content();
if ($content != NULL)
echo
.
.
. ;
else
echo ;
}
echo ;
}
echo ;
if ($this->model->is_completed()){
echo ;
echo ;
echo ;
}
}
}
class Controller
{
protected $model;
protected $view;
function __construct($model, $view){
$this->model = $model;
$this->view = $view;
}
function run(){
if (isset($_GET['index'])){
$index = $_GET['index'];
$this->model->move($this->model->get_tile_by_index($index));
}
$this->view->show();
}
}
?>
<!DOCTYPE html>
<html lang=><meta charset=>
<head>
<title>15 puzzle game</title>
<style>
.puzzle{width: 4ch; display: inline-block; margin: 0; padding: 0.25ch;}
span.puzzle{padding: 0.1ch;}
.end-game{font-size: 400%; color: red;}
</style>
</head>
<body>
<p><?php
if (!isset($_SESSION['model'])){
$width = 4; $height = 4;
$model = new Model($width, $height);
}
else
$model = unserialize($_SESSION['model']);
$view = new View($model);
$controller = new Controller($model, $view);
$controller->run();
$_SESSION['model'] = serialize($model);
?></p>
</body>
</html> | 1,18015 puzzle game
| 12php
| wxnep |
use warnings;
use strict;
use feature 'say';
print <<'EOF';
The 24 Game
Given any four digits in the range 1 to 9, which may have repetitions,
Using just the +, -, *, and / operators; and the possible use of
parentheses, (), show how to make an answer of 24.
An answer of "q" or EOF will quit the game.
A blank answer will generate a new set of four digits.
Otherwise you are repeatedly asked for an expression until it evaluates to 24.
Note: you cannot form multiple digit numbers from the supplied digits,
so an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.
EOF
my $try = 1;
while (1) {
my @digits = map { 1+int(rand(9)) } 1..4;
say "\nYour four digits: ", join(" ", @digits);
print "Expression (try ", $try++, "): ";
my $entry = <>;
if (!defined $entry || $entry eq 'q')
{ say "Goodbye. Sorry you couldn't win."; last; }
$entry =~ s/\s+//g;
next if $entry eq '';
my $given_digits = join "", sort @digits;
my $entry_digits = join "", sort grep { /\d/ } split(//, $entry);
if ($given_digits ne $entry_digits ||
$entry =~ /\d\d/ ||
$entry =~ m|[-+*/]{2}| ||
$entry =~ tr|-0-9()+*/||c)
{ say "That's not valid"; next; }
my $n = eval $entry;
if (!defined $n) { say "Invalid expression"; }
elsif ($n == 24) { say "You win!"; last; }
else { say "Sorry, your expression is $n, not 24"; }
} | 1,17524 game
| 2perl
| vua20 |
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 will quit the game.
An answer of will generate a new set of four digits.
Otherwise you are repeatedly asked for an expression until it evaluates to 24
Note: you cannot form multiple digit numbers from the supplied digits,
so an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.
<?php
while (true) {
$numbers = make_numbers();
for ($iteration_num = 1; ; $iteration_num++) {
echo ;
$entry = rtrim(fgets(STDIN));
if ($entry === '!') break;
if ($entry === 'q') exit;
$result = play($numbers, $entry);
if ($result === null) {
echo ;
continue;
}
elseif ($result != 24) {
echo ;
continue;
}
else {
echo ;
exit;
}
}
}
function make_numbers() {
$numbers = array();
echo ;
for ($i = 0; $i < 4; $i++) {
$number = rand(1, 9);
if (!isset($numbers[$number])) {
$numbers[$number] = 0;
}
$numbers[$number]++;
print ;
}
print ;
return $numbers;
}
function play($numbers, $expression) {
$operator = true;
for ($i = 0, $length = strlen($expression); $i < $length; $i++) {
$character = $expression[$i];
if (in_array($character, array('(', ')', ' ', ))) continue;
$operator = !$operator;
if (!$operator) {
if (!empty($numbers[$character])) {
$numbers[$character]--;
continue;
}
return;
}
elseif (!in_array($character, array('+', '-', '*', '/'))) {
return;
}
}
foreach ($numbers as $remaining) {
if ($remaining > 0) {
return;
}
}
return eval();
}
?> | 1,17524 game
| 12php
| 089sp |
prisoners = [*1..100]
N = 10_000
generate_rooms = ->{ [nil]+[*1..100].shuffle }
res = N.times.count do
rooms = generate_rooms[]
prisoners.all? {|pr| rooms[1,100].sample(50).include?(pr)}
end
puts % (res.fdiv(N) * 100)
res = N.times.count do
rooms = generate_rooms[]
prisoners.all? do |pr|
cur_room = pr
50.times.any? do
found = (rooms[cur_room] == pr)
cur_room = rooms[cur_room]
found
end
end
end
puts % (res.fdiv(N) * 100) | 1,176100 prisoners
| 14ruby
| 54euj |
'''
Note that this code is broken, e.g., it won't work when
blocks = [(, ), (,)] and the word is , where the answer
should be True, but the code returns False.
'''
blocks = [(, ),
(, ),
(, ),
(, ),
(, ),
(, ),
(, ),
(, ),
(, ),
(, ),
(, ),
(, ),
(, ),
(, ),
(, ),
(, ),
(, ),
(, ),
(, ),
(, )]
def can_make_word(word, block_collection=blocks):
if not word:
return False
blocks_remaining = block_collection[:]
for char in word.upper():
for block in blocks_remaining:
if char in block:
blocks_remaining.remove(block)
break
else:
return False
return True
if __name__ == :
import doctest
doctest.testmod()
print(.join(% (w, can_make_word(w)) for w in
[, , , , ,
, , ])) | 1,173ABC problem
| 3python
| z37tt |
[dependencies]
rand = '0.7.2' | 1,176100 prisoners
| 15rust
| 4gw5u |
''' Structural Game for 15 - Puzzle with different difficulty levels'''
from random import randint
class Puzzle:
def __init__(self):
self.items = {}
self.position = None
def main_frame(self):
d = self.items
print('+-----+-----+-----+-----+')
print('|%s|%s|%s|%s|'% (d[1], d[2], d[3], d[4]))
print('+-----+-----+-----+-----+')
print('|%s|%s|%s|%s|'% (d[5], d[6], d[7], d[8]))
print('+-----+-----+-----+-----+')
print('|%s|%s|%s|%s|'% (d[9], d[10], d[11], d[12]))
print('+-----+-----+-----+-----+')
print('|%s|%s|%s|%s|'% (d[13], d[14], d[15], d[16]))
print('+-----+-----+-----+-----+')
def format(self, ch):
ch = ch.strip()
if len(ch) == 1:
return ' ' + ch + ' '
elif len(ch) == 2:
return ' ' + ch + ' '
elif len(ch) == 0:
return ' '
def change(self, to):
fro = self.position
for a, b in self.items.items():
if b == self.format(str(to)):
to = a
break
self.items[fro], self.items[to] = self.items[to], self.items[fro]
self.position = to
def build_board(self, difficulty):
for i in range(1, 17):
self.items[i] = self.format(str(i))
tmp = 0
for a, b in self.items.items():
if b == ' 16 ':
self.items[a] = ' '
tmp = a
break
self.position = tmp
if difficulty == 0:
diff = 10
elif difficulty == 1:
diff = 50
else:
diff = 100
for _ in range(diff):
lst = self.valid_moves()
lst1 = []
for j in lst:
lst1.append(int(j.strip()))
self.change(lst1[randint(0, len(lst1)-1)])
def valid_moves(self):
pos = self.position
if pos in [6, 7, 10, 11]:
return self.items[pos - 4], self.items[pos - 1],\
self.items[pos + 1], self.items[pos + 4]
elif pos in [5, 9]:
return self.items[pos - 4], self.items[pos + 4],\
self.items[pos + 1]
elif pos in [8, 12]:
return self.items[pos - 4], self.items[pos + 4],\
self.items[pos - 1]
elif pos in [2, 3]:
return self.items[pos - 1], self.items[pos + 1], self.items[pos + 4]
elif pos in [14, 15]:
return self.items[pos - 1], self.items[pos + 1],\
self.items[pos - 4]
elif pos == 1:
return self.items[pos + 1], self.items[pos + 4]
elif pos == 4:
return self.items[pos - 1], self.items[pos + 4]
elif pos == 13:
return self.items[pos + 1], self.items[pos - 4]
elif pos == 16:
return self.items[pos - 1], self.items[pos - 4]
def game_over(self):
flag = False
for a, b in self.items.items():
if b == ' ':
pass
else:
if a == int(b.strip()):
flag = True
else:
flag = False
return flag
g = Puzzle()
g.build_board(int(input('Enter the difficulty: 0 1 2\n2 '
'=> highest 0=> lowest\n')))
g.main_frame()
print('Enter 0 to exit')
while True:
print('Hello user:\nTo change the position just enter the no. near it')
lst = g.valid_moves()
lst1 = []
for i in lst:
lst1.append(int(i.strip()))
print(i.strip(), '\t', end='')
print()
x = int(input())
if x == 0:
break
elif x not in lst1:
print('Wrong move')
else:
g.change(x)
g.main_frame()
if g.game_over():
print('You WON')
break | 1,18015 puzzle game
| 3python
| clr9q |
require 'io/console'
class Board
def initialize size=4, win_limit=2048, cell_width = 6
@size = size; @cw = cell_width; @win_limit = win_limit
@board = Array.new(size) {Array.new(size, 0)}
@moved = true; @score = 0; @no_more_moves = false
spawn
end
def draw
print if @r_vert
print ' ' if @r_hori
print '' + (['' * @cw] * @size).join('') + ''
@board.each do |row|
print
formated = row.map {|num| num == 0? ' ' * @cw: format(num)}
print ' ' if @r_hori
puts '' + formated.join('') + ''
print ' ' if @r_hori
print '' + ([' ' * @cw] * @size).join('') + ''
end
print
print ' ' if @r_hori
puts '' + (['' * @cw] * @size).join('') + ''
end
def move direction
case direction
when :up
@board = column_map {|c| logic(c)}
@r_vert = false if $rumble
when :down
@board = column_map {|c| logic(c.reverse).reverse}
@r_vert = true if $rumble
when :left
@board = row_map {|r| logic(r)}
@r_hori = false if $rumble
when :right
@board = row_map {|r| logic(r.reverse).reverse}
@r_hori = true if $rumble
end
spawn
@moved = false
end
def print_score
puts
puts if to_enum.any? {|e| e >= @win_limit}
end
def no_more_moves?; @no_more_moves; end
def won?; to_enum.any? {|e| e >= @win_limit}; end
def reset!; initialize @size, @win_limit, @cw; end
private
def set x, y, val
@board[y][x] = val
end
def spawn
free_pos = to_enum.select{|elem,x,y| elem == 0}.map{|_,x,y| [x,y]}
unless free_pos.empty?
set *free_pos.sample, rand > 0.1? 2: 4 if @moved
else
snap = @board
unless @stop
@stop = true
%i{up down left right}.each{|s| move(s)}
@no_more_moves = true if snap.flatten == @board.flatten
@board = snap
@stop = false
end
end
end
def logic list
jump = false
result =
list.reduce([]) do |res, val|
if res.last == val &&!jump
res[-1] += val
@score += val
jump = true
elsif val!= 0
res.push val
jump = false
end
res
end
result += [0] * (@size - result.length)
@moved ||= list!= result
result
end
def column_map
xboard = @board.transpose
xboard.map!{|c| yield c }
xboard.transpose
end
def row_map
@board.map {|r| yield r }
end
def to_enum
@enum ||= Enumerator.new(@size * @size) do |yielder|
(@size*@size).times do |i|
yielder.yield (@board[i / @size][i % @size]), (i % @size), (i / @size )
end
end
@enum.rewind
end
def format(num)
if $color
cstart = + $colors[Math.log(num, 2)] +
cend =
else
cstart = cend =
end
cstart + num.to_s.center(@cw) + cend
end
end
$color = true
$colors = %W{0 1;97 1;93 1;92 1;96 1;91 1;95 1;94 1;30;47 1;43 1;42
1;46 1;41 1;45 1;44 1;33;43 1;33;42 1;33;41 1;33;44}
$rumble = false
$check_score = true
unless ARGV.empty?
puts ; exit if %W[-h --help].include?(ARGV[0])
args = ARGV.map(&:to_i).reject{|n| n == 0}
b = Board.new(*args) unless args.empty?
$rumble = true if ARGV.any?{|a| a =~ /rumble/i }
$color = false if ARGV.any?{|a| a =~ /no.?color/i}
end
b ||= Board.new
puts
b.draw
puts
loop do
input = STDIN.getch
if input ==
2.times {input << STDIN.getch}
end
case input
when , then b.move(:up)
when , then b.move(:down)
when , then b.move(:right)
when , then b.move(:left)
when ,, then b.print_score; exit
when
puts <<-EOM.gsub(/^\s*/, '')
Use the arrow-keys or WASD on your keyboard to push board in the given direction.
Tiles with the same number merge into one.
Get a tile with a value of
In case you cannot move or merge any tiles anymore, you loose.
You can start this game with different settings by providing commandline argument:
For instance:
%>
PRESS q TO QUIT (or Ctrl-C or Ctrl-D)
EOM
input = STDIN.getch
end
puts
b.draw
if b.no_more_moves? or $check_score && b.won?
b.print_score
if b.no_more_moves?
puts
puts
exit if STDIN.gets.chomp.downcase ==
$check_score = true
b.reset!
puts
b.draw
else
puts
exit if STDIN.gets.chomp.downcase ==
$check_score = false
puts
b.draw
end
end
end | 1,1792048
| 14ruby
| dfcns |
use std::io::{self,BufRead};
extern crate rand;
enum Usermove {
Up,
Down,
Left,
Right,
}
fn print_game(field:& [[u32;4];4] ){
println!("{:?}",&field[0] );
println!("{:?}",&field[1] );
println!("{:?}",&field[2] );
println!("{:?}",&field[3] );
}
fn get_usermove()-> Usermove {
let umove: Usermove;
loop{
let mut input = String::new();
io::stdin().read_line(&mut input).unwrap();
match input.chars().nth(0){
Some('a') =>{umove = Usermove::Left;break },
Some('w') =>{umove = Usermove::Up ;break },
Some('s') =>{umove = Usermove::Down;break },
Some('d') =>{umove = Usermove::Right;break },
_ => {println!("input was {}: invalid character should be a,s,w or d ",input.chars().nth(0).unwrap());} ,
}
}
umove
} | 1,1792048
| 15rust
| ftld6 |
import scala.util.Random
import scala.util.control.Breaks._
object Main {
def playOptimal(n: Int): Boolean = {
val secretList = Random.shuffle((0 until n).toBuffer)
for (i <- secretList.indices) {
var prev = i
breakable {
for (_ <- 0 until secretList.size / 2) {
if (secretList(prev) == i) {
break()
}
prev = secretList(prev)
}
return false
}
}
true
}
def playRandom(n: Int): Boolean = {
val secretList = Random.shuffle((0 until n).toBuffer)
for (i <- secretList.indices) {
val trialList = Random.shuffle((0 until n).toBuffer)
breakable {
for (j <- 0 until trialList.size / 2) {
if (trialList(j) == i) {
break()
}
}
return false
}
}
true
}
def exec(n: Int, p: Int, play: Int => Boolean): Double = {
var succ = 0.0
for (_ <- 0 until n) {
if (play(p)) {
succ += 1
}
}
(succ * 100.0) / n
}
def main(args: Array[String]): Unit = {
val n = 100000
val p = 100
printf("# of executions:%,d\n", n)
printf("Optimal play success rate:%f%%\n", exec(n, p, playOptimal))
printf("Random play success rate:%f%%\n", exec(n, p, playRandom))
}
} | 1,176100 prisoners
| 16scala
| 7jsr9 |
import java.awt.event.{KeyAdapter, KeyEvent, MouseAdapter, MouseEvent}
import java.awt.{BorderLayout, Color, Dimension, Font, Graphics2D, Graphics, RenderingHints}
import java.util.Random
import javax.swing.{JFrame, JPanel, SwingUtilities}
object Game2048 {
val target = 2048
var highest = 0
def main(args: Array[String]): Unit = {
SwingUtilities.invokeLater(() => {
val f = new JFrame
f.setDefaultCloseOperation(3)
f.setTitle("2048")
f.add(new Game, BorderLayout.CENTER)
f.pack()
f.setLocationRelativeTo(null)
f.setVisible(true)
})
}
class Game extends JPanel {
private val (rand , side)= (new Random, 4)
private var (tiles, gamestate)= (Array.ofDim[Tile](side, side), Game2048.State.start)
final private val colorTable =
Seq(new Color(0x701710), new Color(0xFFE4C3), new Color(0xfff4d3), new Color(0xffdac3), new Color(0xe7b08e), new Color(0xe7bf8e),
new Color(0xffc4c3), new Color(0xE7948e), new Color(0xbe7e56), new Color(0xbe5e56), new Color(0x9c3931), new Color(0x701710))
setPreferredSize(new Dimension(900, 700))
setBackground(new Color(0xFAF8EF))
setFont(new Font("SansSerif", Font.BOLD, 48))
setFocusable(true)
addMouseListener(new MouseAdapter() {
override def mousePressed(e: MouseEvent): Unit = {
startGame()
repaint()
}
})
addKeyListener(new KeyAdapter() {
override def keyPressed(e: KeyEvent): Unit = {
e.getKeyCode match {
case KeyEvent.VK_UP => moveUp()
case KeyEvent.VK_DOWN => moveDown()
case KeyEvent.VK_LEFT => moveLeft()
case KeyEvent.VK_RIGHT => moveRight()
case _ =>
}
repaint()
}
})
override def paintComponent(gg: Graphics): Unit = {
super.paintComponent(gg)
val g = gg.asInstanceOf[Graphics2D]
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
drawGrid(g)
}
private def drawGrid(g: Graphics2D): Unit = {
val (gridColor, emptyColor, startColor) = (new Color(0xBBADA0), new Color(0xCDC1B4), new Color(0xFFEBCD))
if (gamestate == State.running) {
g.setColor(gridColor)
g.fillRoundRect(200, 100, 499, 499, 15, 15)
for (
r <- 0 until side;
c <- 0 until side
) if (Option(tiles(r)(c)).isEmpty) {
g.setColor(emptyColor)
g.fillRoundRect(215 + c * 121, 115 + r * 121, 106, 106, 7, 7)
}
else drawTile(g, r, c)
} else {
g.setColor(startColor)
g.fillRoundRect(215, 115, 469, 469, 7, 7)
g.setColor(gridColor.darker)
g.setFont(new Font("SansSerif", Font.BOLD, 128))
g.drawString("2048", 310, 270)
g.setFont(new Font("SansSerif", Font.BOLD, 20))
if (gamestate == Game2048.State.won) g.drawString("you made it!", 390, 350)
else if (gamestate == Game2048.State.over) g.drawString("game over", 400, 350)
g.setColor(gridColor)
g.drawString("click to start a new game", 330, 470)
g.drawString("(use arrow keys to move tiles)", 310, 530)
}
}
private def drawTile(g: Graphics2D, r: Int, c: Int): Unit = {
val value = tiles(r)(c).value
g.setColor(colorTable((math.log(value) / math.log(2)).toInt + 1))
g.fillRoundRect(215 + c * 121, 115 + r * 121, 106, 106, 7, 7)
g.setColor(if (value < 128) colorTable.head else colorTable(1))
val (s , fm)= (value.toString, g.getFontMetrics)
val asc = fm.getAscent
val (x, y) = (215 + c * 121 + (106 - fm.stringWidth(s)) / 2,115 + r * 121 + (asc + (106 - (asc + fm.getDescent)) / 2))
g.drawString(s, x, y)
}
private def moveUp(checkingAvailableMoves: Boolean = false) = move(0, -1, 0, checkingAvailableMoves)
private def moveDown(checkingAvailableMoves: Boolean = false) = move(side * side - 1, 1, 0, checkingAvailableMoves)
private def moveLeft(checkingAvailableMoves: Boolean = false) = move(0, 0, -1, checkingAvailableMoves)
private def moveRight(checkingAvailableMoves: Boolean = false) = move(side * side - 1, 0, 1, checkingAvailableMoves)
private def clearMerged(): Unit = for (row <- tiles; tile <- row) if (Option(tile).isDefined) tile.setMerged()
private def movesAvailable() = moveUp(true) || moveDown(true) || moveLeft(true) || moveRight(true)
def move(countDownFrom: Int, yIncr: Int, xIncr: Int, checkingAvailableMoves: Boolean): Boolean = {
var moved = false
for (i <- 0 until side * side) {
val j = math.abs(countDownFrom - i)
var( r,c) = (j / side, j % side)
if (Option(tiles(r)(c)).isDefined) {
var (nextR, nextC, breek) = (r + yIncr, c + xIncr, false)
while ((nextR >= 0 && nextR < side && nextC >= 0 && nextC < side) && !breek) {
val (next, curr) = (tiles(nextR)(nextC),tiles(r)(c))
if (Option(next).isEmpty)
if (checkingAvailableMoves) return true
else {
tiles(nextR)(nextC) = curr
tiles(r)(c) = null
r = nextR
c = nextC
nextR += yIncr
nextC += xIncr
moved = true
}
else if (next.canMergeWith(curr)) {
if (checkingAvailableMoves) return true
Game2048.highest = math.max(next.mergeWith(curr), Game2048.highest)
tiles(r)(c) = null
breek = true
moved = true
} else breek = true
}
}
}
if (moved) if (Game2048.highest < Game2048.target) {
clearMerged()
addRandomTile()
if (!movesAvailable) gamestate = State.over
}
else if (Game2048.highest == Game2048.target) gamestate = State.won
moved
}
private def startGame(): Unit = {
if (gamestate ne Game2048.State.running) {
Game2048.highest = 0
gamestate = Game2048.State.running
tiles = Array.ofDim[Tile](side, side)
addRandomTile()
addRandomTile()
}
}
private def addRandomTile(): Unit = {
var pos = rand.nextInt(side * side)
var (row, col) = (0, 0)
do {
pos = (pos + 1) % (side * side)
row = pos / side
col = pos % side
} while (Option(tiles(row)(col)).isDefined)
tiles(row)(col) = new Tile(if (rand.nextInt(10) == 0) 4 else 2)
}
class Tile(var value: Int) {
private var merged = false
def setMerged(): Unit = merged = false
def mergeWith(other: Tile): Int = if (canMergeWith(other)) {
merged = true
value *= 2
value
} else -1
def canMergeWith(other: Tile): Boolean = !merged && Option(other).isDefined && !other.merged && value == other.value
}
}
object State extends Enumeration {
type State = Value
val start, won, running, over = Value
}
} | 1,1792048
| 16scala
| 36uzy |
blocks <- rbind(c("B","O"),
c("X","K"),
c("D","Q"),
c("C","P"),
c("N","A"),
c("G","T"),
c("R","E"),
c("T","G"),
c("Q","D"),
c("F","S"),
c("J","W"),
c("H","U"),
c("V","I"),
c("A","N"),
c("O","B"),
c("E","R"),
c("F","S"),
c("L","Y"),
c("P","C"),
c("Z","M"))
canMake <- function(x) {
x <- toupper(x)
used <- rep(FALSE, dim(blocks)[1L])
charList <- strsplit(x, character(0))
tryChars <- function(chars, pos, used, inUse=NA) {
if (pos > length(chars)) {
TRUE
} else {
used[inUse] <- TRUE
possible <- which(blocks == chars[pos] &!used, arr.ind=TRUE)[, 1L]
any(vapply(possible, function(possBlock) tryChars(chars, pos + 1, used, possBlock), logical(1)))
}
}
setNames(vapply(charList, tryChars, logical(1), 1L, used), x)
}
canMake(c("A",
"BARK",
"BOOK",
"TREAT",
"COMMON",
"SQUAD",
"CONFUSE")) | 1,173ABC problem
| 13r
| nd5i2 |
import Foundation
struct PrisonersGame {
let strategy: Strategy
let numPrisoners: Int
let drawers: [Int]
init(numPrisoners: Int, strategy: Strategy) {
self.numPrisoners = numPrisoners
self.strategy = strategy
self.drawers = (1...numPrisoners).shuffled()
}
@discardableResult
func play() -> Bool {
for num in 1...numPrisoners {
guard findNumber(num) else {
return false
}
}
return true
}
private func findNumber(_ num: Int) -> Bool {
var tries = 0
var nextDrawer = num - 1
while tries < 50 {
tries += 1
switch strategy {
case .random where drawers.randomElement()! == num:
return true
case .optimum where drawers[nextDrawer] == num:
return true
case .optimum:
nextDrawer = drawers[nextDrawer] - 1
case _:
continue
}
}
return false
}
enum Strategy {
case random, optimum
}
}
let numGames = 100_000
let lock = DispatchSemaphore(value: 1)
var done = 0
print("Running \(numGames) games for each strategy")
DispatchQueue.concurrentPerform(iterations: 2) {i in
let strat = i == 0? PrisonersGame.Strategy.random: .optimum
var numPardoned = 0
for _ in 0..<numGames {
let game = PrisonersGame(numPrisoners: 100, strategy: strat)
if game.play() {
numPardoned += 1
}
}
print("Probability of pardon with \(strat) strategy: \(Double(numPardoned) / Double(numGames))")
lock.wait()
done += 1
lock.signal()
if done == 2 {
exit(0)
}
}
dispatchMain() | 1,176100 prisoners
| 17swift
| u5avg |
puz15<-function(scramble.length=100){
m=matrix(c(1:15,0),byrow=T,ncol=4)
scramble=sample(c("w","a","s","d"),scramble.length,replace=T)
for(i in 1:scramble.length){
m=move(m,scramble[i])
}
win=F
turn=0
while(!win){
print.puz(m)
newmove=getmove()
if(newmove=="w"|newmove=="a"|newmove=="s"|newmove=="d"){
m=move(m,newmove)
turn=turn+1
}
else{
cat("Input not recognized","\n")
}
if(!(F%in% m==matrix(c(1:15,0),byrow=T,ncol=4))){
win=T
}
}
print.puz(m)
cat("\n")
print("You win!")
cat("\n","It took you",turn,"moves.","\n")
}
getmove<-function(){
direction<-readline(prompt="Move:")
return(direction)
}
move<-function(m,direction){
if(direction=="w"){
m=move.u(m)
}
else if(direction=="s"){
m=move.d(m)
}
else if(direction=="a"){
m=move.l(m)
}
else if(direction=="d"){
m=move.r(m)
}
return(m)
}
move.u<-function(m){
if(0%in% m[4,]){}
else{
pos=which(m==0)
m[pos]=m[pos+1]
m[pos+1]=0
}
return(m)
}
move.d<-function(m){
if(0%in% m[1,]){}
else{
pos=which(m==0)
m[pos]=m[pos-1]
m[pos-1]=0
}
return(m)
}
move.l<-function(m){
if(0%in% m[,4]){return(m)}
else{return(t(move.u(t(m))))}
}
move.r<-function(m){
if(0%in% m[,1]){return(m)}
else{return(t(move.d(t(m))))}
}
print.puz<-function(m){
cat("+----+----+----+----+","\n")
for(r in 1:4){
string="|"
for(c in 1:4){
if(m[r,c]==0)
string=paste(string," |",sep="")
else if(m[r,c]<10)
string=paste(string," ",m[r,c]," |",sep="")
else
string=paste(string," ",m[r,c]," |",sep="")
}
cat(string,"\n","+----+----+----+----+","\n",sep="")
}
} | 1,18015 puzzle game
| 13r
| 6yu3e |
package main
import "fmt"
func main() {
var a, b int
fmt.Scan(&a, &b)
fmt.Println(a + b)
} | 1,178A+B
| 0go
| 8oy0g |
main() {
BeerSong beerSong = BeerSong(); | 1,18199 bottles of beer
| 18dart
| 2v7lp |
'''
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 will quit the game.
An answer of will generate a new set of four digits.
Otherwise you are repeatedly asked for an expression until it evaluates to 24
Note: you cannot form multiple digit numbers from the supplied digits,
so an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.
'''
from __future__ import division, print_function
import random, ast, re
import sys
if sys.version_info[0] < 3: input = raw_input
def choose4():
'four random digits >0 as characters'
return [str(random.randint(1,9)) for i in range(4)]
def welcome(digits):
print (__doc__)
print ( + ' '.join(digits))
def check(answer, digits):
allowed = set('() +-*/\t'+''.join(digits))
ok = all(ch in allowed for ch in answer) and \
all(digits.count(dig) == answer.count(dig) for dig in set(digits)) \
and not re.search('\d\d', answer)
if ok:
try:
ast.parse(answer)
except:
ok = False
return ok
def main():
digits = choose4()
welcome(digits)
trial = 0
answer = ''
chk = ans = False
while not (chk and ans == 24):
trial +=1
answer = input(% trial)
chk = check(answer, digits)
if answer.lower() == 'q':
break
if answer == '!':
digits = choose4()
print (, ' '.join(digits))
continue
if not chk:
print (% answer)
else:
ans = eval(answer)
print (, ans)
if ans == 24:
print ()
print ()
if __name__ == '__main__': main() | 1,17524 game
| 3python
| u5evd |
def abAdder = {
def reader = new Scanner(System.in)
def a = reader.nextInt();
def b = reader.nextInt();
assert (-1000..1000).containsAll([a,b]): "both numbers must be between -1000 and 1000 (inclusive)"
a + b
}
abAdder() | 1,178A+B
| 7groovy
| wxfel |
twenty.four <- function(operators=c("+", "-", "*", "/", "("),
selector=function() sample(1:9, 4, replace=TRUE),
arguments=selector(),
goal=24) {
newdigits <- function() {
arguments <<- selector()
cat("New digits:", paste(arguments, collapse=", "), "\n")
}
help <- function() cat("Make", goal,
"out of the numbers",paste(arguments, collapse=", "),
"and the operators",paste(operators, collapse=", "), ".",
"\nEnter 'q' to quit, '!' to select new digits,",
"or '?' to repeat this message.\n")
help()
repeat {
switch(input <- readline(prompt="> "),
q={ cat("Goodbye!\n"); break },
`?`=help(),
`!`=newdigits(),
tryCatch({
expr <- parse(text=input, n=1)[[1]]
check.call(expr, operators, arguments)
result <- eval(expr)
if (isTRUE(all.equal(result, goal))) {
cat("Correct!\n")
newdigits()
} else {
cat("Evaluated to", result, "( goal", goal, ")\n")
}
},error=function(e) cat(e$message, "\n")))
}
}
check.call <- function(expr, operators, arguments) {
unexpr <- function(x) {
if (is.call(x))
unexpr(as.list(x))
else if (is.list(x))
lapply(x,unexpr)
else x
}
leaves <- unlist(unexpr(expr))
if (any(disallowed <-
!leaves%in% c(lapply(operators, as.name),
as.list(arguments)))) {
stop("'", paste(sapply(leaves[disallowed], as.character),
collapse=", "),
"' not allowed. ")
}
numbers.used <- unlist(leaves[sapply(leaves, mode) == 'numeric'])
if (! isTRUE(all.equal(sort(numbers.used), sort(arguments))))
stop("Must use each number once.")
} | 1,17524 game
| 13r
| clb95 |
words = %w(A BaRK BOoK tREaT COmMOn SqUAD CoNfuSE) <<
words.each do |word|
blocks =
res = word.each_char.all?{|c| blocks.sub!(/\w?
puts
end | 1,173ABC problem
| 14ruby
| 6yh3t |
require 'io/console'
class Board
SIZE = 4
RANGE = 0...SIZE
def initialize
width = (SIZE*SIZE-1).to_s.size
@frame = ( + *(width+2)) * SIZE +
@form = * SIZE +
@step = 0
@orign = [*0...SIZE*SIZE].rotate.each_slice(SIZE).to_a.freeze
@board = @orign.map{|row | row.dup}
randomize
draw
message
play
end
private
def randomize
@board[0][0], @board[SIZE-1][SIZE-1] = 0, 1
@board[SIZE-1][0], @board[0][SIZE-1] = @board[0][SIZE-1], @board[SIZE-1][0]
x, y, dx, dy = 0, 0, 1, 0
50.times do
nx,ny = [[x+dx,y+dy], [x+dy,y-dx], [x-dy,y+dx]]
.select{|nx,ny| RANGE.include?(nx) and RANGE.include?(ny)}
.sample
@board[nx][ny], @board[x][y] = 0, @board[nx][ny]
x, y, dx, dy = nx, ny, nx-x, ny-y
end
@x, @y = x, y
end
def draw
puts
@board.each do |row|
puts @frame
puts (@form % row).sub(, )
end
puts @frame
puts
end
DIR = {up: [-1,0], down: [1,0], left: [0,-1], right: [0,1]}
def move(direction)
dx, dy = DIR[direction]
nx, ny = @x + dx, @y + dy
if RANGE.include?(nx) and RANGE.include?(ny)
@board[nx][ny], @board[@x][@y] = 0, @board[nx][ny]
@x, @y = nx, ny
@step += 1
draw
end
end
def play
until @board == @orign
case key_in
when , then move(:up)
when , then move(:down)
when , then move(:right)
when , then move(:left)
when ,, then exit
when then message
end
end
puts
end
def key_in
input = STDIN.getch
if input ==
2.times {input << STDIN.getch}
end
input
end
def message
puts <<~EOM
Use the arrow-keys or WASD on your keyboard to push board in the given direction.
PRESS q TO QUIT (or Ctrl-C or Ctrl-D)
EOM
end
end
Board.new | 1,18015 puzzle game
| 14ruby
| 2vjlw |
main = print . sum . map read . words =<< getLine | 1,178A+B
| 8haskell
| l2hch |
use std::iter::repeat;
fn rec_can_make_word(index: usize, word: &str, blocks: &[&str], used: &mut[bool]) -> bool {
let c = word.chars().nth(index).unwrap().to_uppercase().next().unwrap();
for i in 0..blocks.len() {
if!used[i] && blocks[i].chars().any(|s| s == c) {
used[i] = true;
if index == 0 || rec_can_make_word(index - 1, word, blocks, used) {
return true;
}
used[i] = false;
}
}
false
}
fn can_make_word(word: &str, blocks: &[&str]) -> bool {
return rec_can_make_word(word.chars().count() - 1, word, blocks,
&mut repeat(false).take(blocks.len()).collect::<Vec<_>>());
}
fn main() {
let blocks = [("BO"), ("XK"), ("DQ"), ("CP"), ("NA"), ("GT"), ("RE"), ("TG"), ("QD"), ("FS"),
("JW"), ("HU"), ("VI"), ("AN"), ("OB"), ("ER"), ("FS"), ("LY"), ("PC"), ("ZM")];
let words = ["A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "CONFUSE"];
for word in &words {
println!("{} -> {}", word, can_make_word(word, &blocks))
}
} | 1,173ABC problem
| 15rust
| ymk68 |
extern crate rand;
use std::collections::HashMap;
use std::fmt;
use rand::Rng;
use rand::seq::SliceRandom;
#[derive(Copy, Clone, PartialEq, Debug)]
enum Cell {
Card(usize),
Empty,
}
#[derive(Eq, PartialEq, Hash, Debug)]
enum Direction {
Up,
Down,
Left,
Right,
}
enum Action {
Move(Direction),
Quit,
}
type Board = [Cell; 16];
const EMPTY: Board = [Cell::Empty; 16];
struct P15 {
board: Board,
}
impl P15 {
fn new() -> Self {
let mut board = EMPTY;
for (i, cell) in board.iter_mut().enumerate().skip(1) {
*cell = Cell::Card(i);
}
let mut rng = rand::thread_rng();
board.shuffle(&mut rng);
if!Self::is_valid(board) { | 1,18015 puzzle game
| 15rust
| vuh2t |
object AbcBlocks extends App {
protected class Block(face1: Char, face2: Char) {
def isFacedWith(that: Char) = { that == face1 || that == face2 }
override def toString() = face1.toString + face2
}
protected object Block {
def apply(faces: String) = new Block(faces.head, faces.last)
}
type word = Seq[Block]
private val blocks = List(Block("BO"), Block("XK"), Block("DQ"), Block("CP"), Block("NA"),
Block("GT"), Block("RE"), Block("TG"), Block("QD"), Block("FS"),
Block("JW"), Block("HU"), Block("VI"), Block("AN"), Block("OB"),
Block("ER"), Block("FS"), Block("LY"), Block("PC"), Block("ZM"))
private def isMakeable(word: String, blocks: word) = {
def getTheBlocks(word: String, blocks: word) = {
def inner(word: String, toCompare: word, rest: word, accu: word): word = {
if (word.isEmpty || rest.isEmpty || toCompare.isEmpty) accu
else if (toCompare.head.isFacedWith(word.head)) {
val restant = rest diff List(toCompare.head)
inner(word.tail, restant, restant, accu :+ toCompare.head)
} else inner(word, toCompare.tail, rest, accu)
}
inner(word, blocks, blocks, Nil)
}
word.lengthCompare(getTheBlocks(word, blocks).size) == 0
}
val words = List("A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "CONFUSED", "ANBOCPDQERSFTGUVWXLZ") | 1,173ABC problem
| 16scala
| cl193 |
import java.util.Random
import jline.console._
import scala.annotation.tailrec
import scala.collection.immutable
import scala.collection.parallel.immutable.ParVector
object FifteenPuzzle {
def main(args: Array[String]): Unit = play()
@tailrec def play(len: Int = 1000): Unit = if(gameLoop(Board.randState(len))) play(len)
def gameLoop(board: Board): Boolean = {
val read = new ConsoleReader()
val km = KeyMap.keyMaps().get("vi-insert")
val opMap = immutable.HashMap[Operation, Char](
Operation.PREVIOUS_HISTORY -> 'u',
Operation.BACKWARD_CHAR -> 'l',
Operation.NEXT_HISTORY -> 'd',
Operation.FORWARD_CHAR -> 'r')
@tailrec
def gloop(b: Board): Boolean = {
println(s"\u001B[2J\u001B[2;0H$b\nq")
if(b.isSolved) println("Solved!\nPlay again? (y/n)")
read.readBinding(km) match{
case Operation.SELF_INSERT => read.getLastBinding match{
case "q" => false
case "y" if b.isSolved => true
case "n" if b.isSolved => false
case _ => gloop(b)
}
case op: Operation if opMap.isDefinedAt(op) => gloop(b.move(opMap(op)))
case _ => gloop(b)
}
}
gloop(board)
}
case class Board(mat: immutable.HashMap[(Int, Int), Int], x: Int, y: Int) {
def move(mvs: Seq[Char]): Board = mvs.foldLeft(this){case (b, m) => b.move(m)}
def move(mov: Char): Board = mov match {
case 'r' if x < 3 => Board(mat ++ Seq(((x, y), mat((x + 1, y))), ((x + 1, y), 0)), x + 1, y)
case 'l' if x > 0 => Board(mat ++ Seq(((x, y), mat((x - 1, y))), ((x - 1, y), 0)), x - 1, y)
case 'd' if y < 3 => Board(mat ++ Seq(((x, y), mat((x, y + 1))), ((x, y + 1), 0)), x, y + 1)
case 'u' if y > 0 => Board(mat ++ Seq(((x, y), mat((x, y - 1))), ((x, y - 1), 0)), x, y - 1)
case _ => this
}
def isSolved: Boolean = sumDist == 0
def sumDist: Int = mat.to(LazyList).map{ case ((a, b), n) => if(n == 0) 6 - a - b else (a + b - ((n - 1) % 4) - ((n - 1) / 4)).abs }.sum
override def toString: String = {
val lst = mat.toVector.map { case ((a, b), n) => (4 * b + a, n) }.sortWith(_._1 < _._1).map(_._2)
lst.map { n => if (n == 0) " " else f"$n%2d" }.grouped(4).map(_.mkString(" ")).mkString("\n")
}
}
object Board {
val moves: Vector[Char] = Vector('r', 'l', 'd', 'u')
def apply(config: Vector[Int]): Board = {
val ind = config.indexOf(0)
val formed = config.zipWithIndex.map { case (n, i) => ((i % 4, i / 4), n) }
val builder = immutable.HashMap.newBuilder[(Int, Int), Int]
builder ++= formed
Board(builder.result, ind % 4, ind / 4)
}
def solveState: Board = apply((1 to 15).toVector :+ 0)
def randState(len: Int, rand: Random = new Random()): Board = Iterator
.fill(len)(moves(rand.nextInt(4)))
.foldLeft(Board.solveState) { case (state, mv) => state.move(mv) }
}
} | 1,18015 puzzle game
| 16scala
| 4gp50 |
class Guess < String
def self.play
nums = Array.new(4){rand(1..9)}
loop do
result = get(nums).evaluate!
break if result == 24.0
puts
end
puts
end
def self.get(nums)
loop do
print
input = gets.chomp
return new(input) if validate(input, nums)
end
end
def self.validate(guess, nums)
name, error =
{
invalid_character: ->(str){!str.scan(%r{[^\d\s()+*/-]}).empty? },
wrong_number: ->(str){ str.scan(/\d/).map(&:to_i).sort!= nums.sort },
multi_digit_number: ->(str){ str.match(/\d\d/) }
}
.find {|name, validator| validator[guess] }
error? puts(): true
end
def evaluate!
as_rat = gsub(/(\d)/, '\1r')
eval
rescue SyntaxError
end
end
Guess.play | 1,17524 game
| 14ruby
| 4gx5p |
use std::io::{self,BufRead};
extern crate rand;
use rand::Rng;
fn op_type(x: char) -> i32{
match x {
'-' | '+' => return 1,
'/' | '*' => return 2,
'(' | ')' => return -1,
_ => return 0,
}
}
fn to_rpn(input: &mut String){
let mut rpn_string: String = String::new();
let mut rpn_stack: String = String::new();
let mut last_token = '#';
for token in input.chars(){
if token.is_digit(10) {
rpn_string.push(token);
}
else if op_type(token) == 0 {
continue;
}
else if op_type(token) > op_type(last_token) || token == '(' {
rpn_stack.push(token);
last_token=token;
}
else {
while let Some(top) = rpn_stack.pop() {
if top=='(' {
break;
}
rpn_string.push(top);
}
if token!= ')'{
rpn_stack.push(token);
}
}
}
while let Some(top) = rpn_stack.pop() {
rpn_string.push(top);
}
println!("you formula results in {}", rpn_string);
*input=rpn_string;
}
fn calculate(input: &String, list: &mut [u32;4]) -> f32{
let mut stack: Vec<f32> = Vec::new();
let mut accumulator: f32 = 0.0;
for token in input.chars(){
if token.is_digit(10) {
let test = token.to_digit(10).unwrap() as u32;
match list.iter().position(|&x| x == test){
Some(idx) => list[idx]=10 ,
_ => println!(" invalid digit: {} ",test),
}
stack.push(accumulator);
accumulator = test as f32;
}else{
let a = stack.pop().unwrap();
accumulator = match token {
'-' => a-accumulator,
'+' => a+accumulator,
'/' => a/accumulator,
'*' => a*accumulator,
_ => {accumulator}, | 1,17524 game
| 15rust
| grq4o |
C:\Workset>scala TwentyFourGame
The 24 Game
Given any four digits in the range 1 to 9, which may have repetitions,
Using just the +, -, *, and / operators; and the possible use of
brackets, (), show how to make an answer of 24.
An answer of "q" will quit the game.
An answer of "!" will generate a new set of four digits.
Otherwise you are repeatedly asked for an expression until it evaluates to 24
Note: you cannot form multiple digit numbers from the supplied digits,
so an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.
Your four digits: 2, 7, 7, 2.
Expression 1: 2*7+2+7
Sorry, that's 23.0.
Expression 2: 7*7/2-2
Sorry, that's 22.5.
Expression 3: 2*7+(7-2)
Sorry, that's 19.0.
Expression 4: 2*(7+7-2)
That's right!
Thank you and goodbye! | 1,17524 game
| 16scala
| jh87i |
import Darwin
import Foundation
println("24 Game")
println("Generating 4 digits...")
func randomDigits() -> Int[] {
var result = Int[]();
for var i = 0; i < 4; i++ {
result.append(Int(arc4random_uniform(9)+1))
}
return result;
} | 1,17524 game
| 17swift
| 54wu8 |
import java.util.Scanner;
public class Sum2 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in); | 1,178A+B
| 9java
| 365zg |
<html>
<body>
<div id='input'></div>
<div id='output'></div>
<script type='text/javascript'>
var a = window.prompt('enter A number', '');
var b = window.prompt('enter B number', '');
document.getElementById('input').innerHTML = a + ' ' + b;
var sum = Number(a) + Number(b);
document.getElementById('output').innerHTML = sum;
</script>
</body>
</html> | 1,178A+B
| 10javascript
| clj9j |
import Foundation
func Blockable(str: String) -> Bool {
var blocks = [
"BO", "XK", "DQ", "CP", "NA", "GT", "RE", "TG", "QD", "FS",
"JW", "HU", "VI", "AN", "OB", "ER", "FS", "LY", "PC", "ZM" ]
var strUp = str.uppercaseString
var final = ""
for char: Character in strUp {
var CharString: String = ""; CharString.append(char)
for j in 0..<blocks.count {
if blocks[j].hasPrefix(CharString) ||
blocks[j].hasSuffix(CharString) {
final.append(char)
blocks[j] = ""
break
}
}
}
return final == strUp
}
func CanOrNot(can: Bool) -> String {
return can? "can": "cannot"
}
for str in [ "A", "BARK", "BooK", "TrEaT", "comMON", "sQuAd", "Confuse" ] {
println("'\(str)' \(CanOrNot(Blockable(str))) be spelled with blocks.")
} | 1,173ABC problem
| 17swift
| 36jz2 |
null | 1,178A+B
| 11kotlin
| ndcij |
a,b = io.read("*number", "*number")
print(a+b) | 1,178A+B
| 1lua
| dflnq |
package main
import "fmt"
func main() {
bottles := func(i int) string {
switch i {
case 0:
return "No more bottles"
case 1:
return "1 bottle"
default:
return fmt.Sprintf("%d bottles", i)
}
}
for i := 99; i > 0; i-- {
fmt.Printf("%s of beer on the wall\n", bottles(i))
fmt.Printf("%s of beer\n", bottles(i))
fmt.Printf("Take one down, pass it around\n")
fmt.Printf("%s of beer on the wall\n", bottles(i-1))
}
} | 1,18199 bottles of beer
| 0go
| ndyi1 |
def bottles = { "${it==0? 'No more': it} bottle${it==1? '': 's' }" }
99.downto(1) { i ->
print """
${bottles(i)} of beer on the wall
${bottles(i)} of beer
Take one down, pass it around
${bottles(i-1)} of beer on the wall
"""
} | 1,18199 bottles of beer
| 7groovy
| s0fq1 |
main = mapM_ (putStrLn . beer) [99, 98 .. 0]
beer 1 = "1 bottle of beer on the wall\n1 bottle of beer\nTake one down, pass it around"
beer 0 = "better go to the store and buy some more."
beer v = show v ++ " bottles of beer on the wall\n"
++ show v
++" bottles of beer\nTake one down, pass it around\n"
++ head (lines $ beer $ v-1) ++ "\n" | 1,18199 bottles of beer
| 8haskell
| u5hv2 |
import java.text.MessageFormat;
public class Beer {
static String bottles(int n) {
return MessageFormat.format("{0,choice,0#No more bottles|1#One bottle|2#{0} bottles} of beer", n);
}
public static void main(String[] args) {
String bottles = bottles(99);
for (int n = 99; n > 0; ) {
System.out.println(bottles + " on the wall");
System.out.println(bottles);
System.out.println("Take one down, pass it around");
bottles = bottles(--n);
System.out.println(bottles + " on the wall");
System.out.println();
}
}
} | 1,18199 bottles of beer
| 9java
| m95ym |
var beer = 99;
while (beer > 0) {
var verse = [
beer + " bottles of beer on the wall,",
beer + " bottles of beer!",
"Take one down, pass it around",
(beer - 1) + " bottles of beer on the wall!"
].join("\n");
console.log(verse);
beer--;
} | 1,18199 bottles of beer
| 10javascript
| vuj25 |
fun main(args: Array<String>) {
for (i in 99.downTo(1)) {
println("$i bottles of beer on the wall")
println("$i bottles of beer")
println("Take one down, pass it around")
}
println("No more bottles of beer on the wall!")
} | 1,18199 bottles of beer
| 11kotlin
| tzcf0 |
my ($a,$b) = split(' ', scalar(<STDIN>));
print "$a $b " . ($a + $b) . "\n"; | 1,178A+B
| 2perl
| 7jxrh |
fscanf(STDIN, , $a, $b);
echo ($a + $b) . ; | 1,178A+B
| 12php
| ft2dh |
local bottles = 99
local function plural (bottles) if bottles == 1 then return '' end return 's' end
while bottles > 0 do
print (bottles..' bottle'..plural(bottles)..' of beer on the wall')
print (bottles..' bottle'..plural(bottles)..' of beer')
print ('Take one down, pass it around')
bottles = bottles - 1
print (bottles..' bottle'..plural(bottles)..' of beer on the wall')
print ()
end | 1,18199 bottles of beer
| 1lua
| z3lty |
try: raw_input
except: raw_input = input
print(sum(map(int, raw_input().split()))) | 1,178A+B
| 3python
| jhq7p |
sum(scan("", numeric(0), 2)) | 1,178A+B
| 13r
| 4ga5y |
puts gets.split.sum(&:to_i) | 1,178A+B
| 14ruby
| kb0hg |
use std::io;
fn main() {
let mut line = String::new();
io::stdin().read_line(&mut line).expect("reading stdin");
let mut i: i64 = 0;
for word in line.split_whitespace() {
i += word.parse::<i64>().expect("trying to interpret your input as numbers");
}
println!("{}", i);
} | 1,178A+B
| 15rust
| bp8kx |
println(readLine().split(" ").map(_.toInt).sum) | 1,178A+B
| 16scala
| aen1n |
SELECT A+B | 1,178A+B
| 19sql
| xqtwq |
import Foundation
let input = NSFileHandle.fileHandleWithStandardInput()
let data = input.availableData
let str = NSString(data: data, encoding: NSUTF8StringEncoding)!
let nums = str.componentsSeparatedByString(" ")
let a = (nums[0] as String).toInt()!
let b = (nums[1] as String).toInt()!
print(" \(a + b)") | 1,178A+B
| 17swift
| hksj0 |
function add(a: number, b: number) {
return a+b;
} | 1,178A+B
| 20typescript
| in9o6 |