【Description】
The shuffles asmall pack of card ,holds it face down and performs the following procedure:
1. The top card is moved to the bottom of thepack.The new top card is dealt face up onto the table . It is the Ace ofSpades.
2. Two cards are moved one at a time from thetop to the botom.The next card is dealt face up onto the table .It is the Twoof Spades.
3. Three cards are moved one at a time …
4. This goes on until the nth and last cardturns to be the n of Spades.
The impresive trick works if the magician knows how toarrange the cards beforehand (and knows how to give a false shuffle).Yourprogram has to determine the initil order of the cards for a given number ofcards,
1<=n<=13.
【Standard input】
On the first line of the input is a singlepositive integerk,telling the number of test cases to follow.1<=k<=10 Each case consists ofone line containing the intger n. 1<=n<=13
【Standard output】
For each test case , output a line with thecorrect permutation of the values 1 ton, space separated. The first nnumber showing the top card of the pack , ect…
【Sampleinput】 【Standard output】
2
4 2 1 4 3
5 3 1 4 5 2
基本思路:把一个线性结构当作循环链表。java写循环链表较复杂,我采用了取余循环,
import java.util.LinkedList;
import java.util.Scanner;
public class CardTrick {
public static void main(String[] args){
Scanner s = new Scanner(System.in);
int n = s.nextInt();
while(n--!=0){
int m = s.nextInt();
int[] temp = new int[m];
LinkedList<Integer> ll = new LinkedList<Integer>();
//init
for(int i=1;i<=m;i++){
ll.add(i);
}
//fill it
int jCount= 0;
int rCount= 1;
for(int i=1;i<=m;i++){
int size = ll.size();
rCount = (rCount+i)%ll.size();
//有个问题就是当计数计到最后一位时,实际取的是最后一位
if(rCount==0){
rCount = size;
}
jCount = rCount-1;
int tempIndex = ll.get(jCount)-1;
temp[tempIndex] = i;
ll.remove(jCount);
}
for(int i:temp){
System.out.print(i+" ");
}
}
}
}