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;
}
if (integers.length - 2 == a)?awas the index you were looping over. As Jim Garrison says, you need to only use the position, not the content.