...

View Full Version : most effective way to get largest value of remainder?



ereignis
02-28-2008, 03:21 AM
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?




<?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

?>

oesxyl
02-28-2008, 04:37 AM
<?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



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum