-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathbalance.php
More file actions
31 lines (28 loc) · 1.24 KB
/
balance.php
File metadata and controls
31 lines (28 loc) · 1.24 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
<?php
// 6 kyu - Exclamation marks series #17: Put the exclamation marks and question marks to the balance, Are they balanced?
// Description:
// Each exclamation mark weight is 2; Each question mark weight is 3. Put two string left and right to the balance, Are they balanced?
//
// If the left side is more heavy, return "Left"; If the right side is more heavy, return "Right"; If they are balanced, return "Balance".
//
// Examples
// balance("!!","??") == "Right"
// balance("!??","?!!") == "Left"
// balance("!?!!","?!?") == "Left"
// balance("!!???!????","??!!?!!!!!!!") == "Balance"
// Note
// Please don't post issue about difficulty or duplicate.
function balance(string $l, string $r): string {
$l = array_sum(preg_replace(['/[!]/', '/[?]/'], [2,3], str_split($l)));
$r = array_sum(preg_replace(['/[!]/', '/[?]/'], [2,3], str_split($r)));
return $l === $r ? 'Balance' : ($l > $r ? 'Left' : 'Right');
}
// Alternative Solution:
// function balance(string $l, string $r): string {
// $a = substr_count($l, "!")*2+substr_count($l, "?")*3;
// $b = substr_count($r, "!")*2+substr_count($r, "?")*3;
// if ($a == $b) return "Balance"; elseif ($a < $b) return "Right"; else return "Left";
// }
$answer = balance("!!", "??");
print_r("$answer \n");
?>