(使用栈方法)判断给出的四张扑克牌能否组成24点(java实现)

(使用栈方法)判断给出的四张扑克牌能否组成24点(java实现)

题目: 给定四张扑克牌,用±*/运算,令其等于24

import java.util.Scanner;
import java.util.Stack;
public class _24 {
 public static String random_op() {//随机产生一种操作符
  int n=(int)(Math.random()*4);
  if(n==0)return"+";
  if(n==1)return"-";
  if(n==2)return"*";
  return"/";
 }
 public static void shuffle(String[]x) {//打乱顺序
  for(int i=0;i<x.length;i++) {
   int j=(int)(Math.random()*x.length);
   String temp=x[i];
   x[i]=x[j];
   x[j]=temp;
  }
 }
 public static int op(int a,int b,String oper) throws Exception//op方法,用于操作符计算
 {
  if(oper.equals("+"))return a+b;
  if(oper.equals("-"))return a-b;
  if(oper.equals("*"))return a*b;
     if(a%b!=0)throw new Exception("no");//若ab间无法整除,则抛出异常
  return a/b;}
 public static boolean count(String[] date) {//核心代码:用于对数组进行压栈出栈操作
  Stack stack=new Stack();
  try{for(int i=0;i<date.length;i++){
   if(date[i].equals("+")||date[i].equals("-")||date[i].equals("*")||date[i].equals("/"))//若遇见操作符则令两个数字出栈
    {int a=Integer.parseInt(stack.pop()+"");//Integer.parseInt常用于将字符串转化为整数
        int b=Integer.parseInt(stack.pop()+"");
       stack.push(op(a,b,date[i])+"");//两个数字出栈后调用op方法对其进行计算后的结果压栈
       }
       else {
        stack.push(date[i]);}//若遇见数字则直接进栈
        }
  }
  catch (Exception e) {
   return false;//抛出异常,若遇见异常则说明此组合无法得出24,则return false
  }
  if(stack.size()==1&&stack.pop().equals("24"))//若栈内只剩下一个元素,并且出栈发现此元素是24,则说明此组合可组合为24,返回true,否则返回false
   return true;
  return false;
 }
 public static void show(String[]date) {//show方法用于打印出计算的步骤
  Stack stack=new Stack();//新建立一个栈
  for(int i=0;i<date.length;i++){//若遇见操作符则压栈中缀表达式,注意+括号
   if(date[i].equals("+")||date[i].equals("-")||date[i].equals("*")||date[i].equals("/"))
       stack.push("("+stack.pop()+date[i]+stack.pop()+")");
  else
   stack.push(date[i]);}
  System.out.println(stack.pop()); //最后仅剩一个元素即一个完整的操作步骤,直接出栈
 }//因为此步骤在判断能否组合成24点的count方法后,故发送过来的contain数组一定无异常,故不用抛异常操作
    public static void f(String[]s) {
     for(int i=0;i<10000*10;i++) {
      String[]contain = new String[7];
      for(int j=0;j<4;j++) 
       contain[j]=s[j];
      for(int k=4;k<7;k++)
       contain[k]=random_op();
      shuffle(contain);
      if(count(contain))
      show(contain);
     }
    }
    public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    while(true) {
     System.out.print("请输入四个整数");
     String[]s=scanner.nextLine().split(" +");
        f(s);
    }
    }
    }

整体思路:
1. 创建contain数组对输入进来的s数组的四个数字进行存储
2 再创建并调用random_op方法随机产生操作符,并用contain数组存储
3. 创建并调用shuffle方法对存储完毕的contain数组进行顺序的打乱
4. 调用count方法对打乱完毕的contain数组进行计算,若计算结果为24则返回true
5. 用if语句对count的结果进行判定,若判断为true,即可组成24点,则调用show方法进行输出其计算步骤
6. 在f方法中重复10000次此种随机操作

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值