This site requires JavaScript, please enable it in your browser!
Greenfoot back
rickykwl
rickykwl wrote ...

2018/10/18

Having trouble about these pattern by using loop

rickykwl rickykwl

2018/10/18

#
Can’t use a nested loop and i can ONLY use 1D loop to solve these patterns please help me, thanks!!!
danpost danpost

2018/10/18

#
HINT: to change a 2D loop into a 1D loop, you would need to multiply the limits of the counters used in a 2D loop and use it in your 1D loop. Then use modulus and division to determine what the individual values needed would be in the 1D loop. For example, if you wanted 4 rows of 8 objects:
for (int i=0; i<4*8; i++) addObject(new Obj(), i%8, i/8);
Using appropriate conditions, you can create the different patterns. For example, for your first pattern, the sum of (i%8) and (i/8) would be even, so:
for (int i=0; i<4*8; i++) if ( ((i%8)+(i/8)) %2 == 0 ) addObject(new Obj(), i%8, i/8);
For the others, you would use multiple/compound conditions to limit where an object is placed. Think about what happens when you limit the same sum to be greater than a certain value. I would go about doing the other patterns in a more mathematically described way to impose some of the limiting factors, but it would probably be confusing to most others. Just impose the multiple conditions needed by ANDing them together (conditionOne && conditionTwo && ...).
rickykwl rickykwl

2018/10/19

#
thank you, otherwise, may i know what means about % and / ?, and how to impose the multiple conditions for the second and third pattern? Sorry for my annoying
danpost danpost

2018/10/19

#
rickykwl wrote...
may i know what means about % and / ?,
The / is just division. Actually, in this case, it is integer division where any fractional remainder is discarded (only because we are working with integer values). The % is the modulus operator. It returns the remainder after division So, as the iterator, i, progresses from 0 to 31, i/8 will be 0 until i=8, then 1 until i=16, etc., while i%8 will repeatedly go from 0 to 7. One complete cycle from 0 to 7 will occur for each "increment" of i/8 (which will go from 0 to 3).
how to impose the multiple conditions for the second and third pattern?
You will add or subtract using 'i/8' and 'i%8' and set the result greater than or less than some value for each of the two conditions needed for each pattern. The two conditions for each pattern will be either ORed (using '||') or ANDed (using '&&') together. Test one condition at a time before concatenating the two; then determine which operator should join them.
You need to login to post a reply.