ОК, это доставило мне неприятности. Я думаю, что это довольно приятно, даже если результаты не так артистичны, как некоторые другие. Это сделка со случайностью. Возможно, некоторые промежуточные изображения выглядят лучше, но я действительно хотел иметь полностью работающий алгоритм с диаграммами вороного.

Редактировать:

Это один из примеров окончательного алгоритма. Изображение в основном представляет собой суперпозицию трех вороновых диаграмм, по одной для каждого цветового компонента (красный, зеленый, синий).
Код
ungolfed, прокомментированная версия в конце
unsigned short red_fn(int i, int j){
int t[64],k=0,l,e,d=2e7;srand(time(0));while(k<64){t[k]=rand()%DIM;if((e=_sq(i-t[k])+_sq(j-t[42&k++]))<d)d=e,l=k;}return t[l];
}
unsigned short green_fn(int i, int j){
static int t[64];int k=0,l,e,d=2e7;while(k<64){if(!t[k])t[k]=rand()%DIM;if((e=_sq(i-t[k])+_sq(j-t[42&k++]))<d)d=e,l=k;}return t[l];
}
unsigned short blue_fn(int i, int j){
static int t[64];int k=0,l,e,d=2e7;while(k<64){if(!t[k])t[k]=rand()%DIM;if((e=_sq(i-t[k])+_sq(j-t[42&k++]))<d)d=e,l=k;}return t[l];
}
Мне потребовалось много усилий, поэтому я чувствую, что хочу поделиться результатами на разных этапах, и есть хорошие (неправильные), которые можно показать.
Первый шаг: расположить несколько точек случайным образом, с x=y

Я преобразовал его в jpeg, потому что исходный png был слишком тяжел для загрузки ( >2MB
), я уверен, что это более 50 оттенков серого!
Второе: иметь лучшую координату у
Я не мог позволить себе создать другую таблицу координат, случайно сгенерированную для y
оси, поэтому мне нужен был простой способ получить " случайные " из как можно меньшего числа символов. Я использовал x
координату другой точки в таблице, выполнив побитовое AND
управление индексом точки.

3-е: я не помню, но становится лучше
Но в то время у меня было более 140 символов, поэтому мне нужно было немного упасть.

4-е: сканы
Шучу, это не нужно, но круто, я думаю.

Продолжая работать над уменьшением размера алгоритма, я с гордостью представляю:
Издание StarFox

Вороной Инстаграм

5-е: увеличить количество очков
Теперь у меня есть рабочий кусок кода, так что давайте перейдем от 25 до 60 баллов.

Это трудно увидеть только с одного изображения, но почти все точки находятся в одном y
диапазоне. Конечно, я не менял побитовую операцию, &42
гораздо лучше:

И вот мы в том же месте, что и самое первое изображение из этого поста. Давайте теперь объясним код для редких, которые будут заинтересованы.
Разоблаченный и объясненный код
unsigned short red_fn(int i, int j)
{
int t[64], // table of 64 points's x coordinate
k = 0, // used for loops
l, // retains the index of the nearest point
e, // for intermediary results
d = 2e7; // d is the minimum distance to the (i,j) pixel encoutnered so far
// it is initially set to 2e7=2'000'000 to be greater than the maximum distance 1024²
srand(time(0)); // seed for random based on time of run
// if the run overlaps two seconds, a split will be observed on the red diagram but that is
// the better compromise I found
while(k < 64) // for every point
{
t[k] = rand() % DIM; // assign it a random x coordinate in [0, 1023] range
// this is done at each call unfortunately because static keyword and srand(...)
// were mutually exclusive, lenght-wise
if (
(e= // assign the distance between pixel (i,j) and point of index k
_sq(i - t[k]) // first part of the euclidian distance
+
_sq(j - t[42 & k++]) // second part, but this is the trick to have "" random "" y coordinates
// instead of having another table to generate and look at, this uses the x coordinate of another point
// 42 is 101010 in binary, which is a better pattern to apply a & on; it doesn't use all the table
// I could have used 42^k to have a bijection k <-> 42^k but this creates a very visible pattern splitting the image at the diagonal
// this also post-increments k for the while loop
) < d // chekcs if the distance we just calculated is lower than the minimal one we knew
)
// { // if that is the case
d=e, // update the minimal distance
l=k; // retain the index of the point for this distance
// the comma ',' here is a trick to have multiple expressions in a single statement
// and therefore avoiding the curly braces for the if
// }
}
return t[l]; // finally, return the x coordinate of the nearest point
// wait, what ? well, the different areas around points need to have a
// "" random "" color too, and this does the trick without adding any variables
}
// The general idea is the same so I will only comment the differences from green_fn
unsigned short green_fn(int i, int j)
{
static int t[64]; // we don't need to bother a srand() call, so we can have these points
// static and generate their coordinates only once without adding too much characters
// in C++, objects with static storage are initialized to 0
// the table is therefore filled with 60 zeros
// see http://stackoverflow.com/a/201116/1119972
int k = 0, l, e, d = 2e7;
while(k<64)
{
if( !t[k] ) // this checks if the value at index k is equal to 0 or not
// the negation of 0 will cast to true, and any other number to false
t[k] = rand() % DIM; // assign it a random x coordinate
// the following is identical to red_fn
if((e=_sq(i-t[k])+_sq(j-t[42&k++]))<d)
d=e,l=k;
}
return t[l];
}
Спасибо за чтение до сих пор.