From a6ab09889069dcd4ec47f9826c1ba630d461dac7 Mon Sep 17 00:00:00 2001 From: Asriel Camora Date: Sun, 18 Jun 2023 12:28:53 -0700 Subject: [PATCH] Speed up Rust's max_by implementation --- Solver/Crafty/Solver.cs | 49 +++++++++++------------------------------ 1 file changed, 13 insertions(+), 36 deletions(-) diff --git a/Solver/Crafty/Solver.cs b/Solver/Crafty/Solver.cs index 8a384f4..6b6f8b4 100644 --- a/Solver/Crafty/Solver.cs +++ b/Solver/Crafty/Solver.cs @@ -79,45 +79,22 @@ public class Solver return exploitation + exploration; } - - private enum Ordering + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static int RustMaxBy(List source, Func into) { - Less, - Equal, - Greater - } - - private static V? RustMaxBy(List source, Func into) - { - static Func compare_into(Func compare, Func into) => - (a, b) => compare(into(a), into(b)); - - static Func compare(IComparer comparer) => - (x, y) => comparer.Compare(x, y) switch - { - < 0 => Ordering.Less, - 0 => Ordering.Equal, - > 0 => Ordering.Greater, - }; - - static Func max_by_fold(Func compare) => - (x, y) => compare(x, y) switch - { - Ordering.Less or Ordering.Equal => y, - Ordering.Greater => x, - _ => x - }; - - static V? reduce(List d, Func f) + var max = 0; + var maxV = into(source[0]); + for (var i = 1; i < source.Count; ++i) { - V? accum = default!; - for (var i = 0; i < d.Count; ++i) - accum = i == 0 ? d[i] : f(accum, d[i]); - return accum; + var nextV = into(source[i]); + if (maxV <= nextV) + { + max = i; + maxV = nextV; + } } - - var comparer = compare_into(compare(Comparer.Default), into); - return reduce(source, max_by_fold(comparer)); + return source[max]; } public int Select(int currentIndex)