Transpiled version (9583L) is out of date.
1 | // Cut a list off at a certain point in order to stay within a |
2 | // defined "budget" (according to a user-defined function giving |
3 | // a price for each element) |
4 | |
5 | sclass CutListToBudget<A> {
|
6 | settable double maxPrice; |
7 | settable Iterable<A> inputList; |
8 | gettable L<A> outputList; |
9 | gettable double finalPrice; |
10 | |
11 | // cut up last element to fill remaining budget? |
12 | settable bool allowPartial; |
13 | |
14 | // last element of outputList before reduction |
15 | // (if there was a reduction) |
16 | gettable A fullLastElement; |
17 | |
18 | swappable double getPrice(A element) { throw unimplemented(); }
|
19 | |
20 | // reduce an element to fit a budget |
21 | // can return null if no reduced element is possible |
22 | swappable A reduceElement(A element, double budget) { null; }
|
23 | |
24 | *(IF1<A, Double> *getPrice) {}
|
25 | *(IF1<A, Double> *getPrice, double *maxPrice, Iterable<A> *inputList) {}
|
26 | |
27 | run {
|
28 | outputList = new L; |
29 | finalPrice = 0; |
30 | fOr (element : inputList) {
|
31 | double price = getPrice(element); |
32 | if (finalPrice + price > maxPrice) {
|
33 | if (allowPartial) {
|
34 | A partial = reduceElement(element, maxPrice-finalPrice); |
35 | if (partial != null) {
|
36 | fullLastElement = element; |
37 | finalPrice += getPrice(partial); |
38 | outputList.add(partial); |
39 | if (finalPrice > maxPrice) |
40 | fail("reduceElement failure (over budget)");
|
41 | } |
42 | } |
43 | break; |
44 | } |
45 | finalPrice += price; |
46 | outputList.add(element); |
47 | } |
48 | } |
49 | |
50 | L<A> get() {
|
51 | if (outputList == null) run(); |
52 | ret outputList; |
53 | } |
54 | |
55 | selfType allowPartial(IF2<A, Double, A> reduceElement) {
|
56 | this.reduceElement = reduceElement; |
57 | ret allowPartial(true); |
58 | } |
59 | |
60 | A lastElement() {
|
61 | ret last(get()); |
62 | } |
63 | |
64 | Percent lastElementKeptPercentage() {
|
65 | ret fullLastElement == null ?: Percent(getPrice(lastElement())/getPrice(fullLastElement)*100); |
66 | } |
67 | } |
Began life as a copy of #1035616
download show line numbers debug dex old transpilations
Travelled to 2 computer(s): elmgxqgtpvxh, mqqgnosmbjvj
No comments. add comment
| Snippet ID: | #1035752 |
| Snippet name: | CutListToBudget |
| Eternal ID of this version: | #1035752/13 |
| Text MD5: | 43306758b808510072f160cc870b6740 |
| Author: | stefan |
| Category: | javax / gazelle 22 |
| Type: | JavaX fragment (include) |
| Public (visible to everyone): | Yes |
| Archived (hidden from active list): | No |
| Created/modified: | 2022-07-25 15:51:28 |
| Source code size: | 1947 bytes / 67 lines |
| Pitched / IR pitched: | No / No |
| Views / Downloads: | 592 / 725 |
| Version history: | 12 change(s) |
| Referenced in: | [show references] |