Last active
March 12, 2023 17:34
-
-
Save kraftdorian/c36a23544f3745378db15c40acfd7c1d to your computer and use it in GitHub Desktop.
Transform 2-D array to 1-D array
This file contains hidden or 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
flatten2DList :: [[a]] -> [a] -> [a] | |
flatten2DList (x:[]) acc = acc ++ x | |
flatten2DList (x:xs) acc = flatten2DList xs (acc ++ x) | |
-- or just use concat | |
flatten2DList' :: [[a]] -> [a] | |
flatten2DList' x = concat x |
This file contains hidden or 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
/** | |
* @param {Array<Array<unknown>>} arr 2D array to transform into one-dimensional array | |
* @return {Array<unknown>|null} one-dimensional array if 2D array was provided, null otherwise | |
*/ | |
function mapTo1DArray(arr) { | |
if (arr == null || !Array.isArray(arr) || !Array.isArray(arr[0])) { | |
return null; | |
} | |
const result = new Array(arr[0].length * arr.length); | |
let ptr = 0, | |
yPtr = 0, | |
xPtr = 0; | |
while (ptr < result.length) { | |
result[ptr++] = arr[yPtr][xPtr]; | |
xPtr++; | |
if (xPtr > arr[0].length - 1) { | |
// last column of current row was reached, | |
// reset X pointer to 0 and move to the next row by increasing Y pointer | |
xPtr = 0; | |
yPtr++; | |
} | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment