1

Recently I got a different version of the "fizzbuzz question" that ask you to do this:

implement function fizzBuzz(n, conditions) where n is an integer and condition is a map of key: value (number: string)

you need to run on all the numbers from 1 to n, and for each number, you need to check which conditions it fulfills if non then print the number, but if a condition X is fulfilled and you can get X from Y * Z then print the only X and not Y * Z

exmaples:

input: n = 100
condition = {
3: 'fizz:',
5: 'buzz',
15: 'foo'
}

will print: 1,2,fizz,4,buzz,fizz,7,8,fizz,10,11,fizz,13,14,**foo** which mean for 15 it will print only foo. but if the condition object was:

condition = {
3: 'fizz:',
5: 'buzz',
}

then the output would be the same but on 15 it would print 'fizzbuzz' (both 3+5)

example:

condition = {
2: 'boo',
3: 'fizz:',
5: 'buzz',
}

for 30 it will print boofizzbuzz (2+3+5)

How would you solve this?

Lakshya Thakur
  • 8,030
  • 1
  • 12
  • 39
itay
  • 357
  • 4
  • 16
  • What would be the output for :- advancedFizzBuzz(181,{ 2: 'boo', 3: 'fizz', 30: 'buzz', 180:'crazy' }) when we encounter a number say 30,150 and 180 – Lakshya Thakur Feb 18 '21 at 14:25
  • And what would it do for `12` in `{2: 'boo', 3: 'fizz', 12: 'buzz'}`, since `12 = 2 * 2 * 3`? Is it `'booboofizz'` or `'buzz'`? – Scott Sauyet Feb 19 '21 at 18:36

1 Answers1

0

I think this is working

Edit: I thought it was just the entered number.

const n = 100
const condition = {
  2: 'poo',
  3: 'fizz',
  5: 'buzz',
  15: 'foo'
}

function fizzBuzz(n, condition){
  const fizzOrNumber = i => {
    const text = Object.keys(condition).reduce((acc, item) => {
      return i % parseInt(item) == 0 ? acc+condition[item] : acc;
    }, '');
    return text || i; 
  };

  let results = [];
  for(let i=1; i<n; i+=1){
    const item = Object.keys(condition).includes(`${i}`) ? condition[i] : fizzOrNumber(i);
    results.push(item);
  }

  return results.join(',');
}

console.log(fizzBuzz(n, condition));
  • 1) it print only the entered number, 2) the output simes incorrect for some input like: n=30, condition = { 2: 'poo', 3: 'fizz', 5: 'buzz', 15: 'foo' } – itay Feb 18 '21 at 17:50
  • @itay What's the expected output for n = 30 and condition = { 2: 'poo', 3: 'fizz', 5: 'buzz', 15: 'foo' } ? – Lakshya Thakur Feb 18 '21 at 18:15