[关闭]
@w1024020103 2017-05-03T12:11:56.000000Z 字数 1210 阅读 503

Homework 3: Hashing

CS61B


Simple Oomage

再一次在open project的时候遇到了java.lang.ClassNotFoundException这个异常,采用笨办法,自己建project,再一一建立新类解决了这个问题。有更好的办法吗?

A Perfect hashCode

这个不会写.
给的Hint:Try out every possible combination of red, green, and blue values and ensure that you never see the same value more than once.

最后还是用了O(N^3)的brute force, 不过一个小技巧值得留意。 要确定不同组合的red,green,blue不会返回相同的hashcode,就要确定所有组合返回的hashcode没有duplicate. 可以先用arraylist装这些int,再用hashset装这些int。 因为hashset不允许duplicate,所以只需要assertequal这个arraylist和hashset的size就能判断这些有没有duplicates了

  1. public void testHashCodePerfect() {
  2. /* TODO: Write a test that ensures the hashCode is perfect,
  3. meaning no two SimpleOomages should EVER have the same
  4. hashCode!
  5. Hint: Try out every possible combination of red, green, and blue values and
  6. ensure that you never see the same value more than once.
  7. */
  8. ArrayList<Integer> hashList = new ArrayList<>();
  9. for(int i = 0; i < 256; i += 5){
  10. for(int j = 0; j <256; j += 5){
  11. for(int k = 0; k < 256; k += 5){
  12. SimpleOomage soA = new SimpleOomage(i,j,k);
  13. int hash = soA.hashCode();
  14. hashList.add(hash);
  15. }
  16. }
  17. }
  18. HashSet<Integer> set = new HashSet(hashList);
  19. assertEquals(hashList.size(), set.size());
  20. }

Perfect HashCode不是很懂为何要那么些,但通过测试了。

  1. @Override
  2. public int hashCode() {
  3. if (!USE_PERFECT_HASH) {
  4. return red + green + blue;
  5. } else {
  6. // TODO: Write a perfect hash function for Simple Oomages.
  7. return 256*256*red + 256*green + blue;
  8. }
  9. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注