/
dedup.go
57 lines (48 loc) · 1016 Bytes
/
dedup.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package main
import (
"fmt"
"os"
"strings"
)
type dedupfn func([]string) []string
func dedupInplace(seq []string) []string {
if len(seq) == 0 {
return seq
}
i := 0
for _, s := range seq[1:] {
if seq[i] == s {
continue
}
i++
seq[i] = s
}
// Here is we keep all source slice in memory. Need to copy or append to
// new one to deacrease memory usage and to allow GC perform clean up.
// See bellow function for such solutions.
return seq[:i+1]
}
func dedupAppend(s []string, fn dedupfn) []string {
return append([]string{}, fn(s)...)
}
func dedupCopy(s []string, fn dedupfn) []string {
result := make([]string, len(s))
copy(result, fn(s))
return result
}
func remove(seq []string, i int) []string {
return seq[:i+copy(seq[i:], seq[i+1:])]
}
func dedupRemove(seq []string) []string {
for i := 0; i < len(seq)-1; {
if seq[i] == seq[i+1] {
seq = remove(seq, i+1)
} else {
i++
}
}
return seq
}
func main() {
fmt.Println(strings.Join(dedupInplace(os.Args[1:]), " "))
}