接收失败以分配内存错误

时间:2013-07-18 17:11:19

标签: ruby memory

我正在执行CodeEval问题,要求查找数字可以成为双方的方式。这是问题的链接:

  

https://www.codeeval.com/open_challenges/33

当我从命令行运行程序时,它会非常快速地输出正确的解决方案,但是,当我将程序提交到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])}

1 个答案:

答案 0 :(得分:0)

我认为CodeEval的服务器或沙箱环境存在问题。