Organize positions of a vector

0

I have an exercise that asks you to create two vectors, with real numbers and with 3 elements each. Then copy these values to a new vector with 6 elements. However, the first 3 values must be of the vector that has the highest summation value among the 2 input vectors.

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]

What I had been trying before:

package pct;
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);
}
}
    
asked by anonymous 18.02.2017 / 16:25

4 answers

2

Java offers different ways to copy content from one array to another:

  • Implementing a loop with the for
  • Using the clone
  • Using System.arraycopy
  • Using Arrays.copyOf
  • The most appropriate strategy in this case is arraycopy where you can define exactly the positions you want to copy with just one row, the best performance, and no need to import any library additional, that is, 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: link

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

  • Object objetoQueSeraCopiado
  • int posicaoInicialObjetoQueSeraCopiado
  • Object objetoDestino
  • int posicaoObjetoDestino
  • int tamanhoObjetoCopiado
  • Used in the example:

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

    vector1 will be copied, from position zero , to vector3 , starting at position zero , by making a full size ( length length ) copy of vector1 .

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

    vector2 will be copied, from position zero , to vector3 , starting at position three , by making a full size ( length length ) copy of vector2 .

    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() is very simple:

    int [] vetorB = vetorA.clone();
    

    Using the java.util.Arrays library you can use copyOf :

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

    More information: link

    I hope this helps ...

    Good Luck!

        
    19.02.2017 / 06:40
    2

    One way to do this is to use the arraycopy after checking which sum is greater. 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 srcPos argument is the starting position in the array source. The destPos argument is the starting position in the array target. Finally, length is used to specify the number of elements to be copied.

    Here's 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 on Ideone .

        
    18.02.2017 / 17:09
    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));
        }
    }
    
        
    18.02.2017 / 17:41
    -2

    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);
            }
        }
    }
    

    link

        
    18.02.2017 / 17:18