MATLAB: Making different numbers with same digits

combinationsdigitspermutationsscramble

hello,
how do I make sure to find the next number greater and less than the number requested from the user, but it must contain the same digits as the requested number
for exemple: you get 536 so the answer will be 365 and 635

Best Answer

Try this:
% Create original number
nUser = 536;
% Convert to string.
strx = num2str(nUser);
% Get all possible permutations of the digits.
p = perms(1 : length(strx))
% Make list of all possible combinations
counter = 1;
for k = 1 : size(p, 1)
nAll(k) = str2double(strx(p(k,:)));
end
% Sort them
nSorted = sort(nAll, 'ascend');
% Find the index of the original number
index = find(nSorted == nUser)
% Get the two numbers that are just below and just above that number.
n = [nSorted(index-1), nSorted(index+1)];
% All Done! Display all the numbers in the command window:
nAll
n
You'll see
p =
3 2 1
3 1 2
2 3 1
2 1 3
1 3 2
1 2 3
index =
3
nAll =
635 653 365 356 563 536
n =
365 563
n is a list of all possible numbers that can be created from your original digits.
Be aware that you'll have to do some validation to see if the user's number is the smallest or largest possible because there would be no lower or higher number in those cases.
Is this what you were looking for?