3 回答

TA貢獻2051條經(jīng)驗 獲得超10個贊
你可以記住這個e -> minimax(e)函數(shù):
public static <T, S> Function<T, S> memoize(Function<T, S> function) {
Map<T, S> cache = new HashMap<>();
return argument -> cache.computeIfAbsent(argument, function);
}
然后,只需使用 memoized 函數(shù):
GameState bestGs = Collections.max(ns,
Comparator.comparing(memoize(e -> minimax(e))));
編輯:這種方法需要GameState實現(xiàn)hashCode和equals 一致。這些方法也應(yīng)該運行得非常快(這是通常的情況)。
編輯 2:正如 M. Justin 在下面的評論中所說,這個解決方案不是線程安全的。如果要從多個線程使用記憶化函數(shù),則應(yīng)使用 aConcurrentHashMap而不是 a HashMap。

TA貢獻1816條經(jīng)驗 獲得超6個贊
import java.util.ArrayList;
import java.util.List;
import static java.lang.Integer.MIN_VALUE;
import static java.util.AbstractMap.SimpleEntry;
...
var bestEntry = ns.stream()
.map(i -> new SimpleEntry<>(i, minimax(i)))
.max(Map.Entry.comparingByValue())
.orElse(new SimpleEntry<>(null, MIN_VALUE));
var bestGameState = bestEntry.getKey();
var bestScore = bestEntry.getValue();
減少后,您將得到一個Optional<Pair<GameState, Integer>>可能包含最高minimax結(jié)果和相應(yīng)的GameState. 如果沒有游戲狀態(tài),我們返回默認(rèn)條目new SimpleEntry<>(null, MIN_VALUE)。

TA貢獻1883條經(jīng)驗 獲得超3個贊
GameState max = ns.stream()
.collect(Collectors.toMap(str -> minimax(str), Function.identity(), (gs1, gs2) -> gs1,
(Supplier<Map<Integer, GameState>>)() -> new TreeMap<>(Comparator.reverseOrder())
)).values().iterator().next();
添加回答
舉報