zoukankan      html  css  js  c++  java
  • 寻找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;
        }
    };
  • 相关阅读:
    常用函数
    小工具
    javascript实现的平方米、亩、公顷单位换算小程序
    在spring boot 项目中使用thymeleaf模板
    IntellJ IDEA 中JAVA代码的任务标记(TODO、FIXME、【XXX】)
    XMPP学习
    iOS绘图教程(个人学习总结)
    iOS: #ifdef DEBUG
    iphone sdk版本宏
    xmpp
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/4830399.html
Copyright © 2011-2022 走看看