これはあなたが特に探している解決策ではないかもしれませんが、この質問のタイトルと一致するため、解決策を探している他の人にとっては役立つと思います.
仮定:
- コンテナのサイズは 3 x 3 セル
- 細胞の大きさは同じ
- 行よりも列番号でセルを参照します(最初に水平に配置し、次に垂直に配置します)
- コンテナ内の占有スペースに関する情報を含むオブジェクトがあります(「占有」と呼びましょう)。私の例では、各最終エントリはコンテンツの水平サイズを保持する「幅」プロパティを持つオブジェクトを保持します (私はそれらを「タイル」と呼びます) が、これはエントリに直接割り当てられたフラットな整数である可能性もあります。
コンテンツの例:
occupancy[0][1] = {width: 1};
occupancy[1][0] = {width: 1};
occupancy[1][1] = {width: 2};
occupancy[2][2] = {width: 1};
したがって、占有率は次のようになります (「x」は占有を意味します)。
| - | x | - |
| x | x | x |
| - | - | x |
実装:
const COLUMNS_COUNT = 3;
const MAX_ROWS = 3;
const tilesGroupedByRowColumn = {
'0': {'1': {width: 1}},
'1': {'0': {width: 1}},
'1': {'1': {width: 2}},
'2': {'2': {width: 1}},
}
let getTileOccupancyAreasMatrix = function () {
let tileOccupancyAreasMatrix = {};
for (let row = 0; row < MAX_ROWS; row++) {
for (let column = 0; column < COLUMNS_COUNT; column++) {
if (typeof tileOccupancyAreasMatrix[row] === 'undefined') {
tileOccupancyAreasMatrix[row] = {};
}
if (tileOccupancyAreasMatrix[row][column] === 1) {
// columns have been marked used by some previous iteration,
// that was handling tiles extending to more than 1 column width
continue;
}
if (typeof tilesGroupedByRowColumn[row] === 'undefined'
|| typeof tilesGroupedByRowColumn[row][column] === 'undefined') {
tileOccupancyAreasMatrix[row][column] = 0;
continue;
}
let tileWidth = tilesGroupedByRowColumn[row][column].width;
let tileHeight = tilesGroupedByRowColumn[row][column].height;
// code below also handles the case when tile extends to next rows and column(s)
for (let rowNumber = row; rowNumber < row + tileHeight; rowNumber++) {
if (typeof tileOccupancyAreasMatrix[rowNumber] === 'undefined') {
tileOccupancyAreasMatrix[rowNumber] = {};
}
for (let columnNumber = column; columnNumber < column + tileWidth; columnNumber++) {
tileOccupancyAreasMatrix[rowNumber][columnNumber] = 1;
}
}
}
}
return tileOccupancyAreasMatrix;
},
ソリューションは、どのサイズのコンテナーでも機能するはずです。例を簡単にするために、3x3 の例を示しました。
最終的な解決策は、おそらく事前定義された定数に依存するよりもパラメーターを受け入れる必要があります-私の例は、フレームワークデータを読み取る Vue 実装からのものであるため、パラメーターは必要ありませんでした。