Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New Coder
    Join Date
    Feb 2008
    Posts
    29
    Thanks
    4
    Thanked 3 Times in 3 Posts

    most effective way to get largest value of remainder?

    i am dynamically assigning a number of cells per row to populate a directory page that shows thumbnails, based on the amount of thumbnails available, in an attempt to have as many cells per row throughout (i.e., avoid having a row where there is only one cell). i have the following code which works, but i keep thinking there's a more efficient way to go about doing this... any clues?


    Code:
    <?php
    
    function getNumCells($j) {
    
      for ($i=6;$i>=3;$i--) {      // max of 6 cells/row, min of 3
    
        if (($j &#37; $i) == 0) {        // take most cells with no remainder if any
          $good = $i;
          break;
        } else {
          $val[$i] = ($j % $i);     // otherwise store divisor and remainders in array
        }
    
      }
    
      if (!isset($good)) {          // if no 'clean' result...
        $val=array_flip($val);     // flip array...
        ksort($val);                  // sort array by remainder...
        $good = end($val);        // and get number of cells for highest remainder
      }
    
      return $good;
    
    }
    
    $nrows=149;                     // will actually be value of mysql_num_rows
    $success = getNumCells($nrows); 
    echo $success;                 // will actually be used to limit # of cells per row
    
    ?>

  • #2
    Master Coder
    Join Date
    Dec 2007
    Posts
    6,682
    Thanks
    436
    Thanked 890 Times in 879 Posts
    PHP Code:
    <?php

    function getNumCells($number$minlim$maxlim){
      
    $results = array();
      for(
    $i $maxlim$i >= $minlim$i--){
        
    $rem $number $i;
        if(
    $rem == 0){
           return 
    $i;
        }elseif(!
    in_array($rem,$results)){
          
    $results[$i] = $rem;
        }
      }
      
    arsort($results);
      return 
    key($results);
    }

    $num 149;
    $limmin 3;
    $limmax 6;

    $rem getNumCells($num,$limmin,$limmax);
    print 
    $num ": " $rem " : " $num $rem "<br/>";

    ?>
    best regards

  • Users who have thanked oesxyl for this post:

    ereignis (03-12-2008)


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •