Home > Back-end >  How do I find the index of the group of numbers a number belongs to in a square table?
How do I find the index of the group of numbers a number belongs to in a square table?

Time:10-25

Here is an 8x8 table of 64 cells, each containing a number

| 0| 1| 2| 3| 4| 5| 6| 7|
| 8| 9|10|11|12|13|14|15|
|16|17|18|19|20|21|22|23|
|24|19|20|21|22|23|24|25|
|32|33|34|35|36|37|38|39|
|40|41|42|43|44|45|46|47|
|48|49|50|51|52|53|54|55|
|56|57|58|59|60|61|62|63|

If we mentally split the table into tiles of 4 cells each we will end up with:

index:0    index:1      index:12  index:15
| 0| 1|    | 2| 3|      |48|49|   |54|55|
| 8| 9| ,  |10|11| .... |56|57| , |62|63|

I want to create a method that based on the number passed to it it will return the index of the tile this number belongs to.

getTileIndexFor(8, ...)  // returns 0
getTileIndexFor(11, ...) // returns 1
getTileIndexFor(62, ...) // returns 15
getTileIndexFor(55, ...) // returns 15
etc..

Here's what I have so far:

function getTileIndexFor(number, ...) { 
  // ????
}
 
let tiles = [/* an array of tiles, each tile itself being an array of { numberWithCoords } */]
let numbersPerTileSide  = 2 // i.e. a 4x4 tile (should also work with any multiple of 2)
let numbersPerTableSide = 8 // should also work with any multiple of {numbersPerTileSide}

// making a 8x8 table of numbers from 0 to 63
let tableOfNumbers = [...Array(numbersPerTableSide * numbersPerTableSide).keys()]
    
tableOfNumbers.forEach((index) => {
    let x = index % numbersPerTableSide
    let y = Math.floor(index / numbersPerTableSide)

    // get current number alongs with its x & y in the table
    let numberWithCoords = { number: index, x, y  }

    let tileIndex = getTileIndexFor(number, ...)

    // if tile doesn't exist create it
    tiles[tileIndex] = tiles[tileIndex] || []

    // push current number into the correct tile
    tiles[tileIndex].push(numberWithCoords) 
})

console.log(tiles)

should log:

[
  [
    { number: 0, x: 0, y: 0 },
    { number: 1, x: 1, y: 0 },
    { number: 8, x: 0, y: 1 },
    { number: 9, x: 1, y: 1 }
  ],
  ....,
  [
    { number: 54, x: 6, y: 6 },
    { number: 55, x: 7, y: 6 },
    { number: 62, x: 6, y: 7 },
    { number: 63, x: 7, y: 7 }
  ]
]

CodePudding user response:

You could calculate the index of 2x2 parts.

function getIndex(i) {
    let col = Math.floor(i / cellCols) % (cols / cellCols),
        row = Math.floor(i / (rows * cellRows));

    return col   row * (rows / cellRows);
}

const
    result = []
    cols = 8,
    rows = 8,
    cellCols = 2,
    cellRows = 2;

for (let y = 0; y < rows; y  ) {
    for (let x = 0; x < cols; x  ) {
        const number = y * cols   x;
        (result[getIndex(number)] ??= []).push({ number, x, y });
    }
}

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related