Reputation: 95
I want to write a program that looks for three numbers in array that gives an arithmetic sequence of length three - three numbers a,b and c form an arithmetic sequence of length 3 if: b-a = c-b.
The problem is that he code doesn't print "yes" even when it should, it never get into the command if. I guess I have a problem when writing the math command for b-a = c-b.
public static void main (String[] args) {
int [] a = new int [args.length - 1];W
for (int i = 0; i<a.length; i++) {
a[i] = Integer.parseInt(args[i+1]);
}
for (int i = 0; i < a.length - 2; i++) {
for (int j = i+1; j < a.length - 1; j++) {
int b = a[i];
for (int k = j + 1; k < a.length; k++) {
int c = a[k];
if (b - a[i] == c - b) {
System.out.println("yes");
break;
}
}
}
}
}
}
Upvotes: 0
Views: 2149
Reputation: 69
This works:
public static void main(String[] args) {
int [] a =new int [new Integer(args.length)];
for (int i = 0; i<a.length; i++) {
a[i] = Integer.parseInt(args[i]);
}
for(int j=0;j<a.length;j++){
if(j+2<a.length){
if(a[j+1]-a[j] ==a[j+2] - a[j+1])
System.out.println("Yes........." +a[j] +""+ a[j+1] +"" +a[j+2]);
}
}
}
tested with 2 3 4 6(2 3 4 is sequence) and 1 3 5 7 (1 3 5 and 3 5 7 are sequence)
Upvotes: 1
Reputation: 10665
I think this is what you want:
Changes:
Arrays.sort(a);
outerLoop:
for (int i = 0; i < a.length - 2; i++) {
for(int j = i+1; j < a.length - 1; j++){
for(int k = j+1; k < a.length; k++){
if(a[j] - a[i] == a[k] - a[j]){
System.out.println("yes");
break outerLoop;
}
}
}
}
Update:
You are missing the first element of the array because of this code:
int [] a = new int [args.length - 1]
for (int i = 0; i<a.length; i++) {
a[i] = Integer.parseInt(args[i+1]);
}
Change it to:
int [] a = new int [args.length]
for (int i = 0; i<a.length; i++) {
a[i] = Integer.parseInt(args[i]);
}
Upvotes: 1