Last active
August 26, 2022 19:30
-
-
Save imfeng/a47de31517d56f78c2282e5b56b283c0 to your computer and use it in GitHub Desktop.
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
const rows = 3; | |
const columns = 2; | |
console.log('1. Recursive version'); | |
recusive2DArray(rows, columns, (i, j) => console.log(i, j)); | |
console.log('2. While loop version'); | |
while2DArray(rows, columns, (i, j) => console.log(i, j)); | |
console.log('3. For loop version'); | |
forloop2DArray(rows, columns, (i, j) => console.log(i, j)); | |
console.log('4. yield version'); | |
for(let [i, j] of twoDGenerator(rows, columns)) { | |
console.log(i, j); | |
} | |
function recusive2DArray(rows, cols, func, i = 0, j = 0) { | |
func(i, j); | |
if(j + 1 < cols) { | |
return recusive2DArray(rows, cols, func, i, j + 1); | |
} | |
if(i + 1 < rows) { | |
return recusive2DArray(rows, cols, func, i + 1, 0); | |
} | |
} | |
function while2DArray(rows, cols, func) { | |
let count = rows * cols; | |
while(count--) { | |
const i = Math.floor(count / cols); | |
const j = count % cols; | |
func(i, j); | |
} | |
} | |
function forloop2DArray(rows, cols, func) { | |
for(let i = 0; i < rows; i++) { | |
for(let j = 0; j < cols; j++) { | |
func(i, j); | |
} | |
} | |
} | |
function *twoDGenerator(rows, cols, i=0, j=0) { | |
j >= cols | |
? ((i + 1 >= rows) ? 0 : yield *twoDGenerator(rows, cols, i + 1, 0)) | |
: ((yield [i, j]) || (yield *twoDGenerator(rows, cols, i, j + 1))); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment