Card Trick

【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+" ");
		}
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值