Skip to content

Instantly share code, notes, and snippets.

@rmcvey
Last active May 4, 2016 21:11
Show Gist options
  • Save rmcvey/9332d8af9ef405c557f91a4ecd91329a to your computer and use it in GitHub Desktop.
Save rmcvey/9332d8af9ef405c557f91a4ecd91329a to your computer and use it in GitHub Desktop.
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));
@rmcvey
Copy link
Author

rmcvey commented May 4, 2016

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)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment