Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

169
Visualizações
How to translate matrix list index into matrix coords?

Say you have a 2d matrix:

const matrix = [
  [0, 1, 2, 3, 4, 5],
  [0, 1, 2, 3, 4, 5]
];

Which is represented as a list:

const list = [0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5];

You can easily generate the list index in the list using the following:

function coordsToListIndex({ x, y }, width) {
    return x + (y * width);
}

// index = 7
const index = coordsToListIndex({ x: 1, y: 1 }, 6);

What is the best way to translate in the opposite direction, from list index to coordinates?

What I've come up with is as follows, but I suspect there could be a better way.

function listIndexToCoords(index, width) {

    let count = 0;
    let x = 0;
    let y = 0;
    for (let i = 0; i < width; i++) {
        count++;
        x++;
        if (count === index) {
            break;
        } else if (i == width - 1) {
            x = 0;
            y++;
            i = 0;
        }
    }

    return {
        x,
        y
    };
}

// cords = { x: 1, y: 1 }
const coords = listIndexToCoords(7, 6);
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Based on input and solutions from
Mike 'Pomax' Kamermans and shawn_halayka in the comments above.

function coordsToListIndex({ x, y }, width) {
    return x + (y * width);
}

function listIndexToCoords(index, width) {
    return {
        x: index % width,
        y: Math.floor(index / width)
    };
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda