Hello Victor,
for the Advent of code of yesterday [1], i've this code golfing solution (the
full code is here [2])
var input = ...;
class Node {
final HashMap<Integer, Node> map = new HashMap<>();
boolean end;
}
var root = new Node();
Arrays.stream(input.substring(0, input.indexOf('\n')).split(", "))
.forEach(w -> w.chars().boxed().gather(Gatherers.fold(() -> root,
(n, c) -> n.map.computeIfAbsent(c, _ -> new
Node()))).findFirst().orElseThrow().end = true);
println(input.lines().skip(2).filter(w ->
w.chars().boxed().<Set<Node>>gather(Gatherers.fold(() -> new
HashSet<>(Set.of(root)),
(ms, c) -> ms.stream().flatMap(m -> Stream.ofNullable(m.map.get(c)))
.flatMap(n -> n != null && n.end ? Stream.of(n, root) :
Stream.ofNullable(n)).collect(Collectors.toSet())))
.findFirst().orElseThrow().stream().anyMatch(n -> n.end)).count());
As you can see, the second call to Gatherers.fold() requires to specify the
type argument, the <Set<Node>> in front because the supplier is not declared as
a Supplier<? extends ...>
Thinking a little more, i do not understand why fold takes a Supplier as first
parameter and not just a value given that the Gatherer is created with
ofSequential().
regards,
Rémi
[1] https://adventofcode.com/2024/day/19
[2] https://github.com/forax/advent-of-code-2024