Created
October 17, 2023 14:47
-
-
Save UniBreakfast/6f9bcfdf03ab02b1fa95ee77fbec8ecc to your computer and use it in GitHub Desktop.
A function to build two-dimensional array of sequential numbers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
buildMatrix(3, 4, 5, 'right-up') | |
// [ | |
// [1, 2, 3, 4], | |
// [2, 3, 4, 5], | |
// [3, 4, 5, 6], | |
// ] | |
function buildMatrix0(rCount, cCount, countStart, direction) { | |
const [first, then] = direction.split('-') | |
const matrix = Array(rCount).fill().map(() => []) | |
const counts = {r: rCount, c: cCount} | |
const i = {} | |
let [d1, d2] = ['up', 'down'].includes(first) | |
? ['c', 'r'] : ['r', 'c'] | |
for (i[d1] = 0; i[d1] < counts[d1]; i[d1]++) | |
for (i[d2] = 0; i[d2] < counts[d2]; i[d2]++) | |
matrix[i.r][i.c] = countStart++ | |
if ([first, then].includes('up')) matrix.reverse() | |
if ([first, then].includes('left')) matrix.forEach(row => row.reverse()) | |
return matrix | |
} | |
function buildMatrix(rCount, cCount, countStart, direction) { | |
const matrix = [] | |
const calc = getCalc(countStart, direction, rCount, cCount) | |
for (let r = 0; r < rCount; r++) { | |
matrix[r] = [] | |
for (let c = 0; c < cCount; c++) { | |
matrix[r][c] = calc(r, c) | |
} | |
} | |
return matrix | |
} | |
function getCalc(start, dir, rCount, cCount) { | |
return dir == 'right-down' ? (r, c) => start + r * cCount + c | |
: dir == 'right-up' ? (r, c) => start + (rCount - r - 1) * cCount + c | |
: dir == 'left-up' ? (r, c) => start + (rCount - r - 1) * cCount + (cCount - c - 1) | |
: dir == 'left-down' ? (r, c) => start + r * cCount + (cCount - c - 1) | |
: dir == 'down-right' ? (r, c) => start + c * rCount + r | |
: dir == 'down-left' ? (r, c) => start + c * rCount + (rCount - r - 1) | |
: dir == 'up-left' ? (r, c) => start + (cCount - c - 1) * rCount + (rCount - r - 1) | |
: dir == 'up-right' ? (r, c) => start + (cCount - c - 1) * rCount + r | |
: null | |
} | |
const directions = [ | |
'right-down', | |
'right-up', | |
'left-up', | |
'left-down', | |
'down-right', | |
'down-left', | |
'up-left', | |
'up-right', | |
] | |
for (const direction of directions) { | |
console.log(direction) | |
console.log(buildMatrix(3, 4, 5, direction)) | |
console.log() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment