E
E
Ensiouel2018-09-27 14:36:39
Lua
Ensiouel, 2018-09-27 14:36:39

How can I find the coordinates of a number?

How do I find in which column and column to be, for example, the number 4

array = {
    1,2,3,
    4,5,6,
    7,8,9
  }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
dollar, 2018-09-27
@Ensiouel

Obviously the number 4 is in the first column (x==1) and the second row (y==2).
This is visible to the naked eye.
This can be done programmatically like this:

array = {
    1,2,3,
    4,5,6,
    7,8,9
}

function getXY(num)
    local x,y,i=1,1,1
    while array[i] ~= num do
        i = i + 1
        x = x + 1
        if x > 3 then
            x = 1
            y = y + 1
        end
        if not array[i] then return end
    end
    return x,y
end

print(getXY(4)) --1,2
print(getXY(8)) --2,3
print(getXY(3)) --3,1

And if you need an inverse problem (look for a number by coordinates), then here:
array = {
    1,2,3,
    4,5,6,
    7,8,9
}

function find(x,y)
    return array[(y-1)*3 + x]
end

print(find(1,2)) --4
print(find(2,3)) --8
print(find(3,1)) --3

But still it is better to reconsider the way data is stored. For example, like this:
array = {
    { 1,2,3 },
    { 4,5,6 },
    { 7,8,9 },
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question