user862010
user862010

Reputation:

Algorithm to portion

I have a number X, consider X = 1000 And I want piecemeal this number at three times, then Y = 3, then X = (X / 3) This will give me equal, just not always accurate, so I need: a percentage value is set, also consider K = 8, K is the percentage, but what I want to do? I want the first portion has a value over 8% in K, suppose that 8% are: 500 and the other two plots are 250, 250

The algorithm is basically what I need it, add a percentage value for the first installment and the other equals

Upvotes: 0

Views: 98

Answers (3)

sberry
sberry

Reputation: 132018

EDIT

I just realized, this is far simpler than I made it. To find the value of $div in my original answer you can just:

$div = (int)($num / ($parcels + $percent / 100));

Then the $final_parcels will be the same as below. Basically, the line above replaces the while loop entirely. Don't know what I was thinking.

/EDIT

I think this will do what you want... unless I am missing something.

<?php

$num = 1000;
$percent = 8;
$parcels = 3;

$total = PHP_INT_MAX;
$div = (int)($num / $parcels);
while ($total > $num) {
  $div -= 1;
  $total = (int)($div * ($parcels + $percent / 100));
}

$final_parcels = array();
$final_parcels[] = ($num - (($parcels - 1) * $div));
for ($i = 1; $i < $parcels; $i++) {
  $final_parcels[] = $div;
}

print_r($final_parcels);

This output will be

Array
(
    [0] => 352
    [1] => 324
    [2] => 324
)

324 * 1.08 = 350. 
352 + 324 * 2 = 1000.

Upvotes: 1

ElKamina
ElKamina

Reputation: 7807

Extra for the first piece W = X*K/100

Remaining Z = X-W

Each non-first piece = Z/Y = (X-W)/Y = (100-K)*X/(100*Y)

The first piece = W + (100-K)*X/(100*Y) = X*K/100 + (100-K)*X/(100*Y)

Upvotes: 1

Cheery
Cheery

Reputation: 16214

Let $T is your total X, $n is a number of parts and $K is percentage mentioned above. Than

$x1 = $T / $n + $T * $K / 100;
$x2 = $x3 = .. = $xn = ($T - $x1) / ($n - 1);

Applied to your example:

$x1 = 1000 / 3 + 1000 * 0.03 = 363.3333333333333333333333333333 
// you could round it if you want
// lets round it to ten, as you mentioned
$x1 = round($x1, -1) = 360
$x2 = $x3 = (1000 - 360) / 2 = 320

Upvotes: 1

Related Questions