Tuesday, April 23, 2024
HomeSoftware EngineeringThe way to Reimplement the Unix Uniq Command in Golang

The way to Reimplement the Unix Uniq Command in Golang


The problem

Implement a perform which behaves just like the uniq command in UNIX.

It takes as enter a sequence and returns a sequence wherein all duplicate components following one another have been lowered to 1 occasion.

Instance:

["a", "a", "b", "b", "c", "a", "b", "c"]  =>  ["a", "b", "c", "a", "b", "c"]

The answer in Golang

Possibility 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
}

Possibility 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
}

Possibility 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]
}

Take a look at circumstances to validate our answer

bundle uniq_test
import (
  . "github.com/onsi/ginkgo"
  . "github.com/onsi/gomega"
)
var _ = Describe("Take a look at Suite", func() {
  It("Pattern Checks", func() {
    Count on(Uniq([]string{"a", "a", "b", "b", "c", "a", "b", "c", "c"})).To(Equal([]string{"a", "b", "c", "a", "b", "c"}))
    Count on(Uniq([]string{"a", "a", "a", "b", "b", "b", "c", "c", "c"})).To(Equal([]string{"a", "b", "c"}))
    Count on(Uniq([]string{})).To(Equal([]string{}))
    Count on(Uniq([]string{"foo"})).To(Equal([]string{"foo"}))
    Count on(Uniq([]string{"bar"})).To(Equal([]string{"bar"}))
    Count on(Uniq([]string{""})).To(Equal([]string{""}))
    Count on(Uniq([]string{"a", "a"})).To(Equal([]string{"a"}))
  })
})
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments