1 package com.github.lstephen.ai.search;
2
3 import java.util.List;
4 import java.util.function.Supplier;
5 import java.util.stream.Collectors;
6 import java.util.stream.Stream;
7
8 import com.google.common.base.Preconditions;
9
10
11
12
13 public final class RepeatedHillClimbing<S> {
14
15 private static final Integer REPEATS = 5;
16
17 private final Supplier<S> initialFactory;
18
19 private final HillClimbing<S> hillClimbing;
20
21 public RepeatedHillClimbing(Supplier<S> initialFactory, HillClimbing<S> hillClimbing) {
22 Preconditions.checkNotNull(initialFactory);
23 Preconditions.checkNotNull(hillClimbing);
24
25 this.initialFactory = initialFactory;
26 this.hillClimbing = hillClimbing;
27 }
28
29 public S search() {
30 List<S> initial = Stream
31 .generate(initialFactory)
32 .limit(REPEATS)
33 .collect(Collectors.toList());
34
35 return initial
36 .parallelStream()
37 .map(hillClimbing::search)
38 .max(hillClimbing.getHeuristic())
39 .orElseThrow(() -> new IllegalStateException("Could not find final result"));
40 }
41
42 }