4u53r
4u53r

Reputation: 737

How to make shuffled number never equal original? (Java)

I have an original number (LoadG1). I then produce shuffled versions of this number as seen in the code below. Note: generateG1 is a Random.

int loadG1 = generateG1.nextInt(89999) + 10000;
for (int allrbA = 0; allrbA < 4; allrbA++) {

StringBuilder charLoadG1 = new StringBuilder(String.valueOf(loadG1));
StringBuilder randomLoadG1 = new StringBuilder();
while(charLoadG1.length() != 0) {
int index = generateG1.nextInt(charLoadG1.length());
char c = charLoadG1.charAt(index);
randomLoadG1.append(c);
charLoadG1.deleteCharAt(index);
}

}

 if(Integer.valueof(String.valueof(randomLoadG1))==loadG1) {
for (int allrbA = 0; allrbA < 4; allrbA++) {

StringBuilder charLoadG1 = new   StringBuilder(String.valueOf(loadG1));
StringBuilder randomLoadG1 = new StringBuilder();
while(charLoadG1.length() != 0) {
int index = generateG1.nextInt(charLoadG1.length());
char c = charLoadG1.charAt(index);
randomLoadG1.append(c);
charLoadG1.deleteCharAt(index);
}

}

This successfully rearranges the numbers in loadG1, seen as the value for randomLoadG1. The issue is, I don't want randomLoadG1 to ever be == to loadG1. This can happen if it is rearranged into the exact same order. I tried using a while loop to sort this out, but it only crashed my app whenever an identical randomLoadG1 was produced.

Can anyone help out with explaining how to get randomLoadG1 (the shuffled version(s) of the original loadG1) to never have the same value as loadG1? Any submitted code is greatly appreciated, many thanks.

Upvotes: 0

Views: 80

Answers (1)

Stephen C
Stephen C

Reputation: 719551

Here is a pseudocode implementation:

number1 = random number
do {
    number2 = random_shuffle(number1);
} while (number1 == number2)

... where random_shuffle(number1) stands for your existing shuffle algorithm.

Now I don't understand why you can't refactor your existing implementation to follow this pattern, but it should be simple Java programming. If your code is crashing, then you should use a debugger to find out why.

Upvotes: 1

Related Questions