01 public class CardDealer{
02 static int [] cards = new int [52];
03 static { for (int i=0; i<52; i++) cards[i]=i; }
04 /** create a random number in a range */
05 public static int getRandomNumber (int from, int to) {
06 return ((int)(Math.random() * (to - from)) + from);
07 }
08 /** shuffle the cards */
09 public static void shuffleCards() {
10 int r, temp;
11 for (int i=0; i<52; i++) {
12 r = getRandomNumber(i, 52);
13 temp = cards[i];
14 cards[i] = cards[r];
15 cards[r] = temp:
16 }
17 }
18 public static void main(String[] args) {
19 shuffleCards();
20 for (int=0; i<52; i++) {
21 System.out.print(`` `` + cards[i]);
22 }
23 }
24 }
The above program contains following program plans:
|
Plan Name |
Plan Description |
Lines Realizing the Plan |
|
Create a random number in a range |
Get the range;
Convert a random number between [0, 1.0] to the range. |
5,7 |
|
Swap two numbers |
Save one data to a temporary variable;
Move the other data to the saved data;
Move the temporary variable to the other data. |
13-15 |
|
Loop over an array |
Initialize;
Set the ending condition;
Perform operations;
Increase the loop variable. |
11-16;
20-22 |
|
Shuffling an array |
Loop over an array;
Create a random number in a range;
Swap two numbers. |
11-16 |
|