Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

More effective Lua way of this algorithm?

edited July 2013 in General Posts: 7

Hi,

every programming language has it's best way of implementing things. Looking at my rather standard/basic implementarion of this 'every one with everyone in both ways' I would like to know if there is a best Lua way for this?

flubs ={1,2,3,4,5}

max = (#flubs*(#flubs-1))
print(max)
c = 1 -- only for loopcount
for i=1, #flubs do
    local k = i + 1
    for y = 1, #flubs-1 do
        if (k>#flubs) then k=1 end
        print(c .. ": " .. flubs[i] .. " - " .. flubs[k])
        k = k + 1
        c = c + 1 -- only for loopcount
    end
end

Many thanks

Tagged:

Comments

  • IgnatzIgnatz Mod
    edited July 2013 Posts: 5,396

    You're looking for all pair combinations.

    I'm not sure there's any special Lua way, but I would have just done this

    flubs ={1,2,3,4,5}
    max = (#flubs*(#flubs-1))
    print(max)
    for i=1, #flubs do
        for k = 1, #flubs do
            if (i~=k) then print(c .. ": " .. flubs[i] .. " - " .. flubs[k]) end
        end
    end
    
  • Posts: 7

    Wow, I don't know if this is the best Lua way, but it surely is much cleaner than my code.
    Thanks!

  • Posts: 22

    If you want to use more lua functionality instead of just two simple loops, you could do something like this. It's not more efficient, just looks nicer when you actually use it:

    function mypairs(t)
        return coroutine.wrap(function() 
            local c = 1
            for i = 1, #t do
                for j = 1, #t do
                    if t[i] ~= t[j] then
                        coroutine.yield(c, t[i]..t[j])
                        c = c + 1
                    end
                end
            end
        end)
    end
    
    flubs = {1, 2, 3, 4, 5}
    for i, v in mypairs(flubs) do print(i..":", v) end
    

    Lua lacks functionality other languages have that make things like this look more elegant, but that doesn't mean two for loops are less efficient than a call to a complex library function.

  • Posts: 7

    Nahhh, I think I'll stick with Ignatzs' version ;) Nice and small and I understood it directly. Yours looks very interesting though, with some unknown things I'll have to check. 'coroutine.wrap' and '.yield'. Thanks for giving me learning material.

Sign In or Register to comment.