I just browsing some examples code and see this code, it looks cool but, it confused me.
function chickenOptions(n) {
var res = [0];
for(var i = 1; i <= n; i++) {
if (!(i % 3) || !(i % 10))
res.push(i);
else
for(var k = i-10; k>=0; k-=10)
if(!(k % 3)) {
res.push(i);
break;
}
}
return res;
}
Can someone help me understand it?
Help me understand how it works and why it works.
Thanks.
Pseudocoded:
Taken n as a parameter.
declare res as 0-length array. //result array
for (i from 1 to n){
if (3 divides i evenly OR 10 divides i){
push i on to res[]
} else {
for (k = i-10 to 0, counting down by 10s){
if (3 divides i){
push i on to res[]
resume outer for loop
}
}
}
return result array
}
Effect : finds every number between 1 and n that is divisible by 3 or 10, AND every number ending in a 3, 6, or 9, regardless of the first digit (if we’re talking about decimal numbers).
Whoops: Forgot one edge case. The numbers ending in 3, 6, and 9 that are less than 9 smaller than n are not included unless they are divisible by 3 themselves.
As to why you would want these numbers, I have no idea. As to why it works, the issue is about boolean logic and modulo arithmetic. The % operator returns a number between 0 and m, as in:
r = x % m
Essentially, the output of the modulo is the remainder if you divided by m. If m divides x perfectly, there will be no remainder, and the output of the modulo operator is 0. Since 0 is a “falsy” value in Javascript (and many other C-type languages), negating it with the !
operator means that !(x%m)
returns true
when m divides x perfectly. The ||
or boolean OR operator is evaluated left-to-right, and exits when the first condition is true
, since if ANY of the tests are true
, the whole expression is. So, in the first conditional, even if 3 doesn’t divide i, but 10 does, the expression is true and the number is added to the results array.
What was this code for? And where did it come from?