标签:amp dom AMM return ring i++ 情况 out 无限
它是一个经典的统计问题,有很多实际应用。这个问题从一套对象中拿出一个对象,然后找到要将所有需要拿的对象都至少拿出来一次,需要拿多少次。为了叙述方便,以扑克牌为例。一副打乱的52张扑克牌,找出在看到每种花色都有一张出现前,需要选多少次。编写程序,模拟要得到四张不同花色的牌所需要的选取次数,然后显示选中的四张牌(有可能一张牌被选了两次)。
要解决这个问题首先要解决以下几个子问题:
这里我们这里我们使用了一个boolean型的数组存储每个花色是否出现过,出现了就设为true。
public class demo1{
public static void main(String[] args){
boolean[] huase = new boolean[4]; //存放每种花色的抽取情况
boolean flag = false;
int count = 0;
//因为并不知道要抽多少次,所以要放在一个无限循环中
while(flag == false){
if(huase[0]&&huase[1]&&huase[2]&&huase[3]) //若四种花色都出现过
flag = true;
else{
switch(choosePai(huase)){
case "Spades":
huase[0] = true;
break;
case "Hearts":
huase[1] = true;
break;
case "Diammonds":
huase[2] = true;
break;
case "Clubs":
huase[3] = true;
break;
}
}
count++;
}
System.out.println("Number of picks:"+count);
}
public static String choosePai(boolean[] huase){
int[] deck = new int[52]; //用来存放52张牌
String[] Huases = {"Spades","Hearts","Diamonds","Clubs"};
String[] ranks = {"Ace","2","3","4","5","6","7","8","9","10","Jack","Queen","King"};
//首先初始化牌组
for(int i = 0;i < deck.length;i++){
deck[i] = i;
}
//进行洗牌
for(int i = 0;i < deck.length;i++){
int Index = (int)(Math.random()*deck.length);
int temp = deck[i];
deck[i] = deck[Index];
deck[Index] = temp;
}
//从52张牌中任选一张进行抽牌
int i = (int)(Math.random()*deck.length);
String Huase = Huases[deck[i] / 13];
String rank = ranks[deck[i]%13];
switch(Huase){
case "Spades":
if(!huase[0])
{System.out.println(rank+" of "+Huase);huase[0] = true;}
break;
case "Hearts":
if(!huase[1])
{System.out.println(rank+" of "+Huase);huase[1] = true;}
break;
case "Diamonds":
if(!huase[2])
{System.out.println(rank+" of "+Huase);huase[2] = true;}
break;
case "Clubs":
if(!huase[3])
{System.out.println(rank+" of "+Huase);huase[3] = true;}
break;
}
return Huase;
}
}
标签:amp dom AMM return ring i++ 情况 out 无限
原文地址:https://www.cnblogs.com/Western-Trail/p/8886197.html