Skip to content

Instantly share code, notes, and snippets.

@ashmckenzie
Created December 13, 2010 01:37
Show Gist options
  • Save ashmckenzie/738540 to your computer and use it in GitHub Desktop.
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
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