zoukankan      html  css  js  c++  java
  • 24点游戏算法, 华为, 全排列

    生成4个数的全排列, 和3个操作符的全排列,判断是否运算结果为24。

    import java.util.*;
    public class Main {
        static boolean res;
        static boolean is24(int[] a, int n, char[] op) {
            int res = a[0];
            for(int i=1; i < n; i++) {
                if(op[i-1] == '+') res += a[i];
                else if(op[i-1] == '-') res -= a[i];
                else if(op[i-1] == '*') res *= a[i];
                else if(a[i] == 0 || res % a[i] != 0) return false;
                else res /= a[i];
            }
            return res == 24;
        }
        static void dfs(int[] a, int n, char[] op, int u){
            if(u == n) {
                if(is24(a, n, op)) 
                    res = true;
                return ;
            } 
            for(int i=u; i < n; i++) {
                int t = a[i]; a[i] = a[u]; a[u] = t;
                dfs(a, n, op, u+1);
                t = a[i]; a[i] = a[u]; a[u] = t;
            }
        }
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            while(sc.hasNext()) {
                int a = sc.nextInt(), b = sc.nextInt();
                int c = sc.nextInt(), d = sc.nextInt();
                int[] arr = new int[] {a, b, c, d}; 
                char[] op = new char[] {'+', '-', '*', '/'};
                res = false;
                for(int i=0; i < 4; i++) {
                    for(int j=0; j < 4; j++) {
                        for(int k=0; k < 4; k++) {
                            char[] t = new char[] {op[i],op[j],op[k]}; 
                            dfs(arr, 4, t, 0);
                            if(res == true){
                                i = j = k = 5; // break;
                            }
                        }
                    }
                }
                System.out.println(res);
            }
        }
    }
    
    
  • 相关阅读:
    第五章 条件语句
    第四章 javaScript运算符
    第三章 javaScript数据类型
    看电影学英语十
    英语口语会话十
    看电影学英语九
    英语口语会话九
    英语口语会话八
    看电影学英语八
    Linux command line and shell scripting buble
  • 原文地址:https://www.cnblogs.com/lixyuan/p/13262279.html
Copyright © 2011-2022 走看看