gpt4 book ai didi

java - 使用java在环形平面上包含/排除

转载 作者:行者123 更新时间:2023-12-02 07:34:35 33 4
gpt4 key购买 nike

我编写了一个程序来解决以下问题:

Implement a diffusion limited aggregation simulation on a toroid plane where seeds are randomly created, and particles move randomly. they move if they particles do not land near a seed or a particle. where user inputs seeds (red pixels), particles (black pixels), steps (no or iterations), plane size.

我的代码非常慢。我怎样才能让它更快?

我随机创建了x和y坐标并绘制了红色像素(种子),然后随机创建了黑色像素(粒子)的x和y,如果黑色像素落在有红色或黑色像素的地方它可以留下,否则它再次随机移动,直到不再有粒子。如果像素落在边界之外,例如 x > border,则 x=0;如果 x <1,则 x= 边界。 y 也一样。

这只是意味着,如果它落在边界上,我会将其移动到相反的边界。然后再次检查相邻像素。我有一个用于创建种子的外循环和用于创建粒子的内循环。在内部循环中,我检查 x,y 位置:

//Place, move, and "stick" the particles; stop if either steps or particles = 0
for (int p = 0; p < particles; p++) {

for (int s = 0; s < steps; s++) {
if (xPos > image.getWidth() ) {
do something
}
else if (xPos < 1) {
do something
}
if (yPos > image.getHeight() - 2) {
do something
}
else if (yPos < 1) {
do something
}
else if (xPos > image.getWidth() && yPos > image.getHeight()) {
do something
}
else if (xPos < 1 && yPos < 1) {
do something
}

//If the surrounding pixels' color is not white, make that particle stick.
if (moveValid()) {
image.setRGB(xPos, yPos, 0xFF000000);
}


//Otherwise, move in a random direction
else {
if(xPos == 1 && image.getRGB(size - 2, yPos) != 0xFFFFFFFF){
draw(xPos,yPos);
}
else if(xPos == size - 2 && image.getRGB(1,yPos) != 0xFFFFFFFF){
draw(xPos,yPos);
}
if(yPos == 1 && image.getRGB(xPos, size - 2) != 0xFFFFFFFF){
draw(xPos,yPos);
}
else if(yPos == size - 2 && image.getRGB(xPos,1) != 0xFFFFFFFF){
draw(xPos,yPos);
}
else {
move();

}


}
}

//Regenerate random x and y positions for the next particle
xPos = random.nextInt(size);
yPos = random.nextInt(size);
}

最佳答案

虽然未显示 draw() 的实现,但看起来您正在更新 BufferedImage 然后渲染它。

  1. 第一步始终是 profile您现有的代码,寻找易于实现的优化。

  2. 第二步有时是搁置现有代码并尝试不同的方法。

您也许能够利用模式- View - Controller 模式,概述 here并讨论了here 。特别是让您的DLA 模型在后台线程上全速发展,同时以更可持续的速度更新您的 View 。这个article建议了几种同步方法,并包含一个使用 javax.swing.Timer 来调整更新速度的相关示例。

关于java - 使用java在环形平面上包含/排除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12433647/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com