[size=medium]前段时间,面试某知名公司的时候,被问到洗牌技术。当时,没有好的思路,结果,悲剧....
现整理思路如下:
假设洗54张牌,数组pokers存放每张牌的名字,pokersId存放牌的id,洗牌的过程使pokersId随机化。随机思路为产生两个随机数(合适范围),交互这两个位置的牌Id.重复该过程一定次数,原则上至少等于牌的张数。[/size]
测试结果大致为
shaking....
after shake....
♠2 ♦8 ♦9 ♥9 ♥5 JOKER ♠Q ♣5 ♠K ♠1 ♥2 ♥K ♣7
♥J ♦6 ♠J ♦4 ♥Q ♦3 ♦10 ♣2 ♣3 ♥3 ♥4 ♥1 ♦K
♥6 ♦7 ♥7 ♣K ♠5 ♠6 ♥8 ♠8 ♠3 ♣6 ♥10 ♣4 ♠7
♣1 ♦Q ♦5 ♠10 ♠9 ♦1 ♣J ♣10 ♠4 ♦J ♣9 joker ♦2
♣Q ♣8
现整理思路如下:
假设洗54张牌,数组pokers存放每张牌的名字,pokersId存放牌的id,洗牌的过程使pokersId随机化。随机思路为产生两个随机数(合适范围),交互这两个位置的牌Id.重复该过程一定次数,原则上至少等于牌的张数。[/size]
package cn.edu.hust.cs.j2se.test;
import java.util.Date;
import java.util.Random;
public class ShakePoker {
public static void shake(int[] pokers, int times) {
System.out.println("shaking....");
int pos1 = 0;
int pos2 = 0;
int tmp = 0;
int max = pokers.length;
if (times < pokers.length) {
times = pokers.length;
}
Random rand = new Random(new Date().getTime());
for (int i = 0; i < times; i++) {
//产生随机数
pos1 = rand.nextInt(max) % pokers.length;
pos2 = rand.nextInt(max) % pokers.length;
//交换id
tmp = pokers[pos1];
pokers[pos1] = pokers[pos2];
pokers[pos2] = tmp;
}
}
public static void main(String[] args) {
int[] pokersId = new int[54];
String[] pokers = new String[54];
//红桃♥heart方块♦diamond 黑桃♠spade 梅花♣club
String[] groupName = {"♥","♦","♠","♣"};
String[] pokerName = {"1","2","3","4","5","6","7","8","9","10","J","Q","K"};
//初始化数据
for(int i=0;i<groupName.length;i++){
for(int j=0;j<pokerName.length;j++){
pokers[i*pokerName.length + j] = groupName[i] + pokerName[j];
}
}
pokers[52] = "JOKER";//大王
pokers[53] = "joker";//小王
int max = pokersId.length;
for (int i = 0; i < pokersId.length; i++) {
pokersId[i] = i;
}
shake(pokersId, max);
System.out.println("after shake....");
for (int i = 0; i < pokersId.length; i++) {
System.out.print(pokers[pokersId[i]] + " ");
if(((i+1)%13)==0){
System.out.println();
}
}
}
}
测试结果大致为
shaking....
after shake....
♠2 ♦8 ♦9 ♥9 ♥5 JOKER ♠Q ♣5 ♠K ♠1 ♥2 ♥K ♣7
♥J ♦6 ♠J ♦4 ♥Q ♦3 ♦10 ♣2 ♣3 ♥3 ♥4 ♥1 ♦K
♥6 ♦7 ♥7 ♣K ♠5 ♠6 ♥8 ♠8 ♠3 ♣6 ♥10 ♣4 ♠7
♣1 ♦Q ♦5 ♠10 ♠9 ♦1 ♣J ♣10 ♠4 ♦J ♣9 joker ♦2
♣Q ♣8