How do I make a script that outputs all numbers containing a certain set of digits?

1 次查看(过去 30 天)
Say I want to make a vector containing all numbers with the digits [2,4,5,7,9], so 25497, 95742, etc. How can I make a script that puts all numbers in this vector?
I've tried the following:
%
vec = zeros (1,factorial(5));
i = 0
while i < factorial(5)
num = 0;
ii = 0;
iii = [2,4,5,7,9];
while ii < 5; % This while loop creates a number
randnum = randi(5);
eval = iii(randnum);
if eval > 0
num = num + eval*10^(ii);
iii(randnum) = 0;
ii = ii + 1;
end
end
if not(ismember(num,vec(:))) %This if-statement checks if the number had already been created earlier
i = i + 1;
vec(i) = num; %If not, it is added to the vector
end
end
but it is impressively inelegant and simply takes too long for larger amounts of numbers.

采纳的回答

Kai Domhardt
Kai Domhardt 2018-2-9
digits = [2,4,5,7,9];
sum(perms(digits).*10.^[size(digits,2)-1:-1:0],2);
---
perms(digits)
creates all permutations of digits
10.^[size(digits,2)-1:-1:0]
creates a vector with the relevant orders of magnitude:
ans =
10000 1000 100 10 1
which you can use to give your digits the right positional value:
perms(digits).*10.^[size(digits,2)-1:-1:0]
Now you only need to sum it up row wise:
sum( perms(digits).*10.^[size(digits,2)-1:-1:0] ,2)

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by