Advertisement
Guest User

Untitled

a guest
Apr 20th, 2018
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.31 KB | None | 0 0
  1. import java.util.ArrayList;
  2. import java.util.Scanner;
  3.  
  4. public class Test {
  5.     public static void main(String[] args){
  6.         Test test = new Test();
  7.         test.combineOperators();
  8.         Scanner scanner = new Scanner(System.in);
  9.  
  10.         int result = scanner.nextInt();       //get input
  11.         int[] numbers = new int[5];
  12.         for(int i = 0; i <5; i++){
  13.             numbers[i] = scanner.nextInt();
  14.         }
  15.  
  16.         ArrayList<Integer> results = test.operationsOnArrays(numbers, test.combineOperators());         //check for results
  17.         if(results.contains(result)){
  18.             System.out.println(result + " is a possible solution");
  19.         }else{
  20.             System.out.println(result + " is not a possible solution");
  21.         }
  22.  
  23.     }
  24.     public ArrayList<String[]> combineOperators(){             //create all possible combinations of operators
  25.         String[] signs = {"+","-","*"};
  26.         ArrayList<String[]> combinations = new ArrayList<String[]>();
  27.         for(String a : signs){
  28.             for (String b : signs){
  29.                 for(String c : signs){
  30.                     for(String d: signs){
  31.                             String[]temp = {a,b,c,d};
  32.                             combinations.add(temp);
  33.                     }
  34.                 }
  35.             }
  36.         }
  37.         return  combinations;
  38.     }
  39.  
  40.     public ArrayList operationsOnArrays(int[] num, ArrayList<String[]> combinations){   //do the math with every combination on given ints
  41.         ArrayList<Integer> list = new ArrayList<Integer>();
  42.         for(String[] operators : combinations){         //for every operators combination
  43.             int result = num[0];
  44.             for(int i = 0; i<=3 ; i++){
  45.                 result = doTheMath(operators[i],result,num[i+1]);      // take two ints and operator
  46.             }
  47.             list.add(result);
  48.         }
  49.         return list;
  50.     }
  51.  
  52.     public int doTheMath(String operator, int prev, int next){   // it take two ints from input array, and do operation
  53.         if(operator.equals("+")){                                // determined by a taken operator
  54.             return prev + next;
  55.         }else  if(operator.equals("-")){
  56.             return prev - next;
  57.         }else if(operator.equals("*")){
  58.             return prev  *next;
  59.         }
  60.         return 0;
  61.     }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement