DEV Community

Discussion on: Daily Challenge #5 - Ten Minute Walk

Collapse
 
martyhimmel profile image
Martin Himmel

PHP

function go_for_a_walk(int $distance) {
    if ($distance % 2 == 1) {
        throw new Exception("There's no place like home. Unfortunately, you won't return home with an odd number of steps.");
    }

    $steps = [];
    $directions = ['n', 'e', 's', 'w'];
    while ($distance > 0) {
        $index = array_rand($directions);
        $steps[] = $directions[$index];
        $steps[] = $directions[($index + 2) % 4];
        $distance -= 2;
    }
    shuffle($steps);
    return $steps;
}

echo implode(', ', go_for_a_walk(10)) . PHP_EOL;