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(...
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 ch...
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 ...
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...
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,...
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.gr...
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...
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 i...
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 fou...
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; ...
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....
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 @d...
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...
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 ma...
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 ...
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->...
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->finishS...
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(); m...
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 (str...
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):...
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 ...
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 acti...
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, 'n...
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) ...
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" par...
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,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...
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...
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 ...
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 = [(, ), (, ), (, ), (, ), (, ), (, ), (, ), (, ), (, ), (...
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...
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 ' ' ...
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 um...
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(...
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: Arra...
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) { ...
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() -> B...
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"|new...
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 repea...
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, collap...
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 dr...
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; ...
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(Direct...
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 ...
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))) ...
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...
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(); le...
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 digi...
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 =...
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 Ch...
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\...
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, p...
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; ) {...
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,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