Reverse the positions

1
 package pag1;

   import java.util.Arrays;
   import java.util.Scanner;

   public class ex3 {
   public static void main (String[] args){
    Scanner x = new Scanner (System.in);

    int posicao = 0;
    int[] numeros = new int [5];
    System.out.println("Digite 5 números: ");

    while (posicao < numeros.length){
        numeros [posicao] = x.nextInt();
        posicao++;          
    }
    System.out.println(Arrays.toString(numeros));
    Arrays.sort(numeros, 0, numeros.length);
    System.out.print("[" + numeros[4] + ", " + numeros[3] + ", " + numeros[2] + ", " + numeros[1] + ", " + numeros[0] + "]");

  }

}

How can I do to show the items of the array reverted without being using this game that I did in the end?

    
asked by anonymous 04.07.2017 / 05:23

2 answers

2

To change two integer variables, you can do the following:

int a = 2;
int b = 4;

int swapAux = a;
a = b;
b = swapAux;

We can use the same logic to swap integers in vector positions. Be i a position in a vector of n elements, indexed by 0, the element opposite i is n - i - 1 .

  

Check for i as the first element i = 0 and as the last element i = n - 1 if you are not convinced of the formula

To ensure that we change the elements only once, we can iterate only halfway. Therefore, the inversion of a vector can be done like this:

public void inverteVetor(int[] vet) {
    for (int i = 0; i < vet.length / 2; i++) {
        int reverso = vet.length - i - 1;

        int swapAux = vet[i];
        vet[i] = vet[reverso];
        vet[reverso] = swapAux;
    }
}
    
04.07.2017 / 05:45
2

Using the new Java 8 and lambdas streams features just do:

int[] numerosInvertidos = IntStream.range(0, numeros.length)
                                   .map(i->numeros[numeros.length-i-1]).toArray();

System.out.println(Arrays.toString(numerosInvertidos)); //mostrar o array todo

Where map maps each value to its inverse through array positions. From 0 to 4 , 1 to 3 , and so on.

    
04.07.2017 / 05:49