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).

1  
!7
2  
3  
// A must be comparable
4  
sclass ArrayTreeMap<A, B> {
5  
  O[] array; // key, value, key, value...
6  
  
7  
  *() {}
8  
  *(Map<A, B> map) {
9  
    array = new O[roundUpToPowerOfTwo(l(map))*2];
10  
    fill(sorted(keys(map)), map, 0, l(array)/2, 0);
11  
  }
12  
  
13  
  void fill(L<A> l, Map<A, B> map, int lIdx1, int lIdx2, int aIdx) {
14  
    if (lIdx2 <= lIdx1) ret;
15  
    int middle = (lIdx1+lIdx2)/2;
16  
    A key = _get(l, middle);
17  
    array[aIdx*2] = key;
18  
    array[aIdx*2+1] = map.get(key);
19  
    fill(l, map, lIdx1, middle, aIdx*2+1);
20  
    fill(l, map, middle+1, lIdx2, aIdx*2+2);
21  
  }
22  
  
23  
  B get(A a) {
24  
    int i = 0;
25  
    while (i < l(array)) {
26  
      int x = array[i] == null ? -1 : cmp(a, array[i]);
27  
      if (x == 0) ret (B) array[i+1];
28  
      i = i*2+(x > 0 ? 4 : 2);
29  
    }
30  
    null;
31  
  }
32  
}
33  
34  
p {
35  
  new Map<Int, S> m;
36  
  for (int n = 0; n <= 1024; n++) {
37  
    if (n != 0) m.put(n*10, str(n*10));
38  
    print("n=" + n); assertEquals(n, l(m));
39  
    ArrayTreeMap<Int, S> map = new ArrayTreeMap(m);
40  
    if (n <= 64)
41  
      printStruct(map);
42  
    for (int i : keys(m)) {
43  
      assertEquals(str(i), map.get(i));
44  
      assertNull(map.get(i-1));
45  
      assertNull(map.get(i+1));
46  
    }
47  
  }
48  
  print("OK");
49  
}

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: 523 / 1040
Version history: 9 change(s)
Referenced in: [show references]