我在ruby exercice上创建了一种计算网格NxN
中的平方的方法如果n = 1,则有一个1乘1平方= 1。
If n = 3, there is one 3-by-3 square, four 2-by-2 squares and nine 1-by-1 squares = 14.
如果我们继续上面的任意n的序列,那么我们将有一个n-by-n平方,四(n-1)-by-(n-1)个正方形,九个(n-2)-by - (n - 2)个正方形,......和n2个1个1的正方形。
我想知道如何在红宝石中获得这个
答案 0 :(得分:2)
通常对于 n x n 方格,总方块数由
定义n²+(n-1)²+(n-2)²+ ... + 1。
在Ruby中你可以这样做:
class Number
def squares_counter(n)
(1..n).map {|e| e*e }.inject(:+)
end
end
map
从1
到n
创建一个平方数数组,然后inject
将它们相加。使用它我们可以计算棋盘上的方格数:
num = Number.new
puts num.squares_counter(8) #=> 204