面试题:Java实现扑克洗牌 + Java实现取得某个范围内不重复的随机数
首先、Java实现扑克洗牌
包括四种花色(黑桃,红心,梅花,方块),十三种点数(2-10,J,Q,K),考虑大小王。
代碼:
public String poker(int num) {
String str = "";
String[] face = { "♥", "♠", "♣", "♦" };
String[] number = { "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K" };
str += face[num % 4] + number[num % 13];
return str;
}
@SuppressWarnings("unchecked")
public static void main(String[] args) {
@SuppressWarnings("rawtypes")
ArrayList list = new ArrayList();
Card card = new Card();
for (int i = 0; i < 54; i++) {
if(i < 52) {
list.add(card.poker(i));
}else if(i == 52) {
list.add("SK");
}else if(i == 53) {
list.add("LK");
}
}
System.out.println("洗牌前:");
for (int i = 0; i < list.size(); i++) {
System.out.printf("%s\t", list.get(i));
if ((i + 1) % 13 == 0) {
System.out.println(" ");
}
}
System.out.println();
Collections.shuffle(list);
System.out.println("洗牌后:");
for (int i = 0; i < list.size(); i++) {
System.out.printf("%s\t", list.get(i));
if ((i + 1) % 13 == 0) {
System.out.println(" ");
}
}
}
運行結果:
洗牌前:
♥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 ♥2 ♠3 ♣4 ♦5 ♥6 ♠7 ♣8 ♦9 ♥10 ♠J ♣Q ♦K
SK LK
洗牌后:
♥9 ♦K ♦9 ♦J ♦10 ♦A ♥K ♠8 ♦2 ♣5 ♠4 ♦4 ♣6
♥5 ♣3 ♣Q ♠2 ♥10 ♦5 ♦7 ♦3 ♣10 ♥6 ♥J ♣A ♠J
♥3 ♥4 ♥Q ♣K ♥A LK ♦8 ♣9 ♠K ♦6 ♥7 ♣J ♥8
♠5 ♣4 ♠Q SK ♠6 ♠A ♣2 ♠9 ♦Q ♠10 ♥2 ♠3 ♠7
♣8 ♣7
其次、Java实现取得某个范围内不重复的随机数
代碼:
public static void main(String[] args) {
int[] reult = randomArray(0, 12, 13);
for (int i : reult) {
System.out.print(i + " ");
}
}
public static int[] randomArray(int min, int max, int n) {
int len = max - min + 1;
if (max < min || n > len) {
return null;
}
// 初始化给定范围的待选数组
int[] source = new int[len];
for (int i = min; i < min + len; i++) {
source[i - min] = i;
}
int[] result = new int[n];
Random rd = new Random();
int index = 0;
for (int i = 0; i < result.length; i++) {
// 待选数组0到(len-2)随机一个下标
index = Math.abs(rd.nextInt(len--));
// 将随机到的数放入结果集
result[i] = source[index];
// 将待选数组中被随机到的数,用待选数组(len-1)下标对应的数替换
source[index] = source[len];
}
return result;
}
運行結果:
0 10 9 8 12 3 4 11 1 2 5 7 6
参考:
https://www.jb51.net/article/132299.htm
https://www.cnblogs.com/happyday56/p/5163264.html