Skip to content

Commit

Permalink
add: original solution for challenge1 of Pattern12
Browse files Browse the repository at this point in the history
  • Loading branch information
zhiwei-Feng committed May 19, 2021
1 parent dd18336 commit ce147b5
Show file tree
Hide file tree
Showing 2 changed files with 77 additions and 0 deletions.
49 changes: 49 additions & 0 deletions Pattern12 - Bitwise XOR/Challenge1/solution.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package challenge1

/*
Given a binary matrix representing an image, we want to flip the image horizontally, then invert it.
To flip an image horizontally means that each row of the image is reversed. For example, flipping [0, 1, 1] horizontally results in [1, 1, 0].
To invert an image means that each 0 is replaced by 1, and each 1 is replaced by 0. For example, inverting [1, 1, 0] results in [0, 0, 1].
Input: [
[1,0,1],
[1,1,1],
[0,1,1]
]
Output: [
[0,1,0],
[0,0,0],
[0,0,1]
]
Input: [
[1,1,0,0],
[1,0,0,1],
[0,1,1,1],
[1,0,1,0]
]
Output: [
[1,1,0,0],
[0,1,1,0],
[0,0,0,1],
[1,0,1,0]
]
ref: https://leetcode-cn.com/problems/flipping-an-image/
*/

func flipAndInvertImage(image [][]int) [][]int {
if len(image) == 0 {
return [][]int{}
}

s := len(image[0])
for i := 0; i < len(image); i++ {
for j := 0; j < (s+1)/2; j++ {
image[i][j], image[i][s-j-1] = image[i][s-j-1]^1, image[i][j]^1
}
}
return image
}
28 changes: 28 additions & 0 deletions Pattern12 - Bitwise XOR/Challenge1/solution_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package challenge1

import (
"reflect"
"testing"
)

func Test_flipAndInvertImage(t *testing.T) {
type args struct {
image [][]int
}
tests := []struct {
name string
args args
want [][]int
}{
{"case1", args{[][]int{}}, [][]int{}},
{"case2", args{[][]int{{1, 0, 1}, {1, 1, 1}, {0, 1, 1}}}, [][]int{{0, 1, 0}, {0, 0, 0}, {0, 0, 1}}},
{"case3", args{[][]int{{1, 1, 0, 0}, {1, 0, 0, 1}, {0, 1, 1, 1}, {1, 0, 1, 0}}}, [][]int{{1, 1, 0, 0}, {0, 1, 1, 0}, {0, 0, 0, 1}, {1, 0, 1, 0}}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := flipAndInvertImage(tt.args.image); !reflect.DeepEqual(got, tt.want) {
t.Errorf("flipAndInvertImage() = %v, want %v", got, tt.want)
}
})
}
}

0 comments on commit ce147b5

Please sign in to comment.