From 6bd8e492540bbaf69a3a4638a99b2c41fe4d549b Mon Sep 17 00:00:00 2001 From: Brett Dawidowski Date: Thu, 4 Apr 2019 00:30:29 -0400 Subject: [PATCH] [Matrix] #14 Complete --- exercises/matrix/index.js | 56 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 55 insertions(+), 1 deletion(-) diff --git a/exercises/matrix/index.js b/exercises/matrix/index.js index 13bdc31f82..c28d833b45 100644 --- a/exercises/matrix/index.js +++ b/exercises/matrix/index.js @@ -15,6 +15,60 @@ // [11, 16, 15, 6], // [10, 9, 8, 7]] -function matrix(n) {} +function matrix(n) { + const results = []; + + // Precreate all the empty subarray + for (let i = 0; i < n; i++){ + results.push([]); + } + + // Global Counter Variable + let counter = 1; + + // Start will always at 0 + let startCol = 0; + let startRow = 0; + + // End will always start at n - 1 + let endCol = n - 1; + let endRow = n - 1; + + while (startCol <= endCol && startRow <= endRow) { + + // Building top row + for (let i = startCol; i <= endCol; i++){ + results[startCol][i] = counter; + counter++; + } + startRow++; + + // Building far right col + for (let i = startRow; i <= endRow; i++){ + results[i][endRow] = counter; + counter++; + } + endCol--; + + // Building bottom row + for (let i = endCol; i >= startCol; i--){ + results[endRow][i] = counter; + counter++; + } + endRow--; + + // Building far left col + for (let i = endRow; i >= startRow; i--){ + results[i][startCol] = counter; + counter++; + } + startCol++; + + + + } + + return results; +} module.exports = matrix;