Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Complete Challenge2015 #50

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 18 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#Degrees of Separation

With cinema going global these days, every one of the [A-Z]ollywoods are now connected. Use the wealth of data available at [Moviebuff](http://www.moviebuff.com) to see how.
With cinema going global these days, every one of the [A-Z]ollywoods are now connected. Use the wealth of data available at [Moviebuff](http://www.moviebuff.com) to see how.

Write a Go program that behaves the following way:

Expand All @@ -22,7 +22,7 @@ Director: Martin Scorsese
Actor: Robert De Niro
```

Your solution should use the Moviebuff data available to figure out the smallest degree of separation between the two people.
Your solution should use the Moviebuff data available to figure out the smallest degree of separation between the two people.
All the inputs should be Moviebuff URLs for their respective people: For Amitabh Bachchan, his page is on http://www.moviebuff.com/amitabh-bachchan and his Moviebuff URL is `amitabh-bachchan`.

Please do not attempt to scrape the Moviebuff website - All the data is available on an S3 bucket in an easy to parse JSON format here: `https://data.moviebuff.com/{moviebuff_url}`
Expand All @@ -42,11 +42,25 @@ http://data.moviebuff.com/martin-scorsese
http://data.moviebuff.com/taxi-driver

##Notes
* If you receive HTTP errors when trying to fetch the data, that might be the CDN throttling you. Luckily, Go has some very elegant idioms for rate limiting :)
* There may be a discrepancy in some cases where a movie appears on an actor's list but not vice versa. This usually happens when we edit data while exporting it, so feel free to either ignore these mismatches or handle them in some way.

- If you receive HTTP errors when trying to fetch the data, that might be the CDN throttling you. Luckily, Go has some very elegant idioms for rate limiting :)
- There may be a discrepancy in some cases where a movie appears on an actor's list but not vice versa. This usually happens when we edit data while exporting it, so feel free to either ignore these mismatches or handle them in some way.

Write a program in any language you want (If you're here from Gophercon, use Go :D) that does this. Feel free to make your own input and output format / command line tool / GUI / Webservice / whatever you want. Feel free to hold the dataset in whatever structure you want, but try not to use external databases - as far as possible stick to your langauage without bringing in MySQL/Postgres/MongoDB/Redis/Etc.

To submit a solution, fork this repo and send a Pull Request on Github.

For any questions or clarifications, raise an issue on this repo and we'll answer your questions as fast as we can.

# How to use CLI tool to find degrees of separation

1. Clone this repo.
2. Navigate to the project directory.
3. Install dependencies using the below command:
```
go mod download
```
4. Run the tool using the below command:
```
go run . <moviebuff_url_1> <moviebuff_url_2>
```
93 changes: 93 additions & 0 deletions api.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
package main

import (
"encoding/json"
"fmt"
"io"
"net/http"
)

// CommonData is the common data that exists in both Person and Movie.
type CommonData struct {
URL string `json:"url"`
Type string `json:"type"`
Name string `json:"name"`
}

// Participation is the data that represents both:
// 1. A movie in which a person has played a role.
// 2. A person who played a role in a movie.
type Participation struct {
URL string `json:"url"`
Name string `json:"name"`
Role string `json:"role"`
}

// Person is the data that represents a person.
type Person struct {
CommonData
Movies []Participation `json:"movies"`
}

// Movie is the data that represents a movie.
type Movie struct {
CommonData
Cast []Participation `json:"cast"`
Crew []Participation `json:"crew"`
}

// baseURL is the base URL for the Moviebuff API.
const baseURL = "https://data.moviebuff.com"

// FetchData is a helper function that fetches data from any Moviebuff URL.
func FetchData(moviebuffURL string) ([]byte, error) {
res, err := http.Get(fmt.Sprintf("%s/%s", baseURL, moviebuffURL))
if err != nil {
return nil, err
}

data, err := io.ReadAll(res.Body)
if err != nil {
return nil, err
}

switch res.StatusCode {
case 200:
return data, nil

default:
return nil, fmt.Errorf("invalid response. Status code: %d. Data: %s", res.StatusCode, string(data))
}
}

// FetchMovie is a helper function that fetches movie data from a Moviebuff URL.
func FetchMovie(movieURL string) (Movie, error) {
data, err := FetchData(movieURL)
if err != nil {
return Movie{}, err
}

var movie Movie
err = json.Unmarshal(data, &movie)
if err != nil {
return Movie{}, err
}

return movie, nil
}

// FetchPerson is a helper function that fetches person data from a Moviebuff URL.
func FetchPerson(personURL string) (Person, error) {
data, err := FetchData(personURL)
if err != nil {
return Person{}, err
}

var person Person
err = json.Unmarshal(data, &person)
if err != nil {
return Person{}, err
}

return person, nil
}
13 changes: 13 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
module github.com/milanvthakor/qube-cinema-task

go 1.23.1

require github.com/briandowns/spinner v1.23.1

require (
github.com/fatih/color v1.7.0 // indirect
github.com/mattn/go-colorable v0.1.2 // indirect
github.com/mattn/go-isatty v0.0.8 // indirect
golang.org/x/sys v0.0.0-20220412211240-33da011f77ad // indirect
golang.org/x/term v0.1.0 // indirect
)
13 changes: 13 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
github.com/briandowns/spinner v1.23.1 h1:t5fDPmScwUjozhDj4FA46p5acZWIPXYE30qW2Ptu650=
github.com/briandowns/spinner v1.23.1/go.mod h1:LaZeM4wm2Ywy6vO571mvhQNRcWfRUnXOs0RcKV0wYKM=
github.com/fatih/color v1.7.0 h1:DkWD4oS2D8LGGgTQ6IvwJJXSL5Vp2ffcQg58nFV38Ys=
github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4=
github.com/mattn/go-colorable v0.1.2 h1:/bC9yWikZXAL9uJdulbSfyVNIR3n3trXl+v8+1sx8mU=
github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE=
github.com/mattn/go-isatty v0.0.8 h1:HLtExJ+uU2HOZ+wI0Tt5DtUDrx8yhUqDcp7fYERX4CE=
github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20220412211240-33da011f77ad h1:ntjMns5wyP/fN65tdBD4g8J5w8n015+iIIs9rtjXkY0=
golang.org/x/sys v0.0.0-20220412211240-33da011f77ad/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.1.0 h1:g6Z6vPFA9dYBAF7DWcH6sCcOntplXsDKcliusYijMlw=
golang.org/x/term v0.1.0/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
31 changes: 31 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package main

import (
"fmt"
"os"
"time"

"github.com/briandowns/spinner"
)

func main() {
if len(os.Args) < 3 {
fmt.Println("Error: Invalid number of arguments.")
fmt.Println("Usage: go run . <moviebuff_url_1> <moviebuff_url_2>")
return
}

moviebuffURL1 := os.Args[1]
moviebuffURL2 := os.Args[2]
if moviebuffURL1 == moviebuffURL2 {
fmt.Println("Error: Moviebuff URLs must be different.")
return
}

fmt.Println("Searching Moviebuff...")
s := spinner.New(spinner.CharSets[9], 100*time.Millisecond)
s.Start()
defer s.Stop()

SeperationDegrees(moviebuffURL1, moviebuffURL2)
}
30 changes: 30 additions & 0 deletions utils.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package main

import (
"fmt"
)

// Collaboration represents a collaboration between two people in a movie.
type Collaboration struct {
Movie string
Person1 string
Person1Role string
Person2 string
Person2Role string
}

// PrintCollaborations prints a list of collaborations.
func PrintCollaborations(collabs []Collaboration, degree int64) {
if len(collabs) == 0 {
fmt.Println("\nNo collaborations found.")
return
}

fmt.Println("\nDegree of Seperation: ", degree)
for i, connection := range collabs {
fmt.Printf("%d. Movie: %s\n", i+1, connection.Movie)
fmt.Printf("%s: %s\n", connection.Person1Role, connection.Person1)
fmt.Printf("%s: %s\n", connection.Person2Role, connection.Person2)
fmt.Println()
}
}
33 changes: 33 additions & 0 deletions visited-sources.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package main

import "sync"

// VisitedSources is a set of visited sources with a mutex lock for concurrent access.
// This set is used to avoid repeatedly fetching data from the same source and processing it multiple times.
type VisitedSources struct {
URLs map[string]struct{}
mutex *sync.RWMutex
}

// NewVisitedSources creates a new VisitedSources.
func NewVisitedSources() *VisitedSources {
return &VisitedSources{
URLs: make(map[string]struct{}),
mutex: &sync.RWMutex{},
}
}

// Add adds a URL to the VisitedSources.
func (vs *VisitedSources) Add(url string) {
vs.mutex.Lock()
defer vs.mutex.Unlock()
vs.URLs[url] = struct{}{}
}

// Has checks if a URL is in the VisitedSources.
func (vs *VisitedSources) Has(url string) bool {
vs.mutex.RLock()
defer vs.mutex.RUnlock()
_, ok := vs.URLs[url]
return ok
}
Loading