Last active
May 4, 2016 21:11
-
-
Save rmcvey/9332d8af9ef405c557f91a4ecd91329a to your computer and use it in GitHub Desktop.
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
input = [ | |
[1,2,3], | |
[4,5,6], | |
[7,8,9], | |
] | |
input2 = [ | |
[1, 2, 3, 4], | |
[5, 6, 7, 8], | |
[9, 10, 11, 12], | |
[13, 14, 15, 16] | |
] | |
output = [ | |
[1], | |
[4,2], | |
[7,5,3], | |
[8,6], | |
[9], | |
] | |
const getDiagonals = (matrix) => { | |
const l = matrix[0].length; | |
const n = l * 2 - 1; | |
const output = []; | |
const mid = Math.ceil(n / 2); | |
const count = 0; | |
for (let i = 0; i < n; i++) { | |
let x = i < l ? i : l - 1; | |
let y = i < l ? 0 : i - l + 1; | |
let z = (i < mid ? i : n % (i+1)) + 1; | |
let diags = []; | |
for (let j = 0; j < z; j++) { | |
diags.push(matrix[x--][y++]); | |
} | |
output.push(diags); | |
} | |
return output; | |
} | |
console.log(getDiagonals(input)); | |
console.log(getDiagonals(input2)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Github isn't respecting my request to use 2 spaces instead of tabs, so I apologize for the formatting (also, count variable is unnecessary, but I didn't want to update this a bunch)