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.
댓글 수: 0
채택된 답변
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
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Whos에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!