特别是关于均匀分布,每 10 个像素有 1 个随机位置似乎没问题:
哦等等,每 1 个像素有 1 个随机位置,种子线程方法似乎更好!?在完美的均匀分布中(对于大小 250000),它将是全黑的:
剩下:
public class SingleRandomProof extends JFrame {
public static final int WIDTH = 500;
public static final int HEIGHT = 500;
public static final int SIZE = WIDTH * HEIGHT;
public static void main(String[] args) {
SingleRandomProof proof = new SingleRandomProof();
proof.pack();
proof.setVisible(true);
proof.doCalc();
}
private JLabel panel;
public SingleRandomProof() throws HeadlessException {
super("1 random");
BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_ARGB);
panel = new JLabel(new ImageIcon(image));
setContentPane(panel);
}
private void doCalc() {
BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_ARGB);
Graphics g = image.getGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, WIDTH, HEIGHT);
g.setColor(Color.BLACK);
Random r = new Random(37);
for (int i = 0; i < SIZE; i++) {
int position = r.nextInt(SIZE);
g.fillRect(position % HEIGHT, position / HEIGHT, 1, 1);
}
panel.setIcon(new ImageIcon(image));
}
}
正确的:
public class SeededThreadRandomProof extends JFrame {
public static final int WIDTH = 500;
public static final int HEIGHT = 500;
public static final int SIZE = WIDTH * HEIGHT;
public static void main(String[] args) {
SeededThreadRandomProof proof = new SeededThreadRandomProof();
proof.pack();
proof.setVisible(true);
proof.doCalc();
}
private JLabel panel;
public SeededThreadRandomProof() throws HeadlessException {
super("10 seeded randoms");
BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_ARGB);
panel = new JLabel(new ImageIcon(image));
setContentPane(panel);
}
private void doCalc() {
BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_ARGB);
Graphics g = image.getGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, WIDTH, HEIGHT);
g.setColor(Color.BLACK);
Random initRandom = new Random(37);
for (int j = 0; j < 10; j++) {
Random r = new Random(initRandom.nextLong());
for (int i = 0; i < SIZE / 10; i++) {
int position = r.nextInt(SIZE);
g.fillRect(position % HEIGHT, position / HEIGHT, 1, 1);
}
}
panel.setIcon(new ImageIcon(image));
}
}