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

90
LINES

< > BotCompany Repo | #1025302 // StringClustersWithIDs

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

Libraryless. Click here for Pure Java version (3408L/21K).

sclass StringClustersWithIDs {
  new L<Cluster> clusters;
  
  !include #1025301 // change()/onChange()
  
  sclass Cluster {
    GlobalID globalID = aGlobalIDObject();
    Set<S> synonyms = ciSet();

    *() {}
    *(S s) { synonyms.add(s); }
    
    toString { ret "Cluster " + globalID + ": " + synonyms; }
    
    bool add(S s) {
      ret synonyms.add(s);
    }
  }
 
  L<Cluster> searchForCluster(S s) {
    ret filter(clusters, c -> contains(c.synonyms, s));
  }
  
  Cluster clusterWith(S s) {
    ret first(searchForCluster(s));
  }
  
  void add(Cluster cluster) {
    clusters.add(cluster);
    change();
  }
  
  void remove(Cluster cluster) {
    clusters.remove(cluster);
    change();
  }
  
  // also adds to list
  Cluster newCluster(S s) {
    Cluster c = new(s);
    add(c);
    ret c;
  }
  
  // also adds to list
  Cluster newCluster(Cl<S> synonyms) {
    new Cluster c;
    addAll(c.synonyms, synonyms);
    add(c);
    ret c;
  }
  
  // also merges clusters
  void addPair(S a, S b) {
    Cluster c1 = clusterWith(a), c2 = clusterWith(b);
    if (c1 != null)
      if (c2 != null)
        mergeClusters(c1, c2);
      else { c1.add(b); change(); }
    else
      if (c2 != null) { c2.add(a); change(); }
      else
        newCluster(ll(a, b));
  }
  
  void mergeClusters(Cluster a, Cluster b) {
    if (a == b) ret;
    a.synonyms.addAll(b.synonyms);
    remove(b);
  }
  
  // either return s or all synonyms from the first cluster containing s
  Set<S> extend(S s) {
    Cluster c = clusterWith(s);
    ret c == null ? litciset(s) : c.synonyms;
  }
  
  int totalCount() {
    ret intSum(map(clusters, c -> l(c.synonyms)));
  }
  
  bool eqicOrInSameCluster(S a, S b) {
    if (eqic(a, b)) true;
    if (a == null || b == null) false; 
    for (Cluster c : clusters)
      if (contains(c.synonyms, a) && contains(c.synonyms, b))
        true;
    false;
  }
}

Author comment

Began life as a copy of #1025290

download  show line numbers  debug dex  old transpilations   

Travelled to 6 computer(s): bhatertpkbcr, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, tvejysmllsmz, vouqrxazstgt

No comments. add comment

Snippet ID: #1025302
Snippet name: StringClustersWithIDs
Eternal ID of this version: #1025302/18
Text MD5: 934f5ea6e9be14f3ccc6d5e7c685e536
Transpilation MD5: 2242325a8c27f02a0c69c2c0db998cdd
Author: stefan
Category: javax / a.i.
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2019-10-26 02:13:25
Source code size: 1979 bytes / 90 lines
Pitched / IR pitched: No / No
Views / Downloads: 350 / 811
Version history: 17 change(s)
Referenced in: [show references]