【问题标题】:Random Array from an array - Java [closed]来自数组的随机数组 - Java [关闭]
【发布时间】:2017-09-27 13:29:20
【问题描述】:

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

【问题讨论】:

标签: java arrays random


【解决方案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]

【讨论】:

  • @StringDot 如果您对代码有任何疑问,请不要犹豫
【解决方案2】:

伪代码:

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

真的有那么难吗?

【讨论】:

    【解决方案3】:

    这是一个如何使用随机数组的示例:

    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]
    

    【讨论】:

    • 谢谢!像魅力一样工作
    • 不客气...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-07
    • 1970-01-01
    相关资源
    最近更新 更多