Skip to content

Instantly share code, notes, and snippets.

@richardpq
Last active August 29, 2015 14:08
Show Gist options
  • Save richardpq/6e7b47e44671b53f0896 to your computer and use it in GitHub Desktop.
Save richardpq/6e7b47e44671b53f0896 to your computer and use it in GitHub Desktop.
This is a very basic algorithm for a "magic trick" where you choose the same letter 3 times (in your mind) from a set of different letters distributed in 3 columns and the system will guess which one you choose.
<?php
$letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U'];
shuffle($letters);
$count = 1;
$message = "";
do {
printLetters($letters);
echo "\n";
if ($count === 1) {
$message = "Select one letter (in your mind) and type the column number where it is (1,2,3): ";
} elseif ($count === 2) {
$message = "Look for the same letter and type the column number where it is now (1,2,3): ";
} else {
$message = "Look for the same letter again (last time, I promise) and type the column number where it is now (1,2,3): ";
}
echo $message;
$input = fopen ("php://stdin","r");
$value = (int)fgets($input) -1;
while (!valid($value)) {
echo "Please enter a valid colum number (1,2,3): ";
$input = fopen ("php://stdin","r");
$value = (int)fgets($input) -1;
echo "\n";
}
echo "\n";
$letters = reArrange($letters, $value);
$count++;
} while ($count <= 3);
echo "\n";
echo "\n";
echo "\n*** The letter you choose is: $letters[10] ***\n\n";
//Display in a 'pretty' format the letters in 3 columns
function printLetters(array $arrayLetters)
{
echo "\tColum 1\t\tColum 2\t\tColum 3\n";
echo "-------------------------------------------------\n";
for ($i = 0; $i < count($arrayLetters); $i++) {
echo "\t ".$arrayLetters[$i]."\t";
if (($i+1) % 3 === 0) {
echo "\n";
}
}
}
/*
Arrange the cards, in order to the 'trick' works,
the column picked by the user should be moved to
the middle (always)
*/
function reArrange(array $arrayToArrange, $index)
{
$reArranged = array();
$cols = array();
for($i = 0; $i < 7; $i++) {
for ($j = 0; $j < 3; $j++) {
$cols[$j][$i] = array_shift($arrayToArrange);
}
}
$reArranged[1] = $cols[$index];
unset($cols[$index]);
$reArranged[0] = array_shift($cols);
$reArranged[2] = array_shift($cols);
return array_merge($reArranged[0], $reArranged[1], $reArranged[2]);
}
//Validate if the value the user typed is a number and in a valid range
function valid($value)
{
if (!in_array($value, array(0,1,2), true)) {
return false;
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment