0
我正在做一个CodeEval问题,要求查找一个数字可以变成双平方的方式。这里的链接的问题:接收无法分配内存错误
当我在命令行中运行它,它很快就输出了正确的解决方案,但是,当我提出的计划,我不断收到一个错误CodeEval,内容如下:
“致命:分配内存失败”。
我是编程新手,不确定为什么会出现这种情况,有人可以向我解释这一点。
这里是我的代码:
def double_square(x)
#Create array for storing double squares
arr = []
#Make x an integer
x = x.to_i
#Solve for case 0
if x == 0 then arr << 0 end
sqrt_x = Math.sqrt(x)
sqrt_x_as_int = Math.sqrt(x).to_i
#Check if x is a perfect square, if it is add it to array with '0'
if sqrt_x/sqrt_x_as_int == 1.0
arr << [0,x]
end
#Find squares of all numbers less than the square root of x
squares = (1..sqrt_x_as_int).map {|num| num**2}
#Create array containing the combinations of squares & if array contains x, delete it
combos = squares.combination(2).to_a.delete_if {|combo| combo.any? {|num| num == x}}
#Find the sum of each array and select the arrays whose sums are equal to x
sums = combos.map do |combo|
sum = combo.inject(:+)
if sum == x
arr << combo
end
end
#Return the amount of double squares for n
puts arr.count
end
lines = File.readlines(ARGV[0]).map {|line| line.strip}
lines[0].to_i.times {|i| double_square(lines[i+1])}