Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var e = [[5, 7, 8, 6, 3],
- [0, 0, 7, 0, 4],
- [4, 6, 3, 4, 9],
- [3, 1, 0, 5, 8]];
- function maxCarrots(matrix) {
- if (matrix.length == 1 && matrix[0].length == 1) {
- return matrix[0][0];
- } else {
- var center = findCenter(matrix);
- var visited = traverseGarden(matrix, center);
- return visited.reduce(function (a, b) { return a + b; }, 0);
- }
- }
- function findCenter(matrix) {
- var height = matrix.length;
- var width = matrix[0].length;
- var midHeight = Math.floor(height / 2);
- var midWidth = Math.floor(width / 2);
- if (height % 2 == 1 && width % 2 == 1) {
- return [midHeight,midWidth];
- } else if (height % 2 == 1 && width % 2 == 0) {
- if (matrix[midHeight][midWidth] > matrix[midHeight][midWidth - 1]) {
- return [midHeight, midWidth];
- } else {
- return [midHeight, midWidth - 1];
- }
- } else if (height % 2 == 0 && width % 2 == 1) {
- if (matrix[midHeight][midWidth] > matrix[midHeight - 1][midWidth]) {
- return [midHeight, midWidth];
- } else {
- return [midHeight - 1, midWidth];
- }
- } else {
- var maxValues = [matrix[midHeight - 1][midWidth - 1], matrix[midHeight - 1][midWidth], matrix[midHeight][midWidth - 1], matrix[midHeight][midWidth]];
- var maxIndex = maxValues.reduce((maxIndex, curValue, curIndex, maxValues) => curValue > maxValues[maxIndex] ? curIndex : maxIndex, 0);
- switch (maxIndex) {
- case 0:
- return [midHeight - 1, midWidth - 1];
- case 1:
- return [midHeight - 1, midWidth];
- case 2:
- return [midHeight, midWidth - 1];
- case 3:
- return [midHeight, midWidth];
- }
- }
- }
- function traverseGarden(matrix, center) {
- var pos = center;
- var centerValue = matrix[center[0]][center[1]];
- var visited = [centerValue]
- while (findMaxMove(matrix, pos)[0] > 0) {
- var move = findMaxMove(matrix, pos);
- var nextVal = move[0];
- var nextPos = move[1];
- visited.push(nextVal);
- pos = nextPos;
- }
- return visited;
- }
- function findMaxMove(matrix, pos) {
- var x = pos[0];
- var y = pos[1];
- var up = x-1 in matrix && matrix[x - 1][y] ? matrix[x - 1][y] : Number.NEGATIVE_INFINITY;
- var down = x+1 in matrix && matrix[x + 1][y] ? matrix[x + 1][y] : Number.NEGATIVE_INFINITY;
- var left = y-1 in matrix[0] && matrix[x][y - 1] ? matrix[x][y - 1] : Number.NEGATIVE_INFINITY;
- var right = y+1 in matrix[0] && matrix[x][y + 1] ? matrix[x][y + 1] : Number.NEGATIVE_INFINITY;
- var moves = [up, down, left, right];
- var maxMove = moves.reduce((maxIndex, curValue, curIndex, moves) => curValue > moves[maxIndex] ? curIndex : maxIndex, 0);
- var value = moves[maxMove];
- matrix[x][y] = 0
- switch (maxMove) {
- case 0:
- return [value, [x - 1, y]];
- case 1:
- return [value, [x + 1, y]];
- case 2:
- return [value, [x, y - 1]];
- case 3:
- return [value, [x, y + 1]];
- }
- }
- maxCarrots(e)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement