|
| 1 | +# JavaScript Flipping An Image |
| 2 | + |
| 3 | +## Challenge: |
| 4 | + |
| 5 | +Given an `n x n` binary matrix `image`, flip the image horizontally, then invert it, and return the resulting image. |
| 6 | + |
| 7 | +To flip an image horizontally means that each row of the image is reversed. |
| 8 | +<br/> |
| 9 | + |
| 10 | +* For example, flipping `[1,1,0]` horizontally results in `[0,1,1]`. |
| 11 | + |
| 12 | +To invert an image means that each `0` is replaced by `1`, and each `1` is replaced by `0`. |
| 13 | +<br/> |
| 14 | + |
| 15 | +* For example, inverting `[0,1,1]` results in `[1,0,0]`. |
| 16 | + |
| 17 | +### 1<sup>st</sup> Example: |
| 18 | + |
| 19 | +`Input: image = [[1,1,0],[1,0,1],[0,0,0]]` |
| 20 | +<br/> |
| 21 | +`Output: [[1,0,0],[0,1,0],[1,1,1]]` |
| 22 | +<br/> |
| 23 | +`Explanation: First reverse each row: [[0,1,1],[1,0,1],[0,0,0]].` |
| 24 | +<br/> |
| 25 | +`Then, invert the image: [[1,0,0],[0,1,0],[1,1,1]]` |
| 26 | + |
| 27 | +### 2<sup>nd</sup> Example: |
| 28 | + |
| 29 | +`Input: image = [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]]` |
| 30 | +<br/> |
| 31 | +`Output: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]` |
| 32 | +<br/> |
| 33 | +`Explanation: First reverse each row: [[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]].` |
| 34 | +<br/> |
| 35 | +`Then invert the image: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]` |
| 36 | + |
| 37 | +### Constraints: |
| 38 | + |
| 39 | +`n == image.length` |
| 40 | +<br/> |
| 41 | +`n == image[i].length` |
| 42 | +<br/> |
| 43 | +`1 <= n <= 20` |
| 44 | +<br/> |
| 45 | +`images[i][j]` is either `0` or `1`. |
| 46 | + |
| 47 | +## Solution: |
| 48 | + |
| 49 | +`const flipAndInvertImage = (image) => {` |
| 50 | +<br/> |
| 51 | + `for(let row in image) {` |
| 52 | +<br/> |
| 53 | + `image[row] = image[row].reverse();` |
| 54 | +<br/> |
| 55 | + `image[row] = image[row].map(x=>1-x);` |
| 56 | +<br/> |
| 57 | + `}` |
| 58 | +<br/> |
| 59 | +<br/> |
| 60 | + `return image;` |
| 61 | +<br/> |
| 62 | +`};` |
| 63 | +<br/> |
| 64 | +<br/> |
0 commit comments