Thursday, October 14, 2010

Looping (count/2*(count%2==2?1:-1)) from middle to start and end.

Have you ever loop from middle to end and start of any list. i.e the index should move something like 0,1,-1,2,-2,3,-3 ...
One of the following would do:
1.
for(int i = 0 ; i < 5;i++){
System.out.println(i);
System.out.println(i*-1);
}

2.
for(int i =1 ; i <10;i++){
System.out.println(i/2*(i%2==0?1:-1));
}

of course, first one will print 0 two times. So,

1.1.
System.out.println(0);
for(int i = 1 ; i < 5;i++){
System.out.println(i);
System.out.println(i*-1);
}

Let me change these suitable for real situation:

1.1.
doSomethingForIndex(0)
for(int i = 1 ; i < 5;i++){
doSomethingForIndex(i);
doSomethingForIndex(0);
}

2.
for(int i =1 ; i <10;i++){
doSomethingForIndex(i/2*(i%2==0?1:-1));
}

If you look at these you will see no different in execution, because all statements run one after other.
But, say if we want to run doSomethingForIndex(i); in different threads one after other, then sample 1.1 will run two statements in one thread. So in that case it is better to go for option 2. (count/2*(count%2==2?1:-1))

2 comments:

Unknown said...

Good one!

Unknown said...

PokerStars - Gaming & Slots at Aprcasino
Join the 나비효과 fun at Aprcasino and play apr casino the best of the best PokerStars https://octcasino.com/ casino casinosites.one games including Slots, titanium earrings Blackjack, Roulette, Video Poker and more!