I’m going to start posting some useful little bits of code up here as i think of them.
This is partly to help with my exceptionally poor memory, and partly to help out anyone who might be interested. I encourage anyone else who knows of some similar little helpful tips to send them to me and i’ll post them up here.
Ok, so here’s a nice simple one to start off. What’s an easy and simple method to determine if a number is odd or even?
The answer lies with the modulo operator (%) or the bitwise AND operator (&).
1
i%2
Whatever i is, i%2 will evaluate to either 0 or 1.
Or a faster method for determining odd or even numbers would be the Bitwise AND operator (represented by a single ampersand: &):
1
i&1
So what use is this?
Let’s say you’ve got a for loop:
1 2 3 4 5 6 7
for(var i:int = 0; i <50; i++){ if(i%2){// Or i&1 //do something for odd numbers }else{ //do something else for even numbers } }
So why would we use the modulo operator if a bitwise AND is faster?
To take this further, you could specify separate code for every nth number:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
for(var i:int = 0; i <50; i++){ switch(i%4){ case 0: trace("run every 4 iterations starting from 0"); break; case 1: trace("run every 4 iterations starting from 1"); break; case 2: trace("run every 4 iterations starting from 2"); break; case 3: trace("run every 4 iterations starting from 3"); break; } }
Useful hints: #1 – Odd/Even numbers (Modulo operator [%] and Bitwise And [&])
I’m going to start posting some useful little bits of code up here as i think of them.
This is partly to help with my exceptionally poor memory, and partly to help out anyone who might be interested. I encourage anyone else who knows of some similar little helpful tips to send them to me and i’ll post them up here.
Ok, so here’s a nice simple one to start off. What’s an easy and simple method to determine if a number is odd or even?
The answer lies with the modulo operator (%) or the bitwise AND operator (&).
Whatever i is, i%2 will evaluate to either 0 or 1.
Or a faster method for determining odd or even numbers would be the Bitwise AND operator (represented by a single ampersand: &):
So what use is this?
Let’s say you’ve got a for loop:
2
3
4
5
6
7
if(i%2){ // Or i&1
//do something for odd numbers
}else{
//do something else for even numbers
}
}
So why would we use the modulo operator if a bitwise AND is faster?
To take this further, you could specify separate code for every nth number:
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
switch(i%4){
case 0:
trace ("run every 4 iterations starting from 0");
break;
case 1:
trace ("run every 4 iterations starting from 1");
break;
case 2:
trace ("run every 4 iterations starting from 2");
break;
case 3:
trace ("run every 4 iterations starting from 3");
break;
}
}