Last active
November 14, 2019 06:35
-
-
Save bion/9db02fa6fe4389927f031e57148b74e4 to your computer and use it in GitHub Desktop.
Webpage counting interview question
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
| require 'set' | |
| Page = Struct.new(:url) do | |
| LINK_TABLE = { | |
| "google.com" => %w[google.com/maps google.com/mail], | |
| "google.com/mail" => %w[google.com google.com/mail/drafts google.com/mail/spam], | |
| "google.com/mail/drafts" => %w[google.com google.com/mail google.com/mail/spam], | |
| "google.com/mail/spam" => %w[google.com google.com/mail google.com/mail/drafts], | |
| "google.com/maps" => %w[google.com google.com/my-maps google.com/mail], | |
| "google.com/my-maps" => %w[google.com google.com/maps] | |
| } | |
| def links | |
| LINK_TABLE.fetch(url) | |
| rescue KeyError | |
| puts "unknown url: #{url}" | |
| end | |
| end | |
| def count_pages(starting_url) | |
| visited_urls = Set.new | |
| urls_to_visit = [starting_url] | |
| until urls_to_visit.empty? | |
| current_page = Page.new(urls_to_visit.pop) | |
| visited_urls.add(current_page.url) | |
| current_page.links.each do |link| | |
| unless visited_urls.include?(link) | |
| urls_to_visit.push(link) | |
| end | |
| end | |
| end | |
| visited_urls.size | |
| end | |
| puts count_pages("google.com") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment