Forming Unique Array Combinations in Golang

1 min read 285 words

The challenge

You are given an array of arrays and your task will be to return the number of unique arrays that can be formed by picking exactly one element from each subarray.

For example: solve([[1,2],[4],[5,6]]) = 4, because it results in only 4 possibilites. They are [1,4,5],[1,4,6],[2,4,5],[2,4,6].

Make sure that you don’t count duplicates; for example solve([[1,2],[4,4],[5,6,6]]) = 4, since the extra outcomes are just duplicates.

The solution in Golang

Option 1:

package solution
func Solve(data [][]int) int {
  qtd := 1
  for _, sss := range data {
    mp := make(map[int]bool)
    for _, e := range sss {
      mp[e] = true
    }
    qtd *= len(mp)
  }
  return qtd
}

Option 2:

package solution
func Solve(data [][]int) int {
  res := 1
  for _, d := range data{
    cnt := 0
    dup := make(map[int]int)
    for _, n := range d {
      if dup[n] == 0 {
        cnt++
        dup[n] = 1
      }
    }
    res *= cnt
  }
  return res
}

Option 3:

package solution
func Solve(data [][]int) int {
  sets := make([]map[int]bool, len(data))
  for i := 0; i < len(data); i++ {
    sets[i] = make(map[int]bool, len(data[i]))
    for _, v := range data[i] {
      sets[i][v] = true
    }
  }
  result := 1
  for _, s := range sets {
    result *= len(s)
  }
  return result
}

Test cases to validate our solution

package solution_test
import (
  "math/rand"
  "time"
  . "github.com/onsi/ginkgo"
  . "github.com/onsi/gomega"
)
func init() {
  rand.Seed(time.Now().UTC().UnixNano())
}
var _ = Describe("Sample Tests", func() {
  It("should work with sample tests", func() {
    Expect(Solve([][]int{{1, 2}, {4}, {5, 6}})).To(Equal(4))
    Expect(Solve([][]int{{1, 2}, {4, 4}, {5, 6, 6}})).To(Equal(4))
    Expect(Solve([][]int{{1, 2}, {3, 4}, {5, 6}})).To(Equal(8))
    Expect(Solve([][]int{{1, 2, 3}, {3, 4, 6, 6, 7}, {8, 9, 10, 12, 5, 6}})).To(Equal(72))
  })
})
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags

Recent Posts