Jetpack_Constrained_Array_Rounding

Lets you round the numeric elements of an array to integers while preserving their sum.

Defined (1)

The class is defined in the following location(s).

/modules/tiled-gallery/math/class-constrained-array-rounding.php  
  1. class Jetpack_Constrained_Array_Rounding { 
  2. public static function get_rounded_constrained_array( $bound_array, $sum = false ) { 
  3. // Convert associative arrays before working with them and convert them back before returning the values 
  4. $keys = array_keys( $bound_array ); 
  5. $bound_array = array_values( $bound_array ); 
  6.  
  7. $bound_array_int = self::get_int_floor_array( $bound_array ); 
  8.  
  9. $lower_sum = array_sum( wp_list_pluck( $bound_array_int, 'floor' ) ); 
  10. if ( ! $sum || ( $sum < $lower_sum ) ) { 
  11. // If value of sum is not supplied or is invalid, calculate the sum that the returned array is constrained to match 
  12. $sum = array_sum( $bound_array ); 
  13. $diff_sum = $sum - $lower_sum; 
  14.  
  15. self::adjust_constrained_array( $bound_array_int, $diff_sum ); 
  16.  
  17. $bound_array_fin = wp_list_pluck( $bound_array_int, 'floor' ); 
  18. return array_combine( $keys, $bound_array_fin ); 
  19.  
  20. private static function get_int_floor_array( $bound_array ) { 
  21. $bound_array_int_floor = array(); 
  22. foreach ( $bound_array as $i => $value ) { 
  23. $bound_array_int_floor[$i] = array( 
  24. 'floor' => (int) floor( $value ),  
  25. 'fraction' => $value - floor( $value ),  
  26. 'index' => $i,  
  27. ); 
  28.  
  29. return $bound_array_int_floor; 
  30.  
  31. private static function adjust_constrained_array( &$bound_array_int, $adjustment ) { 
  32. usort( $bound_array_int, array( 'self', 'cmp_desc_fraction' ) ); 
  33.  
  34. $start = 0; 
  35. $end = $adjustment - 1; 
  36. $length = count( $bound_array_int ); 
  37.  
  38. for ( $i = $start; $i <= $end; $i++ ) { 
  39. $bound_array_int[ $i % $length ]['floor']++; 
  40.  
  41. usort( $bound_array_int, array( 'self', 'cmp_asc_index' ) ); 
  42.  
  43. private static function cmp_desc_fraction( $a, $b ) { 
  44. if ( $a['fraction'] == $b['fraction'] ) 
  45. return 0; 
  46. return $a['fraction'] > $b['fraction'] ? -1 : 1; 
  47.  
  48. private static function cmp_asc_index( $a, $b ) { 
  49. if ( $a['index'] == $b['index'] ) 
  50. return 0; 
  51. return $a['index'] < $b['index'] ? -1 : 1;