Page 1 of 1
Anyone know what this function doing ?
Posted: Mon Aug 22, 2011 11:54 pm
by kcp88
Anyone know what this function doing ? Can explain to me ?
Code: Select all
function countMaxOcc($tpp, $s){
$t=0;$c=0;$p=true;
foreach($tpp as $n){
if($n==$s){
$c=($p)?$c+1:1;
$p=true;
}else{
$t=($c>$t)?$c:$t;
$p=false;
}
}
return $t;
}
Re: Anyone know what this function doing ?
Posted: Tue Aug 23, 2011 10:47 am
by social_experiment
Code: Select all
<?php
function countMaxOcc($tpp, $s){
// set variables
$t=0;$c=0;$p=true;
// $tpp should be an array, foreach loops through each
// value in an array
foreach($tpp as $n){
// if the value $n is equal to the value of $s
if($n==$s){
// if $p is true, $c is incremented by 1, if $p is false, $c = 1
$c=($p)?$c+1:1;
// set $p to true
$p=true;
// if $n is not equal to $s
}else{
// if $c is greater than $t, $t is equal to the value of $c, if not, $t's value
// is equal to the value in $t.
$t=($c>$t)?$c:$t;
// $p is set to false
$p=false;
}
}
// return the value of $t
return $t;
}
?>
Re: Anyone know what this function doing ?
Posted: Tue Aug 23, 2011 11:42 am
by Jonah Bron
In English, it counts the number of times a given value occurs consecutively in an array.
Re: Anyone know what this function doing ?
Posted: Fri Aug 26, 2011 12:20 am
by Jonah Bron
And it could be better written as this:
Code: Select all
function countMaxOcc($list, $value) {
$finalMax = 0;
$currentMax = 0;
foreach ($list as $listItem) {
if ($listItem == $value) {
$finalMax = max($finalMax, ++$currentMax);
} else {
$currentMax = 0;
}
return $finalMax;
}
Re: Anyone know what this function doing ?
Posted: Fri Aug 26, 2011 8:10 am
by social_experiment
Maybe add a check to see if $list is an array?
Re: Anyone know what this function doing ?
Posted: Fri Aug 26, 2011 2:31 pm
by Benjamin
Here's another way:
Code: Select all
function countMaxOcc($array, $value) {
$n = array_count_values($array);
return array_key_exists($value, $n) ? $n[$value] : 0;
}
Re: Anyone know what this function doing ?
Posted: Fri Aug 26, 2011 2:49 pm
by Jonah Bron
I should have seen that one coming

Re: Anyone know what this function doing ?
Posted: Fri Aug 26, 2011 3:10 pm
by Benjamin
Yeah.. I hear that.

Re: Anyone know what this function doing ?
Posted: Fri Aug 26, 2011 10:46 pm
by Benjamin
Actually, what I wrote won't work. I thought it was counting the total occurrences, when in fact it's counting consecutive occurrences.
Re: Anyone know what this function doing ?
Posted: Sat Aug 27, 2011 11:34 am
by Jonah Bron
Yeah, that's what it's supposed to do. You're so good, you wrote the right thing and didn't even know it
