Labels

algorithms (22) Design Patterns (20) java (19) linux (14) Snippet (13) service mix (6) soa (4)

Cards Shuffle Code in Java

package org.code;
import java.util.Arrays;
import java.util.Random;

/**
*
@author Purna
*
* this class just shuffles the given set of cards assuming there are 52
* cards 1-52
*/
public class CardsShuffler {

public static Random randomGenerator = new Random();

public static void main(String args[]) {
int[] cards = new int[5];
for (int index = 0; index < cards.length; index++) {
cards[index]
= index + 1;
}

printCards(cards);
shuffleCards(cards);
}

/**
* shuffles the cards using
*
* Knuth Shuffle
*
*
@param cards
*/
private static void shuffleCards(int[] cards) {

for (int index = 1; index < cards.length; index++) {
int cardToShuffleWith = randomGenerator.nextInt(index);
swapNumbers(cards, index, cardToShuffleWith);
// printing the cards on every shuffle
printCards(cards);
}

}

/**
* Swaps two Cards
*
*
@param cards
*
@param index
*
@param cardToShuffleWith
*/
private static void swapNumbers(int[] cards, int index,
int cardToShuffleWith) {
int temp = cards[index];
cards[index]
= cards[cardToShuffleWith];
cards[cardToShuffleWith]
= temp;
}

/**
* prints the cards
*
*
@param cards
*/
private static void printCards(int[] cards) {
System.out.println(Arrays.toString(cards));
}
}

3 comments:

  1. Well... Prior to random number generator java https://explainjava.com/random-number-generator-java/,
    the way to find the parameter names is by turning debug symbols on at the compilation stage. That's why I added meta information about the parameter this way. Fortunately, I no longer need to do this routine, the code is optimized, and I'm sure it works on your PC too. Thank you very much, without your help I wouldn't have coped.

    ReplyDelete
  2. Gift Card Granny, for example, will buy your card for 60%-80% of its value. You can also sell your card on a website like Craigslist or eBay. Other websites like Gift Card Swapping allow you to trade your gift card for one you'll actually use.
    Giant teddy bears

    ReplyDelete
  3. We all know that it is difficult to start a business especially if you don't have much capital. cheapest color copies online

    ReplyDelete

Search 24 Bytes