来自数组的随机数组 - Java

时间:2017-04-29 14:46:33

标签: java arrays random

我有一个数组:{红色,蓝色,绿色}。我想生成其他包含ex:{red,red,blue,green,blue}的数组。我想使用随机数组的可变长度。

3 个答案:

答案 0 :(得分:1)

你可以尝试这样的事情:

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

输出例如:

[GREEN, GREEN, BLUE, GREEN, RED, BLUE, GREEN, RED, RED, BLUE]

答案 1 :(得分:0)

以下是如何使用随机数组的示例:

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
}

<强>输出

[red, green, green, green, green, green, red, blue, red, red]

答案 2 :(得分:0)

伪代码:

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

这真的很难吗?