Skip to content

Instantly share code, notes, and snippets.

@kastaneda
Created July 5, 2011 15:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kastaneda/1065091 to your computer and use it in GitHub Desktop.
Save kastaneda/1065091 to your computer and use it in GitHub Desktop.
#!/usr/bin/env php
<?php
// http://twitter.com/#!/Xopus/status/88187651705946112
// "We ask new devs to write program to find equation with 3, 6, 9, 12, 15
// (all) and +, -, *, / (any) which equals 381. Many struggle. Can you do it?"
// Let's rock! This one is for classic PHP4 style. Very dumb.
function permutations($array) {
if (count($array) == 1) {
return array($array);
} else {
$result = array();
foreach ($array as $key => $value) {
$tail = $array;
unset($tail[$key]);
$tail = permutations($tail);
foreach ($tail as $row) {
$result[] = array_merge(array($value), $row);
}
}
return $result;
}
}
function exhaustion($variants, $depth) {
$result = array();
foreach ($variants as $variant) {
if ($depth > 1) {
$tail = exhaustion($variants, $depth-1);
foreach ($tail as $row) {
$result[] = array_merge(array($variant), $row);
}
} else {
$result[] = array($variant);
}
}
return $result;
}
function calculate_RPN($commands) {
$stack = array();
while (count($commands)) {
$cmd = array_shift($commands);
switch (TRUE) {
case is_numeric($cmd):
array_push($stack, $cmd);
break;
case in_array($cmd, array('+', '-', '*', '/')):
if (count($stack) < 2) {
return 'Stack underflow';
}
$b = array_pop($stack);
$a = array_pop($stack);
switch ($cmd) {
case '+':
$c = $a + $b;
break;
case '-':
$c = $a - $b;
break;
case '*':
$c = $a * $b;
break;
case '/':
if (empty($b)) {
return 'Division by zero';
}
$c = $a / $b; break;
}
array_push($stack, $c);
break;
default:
die('Wrong command: '.$cmd);
}
}
return end($stack);
}
$source_numbers = array(3, 6, 9, 12, 15);
$operators = array('+', '-', '*', '/');
$count_row = $count_all = $count_valid = 0;
$commands = exhaustion($operators, count($source_numbers)-1);
foreach ($commands as $command_set) {
echo (++$count_row) . ' of ' . count($commands) . "\r";
$equation_items = array_merge($source_numbers, $command_set);
foreach (permutations($equation_items) as $equation) {
$count_all++;
$result = calculate_RPN($equation);
if (is_numeric($result)) {
$count_valid++;
if ($result == 381) {
echo join(' ', $equation) . ' = ' . $result . "\n";
}
}
}
}
echo "Tested equations: $count_all, valid: $count_valid\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment