寻找hash值——把int array看成是一个整数

QUESTION:

Write a class DominoChecker that has a method called addBox(int[]) that takes a box of five dominoes, described as a list of 10 integers (explained after), adds it to a collection, and returns true if a box with the same dominoes was already in the collection and false otherwise. A box of dominoes is encoded as a list of 10 integers from 0 to 9, where a pair of numbers represent a domino. For example: 0,2,9,1,3,3,7,4,5,6 represents a box containing dominoes: (0,2); (9,1); (3,3); (7,4); (5,6). 
SOLUTION:
typedef pair< int,int > Domino;

class DominoChecker {
   unordered_set< long long > hash;
   vector< vector< Domino > > boxes;

  public:
    bool addBox(const vector< int >& box) {
        vector< Domino > v;
        for (int i = 0; i < 5; i++) {
            Domino d(box[2*i], box[2*i+1]);
            if (d.first > d.second)
                swap(d.first, d.second); // order does not matter
            v.push_back(d);
        }
        sort(v.begin(), v.end());  // order does not matter here as well.
        long long hash_value = 0;
        for (int i = 0 ; i < 5; i++)
             hash_value = hash_value * 100 + v[i].first*10 + v[i].second; //把int  array看成是一个整数
        if (hash.find(hash_value) != hash.end())
            return false;
        hash.insert(hash_value);
        boxes.push_back(v); // i suppose we want to store them
        return true;
    }
};

 

posted on 2015-09-22 20:29  joannae  阅读(474)  评论(0编辑  收藏  举报

导航