3 回答

TA貢獻(xiàn)2051條經(jīng)驗(yàn) 獲得超10個(gè)贊
你可以記住這個(gè)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實(shí)現(xiàn)hashCode和equals 一致。這些方法也應(yīng)該運(yùn)行得非??欤ㄟ@是通常的情況)。
編輯 2:正如 M. Justin 在下面的評(píng)論中所說(shuō),這個(gè)解決方案不是線程安全的。如果要從多個(gè)線程使用記憶化函數(shù),則應(yīng)使用 aConcurrentHashMap而不是 a HashMap。

TA貢獻(xiàn)1816條經(jīng)驗(yàn) 獲得超6個(gè)贊
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();
減少后,您將得到一個(gè)Optional<Pair<GameState, Integer>>可能包含最高minimax結(jié)果和相應(yīng)的GameState. 如果沒(méi)有游戲狀態(tài),我們返回默認(rèn)條目new SimpleEntry<>(null, MIN_VALUE)。

TA貢獻(xiàn)1883條經(jīng)驗(yàn) 獲得超3個(gè)贊
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();
添加回答
舉報(bào)