Forum Moderators: coopster
Dim intCounter As Integer
Dim tmpPart As Integer
Dim intDifference As Integer
Dim tmpAnswer As String
Dim intNumberOfParts As Integer
Dim intAmount
' grab inputs from form
intNumberOfParts = CInt(txtQuals.Text)
' multiply amount by 100 to help working in money format
intAmount = CDbl(txtAmount.Text) * 100
' create array for results
Dim arrParts() As Integer
ReDim arrParts(intNumberOfParts)
' set rough value always rounding down
tmpPart = Int(CInt(intAmount) / intNumberOfParts)
' copy rough value to all parts
For intCounter = 0 To UBound(arrParts, 1) - 1
arrParts(intCounter) = tmpPart
Next
' calc difference that rounding caused
intDifference = CInt(intAmount) - (tmpPart * intNumberOfParts)
' add difference to first part
arrParts(0) = arrParts(0) + intDifference
<?php
function pre($o) {
echo '<pre style="margin:5px; padding:4px;">'."\n";
print_r(($o === null) ? 'NULL' : $o);
echo "</pre>\n";
}
function divvyUp($amount, $splitTimes) {
if (!is_int($splitTimes) || !(is_int($amount) || is_float($amount)) || $amount / $splitTimes < 0.01) {
return null; //either improper inputs or can not split to a penny or more
}
$n = round($amount / $splitTimes, 2);
$rem = fmod($amount, $n); //remainder of $amount / $n (note mod operator '%' does not work with floats, must use fmod)
//basically DONE by here (the 'predictions' are done, just need to decide what to do with the differential, if any).
//There will be two cases of differential:
//$rem will be within ($splitTimes / 100) of $n,
//or $rem will be less than ($splitTimes / 100).
//(($splitTimes / 100) being number of pennies)
$splits = array_fill(0, $splitTimes, $n);
$randomPersonsIndex = rand(0, $splitTimes - 1); //who are we to decide who the lucky/unlucky one is? Let it be random, I'd say!
if ($rem < $splitTimes / 100) {
$splits[$randomPersonsIndex] += $rem;
} else {
$splits[$randomPersonsIndex] = $rem;
}
return array(
'total' => $amount,
'splitTimes' => $splitTimes,
'normalAmount' => $n,
'offsetAmount' => $splits[$randomPersonsIndex],
'randomLuckyOrUnluckyPerson' => $randomPersonsIndex + 1,
'splits' => $splits
);
}
$tests = array(
array(1.11, 120),
array(16.79, 5),
array(233.55, 17),
array(62.03, 111),
array(2.44, 12),
array(20.20, 4),
array(1298759, 27)
);
foreach ($tests as $arr) {
$a = divvyUp($arr[0], $arr[1]);
pre($a);
}
?>