我有一组已排序的人员,我想从上到下分发一个定义的计数。示例:
设想情况:
int i = 8;
personA = 0;
personB = 0;
personC = 0;预期结果:
personA = 3;
personB = 3;
personC = 2;当然,我可以使用for/while循环进行迭代,但是如果i非常大,则可能效率很低。
结果也能用去视觉来获得,没有循环吗?
伪码:
distributed = 0;
while (distributed < i) {
for (int p : persons) {
p++;
distributed++;
}
}互动步骤:
1-1-1 > start over > 2-2-2 > start over > 3-3-2发布于 2014-10-30 11:06:22
是的,当然有可能。由于您没有给出任何特定的实现,所以我将把数字放在一个数组中。当然,这只是一个示范。假设NUM_OF_PERSONS是数组中的人数,NUM_TO_DISTRIBUTE是要分发的数字。在你的例子中,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 );
}测试用例1: 9给,3人。基本配给是3,额外增加的人数是零。在循环中,由于没有i小于0,所以每个人都将得到basicRation + 0,这意味着3。
测试用例2: 8给,3人。基数是2,得到额外的人数是2。在循环中,索引0和1的人将得到2+ 1,最后一个人得到2+0。
发布于 2014-10-30 11:04:32
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++;
}
}发布于 2014-10-30 11:18:59
以下代码将用于i=8 5次,i=10 4次,,随着我的增加,执行的时间循环的次数按比例减少
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;
}https://stackoverflow.com/questions/26651066
复制相似问题