Basically, I'm creating a puzzle where you can swap pieces. And I want to make sure that when swapping 2 elements, the selection is valid.
Since the puzzle is only 9 pieces (3x3), I am currently using the code:
function valid_selection(p1, p2) {
if (p1 == 1 && (p2 == 2 || p2 == 4)) return true;
if (p1 == 2 && (p2 == 1 || p2 == 3 || p2 == 5)) return true;
if (p1 == 3 && (p2 == 2 || p2 == 6)) return true;
if (p1 == 4 && (p2 == 1 || p2 == 5 || p2 == 7)) return true;
if (p1 == 5 && (p2 == 2 || p2 == 4 || p2 == 6 || p2 == 8)) return true;
if (p1 == 6 && (p2 == 3 || p2 == 5 || p2 == 9)) return true;
if (p1 == 7 && (p2 == 4 || p2 == 8)) return true;
if (p1 == 8 && (p2 == 5 || p2 == 7 || p2 == 9)) return true;
if (p1 == 9 && (p2 == 6 || p2 == 8)) return true;
return false;
}
But, can I do this programatically? Anyone know of such an algorithm?
Any help is appreciated.