-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution.php
More file actions
105 lines (95 loc) · 2.47 KB
/
solution.php
File metadata and controls
105 lines (95 loc) · 2.47 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
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
101
102
103
104
105
<?php
/*
# Author Felixander Loetama
# Professional Email: floetama@gmail.com
# Coding Challenge - Count Chains
## Task
- Count the number of horizontal and vertical chains in a square grid modelling a Bejeweled board.
- A chain consists of 3 or more consecutive items that are the same. The digits 0-9 are used to represent items.
- Your solution will be tested as follows:
```
// Result should be 4 for this board
$board = [
[0,3,3,3],
[0,0,0,2],
[0,1,4,2],
[0,9,8,2],
];
$result = $countChains($board);
```
- Restrictions:
+ Only `while` loops are allowed.
+ Only one-dimensional arrays are allowed, except for the argument.
+ No using of in-built array functions except for `count()`.
*/
$board = [
[0,3,3,2,1,2,1],
[0,0,0,2,1,1,1],
[0,1,4,2,1,1,1],
[3,9,8,2,1,1,2],
[3,3,3,3,3,3,2],
];
$result = countChains($board);
echo $result;
function countChains($data = "") {
$processCount = array();
$processCount[] = countHorizontal($data);
$processCount[] = countVertical($data);
return max($processCount);
}
function countVertical($data = "") {
if(empty($data)) return 0;
else {
$j = 0;
$no_occurrence = array();
while($j < count($data[0])) {
$i = 0;
$tempData = array();
$totalArray = array();
while($i < count($data)) {
$tempData[] = $data[$i][$j];
$totalArray[] = getTotal($tempData);
$i++;
}
$total_occurrence[] = max($totalArray);
$j++;
}
return max($total_occurrence);
}
}
function countHorizontal($data = "") {
if(empty($data)) return 0;
else {
$i = 0;
$total_occurrence = array();
while($i < count($data)) {
$j = 0;
$tempData = array();
$totalArray = array();
while($j < count($data[$i])) {
$tempData[] = $data[$i][$j];
$totalArray[] = getTotal($tempData);
$j++;
}
$total_occurrence[] = max($totalArray);
$i++;
}
return max($total_occurrence);
}
}
function getTotal($data = "") {
$i = 0;
$unique = array();
$counter = 0;
while($i < count($data)) {
$unique[$data[$i]] = 1;
if(count($unique) > 1) {
$counter = 1;
} else {
$counter++;
}
$i++;
}
return $counter;
}
?>