Reputation:
Okay, so if I have this:
var array = ["1", "2", "3", "4", "5", "6", "7", "8", "9"];
And what I want is to sum:
1 + 2 + 3 && 1 + 4 + 7 && 1 + 5 + 9
Like in tic tac toe, so my question is how can I do that without filling my code with 300 lines of code?
Upvotes: 1
Views: 77
Reputation: 2155
Assuming the array is always 9 entries, this is easiest done by identifying the indexes manually. The indexes are 0...8:
0 1 2
3 4 5
6 7 8
We can then model the rows, columns and diagonals as such:
const rows = [
[0, 1, 2], //Top row
[3, 4, 5], //Middle row
[6, 7, 8] //Bottom row
];
const columns = [
[0, 3, 6], //Left column
[1, 4, 7], //Middle column
[2, 5, 8] //Right column
];
const bsDiag = [0, 4, 8]; //Backslash diagonal "\"
const fsDiag = [6, 4, 2]; //Forward slash diagonal "/"
Then extract the sums from the array array
:
const rowSums = rows.map((row, index) => array[row[0]] + array[row[1]] + array[row[2]]);
const columnSums = columns.map((col, index) => array[col[0]] + array[col[1]] + array[col[2]]);
const bsDiagSum = array[bsDiag[0]] + array[bsDiag[1]] + array[bsDiag[2]]
const fsDiagSum = array[fsDiag[0]] + array[fsDiag[1]] + array[fsDiag[2]]
And now you can print your results with
rowSums.forEach((sum, index) => console.log(`Row ${index + 1} has sum: ${sum}`));
columnSums.forEach((sum, index) => console.log(`Column ${index + 1} has sum: ${sum}`));
console.log(`Backslash diagonal has sum ${bsDiagSum}`);
console.log(`Forward slash diagonal has sum ${fsDiagSum}`);
In your question your array had string values, rather than numbers. This answer assumes the array contains numbers. I'll leave the conversion from strings to numbers as a google exercise.
Upvotes: 1
Reputation: 386650
You could take two arrays with the start values of row and column and take the sum as index for calculating the wanted sum.
15 / 1 2 3 | 6 4 5 6 | 15 7 8 9 | 24 --- --- --- \ 12 15 18 15
var array = ["1", "2", "3", "4", "5", "6", "7", "8", "9"],
rows = [0, 3, 6].map(i => [0, 1, 2].reduce((s, j) => s + +array[i + j], 0)),
cols = [0, 1, 2].map(i => [0, 3, 6].reduce((s, j) => s + +array[i + j], 0)),
slash = [0, 4, 8].reduce((s, i) => s + +array[i], 0),
backslash = [2, 4, 6].reduce((s, i) => s + +array[i], 0);
console.log(rows); // -
console.log(cols); // |
console.log(slash); // /
console.log(backslash); // \
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 1