Invert values from one vector to another vector

Asked

Viewed 2,979 times

2

I am in the second semester of college, we are learning vector, and I am very lost in the exercise list.

An exercise asks the user to type 5 elements for a vector, and then I have to take these elements, send them to another vector, only in reverse order. How can I do that?

Example:

vetor_original [ 1, 2, 3, 4, 5]
vetor_cppia [ 5, 4, 3, 2, 1]

2 answers

1


You can do it like this:

int[] vetor_original = { 1, 2, 3, 4, 5 };
int tamanhoVetorOriginal = vetor_original.length;
int[] vetor_copia = new int[tamanhoVetorOriginal];
int tamanhoVetorOriginalZeroBased = tamanhoVetorOriginal - 1;
for(int i = 0; i < tamanhoVetorOriginal; i++) {
    vetor_copia[i] = vetor_original[tamanhoVetorOriginalZeroBased - i];
    System.out.print(vetor_copia[i]);
}

Exit: 54321


Explanation

  • int tamanhoVetorOriginal: represents the size of the original vector. That is, 5;
  • int[] vetor_copia = new int[tamanhoVetorOriginal]: creates a new array/array of the same size as vetor_original;
  • int tamanhoVetorOriginalZeroBased: arrays are structures zero-based. This means that your record count never starts from number 1, but rather from 0. Ex: if you do System.out.println(vetor_original[1]) will be printed 2 and not 1, for the record 1 is in position vetor_original[0]. I created this variable to use as a little trick to traverse the array. If the size of the vetor_original is 5, if we go from 0 to 5 we will have 6 positions: 0, 1, 2, 3, 4, 5. So I subtract 1 from the original size, making this variable to be set to the value 4 and when we go through: 0, 1, 2, 3, 4 -> 5 positions;
  • vetor_copia[i] = vetor_original[tamanhoVetorOriginalZeroBased - i]: iterates the vetor_original back to front. Ex: assuming i = 0, we shall have: vetor_copia[0] = vetor_original[tamanhoVetorOriginalZeroBased - 0] -> in position 0 of vetor_copia the value of the last position of the vetor_original;

0

You fall into a situation where you may not know which numbers are typed so you can do so automatically:

public static void main(String[] args) {
        int[] a = { 2, 3, 4, 5 };

        for (int i = 0; i < a.length; i++) {
            System.out.println(a[i]);
        }
        System.out.println("Agora a ordem invertida");
        for (int j = a.length - 1; j >= 0; j--) {
            System.out.println(a[j]);
        }

    }

First I do one for printing the original values and then after I create another to show in reverse.

Browser other questions tagged

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