1

So I forgot a string and know there is three substrings in there and I know a few possibilities for each string. So all I need to do is go through all possible combinations and orders until I find the one I forgot. But since humans can only hold four items in their working memory (definately an upper limit for me), I cant keep tabs on which ones I examined.

So say I have n sets of m strings, how do I get all strings that have a length of n substrings consisting of one string from each set in any order?

I saw an example of how to do it in a nested loop but then I have to specify the order. The example is for n = 3 with different m`s. Not sure how to make this more general:

first = {'Hoi','Hi','Hallo'}; 
second = {'Jij','You','Du'};
third = {'Daar','There','Da','LengthIsDifferent'}; 

for iF = 1:length(first) 
    for iS = 1:length(second)
        for iT = 1:length(third)
            [first{iF}, second{iS}, third{iT}] 
        end
    end 
end

About this question: it does not solve this problem because it presumes that the order of the sets to choose from is known.

Community
  • 1
  • 1
Leo
  • 1,757
  • 3
  • 20
  • 44
  • 1
    you can use `perms` to obtain all possible permutations of each of the vectors your original loop returns, that should give you all the required vectors. – Wouter Kuijsters Feb 18 '15 at 09:12

1 Answers1

1

This generates the cartesian product of the indices using ndgrid. Then uses some cellfun-magic to get all the strings. Afterwards it just cycles through all the permutations and appends those.

first = {'Hoi','Hi','Hallo'}; 
second = {'Jij','You','Du'};
third = {'Daar','There','Da','LengthIsDifferent'}; 
Vs = {first, second, third};
%% Create cartesian product
Indices = cellfun(@(X) 1:numel(X), Vs, 'uni', 0);
[cartesianProductInd{1:numel(Vs)}] = ndgrid(Indices{:});
AllStringCombinations = cellfun(@(A,I) A(I(:)), Vs, cartesianProductInd,'uni',0);
AllStringCombinations = cat(1, AllStringCombinations{:}).';%.'
%% Permute what we got
AllStringCombinationsPermuted = [];
permutations = perms(1:numel(Vs));
for i = 1:size(permutations,1)
    AllStringCombinationsPermuted = [AllStringCombinationsPermuted; ...
                                     AllStringCombinations(:,permutations(i,:));];
end
knedlsepp
  • 6,065
  • 3
  • 20
  • 41
  • Nice thanks. I didn't identify the second operation I wanted to do as permutation. Also your cellfun approach with nested sets makes it very generalizable. – Leo Feb 18 '15 at 12:57