use of jcog.data.ArrayHashSet in project narchy by automenta.
the class DeriveTime method solveMerged.
@Nullable
Function<long[], Term> solveMerged(ArrayHashSet<Event> solutions, int dur) {
int ss = solutions.size();
// callee will use the only solution by default
if (ss <= 1)
return null;
SortedSetMultimap<Term, LongLongPair> m = MultimapBuilder.hashKeys(ss).treeSetValues().build();
solutions.forEach(x -> {
long w = x.when();
if (w != TIMELESS)
m.put(x.id, PrimitiveTuples.pair(w, w));
});
int ms = m.size();
switch(ms) {
case 0:
return null;
case 1:
Map.Entry<Term, LongLongPair> ee = m.entries().iterator().next();
LongLongPair ww = ee.getValue();
long s = ww.getOne();
long e = ww.getTwo();
return (w) -> {
w[0] = s;
w[1] = e;
return ee.getKey();
};
}
FasterList<Pair<Term, long[]>> choices = new FasterList(ms);
// coalesce adjacent events
m.asMap().forEach((t, cw) -> {
int cws = cw.size();
if (cws > 1) {
long[][] ct = new long[cws][2];
int i = 0;
for (LongLongPair p : cw) {
long[] cc = ct[i++];
cc[0] = p.getOne();
cc[1] = p.getTwo();
}
// TODO more complete comparison
long[] prev = ct[0];
for (int j = 1; j < cws; j++) {
long[] next = ct[j];
if (prev[0] == ETERNAL) {
assert (j == 1);
assert (ct[0][0] == ETERNAL);
// ignore eternal solution amongst other temporal solutions
ct[0] = null;
} else if (Math.abs(prev[1] - next[0]) <= dur) {
// stretch
prev[1] = next[1];
ct[j] = null;
continue;
}
prev = next;
}
for (int j = 0; j < cws; j++) {
long[] nn = ct[j];
if (nn != null)
choices.add(pair(t, nn));
}
} else {
LongLongPair f = ((SortedSet<LongLongPair>) cw).first();
choices.add(pair(t, new long[] { f.getOne(), f.getTwo() }));
}
});
if (choices.size() > 1) {
// random fallback
return (w) -> {
Pair<Term, long[]> pp = choices.get(d.random);
long[] cw = pp.getTwo();
w[0] = cw[0];
w[1] = cw[1];
return pp.getOne();
};
} else {
Pair<Term, long[]> c = choices.get(0);
long[] cw = c.getTwo();
Term cct = c.getOne();
return (w) -> {
w[0] = cw[0];
w[1] = cw[1];
return cct;
};
}
}
Aggregations