从集合中选择具有最小Schwartzian变换的对象

问题描述 投票:1回答:1

我正在为http://aichallenge.org/specification.php实现A *,并且想知道一种灵活的方法来选择基于schartzian变换的最小集合。

基本上,我有一组合适的方块可以移动到,我想以最低的成本移动到广场。

基本上我将从我的邻居那里选择一个循环中成本最低的广场。

我能想到的唯一方法是做类似的事情

next_spot = spot.neighbors.sort_by |a,b| { a.cost(dest) <=> b.cost(dest) }.first

但是我真的想要更高性能的东西,因为我真的不想对集合进行排序,我只想要一个具有最小变换值的那个

注意,我可以写一些更详细和“C风格”循环并跟踪先前的最小值,但我希望有一些清晰和紧凑的东西。

ruby artificial-intelligence path-finding
1个回答
2
投票

为什么不使用min_by

next_spot = spot.neighbors.min_by { |x| x.cost(dest) }

如果不存在Enumerable-ish方法的“_by”版本,你可以通过这种伪Ruby模式手工完成旧学校并进行Schwartzian变换:

a.map { |x| [ expensive(x), x ] }.       # Do the expensive part once and cache it
  op  { |x| something_with x.first... }. # Do what you really came to do
  map { |x| x.last }                     # Unwrap the caching
© www.soinside.com 2019 - 2024. All rights reserved.