Home Software Engineering Easy methods to Take away Duplicates in an Array in Golang

Easy methods to Take away Duplicates in an Array in Golang

0
Easy methods to Take away Duplicates in an Array in Golang

[ad_1]

The problem

Take away the left-most duplicates from a listing of integers and return the end result.

// Take away the three's at indices 0 and three
// adopted by eradicating a 4 at index 1
clear up([3, 4, 4, 3, 6, 3]); // => [4, 6, 3]

The answer in Golang

Possibility 1:

package deal answer 

func Clear up(arr []int) (res []int) {
    visited := map[int]bool{}
    for i := len(arr) - 1; i >= 0; i-- {
        n := arr[i]
        if visited[n] { proceed }
      
        visited[n] = true
        res = append([]int{n}, res...)
    }
  
    return
}

Possibility 2:

package deal answer 

func Clear up(arr []int) []int {
  counts := make(map[int]bool)
  for _,x := vary arr {
    counts[x]=true
  }
  end result := make([]int,len(counts))
  j := len(end result)-1
  for i := len(arr)-1; i>=0; i-- {
    if counts[arr[i]] {
      counts[arr[i]] = false;
      end result[j] = arr[i]
      j--
    }
  }
  return end result
}

Possibility 3:

package deal answer 

func Clear up(a []int) (r[]int) {
  m:=map[int]int{}
  for _,v:=vary a{ m[v]++ }
  for _,v:=vary a{
    if m[v]==1{
      r=append(r,v)
    }
    m[v]--
  }
  return
}

Check circumstances to validate our answer

package deal our_test

import (
  . "github.com/onsi/ginkgo"
  . "github.com/onsi/gomega"
  . "codewarrior/kata"
)

func dotest(arr , exp []int) {
    var ans = Clear up(arr)
    Anticipate(ans).To(Equal(exp))
}

var _ = Describe("Instance assessments", func() {
  It("It ought to work for primary assessments", func() {       
        dotest([] int{3,4,4,3,6,3}, []int{4,6,3})
        dotest([] int{1,2,1,2,1,2,3}, []int{1,2,3})    
        dotest([] int{1,2,3,4}, []int{1,2,3,4})
        dotest([] int{1,1,4,5,1,2,1}, []int{4,5,2,1})
        dotest([] int{1,2,1,2,1,1,3}, []int{2,1,3})
        dotest([] int{0,4,4,3,0,3}, []int{4,0,3})       
  })
})

[ad_2]

LEAVE A REPLY

Please enter your comment!
Please enter your name here