get a combination of unique paths for given pair of numbers
4 views (last 30 days)
Show older comments
I need to get combination of all unique paths. I have a path as follows:
107 111 354 371 326 375 145
pipe# 107 has 2 other pipes - 108 and 109
similarly, 354 has another 355
375 has 378 and 382
Desired output from [107/108/109], 111, [354 355], 371, 326, [375 378 382], 145 should be :
107 111 354 371 326 375 145
108 111 354 371 326 375 145
109 111 354 371 326 375 145
107 111 355 371 326 375 145
108 111 355 371 326 375 145
109 111 355 371 326 375 145
107 111 354 371 326 378 145
108 111 354 371 326 378 145
109 111 354 371 326 378 145
107 111 355 371 326 378 145
108 111 355 371 326 378 145
109 111 355 371 326 378 145
107 111 354 371 326 382 145
108 111 354 371 326 382 145
109 111 354 371 326 382 145
107 111 355 371 326 382 145
108 111 355 371 326 382 145
109 111 355 371 326 382 145
I would really appreciate if you could help me with the code or an idea. Thank you!!
0 Comments
Answers (1)
Walter Roberson
on 23 Oct 2020
This is easy to calculate using a code pattern that I call "odometer". Each cycle, move on to next valid entry in the last position, and when it reaches the maximum, "roll over" it and increment the second last... rolling it over as necessary. The general code pattern does not require that each position has the same number of possibilities.
https://www.mathworks.com/matlabcentral/answers/602395-different-number-of-for-loops#answer_502861
3 Comments
Walter Roberson
on 23 Oct 2020
The odometer utilities here do not assume that the values to be cycled through are all the same datatype.
The way the output is formatted for this particular example does assume that the entries are all integers.
pipes = {[107,108,109], 111, [354,355], 371, 326, [375, 378, 382], 145};
fmt = [repmat('%d ', 1, length(pipes)-1), '%d\n'];
[od_index, at_end] = odometer_init(pipes);
while ~at_end
od_reading = odometer_fetch_reading(od_index, pipes);
fprintf(fmt, cell2mat(od_reading));
[od_index, at_end] = odometer_next(od_index, pipes);
end
%these utilities do not permit empty positions.
function [od_index, at_end] = odometer_init(odvec)
if isempty(odvec) || any(cellfun(@isempty, odvec))
od_index = 0;
at_end = true;
else
od_index = ones(1, length(odvec));
at_end = false;
end
end
function odreading = odometer_fetch_reading(od_index, odvec)
odreading = cellfun(@(odcell, cellidx) odcell(cellidx), odvec, num2cell(od_index), 'uniform', 0);
end
function [od_index, at_end] = odometer_next(od_index, odvec)
at_end = true;
for vecidx = length(odvec) : -1 : 1
if od_index(vecidx) == length(odvec{vecidx})
od_index(vecidx) = 1;
else
od_index(vecidx) = od_index(vecidx) + 1;
at_end = false;
break;
end
end
end
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!