Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

looping in two directions

hey I'm looking for are clean solution to this problem:

alt text

i start the loop with i = 0 in the second loop step the i = 1, then i = -1 and then i = 2 ect.

how to programm this with a for loop in a clean way?

like image 682
antpaw Avatar asked Jul 01 '10 08:07

antpaw


2 Answers

f(0); //do stuff with 0  for(var i = 1; i<len; i++) //where len = positive boundary {     f(i);  //do stuff with i     f(-i); //do stuff with -i } 

Should do what you want

like image 80
fbstj Avatar answered Oct 03 '22 23:10

fbstj


If you don't mind having the inner loop appear 3 times:

f(0); for (var i = 1; i <= 3; ++ i) {   f(i);   f(-i); } 

2 times with an if:

for (var i = 0; i <= 3; ++ i) {   f(i);   if (i > 0)      f(-i); } 

single time but with an ugly expression:

for (var j = 1; j <= 7; ++ j) {    var i = j / 2;    if (j % 2) i = -i;     f(i); } 
like image 33
kennytm Avatar answered Oct 03 '22 23:10

kennytm