javascript FizzBu​​zz

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript FizzBu​​zz相关的知识,希望对你有一定的参考价值。

/** 
 * Reverse 3 Multiples
 * Instruction: Write a program that prints out, in reverse order, 
 * every multiple of 3 between 1 and 200.
 *
 * Reationale: Doing it in normal order it easy: multiply the loop index by 3 
 * until you reach a number that exceeds 200, then quit. You don't have to worry
 * about how many iterations to terminate after, you just keep going until you
 * reach the first value that's too high. But going backwards, you have to know
 * where to start. Some might realize intuitively that 198 (3 * 66) is the
 * highest multiple of 3, and as such, hard-code 66 into the loop. Others might
 * use a mathematical operation (integer division or a floor() on a floating
 * point division of 200 and 3) to figure out that number, and in doing so, 
 * provide something more generically applicable.
**/
/** 
 * FizzBuzz 
 * Instruction: Write a program that prints the numbers from 1 to 100. 
 * But for multiples of three print "Fizz" instead of the number and for the 
 * multiples of five print "Buzz". For numbers which are multiples of both three 
 * and five print "FizzBuzz".
**/

// Common dynamic implementation, vanilla:
function fizzbuzz(start = 0, end = 100, dict = {3: 'Fizz', 5: 'Buzz'}) {
  for (let i = start; i <= end; i++) {
    let word = '';
    for (const divider in dict) {
      if (i % divider === 0) {
        word += dict[divider];
      }
    }
    console.log(word || i);
  }
}

// Minimal static implementation, vanilla:
fb = () => for(i=0;i++<100;console.log((i%3?'':'Fizz')+(i%5?'':'Buzz')||i));

// Minimal dynamic implementation, vanilla:
fb = (start = 0, end = 100, dict = {3: 'Fizz', 5: 'Buzz'}) => for(i=start;i++<end;console.log(Object.keys(dict).map(k=>i%k?'':dict[k]).join('')||i));

// Minimal Dynamic implementation with Lodash, single print:
fb = (start = 0, end = 100, dict = {3: 'Fizz', 5: 'Buzz'}) => console.log(_(_.range(start, end + 1)).map(i => _(dict).keys().map(k => i % k === 0 ? dict[k] : null).compact().join('') || i).join('\n'));

// https://blog.codinghorror.com/why-cant-programmers-program/

以上是关于javascript FizzBu​​zz的主要内容,如果未能解决你的问题,请参考以下文章

javascript FizzBu​​zz

C#FizzBu zz交换机解决方案

FizzBu​​zz 使用三元条件运算符

markdown FizzBu​​zz

python FizzBu​​zz.py

python FizzBu​​zz.py