Ruby code qn. How to decrease iteration

2019-08-02 13:16发布

问题:

I'm new to ruby and I'm wondering why this error comes up. (Sorry for bad formatting)

Error:

rb37: in '%': nil can't be coerced into Fixnum (TypeError)

And also I need help with my question. I'm suppose to come up with a method to run through a list of 1 million ID numbers to find a specific ID using the most efficient way possible (in less than 5min). I've been at this the whole afternoon :(

def exist?(id)
    dump = []
    employee_list = $employee_list.sort    #employee_list is an array of 1 million lines of data, I have to look for a specific "id"

    while dump.length < id
        dump << employee_list.first 

        if dump.last != id 
            if id%dump.last != 0 && dump.last != 1
                 employee_list.delete_if { |n| n%dump.last == 0 }
 #what im doing here is to delete ID from employee_list that are multiples of n 
            elsif id%dump.last == 0 
                employee_list.delete_if { |m| m%dump.last == 0 && m!=id }
 #deleting multiples of m (excluding id itself) 
            end
        elsif dump.last == id 
            return true
        end
    end
    return false 
end

回答1:

I honestly have absolutely no idea what your code is trying to do, but here's the problem: you loop until the length of your dump array is greater than the id you are searching. In the loop, you append the first element of the employee_list array to the end of dump. You also delete stuff from employee_list.

Now, depending on how large id is, you are going to loop very often. E.g. imagine id is, say, 1234567890, you are going to loop over a billion times, and you are appending over a billion elements to your dump array. At the same time, you are also constantly deleting stuff from employee_list. It is very likely, that at some point in time, employee_list will become empty, which means that employee_list.first will become nil, you will append nil as the last element of dump, and thus you will try to take the modulus of id and nil in line 9, 10, 12, or 13.

Like I said, I don't actually understand what you are doing at all, so I can't tell you how to fix the problem.

Here's how I would solve the problem:

def exist?(id)
  $employee_list.find(id)
end