我正在尝试滚动浏览垂直像素上的每个RGB颜色组合。在此示例中,假设像素列为1080。我知道所有可能的组合在这个数字时约为180亿。我似乎无法将头缠绕在循环结构上。我有在这里找出一个像素的所有颜色组合的循环。
for(int r = 0;r < 256;r++){
for(int g = 0;g < 256;g++){
for(int b = 0;b < 256;b++){
pixelC =
Integer.toString(r)+":"+
Integer.toString(g)+":"+
Integer.toString(b)+";";
}
}
}
现在,我需要可以将像素颜色应用于列的东西。我只是不确定如何确定这样做的逻辑,因为我必须在所有可能的组合中应用颜色。因此,拥有所有白色的垂直条带有所有黑色的垂直条,这不是我的目标。
您要完成的工作太困难且笨拙。
基本上,您正在尝试在基本256^3 = 16,777,216
中计数。并且列高为1080,组合数为天文学!
(256^3)^1080 ≈ 4.983 × 10^7802
让我用简化的示例解释。假设它是高度4的,而不是列的高度为1080。而不是每个像素的16,777,216不同的颜色组合,而是说我们只有10种不同的颜色组合。
此外,而不是由RGB组成,而是说每种颜色都可以从0-9起一个值。在此示例中,(4个像素的)列可以在10^4 = 10,000
不同的状态中。
让我们想象一下:考虑一下列位于其侧面,因此它是水平的,让我们像对待它一样对待它是一个可以从0-9旋转的组合锁之一。
这将是初始状态(color = 0处的所有4个拨号/像素):
-------------------------
| 0 | 0 | 0 | 0 |
-------------------------
这将是最终状态(颜色= 9处的所有4个拨号/像素):
-------------------------
| 9 | 9 | 9 | 9 |
-------------------------
在您的情况下,您的组合锁将具有1080个表盘,每个拨盘可以从0-16,777,215
旋转现在,我对如何简化代码很感兴趣,以便您在n是列的高度的一般情况下不必为循环或n个循环。
。这是我想到的:
// This represents the combination lock with 4 dials
int [] arr = new int [4];
// This represents how many states each dial can be in
int base = 10; // (0-9)
boolean done = false;
while (!done)
{
// just for printing out the current state of the array
System.out.println(Arrays.toString(arr));
int index = 0;
// get to the first dial that has not reached its max value
while (index < arr.length && arr[index] == base - 1)
{
index++;
}
// all dials are at the max value -> we are done
if (index == arr.length)
{
done = true;
}
else
{
// increase the first dial we found to not have a max value
arr[index]++;
// set all dials before it to 0
for (int i = 0; i < index; i++)
{
arr[i] = 0;
}
}
}
NOTE :此算法从左到右增加了值。我认为这在将图形中的一列调整到实际问题中是有意义的,因为您将开始从上下向下与自下而上的颜色更改颜色。如果您希望颜色从自下而上开始更改,则可以通过更改索引,增量减少等轻松调整它。
。现在,此示例用于简单的整数值和int数组。我们如何适应您的颜色问题?
首先,让我们假设列切片是java.awt.Color
也就是说, int [] arr = new int [4];
变为 Color [] arr = new Color [4];
接下来,而不是int base = 10; // (0-9)
我们将拥有int base = 16777216; // (0-16,777,215)
现在,其余代码几乎相同,除了我们必须调整一些内容:
这个:
while (index < arr.length && arr[index] == base - 1)
{
index++;
}
需要成为这个:
while (index < arr.length && arr[index].equals(Color.WHITE))
{
index++;
}
这个:
// increase the first dial we found to not have a max value
arr[index]++;
需要成为这个:
// increase the first color we found to not have a max value
Color current = arr[index];
arr[index] = new Color(current.getRGB() + 1);
最后,对于此部分:
// set all dials before it to 0
for (int i = 0; i < index; i++)
{
arr[i] = 0;
}
我们可以简单地做:
// set all colors before it to 0
for (int i = 0; i < index; i++)
{
arr[i] = Color.BLACK;
}
另外,请记住,您需要初始化颜色数组。可以这样做:
for (int i = 0; i < arr.length; i++)
{
arr[i] = Color.BLACK;
}
我希望这会有所帮助。祝你好运!