I hope I do not understand the problem ... Here is the solution in SWI-Prolog
:- module(subsets, [solve/0]). :- [library(pairs), library(aggregate)]. solve :- problem(R, K, Subsets), once(subset_of_maximal_number(R, K, Subsets, Subset)), writeln(Subset). problem(4, 2, [[1,2,3], [1,2,3], [1,2,4], [1,3,4]]). problem(8, 3, [[1, 3, 4, 6], [2, 6, 7, 8], [3, 5, 6, 7], [2, 4, 6, 7], [1, 4, 5, 8], [2, 4, 6, 8], [1, 2, 3, 8], [1, 6, 7, 8], [1, 2, 4, 7], [1, 2, 5, 7]]). subset_of_maximal_number(R, K, Subsets, Subset) :- flatten(Subsets, Numbers), findall(Num-Count, ( between(1, R, Num), aggregate_all(count, member(Num, Numbers), Count) ), NumToCount), transpose_pairs(NumToCount, CountToNumSortedR), reverse(CountToNumSortedR, CountToNumSorted), length(Subset, K), % list of free vars prefix(SolutionsK, CountToNumSorted), pairs_values(SolutionsK, Subset).
test output:
?- solve. [1,3] true ; [7,6,2] true.
edit: I think the above solution is wrong, in the sense that the return could not be a subset of any of the input: here is a (commented) solution without this problem:
:- module(subsets, [solve/0]). :- [library(pairs), library(aggregate), library(ordsets)]. solve :- problem(R, K, Subsets), once(subset_of_maximal_number(R, K, Subsets, Subset)), writeln(Subset). problem(4, 2, [[1,2,3], [1,2,3], [1,2,4], [1,3,4]]). problem(8, 3, [[1, 3, 4, 6], [2, 6, 7, 8], [3, 5, 6, 7], [2, 4, 6, 7], [1, 4, 5, 8], [2, 4, 6, 8], [1, 2, 3, 8], [1, 6, 7, 8], [1, 2, 4, 7], [1, 2, 5, 7]]). subset_of_maximal_number(R, K, Subsets, Subset) :- flatten(Subsets, Numbers), findall(Num-Count, ( between(1, R, Num), aggregate_all(count, member(Num, Numbers), Count) ), NumToCount), % actually sort by ascending # of occurrences transpose_pairs(NumToCount, CountToNumSorted), pairs_values(CountToNumSorted, PreferredRev), % we need higher values first reverse(PreferredRev, Preferred), % empty slots to fill, preferred first length(SubsetP, K), select_k(Preferred, SubsetP), % verify our selection it an actual subset of any of subsets sort(SubsetP, Subset), once((member(S, Subsets), ord_subtract(Subset, S, []))). select_k(_Subset, []). select_k(Subset, [E|R]) :- select(E, Subset, WithoutE), select_k(WithoutE, R).
Test:
?- solve. [1,3] true ; [2,6,7] true.