1

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
4

3 Answers 3

2

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)
}
Sign up to request clarification or add additional context in comments.

Comments

0

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
)

Comments

0

New version:

$result = array_replace(array_fill(0, $m+1, 0),
                        array_slice(array_count_values($A), 0, $m-1, true));
  • Replace an array of zeros with length $m+1 with a count of the values of $A up to length $m.

Original version:

$result = array_fill(0, $m+1, 0);

foreach($A as $i) {
    if(isset($result[$i])) {
        $result[$i]++;
    }
}
  • Create a $result array of zeros with length $m+1
  • Loop array $A and increment $result index of $A value

Obviously if you want a function just wrap code in:

function counting($A, $m) {
    //code
    return $result;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.