I don’t know how to calculate the distance

Asked

Viewed 82 times

1

    Chromosome chromosome = new Chromosome();
    int[] gene = new int[6];
    gene[0] = 0;
    gene[1] = (int) (1 + (Math.random() * 3));
    gene[2] = (int) (4 + (Math.random() * 4));
    gene[3] = (int) (8 + (Math.random() * 4));
    gene[4] = (int) (12 + (Math.random() * 3));
    gene[5] = 15;

    chromosome.setGenes(gene);
    return chromosome;
}

I have this method that inserts random numbers, and with that, I need to do another method that calculates the total distance travelled, which would be the 6 positions of the array. But I’m having trouble seeing a way to add that distance in another method.

  • You want to add up all the indices of that array, that’s it?

  • That’s right, but I don’t know how to have those numbers in another method

2 answers

0


You can create the method:

public static int somarArray(int[] array) {
    int valorTotal = 0;
    for (int i = 0; i < array.length; i++) {
        valorTotal += array[i];
    }
    return valorTotal;
}

passing your array ex:

int[] gene = new int[6];
gene[0] = 0;
gene[1] = (int) (1 + (Math.random() * 3));
gene[2] = (int) (4 + (Math.random() * 4));
gene[3] = (int) (8 + (Math.random() * 4));
gene[4] = (int) (12 + (Math.random() * 3));
gene[5] = 15;

System.out.println(Classe.somarArray(gene));
  • Sorry, but I did not understand this call here: System.out.println(Class.somarArray(gene gene));

  • It’s just for you to see the method out.

  • got it, I’ll see if it works within what I need. Thank you

0

just pass this chromosome object as reference in another method, so you will have access to everything of this object.

example:

private int somaDistancia (Chromosome chromosome){
int soma = 0;
    for(int i=0; i<chromosome.getGenes().length){
        //faz a manipulacao por ex:
        soma += chromosome.getGenes()[i];
    }
    return soma;
}

That’s what you wanted?

  • that’s basically it, but I get by parameter an array of integers

  • would be the same thing, but instead of passing the object by reference would just pass the array.. the @Matheus response fits better

  • yes, yes. but I did not understand his last call with system

  • that call is just trying to print the sum.. somarArray is the name of the method he created.. if you create the method within the same class as this other one, in your case it would be: System.out.println(somarArray(gene));

  • yes, now I understand. Thank you

Browser other questions tagged

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