abstract class X {
type A
var B: A
val C: A
def D(a: A): A
}
trait Y {
val x: X
}
1,166Abstract type
16scala
p1cbj
def ack(m, n)
if m == 0
n + 1
elsif n == 0
ack(m-1, 1)
else
ack(m-1, ack(m, n-1))
end
end
1,162Ackermann function
14ruby
m9oyj
shopt -s expand_aliases
alias bind_variables='
{
local -ri goal_count=21
local -ri player_human=0
local -ri player_computer=1
local -i turn=1
local -i total_count=0
local -i input_number=0
local -i choose_turn=0
}
'
whose_turn() {
case $(( ( turn + choose_turn ) % 2 )) in
${player_human}) echo "player";;
${player_computer}) echo "computer";;
esac
}
next_turn() {
let turn++
}
validate_number() {
! test ${input_number} -ge 1 -a ${input_number} -le $( max_guess )
}
prompt_number() {
local prompt_str
test $( max_guess ) -eq 1 && {
prompt_str="enter the number 1 to win"
true
} || {
prompt_str="enter a number between 1 and $( max_guess )"
}
while [ ! ]
do
read -p "${prompt_str} (or quit): "
input_number=${REPLY}
case ${REPLY} in
"quit") {
false
return
} ;;
esac
validate_number || break
echo "try again"
done
}
update_count() {
let total_count+=input_number
}
remaining_count() {
echo $(( goal_count - total_count ))
}
max_guess() {
local -i remaining_count
remaining_count=$( remaining_count )
case $( remaining_count ) in
1|2|3) echo ${remaining_count} ;;
*) echo 3 ;;
esac
}
iter() {
update_count
next_turn
}
on_game_over() {
test ! ${input_number} -eq $( remaining_count ) || {
test ! "$( whose_turn )" = "player" && {
echo -ne "\nYou won!\n\n"
true
} || {
echo -ne "\nThe computer won!\nGAME OVER\n\n"
}
false
}
}
on_game_start() {
echo 21 Game
read -p "Press enter key to start"
}
choose_turn() {
let choose_turn=${RANDOM}%2
}
choose_number() {
local -i remaining_count
remaining_count=$( remaining_count )
case ${remaining_count} in
1|2|3) {
input_number=${remaining_count}
} ;;
5|6|7) {
let input_number=remaining_count-4
} ;;
*) {
let input_number=${RANDOM}%$(( $( max_guess ) - 1 ))+1
}
esac
}
game_play() {
choose_turn
while [ ! ]
do
echo "Total now ${total_count} (remaining: $( remaining_count ))"
echo -ne "Turn: ${turn} ("
test ! "$( whose_turn )" = "player" && {
echo -n "Your"
true
} || {
echo -n "Computer"
}
echo " turn)"
test ! "$( whose_turn )" = "player" && {
prompt_number || break
true
} || {
choose_number
sleep 2
echo "Computer chose ${input_number}"
}
on_game_over || break
sleep 1
iter
done
}
21_Game() {
bind_variables
on_game_start
game_play
}
if [ ${
then
true
else
exit 1
fi
21_Game
1,17221 game
4bash
p1zbb
import java.math.BigInteger;
import java.util.*;
import static java.util.Arrays.asList;
import static java.util.stream.Collectors.toList;
import static java.util.stream.IntStream.range;
import static java.lang.Math.min;
public class Test {
static List<BigInteger> cumu(int n) {
List<List<BigInteger>> cache = new ArrayList<>();
cache.add(asList(BigInteger.ONE));
for (int L = cache.size(); L < n + 1; L++) {
List<BigInteger> r = new ArrayList<>();
r.add(BigInteger.ZERO);
for (int x = 1; x < L + 1; x++)
r.add(r.get(r.size() - 1).add(cache.get(L - x).get(min(x, L - x))));
cache.add(r);
}
return cache.get(n);
}
static List<BigInteger> row(int n) {
List<BigInteger> r = cumu(n);
return range(0, n).mapToObj(i -> r.get(i + 1).subtract(r.get(i)))
.collect(toList());
}
public static void main(String[] args) {
System.out.println("Rows:");
for (int x = 1; x < 11; x++)
System.out.printf("%2d:%s%n", x, row(x));
System.out.println("\nSums:");
for (int x : new int[]{23, 123, 1234}) {
List<BigInteger> c = cumu(x);
System.out.printf("%s%s%n", x, c.get(c.size() - 1));
}
}
}
1,1709 billion names of God the integer
9java
aem1y
null
1,169Abundant odd numbers
1lua
oig8h
static char DESCRIPTION[] =
;
static int total;
void update(char* player, int move)
{
printf(, player, total + move, total, move);
total += move;
if (total == GOAL)
printf(_(), player);
}
int ai()
{
static const int precomputed[] = { 1, 1, 3, 2, 1, 1, 3, 2, 1, 1, 3, 2, 1, 1,
3, 2, 1, 1, 3, 2, 1, 1, 3, 2, 1, 1, 3, 2, 1, 1, 3 };
update(_(), precomputed[total]);
static const int precomputed[] = { 1, 1, 3, 2};
update(_(), precomputed[total % (MAX_MOVE + 1)]);
int i;
int move = 1;
for (i = MIN_MOVE; i <= MAX_MOVE; i++)
if ((total + i - 1) % (MAX_MOVE + 1) == 0)
move = i;
for (i = MIN_MOVE; i <= MAX_MOVE; i++)
if (total + i == GOAL)
move = i;
update(_(), move);
}
void human(void)
{
char buffer[BUFFER_SIZE];
int move;
while ( printf(_()),
fgets(buffer, BUFFER_SIZE, stdin),
sscanf(buffer, , &move) != 1 ||
(move && (move < MIN_MOVE || move > MAX_MOVE || total+move > GOAL)))
puts(_());
putchar('\n');
if (!move) exit(EXIT_SUCCESS);
update(_(), move);
}
int main(int argc, char* argv[])
{
srand(time(NULL));
puts(_(DESCRIPTION));
while (true)
{
puts(_());
puts(_());
total = 0;
if (rand() % NUMBER_OF_PLAYERS)
{
puts(_());
ai();
}
else
puts(_());
while (total < GOAL)
{
human();
ai();
}
}
}
1,17221 game
5c
ae611
(function () {
var cache = [
[1]
];
1,1709 billion names of God the integer
10javascript
s0vqz
fn ack(m: isize, n: isize) -> isize {
if m == 0 {
n + 1
} else if n == 0 {
ack(m - 1, 1)
} else {
ack(m - 1, ack(m, n - 1))
}
}
fn main() {
let a = ack(3, 4);
println!("{}", a);
1,162Ackermann function
15rust
9cimm
require
File.read().each_line do |line|
next if line.strip.empty?
abbr = line.split.abbrev.invert
puts , abbr.inspect,
end
1,168Abbreviations, automatic
14ruby
p1mbh
use std::fs::File;
use std::io;
use std::io::{BufRead, BufReader};
fn main() {
let table = read_days("weekdays.txt").expect("Error in Function read_days:");
for line in table {
if line.len() == 0 {
continue;
};
let mut max_same = 0;
for i in 0..(line.len() - 1) {
for j in i + 1..line.len() {
max_same = max_same.max(begins_with_num_same_chars(&line[i], &line[j]));
}
}
println!("{}\t{:?}", max_same + 1, line);
}
}
fn read_days(filename: &str) -> io::Result<Vec<Vec<String>>> {
let f = File::open(filename)?;
let reader = BufReader::new(f);
let mut table: Vec<Vec<String>> = Vec::new();
for line in reader.lines() {
let mut days: Vec<String> = Vec::with_capacity(7);
for day in line?.split_whitespace() {
days.push(day.to_string());
}
table.push(days);
}
Ok(table)
}
fn begins_with_num_same_chars(str_a: &str, str_b: &str) -> u32 {
let mut num = 0;
for (pos, char_a) in str_a.chars().enumerate() {
match str_b.chars().nth(pos) {
Some(char_b) => {
if char_a == char_b {
num = num + 1;
} else {
return num;
}
}
None => return num,
}
}
num
}
1,168Abbreviations, automatic
15rust
1a9pu
import java.lang.Math.min
import java.math.BigInteger
import java.util.ArrayList
import java.util.Arrays.asList
fun namesOfGod(n: Int): List<BigInteger> {
val cache = ArrayList<List<BigInteger>>()
cache.add(asList(BigInteger.ONE))
(cache.size..n).forEach { l ->
val r = ArrayList<BigInteger>()
r.add(BigInteger.ZERO)
(1..l).forEach { x ->
r.add(r[r.size - 1] + cache[l - x][min(x, l - x)])
}
cache.add(r)
}
return cache[n]
}
fun row(n: Int) = namesOfGod(n).let { r -> (0 until n).map { r[it + 1] - r[it] } }
fun main(args: Array<String>) {
println("Rows:")
(1..25).forEach {
System.out.printf("%2d:%s%n", it, row(it))
}
println("\nSums:")
intArrayOf(23, 123, 1234, 1234).forEach {
val c = namesOfGod(it)
System.out.printf("%s%s%n", it, c[c.size - 1])
}
}
1,1709 billion names of God the integer
11kotlin
hktj3
name := "Abbreviations-automatic"
scalaVersion := "2.13.0"
version := "0.1"
homepage := Some(url("http:
1,168Abbreviations, automatic
16scala
wx2es
int can_make_words(char **b, char *word)
{
int i, ret = 0, c = toupper(*word);
if (!c) return 1;
if (!b[0]) return 0;
for (i = 0; b[i] && !ret; i++) {
if (b[i][0] != c && b[i][1] != c) continue;
SWAP(b[i], b[0]);
ret = can_make_words(b + 1, word + 1);
SWAP(b[i], b[0]);
}
return ret;
}
int main(void)
{
char* blocks[] = {
, , , , ,
, , , , ,
, , , , ,
, , , , ,
0 };
char *words[] = {
, , , , , , , , 0
};
char **w;
for (w = words; *w; w++)
printf(, *w, can_make_words(blocks, *w));
return 0;
}
1,173ABC problem
5c
inuo2
function nog(n)
local tri = {{1}}
for r = 2, n do
tri[r] = {}
for c = 1, r do
tri[r][c] = (tri[r-1][c-1] or 0) + (tri[r-c] and tri[r-c][c] or 0)
end
end
return tri
end
function G(n)
local tri, sum = nog(n), 0
for _, v in ipairs(tri[n]) do sum = sum + v end
return sum
end
tri = nog(25)
for i, row in ipairs(tri) do
print(i .. ": " .. table.concat(row, " "))
end
print("G(23) = " .. G(23))
print("G(123) = " .. G(123))
(def blocks
(-> "BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM" (.split " ") vec))
(defn omit
"return bs with (one instance of) b omitted"
[bs b]
(let [[before after] (split-with #(not= b %) bs)]
(concat before (rest after))))
(defn abc
"return lazy sequence of solutions (i.e. block lists)"
[blocks [c & cs]]
(if (some? c)
(for [b blocks:when (some #(= c %) b)
bs (abc (omit blocks b) cs)]
(cons b bs))
[[]]))
(doseq [word ["A" "BARK" "Book" "treat" "COMMON" "SQUAD" "CONFUSE"]]
(->> word .toUpperCase (abc blocks) first (printf "%s:%b\n" word)))
1,173ABC problem
6clojure
z37tj
package main
import "fmt"
func main(){
n, c := getCombs(1,7,true)
fmt.Printf("%d unique solutions in 1 to 7\n",n)
fmt.Println(c)
n, c = getCombs(3,9,true)
fmt.Printf("%d unique solutions in 3 to 9\n",n)
fmt.Println(c)
n, _ = getCombs(0,9,false)
fmt.Printf("%d non-unique solutions in 0 to 9\n",n)
}
func getCombs(low,high int,unique bool) (num int,validCombs [][]int){
for a := low; a <= high; a++ {
for b := low; b <= high; b++ {
for c := low; c <= high; c++ {
for d := low; d <= high; d++ {
for e := low; e <= high; e++ {
for f := low; f <= high; f++ {
for g := low; g <= high; g++ {
if validComb(a,b,c,d,e,f,g) {
if !unique || isUnique(a,b,c,d,e,f,g) {
num++
validCombs = append(validCombs,[]int{a,b,c,d,e,f,g})
}
}
}
}
}
}
}
}
}
return
}
func isUnique(a,b,c,d,e,f,g int) (res bool) {
data := make(map[int]int)
data[a]++
data[b]++
data[c]++
data[d]++
data[e]++
data[f]++
data[g]++
return len(data) == 7
}
func validComb(a,b,c,d,e,f,g int) bool{
square1 := a + b
square2 := b + c + d
square3 := d + e + f
square4 := f + g
return square1 == square2 && square2 == square3 && square3 == square4
}
1,1714-rings or 4-squares puzzle
0go
ft7d0
class FourRings {
static void main(String[] args) {
fourSquare(1, 7, true, true)
fourSquare(3, 9, true, true)
fourSquare(0, 9, false, false)
}
private static void fourSquare(int low, int high, boolean unique, boolean print) {
int count = 0
if (print) {
println("a b c d e f g")
}
for (int a = low; a <= high; ++a) {
for (int b = low; b <= high; ++b) {
if (notValid(unique, a, b)) continue
int fp = a + b
for (int c = low; c <= high; ++c) {
if (notValid(unique, c, a, b)) continue
for (int d = low; d <= high; ++d) {
if (notValid(unique, d, a, b, c)) continue
if (fp != b + c + d) continue
for (int e = low; e <= high; ++e) {
if (notValid(unique, e, a, b, c, d)) continue
for (int f = low; f <= high; ++f) {
if (notValid(unique, f, a, b, c, d, e)) continue
if (fp != d + e + f) continue
for (int g = low; g <= high; ++g) {
if (notValid(unique, g, a, b, c, d, e, f)) continue
if (fp != f + g) continue
++count
if (print) {
printf("%d%d%d%d%d%d%d%n", a, b, c, d, e, f, g)
}
}
}
}
}
}
}
}
if (unique) {
printf("There are%d unique solutions in [%d,%d]%n", count, low, high)
} else {
printf("There are%d non-unique solutions in [%d,%d]%n", count, low, high)
}
}
private static boolean notValid(boolean unique, int needle, int ... haystack) {
return unique && Arrays.stream(haystack).anyMatch({ p -> p == needle })
}
}
1,1714-rings or 4-squares puzzle
7groovy
8ou0b
use strict;
use warnings;
use feature 'say';
use ntheory qw/divisor_sum divisors/;
sub odd_abundants {
my($start,$count) = @_;
my $n = int(( $start + 2 ) / 3);
$n += 1 if 0 == $n % 2;
$n *= 3;
my @out;
while (@out < $count) {
$n += 6;
next unless (my $ds = divisor_sum($n)) > 2*$n;
my @d = divisors($n);
push @out, sprintf "%6d: divisor sum:%s =%d", $n, join(' + ', @d[0..@d-2]), $ds-$n;
}
@out;
}
say 'First 25 abundant odd numbers:';
say for odd_abundants(1, 25);
say "\nOne thousandth abundant odd number:\n", (odd_abundants(1, 1000))[999];
say "\nFirst abundant odd number above one billion:\n", odd_abundants(999_999_999, 1);
1,169Abundant odd numbers
2perl
4gi5d
import Data.List
import Control.Monad
perms :: (Eq a) => [a] -> [[a]]
perms [] = [[]]
perms xs = [ x:xr | x <- xs, xr <- perms (xs\\[x]) ]
combs :: (Eq a) => Int -> [a] -> [[a]]
combs 0 _ = [[]]
combs n xs = [ x:xr | x <- xs, xr <- combs (n-1) xs ]
ringCheck :: [Int] -> Bool
ringCheck [x0, x1, x2, x3, x4, x5, x6] =
v == x1+x2+x3
&& v == x3+x4+x5
&& v == x5+x6
where v = x0 + x1
fourRings :: Int -> Int -> Bool -> Bool -> IO ()
fourRings low high allowRepeats verbose = do
let candidates = if allowRepeats
then combs 7 [low..high]
else perms [low..high]
solutions = filter ringCheck candidates
when verbose $ mapM_ print solutions
putStrLn $ show (length solutions)
++ (if allowRepeats then " non" else "")
++ " unique solutions for "
++ show low
++ " to "
++ show high
putStrLn ""
main = do
fourRings 1 7 False True
fourRings 3 9 False True
fourRings 0 9 True False
1,1714-rings or 4-squares puzzle
8haskell
4g85s
use ntheory qw/:all/;
sub triangle_row {
my($n,@row) = (shift);
forpart { $row[ $_[0] - 1 ]++ } $n;
@row;
}
printf "%2d:%s\n", $_, join(" ",triangle_row($_)) for 1..25;
print "\n";
say "P($_) = ", partitions($_) for (23, 123, 1234, 12345);
1,1709 billion names of God the integer
2perl
z3ktb
typedef struct {int val, op, left, right;} Node;
Node nodes[10000];
int iNodes;
int b;
float eval(Node x){
if (x.op != -1){
float l = eval(nodes[x.left]), r = eval(nodes[x.right]);
switch(x.op){
case 0: return l+r;
case 1: return l-r;
case 2: return r-l;
case 3: return l*r;
case 4: return r?l/r:(b=1,0);
case 5: return l?r/l:(b=1,0);
}
}
else return x.val*1.;
}
void show(Node x){
if (x.op != -1){
printf();
switch(x.op){
case 0: show(nodes[x.left]); printf(); show(nodes[x.right]); break;
case 1: show(nodes[x.left]); printf(); show(nodes[x.right]); break;
case 2: show(nodes[x.right]); printf(); show(nodes[x.left]); break;
case 3: show(nodes[x.left]); printf(); show(nodes[x.right]); break;
case 4: show(nodes[x.left]); printf(); show(nodes[x.right]); break;
case 5: show(nodes[x.right]); printf(); show(nodes[x.left]); break;
}
printf();
}
else printf(, x.val);
}
int float_fix(float x){ return x < 0.00001 && x > -0.00001; }
void solutions(int a[], int n, float t, int s){
if (s == n){
b = 0;
float e = eval(nodes[0]);
if (!b && float_fix(e-t)){
show(nodes[0]);
printf();
}
}
else{
nodes[iNodes++] = (typeof(Node)){a[s],-1,-1,-1};
for (int op = 0; op < 6; op++){
int k = iNodes-1;
for (int i = 0; i < k; i++){
nodes[iNodes++] = nodes[i];
nodes[i] = (typeof(Node)){-1,op,iNodes-1,iNodes-2};
solutions(a, n, t, s+1);
nodes[i] = nodes[--iNodes];
}
}
iNodes--;
}
};
int main(){
int a[4] = {8, 3, 8, 3};
float t = 24;
nodes[0] = (typeof(Node)){a[0],-1,-1,-1};
iNodes = 1;
solutions(a, sizeof(a)/sizeof(int), t, 1);
return 0;
}
1,17424 game/Solve
5c
vue2o
import java.util.Arrays;
public class FourSquares {
public static void main(String[] args) {
fourSquare(1, 7, true, true);
fourSquare(3, 9, true, true);
fourSquare(0, 9, false, false);
}
private static void fourSquare(int low, int high, boolean unique, boolean print) {
int count = 0;
if (print) {
System.out.println("a b c d e f g");
}
for (int a = low; a <= high; ++a) {
for (int b = low; b <= high; ++b) {
if (notValid(unique, a, b)) continue;
int fp = a + b;
for (int c = low; c <= high; ++c) {
if (notValid(unique, c, a, b)) continue;
for (int d = low; d <= high; ++d) {
if (notValid(unique, d, a, b, c)) continue;
if (fp != b + c + d) continue;
for (int e = low; e <= high; ++e) {
if (notValid(unique, e, a, b, c, d)) continue;
for (int f = low; f <= high; ++f) {
if (notValid(unique, f, a, b, c, d, e)) continue;
if (fp != d + e + f) continue;
for (int g = low; g <= high; ++g) {
if (notValid(unique, g, a, b, c, d, e, f)) continue;
if (fp != f + g) continue;
++count;
if (print) {
System.out.printf("%d%d%d%d%d%d%d%n", a, b, c, d, e, f, g);
}
}
}
}
}
}
}
}
if (unique) {
System.out.printf("There are%d unique solutions in [%d,%d]%n", count, low, high);
} else {
System.out.printf("There are%d non-unique solutions in [%d,%d]%n", count, low, high);
}
}
private static boolean notValid(boolean unique, int needle, int... haystack) {
return unique && Arrays.stream(haystack).anyMatch(p -> p == needle);
}
}
1,1714-rings or 4-squares puzzle
9java
cle9h
package main
import (
"bufio"
"fmt"
"log"
"math/rand"
"os"
"strconv"
"time"
)
var scanner = bufio.NewScanner(os.Stdin)
var (
total = 0
quit = false
)
func itob(i int) bool {
if i == 0 {
return false
}
return true
}
func getChoice() {
for {
fmt.Print("Your choice 1 to 3: ")
scanner.Scan()
if scerr := scanner.Err(); scerr != nil {
log.Fatalln(scerr, "when choosing number")
}
text := scanner.Text()
if text == "q" || text == "Q" {
quit = true
return
}
input, err := strconv.Atoi(text)
if err != nil {
fmt.Println("Invalid number, try again")
continue
}
newTotal := total + input
switch {
case input < 1 || input > 3:
fmt.Println("Out of range, try again")
case newTotal > 21:
fmt.Println("Too big, try again")
default:
total = newTotal
fmt.Println("Running total is now", total)
return
}
}
}
func main() {
rand.Seed(time.Now().UnixNano())
computer := itob(rand.Intn(2))
fmt.Println("Enter q to quit at any time\n")
if computer {
fmt.Println("The computer will choose first")
} else {
fmt.Println("You will choose first")
}
fmt.Println("\nRunning total is now 0\n")
var choice int
for round := 1; ; round++ {
fmt.Printf("ROUND%d:\n\n", round)
for i := 0; i < 2; i++ {
if computer {
if total < 18 {
choice = 1 + rand.Intn(3)
} else {
choice = 21 - total
}
total += choice
fmt.Println("The computer chooses", choice)
fmt.Println("Running total is now", total)
if total == 21 {
fmt.Println("\nSo, commiserations, the computer has won!")
return
}
} else {
getChoice()
if quit {
fmt.Println("OK, quitting the game")
return
}
if total == 21 {
fmt.Println("\nSo, congratulations, you've won!")
return
}
}
fmt.Println()
computer = !computer
}
}
}
1,17221 game
0go
m9pyi
(() => {
1,1714-rings or 4-squares puzzle
10javascript
540ur
import System.Random
import System.IO
import System.Exit
import Control.Monad
import Text.Read
import Data.Maybe
promptAgain :: IO Int
promptAgain = do
putStrLn "Invalid input - must be a number among 1,2 or 3. Try again."
playerMove
playerMove :: IO Int
playerMove = do
putStr "Your choice(1 to 3):"
number <- getLine
when (number == "q") $ do
exitWith ExitSuccess
let n = readMaybe number :: Maybe Int
x <- if isNothing n
then promptAgain
else let val = read number
in if (val > 3 || val < 1)
then promptAgain
else return val
return x
computerMove :: IO Int
computerMove = do
x <- randomRIO (1, 3)
putStrLn $ "Computer move:" ++ (show x)
return x
gameLoop :: (IO Int, IO Int) -> IO Int
gameLoop moveorder = loop moveorder 0
where loop moveorder total = do
number <- fst moveorder
let total1 = number + total
putStrLn $ "Running total:" ++ (show total1)
if total1 >= 21
then return 0
else do
number <- snd moveorder
let total2 = number + total1
putStrLn $ "Running total:" ++ (show total2)
if total2 >= 21
then return 1
else loop moveorder total2
main :: IO ()
main = do
hSetBuffering stdout $ BlockBuffering $ Just 1
putStrLn "Enter q to quit at any time"
x <- randomRIO (0, 1) :: IO Int
let (moveorder, names) = if x == 0
then ((playerMove, computerMove), ("Player", "Computer"))
else ((computerMove, playerMove), ("Computer", "Player"))
when (x == 1) $ do
putStrLn "Computer will start the game"
y <- gameLoop moveorder
when (y == 0) $ do
putStrLn $ (fst names) ++ " has won the game"
when (y == 1) $ do
putStrLn $ (snd names) ++ " has won the game"
1,17221 game
8haskell
kbfh0
oddNumber = 1
aCount = 0
dSum = 0
from math import sqrt
def divisorSum(n):
sum = 1
i = int(sqrt(n)+1)
for d in range (2, i):
if n% d == 0:
sum += d
otherD = n
if otherD != d:
sum += otherD
return sum
print ()
while aCount < 25:
dSum = divisorSum(oddNumber )
if dSum > oddNumber:
aCount += 1
print(. format(oddNumber ,dSum ))
oddNumber += 2
while aCount < 1000:
dSum = divisorSum(oddNumber )
if dSum > oddNumber:
aCount += 1
oddNumber += 2
print ()
print (,(oddNumber - 2),,dSum)
oddNumber = 1000000001
found = False
while not found:
dSum = divisorSum(oddNumber )
if dSum > oddNumber:
found = True
print ()
print (,oddNumber,,dSum)
oddNumber += 2
1,169Abundant odd numbers
3python
grn4h
cache = [[1]]
def cumu(n):
for l in range(len(cache), n+1):
r = [0]
for x in range(1, l+1):
r.append(r[-1] + cache[l-x][min(x, l-x)])
cache.append(r)
return cache[n]
def row(n):
r = cumu(n)
return [r[i+1] - r[i] for i in range(n)]
print
for x in range(1, 11): print %x, row(x)
print
for x in [23, 123, 1234, 12345]: print x, cumu(x)[-1]
1,1709 billion names of God the integer
3python
36bzc
import java.util.Random;
import java.util.Scanner;
public class TwentyOneGame {
public static void main(String[] args) {
new TwentyOneGame().run(true, 21, new int[] {1, 2, 3});
}
public void run(boolean computerPlay, int max, int[] valid) {
String comma = "";
for ( int i = 0 ; i < valid.length ; i++ ) {
comma += valid[i];
if ( i < valid.length - 2 && valid.length >= 3 ) {
comma += ", ";
}
if ( i == valid.length - 2 ) {
comma += " or ";
}
}
System.out.printf("The%d game.%nEach player chooses to add%s to a running total.%n" +
"The player whose turn it is when the total reaches%d will win the game.%n" +
"Winner of the game starts the next game. Enter q to quit.%n%n", max, comma, max);
int cGames = 0;
int hGames = 0;
boolean anotherGame = true;
try (Scanner scanner = new Scanner(System.in);) {
while ( anotherGame ) {
Random r = new Random();
int round = 0;
int total = 0;
System.out.printf("Start game%d%n", hGames + cGames + 1);
DONE:
while ( true ) {
round++;
System.out.printf("ROUND%d:%n%n", round);
for ( int play = 0 ; play < 2 ; play++ ) {
if ( computerPlay ) {
int guess = 0;
<!DOCTYPE html><html lang="en">
<head>
<meta charset="UTF-8">
<meta name="keywords" content="Game 21">
<meta name="description" content="
21 is a two player game, the game is played by choosing a number
(1, 2, or 3) to be added to the running total. The game is won by
the player whose chosen number causes the running total to reach
exactly 21. The running total starts at zero.
">
<!--DCMI metadata (Dublin Core Metadata Initiative)-->
<meta name="dc.publisher" content="Rosseta Code">
<meta name="dc.date" content="2020-07-23">
<meta name="dc.created" content="2020-07-23">
<meta name="dc.modified" content="2020-07-30">
<title>
21 Game
</title>
<!-- Remove the line below in the final/production version. -->
<meta http-equiv="cache-control" content="no-cache">
<style>
.ui div { width: 50%; display: inline-flex; justify-content: flex-end; }
div.total { margin-bottom: 1ch; }
label { padding-right: 1ch; }
button + button { margin-left: 1em; }
</style>
</head>
<body>
<h1>
21 Game in ECMA Script (Java Script)
</h1>
<p>
21 is a two player game, the game is played by choosing a number
(1, 2, or 3) to be added to the running total. The game is won by
the player whose chosen number causes the running total to reach
exactly 21. The running total starts at zero.
</p>
<p><span id="first"></span> Use buttons to play.</p>
<div class="ui">
<div class="total">
<label for="human">human last choice:</label>
<input type="text" id="human" readonly>
</div>
<div class="total">
<label for="AI">AI last choice:</label>
<input type="text" id="AI" readonly>
</div>
<div class="total">
<label for="runningTotalText">running total:</label>
<input type="text" id="runningTotalText" readonly>
</div>
<div class="buttons">
<button onclick="choice(1);" id="choice1"> one </button>
<button onclick="choice(2);" id="choice2"> two </button>
<button onclick="choice(3);" id="choice3"> three </button>
<button onclick="restart();"> restart </button>
</div>
</div>
<p id="message"></p>
<noscript>
No script, no fun. Turn on Javascript on.
</noscript>
<script>
1,17221 game
10javascript
hkdjh
function valid(unique,needle,haystack)
if unique then
for _,value in pairs(haystack) do
if needle == value then
return false
end
end
end
return true
end
function fourSquare(low,high,unique,prnt)
count = 0
if prnt then
print("a", "b", "c", "d", "e", "f", "g")
end
for a=low,high do
for b=low,high do
if valid(unique, a, {b}) then
fp = a + b
for c=low,high do
if valid(unique, c, {a, b}) then
for d=low,high do
if valid(unique, d, {a, b, c}) and fp == b + c + d then
for e=low,high do
if valid(unique, e, {a, b, c, d}) then
for f=low,high do
if valid(unique, f, {a, b, c, d, e}) and fp == d + e + f then
for g=low,high do
if valid(unique, g, {a, b, c, d, e, f}) and fp == f + g then
count = count + 1
if prnt then
print(a, b, c, d, e, f, g)
end
end
end
end
end
end
end
end
end
end
end
end
end
end
if unique then
print(string.format("There are%d unique solutions in [%d,%d]", count, low, high))
else
print(string.format("There are%d non-unique solutions in [%d,%d]", count, low, high))
end
end
fourSquare(1,7,true,true)
fourSquare(3,9,true,true)
fourSquare(0,9,false,false)
1,1714-rings or 4-squares puzzle
1lua
6yb39
jmp_buf ctx;
const char *msg;
enum { OP_NONE = 0, OP_NUM, OP_ADD, OP_SUB, OP_MUL, OP_DIV };
typedef struct expr_t *expr, expr_t;
struct expr_t {
int op, val, used;
expr left, right;
};
expr_t digits[N_DIGITS];
void gen_digits()
{
int i;
for (i = 0; i < N_DIGITS; i++)
digits[i].val = 1 + rand() % 9;
}
char str[MAX_INPUT];
int pos;
expr_t pool[POOL_SIZE];
int pool_ptr;
void reset()
{
int i;
msg = 0;
pool_ptr = pos = 0;
for (i = 0; i < POOL_SIZE; i++) {
pool[i].op = OP_NONE;
pool[i].left = pool[i].right = 0;
}
for (i = 0; i < N_DIGITS; i++)
digits[i].used = 0;
}
void bail(const char *s)
{
msg = s;
longjmp(ctx, 1);
}
expr new_expr()
{
if (pool_ptr < POOL_SIZE)
return pool + pool_ptr++;
return 0;
}
int next_tok()
{
while (isspace(str[pos])) pos++;
return str[pos];
}
int take()
{
if (str[pos] != '\0') return ++pos;
return 0;
}
expr get_fact();
expr get_term();
expr get_expr();
expr get_expr()
{
int c;
expr l, r, ret;
if (!(ret = get_term())) bail();
while ((c = next_tok()) == '+' || c == '-') {
if (!take()) bail();
if (!(r = get_term())) bail();
l = ret;
ret = new_expr();
ret->op = (c == '+') ? OP_ADD : OP_SUB;
ret->left = l;
ret->right = r;
}
return ret;
}
expr get_term()
{
int c;
expr l, r, ret;
ret = get_fact();
while((c = next_tok()) == '*' || c == '/') {
if (!take()) bail();
r = get_fact();
l = ret;
ret = new_expr();
ret->op = (c == '*') ? OP_MUL : OP_DIV;
ret->left = l;
ret->right = r;
}
return ret;
}
expr get_digit()
{
int i, c = next_tok();
expr ret;
if (c >= '0' && c <= '9') {
take();
ret = new_expr();
ret->op = OP_NUM;
ret->val = c - '0';
for (i = 0; i < N_DIGITS; i++)
if (digits[i].val == ret->val && !digits[i].used) {
digits[i].used = 1;
return ret;
}
bail();
}
return 0;
}
expr get_fact()
{
int c;
expr l = get_digit();
if (l) return l;
if ((c = next_tok()) == '(') {
take();
l = get_expr();
if (next_tok() != ')') bail();
take();
return l;
}
return 0;
}
expr parse()
{
int i;
expr ret = get_expr();
if (next_tok() != '\0')
bail();
for (i = 0; i < N_DIGITS; i++)
if (!digits[i].used)
bail();
return ret;
}
typedef struct frac_t frac_t, *frac;
struct frac_t { int denom, num; };
int gcd(int m, int n)
{
int t;
while (m) {
t = m; m = n % m; n = t;
}
return n;
}
void eval_tree(expr e, frac res)
{
frac_t l, r;
int t;
if (e->op == OP_NUM) {
res->num = e->val;
res->denom = 1;
return;
}
eval_tree(e->left, &l);
eval_tree(e->right, &r);
switch(e->op) {
case OP_ADD:
res->num = l.num * r.denom + l.denom * r.num;
res->denom = l.denom * r.denom;
break;
case OP_SUB:
res->num = l.num * r.denom - l.denom * r.num;
res->denom = l.denom * r.denom;
break;
case OP_MUL:
res->num = l.num * r.num;
res->denom = l.denom * r.denom;
break;
case OP_DIV:
res->num = l.num * r.denom;
res->denom = l.denom * r.num;
break;
}
if ((t = gcd(res->denom, res->num))) {
res->denom /= t;
res->num /= t;
}
}
void get_input()
{
int i;
reinput:
reset();
printf();
for (i = 0; i < N_DIGITS; i++)
printf(, digits[i].val);
printf(
);
while (1) {
for (i = 0; i < MAX_INPUT; i++) str[i] = '\n';
fgets(str, MAX_INPUT, stdin);
if (*str == '\0') goto reinput;
if (str[MAX_INPUT - 1] != '\n')
bail();
for (i = 0; i < MAX_INPUT; i++)
if (str[i] == '\n') str[i] = '\0';
if (str[0] == 'q') {
printf();
exit(0);
}
if (str[0] == 'n') {
gen_digits();
goto reinput;
}
return;
}
}
int main()
{
frac_t f;
srand(time(0));
gen_digits();
while(1) {
get_input();
setjmp(ctx);
if (msg) {
printf(, msg, pos, str);
continue;
}
eval_tree(parse(), &f);
if (f.denom == 0) bail();
if (f.denom == 1 && f.num == 24)
printf();
else {
if (f.denom == 1)
printf(, f.num);
else
printf(, f.num, f.denom);
printf();
}
}
return 0;
}
1,17524 game
5c
9ckm1
find_div_sum <- function(x){
if (x < 16) return(0)
root <- sqrt(x)
vec <- as.vector(1)
for (i in seq.int(3, root - 1, by = 2)){
if(x%% i == 0){
vec <- c(vec, i, x/i)
}
}
if (root == trunc(root)) vec = c(vec, root)
return(sum(vec))
}
get_n_abun <- function(index = 1, total = 25, print_all = TRUE){
n <- 1
while(n <= total){
my_sum <- find_div_sum(index)
if (my_sum > index){
if(print_all) cat(index, "..... sigma is", my_sum, "\n")
n <- n + 1
}
index <- index + 2
}
if(!print_all) cat(index - 2, "..... sigma is", my_sum, "\n")
}
cat("The first 25 abundants are")
get_n_abun()
cat("The 1000th odd abundant is")
get_n_abun(total = 1000, print_all = F)
cat("First odd abundant after 1e9 is")
get_n_abun(index = 1e9 + 1, total = 1, print_all = F)
1,169Abundant odd numbers
13r
vu027
gamewon = false
running_total = 0
player = 1
opponent = 2
while not gamewon do
num = 0
if player == 1 then
opponent = 2
repeat
print("Enter a number between 1 and 3 (0 to quit):")
num = io.read("*n")
if num == 0 then
os.exit()
end
until (num > 0) and (num <=3)
end
if player == 2 and not (gamewon) then
opponent = 1
if (21 - running_total <= 3) then
num = 21 - running_total
else
num = math.random(1,3)
end
print("Player 2 picks number "..num)
end
running_total = running_total + num
print("Total: "..running_total)
if running_total == 21 then
print("Player "..player.." wins!")
gamewon = true
end
if running_total > 21 then
print("Player "..player.." lost...")
print("Player "..opponent.." wins!")
gamewon = true
end
if player == 1 then
player = 2
else player = 1
end
end
1,17221 game
1lua
2vwl3
def g(n,g)
return 1 unless 1 < g and g < n-1
(2..g).inject(1){|res,q| res + (q > n-g? 0: g(n-g,q))}
end
(1..25).each {|n|
puts (1..n).map {|g| % g(n,g)}.join
}
extern crate num;
use std::cmp;
use num::bigint::BigUint;
fn cumu(n: usize, cache: &mut Vec<Vec<BigUint>>) {
for l in cache.len()..n+1 {
let mut r = vec![BigUint::from(0u32)];
for x in 1..l+1 {
let prev = r[r.len() - 1].clone();
r.push(prev + cache[l-x][cmp::min(x, l-x)].clone());
}
cache.push(r);
}
}
fn row(n: usize, cache: &mut Vec<Vec<BigUint>>) -> Vec<BigUint> {
cumu(n, cache);
let r = &cache[n];
let mut v: Vec<BigUint> = Vec::new();
for i in 0..n {
v.push(&r[i+1] - &r[i]);
}
v
}
fn main() {
let mut cache = vec![vec![BigUint::from(1u32)]];
println!("rows:");
for x in 1..26 {
let v: Vec<String> = row(x, &mut cache).iter().map(|e| e.to_string()).collect();
let s: String = v.join(" ");
println!("{}: {}", x, s);
}
println!("sums:");
for x in vec![23, 123, 1234, 12345] {
cumu(x, &mut cache);
let v = &cache[x];
let s = v[v.len() - 1].to_string();
println!("{}: {}", x, s);
}
}
1,1709 billion names of God the integer
15rust
m9aya
object Main {
1,1709 billion names of God the integer
16scala
l2xcq
(ns rosettacode.24game)
(def ^:dynamic *luser*
"You guessed wrong, or your input was not in prefix notation.")
(def ^:private start #(println
"Your numbers are: " %1 ". Your goal is " %2 ".\n"
"Use the ops [+ - * /] in prefix notation to reach" %2 ".\n"
"q[enter] to quit."))
(defn play
([] (play 24))
([goal] (play goal (repeatedly 4 #(inc (rand-int 9)))))
([goal gns]
(start gns goal)
(let [input (read-string (read-line))
flat (flatten input)]
(println
(if (and (re-find #"^\([\d\s+*/-]+\d?\)$" (pr-str flat))
(= (set gns) (set (filter integer? flat)))
(= goal (eval input)))
"You won the game!"
*luser*))
(when (not= input 'q) (recur goal gns)))))
1,17524 game
6clojure
u5evi
func ackerman(m:Int, n:Int) -> Int {
if m == 0 {
return n+1
} else if n == 0 {
return ackerman(m-1, 1)
} else {
return ackerman(m-1, ackerman(m, n-1))
}
}
1,162Ackermann function
17swift
ym86e
use ntheory qw/forperm/;
use Set::CrossProduct;
sub four_sq_permute {
my($list) = @_;
my @solutions;
forperm {
@c = @$list[@_];
push @solutions, [@c] if check(@c);
} @$list;
print +@solutions . " unique solutions found using: " . join(', ', @$list) . "\n";
return @solutions;
}
sub four_sq_cartesian {
my(@list) = @_;
my @solutions;
my $iterator = Set::CrossProduct->new( [(@list) x 7] );
while( my $c = $iterator->get ) {
push @solutions, [@$c] if check(@$c);
}
print +@solutions . " non-unique solutions found using: " . join(', ', @{@list[0]}) . "\n";
return @solutions;
}
sub check {
my(@c) = @_;
$a = $c[0] + $c[1];
$b = $c[1] + $c[2] + $c[3];
$c = $c[3] + $c[4] + $c[5];
$d = $c[5] + $c[6];
$a == $b and $a == $c and $a == $d;
}
sub display {
my(@solutions) = @_;
my $fmt = "%2s " x 7 . "\n";
printf $fmt, ('a'..'g');
printf $fmt, @$_ for @solutions;
print "\n";
}
display four_sq_permute( [1..7] );
display four_sq_permute( [3..9] );
display four_sq_permute( [8, 9, 11, 12, 17, 18, 20, 21] );
four_sq_cartesian( [0..9] );
1,1714-rings or 4-squares puzzle
2perl
p13b0
(ns clojure-sandbox.prisoners)
(defn random-drawers []
"Returns a list of shuffled numbers"
(-> 100
range
shuffle))
(defn search-50-random-drawers [prisoner-number drawers]
"Select 50 random drawers and return true if the prisoner's number was found"
(->> drawers
shuffle
(take 50)
(filter (fn [x] (= x prisoner-number)))
count
(= 1)))
(defn search-50-optimal-drawers [prisoner-number drawers]
"Open 50 drawers according to the agreed strategy, returning true if prisoner's number was found"
(loop [next-drawer prisoner-number
drawers-opened 0]
(if (= drawers-opened 50)
false
(let [result (nth drawers next-drawer)]
(if (= result prisoner-number)
true
(recur result (inc drawers-opened)))))))
(defn try-luck [drawers drawer-searching-function]
"Returns 1 if all prisoners find their number otherwise 0"
(loop [prisoners (range 100)]
(if (empty? prisoners)
1
(let [res (-> prisoners
first
(drawer-searching-function drawers))]
(if (false? res)
0
(recur (rest prisoners)))))))
(defn simulate-100-prisoners []
"Simulates all prisoners searching the same drawers by both strategies, returns map showing whether each was successful"
(let [drawers (random-drawers)]
{:random (try-luck drawers search-50-random-drawers)
:optimal (try-luck drawers search-50-optimal-drawers)}))
(defn simulate-n-runs [n]
"Simulate n runs of the 100 prisoner problem and returns a success count for each search method"
(loop [random-successes 0
optimal-successes 0
run-count 0]
(if (= n run-count)
{:random-successes random-successes
:optimal-successes optimal-successes
:run-count run-count}
(let [next-result (simulate-100-prisoners)]
(recur (+ random-successes (:random next-result))
(+ optimal-successes (:optimal next-result))
(inc run-count))))))
(defn -main [& args]
"For 5000 runs, print out the success frequency for both search methods"
(let [{:keys [random-successes optimal-successes run-count]} (simulate-n-runs 5000)]
(println (str "Probability of survival with random search: " (float (/ random-successes run-count))))
(println (str "Probability of survival with ordered search: " (float (/ optimal-successes run-count))))))
1,176100 prisoners
6clojure
vu12f
require
class Integer
def proper_divisors
return [] if self == 1
primes = prime_division.flat_map{|prime, freq| [prime] * freq}
(1...primes.size).each_with_object([1]) do |n, res|
primes.combination(n).map{|combi| res << combi.inject(:*)}
end.flatten.uniq
end
end
def generator_odd_abundants(from=1)
from += 1 if from.even?
Enumerator.new do |y|
from.step(nil, 2) do |n|
sum = n.proper_divisors.sum
y << [n, sum] if sum > n
end
end
end
generator_odd_abundants.take(25).each{|n, sum| puts }
puts % generator_odd_abundants.take(1000).last
puts % generator_odd_abundants(1_000_000_000).next
1,169Abundant odd numbers
14ruby
7jfri
fn divisors(n: u64) -> Vec<u64> {
let mut divs = vec![1];
let mut divs2 = Vec::new();
for i in (2..).take_while(|x| x * x <= n).filter(|x| n% x == 0) {
divs.push(i);
let j = n / i;
if i!= j {
divs2.push(j);
}
}
divs.extend(divs2.iter().rev());
divs
}
fn sum_string(v: Vec<u64>) -> String {
v[1..]
.iter()
.fold(format!("{}", v[0]), |s, i| format!("{} + {}", s, i))
}
fn abundant_odd(search_from: u64, count_from: u64, count_to: u64, print_one: bool) -> u64 {
let mut count = count_from;
for n in (search_from..).step_by(2) {
let divs = divisors(n);
let total: u64 = divs.iter().sum();
if total > n {
count += 1;
let s = sum_string(divs);
if!print_one {
println!("{}. {} < {} = {}", count, n, s, total);
} else if count == count_to {
println!("{} < {} = {}", n, s, total);
}
}
if count == count_to {
break;
}
}
count_to
}
fn main() {
let max = 25;
println!("The first {} abundant odd numbers are:", max);
let n = abundant_odd(1, 0, max, false);
println!("The one thousandth abundant odd number is:");
abundant_odd(n, 25, 1000, true);
println!("The first abundant odd number above one billion is:");
abundant_odd(1e9 as u64 + 1, 0, 1, true);
}
1,169Abundant odd numbers
15rust
jht72
import scala.collection.mutable.ListBuffer
object Abundant {
def divisors(n: Int): ListBuffer[Int] = {
val divs = new ListBuffer[Int]
divs.append(1)
val divs2 = new ListBuffer[Int]
var i = 2
while (i * i <= n) {
if (n % i == 0) {
val j = n / i
divs.append(i)
if (i != j) {
divs2.append(j)
}
}
i += 1
}
divs.appendAll(divs2.reverse)
divs
}
def abundantOdd(searchFrom: Int, countFrom: Int, countTo: Int, printOne: Boolean): Int = {
var count = countFrom
var n = searchFrom
while (count < countTo) {
val divs = divisors(n)
val tot = divs.sum
if (tot > n) {
count += 1
if (!printOne || !(count < countTo)) {
val s = divs.map(a => a.toString).mkString(" + ")
if (printOne) {
printf("%d <%s =%d\n", n, s, tot)
} else {
printf("%2d.%5d <%s =%d\n", count, n, s, tot)
}
}
}
n += 2
}
n
}
def main(args: Array[String]): Unit = {
val max = 25
printf("The first%d abundant odd numbers are:\n", max)
val n = abundantOdd(1, 0, max, printOne = false)
printf("\nThe one thousandth abundant odd number is:\n")
abundantOdd(n, 25, 1000, printOne = true)
printf("\nThe first abundant odd number above one billion is:\n")
abundantOdd((1e9 + 1).intValue(), 0, 1, printOne = true)
}
}
1,169Abundant odd numbers
16scala
bp6k6
print <<'HERE';
The 21 game. Each player chooses to add 1, 2, or 3 to a running total.
The player whose turn it is when the total reaches 21 wins. Enter q to quit.
HERE
my $total = 0;
while () {
print "Running total is: $total\n";
my ($me,$comp);
while () {
print 'What number do you play> ';
$me = <>; chomp $me;
last if $me =~ /^[123]$/;
insult($me);
}
$total += $me;
win('Human') if $total >= 21;
print "Computer plays: " . ($comp = 1+int(rand(3))) . "\n";
$total += $comp;
win('Computer') if $total >= 21;
}
sub win {
my($player) = @_;
print "$player wins.\n";
exit;
}
sub insult {
my($g) = @_;
exit if $g =~ /q/i;
my @insults = ('Yo mama', 'Jeez', 'Ummmm', 'Grow up');
my $i = $insults[1+int rand($
print "$i, $g is not an integer between 1 and 3...\n"
}
var cache = [[1]]
func namesOfGod(n:Int) -> [Int] {
for l in cache.count...n {
var r = [0]
for x in 1...l {
r.append(r[r.count - 1] + cache[l - x][min(x, l-x)])
}
cache.append(r)
}
return cache[n]
}
func row(n:Int) -> [Int] {
let r = namesOfGod(n)
var returnArray = [Int]()
for i in 0...n - 1 {
returnArray.append(r[i + 1] - r[i])
}
return returnArray
}
println("rows:")
for x in 1...25 {
println("\(x): \(row(x))")
}
println("\nsums: ")
for x in [23, 123, 1234, 12345] {
cache = [[1]]
var array = namesOfGod(x)
var numInt = array[array.count - 1]
println("\(x): \(numInt)")
}
1,1709 billion names of God the integer
17swift
6yp3j
int main()
{
int a, b;
scanf(, &a, &b);
printf(, a + b);
return 0;
}
1,178A+B
5c
541uk
<!DOCTYPE html>
<html lang=>
<head>
<meta charset=>
<meta name= content=>
<meta name= content=>
<!--DCMI metadata (Dublin Core Metadata Initiative)-->
<meta name= content=>
<meta name= content=>
<meta name= content=>
<meta name= content=>
<title>
21 Game
</title>
<!-- Remove the line below in the final/production version. -->
<meta http-equiv= content=>
<style>
.ui div { width: 50%; display: inline-flex; justify-content: flex-end; }
div.total { margin-bottom: 1ch; }
label { padding-right: 1ch; }
button + button { margin-left: 1em; }
</style>
</head>
<body>
<h1>
21 Game in PHP 7
</h1>
<p>
21 is a two player game, the game is played by choosing a number
(1, 2, or 3) to be added to the running total. The game is won by
the player whose chosen number causes the running total to reach
exactly 21. The running total starts at zero.
</p>
<?php
const GOAL = 21;
const PLAYERS = array('AI', 'human');
function best_move($n)
{
for ($i = 1; $i <= 3; $i++)
if ($n + $i == GOAL)
return $i;
for ($i = 1; $i <= 3; $i++)
if (($n + $i - 1) % 4 == 0)
return $i;
return 1;
}
if (isset($_GET['reset']) || !isset($_GET['total']))
{
$first = PLAYERS[rand(0, 1)];
$total = 0;
$human = 0;
$ai = 0;
$message = '';
if ($first == 'AI')
{
$move = best_move($total);
$ai = $move;
$total = $total + $move;
}
}
else
{
$first = $_GET['first'];
$total = $_GET['total'];
$human = $_GET['human'];
$ai = $_GET['ai'];
$message = $_GET['message'];
}
if (isset($_GET['move']))
{
$move = (int)$_GET['move'];
$human = $move;
$total = $total + $move;
if ($total == GOAL)
$message = 'The winner is human.';
else
{
$move = best_move($total);
$ai = $move;
$total = $total + $move;
if ($total == GOAL)
$message = 'The winner is AI.';
}
}
$state = array();
for ($i = 1; $i <= 3; $i++)
$state[$i] = $total + $i > GOAL? 'disabled' : '';
echo <<< END
<p>
The first player is $first.
Use buttons to play.
</p>
<form class=>
<div>
<input type='hidden' id='first' name='first' value='$first'>
<input type='hidden' name='message' value='$message'>
</div>
<div class='total'>
<label for='human'>human last choice:</label>
<input type='text' name='human' readonly value='$human'>
</div>
<div class='total'>
<label for='AI'>AI last choice:</label>
<input type='text' name='ai' readonly value='$ai'>
</div>
<div class='total'>
<label for='runningTotalText'>running total:</label>
<input type='text' name='total' readonly value='$total'>
</div>
<div class='buttons'>
<button type='submit' name='move' value='1' {$state[1]}> one </button>
<button type='submit' name='move' value='2' {$state[2]}> two </button>
<button type='submit' name='move' value='3' {$state[3]}> three </button>
<button type='submit' name='reset' value='reset'> reset </button>
</div>
</form>
<p>
$message
</p>
END
?>
</body>
1,17221 game
12php
vux2v
extension BinaryInteger {
@inlinable
public func factors(sorted: Bool = true) -> [Self] {
let maxN = Self(Double(self).squareRoot())
var res = Set<Self>()
for factor in stride(from: 1, through: maxN, by: 1) where self% factor == 0 {
res.insert(factor)
res.insert(self / factor)
}
return sorted? res.sorted(): Array(res)
}
}
@inlinable
public func isAbundant<T: BinaryInteger>(n: T) -> (Bool, [T]) {
let divs = n.factors().dropLast()
return (divs.reduce(0, +) > n, Array(divs))
}
let oddAbundant = (0...).lazy.filter({ $0 & 1 == 1 }).map({ ($0, isAbundant(n: $0)) }).filter({ $1.0 })
for (n, (_, factors)) in oddAbundant.prefix(25) {
print("n: \(n); sigma: \(factors.reduce(0, +))")
}
let (bigA, (_, bigFactors)) =
(1_000_000_000...)
.lazy
.filter({ $0 & 1 == 1 })
.map({ ($0, isAbundant(n: $0)) })
.first(where: { $1.0 })!
print("first odd abundant number over 1 billion: \(bigA), sigma: \(bigFactors.reduce(0, +))")
1,169Abundant odd numbers
17swift
r7dgg
import itertools
def all_equal(a,b,c,d,e,f,g):
return a+b == b+c+d == d+e+f == f+g
def foursquares(lo,hi,unique,show):
solutions = 0
if unique:
uorn =
citer = itertools.combinations(range(lo,hi+1),7)
else:
uorn =
citer = itertools.combinations_with_replacement(range(lo,hi+1),7)
for c in citer:
for p in set(itertools.permutations(c)):
if all_equal(*p):
solutions += 1
if show:
print str(p)[1:-1]
print str(solutions)++uorn++str(lo)++str(hi)
print
1,1714-rings or 4-squares puzzle
3python
1a6pc
from random import randint
def start():
game_count=0
print(.format(game_count))
roundno=1
while game_count<21:
print(.format(roundno))
t = select_count(game_count)
game_count = game_count+t
print(.format(game_count))
if game_count>=21:
print()
return 0
t = request_count()
if not t:
print('OK,quitting the game')
return -1
game_count = game_count+t
print(.format(game_count))
if game_count>=21:
print()
return 1
roundno+=1
def select_count(game_count):
'''selects a random number if the game_count is less than 18. otherwise chooses the winning number'''
if game_count<18:
t= randint(1,3)
else:
t = 21-game_count
print(.format(t))
return t
def request_count():
'''request user input between 1,2 and 3. It will continue till either quit(q) or one of those numbers is requested.'''
t=
while True:
try:
t = raw_input('Your choice 1 to 3:')
if int(t) in [1,2,3]:
return int(t)
else:
print()
except:
if t==:
return None
else:
print()
c=0
m=0
r=True
while r:
o = start()
if o==-1:
break
else:
c+=1 if o==0 else 0
m+=1 if o==1 else 0
print(.format(c,m))
t = raw_input()
r = (t==)
1,17221 game
3python
s0lq9
perms <- function (n, r, v = 1:n, repeats.allowed = FALSE) {
if (repeats.allowed)
sub <- function(n, r, v) {
if (r == 1)
matrix(v, n, 1)
else if (n == 1)
matrix(v, 1, r)
else {
inner <- Recall(n, r - 1, v)
cbind(rep(v, rep(nrow(inner), n)), matrix(t(inner),
ncol = ncol(inner), nrow = nrow(inner) * n,
byrow = TRUE))
}
}
else sub <- function(n, r, v) {
if (r == 1)
matrix(v, n, 1)
else if (n == 1)
matrix(v, 1, r)
else {
X <- NULL
for (i in 1:n) X <- rbind(X, cbind(v[i], Recall(n - 1, r - 1, v[-i])))
X
}
}
X <- sub(n, r, v[1:n])
result <- vector(mode = "numeric")
for(i in 1:nrow(X)){
y <- X[i, ]
x1 <- y[1] + y[2]
x2 <- y[2] + y[3] + y[4]
x3 <- y[4] + y[5] + y[6]
x4 <- y[6] + y[7]
if(x1 == x2 & x2 == x3 & x3 == x4) result <- rbind(result, y)
}
return(result)
}
print_perms <- function(n, r, v = 1:n, repeats.allowed = FALSE, table.out = FALSE) {
a <- perms(n, r, v, repeats.allowed)
colnames(a) <- rep("", ncol(a))
rownames(a) <- rep("", nrow(a))
if(!repeats.allowed){
print(a)
cat(paste('\n', nrow(a), 'unique solutions from', min(v), 'to', max(v)))
} else {
cat(paste('\n', nrow(a), 'non-unique solutions from', min(v), 'to', max(v)))
}
}
registerS3method("print_perms", "data.frame", print_perms)
print_perms(7, 7, repeats.allowed = FALSE, table.out = TRUE)
print_perms(7, 7, v = 3:9, repeats.allowed = FALSE, table.out = TRUE)
print_perms(10, 7, v = 0:9, repeats.allowed = TRUE, table.out = FALSE)
package main
import (
"fmt"
"math/rand"
"time"
)
const (
op_num = iota
op_add
op_sub
op_mul
op_div
)
type frac struct {
num, denom int
}
1,17424 game/Solve
0go
s09qa
game21<-function(first = c("player","ai","random"),sleep=.5){
state = 0
finished = F
turn = 1
if(length(first)==1 && startsWith(tolower(first),"r")){
first = rbinom(1,1,.5)
}else{
first = (length(first)>1 || startsWith(tolower(first),"p"))
}
while(!finished){
if(turn>1 || first){
cat("The total is now",state,"\n");Sys.sleep(sleep)
while(T){
player.move = readline(prompt = "Enter move: ")
if((player.move=="1"||player.move=="2"||player.move=="3") && state+as.numeric(player.move)<=21){
player.move = as.numeric(player.move)
state = state + player.move
break
}else if(tolower(player.move)=="exit"|tolower(player.move)=="quit"|tolower(player.move)=="end"){
cat("Goodbye.\n")
finished = T
break
}else{
cat("Error: invaid entry.\n")
}
}
}
if(state == 21){
cat("You win!\n")
finished = T
}
if(!finished){
cat("The total is now",state,"\n");Sys.sleep(sleep)
while(T){
ai.move = sample(1:3,1)
if(state+ai.move<=21){
break
}
}
state = state + ai.move
cat("The AI chooses",ai.move,"\n");Sys.sleep(sleep)
if(state == 21){
cat("The AI wins!\n")
finished = T
}
}
turn = turn + 1
}
}
1,17221 game
13r
ewyad
package main
import "fmt"
var (
Nr = [16]int{3, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3}
Nc = [16]int{3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2}
)
var (
n, _n int
N0, N3, N4 [85]int
N2 [85]uint64
)
const (
i = 1
g = 8
e = 2
l = 4
)
func fY() bool {
if N2[n] == 0x123456789abcdef0 {
return true
}
if N4[n] <= _n {
return fN()
}
return false
}
func fZ(w int) bool {
if w&i > 0 {
fI()
if fY() {
return true
}
n--
}
if w&g > 0 {
fG()
if fY() {
return true
}
n--
}
if w&e > 0 {
fE()
if fY() {
return true
}
n--
}
if w&l > 0 {
fL()
if fY() {
return true
}
n--
}
return false
}
func fN() bool {
switch N0[n] {
case 0:
switch N3[n] {
case 'l':
return fZ(i)
case 'u':
return fZ(e)
default:
return fZ(i + e)
}
case 3:
switch N3[n] {
case 'r':
return fZ(i)
case 'u':
return fZ(l)
default:
return fZ(i + l)
}
case 1, 2:
switch N3[n] {
case 'l':
return fZ(i + l)
case 'r':
return fZ(i + e)
case 'u':
return fZ(e + l)
default:
return fZ(l + e + i)
}
case 12:
switch N3[n] {
case 'l':
return fZ(g)
case 'd':
return fZ(e)
default:
return fZ(e + g)
}
case 15:
switch N3[n] {
case 'r':
return fZ(g)
case 'd':
return fZ(l)
default:
return fZ(g + l)
}
case 13, 14:
switch N3[n] {
case 'l':
return fZ(g + l)
case 'r':
return fZ(e + g)
case 'd':
return fZ(e + l)
default:
return fZ(g + e + l)
}
case 4, 8:
switch N3[n] {
case 'l':
return fZ(i + g)
case 'u':
return fZ(g + e)
case 'd':
return fZ(i + e)
default:
return fZ(i + g + e)
}
case 7, 11:
switch N3[n] {
case 'd':
return fZ(i + l)
case 'u':
return fZ(g + l)
case 'r':
return fZ(i + g)
default:
return fZ(i + g + l)
}
default:
switch N3[n] {
case 'd':
return fZ(i + e + l)
case 'l':
return fZ(i + g + l)
case 'r':
return fZ(i + g + e)
case 'u':
return fZ(g + e + l)
default:
return fZ(i + g + e + l)
}
}
}
func fI() {
g := (11 - N0[n]) * 4
a := N2[n] & uint64(15<<uint(g))
N0[n+1] = N0[n] + 4
N2[n+1] = N2[n] - a + (a << 16)
N3[n+1] = 'd'
N4[n+1] = N4[n]
cond := Nr[a>>uint(g)] <= N0[n]/4
if !cond {
N4[n+1]++
}
n++
}
func fG() {
g := (19 - N0[n]) * 4
a := N2[n] & uint64(15<<uint(g))
N0[n+1] = N0[n] - 4
N2[n+1] = N2[n] - a + (a >> 16)
N3[n+1] = 'u'
N4[n+1] = N4[n]
cond := Nr[a>>uint(g)] >= N0[n]/4
if !cond {
N4[n+1]++
}
n++
}
func fE() {
g := (14 - N0[n]) * 4
a := N2[n] & uint64(15<<uint(g))
N0[n+1] = N0[n] + 1
N2[n+1] = N2[n] - a + (a << 4)
N3[n+1] = 'r'
N4[n+1] = N4[n]
cond := Nc[a>>uint(g)] <= N0[n]%4
if !cond {
N4[n+1]++
}
n++
}
func fL() {
g := (16 - N0[n]) * 4
a := N2[n] & uint64(15<<uint(g))
N0[n+1] = N0[n] - 1
N2[n+1] = N2[n] - a + (a >> 4)
N3[n+1] = 'l'
N4[n+1] = N4[n]
cond := Nc[a>>uint(g)] >= N0[n]%4
if !cond {
N4[n+1]++
}
n++
}
func fifteenSolver(n int, g uint64) {
N0[0] = n
N2[0] = g
N4[0] = 0
}
func solve() {
if fN() {
fmt.Print("Solution found in ", n, " moves: ")
for g := 1; g <= n; g++ {
fmt.Printf("%c", N3[g])
}
fmt.Println()
} else {
n = 0
_n++
solve()
}
}
func main() {
fifteenSolver(8, 0xfe169b4c0a73d852)
solve()
}
1,17715 puzzle solver
0go
oi98q
import Data.List
import Data.Ratio
import Control.Monad
import System.Environment (getArgs)
data Expr = Constant Rational |
Expr:+ Expr | Expr:- Expr |
Expr:* Expr | Expr:/ Expr
deriving (Eq)
ops = [(:+), (:-), (:*), (:/)]
instance Show Expr where
show (Constant x) = show $ numerator x
show (a:+ b) = strexp "+" a b
show (a:- b) = strexp "-" a b
show (a:* b) = strexp "*" a b
show (a:/ b) = strexp "/" a b
strexp :: String -> Expr -> Expr -> String
strexp op a b = "(" ++ show a ++ " " ++ op ++ " " ++ show b ++ ")"
templates :: [[Expr] -> Expr]
templates = do
op1 <- ops
op2 <- ops
op3 <- ops
[\[a, b, c, d] -> op1 a $ op2 b $ op3 c d,
\[a, b, c, d] -> op1 (op2 a b) $ op3 c d,
\[a, b, c, d] -> op1 a $ op2 (op3 b c) d,
\[a, b, c, d] -> op1 (op2 a $ op3 b c) d,
\[a, b, c, d] -> op1 (op2 (op3 a b) c) d]
eval :: Expr -> Maybe Rational
eval (Constant c) = Just c
eval (a:+ b) = liftM2 (+) (eval a) (eval b)
eval (a:- b) = liftM2 (-) (eval a) (eval b)
eval (a:* b) = liftM2 (*) (eval a) (eval b)
eval (a:/ b) = do
denom <- eval b
guard $ denom /= 0
liftM (/ denom) $ eval a
solve :: Rational -> [Rational] -> [Expr]
solve target r4 = filter (maybe False (== target) . eval) $
liftM2 ($) templates $
nub $ permutations $ map Constant r4
main = getArgs >>= mapM_ print . solve 24 . map (toEnum . read)
1,17424 game/Solve
8haskell
9cbmo
const long values[] = {
0, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048
};
const char *colors[] = {
, , , , , , , , , , ,
};
struct gamestate_struct__ {
int grid[4][4];
int have_moved;
long total_score;
long score_last_move;
int blocks_in_play;
} game;
struct termios oldt, newt;
void do_draw(void)
{
printf(, game.total_score);
if (game.score_last_move)
printf(, game.score_last_move);
printf();
for (int i = 0; i < 25; ++i)
printf();
printf();
for (int y = 0; y < 4; ++y) {
printf();
for (int x = 0; x < 4; ++x) {
if (game.grid[x][y])
printf(, colors[game.grid[x][y]],
4, values[game.grid[x][y]]);
else
printf(, 4, );
}
printf();
}
for (int i = 0; i < 25; ++i) {
printf();
}
printf();
}
void do_merge(int d)
{
do { \
for (int _v1 = _xs; _v1 _xc; _v1 += _xi) { \
for (int _v2 = _ys; _v2 _yc; _v2 += _yi) { \
if (game.grid[x][y] && (game.grid[x][y] == \
game.grid[x + _x][y + _y])) { \
game.grid[x][y] += (game.have_moved = 1); \
game.grid[x + _x][y + _y] = (0 * game.blocks_in_play--);\
game.score_last_move += values[game.grid[x][y]]; \
game.total_score += values[game.grid[x][y]]; \
} \
} \
} \
} while (0)
game.score_last_move = 0;
switch (d) {
case D_LEFT:
MERGE_DIRECTION(x, y, 0, < 3, 1, 0, < 4, 1, 1, 0);
break;
case D_RIGHT:
MERGE_DIRECTION(x, y, 3, > 0, -1, 0, < 4, 1, -1, 0);
break;
case D_DOWN:
MERGE_DIRECTION(y, x, 3, > 0, -1, 0, < 4, 1, 0, -1);
break;
case D_UP:
MERGE_DIRECTION(y, x, 0, < 3, 1, 0, < 4, 1, 0, 1);
break;
}
}
void do_gravity(int d)
{
do { \
int break_cond = 0; \
while (!break_cond) { \
break_cond = 1; \
for (int _v1 = _xs; _v1 _xc; _v1 += _xi) { \
for (int _v2 = _ys; _v2 _yc; _v2 += _yi) { \
if (!game.grid[x][y] && game.grid[x + _x][y + _y]) { \
game.grid[x][y] = game.grid[x + _x][y + _y]; \
game.grid[x + _x][y + _y] = break_cond = 0; \
game.have_moved = 1; \
} \
} \
} \
do_draw(); usleep(40000); \
} \
} while (0)
switch (d) {
case D_LEFT:
GRAVITATE_DIRECTION(x, y, 0, < 3, 1, 0, < 4, 1, 1, 0);
break;
case D_RIGHT:
GRAVITATE_DIRECTION(x, y, 3, > 0, -1, 0, < 4, 1, -1, 0);
break;
case D_DOWN:
GRAVITATE_DIRECTION(y, x, 3, > 0, -1, 0, < 4, 1, 0, -1);
break;
case D_UP:
GRAVITATE_DIRECTION(y, x, 0, < 3, 1, 0, < 4, 1, 0, 1);
break;
}
}
int do_check_end_condition(void)
{
int ret = -1;
for (int x = 0; x < 4; ++x) {
for (int y = 0; y < 4; ++y) {
if (values[game.grid[x][y]] == 2048)
return 1;
if (!game.grid[x][y] ||
((x + 1 < 4) && (game.grid[x][y] == game.grid[x + 1][y])) ||
((y + 1 < 4) && (game.grid[x][y] == game.grid[x][y + 1])))
ret = 0;
}
}
return ret;
}
int do_tick(int d)
{
game.have_moved = 0;
do_gravity(d);
do_merge(d);
do_gravity(d);
return game.have_moved;
}
void do_newblock(void) {
if (game.blocks_in_play >= 16) return;
int bn = rand() % (16 - game.blocks_in_play);
int pn = 0;
for (int x = 0; x < 4; ++x) {
for (int y = 0; y < 4; ++y) {
if (game.grid[x][y])
continue;
if (pn == bn){
game.grid[x][y] = rand() % 10 ? 1 : 2;
game.blocks_in_play += 1;
return;
}
else {
++pn;
}
}
}
}
int main(void)
{
tcgetattr(STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
srand(time(NULL));
memset(&game, 0, sizeof(game));
do_newblock();
do_newblock();
do_draw();
while (1) {
int found_valid_key, direction, value;
do {
found_valid_key = 1;
direction = D_INVALID;
value = getchar();
switch (value) {
case 'h': case 'a':
direction = D_LEFT;
break;
case 'l': case 'd':
direction = D_RIGHT;
break;
case 'j': case 's':
direction = D_DOWN;
break;
case 'k': case 'w':
direction = D_UP;
break;
case 'q':
goto game_quit;
break;
case 27:
if (getchar() == 91) {
value = getchar();
switch (value) {
case 65:
direction = D_UP;
break;
case 66:
direction = D_DOWN;
break;
case 67:
direction = D_RIGHT;
break;
case 68:
direction = D_LEFT;
break;
default:
found_valid_key = 0;
break;
}
}
break;
default:
found_valid_key = 0;
break;
}
} while (!found_valid_key);
do_tick(direction);
if (game.have_moved != 0){
do_newblock();
}
do_draw();
switch (do_check_end_condition()) {
case -1:
goto game_lose;
case 1:
goto game_win;
case 0:
break;
}
}
if (0)
game_lose:
printf();
goto game_quit;
if (0)
game_win:
printf();
goto game_quit;
if (0)
game_quit:
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
return 0;
}
1,1792048
5c
qstxc
def four_squares(low, high, unique=true, show=unique)
f = -> (a,b,c,d,e,f,g) {[a+b, b+c+d, d+e+f, f+g].uniq.size == 1}
if unique
uniq =
solutions = [*low..high].permutation(7).select{|ary| f.call(*ary)}
else
uniq =
solutions = [*low..high].repeated_permutation(7).select{|ary| f.call(*ary)}
end
if show
puts + [*..].join()
solutions.each{|ary| p ary}
end
puts
puts
end
[[1,7], [3,9]].each do |low, high|
four_squares(low, high)
end
four_squares(0, 9, false)
1,1714-rings or 4-squares puzzle
14ruby
ewmax
#!/usr/bin/lua
1,17715 puzzle solver
1lua
ftvdp
package main
import (
"fmt"
"strings"
)
func newSpeller(blocks string) func(string) bool {
bl := strings.Fields(blocks)
return func(word string) bool {
return r(word, bl)
}
}
func r(word string, bl []string) bool {
if word == "" {
return true
}
c := word[0] | 32
for i, b := range bl {
if c == b[0]|32 || c == b[1]|32 {
bl[i], bl[0] = bl[0], b
if r(word[1:], bl[1:]) == true {
return true
}
bl[i], bl[0] = bl[0], bl[i]
}
}
return false
}
func main() {
sp := newSpeller(
"BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM")
for _, word := range []string{
"A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "CONFUSE"} {
fmt.Println(word, sp(word))
}
}
1,173ABC problem
0go
gr04n
#![feature(inclusive_range_syntax)]
fn is_unique(a: u8, b: u8, c: u8, d: u8, e: u8, f: u8, g: u8) -> bool {
a!= b && a!= c && a!= d && a!= e && a!= f && a!= g &&
b!= c && b!= d && b!= e && b!= f && b!= g &&
c!= d && c!= e && c!= f && c!= g &&
d!= e && d!= f && d!= g &&
e!= f && e!= g &&
f!= g
}
fn is_solution(a: u8, b: u8, c: u8, d: u8, e: u8, f: u8, g: u8) -> bool {
a + b == b + c + d &&
b + c + d == d + e + f &&
d + e + f == f + g
}
fn four_squares(low: u8, high: u8, unique: bool) -> Vec<Vec<u8>> {
let mut results: Vec<Vec<u8>> = Vec::new();
for a in low..=high {
for b in low..=high {
for c in low..=high {
for d in low..=high {
for e in low..=high {
for f in low..=high {
for g in low..=high {
if (!unique || is_unique(a, b, c, d, e, f, g)) &&
is_solution(a, b, c, d, e, f, g) {
results.push(vec![a, b, c, d, e, f, g]);
}
}
}
}
}
}
}
}
results
}
fn print_results(solutions: &Vec<Vec<u8>>) {
for solution in solutions {
println!("{:?}", solution)
}
}
fn print_results_summary(solutions: usize, low: u8, high: u8, unique: bool) {
let uniqueness = if unique {
"unique"
} else {
"non-unique"
};
println!("{} {} solutions in {} to {} range", solutions, uniqueness, low, high)
}
fn uniques(low: u8, high: u8) {
let solutions = four_squares(low, high, true);
print_results(&solutions);
print_results_summary(solutions.len(), low, high, true);
}
fn nonuniques(low: u8, high: u8) {
let solutions = four_squares(low, high, false);
print_results_summary(solutions.len(), low, high, false);
}
fn main() {
uniques(1, 7);
println!();
uniques(3, 9);
println!();
nonuniques(0, 9);
}
object FourRings {
def fourSquare(low: Int, high: Int, unique: Boolean, print: Boolean): Unit = {
def isValid(needle: Integer, haystack: Integer*) = !unique || !haystack.contains(needle)
if (print) println("a b c d e f g")
var count = 0
for {
a <- low to high
b <- low to high if isValid(a, b)
fp = a + b
c <- low to high if isValid(c, a, b)
d <- low to high if isValid(d, a, b, c) && fp == b + c + d
e <- low to high if isValid(e, a, b, c, d)
f <- low to high if isValid(f, a, b, c, d, e) && fp == d + e + f
g <- low to high if isValid(g, a, b, c, d, e, f) && fp == f + g
} {
count += 1
if (print) println(s"$a $b $c $d $e $f $g")
}
println(s"There are $count ${if(unique) "unique" else "non-unique"} solutions in [$low, $high]")
}
def main(args: Array[String]): Unit = {
fourSquare(1, 7, unique = true, print = true)
fourSquare(3, 9, unique = true, print = true)
fourSquare(0, 9, unique = false, print = false)
}
}
1,1714-rings or 4-squares puzzle
16scala
s02qo
GOAL = 21
MIN_MOVE = 1
MAX_MOVE = 3
DESCRIPTION =
def best_move(total)
move = rand(1..3)
MIN_MOVE.upto(MAX_MOVE) do |i|
move = i if (total + i - 1) % (MAX_MOVE + 1) == 0
end
MIN_MOVE.upto(MAX_MOVE) do |i|
move = i if total + i == GOAL
end
move
end
def get_move
print
answer = gets
move = answer.to_i
until move.between?(MIN_MOVE, MAX_MOVE)
exit if answer.chomp == 'q'
print 'Invalid choice. Try again: '
answer = gets
move = answer.to_i
end
move
end
def restart?
print 'Do you want to restart (y/n)? '
restart = gets.chomp
until ['y', 'n'].include?(restart)
print 'Your answer is not a valid choice. Try again: '
restart = gets.chomp
end
restart == 'y'
end
def game(player)
total = round = 0
while total < GOAL
round += 1
puts
player = (player + 1) % 2
if player == 0
move = best_move(total)
puts
else
move = get_move
end
total += move
puts
end
if player == 0
puts 'Sorry, the computer has won!'
return false
end
puts 'Well done, you have won!'
true
end
puts DESCRIPTION
run = true
computer_wins = human_wins = 0
games_counter = player = 1
while run
puts
player = (player + 1) % 2
if game(player)
human_wins += 1
else
computer_wins += 1
end
puts
games_counter += 1
run = restart?
end
puts 'Good bye!'
1,17221 game
14ruby
8ov01
var ar=[],order=[0,1,2],op=[],val=[];
var NOVAL=9999,oper="+-*/",out;
function rnd(n){return Math.floor(Math.random()*n)}
function say(s){
try{document.write(s+"<br>")}
catch(e){WScript.Echo(s)}
}
function getvalue(x,dir){
var r=NOVAL;
if(dir>0)++x;
while(1){
if(val[x]!=NOVAL){
r=val[x];
val[x]=NOVAL;
break;
}
x+=dir;
}
return r*1;
}
function calc(){
var c=0,l,r,x;
val=ar.join('/').split('/');
while(c<3){
x=order[c];
l=getvalue(x,-1);
r=getvalue(x,1);
switch(op[x]){
case 0:val[x]=l+r;break;
case 1:val[x]=l-r;break;
case 2:val[x]=l*r;break;
case 3:
if(!r||l%r)return 0;
val[x]=l/r;
}
++c;
}
return getvalue(-1,1);
}
function shuffle(s,n){
var x=n,p=eval(s),r,t;
while(x--){
r=rnd(n);
t=p[x];
p[x]=p[r];
p[r]=t;
}
}
function parenth(n){
while(n>0)--n,out+='(';
while(n<0)++n,out+=')';
}
function getpriority(x){
for(var z=3;z--;)if(order[z]==x)return 3-z;
return 0;
}
function showsolution(){
var x=0,p=0,lp=0,v=0;
while(x<4){
if(x<3){
lp=p;
p=getpriority(x);
v=p-lp;
if(v>0)parenth(v);
}
out+=ar[x];
if(x<3){
if(v<0)parenth(v);
out+=oper.charAt(op[x]);
}
++x;
}
parenth(-p);
say(out);
}
function solve24(s){
var z=4,r;
while(z--)ar[z]=s.charCodeAt(z)-48;
out="";
for(z=100000;z--;){
r=rnd(256);
op[0]=r&3;
op[1]=(r>>2)&3;
op[2]=(r>>4)&3;
shuffle("ar",4);
shuffle("order",3);
if(calc()!=24)continue;
showsolution();
break;
}
}
solve24("1234");
solve24("6789");
solve24("1127");
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class ABC {
public static void main(String[] args) {
List<String> blocks = Arrays.asList(
"BO", "XK", "DQ", "CP", "NA",
"GT", "RE", "TG", "QD", "FS",
"JW", "HU", "VI", "AN", "OB",
"ER", "FS", "LY", "PC", "ZM");
for (String word: Arrays.asList("", "A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "CONFUSE")) {
System.out.printf("%s:%s%n", word.isEmpty() ? "\"\"": word, canMakeWord(word, blocks));
}
}
public static boolean canMakeWord(String word, List<String> blocks) {
if (word.isEmpty())
return true;
char c = word.charAt(0);
for (int i = 0; i < blocks.size(); i++) {
String b = blocks.get(i);
if (b.charAt(0) != c && b.charAt(1) != c)
continue;
Collections.swap(blocks, 0, i);
if (canMakeWord(word.substring(1), blocks.subList(1, blocks.size())))
return true;
Collections.swap(blocks, 0, i);
}
return false;
}
}
1,173ABC problem
9java
1azp2
final random = new Random()
final input = new Scanner(System.in)
def evaluate = { expr ->
if (expr == 'QUIT') {
return 'QUIT'
} else {
try { Eval.me(expr.replaceAll(/(\d)/, '$1.0')) }
catch (e) { 'syntax error' }
}
}
def readGuess = { digits ->
while (true) {
print "Enter your guess using ${digits} (q to quit): "
def expr = input.nextLine()
switch (expr) {
case ~/^[qQ].*/:
return 'QUIT'
case ~/.*[^\d\s\+\*\/\(\)-].*/:
def badChars = expr.replaceAll(~/[\d\s\+\*\/\(\)-]/, '')
println "invalid characters in input: ${(badChars as List) as Set}"
break
case { (it.replaceAll(~/\D/, '') as List).sort() != ([]+digits).sort() }:
println '''you didn't use the right digits'''
break
case ~/.*\d\d.*/:
println 'no multi-digit numbers allowed'
break
default:
return expr
}
}
}
def digits = (1..4).collect { (random.nextInt(9) + 1) as String }
while (true) {
def guess = readGuess(digits)
def result = evaluate(guess)
switch (result) {
case 'QUIT':
println 'Awwww. Maybe next time?'
return
case 24:
println 'Yes! You got it.'
return
case 'syntax error':
println "A ${result} was found in ${guess}"
break
default:
println "Nope: ${guess} == ${result}, not 24"
println 'One more try, then?'
}
}
1,17524 game
7groovy
kbih7
var blocks = "BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM";
function CheckWord(blocks, word) {
1,173ABC problem
10javascript
qs9x8
package main
import (
"fmt"
"math/rand"
"time"
)
1,176100 prisoners
0go
aef1f
local SIZE = #arg[1]
local GOAL = tonumber(arg[2]) or 24
local input = {}
for v in arg[1]:gmatch("%d") do
table.insert(input, v)
end
assert(#input == SIZE, 'Invalid input')
local operations = {'+', '-', '*', '/'}
local function BinaryTrees(vert)
if vert == 0 then
return {false}
else
local buf = {}
for leften = 0, vert - 1 do
local righten = vert - leften - 1
for _, left in pairs(BinaryTrees(leften)) do
for _, right in pairs(BinaryTrees(righten)) do
table.insert(buf, {left, right})
end
end
end
return buf
end
end
local trees = BinaryTrees(SIZE-1)
local c, opc, oper, str
local max = math.pow(#operations, SIZE-1)
local function op(a,b)
opc = opc + 1
local i = math.floor(oper/math.pow(#operations, opc-1))%#operations+1
return '('.. a .. operations[i] .. b ..')'
end
local function EvalTree(tree)
if tree == false then
c = c + 1
return input[c-1]
else
return op(EvalTree(tree[1]), EvalTree(tree[2]))
end
end
local function printResult()
for _, v in ipairs(trees) do
for i = 0, max do
c, opc, oper = 1, 0, i
str = EvalTree(v)
loadstring('res='..str)()
if(res == GOAL) then print(str, '=', res) end
end
end
end
local uniq = {}
local function permgen (a, n)
if n == 0 then
local str = table.concat(a)
if not uniq[str] then
printResult()
uniq[str] = true
end
else
for i = 1, n do
a[n], a[i] = a[i], a[n]
permgen(a, n - 1)
a[n], a[i] = a[i], a[n]
end
end
end
permgen(input, SIZE)
1,17424 game/Solve
1lua
invot
import Data.List (sort)
import Data.Char (isDigit)
import Data.Maybe (fromJust)
import Control.Monad (foldM)
import System.Random (randomRs, getStdGen)
import System.IO (hSetBuffering, stdout, BufferMode(NoBuffering))
main = do
hSetBuffering stdout NoBuffering
mapM_
putStrLn
[ "THE 24 GAME\n"
, "Given four digits in the range 1 to 9"
, "Use the +, -, *, and / operators in reverse polish notation"
, "To show how to make an answer of 24.\n"
]
digits <- fmap (sort . take 4 . randomRs (1, 9)) getStdGen :: IO [Int]
putStrLn ("Your digits: " ++ unwords (fmap show digits))
guessLoop digits
where
guessLoop digits =
putStr "Your expression: " >> fmap (processGuess digits . words) getLine >>=
either (\m -> putStrLn m >> guessLoop digits) putStrLn
processGuess _ [] = Right ""
processGuess digits xs
| not matches = Left "Wrong digits used"
where
matches = digits == (sort . fmap read $ filter (all isDigit) xs)
processGuess digits xs = calc xs >>= check
where
check 24 = Right "Correct"
check x = Left (show (fromRational (x :: Rational)) ++ " is wrong")
calc xs =
foldM simplify [] xs >>=
\ns ->
(case ns of
[n] -> Right n
_ -> Left "Too few operators")
simplify (a:b:ns) s
| isOp s = Right ((fromJust $ lookup s ops) b a: ns)
simplify _ s
| isOp s = Left ("Too few values before " ++ s)
simplify ns s
| all isDigit s = Right (fromIntegral (read s): ns)
simplify _ s = Left ("Unrecognized symbol: " ++ s)
isOp v = elem v $ fmap fst ops
ops = [("+", (+)), ("-", (-)), ("*", (*)), ("/", (/))]
1,17524 game
8haskell
36rzj
import java.util.function.Function
import java.util.stream.Collectors
import java.util.stream.IntStream
class Prisoners {
private static boolean playOptimal(int n) {
List<Integer> secretList = IntStream.range(0, n).boxed().collect(Collectors.toList())
Collections.shuffle(secretList)
prisoner:
for (int i = 0; i < secretList.size(); ++i) {
int prev = i
for (int j = 0; j < secretList.size() / 2; ++j) {
if (secretList.get(prev) == i) {
continue prisoner
}
prev = secretList.get(prev)
}
return false
}
return true
}
private static boolean playRandom(int n) {
List<Integer> secretList = IntStream.range(0, n).boxed().collect(Collectors.toList())
Collections.shuffle(secretList)
prisoner:
for (Integer i: secretList) {
List<Integer> trialList = IntStream.range(0, n).boxed().collect(Collectors.toList())
Collections.shuffle(trialList)
for (int j = 0; j < trialList.size() / 2; ++j) {
if (Objects.equals(trialList.get(j), i)) {
continue prisoner
}
}
return false
}
return true
}
private static double exec(int n, int p, Function<Integer, Boolean> play) {
int succ = 0
for (int i = 0; i < n; ++i) {
if (play.apply(p)) {
succ++
}
}
return (succ * 100.0) / n
}
static void main(String[] args) {
final int n = 100_000
final int p = 100
System.out.printf("# of executions:%d\n", n)
System.out.printf("Optimal play success rate:%f%%\n", exec(n, p, Prisoners.&playOptimal))
System.out.printf("Random play success rate:%f%%\n", exec(n, p, Prisoners.&playRandom))
}
}
1,176100 prisoners
7groovy
hk8j9
import System.Random
import Control.Monad.State
numRuns = 10000
numPrisoners = 100
numDrawerTries = 50
type Drawers = [Int]
type Prisoner = Int
type Prisoners = [Int]
main = do
gen <- getStdGen
putStrLn $ "Chance of winning when choosing randomly: " ++ (show $ evalState runRandomly gen)
putStrLn $ "Chance of winning when choosing optimally: " ++ (show $ evalState runOptimally gen)
runRandomly :: State StdGen Double
runRandomly =
let runResults = replicateM numRuns $ do
drawers <- state $ shuffle [1..numPrisoners]
allM (\prisoner -> openDrawersRandomly drawers prisoner numDrawerTries) [1..numPrisoners]
in ((/ fromIntegral numRuns) . fromIntegral . sum . map fromEnum) `liftM` runResults
openDrawersRandomly :: Drawers -> Prisoner -> Int -> State StdGen Bool
openDrawersRandomly drawers prisoner triesLeft = go triesLeft []
where go 0 _ = return False
go triesLeft seenDrawers = do
try <- state $ randomR (1, numPrisoners)
case try of
x | x == prisoner -> return True
| x `elem` seenDrawers -> go triesLeft seenDrawers
| otherwise -> go (triesLeft - 1) (x:seenDrawers)
runOptimally :: State StdGen Double
runOptimally =
let runResults = replicateM numRuns $ do
drawers <- state $ shuffle [1..numPrisoners]
return $ all (\prisoner -> openDrawersOptimally drawers prisoner numDrawerTries) [1..numPrisoners]
in ((/ fromIntegral numRuns) . fromIntegral . sum . map fromEnum) `liftM` runResults
openDrawersOptimally :: Drawers -> Prisoner -> Int -> Bool
openDrawersOptimally drawers prisoner triesLeft = go triesLeft prisoner
where go 0 _ = False
go triesLeft drawerToTry =
let thisDrawer = drawers !! (drawerToTry - 1)
in if thisDrawer == prisoner then True else go (triesLeft - 1) thisDrawer
randomLR :: Integral a => Random b => a -> (b, b) -> StdGen -> ([b], StdGen)
randomLR 0 range gen = ([], gen)
randomLR len range gen =
let (x, newGen) = randomR range gen
(xs, lastGen) = randomLR (len - 1) range newGen
in (x: xs, lastGen)
shuffle :: [a] -> StdGen -> ([a], StdGen)
shuffle list gen = (shuffleByNumbers numbers list, finalGen)
where
n = length list
(numbers, finalGen) = randomLR n (0, n-1) gen
shuffleByNumbers :: [Int] -> [a] -> [a]
shuffleByNumbers [] _ = []
shuffleByNumbers _ [] = []
shuffleByNumbers (i:is) xs = let (start, x:rest) = splitAt (i `mod` length xs) xs
in x: shuffleByNumbers is (start ++ rest)
allM :: Monad m => (a -> m Bool) -> [a] -> m Bool
allM func [] = return True
allM func (x:xs) = func x >>= \res -> if res then allM func xs else return False
1,176100 prisoners
8haskell
z34t0
object ABC_block_checker {
fun run() {
println("\"\": " + blocks.canMakeWord(""))
for (w in words) println("$w: " + blocks.canMakeWord(w))
}
private fun Array<String>.swap(i: Int, j: Int) {
val tmp = this[i]
this[i] = this[j]
this[j] = tmp
}
private fun Array<String>.canMakeWord(word: String): Boolean {
if (word.isEmpty())
return true
val c = word.first().toUpperCase()
var i = 0
forEach { b ->
if (b.first().toUpperCase() == c || b[1].toUpperCase() == c) {
swap(0, i)
if (drop(1).toTypedArray().canMakeWord(word.substring(1)))
return true
swap(0, i)
}
i++
}
return false
}
private val blocks = arrayOf(
"BO", "XK", "DQ", "CP", "NA", "GT", "RE", "TG", "QD", "FS",
"JW", "HU", "VI", "AN", "OB", "ER", "FS", "LY", "PC", "ZM"
)
private val words = arrayOf("A", "BARK", "book", "treat", "COMMON", "SQuAd", "CONFUSE")
}
fun main(args: Array<String>) = ABC_block_checker.run()
1,173ABC problem
11kotlin
jhi7r
sub permute (&@) {
my $code = shift;
my @idx = 0..$
while ( $code->(@_[@idx]) ) {
my $p = $
--$p while $idx[$p-1] > $idx[$p];
my $q = $p or return;
push @idx, reverse splice @idx, $p;
++$q while $idx[$p-1] > $idx[$q];
@idx[$p-1,$q]=@idx[$q,$p-1];
}
}
@formats = (
'((%d%s%d)%s%d)%s%d',
'(%d%s (%d%s%d))%s%d',
'(%d%s%d)%s (%d%s%d)',
'%d%s ((%d%s%d)%s%d)',
'%d%s (%d%s (%d%s%d))',
);
@op = qw( + - * / );
@operators = map{ $a=$_; map{ $b=$_; map{ "$a $b $_" }@op }@op }@op;
while(1)
{
print "Enter four integers or 'q' to exit: ";
chomp($ent = <>);
last if $ent eq 'q';
if($ent !~ /^[1-9] [1-9] [1-9] [1-9]$/){ print "invalid input\n"; next }
@n = split / /,$ent;
permute { push @numbers,join ' ',@_ }@n;
for $format (@formats)
{
for(@numbers)
{
@n = split;
for(@operators)
{
@o = split;
$str = sprintf $format,$n[0],$o[0],$n[1],$o[1],$n[2],$o[2],$n[3];
$r = eval($str);
print "$str\n" if $r == 24;
}
}
}
}
1,17424 game/Solve
2perl
grs4e
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Main {
private static boolean playOptimal(int n) {
List<Integer> secretList = IntStream.range(0, n).boxed().collect(Collectors.toList());
Collections.shuffle(secretList);
prisoner:
for (int i = 0; i < secretList.size(); ++i) {
int prev = i;
for (int j = 0; j < secretList.size() / 2; ++j) {
if (secretList.get(prev) == i) {
continue prisoner;
}
prev = secretList.get(prev);
}
return false;
}
return true;
}
private static boolean playRandom(int n) {
List<Integer> secretList = IntStream.range(0, n).boxed().collect(Collectors.toList());
Collections.shuffle(secretList);
prisoner:
for (Integer i : secretList) {
List<Integer> trialList = IntStream.range(0, n).boxed().collect(Collectors.toList());
Collections.shuffle(trialList);
for (int j = 0; j < trialList.size() / 2; ++j) {
if (Objects.equals(trialList.get(j), i)) {
continue prisoner;
}
}
return false;
}
return true;
}
private static double exec(int n, int p, Function<Integer, Boolean> play) {
int succ = 0;
for (int i = 0; i < n; ++i) {
if (play.apply(p)) {
succ++;
}
}
return (succ * 100.0) / n;
}
public static void main(String[] args) {
final int n = 100_000;
final int p = 100;
System.out.printf("# of executions:%d\n", n);
System.out.printf("Optimal play success rate:%f%%\n", exec(n, p, Main::playOptimal));
System.out.printf("Random play success rate:%f%%\n", exec(n, p, Main::playRandom));
}
}
1,176100 prisoners
9java
oic8d
package main
import (
"bufio"
"fmt"
"log"
"math/rand"
"os"
"os/exec"
"strconv"
"strings"
"text/template"
"time"
"unicode"
"golang.org/x/crypto/ssh/terminal"
)
const maxPoints = 2048
const (
fieldSizeX = 4
fieldSizeY = 4
)
const tilesAtStart = 2
const probFor2 = 0.9
type button int
const (
_ button = iota
up
down
right
left
quit
)
var labels = func() map[button]rune {
m := make(map[button]rune, 4)
m[up] = 'W'
m[down] = 'S'
m[right] = 'D'
m[left] = 'A'
return m
}()
var keybinding = func() map[rune]button {
m := make(map[rune]button, 8)
for b, r := range labels {
m[r] = b
if unicode.IsUpper(r) {
r = unicode.ToLower(r)
} else {
r = unicode.ToUpper(r)
}
m[r] = b
}
m[0x03] = quit
return m
}()
var model = struct {
Score int
Field [fieldSizeY][fieldSizeX]int
}{}
var view = func() *template.Template {
maxWidth := 1
for i := maxPoints; i >= 10; i /= 10 {
maxWidth++
}
w := maxWidth + 3
r := make([]byte, fieldSizeX*w+1)
for i := range r {
if i%w == 0 {
r[i] = '+'
} else {
r[i] = '-'
}
}
rawBorder := string(r)
v, err := template.New("").Parse(`SCORE: {{.Score}}
{{range .Field}}
` + rawBorder + `
|{{range .}} {{if .}}{{printf "%` + strconv.Itoa(maxWidth) + `d" .}}{{else}}` +
strings.Repeat(" ", maxWidth) + `{{end}} |{{end}}{{end}}
` + rawBorder + `
(` + string(labels[up]) + `)Up (` +
string(labels[down]) + `)Down (` +
string(labels[left]) + `)Left (` +
string(labels[right]) + `)Right
`)
check(err)
return v
}()
func check(err error) {
if err != nil {
log.Panicln(err)
}
}
func clear() {
c := exec.Command("clear")
c.Stdout = os.Stdout
check(c.Run())
}
func draw() {
clear()
check(view.Execute(os.Stdout, model))
}
func addRandTile() (full bool) {
free := make([]*int, 0, fieldSizeX*fieldSizeY)
for x := 0; x < fieldSizeX; x++ {
for y := 0; y < fieldSizeY; y++ {
if model.Field[y][x] == 0 {
free = append(free, &model.Field[y][x])
}
}
}
val := 4
if rand.Float64() < probFor2 {
val = 2
}
*free[rand.Intn(len(free))] = val
return len(free) == 1
}
type point struct{ x, y int }
func (p point) get() int { return model.Field[p.y][p.x] }
func (p point) set(n int) { model.Field[p.y][p.x] = n }
func (p point) inField() bool { return p.x >= 0 && p.y >= 0 && p.x < fieldSizeX && p.y < fieldSizeY }
func (p *point) next(n point) { p.x += n.x; p.y += n.y }
func controller(key rune) (gameOver bool) {
b := keybinding[key]
if b == 0 {
return false
}
if b == quit {
return true
}
var starts []point
var next point
switch b {
case up:
next = point{0, 1}
starts = make([]point, fieldSizeX)
for x := 0; x < fieldSizeX; x++ {
starts[x] = point{x, 0}
}
case down:
next = point{0, -1}
starts = make([]point, fieldSizeX)
for x := 0; x < fieldSizeX; x++ {
starts[x] = point{x, fieldSizeY - 1}
}
case right:
next = point{-1, 0}
starts = make([]point, fieldSizeY)
for y := 0; y < fieldSizeY; y++ {
starts[y] = point{fieldSizeX - 1, y}
}
case left:
next = point{1, 0}
starts = make([]point, fieldSizeY)
for y := 0; y < fieldSizeY; y++ {
starts[y] = point{0, y}
}
}
moved := false
winning := false
for _, s := range starts {
n := s
move := func(set int) {
moved = true
s.set(set)
n.set(0)
}
for n.next(next); n.inField(); n.next(next) {
if s.get() != 0 {
if n.get() == s.get() {
score := s.get() * 2
model.Score += score
winning = score >= maxPoints
move(score)
s.next(next)
} else if n.get() != 0 {
s.next(next)
if s.get() == 0 {
move(n.get())
}
}
} else if n.get() != 0 {
move(n.get())
}
}
}
if !moved {
return false
}
lost := false
if addRandTile() {
lost = true
Out:
for x := 0; x < fieldSizeX; x++ {
for y := 0; y < fieldSizeY; y++ {
if (y > 0 && model.Field[y][x] == model.Field[y-1][x]) ||
(x > 0 && model.Field[y][x] == model.Field[y][x-1]) {
lost = false
break Out
}
}
}
}
draw()
if winning {
fmt.Println("You win!")
return true
}
if lost {
fmt.Println("Game Over")
return true
}
return false
}
func main() {
oldState, err := terminal.MakeRaw(0)
check(err)
defer terminal.Restore(0, oldState)
rand.Seed(time.Now().Unix())
for i := tilesAtStart; i > 0; i-- {
addRandTile()
}
draw()
stdin := bufio.NewReader(os.Stdin)
readKey := func() rune {
r, _, err := stdin.ReadRune()
check(err)
return r
}
for !controller(readKey()) {
}
}
1,1792048
0go
2vhl7
import java.util.*;
public class Game24 {
static Random r = new Random();
public static void main(String[] args) {
int[] digits = randomDigits();
Scanner in = new Scanner(System.in);
System.out.print("Make 24 using these digits: ");
System.out.println(Arrays.toString(digits));
System.out.print("> ");
Stack<Float> s = new Stack<>();
long total = 0;
for (char c : in.nextLine().toCharArray()) {
if ('0' <= c && c <= '9') {
int d = c - '0';
total += (1 << (d * 5));
s.push((float) d);
} else if ("+/-*".indexOf(c) != -1) {
s.push(applyOperator(s.pop(), s.pop(), c));
}
}
if (tallyDigits(digits) != total)
System.out.print("Not the same digits. ");
else if (Math.abs(24 - s.peek()) < 0.001F)
System.out.println("Correct!");
else
System.out.print("Not correct.");
}
static float applyOperator(float a, float b, char c) {
switch (c) {
case '+':
return a + b;
case '-':
return b - a;
case '*':
return a * b;
case '/':
return b / a;
default:
return Float.NaN;
}
}
static long tallyDigits(int[] a) {
long total = 0;
for (int i = 0; i < 4; i++)
total += (1 << (a[i] * 5));
return total;
}
static int[] randomDigits() {
int[] result = new int[4];
for (int i = 0; i < 4; i++)
result[i] = r.nextInt(9) + 1;
return result;
}
}
import System.IO
import Data.List
import Data.Maybe
import Control.Monad
import Data.Random
import Data.Random.Distribution.Categorical
import System.Console.ANSI
import Control.Lens
prob4 :: Double
prob4 = 0.1
type Position = [[Int]]
combine, shift :: [Int]->[Int]
combine (x:y:l) | x==y = (2*x): combine l
combine (x:l) = x: combine l
combine [] = []
shift l = take (length l) $ combine (filter (>0) l) ++ [0,0..]
reflect :: [[a]] ->[[a]]
reflect = map reverse
type Move = Position -> Position
left, right, up, down :: Move
left = map shift
right = reflect . left . reflect
up = transpose . left . transpose
down = transpose . right . transpose
progress :: Eq a => (a -> a) -> a -> Maybe a
progress f pos = if pos==next_pos then Nothing else Just next_pos where next_pos= f pos
lost, win:: Position -> Bool
lost pos = all isNothing [progress move pos| move<-[left,right,up,down] ]
win = any $ any (>=2048)
go :: Position -> Maybe Move -> Maybe Position
go pos move = move >>= flip progress pos
indicesOf :: [a] -> [ReifiedTraversal' [a] a]
indicesOf l = [ Traversal $ ix i | i <- [0..length l - 1] ]
indices2Of:: [[a]] -> [ReifiedTraversal' [[a]] a]
indices2Of ls = [ Traversal $ i.j | Traversal i <- indicesOf ls, let Just l = ls ^? i, Traversal j <- indicesOf l]
add2or4 :: Position -> RVar Position
add2or4 pos = do
xy <- randomElement [ xy | Traversal xy <- indices2Of pos, pos ^? xy == Just 0 ]
a <- categorical [(1-prob4, 2), (prob4, 4) ]
return $ pos & xy .~ a
play :: Position -> IO ()
play pos = do
c <- getChar
case go pos $ lookup c [('D',left),('C',right),('A',up),('B',down)] of
Nothing -> play pos
Just pos1 -> do
pos2 <- sample $ add2or4 pos1
draw pos2
when (win pos2 && not (win pos)) $ putStrLn $ "You win! You may keep going."
if lost pos2 then putStrLn "You lost!"
else play pos2
main :: IO ()
main = do
pos <- sample $ add2or4 $ replicate 4 (replicate 4 0)
draw pos
play pos
colors =
[(0,"\ESC[38;5;234;48;5;250m ")
,(2,"\ESC[38;5;234;48;5;255m 2 ")
,(4,"\ESC[38;5;234;48;5;230m 4 ")
,(8,"\ESC[38;5;15;48;5;208m 8 ")
,(16,"\ESC[38;5;15;48;5;209m 16 ")
,(32,"\ESC[38;5;15;48;5;203m 32 ")
,(64,"\ESC[38;5;15;48;5;9m 64 ")
,(128,"\ESC[38;5;15;48;5;228m 128 ")
,(256,"\ESC[38;5;15;48;5;227m 256 ")
,(512,"\ESC[38;5;15;48;5;226m 512 ")
,(1024,"\ESC[38;5;15;48;5;221m 1024")
,(2048,"\ESC[38;5;15;48;5;220m 2048")
,(4096,"\ESC[38;5;15;48;5;0m 4096")
,(8192,"\ESC[38;5;15;48;5;0m 8192")
,(16384,"\ESC[38;5;15;48;5;0m16384")
,(32768,"\ESC[38;5;15;48;5;0m32768")
,(65536,"\ESC[38;5;15;48;5;0m65536")
,(131072,"\ESC[38;5;15;48;5;90m131072")
]
showTile x = fromJust (lookup x colors) ++ "\ESC[B\^H\^H\^H\^H\^H \ESC[A\ESC[C"
draw :: Position -> IO ()
draw pos = do
setSGR [Reset]
clearScreen
hideCursor
hSetEcho stdin False
hSetBuffering stdin NoBuffering
setSGR [SetConsoleIntensity BoldIntensity]
putStr "\ESC[38;5;234;48;5;248m"
setCursorPosition 0 0
replicateM_ 13 $ putStrLn $ replicate 26 ' '
setCursorPosition 1 1
putStrLn $ intercalate "\n\n\n\ESC[C" $ concatMap showTile `map` pos
1,1792048
8haskell
aei1g
function twentyfour(numbers, input) {
var invalidChars = /[^\d\+\*\/\s-\(\)]/;
var validNums = function(str) {
1,17524 game
10javascript
z3gt2
blocks = {
{"B","O"}; {"X","K"}; {"D","Q"}; {"C","P"};
{"N","A"}; {"G","T"}; {"R","E"}; {"T","G"};
{"Q","D"}; {"F","S"}; {"J","W"}; {"H","U"};
{"V","I"}; {"A","N"}; {"O","B"}; {"E","R"};
{"F","S"}; {"L","Y"}; {"P","C"}; {"Z","M"};
};
function canUse(table, letter)
for i,v in pairs(blocks) do
if (v[1] == letter:upper() or v[2] == letter:upper()) and table[i] then
table[i] = false;
return true;
end
end
return false;
end
function canMake(Word)
local Taken = {};
for i,v in pairs(blocks) do
table.insert(Taken,true);
end
local found = true;
for i = 1,#Word do
if not canUse(Taken,Word:sub(i,i)) then
found = false;
end
end
print(found)
end
1,173ABC problem
1lua
hknj8
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import javax.swing.*;
public class Game2048 extends JPanel {
enum State {
start, won, running, over
}
final Color[] colorTable = {
new Color(0x701710), new Color(0xFFE4C3), new Color(0xfff4d3),
new Color(0xffdac3), new Color(0xe7b08e), new Color(0xe7bf8e),
new Color(0xffc4c3), new Color(0xE7948e), new Color(0xbe7e56),
new Color(0xbe5e56), new Color(0x9c3931), new Color(0x701710)};
final static int target = 2048;
static int highest;
static int score;
private Color gridColor = new Color(0xBBADA0);
private Color emptyColor = new Color(0xCDC1B4);
private Color startColor = new Color(0xFFEBCD);
private Random rand = new Random();
private Tile[][] tiles;
private int side = 4;
private State gamestate = State.start;
private boolean checkingAvailableMoves;
public Game2048() {
setPreferredSize(new Dimension(900, 700));
setBackground(new Color(0xFAF8EF));
setFont(new Font("SansSerif", Font.BOLD, 48));
setFocusable(true);
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
startGame();
repaint();
}
});
addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_UP:
moveUp();
break;
case KeyEvent.VK_DOWN:
moveDown();
break;
case KeyEvent.VK_LEFT:
moveLeft();
break;
case KeyEvent.VK_RIGHT:
moveRight();
break;
}
repaint();
}
});
}
@Override
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
drawGrid(g);
}
void startGame() {
if (gamestate != State.running) {
score = 0;
highest = 0;
gamestate = State.running;
tiles = new Tile[side][side];
addRandomTile();
addRandomTile();
}
}
void drawGrid(Graphics2D g) {
g.setColor(gridColor);
g.fillRoundRect(200, 100, 499, 499, 15, 15);
if (gamestate == State.running) {
for (int r = 0; r < side; r++) {
for (int c = 0; c < side; c++) {
if (tiles[r][c] == null) {
g.setColor(emptyColor);
g.fillRoundRect(215 + c * 121, 115 + r * 121, 106, 106, 7, 7);
} else {
drawTile(g, r, c);
}
}
}
} else {
g.setColor(startColor);
g.fillRoundRect(215, 115, 469, 469, 7, 7);
g.setColor(gridColor.darker());
g.setFont(new Font("SansSerif", Font.BOLD, 128));
g.drawString("2048", 310, 270);
g.setFont(new Font("SansSerif", Font.BOLD, 20));
if (gamestate == State.won) {
g.drawString("you made it!", 390, 350);
} else if (gamestate == State.over)
g.drawString("game over", 400, 350);
g.setColor(gridColor);
g.drawString("click to start a new game", 330, 470);
g.drawString("(use arrow keys to move tiles)", 310, 530);
}
}
void drawTile(Graphics2D g, int r, int c) {
int value = tiles[r][c].getValue();
g.setColor(colorTable[(int) (Math.log(value) / Math.log(2)) + 1]);
g.fillRoundRect(215 + c * 121, 115 + r * 121, 106, 106, 7, 7);
String s = String.valueOf(value);
g.setColor(value < 128 ? colorTable[0] : colorTable[1]);
FontMetrics fm = g.getFontMetrics();
int asc = fm.getAscent();
int dec = fm.getDescent();
int x = 215 + c * 121 + (106 - fm.stringWidth(s)) / 2;
int y = 115 + r * 121 + (asc + (106 - (asc + dec)) / 2);
g.drawString(s, x, y);
}
private void addRandomTile() {
int pos = rand.nextInt(side * side);
int row, col;
do {
pos = (pos + 1) % (side * side);
row = pos / side;
col = pos % side;
} while (tiles[row][col] != null);
int val = rand.nextInt(10) == 0 ? 4 : 2;
tiles[row][col] = new Tile(val);
}
private boolean move(int countDownFrom, int yIncr, int xIncr) {
boolean moved = false;
for (int i = 0; i < side * side; i++) {
int j = Math.abs(countDownFrom - i);
int r = j / side;
int c = j % side;
if (tiles[r][c] == null)
continue;
int nextR = r + yIncr;
int nextC = c + xIncr;
while (nextR >= 0 && nextR < side && nextC >= 0 && nextC < side) {
Tile next = tiles[nextR][nextC];
Tile curr = tiles[r][c];
if (next == null) {
if (checkingAvailableMoves)
return true;
tiles[nextR][nextC] = curr;
tiles[r][c] = null;
r = nextR;
c = nextC;
nextR += yIncr;
nextC += xIncr;
moved = true;
} else if (next.canMergeWith(curr)) {
if (checkingAvailableMoves)
return true;
int value = next.mergeWith(curr);
if (value > highest)
highest = value;
score += value;
tiles[r][c] = null;
moved = true;
break;
} else
break;
}
}
if (moved) {
if (highest < target) {
clearMerged();
addRandomTile();
if (!movesAvailable()) {
gamestate = State.over;
}
} else if (highest == target)
gamestate = State.won;
}
return moved;
}
boolean moveUp() {
return move(0, -1, 0);
}
boolean moveDown() {
return move(side * side - 1, 1, 0);
}
boolean moveLeft() {
return move(0, 0, -1);
}
boolean moveRight() {
return move(side * side - 1, 0, 1);
}
void clearMerged() {
for (Tile[] row : tiles)
for (Tile tile : row)
if (tile != null)
tile.setMerged(false);
}
boolean movesAvailable() {
checkingAvailableMoves = true;
boolean hasMoves = moveUp() || moveDown() || moveLeft() || moveRight();
checkingAvailableMoves = false;
return hasMoves;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("2048");
f.setResizable(true);
f.add(new Game2048(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}
class Tile {
private boolean merged;
private int value;
Tile(int val) {
value = val;
}
int getValue() {
return value;
}
void setMerged(boolean m) {
merged = m;
}
boolean canMergeWith(Tile other) {
return !merged && other != null && !other.merged && value == other.getValue();
}
int mergeWith(Tile other) {
if (canMergeWith(other)) {
value *= 2;
merged = true;
return value;
}
return -1;
}
}
1,1792048
9java
jhx7c
import java.util.Random
import java.util.Scanner
import java.util.Stack
internal object Game24 {
fun run() {
val r = Random()
val digits = IntArray(4).map { r.nextInt(9) + 1 }
println("Make 24 using these digits: $digits")
print("> ")
val s = Stack<Float>()
var total = 0L
val cin = Scanner(System.`in`)
for (c in cin.nextLine()) {
when (c) {
in '0'..'9' -> {
val d = c - '0'
total += (1 shl (d * 5)).toLong()
s += d.toFloat()
}
else ->
if ("+/-*".indexOf(c) != -1) {
s += c.applyOperator(s.pop(), s.pop())
}
}
}
when {
tally(digits) != total ->
print("Not the same digits. ")
s.peek().compareTo(target) == 0 ->
println("Correct!")
else ->
print("Not correct.")
}
}
private fun Char.applyOperator(a: Float, b: Float) = when (this) {
'+' -> a + b
'-' -> b - a
'*' -> a * b
'/' -> b / a
else -> Float.NaN
}
private fun tally(a: List<Int>): Long = a.reduce({ t, i -> t + (1 shl (i * 5)) }).toLong()
private val target = 24
}
fun main(args: Array<String>) = Game24.run()
1,17524 game
11kotlin
qsyx1
val playOptimal: () -> Boolean = {
val secrets = (0..99).toMutableList()
var ret = true
secrets.shuffle()
prisoner@ for(i in 0 until 100){
var prev = i
draw@ for(j in 0 until 50){
if (secrets[prev] == i) continue@prisoner
prev = secrets[prev]
}
ret = false
break@prisoner
}
ret
}
val playRandom: ()->Boolean = {
var ret = true
val secrets = (0..99).toMutableList()
secrets.shuffle()
prisoner@ for(i in 0 until 100){
val opened = mutableListOf<Int>()
val genNum : () ->Int = {
var r = (0..99).random()
while (opened.contains(r)) {
r = (0..99).random()
}
r
}
for(j in 0 until 50){
val draw = genNum()
if ( secrets[draw] == i) continue@prisoner
opened.add(draw)
}
ret = false
break@prisoner
}
ret
}
fun exec(n:Int, play:()->Boolean):Double{
var succ = 0
for (i in IntRange(0, n-1)){
succ += if(play()) 1 else 0
}
return (succ*100.0)/n
}
fun main() {
val N = 100_000
println("# of executions: $N")
println("Optimal play success rate: ${exec(N, playOptimal)}%")
println("Random play success rate: ${exec(N, playRandom)}%")
}
1,176100 prisoners
11kotlin
xq3ws
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.