Libraryless. Click here for Pure Java version (4977L/28K).
1 | sclass Best_comparable<A> { |
2 | A best; |
3 | Comparable score; |
4 | bool verboseNewBest, replaceIfSameScore; |
5 | |
6 | transient O onChange; |
7 | transient O stringifier; // func(A) -> S |
8 | |
9 | synchronized bool isNewBest(Comparable score) { |
10 | ret this.score == null |
11 | || (replaceIfSameScore |
12 | ? cmp(score, this.score) >= 0 |
13 | : cmp(score, this.score) > 0); |
14 | } |
15 | |
16 | synchronized Comparable bestScore() { |
17 | ret score; |
18 | } |
19 | |
20 | Comparable score() { ret bestScore(); } |
21 | Comparable getScore() { ret bestScore(); } |
22 | |
23 | synchronized float floatScoreOr(float defaultValue) { |
24 | ret best == null ? defaultValue : (float) score; |
25 | } |
26 | |
27 | bool put(Pair<? extends A, Comparable> p) { |
28 | ret p != null && put(p.a, p.b); |
29 | } |
30 | |
31 | bool put(Best<? extends A> b) { |
32 | ret b != null && put(b!, b.score); |
33 | } |
34 | |
35 | bool put(A a, Comparable score) { |
36 | ping(); |
37 | bool change; |
38 | if (a != null) synchronized(this) { |
39 | if (isNewBest(score)) { |
40 | best = a; |
41 | this.score = score; |
42 | set change; |
43 | } |
44 | } |
45 | if (change) { |
46 | if (verboseNewBest) print("New best! " + this); |
47 | pcallF(onChange); |
48 | } |
49 | ret change; |
50 | } |
51 | |
52 | synchronized A get() { ret best; } |
53 | synchronized bool has() { ret best != null; } |
54 | |
55 | synchronized Pair<A, Comparable> pair() { ret main pair(best, bestScore()); } |
56 | |
57 | synchronized A getIfScoreAbove(Comparable x) { ret cmp(x, score()) >= 0 ? best : null; } |
58 | |
59 | toString { |
60 | ret !has() ? "-" : "Score " + score + ": " + callStringifier(stringifier, best); |
61 | } |
62 | |
63 | bool putAndPrintIfNewBest(A a, Comparable score) { |
64 | if (!put(a, score)) false; |
65 | ret true with print(this); |
66 | } |
67 | |
68 | synchronized void clear() { best = null; score = 0; } |
69 | } |
Began life as a copy of #1006090
download show line numbers debug dex old transpilations
Travelled to 3 computer(s): bhatertpkbcr, ekrmjmnbrukm, mqqgnosmbjvj
No comments. add comment
Snippet ID: | #1033886 |
Snippet name: | class Best_comparable - takes objects and scores (comparables) and keeps the highest-scoring object. now synchronized and persistable |
Eternal ID of this version: | #1033886/3 |
Text MD5: | ef7eb1157be733b8edfa05e5fc6fdb3a |
Transpilation MD5: | 614b8423e104e221c08cfa333491f100 |
Author: | stefan |
Category: | javax |
Type: | JavaX fragment (include) |
Public (visible to everyone): | Yes |
Archived (hidden from active list): | No |
Created/modified: | 2022-01-08 22:56:54 |
Source code size: | 1756 bytes / 69 lines |
Pitched / IR pitched: | No / No |
Views / Downloads: | 135 / 228 |
Version history: | 2 change(s) |
Referenced in: | [show references] |