這個我面試時的一題:
一副牌有54張去掉大小王,剩下的52張牌按花色平均分成兩份,每份26張,假如洗牌時每份一張的交叉。如:
初始:
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方
洗一輪後:
A紅 A梅 2紅 2梅 3紅 3梅 4紅 4梅 5紅 5梅 6紅 6梅 7紅
7梅 8紅 8梅 9紅 9梅 10紅 10梅 J紅 J梅 Q紅 Q梅 K紅 K梅
A黑 A方 2黑 2方 3黑 3方 4黑 4方 5黑 5方 6黑 6方 7黑
7方 8黑 8方 9黑 9方 10黑 10方 J黑 J方 Q黑 Q方 K黑 K方
問:
(1)2紅與2方在洗一輪後所在位置爲3和30,第三輪時它們分別在什麼位置。
(2)當洗N輪後牌會回到初始狀態,請問N是都少。
答:(1)分別在9和15。
(2)8
代碼如下:
public class test {
public static String[] insertSort(String[] args) {
for(int i=0;i<args.length/2;i++){
for (int j = 26+i; j > 2*i+1; j--) {
String temp = args[j];
args[j] = args[j-1];
args[j-1] = temp;
}
}
return args;
}
public static void main(String[] args) {
String[] argStrings={
"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方"
};
for (int i = 0; i <1; i++) {
String[] string1 = insertSort(argStrings);
String[] string =null;
System.out.print("請輸入洗牌的輪數:");
int num;
num = new Scanner(System.in).nextInt();
if(num<=0){
System.out.println("輸入的次數不對,請從新輸入");
num=new Scanner(System.in).nextInt();
}
if(num==1){
string=string1;
}else {
for (int j = 0; j < num-1; j++) {
string = insertSort(string1);
}
}
//按每行13張牌進行輸出
for (int j = 0; j < string.length; j++) {
if (j==13) {
System.out.println();
System.out.print(string[j]);
} else if(j==26){
System.out.println();
System.out.print(string[j]);
}else if(j==39){
System.out.println();
System.out.print(string[j]);
}else {
System.out.print(string[j]);
}
}
}
}
}