Receiving Failed to Allocate Memory Error - ruby

I am doing a CodeEval problem asking to find how many ways a number can become a double square. Here's the link to the problem:
https://www.codeeval.com/open_challenges/33
When I run the program from the command line it outputs the correct solution very quickly, however, I keep getting an error when I submit the program to CodeEval that reads:
"FATAL: Failed To Allocate Memory".
I'm new to programming and not sure why this is occurring, can someone please explain this to me.
Here is my code:
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])}

I would guess it's a problem with CodeEval's server or sandbox environment.

Related

Sieve of Eratosthenes variant

I want to do a sieve that doesn't take advantage of the obvious math hacks. I want to brute force it. My algorithm is conceived with the notion that the sieve does a lot of checking for what are not prime numbers and just returning the result of the operations to check those rather than to figure out what are prime numbers. I think some Carmichael Numbers prove it to be invalid for something very large. I could be wrong on that. I went on to check numbers from a range, and followed the basic algorithm given from Wikipedia.
def primes(n)
nums = (2..n)
not_prime = []
primes = []
nums.to_a.each_with_index do |it, idx|
primes << it unless not_prime.include?(it)
p primes.last
p nums.step(primes.last).to_a
nums.step(primes.last).each_with_index do |num, idx|
next if idx == 0
not_prime << num
end
end
primes
end
When my range does the line:
nums.step(primes.last).each_with_index
for numbers other than the first one (2), I get an off-by-x error (compounding on the list I believe). For example, all the non prime two multiples are found, but for the multiples of three, the step on the range returns 2, 5, 8, 11, etc., which are off by one.
I'm trying to figure out a solution using Range objects or converting to an Array, but I like the conciseness of my (wrong) solution. Anyone think they can help me solve this?
EDIT:
I fixed it! The solution was creating an entirely new range to iterate over rather than taking the original range. See below. Shout out to Jörg W Mittag for the inspiration to just create a new range instead of trying to fiddle with the original immutable object which is what I was trying to do. Square peg in round hole sounds so much better sometimes.
def primes(n)
nums = (2..n)
not_prime = []
primes = []
nums.to_a.each_with_index do |it, idx|
next if not_prime.include?(it)
primes << it
((primes.last)..n).step(primes.last).each_with_index do |num, idx|
next if idx == 0 || num == primes.last
not_prime << num
end
end
primes
end
def primes(n)
nums = (2..n)
not_prime = []
primes = []
nums.to_a.each_with_index do |it, idx|
next if not_prime.include?(it)
primes << it
((primes.last)..n).step(primes.last).each_with_index do |num, idx|
next if idx == 0 || num == primes.last
not_prime << num
end
end
primes
end

Why am I getting all these nils - Euler 3

I came up with this solution for Project Euler 3 although I got the answer I also get so many nils before it I can't figure out why? is there any way I can only get the answer.
Anyway here is my code
def factor(number)
max = []
(2...number).each do |x|
if number % x == 0
number = number/x
max << number
s = max[-2]
elsif number == 1
return[]
end
puts s
end
end
puts factor(600851475143)
max is an empty array. s = max[-2] is s =[][-2] for a long time. [][-2] returns nil.

Why is this happening with base converter?

I am building a number base converter. Here is my code:
def num_to_s(num, base)
results = []
remainders = []
while base <= num
result = num / base #divide the initial value of num
num = result #put that back in num so you can do it again
results << num #push into array, then map for remainders
end
remainders << results.map{|i| result = i % base} #get remainders (doesn't shovel first one?)
first_remainder = num % base #since the first remainder isn't getting recorded
return (first_remainder.to_s + remainders.to_s).reverse
end
num_to_s(13346, 7)
The modulo that gathers the remainders from the results array is not picking up the remainder from the very first iteration of that array. I remedied the skip by giving the first modulo operation it's own separate variable, which may be a cheap hack but it works. Why is this happening? And is there a better way to fix it (without some complete overhaul)?
It needs to convert up to base 16. I am aware that this will not convert base 16 yet because of the letters involved, I'll figure that when I get to it. But I am open to suggestions on that as well.
The very first operation you do is to modulo number by base. That’s why the initial is not kept. So, the easiest way to keep it is just to put it into an array initially:
def num_to_s (num, base)
results = [num] # keep the initial
while base <= num
num /= base # divide the initial value of num
results << num # push into array, then map for remainders
end
# reverse an array and only then join it into string
results.map {|i| i % base}.reverse.join
end
puts num_to_s(13346, 7)
#⇒ 53624

Trying to solve for the largest prime factor without recursion - Ruby

I came across a website called Project Euler and everything was going well until I hit the 3rd problem - The Largest Prime Factor. I don't want to use recursion to solve it. I saw solutions online where they use Math.sqrt and I don't want to use that either. Stubborn, I know.
I'd like to solve it with just loops and if statements. I assumed the input is an odd number. Here is my code. The output keeps coming out as [3] if num = 99 and I can't figure out why. I tried putting a puts statement everywhere to see what was being outputted at each step. One issue I realized was that that the array#p was not resetting after each loop. I tried array.clear but that wasn't much help. Could someone point me in the right direction? Is there some fundamental aspect about arrays, loops, and if-statements that I'm not getting?
def prime(num)
arr = []
p = []
not_p = []
# first I find all the numbers that num is divisible by
for i in (2..num/2)
if num % i == 0
arr << i
end
end # this should output [3, 9, 11, 33]
arr.each do |x| # I loop through each element in the above array
for i in (2..(x/2)) # I divide each element - x - by 2 because it cannot be divisble by anything greater than its half
if x % i == 0 # if x is divisble by i
not_p << i # I push the i into array#not_p
end # keep looping until i reaches x/2
end
if not_p.length == 0 # if there are no values in array#not_p, then I know x is a prime factor
p << x # so I push x into array#p
end
end
return p[-1] # returns the last element of the array, which is the largest
end
puts prime(99)
I'm not going to give you the full answer, as that would defeat the object of the practice with Project Euler.
However, you're almost on the right track with sorting out your problem. You don't want to look at the array p not being emptied, that should be collecting your primes. You do want to look at not_p though, since that is the array of divisors of each of your factors.
I hope this helps. Let me know if I can help any more.
Ah ok! Thanks for the suggestion philnash! In fact, I knew about that problem and tried to clear the array with Array.clear but that did not work. Instead, I just moved not_p = [] below the iteration arr.each do |x| and it worked! It makes sense because the not_p resets to [] when it moves on to the next element. Thanks so much for your help and for not providing the answer first! Here is my final, working solution =D
def prime(num)
arr = []
p = []
for i in (2..num / 2)
if num % i == 0
arr << i
end
end # this should output [3, 9, 11, 33]
arr.each do |x|
not_p = []
for i in (2..(x / 2))
if x % i == 0
not_p << i
end
end
if not_p.length == 0
p << x
end
end
return p[-1]
end
puts prime(99) # => 29

optimize this ruby code

So this code will count the total number of pairs of numbers whose difference is K. it is naive method and I need to optimize it. suggestions?
test = $stdin.readlines
input = test[0].split(" ")
numbers = test[1].split(" ")
N = input[0]
K = input[1]
count = 0
for i in numbers
current = i.to_i
numbers.shift
for j in numbers
difference = (j.to_i - current).abs
if (difference == K)
count += 1
end
end
end
puts count
Would have been nice for you to give some examples of input and output, but I think this is correct.
require 'set'
def count_diff(numbers, difference)
set = Set.new numbers
set.inject 0 do |count, num|
set.include?(num+difference) ? count+1 : count
end
end
difference = gets.split[1].to_i
numbers = gets.split.map { |num| num.to_i }
puts count_diff(numbers, difference)
Untested, hopefully actual Ruby code
Documentation for Set: http://www.ruby-doc.org/stdlib/libdoc/set/rdoc/classes/Set.html
require 'set'
numbers_set = Set.new
npairs = 0
numbers.each do |number|
if numbers_set.include?(number + K)
npairs += 1
end
if numbers_set.include?(number - K)
npairs += 1
end
numbers_set.add(number)
end
Someone deleted his post, or his post was deleted... He had the best solution, here it is :
test = $stdin.readlines
input = test[0].split(" ")
numbers = test[1].split(" ")
K = input[1]
count = 0
numbers.combination(2){|couple| couple.inject(:-).abs == K ? count++}
puts count
You don't even need N.
I do not know Ruby so I'll just give you the big idea:
Get the list
Keep a boolean array (call it arr), marking off numbers as true if the number exists in the list
Loop through the list and see if arr[num-K] and/or arr[num+K] is true where num is a number in your list
This uses up quite a bit of memory though so another method is to do the following:
Keep a hash map from an integer n to an integer count
Go through your list, adding num+K and num-K to the hash map, incrementing count accordingly
Go through your list and see if num is in the hash map. If it is, increment your counter by count

Resources