トランプなどをシャッフルする場合は、一度配列に情報を格納して配列をシャッフル
することにより、トランプをシャッフルするやり方が一般的に使用されています。
以下の例では54枚のトランプをシャッフルして頭の10枚を表示しています。
import java.util.Random; public class Run{ public static void main(String[] args){ int buff; int ran1; int ran2; String ke; int[] tor = new int[54]; String[] tor_d = new String[5]; tor_d[0] = "ハート"; tor_d[1] = "グラブ"; tor_d[2] = "ダイヤ"; tor_d[3] = "スペード"; tor_d[4] = "ジョーカー"; Random rnd1 = new Random(); Random rnd2 = new Random(); //トランプの配置(ハート1〜13、クラブ14〜27・・・) for(int i=1;ilt;=54;i++){ tor[i-1] = i-1; } //トランプのシャッフル for(int i=1;ilt;=200;i++){ //乱数を作成 ran1 = rnd1.nextInt(54); ran2 = rnd2.nextInt(54); //配列の入れ替え(乱数1と乱数2を入れ替え) buff = tor[ran1]; tor[ran1] = tor[ran2]; tor[ran2] = buff; } //頭から10枚表示 for(int j=1;jlt;=10;j++){ //ハート、クラブなどの種別を格納 ke = tor_d[tor[j-1]/13]; //カードを表示 System.out.println(ke+"の" +(tor[j-1]%13+1)); } } }
実行結果
グラブの7 ハートの4 ハートの2 スペードの3 ハートの7 ハートの13 スペードの12 ダイヤの11 ダイヤの3 ジョーカーの1