2013-07-18 263 views
0

我正在做一個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])} 

回答

0

我想這是與CodeEval的服務器或沙箱環境問題。