This question was asked by a Abdullah on stackoverflow. So i thought of giving him a better solution.
As you can see from the above image. For a range of number, each number must be added and divided by the length to get the average and then check if the average is greater than or equal to 7.5, he need to set the is heavy value to yes if not No.
Here is the solution i gave him.
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 36 37 38 39 40 41 42 |
<?php $results = heavyDecC(2685, 5875); // Display results like this foreach ($results as $id){ echo "--------------------------<br/>"; foreach($id as $key => $val){ echo $key . " - " . $val . "<br />"; } } function heavyDecC ($x,$y) { for($i=$x; $i<=$y; $i++){ $num = $x; $isHeavy = "No"; $num_length = strlen((string)$num); $array = array_map('intval', str_split($num)); $sum = array_sum($array); $average = ($sum / $num_length); if($average > 7){ $isHeavy = "Yes"; }else { $isHeavy = "No"; } $newdata = array ( 'Number' => $num, 'average' => $average, 'is_heavy' => $isHeavy ); $md_array[$i]= $newdata; $x++; } return $md_array; } ?> |
Results looks like this.
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 |
Number - 2996 average - 6.5 is_heavy - No -------------------------- Number - 2997 average - 6.75 is_heavy - No -------------------------- Number - 2998 average - 7 is_heavy - No -------------------------- Number - 2999 average - 7.25 is_heavy - Yes -------------------------- Number - 3000 average - 0.75 is_heavy - No -------------------------- Number - 3001 average - 1 is_heavy - No -------------------------- Number - 3002 average - 1.25 is_heavy - No |
Hope this will be helpfull. Tnx. 🙂