Guest User

Untitled

a guest
Oct 5th, 2016
337
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.39 KB | None | 0 0
  1. #include <stdint.h> // 15 line binary tree (0 = left node, 1 = right, 2 = key, 3 = value )
  2. #include <stdlib.h> // by graphitemaster 2016 (the same guy who did the 15 line hashtable)
  3. void *(*bnew(void))[4] {
  4.   return calloc(sizeof(void*[4]), 1);
  5. }
  6. void bdel(void *(*l)[4]) {
  7.   if (l) {
  8.     bdel((*l)[0]);
  9.     bdel((*l)[1]);
  10.     free(l);
  11.   }
  12. }
  13. void *(*bput(void *(*l)[4], int k, int v))[4] {
  14.   void *(**m)[4] = (void *(**)[4])&((*l)[!!(k < (uintptr_t)((*l)[2]))]);
  15.   if (*m)
  16.     return bput(*m, k, v);
  17.   *m = bnew();
  18.   (**m)[2] = (void *)(uintptr_t)k;
  19.   (**m)[3] = (void *)(uintptr_t)v;
  20.   return *m;
  21. }
  22. void *(*bget(void *(*l)[4], int k))[4] {
  23.   if (!l)
  24.     return 0;
  25.   if (k < (uintptr_t)(*l)[2])
  26.     return bget((*l)[1], k);
  27.   if (k == (uintptr_t)(*l)[2])
  28.     return l;
  29.   return bget((*l)[0], k);
  30. }
  31.  
  32.  
  33. // example of use
  34. #include <stdio.h>
  35. int main() {
  36.   void *(*l)[4] = bnew(); // make new one (root is key = 0, value = 0)
  37.  
  38.   // add some things
  39.   bput(l, 100, 100);
  40.   bput(l, 200, 500);
  41.   bput(l, 10, 35);
  42.   bput(l, 75, 500);
  43.   bput(l, 6000, 1337);
  44.  
  45.   void *(*a)[4] = bget(l, 75); // 500
  46.   void *(*b)[4] = bget(l, 6000); // 1337
  47.   printf("%d\n", (int)(uintptr_t)(*a)[3]); // 3 is key, need to cast to int
  48.   printf("%d\n", (int)(uintptr_t)(*b)[3]);
  49.  
  50.   // something not in there
  51.   void *(*c)[4] = bget(l, 42);
  52.   printf("search for 42 should be null: %p\n",  c);
  53.  
  54.   bdel(l);
  55. }
Advertisement
Add Comment
Please, Sign In to add comment