Reputation: 86657
I have a sorted set of persons, and I want to distribute a defined count topdown. Example:
Scenario:
int i = 8;
personA = 0;
personB = 0;
personC = 0;
Desired result:
personA = 3;
personB = 3;
personC = 2;
Of course I could iterate with for/while loops, but if i
is very large that might be inefficient.
Can the result also be optained by devision, without loops?
Pseudocode:
distributed = 0;
while (distributed < i) {
for (int p : persons) {
p++;
distributed++;
}
}
interation steps:
1-1-1 > start over > 2-2-2 > start over > 3-3-2
Upvotes: 0
Views: 76
Reputation: 255
The following code will run for i=8 5 times, i=10 4 times, as i increase , number of time loop executed is proportionately less
int i = 10;
int[] arr = new int[3] { 0, 0, 0 };
int BaseVal = i / (arr.Length);
int Remainder = i - (BaseVal * arr.Length);
for (int x = 0; x < arr.Length ;x++)
{
arr[x] = BaseVal;
}
for (int y = 0; y < Remainder; y++)
{
arr[y] = arr[y] + 1;
}
Upvotes: 2
Reputation: 34618
Yes, of course it's possible. Since you didn't give any particular implementation, I'll just put the numbers in an array. This is just a demonstration, of course. Assume NUM_OF_PERSONS is the number of persons in your array, and NUM_TO_DISTRIBUTE is the number you want to distribute. In your example, 8.
int persons[] = new int[NUM_OF_PERSONS];
int basicRation = NUM_TO_DISTRIBUTE / NUM_OF_PERSONS;
int peopleGettingExtra = NUM_TO_DISTRIBUTE % NUM_OF_PERSONS;
for ( int i = 0; i < NUM_OF_PERSONS; i ++ ) {
persons[i] = basicRation + ( i < peopleGettingExtra ? 1 : 0 );
}
Test case 1: 9 to give, 3 people. The base ration is 3. The number of people getting extra is zero. In the loop, since no i
will be less than 0, everybody will get basicRation + 0
which means 3.
Test case 2: 8 to give, 3 people. The base ration is 2. The number of people getting extra is 2. In the loop, people with indexes 0 and 1 will get 2 + 1, and the last person gets 2 + 0.
Upvotes: 3
Reputation: 5087
distributed = 0;
int howManyForEach = (int)(i/persons.size())
for(int p : person){
p = howManyForEach ;
}
distrubuted = howManyForEach * persons.size();
while (distributed < i) {
for (int p : persons) {
p++;
distributed++;
}
}
Upvotes: 2
Reputation: 497
from the problem it is clear, that the maximal difference between any person is 1
.
Just use #persons / i = base value for every person
and #persons % i = # top persons with +1 value
Example
i = 5 , persons = 3:
baseValue = 1
#topPersons = 2
=> 2 2 1
Upvotes: 1