+ k = 0
+ for d in range(4):
+ while True:
+ ii, jj = (
+ torch.randint(self.height, (1,)).item(),
+ torch.randint(self.width, (1,)).item(),
+ )
+ e = 0
+ for i in range(S):
+ for j in range(S):
+ if (
+ ii + i >= self.height
+ or jj + j >= self.width
+ or (
+ f_X[i + i0, j + j0] == c[d]
+ and X[ii + i, jj + j] > 0
+ )
+ ):
+ e = 1
+ if e == 0:
+ break
+ for i in range(S):
+ for j in range(S):
+ if f_X[i + i0, j + j0] == c[d]:
+ X[ii + i, jj + j] = c[d]
+
+ def task_islands(self, A, f_A, B, f_B):
+ c = torch.randperm(len(self.colors) - 1)[:2] + 1
+ for X, f_X in [(A, f_A), (B, f_B)]:
+ while True:
+ k = torch.randperm(self.height * self.width)
+ Z = torch.zeros(self.height + 2, self.width + 2)
+
+ i0, j0 = (
+ torch.randint(self.height, (1,)).item() + 1,
+ torch.randint(self.width, (1,)).item() + 1,
+ )
+
+ Z[i0 - 1 : i0 + 2, j0 - 1 : j0 + 2] = 1
+
+ nb = 9
+
+ for q in k:
+ i, j = q % self.height + 1, q // self.height + 1
+
+ if Z[i, j] == 0:
+ r, s, t, u, v, w, x, y = (
+ Z[i - 1, j],
+ Z[i - 1, j + 1],
+ Z[i, j + 1],
+ Z[i + 1, j + 1],
+ Z[i + 1, j],
+ Z[i + 1, j - 1],
+ Z[i, j - 1],
+ Z[i - 1, j - 1],
+ )
+
+ if (
+ (nb < 16 or r + s + t + u + v + w + x + y > 0)
+ and (s == 0 or r + t > 0)
+ and (u == 0 or t + v > 0)
+ and (w == 0 or x + v > 0)
+ and (y == 0 or x + r > 0)
+ ):
+ # if r+s+t+u+v+w+x+y==0:
+ Z[i, j] = 1
+ nb += 1
+
+ if nb == self.height * self.width // 2:
+ break
+
+ if nb == self.height * self.width // 2:
+ break
+
+ M = Z.clone()
+ Z[i0, j0] = 2
+ X[...] = (Z[1:-1, 1:-1] == 1) * c[0] + (Z[1:-1, 1:-1] == 2) * c[1]
+
+ for _ in range(self.height + self.width):
+ Z[1:-1, 1:-1] = Z[1:-1, 1:-1].maximum(
+ torch.maximum(
+ torch.maximum(Z[0:-2, 1:-1], Z[2:, 1:-1]),
+ torch.maximum(Z[1:-1, 0:-2], Z[1:-1, 2:]),
+ )
+ )
+ Z *= M
+
+ f_X[...] = (Z[1:-1, 1:-1] == 1) * c[0] + (Z[1:-1, 1:-1] == 2) * c[1]
+
+ ######################################################################