简体   繁体   English

如何在方表中找到一个数字所属的一组数字的索引?

[英]How do I find the index of the group of numbers a number belongs to in a square table?

Here is an 8x8 table of 64 cells, each containing a number这是一个包含64 个单元格的8x8表格,每个单元格包含一个数字

| 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:如果我们在心理上将表格分成 4 个单元格的图块,我们最终会得到:

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 }
  ]
]

You could calculate the index of 2x2 parts.您可以计算 2x2 零件的索引。

 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; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM