LebGeeks

A community for technology geeks in Lebanon.

You are not logged in.

#1 April 2 2014

Ra8
Member

[Exercise] Dominoes

Given a set of dominoes, write a function which returns true if you can use them all next to each other.
Let me illustrate that:

dominoes=["ab","bc","cd"] 

return true, (the way they are given in the array)

dominoes=["ab","cb","cd"] 

returns true, (same as above but rotate the 2nd domino)

dominoes=["ab","bc","bd"] 

returns false (you can't use the 'b' in "ab" twice to connect "bd" and "bc"

Assume the dominoes are 2 characters from a-z or A-Z

Edit:

dominoes=["ab","ed","bd","aa","bb"] 

returns true (pattern aa ab bb bd de)
You can switch the places of the dominoes you don't have to use them in the order given in the array.

Last edited by Ra8 (April 2 2014)

Offline

#2 April 2 2014

Johnaudi
Member

Re: [Exercise] Dominoes

Nice exercise...

        public static bool getDominoBool(string[] _arr)
        {
            bool _ret = true;

            char _lastused = ' ';

            for (int i = 0; i < _arr.Length - 1; i++)
            {
                if ((_arr[i].ToArray<char>().Contains(_arr[i + 1][0]) || _arr[i].ToArray<char>().Contains(_arr[i + 1][1])) && !(_arr[i + 1].ToArray<char>().Contains(_lastused)))
                {
                    _lastused = _arr[i].ToArray<char>().Intersect(_arr[i + 1].ToArray<char>()).First();
                }
                else _ret = false;
            } return _ret;
        }

Offline

#3 April 2 2014

Ra8
Member

Re: [Exercise] Dominoes

@Johnaudi I think you solution is wrong or you misunderstood my question...

See the edited version above.

Here is my solution:

function f (dominoes) {
    //count the occurence of all the chars
    var count={};
    for(var i=0;i<dominoes.length;i++){
        if( typeof count[dominoes[i][0]] == "undefined")
            count[dominoes[i][0]]=1;
        else count[dominoes[i][0]]++;

        if( typeof count[dominoes[i][1]] == "undefined")
            count[dominoes[i][1]]=1;
        else count[dominoes[i][1]]++;
    }
    //check for double dominoes
    for(var i=0;i<dominoes.length;i++){
        if(dominoes[i][0]==dominoes[i][1])
        {
            count[dominoes[i][0]]-=2;
            if(count[dominoes[i][0]]==0)
                return false;
        }
    }
    //check if they are all even except for at most 2
    var odds=0;
    for(chr in count){
        odds=odds+count[chr]%2;
    }
    return (odds<=2);
}

Last edited by Ra8 (April 2 2014)

Offline

Board footer