Im trying to solve a puzzle, by using some prunning and brute force I reach level 48. But now thinking use some Memoization to reuse the calculations.
I have some tables:
puzzles: (puzzle_id, level, flips)
CONSTRAINT puzzle_id_pk PRIMARY KEY (puzzle_id)
puzzle_rows (puzzle_id, row_id, row_flips)
CONSTRAINT puzzle_row_pk PRIMARY KEY (puzzle_id, row_id),
CONSTRAINT puzzle_row_puzzle_id_fk FOREIGN KEY (puzzle_id)
pieces: (puzzle_id, piece_id, flips_row1, flips_row2, flips_row3, flips_row4, flips_row5)
CONSTRAINT piece_id_pk PRIMARY KEY (puzzle_id, piece_id),
CONSTRAINT piece_puzzle_id_fk FOREIGN KEY (puzzle_id)
For this level are 18 pieces:
+-----------+-----------+-------------+-------------+-------------+-------------+-------------+
| puzzle_id | piece_id | flips_row1 | flips_row2 | flips_row3 | flips_row4 | flips_row5 |
+-----------+-----------+-------------+-------------+-------------+-------------+-------------+
| 1 | 1 | 2 | 1 | 2 | 0 | 0 |
| 1 | 2 | 2 | 1 | 0 | 0 | 0 |
| 1 | 3 | 2 | 2 | 2 | 0 | 0 |
| 1 | 4 | 3 | 1 | 3 | 0 | 0 |
| 1 | 5 | 4 | 3 | 3 | 3 | 0 |
| 1 | 6 | 3 | 0 | 0 | 0 | 0 |
| 1 | 7 | 3 | 1 | 3 | 0 | 0 |
| 1 | 8 | 3 | 4 | 1 | 2 | 2 |
| 1 | 9 | 1 | 0 | 0 | 0 | 0 |
| 1 | 10 | 2 | 2 | 2 | 0 | 0 |
| 1 | 11 | 2 | 3 | 4 | 0 | 0 |
| 1 | 12 | 1 | 3 | 1 | 3 | 2 |
| 1 | 13 | 1 | 2 | 2 | 0 | 0 |
| 1 | 14 | 2 | 4 | 1 | 1 | 0 |
| 1 | 15 | 1 | 2 | 1 | 0 | 0 |
| 1 | 16 | 1 | 1 | 3 | 0 | 0 |
| 1 | 17 | 3 | 2 | 3 | 1 | 0 |
| 1 | 18 | 1 | 3 | 2 | 2 | 0 |
+-----------+-----------+-------------+-------------+-------------+-------------+-------------+
I need help to fill the table solution_pieces
with all the pieces combination. In this case is 2^18 = 262144
The idea is to check row parity first to prunning the search space. (SUM(pieces.flips_row1) + puzzle_row[1].flips) % 3 = 0
.
For example in the picture below with pieces {14,15}
on first row: pieces total flips (3) + row_flips (3) = 6 % 3 = 0
solutions: (solution_id, puzzle_id,
flips_row1, flips_row2, flips_row3, flips_row4, flips_row5)
CONSTRAINT solution_pk PRIMARY KEY (solution_id),
CONSTRAINT solution_puzzle_id_fk FOREIGN KEY (puzzle_id)
solution_pieces: (solution_id, piece_id)
CONSTRAINT solution_pieces_pk PRIMARY KEY (solution_id, piece_id),
CONSTRAINT solution_pieces_solution_id_fk FOREIGN KEY (solution_id)
CONSTRAINT solution_puzzle_id_fk FOREIGN KEY (puzzle_id)
So I need fill the table solution_pieces
like this.
solution_id piece_id
1 1
.... -- solutions with only one piece
18 18
19 1
19 2
20 1
20 3
.... -- solutions with two pieces
262144 {1..18} -- solution with all pieces
Then the table solutions
is fill with just a GROUP BY