Skip to content

Instantly share code, notes, and snippets.

@anchietajunior
Created November 20, 2023 10:48
Show Gist options
  • Save anchietajunior/7569840281d6983e88ec3796ee35c99b to your computer and use it in GitHub Desktop.
Save anchietajunior/7569840281d6983e88ec3796ee35c99b to your computer and use it in GitHub Desktop.
Search a person number in a list given a person name
def search_phone_by_name(list, name)
left = 0
right = list.length - 1
while left <= right
mid = (left + right) / 2
current_name = list[mid][:name]
if current_name == name
return list[mid][:phone]
elsif current_name < name
left = mid + 1
else
right = mid - 1
end
end
"Name not found"
end
# Tests
require 'rspec/autorun'
describe 'search_phone_by_name' do
list = [
{ name: "Alice", phone: "123-456-7890" },
{ name: "Bob", phone: "456-789-0123" },
{ name: "Lorenna", phone: "555-123-4567" },
{ name: "Zach", phone: "999-888-7777" }
]
it 'returns the phone when the name is present' do
expect(search_phone_by_name(list, "Lorenna")).to eq("555-123-4567")
end
it 'returns a message when the name is not found' do
expect(search_phone_by_name(list, "Sarah")).to eq("Name not found")
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment