Advertisement
Guest User

Untitled

a guest
Nov 20th, 2014
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.70 KB | None | 0 0
  1. /*
  2. * Bitarray Hash Table
  3. *
  4. * 15-122 Principles of Imperative Computation */
  5.  
  6. #include <stdlib.h>
  7. #include <stdbool.h>
  8. #include "lib/contracts.h"
  9. #include "lib/ba-ht.h"
  10. #include "lib/hset.h"
  11. #include "lib/xalloc.h"
  12.  
  13. bitarray to_key(hset_elem x){
  14. REQUIRES(x!=NULL);
  15. struct board_data *b = x;
  16. bitarray k = b->board;
  17. return k;
  18. }
  19.  
  20. bool ba_equal (hset_elem x, hset_elem y){
  21. REQUIRES (x!=NULL && y!=NULL);
  22. bitarray a = to_key(x);
  23. bitarray b = to_key(y);
  24. return a==b;
  25. }
  26.  
  27. size_t ba_hash (hset_elem x){
  28. REQUIRES (x!=NULL);
  29. bitarray a = to_key(x);
  30. return (size_t) a;
  31. }
  32.  
  33. void ba_free(hset_elem x){
  34. free(x);
  35. }
  36.  
  37. /* Initializes a new hash table with the given capacity
  38. */
  39. hset ht_new (size_t capacity){
  40. REQUIRES (capacity > 0);
  41. return hset_new(capacity,&ba_equal,&ba_hash,&free);
  42. }
  43.  
  44. /* ht_insert(H,e) has no return value, because it should have as
  45. * a precondition that no struct currently in the hashtable contains
  46. * the same board as DAT->board
  47. */
  48. void ht_insert (hset H, struct board_data *DAT){
  49. REQUIRES(H!=NULL && DAT!=NULL);
  50. REQUIRES(ht_lookup(H,DAT->board)==NULL);
  51. hset_insert(H,DAT);
  52. }
  53.  
  54. /* ht_lookup(H,B) returns
  55. * NULL if no struct containing the board B exists in H
  56. * A struct containing the board B if one exists in H
  57. */
  58. struct board_data *ht_lookup(hset H, bitarray B){
  59. REQUIRES(H!=NULL);
  60. struct board_data *k = xmalloc(sizeof(struct board_data));
  61. k->last_move = 0;
  62. k->board = B;
  63. hset_elem x = hset_lookup(H,k);
  64. free(k);
  65. return x;
  66. }
  67.  
  68. /* ht_lookup(H,B) returns
  69. * NULL if no struct containing the board B exists in H
  70. * A struct containing the board B if one exists in H
  71. */
  72. void ht_free(hset H){
  73. hset_free(H);
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement