Reputation: 5931
I can't remember what this is called in math, it's not powers though. I'm validating a consecutive order of numbers. They always start at 1 and can go to 3. I really have 3 conditions only.
So my solution was:
$sum = array_sum($group);
count: 1 = (Result) 1
count: 2 = (Result) 3 (1 + 2)
count: 3 = (Result) 6 (1 + 2 + 3)
However, I would like to trim the fat of these 3 if statements into something simpler, can you help me with that math algorithm?
$winnerCount = [
[1, 3]
];
foreach ($winnerCount as $_key => $_group)
{
$winnerTotal = count($_group);
$sum = array_sum($winnerCount[$_key]);
if ($winnerTotal == 1 && $sum != 1) {
$error = true;
}
if ($winnerTotal == 2 && $sum != 3) {
$error = true;
}
if ($winnerTotal == 3 && $sum != 6) {
$error = true;
}
echo $sum;
}
I do reckon I need some coffee this fine afternoon.
I suppose I could do something kinda like this:
$result = [
1 => 1,
2 => 3,
3 => 6
];
if ($winnerTotal != $result[$winnerTotal]) {
$error = true
}
Upvotes: 0
Views: 113
Reputation: 905
formula : n = n(n+1)/2
therefore you could try the followong in your loop :
if($winnerTotal != $winnerTotal ($winnerTotal + 1 ) / 2){
$error = true;
}
Upvotes: 2
Reputation: 9109
The nth triangular number is given by the formula
g(n) = n(n+1)/2
Upvotes: 2
Reputation: 4607
You can use a loop like this :
function sumNum($num){
$sum = 0 ;
for($i=1;$i<=$num;$i++){
$sum += $i;
}
return $sum;
}
$sum = sumNum($count);
OR most simple way :
$sum = ($count*($count+1))/2;
Upvotes: 1