-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathben.php
100 lines (92 loc) · 2.43 KB
/
ben.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
<?php
/* Read input from STDIN. Print your output to STDOUT*/
$fp = fopen('php://stdin', 'r');
//Write code here
$values = $weaponRequired = [];
$i = 0;
while($line = fgets($fp)){
if(empty($values)){
$values = explode(" ", $line);
$level = $values[0];
$weapon = $values[1];
}else{
$line1 = trim($line);
if($weapon == strlen($line1)){
if(count($weaponRequired) < $level){
$weaponRequired[$i] = $line;
$i++;
if(count($weaponRequired) == $level){
break;
}
}else{
break;
}
}else{
break;
}
}
}
fclose($fp);
sort($weaponRequired);
$arr = [];
$totalCoins = [];
$sortedArray = sortArray($weaponRequired);
//echo "sorted - "; print_r($sortedArray);
$allCoins = calculateCoin($sortedArray, $totalCoins);
//echo "coins - "; print_r($allCoins);
$output = array_sum($allCoins);
$output = (int)$output;
fwrite(STDOUT, $output);
function sortArray($givenArray){
//echo "given Arr -"; print_r($givenArray);
$seconArr = [];
foreach($givenArray as $key => $data){
$lastpos = 0;
$positions = [];
$level = [];
while(($lastpos = strpos($data, '1', $lastpos)) !== false){
$positions [] = $lastpos;
$lastpos = $lastpos + strlen(1);
}
$level['ones'] = count($positions);
$level['position'] = implode(',',$positions);
$level['number'] = $data;
array_push($seconArr, $level);
}
usort($seconArr, function ($a, $b){
return $a['ones'] - $b['ones'];
});
return $seconArr;
}
function calculateCoin($array, $totalCoins){
//echo "cal Arr - "; print_r($array);
REPEATE:
if(isset($array[0])){
if($array[0]['ones'] > 0){
$level = $array[0];
$coins = $level['ones'] * $level['ones'];
$firstLevelPositions = explode(',', $level['position']);
array_push($totalCoins, $coins);
//echo "before "; print_r($array);
array_shift($array);
//echo "after "; print_r($array);
$newArray = [];
foreach($array as $newLevel){
$positions = explode(',', $newLevel['position']);
foreach($firstLevelPositions as $firstLevelPosition){
if(in_array($firstLevelPosition, $positions)){
$newLevel['number'] = substr_replace($newLevel['number'], 0, $firstLevelPosition, 1);
}
}
array_push($newArray, $newLevel['number']);
}
$secArray = sortArray($newArray);
return calculateCoin($secArray, $totalCoins);
}else{
array_shift($array);
goto REPEATE;
}
}else{
return $totalCoins;
}
}