Skip to content

Commit

Permalink
computed_collection: Collatz example: Use fromPiecewise to be memory-…
Browse files Browse the repository at this point in the history
…optimal
  • Loading branch information
mstniy committed Oct 2, 2024
1 parent 3c67539 commit 7f050c3
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 10 deletions.
2 changes: 2 additions & 0 deletions packages/computed_collections/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,8 @@ m3.snapshot.listen(print);

This might not be the most performant implementation, but note that it is asymptotically optimal in the sense that it uses memoization. It also showcases the key-local query capabilities, as computing the Collatz sequences of all the integers in the range $[0, 200]$ requires more than 200 indices.

In [`examples/collatz.dart`](examples/collatz.dart), you can find a more advanced implementation which is also asymptotically optimal in its memory complexity.

## <a name='an-index-of-operators'></a>An index of operators

Below is a list of reactive operators on reactive maps along with a high-level description of them.
Expand Down
31 changes: 21 additions & 10 deletions packages/computed_collections/example/collatz.dart
Original file line number Diff line number Diff line change
@@ -1,16 +1,27 @@
import 'package:computed/computed.dart';
import 'package:computed_collections/computedmap.dart';
import 'package:fast_immutable_collections/fast_immutable_collections.dart';

Iterable<int> naturalNumbers() sync* {
var x = 0;
while (true) {
yield x++;
}
}

void main() {
final m1 = ComputedMap.fromIMap(
IMap.fromEntries(List.generate(200, (i) => MapEntry(i, 0))));
late final ComputedMap<int, int> m2;
m2 = m1.mapValuesComputed((k, v) => k <= 1
final naturals = ComputedMap.fromPiecewise(naturalNumbers(), (_) => 0);
final domain = ComputedMap.fromPiecewise(
Iterable<int>.generate(16, (x) => x + 1), (_) => 0);
late final ComputedMap<int, int> collatz;
// We cannot define `collatz` by as a transformation of `domain`,
// as computing the Collatz sequence of an integer may require
// accessing the sequence for larger integers.
collatz = naturals.mapValuesComputed((k, v) => k <= 1
? $(() => 0)
: $(() => m2[((k % 2) == 0 ? k ~/ 2 : (k * 3 + 1))].use! + 1));
final m3 = m1
.removeWhere((k, v) => k == 0 || k > 16)
.mapValuesComputed((k, v) => m2[k]);
m3.snapshot.listen(print);
: $(() => collatz[((k % 2) == 0 ? k ~/ 2 : (k * 3 + 1))].use! + 1));
// We define a `rangedCollatz` as `collatz` is an infinite collection.
// Note that we cannot use `.removeWhere`, as that propagates `.snapshot`
// calls, and we cannot compute the snapshot of an infinite collection.
final rangedCollatz = domain.mapValuesComputed((k, v) => collatz[k]);
rangedCollatz.snapshot.listen(print);
}

0 comments on commit 7f050c3

Please sign in to comment.