算法:模拟法(报数游戏)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chekongfu/article/details/51674695

将自然的过程或者语言直白的程序化,比如题目中的求解过程,我们直接程序化模拟求解。即根据实际问题建立模型,模拟实际玩法从而解决问题。

举一个实际的例子说明以佐证以上说法:

描述:
n个人站成一行玩一个报数游戏。所有人从左到右编号为1到n。游戏开始

时,最左边的人报1,他右边的人报2,编号为3的人报3,等等。当编号为n的人(即最右边的人)报完n之后,轮到他左边的人(即编号为n-1的人)报n+1,然后编号为n-2的人报n+2,以此类推。当最左边的人再次报数之后,报数方向又变成从左到右,依次类推。 

为了防止游戏太无聊,报数时有一个特例:如果应该报的数包含数字7或者是7的倍数,他应当用拍手代替报数。下表是n=4的报数情况(X表示拍手)。当编号为3的人第4次拍手的时候,他实际上数到了35。

给定n,m和k,计算当编号为m的人第k次拍手时,他实际上数到了几。

Input

输入包含不超过10组数据。每组数据占一行,包含三个整数nmk2<=n<=100,1<=m<=n, 1<=k<=100)。输入结束标志为n=m=k=0

Output

对于每组数据,输出一行,即编号为m的人第k次拍手时,他实际上数到的那个整数。

Sample Input

扫描二维码关注公众号,回复: 3202203 查看本文章

4 3 1

4 3 2

4 3 3

4 3 4

0 0 0

Sample Output

17

21

27

35

 

作者贴出自己的算法如下:

package arithmetic.simulation;

import java.util.Scanner;

public class CountGame {
	
	//判断一个整形数字中是否慢组条件1.数字中包含7 或者 2.是7的整数倍
	public static boolean Is7(int n){
		if(n%7==0) {
			return true ;
		} else {
			while(n!=0){
				int m = n%10 ;
				if(m==7){
					return true ;
				}
				n = n/10 ;
			}
			return false ;
		}
	}
	
	public static void main(String[] args) throws Exception {
		Scanner sc = new Scanner(System.in);
		int players = sc.nextInt();	//总人数
		int num = sc.nextInt();		//编号
		if(num>players) {
			throw new Exception("编号不能大于总人数");
		}
		int time = sc.nextInt();	//次数
		
		while(players!=0&&num!=0&&time!=0){
			int callNum = 0;	//实际喊编号的人
			boolean up = true ;
			for(int i=1;;i++){
				
				if(up) {
					callNum ++ ;
				} else {
					callNum -- ;
				}
				
				if(callNum == players ) {
					up = false ;
				} else if (callNum == 1) {
					up = true ;
				}
				
				if(callNum==num&&Is7(i)){
					time-- ;
					if(time==0) {
						System.out.println();
						System.out.print( i );
						
						players = sc.nextInt();	//总人数
						num = sc.nextInt();		//编号
						if(num>players) {
							throw new Exception("编号不能大于总人数");
						}
						time = sc.nextInt();	//次数
						
						break;
					}
				}
			}
		}
	}
}


版权声明:本文为作者原创文章,未经作者允许不得转载。文章内容如有不妥之处,请留言指出,以作讨论。

猜你喜欢

转载自blog.csdn.net/chekongfu/article/details/51674695