Skip to content

Instantly share code, notes, and snippets.

@sekky0905
Last active June 15, 2018 03:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sekky0905/c6438f77efd785ac4598c858f8e4dc84 to your computer and use it in GitHub Desktop.
Save sekky0905/c6438f77efd785ac4598c858f8e4dc84 to your computer and use it in GitHub Desktop.
Goで2つのSliceを重複した値を除いて結合する ref: https://qiita.com/Sekky0905/items/3759ce17200f7864a8fd
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}
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 == false { // 存在しない場合は、その値が存在することを示すためにmapに構造体を格納
m[el] = struct{}{}
sliceD = append(sliceD, el)
}
}
return sliceD
}
結合した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