A Little Code Puzzle : II
Here's another little puzzle. Here, we're trying to come up with the least processor-intensive algorithm for determining, given an array of random integers, how many are even?
I have a solution that works, but I'm not sure it's the most efficient. What's your solution? (If you want to see mine, highlight the space below -- the code is white on white).
function evens( arr ) {
var numFound = 0;
var i = arr.length;
while ( i-- ){
if ( arr[ i ] % 2 > 0 ) {
continue;
} else{
numFound++;
}
}
alert ( numFound );
}


var isOdd = someNumber & 1;
evens = [22,33,2,11,102,5].filter( function(i,n){ return !(i & 1);})
How's that for a non-answer?
I chose that answer because I just bumped into something like this last week in writing an editor macro to apply some basic formatting to an XML file. After I got the basics working, I started looking at how to improve the performance on large files and several tweaks that seemed likely to improve performance actually had the opposite effect.
if (arr[i]%2==0){numFound++}
VERY good point, Ron.
function evens(arr){
var numFound = 0;
var i = arr.length;
while (i--) {
numFound += (arr[i]+1) & 1; // increment the number being tested so that an even generates an incrementer
}
return numFound;
}
AFAIK, you can use a Bitwise AND to MOD powers of two. I'm pretty sure, though, that C-based compilers use MOD(x,y) = x-y*Floor(x/y). Might want to try that for speed.
For the record, in C# I'd use:
new int[]{1,2,3,4,5,6,7,8,9,10}.Where(arg => arg%2 == 0).Count()