Problem 26
In how many ways you choose a committee of 3 from a group of 12 people? The combination formula tells us C(12,3) = 220 possibilities.
Write a function to generate all combinations of a list.
combinations 2 ['a', 'b', 'c'] == [['a', 'b'], ['a', 'c'], ['b', 'c']]
Unit Test
import Html
import List
combinations : Int -> List a -> List (List a)
combinations n list =
-- your implementation goes here
[ [] ]
main : Html.Html a
main =
Html.text
<| case test of
0 ->
"Your implementation passed all tests."
1 ->
"Your implementation failed one test."
x ->
"Your implementation failed " ++ (toString x) ++ " tests."
test : Int
test =
List.length
<| List.filter ((==) False)
[ combinations 1 (List.range 1 5) == [ [ 1 ], [ 2 ], [ 3 ], [ 4 ], [ 5 ] ]
, combinations 2 [ 'a', 'b', 'c' ] == [ [ 'a', 'b' ], [ 'a', 'c' ], [ 'b', 'c' ] ]
, combinations 2 (List.range 1 3) == [ [ 1, 2 ], [ 1, 3 ], [ 2, 3 ] ]
, combinations 2 (List.range 1 4) == [ [ 1, 2 ], [ 1, 3 ], [ 1, 4 ], [ 2, 3 ], [ 2, 4 ], [ 3, 4 ] ]
, combinations 0 (List.range 1 10) == [ [] ]
, combinations -1 (List.range 1 10) == [ [] ]
, List.length (combinations 3 (List.range 1 12)) == 220
, List.length (combinations 4 (List.range 1 15)) == 1365
]
Hint
- Combinations of n number of elements can be generated from combinations of n-1.