Skip to content

Instantly share code, notes, and snippets.

@NoMan2000
Created March 10, 2019 22:40
Show Gist options
  • Save NoMan2000/c8c1e9d0140f27d99681a81893f2978d to your computer and use it in GitHub Desktop.
Save NoMan2000/c8c1e9d0140f27d99681a81893f2978d to your computer and use it in GitHub Desktop.

Revisions

  1. NoMan2000 created this gist Mar 10, 2019.
    86 changes: 86 additions & 0 deletions missing_numbers.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,86 @@
    require "test/unit"

    NOT_A_NUMBER = 1
    ALL_GOOD = 0

    def update_previous_value_if_one_ahead(i, prev)
    if prev == nil
    prev = i.to_i
    else
    check_value = prev.to_i + 1
    if check_value == i
    prev = i.to_i
    end
    end
    prev.to_i
    end

    def find_missing_number(sequence)
    arr = sequence.split(' ')
    unless arr.length
    return ALL_GOOD
    end
    prev = nil


    arr.each do |i|
    # Check if not a number
    if i =~ /\D/
    return NOT_A_NUMBER
    end
    i = i.to_i
    # Wouldn't normally recommend this approach.
    if prev == nil and i == 2
    return 1
    end
    prev = update_previous_value_if_one_ahead(i, prev)

    if i != prev
    return prev + 1
    end
    end
    ALL_GOOD
    end

    class BLUR_TEST < Test::Unit::TestCase

    def test_will_return_one_if_not_a_number
    assert_equal(NOT_A_NUMBER, find_missing_number('a'))
    end

    def test_will_return_missing_number
    assert_equal(
    4,
    find_missing_number("1 2 3 5"),
    "It must work for missing middle terms")
    end

    def test_will_return_missing_number_two
    assert_equal(
    2,
    find_missing_number("1 3")
    )
    end

    def test_will_return_0_for_empty_set
    assert_equal(
    0,
    find_missing_number("")
    )
    end

    def test_will_return_missing_number_again
    assert_equal(
    1,
    find_missing_number("2 3 4 5")
    )
    end
    def test_will_return_1_on_invalid_sequence
    assert_equal(
    1,
    find_missing_number("2 1 4 3 a")
    )
    end

    end