我有一个Node类
class Node:
def __init__(self, move = None, parent = None, state = None):
self.move = move
self.parentNode = parent # "None" for the root node
self.childNodes = []
self.wins = 0
self.visits = 0
self.untriedMoves = state.GetMoves() # future child nodes
self.playerJustMoved = state.playerJustMoved # the only part of the state that the Node needs later
def UCTSelectChild(self):
""" Use the UCB1 formula to select a child node. Often a constant UCTK is applied so we have
lambda c: c.wins/c.visits + UCTK * sqrt(2*log(self.visits)/c.visits to vary the amount of
exploration versus exploitation.
"""
s = sorted(self.childNodes, key = lambda c: c.wins/c.visits + sqrt(2*log(self.visits)/c.visits))
return s
我有这些Node对象的列表。
在Python中,我可以很容易地进行排序。
s = sorted(self.childNodes, key = lambda c: c.wins/c.visits + sqrt(2*log(self.visits)/c.visits))
用JavaScript做到这一点的最佳方法?这是我使用Javascript的第一天。
答案 0 :(得分:0)
您可以使用Array
的{{3}}方法。
array = [...];
array = array.sort();
这将基于默认的比较逻辑对数组进行排序。如果您想提供自己的比较逻辑,则只需传递比较函数作为参数。与Python的key
仅使用一个参数不同,compare函数提供firstElement
和secondElement
作为参数。因此,您可以执行以下操作:
array = array.sort((firstEl, secondEl) => {
let first = firstEl.wins / firstEl.visits + sqrt(2 * Math.log(firstEl.visits)/firstEl.visits);
let second = secondEl.wins / secondEl.visits + sqrt(2 * Math.log(secondEl.visits)/secondEl.visits);
return first - second;
});
当然,这看起来有些冗长,但这就是事实。