Sha256: cc3844f1b2507b11bab536ff4fea3d2fdb0ec6a45fdada3972540f5af12c69fc

Contents?: true

Size: 718 Bytes

Versions: 1

Compression:

Stored size: 718 Bytes

Contents

module Hrom512
  module Nmax
    # Find N maximum numbers in input stream
    class MaxNumbersFinder
      MAX_STORE_ELEMENTS = 1_000_000

      def initialize(input_stream, numbers_count)
        @input_stream = input_stream
        @numbers_count = numbers_count
      end

      def find
        numbers_parser = NumbersParser.new(@input_stream)
        numbers = []

        while (number = numbers_parser.next_number)
          numbers << number
          numbers = max_elements(numbers) if numbers.size > MAX_STORE_ELEMENTS
        end

        max_elements(numbers)
      end

      private

      def max_elements(numbers)
        numbers.uniq.sort.reverse[0..(@numbers_count - 1)]
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
hrom512-nmax-0.1.2 lib/hrom512/nmax/max_numbers_finder.rb