[Huawei 067] 24 point game algorithm

Title Description:

Give 4 numbers of 1-10. By adding, subtracting, multiplying and dividing, you can get a number of 24 and win
Input:
Four 1-10 numbers. [the number is allowed to be repeated, but each number is only allowed to be used once, and the test case guarantees no abnormal number]
Output:
true or false

Java implementation:

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main {
        public static void main(String[] args) throws Exception {
            Scanner sc = new Scanner(System.in);
            while (sc.hasNext()) {
                String line = sc.nextLine();
                String[] strs = line.split(" ");
                List<Integer> list = new ArrayList<Integer>();
                for (int i = 0; i < 4; i++) {
                    list.add(Integer.parseInt(strs[i]));
                }
                boolean flag = fun(list);
                System.out.println(flag);
            }
        }

        public static boolean fun(List<Integer> list) {
            for (int i = 0; i < list.size(); i++) {
                int temp = list.get(i);
                list.remove(i);
                if (getResult(list, temp)) {
                    return true;
                }
                list.add(i, temp);
            }
            return false;
        }

        public static boolean getResult(List<Integer> list, int temp) {
            if (list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    int n = list.get(i);
                    list.remove(i);
                    if (getResult(list, temp * n) || getResult(list, temp + n) || getResult(list, temp - n)) {
                        return true;
                    } else if (temp % n == 0) {
                        if (getResult(list, temp / n)) {
                            return true;
                        }
                    }
                    list.add(i, n);
                }
                return false;
            } else {
                if (temp == 24) {
                    return true;
                } else {
                    return false;
                }
            }
        }
    }

Knowledge points:

  • DFS depth first searches, determines an operator and keeps using it until it finally returns false or true
  • After removing an element from the list, if it is not found after a deep search, add it back

Tags: Java

Posted on Sun, 09 Feb 2020 15:15:56 -0500 by BlaineSch