ruby find_duplicate.rb

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby find_duplicate.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 array as a way to keep track of evaluted numbers
  checked_numbers = []

  numbers_array.each do |number|
    return number if checked_numbers.include?(number)
    checked_numbers << 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.rb的主要内容,如果未能解决你的问题,请参考以下文章

Ruby运算符

Ruby 25 岁了!Ruby 之父说 Ruby 3 有望 3 倍提速

如何学习ruby?Ruby学习技巧分享

ruby Ruby脚本,看看是否用openssl编译了ruby

什么是ruby?

ruby和ruby ee