One Piece, Four Ways to Turn
A piece on the table looks different every time I turn it, but it’s still the same piece. That sounds obvious until I ask a program to keep track of it: ABCD and BCDA are different strings, even if they describe the same four edges after a quarter-turn.
One way to settle the matter is to choose a canonical representation: a single, predictable spelling for every orientation. Here I’ll label the edges clockwise, starting at the top, and choose the alphabetically smallest of the four rotations. ABCD, BCDA, CDAB, and DABC all become ABCD.
piece = "BCDA"
rotations = 4.times.map do |turn|
piece[turn..] + piece[0, turn]
end
puts rotations.min
Ruby makes the comparison read much like the rule. The C version turns the same idea into a small tour of character arrays:
#include <stdio.h>
#include <string.h>
int main(void) {
const char *piece = "BCDA";
char best[5] = "ZZZZ", turn[5] = {0};
for (int r = 0; r < 4; r++) {
for (int i = 0; i < 4; i++)
turn[i] = piece[(i + r) % 4];
if (strcmp(turn, best) < 0) strcpy(best, turn);
}
puts(best);
}
Both print ABCD. The C example assumes four uppercase ASCII letters, so ZZZZ is at least as large as every possible input in its little alphabet. For arbitrary labels, I’d initialize best from the first rotation instead.
This is a useful trick for organizing a workspace: normalize first, then compare. It also has a boundary. A rotation preserves the clockwise order of the edges; flipping a piece over reverses it, and these snippets deliberately treat that as a different arrangement. Real pieces have more detail than four letters, so equal labels would only identify candidates for closer inspection. The code gives each set of rotations a common name; it doesn’t prove two physical pieces are identical.