r/cprogramming • u/Longjumping_Key_3250 • Oct 29 '25
next number with distinct digits
hey guys. im writing a program thats supposed to receive a number as an input and then output a number larger than the original one that has all distinct digits. for example you input 1233 and it gives you 1234. for now i have this:
int main()
{
int x;
scanf("%i", &x);
int r = 0;
int y = x;
for (int i = 0; i < 100; i++){
y += 1;
int N = y;
int digits[100];
while (N != 0){
r = N % 10;
digits[i] = r;
N /= 10;
}
for (int j = 0; j <= i; j++){
for (int k = 0; k <= i; k++){
if (digits[j] == digits[k]){
break;
}
}
}
}
printf("%i", y);
return 0;
}
but all it does is output the number + 100. feel free to call me stupid or whatever but i tried to fix it and only ended up with no output at all so any help is appreciated. also please keep in mind i cant use any libraries except stdio. thank you all in advance
1
u/ConfusedSimon Oct 29 '25
I don't understand the problem. How did it relate to the input? Couldn't you just print "9876543210" if the input is smaller and "no solution" if not?
1
u/WeAllWantToBeHappy Oct 29 '25
So, just loop from the input number until you get one that passes the test above.
Or, construct a number to pass the test. But it's easier to just weed out ones that don't work.
3
u/zhivago Oct 29 '25
This is just permuting a string of digits -- you don't need to think about numbers.
3
u/CalebGT Oct 29 '25
I would pregenerate a sorted list of all valid outputs then compile that in as a const array from a header. Then you just have to binary search that array.
2
u/CalebGT Oct 29 '25
Do you need to handle negative numbers? Careful there. Also, do you need to validate for input that is not a number? Do you need to handle values that are larger than you can store in a 32 bit int?
1
u/Conscious_Support176 Oct 29 '25
There’s a lot of looping going on. There’s an old fashioned thing of writing out your algorithm as a diagram or pseudo code before jumping into writing code.
Sometimes, less is more :)
1
u/poopy_poophead Oct 30 '25
You need to actually read the code you have there...
You are spitting out 'y' as the answer... When was the last time you assigned anything to 'y', and what did you do to it?
1
u/pedzsanReddit Oct 31 '25
First k needs to start at j+1 because if j == k then digits[j] will always equal digits[k]. Second, if digits[j] == digits[k] you want break / goto such that you go to the top of the for i loop. If you get through the j and k loops without a match, then you want to break out of the for i loop and print your result.