Quantcast
Viewing latest article 1
Browse Latest Browse All 2

Answer by Thilo for An algorithm for grouping by trying without feedback

Let's try the following:

Suppose we have an m times n grid grid with p different colors. First we work row by row with the following algorithm:

Column reduction

  1. Drag the piece at (1,1) to (1,2), then (1,2) to (1,3) and so on until you reach (1, n)
  2. Drag the piece at (1,1) the same way to (1,n-1).
  3. Continue till you reach (1, n-p) with the piece moved.

The first step is guaranteed to move the color that was originally at (1,1) to (1,n) and collect all pieces of the same color on its way. The succeeding steps collect the remaining colors. After this part of the algorithm we are guaranteed to have only the columns p to n filled, each with a different color.

This we repeat for the remaining m-1 rows. After that the columns 1 to n-p-1 are guaranteed to be empty.

Row reduction

Now we repeat the same process with the columns, i.e. drag (1, j) to (m, j) for all j >= n-p and then drag (1,j) to (m-1, j).

After this part we are guaranteed to have only filled a p times p subgrid.

Full grid search

Now we collect each different color by brute force: Move (p,p) to (p,p+1), (p, p+2), ... (p, n) and then to (p + 1, n), (p+1, n-1), ..., (p+1, p) and then to (p+2, p), ..., (p+2, n) and so on until we reach either (m, p) or (m,n), depending wether p is even or odd.

This step we repeat p times, only that we stop each time on field short of the last one.

As a result only the remaining p fields are filled and each contains a stack of the same color. Problem solved.

To estimate the complexity:

  • The row moving part requires n + n-1 + n-2 + ... + n-p= n*(n+1)/2 - (n-p)*(n-p+1)/2=np+(p^2+p)/2=O(n^2) moves per row, hence O(mn^2).
  • The column moving part similarly requires O(nm^2) moves.
  • The final moving requires p^2 moves for each color, i.e. O(p^3).

If q = max(n,m,p) the complexity is O(q^3).

Note: If we do not know p we could immediately start with the full grid search. We still remain in complexity O(q^3). If, however, p << n or p << m the column and row reduction will reduce the practical complexity greatly.


Viewing latest article 1
Browse Latest Browse All 2

Trending Articles