PHP Games – Solution to The Impossible Bet

April 8, 2016

/**
 * 100 people put a number in box.
 * every one must find his box within 50 tries
 */
$allTries = 100000;
$usedTries = $allTries;
$players  = 50;
$tries    = 25;
$settings = [];
$people   = [];
for ($i = 0; $i < $players; $i++) {
    $settings[$i]  = $i;
    $people[$i]    = $i;
}

$mostPeopleWon = 0;
while (--$usedTries >= 0) {
    $boxes = $settings;
    shuffle($boxes);

    $peopleWon = 0;
    for ($p = 0; $p < $players; $p++) {

        $personBoxes = $boxes;
        $started     = false;
        $won         = false;
        for ($t = 0; $t < $tries; $t++) {
            if ($started === false) {
                $num     = array_rand($personBoxes, 1);
                $started = true;
            }

            $value = $personBoxes[$num];
            unset($personBoxes[$num]);

            if ($value === $people[$p]) {
                $won = true;
                unset($boxes[$num]);
                break;
            } elseif (!array_key_exists($value, $personBoxes)) {
                $started = false;
            } else {
                $num = $value;
            }
        }

        if($won) {
            $peopleWon++;
        } else {
            break;
        }
    }
    
    if ($peopleWon > $mostPeopleWon) {
        $mostPeopleWon = $peopleWon;
    }
    
    if ($mostPeopleWon >= $players) {
        var_dump('game won in ' . ($allTries - $usedTries) . ' games');
        exit;
    }
}

var_dump('game lost. most people won ' . $mostPeopleWon);

tags: ,
posted in games, php by Ivan Gospodinow

Follow comments via the RSS Feed | Leave a comment | Trackback URL

Leave Your Comment

 
 
Powered by Wordpress and MySQL. Theme by Shlomi Noach, openark.org