ruby find_duplicate_with_hash_store.rb

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby find_duplicate_with_hash_store.rb相关的知识,希望对你有一定的参考价值。

# Given an array of n numbers with exactly one duplicate, write a program that finds the duplicate number in an efficient manner

require 'minitest/autorun'


def find_duplicate(numbers_array)

  # using an hash as a way to keep track of evaluted numbers
  checked_numbers = {}

  numbers_array.each do |number|
    return number if checked_numbers[number] != nil
    checked_numbers[number] = number
  end

  'no duplicate found'
end

class FindDuplicatesTest < MiniTest::Unit::TestCase

  def test_returns_message_with_no_duplicates
    assert_equal 'no duplicate found', find_duplicate([1, 2, 3].shuffle)
  end

  def test_returns_duplicate_with_small_array
    assert_equal 3, find_duplicate([1, 2, 3, 3].shuffle)
  end

  def test_returns_duplicate_with_larger_array
    assert_equal 9999, find_duplicate((1..9999).to_a.shuffle << 9999)
  end
end

以上是关于ruby find_duplicate_with_hash_store.rb的主要内容,如果未能解决你的问题,请参考以下文章

Ruby 脚本可以告诉它在哪个目录中吗?

Ruby:无法加载此类文件 - LoadError

Ruby 命名空间

ruby sieve_1_prime_17.rb

ruby sieve_1_prime_13.rb

ruby sieve_1_prime_11.rb