1

I need an alternate sequence like 1, -1, 1, -1... asf. First I used if-statements for it, but it's dumb. Then I tried something like:

int n = 1;
...
do{
   n = 0 + ( n * (-1));
} while(blabla)

It's ok, but I have to store n value from iteration to iteration. This isn't so pretty. How to compute that sequence from a control variable like frameCount?

Sorry, I am learning not only to code, but English too.

Kevin Workman
  • 41,537
  • 9
  • 68
  • 107
Daria
  • 168
  • 1
  • 8
  • It's been a while since I looked at Processing, but I'll give it a shot. I'm guessing frameCount just increments with every frame? If that's so you could say `n = (frameCount % 2 == 0) ? 1 : -1` That is, when frameCount is even, n is 1; when frameCount is odd, n is -1. – jpm Jan 27 '12 at 20:57

5 Answers5

2

It's not very readable, but if you're looking for something purely "elegant," I suppose you could do something like:

int n = 1 - ((frameCount % 2) * 2);

If you're on an even frame you'll be subtracting (1 - 0), if you're on odd frame you'll be subtracting (1 - 2).

jffrynpmr
  • 91
  • 2
1

Why don't you just do this

float n = 1 ;

void setup() {
....
}

void draw() { 
....
n =-n;
....
} 
Mocas
  • 1,403
  • 13
  • 20
  • 1
    Because you are using a global state variable, which should be avoided to largest possible extent. Pass the state as a reference or pointer instead. – user877329 May 12 '14 at 06:52
1

I recently saw another fun way to create such a sequence using XOR magic.

int n = -1, t = 1 ^ -1;
...
do{
   n ^= t;
}while(blabla);

Found in Algorithms for programmers, page 5.

Daria
  • 168
  • 1
  • 8
1

For readability, I recommend:

int n = (frameCount & 1) == 1 ? 1 : -1;

or

int n = -1;
if ((frameCount & 1) == 1) {
    n = 1;
}

(Note that x & 1 extracts the lowest bit from x just like x % 2 does.)

Kaganar
  • 6,540
  • 2
  • 26
  • 59
  • Also note that once a compiler hits it, jffrynpmr's solution is likely going to be faster for machine execution since it has no branching and simple operations. – Kaganar Jan 27 '12 at 21:03
0

One possibility is

((framecount & 1)<<1) -1;

On even frames, framecount & 1 will yield 0, and the result will then be -1. On odd frames, framecount & 1 will yield 1, and the result will be 1.

Or, less immediate but possibly much faster on some architectures,

frameCount-(frameCount^1)

When frameCount is odd, frameCount^1 will be equal to frameCount-1, and the result will then be 1. If frameCount is even, frameCount^1 will be equal to frameCount+1, giving -1.

LSerni
  • 55,617
  • 10
  • 65
  • 107