-- Create Table
    -- Distinct combination
    --- R:Red, B:Blue, G: Green, V: Violet, O: Orange, Y: Yellow
    DROP TYPE IF EXISTS color cascade;CREATE TYPE color AS ENUM ('R', 'B', 'G', 'V', 'O', 'Y');

    DROP TABLE IF EXISTS guesses cascade; CREATE TABLE guesses (
        FIRST color,
        SECOND color,
        third color ,
        fourth color
    );
    CREATE TABLE mastermind () inherits (guesses);

    INSERT INTO mastermind VALUES ('G', 'B', 'R', 'V');


    INSERT INTO guesses VALUES ('Y', 'Y', 'B', 'B');
    INSERT INTO guesses VALUES ('V', 'R', 'R', 'Y');
    INSERT INTO guesses VALUES ('G', 'V', 'G', 'Y');
    INSERT INTO guesses VALUES ('R', 'R', 'V', 'Y');
    INSERT INTO guesses VALUES ('B', 'R', 'G', 'V');
    INSERT INTO guesses VALUES ('G', 'B', 'R', 'V');


    --- Matches Black
    CREATE OR REPLACE FUNCTION check_black(guesses,  mastermind) RETURNS INTEGER AS $$
        SELECT (
            ($1.FIRST  = $2.FIRST)::INT +
            ($1.SECOND  = $2.SECOND)::INT +
            ($1.third = $2.third)::INT +
            ($1.fourth = $2.fourth)::INT
        );
    $$ LANGUAGE SQL;

    --- Matches White
    CREATE OR REPLACE FUNCTION check_white(guesses,  mastermind) RETURNS INTEGER AS $$
        SELECT (
            CASE WHEN ($1.FIRST = $2.FIRST) THEN 0 ELSE 0 END +
            CASE WHEN ($1.SECOND = $2.SECOND) THEN 0 ELSE 0 END +
            CASE WHEN ($1.third = $2.third)  THEN 0 ELSE 0 END +
            CASE WHEN ($1.fourth = $2.fourth) THEN 0 ELSE 0 END +
            CASE WHEN ($1.FIRST!= $2.FIRST) THEN (
                    $1.FIRST = $2.SECOND OR
                    $1.FIRST = $2.third OR
                    $1.FIRST = $2.fourth
                    )::INT ELSE 0 END +
            CASE WHEN ($1.SECOND!= $2.SECOND) THEN (
                    $1.SECOND = $2.FIRST OR
                    $1.SECOND = $2.third OR
                    $1.SECOND = $2.fourth
                    )::INT ELSE 0 END +
            CASE WHEN ($1.third!= $2.third) THEN (
                    $1.third = $2.FIRST OR
                    $1.third = $2.SECOND OR
                    $1.third = $2.fourth
                    )::INT ELSE 0 END +
            CASE WHEN ($1.fourth!= $2.fourth) THEN (
                    $1.fourth = $2.FIRST OR
                    $1.fourth = $2.SECOND OR
                    $1.fourth = $2.third
                    )::INT ELSE 0 END
        ) FROM guesses
    $$ LANGUAGE SQL;



    SELECT guesses,
           check_black(guesses.*, mastermind.*),
           check_white(guesses.*, mastermind.*)
        FROM   guesses, mastermind