I’m trying to write a method in java that will increment a counter for each time one of the following rules is satisfied when iterating through an array.
1) Two adjacent values in an array equal each other and the first value in each pair starts at an even numbered index value (0,2,4…etc)
2) For all adjacent pairs of entries, the values of one pair equal the values of the next pair and length(adjacent pairs of entries) mod 2 = 0
So 0,0,0,0,1,1 satisfies this rule but 0,0,0,1 does not (there are only 3 0’s which violates the last condition)
So far I have this, which implements the first rule:
public class ArrayEvaluate {
public static double evaluate(int[] array)
{
double ruleSat = 0;
for(int index = 0; index < array.length; index++){
if((array[index] == array[index + 1]) &&(index%2==0)){
ruleSat++;
}
}
return ruleSat;
}
public static void main(final String[] args){
int[] array = new int[6];
array[0]= 1;
array[1]=1;
array[2]=3;
array[3]=3;
array[4]=4;
array[5]=4;
evaluate(array);
}
}
However, this does not work completely, and I’m not sure how to go about the second rule.
Thanks
This will prevent the index out of bounds error your receiving
Update for second rule:
This separates the logic for rule 1 and rule 2 so if you ever need to change a rule individually they are independent.
public class ArrayEvaluate {
}