Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- import java.util.Scanner;
- public class Test {
- public static void main(String[] args){
- Test test = new Test();
- test.combineOperators();
- Scanner scanner = new Scanner(System.in);
- int result = scanner.nextInt(); //get input
- int[] numbers = new int[5];
- for(int i = 0; i <5; i++){
- numbers[i] = scanner.nextInt();
- }
- ArrayList<Integer> results = test.operationsOnArrays(numbers, test.combineOperators()); //check for results
- if(results.contains(result)){
- System.out.println(result + " is a possible solution");
- }else{
- System.out.println(result + " is not a possible solution");
- }
- }
- public ArrayList<String[]> combineOperators(){ //create all possible combinations of operators
- String[] signs = {"+","-","*"};
- ArrayList<String[]> combinations = new ArrayList<String[]>();
- for(String a : signs){
- for (String b : signs){
- for(String c : signs){
- for(String d: signs){
- String[]temp = {a,b,c,d};
- combinations.add(temp);
- }
- }
- }
- }
- return combinations;
- }
- public ArrayList operationsOnArrays(int[] num, ArrayList<String[]> combinations){ //do the math with every combination on given ints
- ArrayList<Integer> list = new ArrayList<Integer>();
- for(String[] operators : combinations){ //for every operators combination
- int result = num[0];
- for(int i = 0; i<=3 ; i++){
- result = doTheMath(operators[i],result,num[i+1]); // take two ints and operator
- }
- list.add(result);
- }
- return list;
- }
- public int doTheMath(String operator, int prev, int next){ // it take two ints from input array, and do operation
- if(operator.equals("+")){ // determined by a taken operator
- return prev + next;
- }else if(operator.equals("-")){
- return prev - next;
- }else if(operator.equals("*")){
- return prev *next;
- }
- return 0;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement