function settheorydemo(N,K)
%function settheorydemo(N,K)
% N elements with K subsets
% Some set theory with matlab on finite sets

showN = min(N,8);%don't get too big to print out
U =[1:N];%My Universe
disp('BEGIN with a finite Universe:')
N
disp(' ')

%Let's paritition into K subsets
%With probability 1/K

subs = ceil(K*rand(1,N));%random 1xN row
subs
disp(' ')
disp('Some typical subset membership (element/subset)')
disp(' ')
disp( [U(1:showN);subs(1:showN)] );

disp(' ')
disp('Display the members of two subsets ')
disp(' ')

Subset1 = U(subs==1);
Subset1
Subset2 = U(subs==2);
Subset2

disp('Merge Subsets 1 and 2 into Subset12')
disp(' ')
Subset12 = union(U(subs==1),U(subs==2));
Subset12

disp('Recover Subset 1 by Set Difference');
disp(' ')
Subsetq1 = setdiff(Subset12,Subset2);
Subsetq1
disp(' ')
disp('So, MATLAB can do set operations on finite sets ')
disp(' ')

disp(' Finding non-interescting subsets--Like Gram Schmidt')




%An interesting problem in Set Theory is the following \n
%Given the universe of N members(elements), 
%and K subsets (S1,S2,...SK )  ');

%NOTE: These overlap in general and do not typically form a partition).
%Create a partition P1,P2, etc as follows
%CreateP1 by placing S1 --> P1
%Create P2 using S2, and removing any elemenets of P!
%Continue until complete.

%Each row will be a subset
%Zeros are simply dummy placholders to keep the matrix
%formating correct 

for k = 1:K
    %Choose the number of elements randomly
    Lmembers = ceil(N*rand(1,1));NL=N-Lmembers;
Subsets(k,:) = [ceil(N*rand(1,Lmembers)) zeros(1,NL)];
end
%Lets look at these

Subsets
    Parts = zeros(K,N);
Parts(1,:)= Subsets(1,:);
%But I need to remove duplicates first 
tempset = unique(Parts(1,:));Lt = length(tempset);
Parts(1,:) = [tempset zeros(1,N-Lt)];
Parts(1,:) = reversesort(Parts(1,:));%zeros at end
for k = 2:K
    %Sieve the Partitions
    Parts(k,:) = Subsets(k,:);
    for kell =1:k-1
        tempset = setdiff(Parts(k,:),Parts(kell,:));
        Lt = length(tempset);
        Parts(k,:) =[tempset zeros(1,N-Lt)];
    %    Parts(k,:) = reversesort(Parts(k,:));%zeros at end
    end

end
Parts

function [avector] = reversesort(avector);
%Reverse sort in descending order
%returns ROWS
avector = avector(:);%make 1 column
avector = sort(avector);
avector = avector([end:-1:1]);
avector = avector(:).';


