From 1 to 100, type “ping” if several of 3, “pong” if their number is 5, or type

I just returned from an interview, and the interviewer asked me to write a program:

It should count from 1 to 100 and type ...

If he was a multiple of 3, "ping"
If it was a multiple of 5, "pong"
Otherwise, type the number.

If it was a multiple of 3 and 5 (for example, 15), it should print "ping" and "pong".

I chose Javascript and came up with the following:

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) } } 

In fact, I left very dissatisfied with my decision, but I can not understand the best.

Does anyone know a better way to do this? He checked twice, I did not like it. I did some tests here at home, without success, this is the only one that returns the correct answer ...

+8
javascript fizzbuzz challenge-response
source share
7 answers

Your decision is quite satisfactory IMHO. Hard, since half the numbers are not a multiple of 3 and 5, I would start the other way around:

 for (var x=1; x <= 100; x++){ if( x % 3 && x % 5 ) { document.write(x); } else { if( x % 3 == 0 ) { document.write("ping"); } if( x % 5 == 0 ) { document.write("pong"); } } document.write('<br>'); //line breaks to enhance output readability }​ 

Fiddle

Also note that any number other than 0 and NaN is a true value, so I removed the unnecessary != 0 and some pairs of brackets.


In another version, it does not perform the same module operation twice, but must store a variable:

 for (var x=1; x <= 100; x++) { var skip = 0; if (x % 3 == 0) { document.write('ping'); skip = 1; } if (x % 5 == 0) { document.write('pong'); skip = 1; } if (!skip) { document.write(x); } document.write('<br>'); //line breaks to enhance output readability } 

Fiddle

+17
source share

Here is my single line:

 for(var x=1;x<101;x++)document.write((((x%3?'':'ping')+(x%5?'':'pong'))||x)+'<br>'); 

I use ternary operators to return either an empty string or 'ping'/'pong' , combining the result of these operators and then doing OR (if the number is not divisible by 3 or 5, the result of concatenation '' , which is FALSEY in javascript). When both cases are true, the result of concatenation is 'pingpong' .

So basically it comes down to

 '' || x // returns x 'ping' || x // returns 'ping' 'pong' || x // returns 'pong' 'pingpong' || x // returns 'pingpong' 
+6
source share

Here is a solution that allows a dynamic list of multiples without adding additional conventions.

 // List of outputs var outputs = [ {mult: 3, str: 'ping'}, {mult: 5, str: 'pong'} // {mult: 10, str: 'play'} ex: [30] => 'pingpongplay' ]; // Loop 100 times for (var i = 1, j = 100; i <= j; i += 1) { // Set empty vars var result, string = ''; // Loop through the listed output objects outputs.forEach(function (output) { // If listed multiple, concat string if (i % output.mult === 0) { string += output.str; } }); // Set result if (string.length) { result = string; } else { result = i; } // print result document.body.innerHTML += result + '<br>'; } 

And as a function that passes jslint:

 /*jslint browser: true */ var printOutputs = function (array, iterations) { 'use strict'; var i = 1; var outputResults = function (arr, idx) { var result; var str = ''; arr.forEach(function (item) { if (idx % item.mult === 0) { str += item.str; } }); if (str.length) { result = str; } else { result = idx; } return result; }; while (i < iterations) { document.body.innerHTML += outputResults(array, i) + '<br>'; i += 1; } }; var outputs = [ {mult: 3, str: 'ping'}, {mult: 5, str: 'pong'} ]; printOutputs(outputs, 100); 

And for fun, a miniature version of ES6:

 const pO=(arr,itr)=>{let i=1,o=(a,idx)=>{let r,s='';a.map(v=>{if(idx%v.mult===0)s+=v.str});s.length?r=s:r=idx;return r};while(i<itr){document.body.innerHTML+=`${o(arr,i)}<br>`;i++}}; pO([{mult:3,str:'ping'},{mult:5,str:'pong'}], 100); 
+1
source share

I wrote several variations of this (using fizz and buzz ) as a reference to consider various ways to iterate through conditional logic.

while won again:

 // Iterate using a recursive function // firing a callback once per iteration function f(s,n) { if(++n >= 102) return; s === '' ? console.log(n-1) : console.log(s); !!(n % 3) ? !!(n % 5) ? f('',n) : f('Buzz',n) : !!(n % 5) ? f('Fizz',n) : f('FizzBuzz',n); } // Iterate using a `while` loop // firing a callback after satisfying a condition function b(n) { var i = n; $: while(++i) { if(i % 3) if(i % 5) console.log(i); else console.log('Buzz'); else if(i % 5) console.log('Fizz'); else console.log('FizzBuzz'); if(i >= 100) break $; } return; } // Iterate using a `for` loop // firing a callback once per iteration function F(n) { var i = n, f = 'Fizz', b = 'Buzz', o = ''; for (; i <= 100; i++) { o = !(i % 3) ? !(i % 5) ? f + b : f : !(i % 5) ? b : i; console.log(o); } return; } // Iterate using a `for` loop // firing a callback after satisfying a condition function B(n) { var i = n; var fiz = 'Fizz'; var buz = 'Buzz'; for(; i <= 100; i++) if(!(i % 3)) if(!(i % 5)) console.log(fiz + buz); else console.log(fiz); else if(!(i % 5)) console.log(buz); else console.log(i); return; } f('', 1); // recursive b(0); // `while` F(1); // `for` B(1); // `for 

Benchmark: http://jsperf.com/fizzbuzz-mod

0
source share
  for( int number = 1 ; number < 100 ; number++ ) { boolean shouldPrintNumber = true; System.out.println("\n"); if( (number%3) == 0 ) { System.out.print("ping"); shouldPrintNumber = false; } if( (number%5) == 0 ) { System.out.print("pong"); shouldPrintNumber = false; } if( shouldPrintNumber ) { System.out.print( number ); } } 
-one
source share
 for var a = 1; a <= 100 ; a++ { if a % 3 == 0 && a % 5 == 0 { println("Fizzbuzz") continue } if a % 5 == 0 { println("Buzz") continue } if a % 3 == 0 { println("Fizz") continue } else { println(a) } } 
-one
source share

To get rid of the last condition, you can use continue :

 for (x=1; x <= 100; x++){ if( x % 3 == 0 ){ write("ping") continue } if( x % 5 == 0 ){ write("pong") continue } write(x) } 
-2
source share

All Articles