Last active
July 4, 2017 19:47
-
-
Save adleroliveira/839965d3499e2d17500c21e020879449 to your computer and use it in GitHub Desktop.
max square sum problem (functional)
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
const neighbours = (pos, transf) => { | |
const x = pos[0] | |
const y = pos[1] | |
return [[x-1, y-1],[x, y-1],[x+1, y-1],[x-1, y],[x,y],[x+1, y],[x-1, y+1],[x, y+1],[x+1, y+1]].map(transf) | |
} | |
const maxSumRect = (rows, cols, nums) => { | |
const revVirtMatrix = pos => [parseInt(pos / cols), pos % cols] | |
const virtualMatrix = pos => (pos[0] * cols + pos[1]) | |
return nums.reduce((max, val, idx) => { | |
const neighboursPosition = neighbours(revVirtMatrix(idx), virtualMatrix) | |
if(neighboursPosition.some(x => x < 0 || x > nums.length-1)) return max | |
const arraySum = neighboursPosition.reduce((arrSum, i) => arrSum + nums[i], 0) | |
return arraySum > max ? arraySum : max | |
}, 0) | |
} | |
maxSumRect(4, 5, [1,2,-1,-4,-20,-8,-3,4,2,1,3,8,10,1,3,-4,-1,1,7,-6]) // 29 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment