Return the inverse of a vector

Asked

Viewed 1,805 times

2

How do I reverse the values of a vector? Example:

1 2 3 turn 3 2 1

I am currently trying to make a method of the type..

public static int [] vetorInvertido(int [] vet){
    int [] vetInvert = new int[vet.length];
        for(int i=vet.length-1;i>=0;i--){
            for(int j=0; j<=vetInvert.length; j++){
            vetInvert[j] = vet[i];
           }
        }
        return vetInvert;
    }
  • Duplicate Stack in English, for a look: http://stackoverflow.com/a/2138004

3 answers

3


Try it like this:

public static int[] vetorInvertido(int[] vet) {
    int tamanho = vet.length;
    int[] vetInvert = new int[tamanho];
    for (int i = 0; i < tamanho; i++) {
        vetInvert[tamanho - 1 - i] = vet[i];
    }
    return vetInvert;
}

The reason is that the code you made has a problem:

        vetInvert[i] = vet[i];

In your code, it will just copy the vector, the order you iterate the positions does not matter. What you have to do is put the positions of one as the inverse of the other, such as in the code of the beginning of this answer:

        vetInvert[tamanho - 1 - i] = vet[i];
  • In your code I got a strange result... [I@13af427

  • 1

    @Guilherme That’s why: http://answall.com/a/64371/132 - Basically, the System.out.println does not normally work with any array, as arrays do not implement toString(). You must use System.out.println(Arrays.toString(array)); instead of System.out.println(array);.

  • thanks, it worked perfectly!

2

Using Collections Java to get the reverse order is very simple:

Integer vetor[] = {1,2,3};
Collections.reverse(Arrays.asList(vetor));

With this, the order of the elements of the vector vetor[] will be reversed.

0

If you can use the external library Commons-lang only one call to a method is necessary:

ArrayUtils.reverse(array);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.