Perimeter of squares in a rectangle
问题:
The drawing shows 6 squares the sides of which have a length of 1, 1, 2, 3, 5, 8. It’s easy to see that the sum of the perimeters of these squares is : 4 * (1 + 1 + 2 + 3 + 5 + 8) = 4 * 20 = 80
Could you give the sum of the perimeters of all the squares in a rectangle when there are n + 1 squares disposed in the same manner as in the drawing:
alternative text
#Hint: See Fibonacci sequence
#Ref: http://oeis.org/A000045
The function perimeter has for parameter n where n + 1 is the number of squares (they are numbered from 0 to n) and returns the total perimeter of all the squares.
perimeter(5) should return 80
perimeter(7) should return 216
NOTE: due to a misspelling in the reference solution for random tests, have an outer auxiliary function that calculates Fibonacci numbers, name this outer function fib. (More than 500 CW passed the kata so it is now impossible to change the random tests).
翻译(来自有道翻译):
这张图显示了6个正方形,它们的边长是1、1、2、3、5、8。很容易看出,这些正方形的周长之和是:4 * (1 + 1 + 2 + 3 + 5 + 8)= 4 * 20 = 80
当n + 1个正方形按图中所示的方式排列时,能否给出一个矩形中所有正方形的周长之和:
替代文本
提示:参见斐波那契数列
函数周长为参数n,其中n + 1是正方形的数目(它们的编号从0到n),并返回所有正方形的总周长。
perimeter(5) should return 80
perimeter(7) should return 216
注意:由于在随机测试的参考解决方案中有一个拼写错误,有一个计算斐波那契数的外部辅助函数,将这个外部函数命名为fib。(超过500名CW通过了kata,所以现在不可能改变随机测试)。
个人解题代码:
//思路:初始化tmp为一个[1,1]的数组,for循环n次并计算相应的num
//每次循环将num加到sum当中最后输出sum*4
function perimeter(n) {
var tmp = [1,1];
var num = 0;
var sum = 2;
for(var i = 0 ; i < n-1 ; i++){
num = tmp[i] + tmp[i+1];
tmp.push(num);
sum+=num
}
return sum*4
}
高亮回答:
function perimeter(n) {
let arr = [1, 1];
for(let i = 0; i < n - 1; i++) {
arr.push(arr[arr.length - 1] + arr[arr.length - 2]);
}
return 4 * arr.reduce((sum, num) => sum + num, 0);
}