140 likes | 258 Vues
Lec 13 Oct 17 cell arrays structures advanced recursive programs. Cell arrays suppose we want to represent a collection of sets such as: {1, 2, 4}, {3, 4, 6}, {7, 8} Each set can be represented by vector:
E N D
Lec 13 Oct 17 • cell arrays • structures • advanced recursive programs
Cell arrays • suppose we want to represent a collection of sets such as: • {1, 2, 4}, {3, 4, 6}, {7, 8} • Each set can be represented by vector: • [1, 2, 4], [3, 4, 6], [7, 8] • >> A = [[ 1, 2, 4], [3, 4, 6], [7, 8]] • A becomes [1, 2, 4, 3, 4, 6, 7, 8]
Generating all subsets of a given set Given a set, like [1, 3, 4], the subsets are: [ ] [1] [3] [4] [1 3] [1 4] [3 4] [1 3 4] We want to write a program to generate all the subsets of a given collection
Idea behind algorithm – recursion This is a problem for which non-recursive solutions are significantly harder than recursive solutions. Idea: input array is a of length n. Recursively find all subsets of a(2:n) Then add a(1) to each of the subsets. Combine the two collections.
Since we need to represent a collection of sets, we have two choices: • use of cell arrays • use of two-dimensional arrays • The latter is not suitable for this problem since the sizes of the subsets are not the same • We need a function insert that inserts a given number into all the sets of a given collection.
Code for insert function out = insert(i, lst) % inserts i into each membet of lst for j = 1:length(lst) out{j}= [i, lst{j}]; end;
Code for subsets function L = subsets(lst) % generates all subsets of lst if length(lst) == 0 L = {[]}; elseif length(lst) == 1 L = {[lst(1)],[]}; else L1 = subsets(lst(2:end)); L2 = insert(lst(1), L1); L = [L1, L2]; end;
Printing the contents of a cell array function setprint(cellset) % prints every member of the cell in one line % assume cellset is a collection of sets of integers for k=1:length(cellset) aprint(cellset{k}); fprintf('\n'); end; function aprint(r) for j = 1:length(r) fprintf('%d', r(j)); fprintf(' '); end; fprintf('\n')
Generating all permutations of a given set Example: set [ 1 3 4] Permutations: [1 3 4] [1 4 3] [3 1 4] [3 4 1] [4 1 3] [4 3 1]