Created
December 13, 2010 01:37
-
-
Save ashmckenzie/738540 to your computer and use it in GitHub Desktop.
Find the smallest index in an array where all array values exist prior to index
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def ps(list) | |
freq = {} | |
list.each do |v| | |
freq[v] = 0 if freq[v].nil? | |
freq[v] += 1 | |
end | |
list.each_with_index do |v, i| | |
freq.delete(v) | |
if freq.empty? | |
return i | |
end | |
end | |
return list.size - 1 | |
end | |
class TestPs < Test::Unit::TestCase | |
def test_one | |
arr = [ 2, 2, 1, 0, 1 ] | |
assert_equal(ps(arr), 3) | |
end | |
def test_two | |
arr = [ 1, 0 ] | |
assert_equal(ps(arr), 1) | |
end | |
def test_three | |
arr = [ 1, 2, 3, 3, 3, 3, 10, 11, 9 ] | |
assert_equal(ps(arr), 8) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment