1

I have an array such as

int[] array = {4,1,1,1,1,4};

The first 4 signifies that there are 4 numbers to be calculated, and the last 4 signifies that we need to find a combination of operations to achieve that number.

I want to make the loop stop when I reach the last 1, or in general the number before the last in the array. Usually this is easy, however when all the numbers are the same, finding the index of one of them at the end is difficult ... suggestions?

I usually use:

int last_num = integers[integers.length-2];


if(last_num == integers[a]){ System.out.println(Total); )

However if last_num = 1, and integers[a] =1, then it can stop after the first time going through the loop.

Same thing occurs if trying to find the index using binarySearch due to all the numbers being the same..

Recursive Function (note I am new to Java and I'm sure I'm using the function wrong because I'm just returning a true everytime, however my goal is to have it run and print out the values I want - please excuse that for now):

public static boolean addMoreMore(int a , double b , String c, int[] integers , int target, double possible2, int last_num){
  int counter = 0;
  char[] symbols1 = {'+' , '-' , '*','/'};            
  for(int z = 0; z<4; z++){
        char operator = symbols1[z];

        String what1 = ""; 
        double total1 = 0;            

        if(operator == '+'){
            total1 = b + integers[a];
            what1 = c + "+" + integers[a];  //System.out.println(what1);    
            if(last_num  != integers[a]){
                //System.out.println("ACTIVATE1");
                addMoreMore(a+1 , total1, what1, integers, target, possible2, last_num);
         }
        else {
            if(total1 == target){
                System.out.println(what1 + " = " + total1);     
            }
        }
  }    
        else if(operator == '-'){

            total1 = b - integers[a];
            what1 = c + "-" + Integer.toString(integers[a]);       
            //System.out.println(what1);                                   

            if(last_num  != integers[a]){
                //     System.out.println("ACTIVATE2");
                addMoreMore(a+1 , total1, what1, integers, target, possible2, last_num);  
            }
            else {
                if(total1 == target){
                    System.out.println(what1 + " = " + total1);
                }          
            }
      }
      else if(operator == '*'){
          total1 = b * integers[a];
          what1 = c + "*" + Integer.toString(integers[a]);  
          //System.out.println(what1);                                

          if(last_num  != integers[a]){
              //       System.out.println("ACTIVATE3");
              addMoreMore(a+1 , total1, what1, integers, target, possible2, last_num);       
          }
          else{
              if(total1 == target){
                  System.out.println(what1 + " = " + total1);
              }   
          }
     }
     else if(operator == '/'){
         total1 = b / integers[a];
         what1 = c + "/" + Integer.toString(integers[a]); // System.out.println(what1);  
         if((b % integers[a]) == 0){

             if(last_num  != integers[a]){
                 // System.out.println("ACTIVATE4");
                addMoreMore(a+1 , total1, what1, integers, target, possible2, last_num);  
             }
          else {
              if(total1 == target){
                  System.out.println(what1 + " = " + total1);    
              }
          }
      }    
  }         
}
return true;       
}
9
  • 2
    I'm glad YOU "want to make a recursive function that stops at the last 1", only I don't see your attempt... Commented Jan 16, 2014 at 23:43
  • 2
    Don't use the contents of the array, keep track of your position within the array. Commented Jan 16, 2014 at 23:44
  • 1
    Why not simply use if (integers.length - 2 == a) ? Commented Jan 16, 2014 at 23:44
  • 1
    @Ds.109 : You hadn't added the rest of the code back then, so I thought a was the index you were looping over. As Jim Garrison says, you need to only use the position, not the content. Commented Jan 17, 2014 at 0:03
  • 3
    Overloading an array/collection like that is a bad idea. Have the last 4 as a separate parameter, and drop the initial 4 (you can infer number of array elements you have to process by looking at length of array). Arrays should be arrays of one type of thing, e.g. colours, pixels, heights of buildings, etc...). Mixing is a nightmare to keep track of and leads to unmaintainable spaghetti code. Commented Jan 17, 2014 at 0:05

2 Answers 2

1

As a comment stated, compare the index position of the array instead of the value.

For example:

Instead of

if(last_num == integers[a]){ System.out.println(Total); )

Try

if(integers.length - 2 == a) { System.out.println(Total); }

Assuming a is a counting variable for the index position in your array.

Sign up to request clarification or add additional context in comments.

4 Comments

Possible - problem is how do I count through this. The idea is I have to go through all the possible combinations of operations with the same order of numbers - i.e. if I have 3 4 5 , then I have to try 3+4+5, 3+4-5, 3+4*5, 3+4/5, 3-4+5, etc... So how could I count through that?
How can I get the position of integers[a] ?
@Ds.109 I'm not sure how to answer your first problem, seeing as I'm not trying to solve your entire algorithm. The focus of my answer is just to show you how to check when you're at the last number. And the position of integers[a] is just a
... You actually solved my confusion with that comment. integers[a] is just a... i can't believe I missed that. Thank You.
0
import java.util.ArrayList;
import java.util.LinkedList;

public class Q21175220 {
    static enum Operation {
        ADD,
        SUBTRACT,
        MULTIPLY,
        DIVIDE
    }

    public static void getValidOperations
    (
        final ArrayList<Operation[]> validOperations,
        final LinkedList<Operation> operations,
        final int[] values,
        final int desired_total
    )
    {
        if ( operations.size() < values.length - 1 )
        {
            operations.addLast( Operation.ADD );
            getValidOperations( validOperations, operations, values, desired_total );
            operations.removeLast();
            operations.addLast( Operation.SUBTRACT );
            getValidOperations( validOperations, operations, values, desired_total );
            operations.removeLast();
            operations.addLast( Operation.MULTIPLY );
            getValidOperations( validOperations, operations, values, desired_total );
            operations.removeLast();
            operations.addLast( Operation.DIVIDE );
            getValidOperations( validOperations, operations, values, desired_total );
            operations.removeLast();
        } else {
            int i = 0;
            int total = values[i];
            for ( Operation op : operations )
            {
                ++i;
                switch ( op )
                {
                case ADD:       total += values[i]; break;
                case SUBTRACT:  total -= values[i]; break;
                case MULTIPLY:  total *= values[i]; break;
                case DIVIDE:    total /= values[i]; break;
                }
            }
            if ( total == desired_total )
                validOperations.add( operations.toArray( new Operation[ values.length - 1 ] ) );
        }
    }

    public static String calculationToString
    (
        final Operation[] operations,
        final int[] values
    )
    {
        final StringBuffer buffer = new StringBuffer();
        int i = 0;
        buffer.append( values[i] );
        for ( Operation op : operations )
        {
            switch ( op )
            {
            case ADD:       buffer.append('+'); break;
            case SUBTRACT:  buffer.append('-'); break;
            case MULTIPLY:  buffer.append('*'); break;
            case DIVIDE:    buffer.append('/'); break;
            }
            buffer.append( values[++i] );
        }
        return buffer.toString();
    }

    public static void test
    (
        final int[] values,
        final int desired_total
    )
    {
        final ArrayList<Operation[]> validOperations = new ArrayList<Operation[]>();
        getValidOperations( validOperations, new LinkedList<Operation>(), values, desired_total );
        for ( Operation[] ops: validOperations )
            System.out.println( calculationToString( ops, values ) + " = " + desired_total );
    }
    public static void main(String[] args) {
        test( new int[]{ 1, 1, 1, 1 }, 4 );
        test( new int[]{ 1, 1, 1, 2, 5 }, 10 );
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.