August 23, 2024

P26 - Generate the combinations of K distinct objects chosen from the N elements of a list.

In how many ways can a committee of 3 be chosen from a group of 12 people? We all know that there areC(12,3) = 220possibilities (C(N,K)denotes the well-known binomial coefficient). For pure mathematicians, this result may be great. But we want to really generate all the possibilities.

Example:

> p26:combinations(2, [1,2,3,4]).                           
    [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]

erlang

%Generate the combinations of K distinct objects chosen from the N elements of a list.
-module(p26).
-export([combinations/2]).


combinations(0, Ls) ->
    [Ls];

combinations(1, Ls) -> 
    lists:map(fun(X) -> [X] end, Ls);

combinations(_, []) ->
    [];

combinations(N, [Head | Tail]) ->
    Sub = combinations(N-1, Tail),
    lists:map(fun(Sl) -> [Head | Sl] end, Sub) ++ combinations(N, Tail) .

% length(p26:combinations(3, [1,2,3,4,5,6,7,8,9,10,11,12])).
% 220
% 
%
Be first to comment
Leave a reply