+void deployment_torus::generate()
+{
+ unsigned a = 0;
+ unsigned b = size();
+ while (a + 1 < b) {
+ unsigned c = (a + b) / 2;
+ if (c * c < size())
+ a = c;
+ else
+ b = c;
+ }
+ unsigned width = b;
+ // here width == ceil(sqrt(size))
+
+ unsigned first_on_last_line = (size() - 1) - (size() - 1) % width;
+ DEBUG4("torus size = %u ; width = %u ; height = %u ; foll = %u",
+ (unsigned )size(), width,
+ (unsigned )(size() / width + !!(size() % width)),
+ first_on_last_line);
+ for (unsigned i = 0; i < size(); i++) {
+ unsigned next_line;
+ unsigned prev_line;
+ unsigned next_column;
+ unsigned prev_column;
+
+ next_line = i + width;
+ if (next_line >= size())
+ next_line %= width; // rewind
+
+ if (i >= width) {
+ prev_line = i - width;
+ } else {
+ prev_line = first_on_last_line + i; // rewind
+ if (prev_line >= size())
+ prev_line -= width; // need to go at last but one line
+ }
+
+ if (i != size() - 1) {
+ next_column = i + 1;
+ if (next_column % width == 0)
+ next_column -= width; // rewind
+ } else {
+ next_column = first_on_last_line; // special case for last cell
+ }
+
+ if (i % width != 0) {
+ prev_column = i - 1;
+ } else if (i < first_on_last_line) {
+ prev_column = i + width - 1; // rewind
+ } else {
+ prev_column = size() - 1; // special case for 1st cell of last line
+ }
+ if (next_line != i) {
+ set_neighbor(i, next_line);
+ if (prev_line != next_line)
+ set_neighbor(i, prev_line);
+ }
+ if (next_column != i) {
+ set_neighbor(i, next_column);
+ if (prev_column != next_column)
+ set_neighbor(i, prev_column);
+ }
+ }
+}