-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathscramble.php
More file actions
38 lines (34 loc) · 1.16 KB
/
scramble.php
File metadata and controls
38 lines (34 loc) · 1.16 KB
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
<?php
// 7 kyu - String Scramble
// Given a string and an array of index numbers, return the characters of the string rearranged to be in the order specified by the accompanying array.
//
// Ex:
//
// scramble('abcd', [0,3,1,2]) -> 'acdb'
//
// The string that you will be returning back will have: 'a' at index 0, 'b' at index 3, 'c' at index 1, 'd' at index 2, because the order of those characters maps to their corisponding numbers in the index array.
//
// In other words, put the first character in the string at the index described by the first element of the array
//
// You can assume that you will be given a string and array of equal length and both containing valid characters (A-Z, a-z, or 0-9).
function scramble($str,$arr){
foreach($arr as $key => $val) {
$result[$val] = $str[$key];
}
ksort($result);
return implode($result);
}
// Alternative Solutions:
// function scramble($str, $arr) {
// $newStr = $str;
// for ($i = 0; $i < strlen($str); $i++) {
// $newStr[$arr[$i]] = $str[$i];
// }
// return $newStr;
// }
// function scramble($str,$arr){
// $a = array_combine($arr,str_split($str));
// ksort($a);
// return implode('', $a);
// }
?>