我想浏览随机生成的颜色列表,并检查它们是否彼此不同。与colour1 == colour2不同,但请确保生成的颜色不太相似。

我的意思是使用此代码(或类似的代码)生成颜色列表:

Random randomGenerator = new Random();
ArrayList<Color> colours = new ArrayList<Color>();
while(true) {
    int red = randomGenerator.nextInt(255);
    int green = randomGenerator.nextInt(255);
    int blue = randomGenerator.nextInt(255);
    Color randomColour = new Color(red,green,blue);
    if(!colours.contains(randomColour)) {
        colours.add(randomColour);
    }
    if(colours.size() >= 100) {
        break;
    }
}

最佳答案

我的第一个想法是这样的,它是伪随机的

    Random randomGenerator = new Random();
    ArrayList<Color> colours = new ArrayList<Color>();
    int k1 = 0, k2=0,  k3 = 0;
    while(true) {
        k1 = k1 +1 <= 4 ? k1 +1 : (k1+1)%4;
        k2 = k2 +2 <= 4 ? k2 +2 : (k2+2)%4;
        k3 = k3 +3 <= 4 ? k3 +3 : (k3+3)%4;
        int red = randomGenerator.nextInt(255/4*k1);
        int green = randomGenerator.nextInt(255/4*k2);
        int blue = randomGenerator.nextInt(255/4*k3);
        Color randomColour = new Color(red,green,blue);
        System.out.println("R:" +randomColour.getRed()+"G:" +randomColour.getGreen()+"B:" +randomColour.getBlue());
        if(!colours.contains(randomColour)) {
            colours.add(randomColour);
        }
        if(colours.size() >= 100) {
            break;
        }

    }

10-06 12:50