Dynamic Array
HackerRank 问题: Dynamic Array
Categories:
Question
Answer
<?php
/*
* Complete the 'dynamicArray' function below.
*
* The function is expected to return an INTEGER_ARRAY.
* The function accepts following parameters:
* 1. INTEGER n
* 2. 2D_INTEGER_ARRAY queries
*/
function dynamicArray($number_of_empty_array, $queries_list) {
// create number of empty array
$sequences_list = [];
for ($i = 0; $i < $number_of_empty_array; $i++) {
$sequences_list[] = [];
}
$answer = [];
$last_answer = 0;
// search query
foreach ($queries_list as $query) {
// get query variable
list($action, $index, $value) = $query;
// find next index
$next_index = ($index ^ $last_answer) % $number_of_empty_array;
if ($action == 1) {
// action = 1: add value to next index
$sequences_list[$next_index][] = $value;
} else {
// action != 1
// get next index sequence
$temp = $sequences_list[$next_index];
$temp_count = count($temp);
// get sequence answer
$last_answer = $sequences_list[$next_index][$value % $temp_count];
$answer[] = $last_answer;
}
}
return $answer;
}
$fptr = fopen(getenv("OUTPUT_PATH"), "w");
$first_multiple_input = explode(' ', rtrim(fgets(STDIN)));
$n = intval($first_multiple_input[0]);
$q = intval($first_multiple_input[1]);
$queries = array();
for ($i = 0; $i < $q; $i++) {
$queries_temp = rtrim(fgets(STDIN));
$queries[] = array_map('intval', preg_split('/ /', $queries_temp, -1, PREG_SPLIT_NO_EMPTY));
}
$result = dynamicArray($n, $queries);
fwrite($fptr, implode("\n", $result) . "\n");
fclose($fptr);