I'm interested in the programming challenge presented by the game Bejewelled. It seems like a simple game but programmatically it's more complex that it looks.
In my search for hints on how the board is evaluated, I came across this QUIZ put on by the good folks at Simple-Talk. They have posted the winning answer, but I'm tarred and feathered if I can really grok how the solution works. I can see that it has something to do with matrices and grouping the cell values together with their rows and columns, but that's as far as I have gotten so far. Can anyone break it down a little further for me?
POSTED SOLUTION (the details of the quiz are at the link above):
--====== Table matches needs to be loaded only once
CREATE TABLE matches(offsetRow1 INT, offsetCol1 INT, offsetRow2 INT, ofsetCol2 INT, directions VARCHAR(20))
-- for horizontal
INSERT INTO matches VALUES(-1, -1, -1, -2, 'up')
INSERT INTO matches VALUES(-1, -1, -1, 1, 'up')
INSERT INTO matches VALUES(-1, 1, -1, 2, 'up')
INSERT INTO matches VALUES( 1, -1, 1, -2, 'down')
INSERT INTO matches VALUES( 1, -1, 1, 1, 'down')
INSERT INTO matches VALUES( 1, 1, 1, 2, 'down')
INSERT INTO matches VALUES( 0, -2, 0, -3, 'left')
INSERT INTO matches VALUES( 0, 2, 0, 3, 'right')
-- for verical
INSERT INTO matches VALUES(-2, -1, -1, -1, 'left')
INSERT INTO matches VALUES(-1, -1, 1, -1, 'left')
INSERT INTO matches VALUES( 1, -1, 2, -1, 'left')
INSERT INTO matches VALUES(-2, 1, -1, 1, 'right')
INSERT INTO matches VALUES(-1, 1, 1, 1, 'right')
INSERT INTO matches VALUES( 1, 1, 2, 1, 'right')
INSERT INTO matches VALUES(-2, 0, -3, 0, 'up')
INSERT INTO matches VALUES( 2, 0, 3, 0, 'down')
--==================================================
;WITH CTE
AS
(
SELECT
[Row] = CAST( [#] AS INT ),
[Col] = CAST( [Col] AS INT ),
[Value]
FROM bejeweled
UNPIVOT ([Value] FOR [Col] IN ([1],[2],[3],[4],[5],[6],[7],[8],[9])) unpvt
)
SELECT DISTINCT T.Row, T.Col, T.Value, directions
FROM CTE T
JOIN CTE T1
ON T.Value = T1.Value
JOIN CTE T2
ON T.Value = T2.Value
JOIN matches
ON (T1.Row - T.Row) = offsetRow1
AND (T1.Col - T.Col) = offsetCol1
AND (T2.Row - T.Row) = offsetRow2
AND (T2.Col - T.Col) = ofsetCol2
ORDER BY T.Row, T.Col