Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

163
Visualizações
Random Array from an array - Java

I have an array : {red, blue, green} . I want to generate other array having random contain ex: {red,red,blue,green,blue} . I want to use a variable length of the random array.

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

you can try something like this:

import java.util.ArrayList;
import java.util.Random;

public class RandomArrayTest {

    public static void main(String[] args) {

        System.out.println(RandomArrayTest.randomArrayOfColors(10)); // for example

    }

    public static ArrayList<String> randomArrayOfColors(int lenOfArray){
        String[] colors = {"RED", "GREEN", "BLUE"};
        ArrayList<String> rndArray = new ArrayList<String>();
        Random rnd = new Random();
        for(int i=0; i<lenOfArray; i++){ // populate the array
            rndArray.add(colors[rnd.nextInt(colors.length)]);
        }

        return rndArray;    
    }
}

The output for example:

[GREEN, GREEN, BLUE, GREEN, RED, BLUE, GREEN, RED, RED, BLUE]
over 4 years ago · Santiago Trujillo Relatório

0

Here is an example how you can use random with array :

public static void main(String[] args) {
    String colors[] = {"red", "blue", "green"};//your array of colors
    int n = 10;//number of element you want to make in your new array
    String random[] = new String[n];
    for(int i = 0; i< n; i++){
        //add values with random values of the colors array
        random[i] =  colors[new Random().nextInt(colors.length)];
    }
    System.out.println(Arrays.toString(random));//print the random array
}

Output

[red, green, green, green, green, green, red, blue, red, red]
over 4 years ago · Santiago Trujillo Relatório

0

Pseudocode:

colours <- {red, blue, green}
length <- random (0 to maxLength)
repeat length times
  colour <- pick random from colours
  append colour to outputArray
end repeat
return outputArray

Was that really so difficult?

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda