Organizing positions of a vector

Asked

Viewed 806 times

3

  • I need to create two vectors, with 3 elements each and real numbers

  • Then copy these values to a new vector with 6 elements

  • The first 3 values must be of the vector with the highest summation value

Example:

vetor1 [2.3, 4.7, 1.4], soma resulta em 8.4
vetor2 [1.6, 6.2, 3.5], soma resulta em 11.3
vetor3 [1.6, 6.2, 3.5, 2.3, 4.7, 1.4]

My code:

public class exer6 {
    public static void main(String[] args) {
        double[] vetor1 = {4.3, 2.5, 4.7};
        double[] vetor2 = {5.7, 5.8, 3.7};
        double[] vetor3 = new double[6];
        double soma1 = 0, soma2 = 0;
        for(int i = 0; i < vetor1.length; i++) {
            soma1+=vetor1[i];
        }
        for (int i = 0; i < vetor2.length; i++) {
            soma2+=vetor2[i];
        }
        if (soma1 > soma2) {
            soma1 = vetor3.length;
            soma2 = vetor3.length;
        } else {
            soma2 = vetor3.length;
            soma1 = vetor3.length;
        }
        System.out.println(vetor3);
    }
}
  • Welcome to the site. What you have tried to do?

  • I started programming recently, and then try not to laugh at my logic.

  • If the vectors have the same size, it can be summed with a single loop.

4 answers

4


The Java offers different ways to copy the contents of a array to another:

  1. Implementing a loop with the command for
  2. Using the method clone
  3. Using System.arraycopy
  4. Using Arrays.copyOf

The most appropriate strategy in this House is arraycopy in which you can set exactly the positions you want to copy with just one line, with the best performance and without the need to import any additional library, ie, easy and efficient.

public class Exercicio6 {
  public static void main(String[] args) {
    float somaV1 = 0, somaV2 = 0;
    float[] vetor1 = {4.3f, 2.5f, 4.7f};
    float[] vetor2 = {5.7f, 5.8f, 3.7f};

    for(int i = 0; i < vetor1.length; i++) {
      somaV1 += vetor1[i];
      somaV2 += vetor2[i];
    }

    System.out.print("Vetor 1 [" + vetor1[0] + ", " + vetor1[1]);
    System.out.println(", " + vetor1[2] + "] Soma = " + somaV1);
    System.out.print("Vetor 2 [" + vetor2[0] + ", " + vetor2[1]);
    System.out.println(", " + vetor2[2] + "] Soma = " + somaV2);

    float[] vetor3 = new float[6];

    if (somaV1 > somaV2) {
      System.arraycopy(vetor1, 0, vetor3, 0, vetor1.length);
      System.arraycopy(vetor2, 0, vetor3, 3, vetor2.length);
      System.out.println("\nVetor 1 com maior soma, resultado final:\n");
      System.out.print("Vetor 3 [" + vetor3[0] + ", " + vetor3[1] + ", " + vetor3[2]);
      System.out.print(", " + vetor3[3] + ", " + vetor3[4] + ", " + vetor3[5] + "]");
    } else {
      System.arraycopy(vetor2, 0, vetor3, 0, vetor2.length);
      System.arraycopy(vetor1, 0, vetor3, 3, vetor1.length);
      System.out.print("\nVetor 2 com maior soma, resultado final:\n");
      System.out.print("Vetor 3 [" + vetor3[0] + ", " + vetor3[1] + ", " + vetor3[2]);
      System.out.print(", " + vetor3[3] + ", " + vetor3[4] + ", " + vetor3[5] + "]");
    }
  }
}

Run the code online: http://ideone.com/g6gKLR

The only thing that can be stranger in the use of arraycopy are the parameters that may confuse you, but below is a brief explanation of what each means in the order in which they are passed:

  1. Object objetoQueSeraCopiado
  2. int posicaoInicialObjetoQueSeraCopiado
  3. Object objetoDestino
  4. int posicaoObjetoDestino
  5. int tamanhoObjetoCopiado

Used in the example:

System.arraycopy(vetor1, 0, vetor3, 0, vetor1.length);

The vector 1 will be copied from the position zero, to the vector 3, starting in position zero, making a full size copy (length) of vector 1.

System.arraycopy(vetor2, 0, vetor3, 3, vetor2.length);

The vector 2 will be copied from the position zero, to the vector 3, starting in position three, making a full size copy (length) of vector 2.


To copy vectors using for:

//Criando um vetorB do mesmo tamanho do vetorA
int [] vetorB = new int[vetorA.length];

//O vetorB recebe todos os dados do vetorA
for (int i=0; i < vetorA.length; i++) {
    vetorB[i] = vetorA[i];
}
//Exibe os dados do vetorB copiados do vetorA
for (int i=0; i < vetorB.length; i++) {
    System.out.println("vetorB[" + i + "] = " + vetorB[i]);
}

To make a vector copy using the native method clone() it’s very simple:

int [] vetorB = vetorA.clone();

Through the library java.util.Arrays it is possible to use the copyOf:

import java.util.Arrays;

int [] vetorB = Arrays.copyOf(vetorA, vetorA.length);

More information:

3

One way to do this is to use the method arraycopy after checking which sum is larger. To use the method you need to specify some parameters, as indicated in the documentation:

public static void arraycopy(Object src, int srcPos, Object dest, int
destPos, int length)

The arguments src and dest represent the origin and destination vectors, respectively. The argument srcPos is the initial position in array origin. The argument destPos is the initial position in array destination. Finally, length is used to specify the number of elements that will be copied.

See how it would look:

 if (soma1 > soma2) {

     System.arraycopy(vector1, 0, vector3, 0, vector1.length);
     System.arraycopy(vector1, 0, vector3, vector1.length, vector2.length);

 } else {

     System.arraycopy(vector2, 0, vector3, 0, vector2.length);
     System.arraycopy(vector2, 0, vector3, vector2.length, vector1.length);
 }

See working here in Ideone.

  • It would be interesting to explain what is happening in this code, because it is an unusual method to use (at least for me it is very unusual, the OP that is starting may be even more)

  • @diegofm yes, sir! =)

0

import java.util.Arrays;

public class Test
{
    public static void main(String args[])
    {
        double[] vetor1 = new double[]{2.3, 4.7, 1.4};
        double[] vetor2 = new double[]{1.6, 6.2, 3.5};
        double[] vetor3 = new double[vetor1.length+vetor2.length];
        double soma1, soma2;
        int i;

        //Calcular a soma de cada vetor
        soma1 = soma2 = 0.0;
        for(i=0; i < vetor1.length; ++i)
            soma1 += vetor1[i];
        for(i=0; i < vetor2.length; ++i)
            soma2 += vetor2[i];

        //Verificar se os vetores estão na ordem pretendida
        if (soma2 > soma1)
        {
            //Trocar os vetores, pois estão ao contrário
            double[] vetorTmp = vetor1;
            vetor1 = vetor2;
            vetor2 = vetorTmp;
        }

        //Copiar o vetor1 para as primeiras posições do vetor3
        for(i=0; i<vetor1.length; ++i)
            vetor3[i] = vetor1[i];
        //Copiar o vetor2 para as últimas posições do vetor3
        for(i=0; i<vetor2.length; ++i)
            vetor3[i+vetor1.length] = vetor2[i];
        //Imprimir o vetor na consola
        System.out.println(Arrays.toString(vetor3));
    }
}

-3

Use the Sort() method, In the case of Java to use it import the lib java.util.Arrays.

Arrays.Sort(Array);

Example:

import java.util.Arrays;

public class SortArray {

    public static void main(String[] args) {

        // initializing unsorted int array
        double myArr[] = {1.6, 6.2, 3.5, 2.3, 4.7, 1.4};

        // let us print all the elements available in list
        for (double number : myArr) {
            System.out.println("Number = " + number);
        }

        // sorting array
        Arrays.sort(myArr);

        // let us print all the elements available in list
        System.out.println("The sorted double array is:");
        for (double number : myArr) {
            System.out.println("Number = " + number);
        }
    }
}

https://www.tutorialspoint.com/java/util/arrays_sort_int.htm

  • I don’t see how that solves the question.

Browser other questions tagged

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