ruby - Receiving Failed to Allocate Memory Error -
i doing codeeval problem asking find how many ways number can become double square. here's link problem:
when run program command line outputs correct solution quickly, however, keep getting error when submit program codeeval reads:
"fatal: failed allocate memory".
i'm new programming , not sure why occurring, can please explain me.
here code:
def double_square(x) #create array storing double squares arr = [] #make x integer x = x.to_i #solve case 0 if x == 0 arr << 0 end sqrt_x = math.sqrt(x) sqrt_x_as_int = math.sqrt(x).to_i #check if x perfect square, if add array '0' if sqrt_x/sqrt_x_as_int == 1.0 arr << [0,x] end #find squares of numbers less square root of x squares = (1..sqrt_x_as_int).map {|num| num**2} #create array containing combinations of squares & if array contains x, delete combos = squares.combination(2).to_a.delete_if {|combo| combo.any? {|num| num == x}} #find sum of each array , select arrays sums equal x sums = combos.map |combo| sum = combo.inject(:+) if sum == x arr << combo end end #return amount of double squares 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])}
i guess it's problem codeeval's server or sandbox environment.
Comments
Post a Comment