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

71
LINES

< > BotCompany Repo | #1031058 // SortedArrayBasedMap - map based on a sorted list [O(log n) access, immutable]

JavaX fragment (include) [tags: use-pretranspiled]

Libraryless. Click here for Pure Java version (3313L/19K).

sclass SortedArrayBasedMap<A, B> extends CompactAbstractMap<A, B> {
  O[] entries; // key, value, ... with keys being sorted
  
  *() {}
  *(Map<A, B> map) {
    LPair<A, B> l = pairsSortedByA(mapToPairs(map));
    int n = l(l);
    entries = new O[n*2];
    for i to n: {
      Pair<A, B> p = l.get(i);
      entries[i*2] = p.a;
      entries[i*2+1] = p.b;
    }
  }
  
  public int size() { ret l(entries)/2; }
  public Set<Map.Entry<A, B>> entrySet() {
    ret new AbstractSet<Map.Entry<A, B>>() {
      public int size() { ret SortedArrayBasedMap.this.size(); }
      
      public Iterator<Map.Entry<A, B>> iterator() {
        ret new Iterator<Map.Entry<A, B>>() {
          int idx;
          
          public bool hasNext() {
            ret idx < l(entries);
          }
          
          public Map.Entry<A, B> next() {
            SimpleEntry<A, B> e = new SimpleEntry<A, B>((A) entries[idx], (B) entries[idx+1]);
            idx += 2;
            ret e;
          }
        };
      }
    };
  }
  
  int find(O key) {
    ret find(0, size(), key);
  }
  
  int find(int fromIndex, int toIndex, O key) {
    int low = fromIndex;
    int high = toIndex - 1;

    while (low <= high) {
      int mid = (low + high) >>> 1;
      O midVal = entries[mid*2];
  
      int c = cmp(midVal, key);
      if (c < 0)
        low = mid + 1;
      else if (c > 0)
        high = mid - 1;
      else
        ret mid; // key found
    }
    ret -(low + 1);  // key not found.
  }
  
  public bool containsKey(O o) {
    ret find(o) >= 0;
  }
  
  @Override
  public B get(O o) {
    int i = find(o)*2;
    ret i >= 0 ? (B) entries[i+1] : null;
  }
}

Author comment

Began life as a copy of #1031042

download  show line numbers  debug dex  old transpilations   

Travelled to 6 computer(s): bhatertpkbcr, ekrmjmnbrukm, mqqgnosmbjvj, onxytkatvevr, pyentgdyhuwx, vouqrxazstgt

No comments. add comment

Snippet ID: #1031058
Snippet name: SortedArrayBasedMap - map based on a sorted list [O(log n) access, immutable]
Eternal ID of this version: #1031058/10
Text MD5: b86e7d5186c157a8df0bfc97f6320311
Transpilation MD5: 5d61e61408dbf6f6ff3366f7303fb88b
Author: stefan
Category: javax
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2021-04-26 17:06:28
Source code size: 1719 bytes / 71 lines
Pitched / IR pitched: No / No
Views / Downloads: 188 / 717
Version history: 9 change(s)
Referenced in: [show references]