Reputation: 1215
I want to write a function that returns a counter array. That is, given an array of integers $A
, in which the integers are in the range (0...$m)
it should return an array of size $m + 1
in which each index has the number of occurrences of that index number in $A
.
For instance, if:
$A = array(1, 4, 2, 2, 4, 2);
$m = 4;
It should output:
array(0, 1, 3, 0, 2)
I'm wondering if there is a built-in function to do this in PHP.
In python it would look something like:
def counting(A, m):
n = len(A)
count = [0] * (m + 1)
for k in xrange(n):
count[A[k]] += 1
return count
Upvotes: 1
Views: 495
Reputation: 78994
$result = array_replace(array_fill(0, $m+1, 0),
array_slice(array_count_values($A), 0, $m-1, true));
$m+1
with a count of the values of $A
up to length $m
.$result = array_fill(0, $m+1, 0);
foreach($A as $i) {
if(isset($result[$i])) {
$result[$i]++;
}
}
$result
array of zeros with length $m+1
$A
and increment $result
index of $A
valueObviously if you want a function just wrap code in:
function counting($A, $m) {
//code
return $result;
}
Upvotes: 0
Reputation: 3879
Try the below code
function count_array($array,$m){
// count values
$count_values = array_count_values($array);
// loop for $m times
for($i=0;$i<=$m;$i++){
// check if there exits a key in the array
if(array_key_exists($i,$count_values)){
$result_array[$i] = $count_values[$i];
}else{
$result_array[$i] = 0;
}
}
return $result_array;
}
$A = array(1, 4, 2, 2, 4, 2);
$m = 4;
$result = count_array($A,$m);
Out Put:
Array
(
[0] => 0
[1] => 1
[2] => 3
[3] => 0
[4] => 2
)
Upvotes: 0
Reputation: 14921
You can try this:
$a = array(1, 4, 2, 2, 4, 2);
$m = 4;
function counting(Array $a, $m){
// Create our result array
$result = array();
// Make sure m is an integer for version before PHP 7, otherwise return an empty array
if(!is_int($m))
return $result;
// Get the count of each occurence in the array
$counts = array_count_values($a);
// Loop through each number of m
for($i=0; $i<=$m; $i++)
$result[$i] = isset($counts[$i]) ? $counts[$i] : 0;
return $result;
}
The result of var_dump(counting($a, $m))
:
array(5) {
[0]=>
int(0)
[1]=>
int(1)
[2]=>
int(3)
[3]=>
int(0)
[4]=>
int(2)
}
Upvotes: 2