-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOrganise_duplicate_numbers_in_list.php
More file actions
35 lines (30 loc) · 1.3 KB
/
Organise_duplicate_numbers_in_list.php
File metadata and controls
35 lines (30 loc) · 1.3 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
<?php
/**
* Sam is an avid collector of numbers. Every time he finds a new number he throws it on the top of his number-pile.
* Help Sam organise his collection so he can take it to the International Number Collectors Conference in Cologne.
* Given an array of numbers, your function should return an array of arrays, where each subarray contains all the duplicates of a particular number.
* Subarrays should be in the same order as the first occurence of the number they contain:
*
* group([3, 2, 6, 2, 1, 3]) >>> [[3, 3], [2, 2], [6], [1]]
*
* Assume the input is always going to be an array of numbers. If the input is an empty array, an empty array should be returned.
*/
function group(array $numeros) {
$resultado = [];
//Mientras haya elementos en el array
while (!empty($numeros)) {
//Extraer el primer numero y crear el subarray
$numeroActual = array_shift($numeros);
$numerosAux = [$numeroActual];
//Buscar duplicados e incluirlos en el subarray
foreach ($numeros as $indice => $valor) {
if ($numeroActual == $valor) {
$numerosAux[] = $valor;
unset($numeros[$indice]);
}
}
//Añadri el subarray al array resultado.
$resultado[] = $numerosAux;
}
return $resultado;
}