loading...

Daily Challenge #301 - Array Combos

thepracticaldev profile image dev.to staff ・1 min read

In this challenge, you will be 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.

Examples

For example: solve([[1,2],[4],[5,6]]) = 4, because it results in only 4 possibilities. 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, but the extra outcomes are just duplicates.

Tests

solve([[1,2],[4,4],[5,6,6]])
solve([[1,2],[3,4],[5,6]])
solve([[1,2,3],[3,4,6,6,7],[8,9,10,12,5,6]])

Good luck!


This challenge comes from KenKamau on CodeWars. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!

Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!

Discussion

pic
Editor guide
Collapse
mbaas2 profile image
Michael Baas

A solution in Dyalog APL:
(In APL-Terminology, these "arrays" are called "vectors" and I'm using the default notation for 'em. It would also be possible to pass a JSON-Array, but that'd 5 more characters!)

solve← {×/≢¨∪¨⍵} 
Enter fullscreen mode Exit fullscreen mode

using it:

      solve(1 2)(4)(5 6)
4
      solve(1 2)(4)(5 5 6)
4
      solve(1 2)(4 4)(5 6 6)
4
      solve(1 2)(3 4)(5 6)
8
      solve(1 2 3)(3 4 6 6 7)(8 9 10 12 5 6)
72

Enter fullscreen mode Exit fullscreen mode

Try it online!

Collapse
cipharius profile image
Valts Liepiņš

My solutions in Haskell.

The first solution - inefficient(O(n) = n^3), yet very elegant looking:

import Data.List (nub)

solve :: Eq a => [[a]] -> Int
solve = product . map (length . nub)
Enter fullscreen mode Exit fullscreen mode

Slightly better solution (O(n) = n^2 * log n) using containers library:

import qualified Data.Set as Set

solve :: Ord a => [[a]] -> Int
solve = product . map (Set.size . Set.fromList)
Enter fullscreen mode Exit fullscreen mode

And best solution (O(n) = n^2), but accepts only integers as input:

import qualified Data.IntSet as Set

solve :: [[Int]] -> Int
solve = product . map (Set.size . Set.fromList)
Enter fullscreen mode Exit fullscreen mode
Collapse
peter279k profile image
peter279k

Here is the simple solution with Python:

def solve(arr):
    result = 1
    for sets in arr:
        sets = list(set(sets))
        result *= len(sets) / 1

    return result
Enter fullscreen mode Exit fullscreen mode
Collapse
_bkeren profile image
''

JS

const solve = (arrays) => arrays.map(array => new Set(array).size).reduce((a,b) => a * b)

Enter fullscreen mode Exit fullscreen mode