The problem
Implement a perform which behaves just like the uniq
command in UNIX.
It takes as enter a sequence and returns a sequence during which all duplicate parts following one another have been diminished to 1 occasion.
Instance:
["a", "a", "b", "b", "c", "a", "b", "c"] => ["a", "b", "c", "a", "b", "c"]
The answer in Golang
Choice 1:
bundle uniq
func Uniq(a []string) []string {
array := []string{}
for i, worth := vary a {
if i == 0 {
array = append(array, worth)
} else if a[i-1] != worth {
array = append(array, worth)
}
}
return array
}
Choice 2:
bundle uniq
func Uniq(a []string) []string {
reply := make([]string, 0, len(a))
for i, str := vary a {
if i == 0 || str != a[i-1] {
reply = append(reply, str)
}
}
return reply
}
Choice 3:
bundle uniq
import "fmt"
func Uniq(a []string) []string {
n := len(a)
if (n == 0) {
return []string{}
}
i := 1
for j := 1; j < n; j++ {
if (a[i] == a[j] || a[i - 1] == a[j]) {
proceed;
} else {
a[i] = a[j]
i++
}
}
fmt.Println(i)
return a[0:i]
}
Check instances to validate our answer
bundle uniq_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("Check Suite", func() {
It("Pattern Checks", func() {
Anticipate(Uniq([]string{"a", "a", "b", "b", "c", "a", "b", "c", "c"})).To(Equal([]string{"a", "b", "c", "a", "b", "c"}))
Anticipate(Uniq([]string{"a", "a", "a", "b", "b", "b", "c", "c", "c"})).To(Equal([]string{"a", "b", "c"}))
Anticipate(Uniq([]string{})).To(Equal([]string{}))
Anticipate(Uniq([]string{"foo"})).To(Equal([]string{"foo"}))
Anticipate(Uniq([]string{"bar"})).To(Equal([]string{"bar"}))
Anticipate(Uniq([]string{""})).To(Equal([]string{""}))
Anticipate(Uniq([]string{"a", "a"})).To(Equal([]string{"a"}))
})
})