gpt4 book ai didi

java - Python 代码中的 Java 排序算法

转载 作者:太空宇宙 更新时间:2023-11-04 10:14:36 26 4
gpt4 key购买 nike

我一直在尝试将此Python代码转换为Processing/Java。我不明白。

def step (r,g,b, repetitions=1):
lum = math.sqrt( .241 * r + .691 * g + .068 * b )
h, s, v = colorsys.rgb_to_hsv(r,g,b)
h2 = int(h * repetitions)
lum2 = int(lum * repetitions)
v2 = int(v * repetitions)
return (h2, lum, v2)

colours.sort(key=lambda (r,g,b): step(r,g,b,8) )

这是 Alan Zucconi 在他的网站上的代码:The incredibly challenging task of sorting colours .

这是我到目前为止所拥有的:

color [] colours = new color[1000];
float lum;
int repetitions = 0;

void setup() {
size(1024, 500);
// pick 1000 random color and put in array
for (int i=0; i<colours.length; i++) {
colours[i]= color(random(255), random(255), random(255));
}
printBar(0);


//simple rgb sort
colours = sort(colours);
printBar(50);

// step sort
for (int j=0; j<colours.length; j++) {
lum = sqrt(.241 * red(colours[j]) + .691 * green(colours[j]) + .068 * blue(colours[j]));
int h2 = int(hue(colours[j]) * repetitions);
int lum2 = int(lum * repetitions);
int v2 = int(brightness(colours[j]) * repetitions);
//I am stuck.......

}
printBar(100);
}

void draw() {
}

void printBar(int step) {
//show all the random colors in a bar
for (int j=0; j<colours.length; j++) {
//strokeWeight(2);
stroke(colours[j]);
line(j+5, 20+step, j+5, 50+step);
}
}

我知道 HSB 和 HSV 颜色系统会存在一些问题,但我会解决这个问题。我不明白的是 Python 中的逐步排序线。有任何想法吗 ?谢谢

最佳答案

退一步来说,您不应该不要尝试逐行翻译代码。类似于翻译人员不会逐字从一种语言翻译成另一种语言。相反,译者会采用整个句子、整个段落或整本书,思考原始单词的意图,然后尝试用目标语言复制该意图。

这也是转换代码的工作原理。您需要退后一步,首先了解代码在做什么。然后,您需要编写用目标语言执行相同操作的代码。

例如,查看这一行:

colours.sort(key=lambda (r,g,b): step(r,g,b,8) )

在编写执行此操作的处理代码之前,您需要准确了解它在做什么。请注意,step() 函数本身不会对任何内容进行排序。它将 RGB 值转换为更容易排序的不同值。从您链接的文章中:

To dampen the impact that sorting on the first component has, we can reduce the colour space from a float value between 0 to 1, to an integer from 0 to 7. By doing this, much of the noise is removed.

所以你的 for 循环看起来已经错误了,除非你打算先转换整个数组或者其他什么。

如果我是你,我会尝试 break your problem down into smaller steps然后一次一个地执行这些步骤。例如:

  • 你能编写一个 step() 函数将 RGB 值转换为转换后的值吗?尝试使用一些示例运行原始代码,然后使用这些相同的示例运行您的代码。你也得到同样的结果吗?
  • 您能编写一个使用 Collections.sort()List.sort() 对 RGB 值进行排序的示例吗?
  • 最后,您能否编写一个示例,将两者结合起来,并使用 Collections.sort()List.sort() 根据转换后的值对 RGB 值进行排序?

然后,如果您在某个特定步骤上遇到困难,您可以发布 MCVE以及更具体的技术问题。祝你好运。

关于java - Python 代码中的 Java 排序算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51873302/

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