Last active
July 3, 2018 11:33
-
-
Save sekky0905/b2acdd568239efb94cc8a74a43a1b892 to your computer and use it in GitHub Desktop.
Goで2つのSliceを重複した値を除いて結合する ref: https://qiita.com/Sekky0905/items/27494a9ed17fdf84dc35
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{1, 2, 3, 4, 5, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5} | |
sliceB := []int{6, 7, 8, 9, 5, 6, 6, 6, 6, 6, 6} |
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() { | |
sliceA := []int{1, 2, 3, 4, 5, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5} | |
sliceB := []int{6, 7, 8, 9, 5, 6, 6, 6, 6, 6, 6} | |
newSlice := MergeWithoutDuplication(sliceA, sliceB) | |
fmt.Printf("sliceAとsliceBを重複しないようにマージ : %#v\n", newSlice) | |
} | |
// MergeWithoutDuplication は、重複を除いて2つのsliceをマージする | |
func MergeWithoutDuplication(sliceA, sliceB []int) []int { | |
// 2つのsliceを結合 | |
sliceC := sliceA[:] | |
sliceC = append(sliceC, sliceB...) | |
fmt.Printf("結合したSliceC : %#v\n", sliceC) | |
sliceD := make([]int, 0) | |
m := make(map[int]struct{}, 0) | |
for _, el := range sliceC { | |
if _, ok := m[el]; !ok { // 存在しない場合は、その値が存在することを示すためにmapに構造体を格納 | |
m[el] = struct{}{} | |
sliceD = append(sliceD, el) | |
} | |
} | |
return sliceD | |
} |
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
結合したSliceC : []int{1, 2, 3, 4, 5, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 6, 7, 8, 9, 5, 6, 6, 6, 6, 6, 6} | |
sliceAとsliceBを重複しないようにマージ : []int{1, 2, 3, 4, 5, 6, 7, 8, 9} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment