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



这是一个8x864表单元格,每个单元格包含一个数字

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

如果我们把表格分成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|

我想创建一个方法,根据传递给它的数字它将返回瓷砖的索引这个号码属于。

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

到目前为止我写的是:

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)

应该日志:

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

可以计算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; }

相关内容

  • 没有找到相关文章

最新更新