Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

49
LINES

< > BotCompany Repo | #1011276 // Array-Based Tree Map [OK!]

JavaX source code (desktop) [tags: use-pretranspiled] - run with: x30.jar

Download Jar. Libraryless. Click here for Pure Java version (2543L/17K).

!7

// A must be comparable
sclass ArrayTreeMap<A, B> {
  O[] array; // key, value, key, value...
  
  *() {}
  *(Map<A, B> map) {
    array = new O[roundUpToPowerOfTwo(l(map))*2];
    fill(sorted(keys(map)), map, 0, l(array)/2, 0);
  }
  
  void fill(L<A> l, Map<A, B> map, int lIdx1, int lIdx2, int aIdx) {
    if (lIdx2 <= lIdx1) ret;
    int middle = (lIdx1+lIdx2)/2;
    A key = _get(l, middle);
    array[aIdx*2] = key;
    array[aIdx*2+1] = map.get(key);
    fill(l, map, lIdx1, middle, aIdx*2+1);
    fill(l, map, middle+1, lIdx2, aIdx*2+2);
  }
  
  B get(A a) {
    int i = 0;
    while (i < l(array)) {
      int x = array[i] == null ? -1 : cmp(a, array[i]);
      if (x == 0) ret (B) array[i+1];
      i = i*2+(x > 0 ? 4 : 2);
    }
    null;
  }
}

p {
  new Map<Int, S> m;
  for (int n = 0; n <= 1024; n++) {
    if (n != 0) m.put(n*10, str(n*10));
    print("n=" + n); assertEquals(n, l(m));
    ArrayTreeMap<Int, S> map = new ArrayTreeMap(m);
    if (n <= 64)
      printStruct(map);
    for (int i : keys(m)) {
      assertEquals(str(i), map.get(i));
      assertNull(map.get(i-1));
      assertNull(map.get(i+1));
    }
  }
  print("OK");
}

Author comment

Began life as a copy of #1011274

download  show line numbers  debug dex  old transpilations   

Travelled to 13 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, cfunsshuasjs, gwrvuhgaqvyk, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, tslmcundralx, tvejysmllsmz, vouqrxazstgt

No comments. add comment

Snippet ID: #1011276
Snippet name: Array-Based Tree Map [OK!]
Eternal ID of this version: #1011276/10
Text MD5: 091bc4707aead1fe4383ae1aac4f6de7
Transpilation MD5: 8c8a89d346ea8a6333e4037f15f284a0
Author: stefan
Category: javax
Type: JavaX source code (desktop)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2017-10-21 23:17:11
Source code size: 1206 bytes / 49 lines
Pitched / IR pitched: No / No
Views / Downloads: 522 / 1038
Version history: 9 change(s)
Referenced in: #1011277 - ArrayTreeMap - quite compact map, but SortedImmutableList is more compact
#1011278 - Test ArrayTreeMap [OK]