Return the inverse of a vector

2

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

1 2 3 turn 3 2 1

I'm currently trying to make a method of 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;
    }
    
asked by anonymous 20.05.2015 / 00:21

3 answers

3

Try 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 have has a problem:

        vetInvert[i] = vet[i];

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

        vetInvert[tamanho - 1 - i] = vet[i];
    
20.05.2015 / 00:24
2

Using Collections of Java to get the reverse order is quite simple:

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

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

    
20.05.2015 / 01:57
0

If you can use the external library commons-lang you only need to call a method:

ArrayUtils.reverse(array);
    
20.05.2015 / 01:33