-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathword_value.php
More file actions
48 lines (44 loc) · 1.66 KB
/
word_value.php
File metadata and controls
48 lines (44 loc) · 1.66 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
39
40
41
42
43
44
45
46
47
48
<?php
// 7 kyu - Word values
// Given a string "abc" and assuming that each letter in the string has a value equal to its position in the alphabet, our string will have a value of 1 + 2 + 3 = 6. This means that: a = 1, b = 2, c = 3 ....z = 26.
//
// You will be given a list of strings and your task will be to return the values of the strings as explained above multiplied by the position of that string in the list. For our purpose, position begins with 1.
//
// nameValue ["abc","abc abc"] should return [6,24] because of [ 6 * 1, 12 * 2 ]. Note how spaces are ignored.
//
// "abc" has a value of 6, while "abc abc" has a value of 12. Now, the value at position 1 is multiplied by 1 while the value at position 2 is multiplied by 2.
//
// Input will only contain lowercase characters and spaces.
function word_value(array $a): array {
foreach($a as $key => $val) {
$x = array_reduce(str_split(str_replace(' ', '', $val)), function($carry, $letter) {
return $carry += (ord(strtoupper($letter)) - 64);
});
$result[] = $x * ($key + 1);
}
return $result;
}
// Alternative Solutions:
// function word_value(array $a): array {
// $i=1;
// foreach($a as $b){
// $arr = str_split($b);
// $nb=0;
// foreach($arr as $c){
// if(ord($c)>=97) $nb += ord($c)-96;
// }
// $sort[]=$nb*$i;
// $i++;
// }
// return $sort;
// }
// function word_value(array $a): array {
// foreach($a as $key => $str) {
// foreach(str_split(str_replace(' ', '', $str)) as $char) {
// $res[$key][] = array_search($char, range('a', 'z')) + 1;
// }
// $res[$key] = array_sum($res[$key]) * ($key + 1);
// }
// return $res;
// }
?>