From 115e15d12b389af16153015f0b5906bf14048867 Mon Sep 17 00:00:00 2001 From: Jeremy Evans Date: Mon, 17 Jun 2019 14:23:24 -0700 Subject: [PATCH] Implement SortedSet#{min,max,minmax,sum} This results in a huge speedup for large sets. Implements [Misc #15925] --- benchmark/set_min_max_sum.yml | 8 ++++++++ lib/set.rb | 16 ++++++++++++++++ test/test_set.rb | 4 ++++ 3 files changed, 28 insertions(+) create mode 100644 benchmark/set_min_max_sum.yml diff --git a/benchmark/set_min_max_sum.yml b/benchmark/set_min_max_sum.yml new file mode 100644 index 0000000000..0a4678bdbc --- /dev/null +++ b/benchmark/set_min_max_sum.yml @@ -0,0 +1,8 @@ +prelude: | + require 'set' + set = SortedSet.new((0..1000).sort{rand}) +benchmark: + min: set.min + max: set.max + minmax: set.minmax + sum: set.sum diff --git a/lib/set.rb b/lib/set.rb index 921f18f97b..421d4dfc88 100644 --- a/lib/set.rb +++ b/lib/set.rb @@ -738,6 +738,22 @@ def replace(enum) super end + def min + to_a.first + end + + def max + to_a.last + end + + def minmax + [min, max] + end + + def sum + to_a.sum + end + def add(o) o.respond_to?(:<=>) or raise ArgumentError, "value must respond to <=>" @keys = nil diff --git a/test/test_set.rb b/test/test_set.rb index b20920e63e..5f5bff58de 100644 --- a/test/test_set.rb +++ b/test/test_set.rb @@ -799,6 +799,10 @@ def test_sortedset s = SortedSet[4,5,3,1,2] assert_equal([1,2,3,4,5], s.to_a) + assert_equal(1, s.min) + assert_equal(5, s.max) + assert_equal([1,5], s.minmax) + assert_equal(15, s.sum) prev = nil s.each { |o| assert(prev < o) if prev; prev = o } -- 2.21.0