这种解决Fizzbuzz挑战的方式是什么?
I am new to programming, and I am currently doing the FizzBuzz test, it looks simple at first but we got some requirements to perform it:
我是编程新手,我目前正在进行FizzBuzz测试,起初看起来很简单,但我们有一些要求来执行它:
- I can use only one
if
. No multiple branches, ternary operators orelse
. - Unit tests.
我只能使用一个。没有多个分支,三元运算符或其他。
I made it by using switch statements, but looking on the internet, I found this way which is shorter, but it is not clear how this process of solving the FizzBuzz challenge is.
我是通过使用switch语句来实现的,但是在互联网上看,我发现这种方式更短,但目前还不清楚这个解决FizzBuzz挑战的过程是怎样的。
This is the code:
这是代码:
var i, values = [, , 'fizz', , 'buzz', 'fizz', , , 'fizz', 'buzz', , 'fizz', , , 'fizzbuzz'];
for (i = 0; i < 100; console.log(values[i++ % 15] || i));
If anyone understands this way of solving the FizzBuzz challenge I would appreciate if it can be explained.
如果有人理解这种解决FizzBuzz挑战的方式,我会很感激,如果可以解释的话。
1 个解决方案
#1
0
It's called a "lookup table". The pattern of responses cycles through all the possibilities every 15 numbers, because that's the least common multiple of 3
and 15
. So we calculate the number modulo 15, and use that as the index into an array of all 15 possibilities.
它被称为“查找表”。响应模式每15个数字循环遍历所有可能性,因为这是3和15的最小公倍数。因此我们计算模数15,并将其用作所有15种可能性的数组的索引。
The blank elements in the array are used to print the numbers themselves instead of fizz
or buzz
. Leaving an array element is roughly equivalent to specifying undefined
as the value, so this is just a shorter way of writing
数组中的空白元素用于打印数字本身而不是嘶嘶声或嗡嗡声。保留数组元素大致相当于将undefined指定为值,因此这只是一种较短的写入方式
values = [undefined, undefined, 'fizz', undefined, 'buzz', 'fizz', undefined, undefined, 'fizz', 'buzz', undefined, 'fizz', undefined, undefined, 'fizzbuzz'];
Since undefined
is falsey, values[i++ % 15] || i
will be i
whenever the array element isn't filled in with one of the strings.
由于undefined是假的,因此值为[i ++%15] ||每当数组元素没有填充其中一个字符串时,我将是我。
更多相关文章
- iframe操作、调用父页面元素或js函数
- 如何使用变量创建数组?
- 推json敲出可观察的数组
- 从占用转义字符的字符数组创建字符串
- Angularjs在ng-repeat中找到最后一个可见元素
- 浏览器如何处理HTML元素上的无效/未指定的属性?
- 为什么推荐把<script>元素写在body里面
- 在bootstrap中为同一元素使用两个数据切换
- 如何获取knockoutjs可观察数组的下一个元素?