Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You can store the last known value as you iterate, and only decrease the points when the value changed. The array is sorted, so the equal elements will be adjacent.</p> <pre><code>/** * award average of points to a number of elements. * @param arrayref $trainergross - reference to the original array * @param int $award - total points to award * @param int $start_index - which element to start with? * @param int $count - how many elements should be awarded points? * @return void */ function award_points(&amp;$trainergross, $award, $start_index, $count=1) { if(!$count || $award&lt;1) return; // if noone is waiting for the award, OR there is no award, bail out // $awards holds total award, and we need to $avgPoints = $award / $count; // award points to $count previous elements for($j = $start_index; $j &lt; $start_index + $count; ++$j) { // in case points key was not initialized, php will issue a notice. if(!isset($trainergross[$j]['points'])) $trainergross[$j]['points'] = 0; $trainergross[$j]['points'] += $avgPoints; } } /** * This is increased on purpose * the first check will be &lt;some number&gt; vs null, which will result in -=2. * this is to eliminate additional !== null test inside the loop. */ $maxpoints = 42; // This will be used to store number of consecutive elements $count = 0; // This will be used to store total points to award $award = 0; // Here we will store last gross value $last = null; for($i = 0; $i &lt; count($trainergross); $i++) { $maxpoints -= 2; // if gross has not changed, just count consecutive elements and continue if($last == $trainergross[$i]['gross']) { $award += $maxpoints; $count++; continue; } // store gross value $last = $trainergross[$i]['gross']; // now really distribute the points we've gathered in award by now award_points($trainergross, $award, $i - $count, $count); // reset count back to 1 (there is only 1 "consecutive" element now) $count = 1; // next element will get this award $award = $maxpoints; } // now we have to award points again // the loop ended, but $count of elements are still awaiting points... award_points($trainergross, $award, $i - $count, $count); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload