This is a challenge from CodeSignal.
For
image = [[1, 1, 1],
[1, 7, 1],
[1, 1, 1]]
the output should be boxBlur(image) = [[1]]
.
To get the value of the middle pixel in the input 3 × 3 square: (1 + 1 + 1 + 1 + 7 + 1 + 1 + 1 + 1) = 15 / 9 = 1.66666 = 1
. The border pixels are cropped from the final result.
For
image = [[7, 4, 0, 1],
[5, 6, 2, 2],
[6, 10, 7, 8],
[1, 4, 2, 0]]
the output should be
boxBlur(image) = [[5, 4],
[4, 4]]
There are four 3 × 3 squares in the input image, so there should be four integers in the blurred output. To get the first value: (7 + 4 + 0 + 5 + 6 + 2 + 6 + 10 + 7) = 47 / 9 = 5.2222 = 5
. The other three integers are obtained the same way, then the surrounding integers are cropped from the final result.
Here's my code:
function boxBlur(image) {
const SQUARE = 3
const outerArr = []
for (let i = 0; i < image.length; i++) {
const innerArr = []
for (let j = 0; j < image[0].length; j++) {
if (image[i][j] !== undefined && image[i][j+2] !== undefined && image[i+2]) {
let sum = 0
for (let k = 0; k < SQUARE; k++) {
for (let y = 0; y < SQUARE; y++) {
sum += image[i+k][j+y]
}
}
innerArr.push(Math.floor(sum/9))
}
}
if (innerArr.length) outerArr.push(innerArr)
}
return outerArr
}
```