News for hackers. Stuff that matters.
Re:Array Iteration Interview Problem by telemachos on Wednesday August 01, 2012 @10:47PM (#4326943)
I've posted and deleted this a few times, since I keep rethinking it. This is a Lua version, and I'm pretty new to Lua (it's good practice). No reverses needed; just numeric for loops.

I'd rather keep n = 0 as a separate case since it doesn't need to consider a break point or a count variable. The test - Is n 0? - happens once and by including it, you can omit a lot of pointless tests - Am I at the breakpoint? - and increments - Add another one to count. Those tests and increments seem much worse than the single test - especially if the array (a table in Lua) will grow to very, very large sizes.

But I would be happy to hear if I'm looking at it wrong or missing a good trick in Lua.

    function add1(t, val, n)
        if n >= 0 then
            start = 1; stop = #t; step = 1
        else
            start = #t; stop = 1; step = -1
        end
    
        if n == 0 then
            for i = start, stop, step do
                if t[i] == val then t[i] = t[i] + 1 end
            end
        else
            break_point = math.abs(n)
            count = 0
            for i = start, stop, step do
                if count == break_point then break end
    
                if t[i] == val then
                    t[i] = t[i] + 1
                    count = count + 1
                end
            end
        end
    
        return t
    end

There are no comments on this comment yet.