-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCircular Array Rotation.php
46 lines (33 loc) · 1.27 KB
/
Circular Array Rotation.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<?php
/*
QUESTION:
John Watson knows of an operation called a right circular rotation on an array of integers. One rotation operation moves the last array element to the first position and shifts all remaining elements right one. To test Sherlock's abilities, Watson provides Sherlock with an array of integers. Sherlock is to perform the rotation operation a number of times then determine the value of the element at a given position.
For each array, perform a number of right circular rotations and return the values of the elements at the given indices.
Example
a = [3, 4, 5]
k = 2
queries = [1, 2]
Here k is the number of rotations on a, and queries holds the list of indices to report. First we perform the two rotations:
[3, 4, 5] -> [5, 3, 4] -> [4, 5, 3]
Now return the values from the zero-based indices 1 and 2 as indicated in the queries array.
a[1] = 5
a[2] = 3
*/
// Solution
function circularArrayRotation($a, $k, $queries) {
// Write your code here
$res = [];
$temp = [];
for($i = 0; $i < count($a); $i++){
$temp[($i + $k) % count($a)] = $a[$i];
}
foreach($queries as $value){
array_push($res, $temp[$value]);
}
return $res;
}
$a = [3, 4, 5];
$k = 2;
$queries = [1, 2];
print_r(circularArrayRotation($a, $k, $queries));
?>