Sha256: 3929a97010a67ef518a6c134763daa27696189ea634083190d61147dfb3f4b9b

Contents?: true

Size: 757 Bytes

Versions: 1

Compression:

Stored size: 757 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)
          next if numbers.include?(number)

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

        max_elements(numbers)
      end

      private

      def max_elements(numbers)
        numbers.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.1 lib/hrom512/nmax/max_numbers_finder.rb