java - Return 3 integers that have the same difference between each two from smallest to biggest in an array -


so, wanted insert array of numbers, , return 3 numbers in order biggest smallest same difference between each two.

example:

2 3 7 9 12.  

return:

2 7 12 because 2+5=7, 7+5=12.  

the code below attempt. made 3 for loops.

loops:

  • the first went through entire array, picked number.
  • the second: remaining numbers, picked smaller number. calculate difference.
  • the third: finds third number smaller , has same difference vs. second number.

so: (first number - second number) = (second number - third number)

public static void main(string[] args) {     int n;     int num1;     int num2;     int num3;     int dif;      scanner scan = new scanner(system.in);      system.out.print("how many numbers want choose from? ");     n = scan.nextint();      int nums[] = new int[n];      system.out.println("please input integers: ");      (int i=0; i<n ;i++){         nums[i] = scan.nextint();     }      system.out.println(" ");      (int i=0; i<n; i++){          (int j=i+1; j<n; j++){      //compare element rest of array              if(nums[j]<= nums[i]){  //if num @ j smaller num @ i,                 num3 = nums[i];     //then num3 num @                 num2 = nums[j];     //and num2 num @ j                 dif = num3 - num2;  //find difference                  for(int k=i+j+1; k<n; k++){                      if(num2 == (nums[k]+ dif)){ //if num2 num @ k + difference                     num1 = nums[k];             //then num1 must num @ k                     }                    }             }         }     }     system.out.print(num3); //this effort printing them out     system.out.print(num2); //but reason couldn't     system.out.print(num1); //even initialized num3,2,1 outside of loop      scan.close();   //closing scanner object } 

this works 2 fors, if looking faster one.

public static void main(string[] args) throws exception {     list<integer> integers = arrays.aslist(1, 3, 5, 9, 17);     map<string, integer> differencemap = new hashmap<>();      (int = 0; < integers.size(); i++) {         int first = integers.get(i);          (int j = + 1; j < integers.size(); j++) {             int second = integers.get(j);              int difference = second - first;             int next = difference + second;             if (integers.contains(next)) {                 differencemap.put(first + " - " + second + " - " + next, difference);             }         }     }      differencemap.keyset().foreach(system.out::println);  } 

Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -