24点游戏(JAVA)

  1. 游戏规则
    从扑克中每次取出4张牌。使用加减乘除,第一个能得出24者为赢。(其中,J代表11,Q代表12,K代表13,A代表1)

  2. 基本要求:
    随机生成4个代表扑克牌牌面的数字字母,程序自动列出所有可能算出24的表达式

  3. 算法
    穷举法:列出4个数字加减乘除的各种可能性,包括括号的算法。我们可以将表达式分成以下几种:首先我们将4个数设为a,b,c,d,,其中算术符号有+,-,*,/,。其中有效的表达式有a,ab-cd,等等。列出所有有效的表达式。其中我们用枚举类型将符号定义成数字常量,比如用1表示+,2表示-等。如下是我对穷举法的一种编程语言。在编程的头部要对变量做下定义。其中a,b,c,d的范围是1到10。这就需要在定义变量的时候要有限制

  4. 源代码

import java.util.Random;

/*
 * date:2018/10/5
 * target:24点
 */
public class homework {
	static double ZERO = 1E-6;
	static int COUNT = 4;
	static int TOTAL = 24;
	static double number[] = new double [COUNT];
	static String show[] = new String [COUNT];
	static boolean flag =  false;
	static int count = 0;
	static void Find(int n){
		if (n == 1)
		{
			if ( Math.abs(number[0] - TOTAL) <= ZERO )
			{
				System.out.println(show[0]+"  ");
				flag = true;
				count ++;
			
			}
			else
			{ }
		}
		for(int i=0; i < n; i++)//查找
		{
			for (int j = i + 1; j < n; j++)//与其后面的查找进行计算
			{
				double a, b;
				String x, y;
				a = number[i];
				b = number[j];
				number[j] = number[n - 1];
				x = show[i];
				y = show[j];
				show[j] = show[n - 1];
				show[i]= '('+ x + '+' + y + ')';
				number[i] = a + b;
				Find(n-1);
				show[i]='('+ x+ '-' + y + ')';
				number[i] = a - b;
				Find(n-1);
				show[i] = '('+y + '-' + x + ')';
				number[i] = b -a;
				Find(n-1);
				show[i]= '('+ x +'*'+ y+ ')';
				number[i]=a*b;
				Find(n-1);
				if (b != 0)
				{
					show[i] ='('+x+'/' + y + ')';
					number[i] = a / b;
					Find(n-1);
				}
				if (a != 0)
				{
					show[i]='('+y + '/'+ x + ')';
					number[i] = b / a;
					Find(n-1);
				}
				number[i] =a;
				number[j]=b;
				show[i] = x;
				show[j] = y;
			}
		}
	}
	public static void main(String a[]){
		 Random rand = new Random();
		 for(int i = 0; i<COUNT;i++){
			 String str;
			number[i] = rand.nextInt(13)+1;
			str = ""+(int)number[i];
			show[i]=str;
		 }
		 System.out.print("系统生成的四个随机数为:");
		 for(int i = 0; i<COUNT;i++){
			 if(number[i]<=10)
			 System.out.print((int)number[i]+" ");
			 else{
				 switch(show[i]){
				 case"11": System.out.print("J ");break;
				 case"12": System.out.print("Q ");break;
				 case"13": System.out.print("K ");break;
				 }
				
			 }
		 }
		 System.out.println();
		 Find(COUNT);
		 
		 if(flag==true){
			System.out.println("总计有"+count+"种方法"); 
		 }else{
			 System.out.println("没有可计算的方法");
		 }
	}
}

  1. 结果截图
    在这里插入图片描述
    在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_40161609/article/details/82950251
今日推荐