Created
July 9, 2018 07:09
-
-
Save sekky0905/7d27fa4831c1a2cc1f68c0f4b9b8c049 to your computer and use it in GitHub Desktop.
Goで2つのSlice(A、B)のうち、Aにだけ存在し、Bには存在しない値を持ったSliceを生成する ref: https://qiita.com/Sekky0905/items/1afa6a78f0aa7354f290
This file contains 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
s1 := []int{1, 2, 3, 4} | |
s2 := []int{1, 5, 6, 7} |
This file contains 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
package main | |
import "fmt" | |
func main() { | |
slice1 := []int{1, 2, 3, 4} | |
slice2 := []int{1, 5, 6, 7} | |
newSliceA := CheckNumIncludedOnlyOneSide(slice1, slice2) | |
fmt.Printf("sliceA = %#v\n", newSliceA) | |
slice3 := []int{1, 2, 3, 4} | |
slice4 := []int{5, 6, 7, 8} | |
newSliceB := CheckNumIncludedOnlyOneSide(slice3, slice4) | |
fmt.Printf("sliceB = %#v\n", newSliceB) | |
slice5 := []int{1, 2, 3, 4, 4, 4, 4, 4} | |
slice6 := []int{1, 1, 5, 6, 7} | |
newSliceC := CheckNumIncludedOnlyOneSide(slice5, slice6) | |
fmt.Printf("sliceC = %#v\n", newSliceC) | |
slice7 := []int{1, 2, 3, 4} | |
slice8 := []int{1, 2, 5, 6, 7} | |
newSliceD := CheckNumIncludedOnlyOneSide(slice7, slice8) | |
fmt.Printf("sliceD = %#v\n", newSliceD) | |
} | |
// CheckNumIncludedOnlyOneSide は、sliceAには含まれているが、sliceBには含まれていない値を持ったsliceを返す | |
func CheckNumIncludedOnlyOneSide(sliceA, sliceB []int) []int { | |
newSlice := []int{} | |
for _, a := range sliceA { | |
// 重複してるかどうかのフラグ | |
isDuplicated := false | |
for _, b := range sliceB { | |
if a == b { // sliceAとsliceBの要素が同じものだったら、フラグをtrueに | |
isDuplicated = true | |
} | |
} | |
if !isDuplicated { // フラグをfalseのものは、newSliceに追加 | |
newSlice = append(newSlice, a) | |
} | |
} | |
return newSlice | |
} |
This file contains 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
sliceA = []int{2, 3, 4} | |
sliceB = []int{1, 2, 3, 4} | |
sliceC = []int{2, 3, 4, 4, 4, 4, 4} | |
sliceD = []int{3, 4} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment