java - Find what number it used to be before element reset -


given array size, in case array size 5.

this array contains numbers 1 5 (must contain of them)

[1 | 2 | 3 | 4 | 5]  0   1   2   3   4 

and now, 1 element reset , set 0, , mission find number used before turned 0.

so have simple solution:

explained: first, loop 1 5, create inner loop check if i first loop exists in whole array, if doesn't exist, means value used before 0, because array contained numbers 1 5 or 1 100 (doesn't matter) , there's on'y 1 rested element.

code:

    int[] numbers = new int[]{1, 2, 3, 4, 5};     numbers[1] = 0;      int lost = -1;      loop:      (int = 1; <= numbers.length; i++) {         (int j = 0; j < numbers.length; j++) {             if (numbers[j] == i) {                 continue loop;             }         }         lost = i;         break loop;     }      system.out.println(lost); 

that solution not bad, think there's better solution, more stable.

i have thought mathematically, in our example:

1 + x + 3 + 4 + 5 = 15 x = 2 

mathematically, it's easy. there way can done in programming language easy mathematically? better algorithms can think of solve question?

this works 1 element being reset. subtract each remaining element sum , ever left on have been previous number element before reset.

public static void main(string[] args) throws exception {     int sum = 15;     int[] numbers = new int[] { 1, 2, 3, 4, 5 };      numbers[4] = 0;     (int = 0; < numbers.length; i++) {         sum -= numbers[i];     }     system.out.println(sum); } 

results:

5


Comments

Popular posts from this blog

javascript - gulp-nodemon - nodejs restart after file change - Error: listen EADDRINUSE events.js:85 -

Fatal Python error: Py_Initialize: unable to load the file system codec. ImportError: No module named 'encodings' -

javascript - oscilloscope of speaker input stops rendering after a few seconds -