-- File: map_coloring.sql -- Version: 1.1 -- Last Changed: 2020-02-27 -- by: Damir; https://www.damirsystems.com -- Project: Map Coloring -- Description: Fun challenge from Decision Management Community -- https://dmcommunity.org/challenge/challenge-may-2019/ -- DB: PostgreSQL, MS SQL Server WITH color AS ( -- Blue, Red, Green, Yellow SELECT p FROM ( VALUES ('B'), ('R'), ('G'), ('Y') ) AS x(p) ), possible AS ( -- generate 4^6 = 4096 possible combinations SELECT a.p AS BE -- Belgium , b.p AS DK -- Denmark , c.p AS FR -- France , d.p AS DE -- Germany , e.p AS LU -- Luxembourg , f.p AS NL -- Netherlands FROM color AS a CROSS JOIN color AS b CROSS JOIN color AS c CROSS JOIN color AS d CROSS JOIN color AS e CROSS JOIN color AS f ) SELECT BE, DK, FR, DE, LU, NL FROM possible WHERE (1=1) -- apply constraints -- BE borders FR, LU, DE, NL AND BE NOT IN (FR, LU, DE, NL) -- DK borders DE AND DK NOT IN (DE) -- FR borders BE, LU, DE AND FR NOT IN (BE, LU, DE) -- DE borders FR, LU, BE, NL, DK AND DE NOT IN (FR, LU, BE, NL, DK) -- LU borders FR, DE, BE AND LU NOT IN (FR, DE, BE) -- NL borders BE, DE AND NL NOT IN (BE, DE) -- order results ORDER BY BE, DK, FR, DE, LU, NL ; -- Note: There are 144 solutions