Speed up Rust's max_by implementation
This commit is contained in:
+13
-36
@@ -79,45 +79,22 @@ public class Solver
|
|||||||
|
|
||||||
return exploitation + exploration;
|
return exploitation + exploration;
|
||||||
}
|
}
|
||||||
|
|
||||||
private enum Ordering
|
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||||
|
private static int RustMaxBy(List<int> source, Func<int, float> into)
|
||||||
{
|
{
|
||||||
Less,
|
var max = 0;
|
||||||
Equal,
|
var maxV = into(source[0]);
|
||||||
Greater
|
for (var i = 1; i < source.Count; ++i)
|
||||||
}
|
|
||||||
|
|
||||||
private static V? RustMaxBy<V, T>(List<V> source, Func<V, T> into)
|
|
||||||
{
|
|
||||||
static Func<V, V, Ordering> compare_into(Func<T, T, Ordering> compare, Func<V, T> into) =>
|
|
||||||
(a, b) => compare(into(a), into(b));
|
|
||||||
|
|
||||||
static Func<T, T, Ordering> compare(IComparer<T> comparer) =>
|
|
||||||
(x, y) => comparer.Compare(x, y) switch
|
|
||||||
{
|
|
||||||
< 0 => Ordering.Less,
|
|
||||||
0 => Ordering.Equal,
|
|
||||||
> 0 => Ordering.Greater,
|
|
||||||
};
|
|
||||||
|
|
||||||
static Func<V, V, V> max_by_fold(Func<V, V, Ordering> compare) =>
|
|
||||||
(x, y) => compare(x, y) switch
|
|
||||||
{
|
|
||||||
Ordering.Less or Ordering.Equal => y,
|
|
||||||
Ordering.Greater => x,
|
|
||||||
_ => x
|
|
||||||
};
|
|
||||||
|
|
||||||
static V? reduce(List<V> d, Func<V, V, V> f)
|
|
||||||
{
|
{
|
||||||
V? accum = default!;
|
var nextV = into(source[i]);
|
||||||
for (var i = 0; i < d.Count; ++i)
|
if (maxV <= nextV)
|
||||||
accum = i == 0 ? d[i] : f(accum, d[i]);
|
{
|
||||||
return accum;
|
max = i;
|
||||||
|
maxV = nextV;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
return source[max];
|
||||||
var comparer = compare_into(compare(Comparer<T>.Default), into);
|
|
||||||
return reduce(source, max_by_fold(comparer));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public int Select(int currentIndex)
|
public int Select(int currentIndex)
|
||||||
|
|||||||
Reference in New Issue
Block a user