Created
December 2, 2021 08:53
-
-
Save MatthieuScarset/85aea566b1ff85868f85e8375de40fbe to your computer and use it in GitHub Desktop.
try to solve GalacticDTH challenge
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
* Complete the 'getMinClicks' function below. | |
* | |
* The function is expected to return an INTEGER. | |
* The function accepts following parameters: | |
* 1. INTEGER lowest_channel | |
* 2. INTEGER highest_channel | |
* 3. INTEGER_ARRAY blocked_channels | |
* 4. INTEGER_ARRAY channel_sequence | |
*/ | |
function getMinClicks($lowest_channel, $highest_channel, $blocked_channels, $channel_sequence): int { | |
$total = 0; | |
$current = $lowest_channel; | |
$before = 0; | |
foreach ($channel_sequence as $target) { | |
$same = $target == $current ? 0 : null; | |
$previous = $target == $before ? 1 : null; | |
$manually = count(str_split($target)); | |
$forward = 0; | |
$i = $current; | |
do { | |
$i++; | |
if ($i > $highest_channel) {$i = $lowest_channel;} | |
if ($i < $lowest_channel) {$i = $highest_channel;} | |
if (!in_array($i, $blocked_channels)) { | |
$forward++; | |
} | |
} while ($i !== $target); | |
$backward = 0; | |
$i = $current; | |
do { | |
$i--; | |
if ($i > $highest_channel) {$i = $lowest_channel;} | |
if ($i < $lowest_channel) {$i = $highest_channel;} | |
if (!in_array($i, $blocked_channels)) { | |
$backward++; | |
} | |
} while ($i !== $target); | |
$values = [$same, $previous, $manually, $forward, $backward]; | |
$values = array_filter($values); | |
$total += min($values); | |
$before = $current; | |
$current = $target; | |
} | |
return $total; | |
} | |
$fptr = fopen(getenv("OUTPUT_PATH"), "w"); | |
$first_multiple_input = explode(' ', rtrim(fgets(STDIN))); | |
$lowest_channel = intval($first_multiple_input[0]); | |
$highest_channel = intval($first_multiple_input[1]); | |
$blocked_channels_count = intval(trim(fgets(STDIN))); | |
$blocked_channels_temp = rtrim(fgets(STDIN)); | |
$blocked_channels = array_map('intval', preg_split('/ /', $blocked_channels_temp, -1, PREG_SPLIT_NO_EMPTY)); | |
$channel_sequence_count = intval(trim(fgets(STDIN))); | |
$channel_sequence_temp = rtrim(fgets(STDIN)); | |
$channel_sequence = array_map('intval', preg_split('/ /', $channel_sequence_temp, -1, PREG_SPLIT_NO_EMPTY)); | |
$min_clicks = getMinClicks($lowest_channel, $highest_channel, $blocked_channels, $channel_sequence); | |
fwrite($fptr, $min_clicks . "\n"); | |
fclose($fptr); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment