I just came home from a job interview, and the interviewer asked me to write a program:
It should, count from 1 to 100, and print...
If it was multiple of 3, "ping"
If it was multiple of 5, "pong"
Else, print the number.
If it was multiple of 3 AND 5 (like 15), it should print "ping" and "pong".
I chose Javascript, and came up with this:
for (x=1; x <= 100; x++){
if( x % 3 == 0 ){
write("ping")
}
if( x % 5 == 0 ){
write("pong")
}
if( ( x % 3 != 0 ) && ( x % 5 != 0 ) ){
write(x)
}
}
Actualy, I left very unhappy with my solution, but I can't figure out a better one.
Does anyone knows a better way to do that? It's checking twice, I didn't like it. I ran some tests here at home, without success, this is the only one that returns the correct answer...
Here's my one-liner:
I'm using ternary operators to return either an empty string or
'ping'/'pong'
, concatenating the result of these operators, then doing an OR (if the number is neither divisible by 3 or 5, the result of the concatenation is''
which is FALSEY in javascript). When both cases are true, the result of the concatenation is'pingpong'
.So basically it comes down to
I wrote a few variations on this (using
fizz
andbuzz
) as a benchmark to consider different ways of iterating over conditional logic.while
won again:Benchmark: http://jsperf.com/fizzbuzz-mod
Here's a solution which allows for a dynamic list of multiples without adding more conditionals.
And as a function which passes jslint:
And for fun, a minified ES6 version:
To get rid of the last condition you might use
continue
:Your solution is quite satisfactory IMHO. Tough, as half numbers are not multiple of 3 nor 5, I'd start the other way around:
Fiddle
Also, note that any number other than
0
andNaN
are truthy values, so I've removed the unnecessary!= 0
and some pairs of parenthesis.Here's another version, it doesn't make the same modulus operation twice but needs to store a variable:
Fiddle