扑克洗牌程序
随机数的使用
在java中可以使用 Random
工具类生成随机数;
我们利用比较、交换的思想(排序算法经常用到)实现简易的扑克洗牌动作。
首先存在有序分扑克牌52张,我们用一个数组保存,洗牌时:
- 遍历扑克数组
- 生成随机数,得到需要交换的目标数组索引下标(注意,使用Random.nextInt(N),N需要小于数组的长度)
- 当前遍历到的元素与随机到的元素交换
完整的程序如下:
package org.byron4j.dsaa.basic;
import java.util.Random;
/**
* 洗牌
* @author BYRON.Y.Y
*
*/
public class ShuffleCard {
public static void main(String[] args) {
String[] arr = {"2♣", "3♣", "4♣", "5♣", "6♣", "7♣", "8♣", "9♣", "10♣", "J♣", "Q♣", "K♣", "A♣", "2♦", "3♦", "4♦", "5♦", "6♦", "7♦", "8♦", "9♦", "10♦", "J♦","Q♦", "K♦", "A♦", "2♥", "3♥", "4♥", "5♥", "6♥", "7♥", "8♥", "9♥", "10♥", "J♥", "Q♥", "K♥", "A♥", "2♠", "3♠", "4♠", "5♠", "6♠", "7♠", "8♠", "9♠", "10♠", "J♠", "Q♠", "K♠", "A♠"};
printf(arr, 13);
shuffle(arr);
System.out.println("\n***********************洗牌完毕*******************");
printf(arr, 13);
}
public static void shuffle( Object[] arr ) {
int n = arr.length;
for( int i = 0; i < n ; i++ ) {
int idx = new Random().nextInt(n);
//交换
Object tmp = arr[i];
arr[i] = arr[idx];
arr[idx] = tmp;
}
}
/**
*
* @param arr 数组
* @param nop 多少一行打印,默认为0表示一行打印出来
*/
public static void printf(Object[] arr, int nop) {
if( nop <= 0 ) {
for( int i = 0; i < arr.length; i++ ) {
System.out.print((arr[i] + " ").substring(0, 4));
}
}else {
for( int i = 0; i < arr.length; i++ ) {
System.out.print((arr[i] + " ").substring(0, 4));
if( ( i + 1 ) % nop == 0 ) System.out.println();
}
}
}
}
程序运行结果如下:
2♣ 3♣ 4♣ 5♣ 6♣ 7♣ 8♣ 9♣ 10♣ J♣ Q♣ K♣ A♣
2♦ 3♦ 4♦ 5♦ 6♦ 7♦ 8♦ 9♦ 10♦ J♦ Q♦ K♦ A♦
2♥ 3♥ 4♥ 5♥ 6♥ 7♥ 8♥ 9♥ 10♥ J♥ Q♥ K♥ A♥
2♠ 3♠ 4♠ 5♠ 6♠ 7♠ 8♠ 9♠ 10♠ J♠ Q♠ K♠ A♠
***********************洗牌完毕*******************
3♥ K♠ 8♦ 2♥ Q♦ 2♣ 5♥ 7♣ 8♣ A♦ 7♦ 9♣ 2♠
10♦ J♥ K♣ 7♥ 10♠ A♣ 4♥ K♦ A♥ A♠ 4♦ 7♠ J♦
Q♣ 4♣ 9♥ 3♣ 2♦ 6♠ 6♦ 3♠ Q♥ 3♦ 5♠ K♥ 5♦
6♥ 9♠ 5♣ 6♣ 10♣ Q♠ 10♥ 4♠ 8♠ J♣ 9♦ 8♥ J♠