'Reshuffling deck of cards
for the code below I need to track a card after a series of multiple shuffles in one run. I have used a for loop, Ofindex(), and Object.equals to find the position of the card. I need help with the reshuffle of the deck after it compiles
how would I go about reshuffling the deck in the code so when I go to find the position of the card in the for loop. it finds a different position everytime
code below is what we are given to build off of. not my personal code
private static String[] createDeck()
{
String[] SUITS = {"Clubs", "Diamonds", "Hearts", "Spades"};
String[] RANKS = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace" };
// Deck creation code
String[] deck = new String[RANKS.length*SUITS.length];
for (int i=0; i< RANKS.length; i++)
for (int j=0; j< SUITS.length; j++)
deck[SUITS.length*i+j] = RANKS[i] + " of " +SUITS[j];
return deck;
}
private static String[] shuffleDeck(String[] deck)
{
//Shuffle Code
int n = deck.length;
for (int i=0; i<n; i++)
{
int r = i + (int)(Math.random()*(n-i));
String temp = deck[i];
deck[i] = deck[r];
deck[r] = temp;
}
return deck;
}
This would be the public static void main part
int x = Integer.parseInt(args[0]);
int y = Integer.parseInt(args[1]);
System.out.println("Shuffling " + x + " times.");
System.out.println(deck[y]);
System.out.println();
int Y = y-1;
System.out.println("Starting Position: "+ Y );
//Objects.equals("test", new String("test"))
for(int L = 0; L < x; L++) {
for (int f = 0; f < deck.length; f++) {
if (Objects.equals(deck[f], new String(deck[y]))) {
System.out.println("Shuffle " + (L + 1) + ": " + f);
keep in mind that some of this will not work with the code above it, as ive said I took out the private static String so I would be able to use some of the upper code.
Solution 1:[1]
your code have a probem in this line:
for (int i=0; i<n; i++){
int r = i + (int)(Math.random()*(n-i));
variable r will be set a random number from i to n(include i),so The card may be exchanged with itself.
If you wish to change the position of all cards after shuffling, you should change the line of code to this:
for (int i=0; i<n-2; i++){
int r = i + (int)(Math.random()*(n-i-1)+1);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | oy9r |
