We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpSyntax Questions › embedded iteration problem
Page Index Toggle Pages: 1
embedded iteration problem (Read 279 times)
embedded iteration problem
Sep 22nd, 2006, 8:10am
 
Hi,

I'm quite new to Processing and programming and have come across a problem that I was hoping someone may be kind enough to help me with.

I'm using an embedded "for" loop to create a matrix of circles which works o.k in the following example:

Code:
 

size (500,500);
stroke(0);
smooth();
int f=0;
int direction=1;
for(int x=25; x<500; x=x+50){
for(int y=25; y<500; y=y+50){
fill(f=f+25*direction);
ellipse (x,y,20,20);
if (f>=255||f<=0){
direction=direction*-1;
}}}


However, the next stage of the experiment fails when I attempt to make the distance between the centre point of the ellipses decrease by introducing a new variable into the loop as follows:

Code:
 

size (500,500);
stroke(0);
smooth();
int f=0;
int g=0;
int direction=1;
for(int x=25; x<500; x=x+50-g){
for(int y=25; y<500; y=y+50-g){
fill(f=f+25*direction);
ellipse (x,y,20,20);
g=g+5;
if (f>=255||f<=0){
direction=direction*-1;
}}}


Running this code causes Processing to freeze, without any error message. I'm guessing that introducing another variable into the loop causes some sort of badness that I don't understand.

If someone could explain or offer a more elegant( and functional) solution, I'd appreciate it.
Re: embedded iteration problem
Reply #1 - Sep 22nd, 2006, 10:18am
 
hey, this works for me:

Code:
int f=0; 
int direction=1;
void setup(){
size (500,500);
stroke(0);
smooth();
}
void draw(){
for(int x=25; x<500; x=x+50){
for(int y=25; y<500; y=y+50){
fill(f=f+25*direction);
ellipse (x,y,20,20);
if (f>=255||f<=0){
direction=direction*-1;
}
}
}
//noLoop();
}
Re: embedded iteration problem
Reply #2 - Sep 22nd, 2006, 2:18pm
 
Processing is freezing b/c it is stuck in an infinite loop.  You start with g equal to 0, so:

g = 0;
y = 25;
if y < 500 loop
y = 25 + 50 - 0 --> 75

Then: g = g + 5, so g = 5;

g = 5;
y = 75;
if y < 500 loop
y = 75 + 50 - 5 --> 120

After a while (10 times), g will equal 50.

g = 50;
y = 250;
if y < 500 loop
y = 250 + 50 - 50 --> 250

The loop will not stop since y will never become larger than 500.  One solution would simply be to constrain the value of g:

Code:

g = constrain(g,0,49);




Re: embedded iteration problem
Reply #3 - Sep 22nd, 2006, 5:04pm
 
thanks to both of you for the help. It's becoming clearer now and I think I should be able to solve the problem.
Page Index Toggle Pages: 1