Is there an easy way to rearrange a number in java? [closed]
Basically in a nut shell I want to take a random number say:
73524896
and I want to us the same number but randomly rearrange it like this:
46932857
Is there a way I can do t开发者_开发百科his easily in java?
Here's my favorite solution. (Note that all shufflings are equally probable.)
Random rnd = new Random();
int rndInt = rnd.nextInt(10000000);
String[] rndChars = ("" + rndInt).split("(?<=.)");
Collections.shuffle(Arrays.asList(rndChars));
String result = "";
for (String s : rndChars) result += s;
int shuffled = Integer.parseInt(result);
// Print original and shuffled
System.out.println(rndInt);
System.out.println(shuffled);
Sample output:
4769797
9497767
//generate random number
String number = "73524896";
//put each digit in an element of a list
List<Character> numberList = new ArrayList<Character>();
for (char c : number.toCharArray()){
numberList.add(c);
}
//shuffle
Collections.shuffle(numberList);
//output
String shuffledNumber = "";
for (Character c : numberList){
shuffledNumber += c;
}
System.out.println(shuffledNumber);
This will this help you : Random Numbers - shuffling.
Not a complete code, just a snippet from the link
Random rgen = new Random(); // Random number generator
int[] cards = new int[52];
//--- Initialize the array to the ints 0-51
for (int i=0; i<cards.length; i++) {
cards[i] = i;
}
//--- Shuffle by exchanging each element randomly
for (int i=0; i<cards.length; i++) {
int randomPosition = rgen.nextInt(cards.length);
int temp = cards[i];
cards[i] = cards[randomPosition];
cards[randomPosition] = temp;
}
turn it into a string, get the character array, then randomize the character array, and turn it back into a string.
that would let you randomize any string, not just numbers.
I would say the easiest way to do this is to parse the integer to a String, rearrange the digit in the String then parse it back to integer.
public int rearrange(int num){
StringBuilder asStr = new StringBuilder(num + ""); //convert to string
inplaceShuffle(asStr);
return Integer.parseInt(asStr.toString());
}
(1) Convert the number to a string
(2) Use a standard shuffling algorithm to shuffle the characters
(3) Convert back to a number
Collections.shuffle()
takes a list and returns a list, which has a toArray()
. Arrays.asList()
takes an array and returns a list. String has a toCharArray()
and a constructor that accepts a char array. Integer has toString()
and valueOf()
精彩评论