Created
May 16, 2020 16:46
-
-
Save fjpse/4151b1dcd1d0c81f459f9f543c868d77 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-module(comb). | |
-export([permutations/1]). | |
%% | |
%% permutations(L): generates a list with all the permutations of the elements of the list. | |
%% | |
%% For each element in the list: | |
%% a) combine this element with the permutations of the rest of the list. | |
%% b) store the results | |
%% | |
-spec permutations([T]) -> [[T]]. | |
permutations([]) -> [[]]; | |
permutations(List) -> permutations(List, List, []). | |
permutations([], _List, Store) -> Store; | |
permutations([Head|Tail], List, Store) -> | |
HeadPermutations = combine(Head, permutations(lists:delete(Head, List))), | |
permutations(Tail, List, Store ++ HeadPermutations). | |
%% | |
%% combine(X, [L]): inserts element X as the head of each list | |
%% | |
-spec combine(T, [[T]]) -> [[T]]. | |
combine(Item, List) -> combine(Item, List, []). | |
combine(_Item, [], Store) -> lists:reverse(Store); | |
combine(Item, [Head|Tail], Store) -> | |
combine(Item, Tail, [[Item|Head] | Store]). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment