Java Relay Kernel Based on Element Number

Here is my array:

int[] myArray = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; 

Let's say I want to move myArray [3] (it can be any element) and myArray [6] (the same with this) to the front of the array when rearranging, how can I do this? Example:

It:

 {0, 1, 2, 3, 4, 5, 6, 7, 8, 9} 

In it:

 {3, 6, 0, 1, 2, 4, 5, 7, 8, 9} 
+4
source share
2 answers

To move the index x to the beginning, you need to:

  • Remember that the index x
  • Copy all values โ€‹โ€‹from 0 to x - 1 up one index, for example. with System.arrayCopy
  • Set the value at index 0 to the value that you remembered in the first step.

For instance:

 public void moveToHead(int[] values, int index) { // TODO: Argument validation int value = values[index]; System.arraycopy(values, 0, values, 1, index - 1); values[0] = value; } 

Note that System.arrayCopy handles copying accordingly:

If the arguments src and dest refer to the same array object, then copying is performed as if the components at srcPos through srcPos + length-1 were first copied to a temporary array with length components, and then the contents of the temporary array were copied to destPos positions through destPos + length-1 of the target array.

In your original example, two elements were mentioned - although you could potentially do all this more effectively, knowing both elements in advance, it would be much easier to define this as two calls to moveToHead . You need to take care of the order - for example, if you want to transfer index 6 to the head first, you will need to move index 4, not index 3, to account for the first move.

+4
source

Another solution might be to convert your array to a list thanks to asList and just use the remove and add methods:

 List<Integer> myList = new ArrayList<Integer>(Arrays.asList(myArray)); myList.add(myList.remove(myIndex)); 
+2
source

Source: https://habr.com/ru/post/1387157/


All Articles