views:

142

answers:

3

I basically have a few variables

0 < na < 250
0 < max <= 16
nb = (na + max - 1) / max

n has the following characterstics

0 <= i < nb - 1 => n = max
i = nb - 1 => n = na - i * max

Is there an easy way to do this without the ternary operator?

for (i = 0; i<nb;i++) {
    n = ((i + 1) * max > na ? na - (i * max) : max);
}

Examples

na = 5
max = 2
nb = 3

i = 0 => n = 2
i = 1 => n = 2
i = 2 => n = 1

na = 16
max = 4
nb = 4

i = 0 => n = 4
i = 1 => n = 4
i = 2 => n = 4
i = 3 => n = 4

na = 11
max = 3
nb = 4

i = 0 => n = 3
i = 1 => n = 3
i = 2 => n = 3
i = 3 => n = 2
+3  A: 

The question is not very clear. Perhaps you're looking for something like this:


for (i=0;i < nb;++i)
{ 
    n = i < nb - 1 ? max : (na - 1) % max + 1;
} 
Henrik
This doesn't work. It fails for "na = 12, max = 4" (gives 4,4,0 instead of 4,4,4). You can fix it with `int n = i < nb - 1 ? max : (na - 1) % max + 1;`.
Mark Byers
@Mark: I think you are right. I didn't check all the corner cases.
Henrik
+1  A: 

Just to add more confusion to the thread:

If only you print max in the first two cases, then you could do something like: (not in any particular language)

//for 0
printf("i = %d, n = %d\n",i,max)
//for 1
printf("i = %d, n = %d\n",i,max)
//for the rest
for (i = 2; i<nb;i++) {
     printf("i = %d, n = %d\n",i,na - (i * max));
}

You can avoid the operator doing two for loops

for (i = 0; (i + 1) * max) > na AND i < nb;i++) {
     printf("i = %d, n = %d\n",i,0);
}
for (; i<nb;i++) {
     printf("i = %d, n = %d\n",i,na - (i * max));
}
gbianchi
+2  A: 

You don't need to calculate nb. This is one way you could do it (C#):

int na = 11;
int max = 4;

for (int i = 0, x = 0; x < na; i++, x += max)
{
     int n = Math.Min(max, na - x);
     Console.WriteLine("i = {0}, n = {1}", i, n);
} 

Output:

i = 0, n = 4
i = 1, n = 4
i = 2, n = 3
Mark Byers