Skip to content

Qube Cinema Challenge2015 solution #57

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

Open
wants to merge 2 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
7 changes: 7 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# Ignore binary files
qubecli
*.exe
*.out
*.o
*.so
*.a
Empty file added LICENSE
Empty file.
59 changes: 59 additions & 0 deletions cmd/degrees.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/*
Copyright © 2025 NAME HERE [email protected]
*/
package cmd

import (
"fmt"
"log"

"github.com/sharmayajush/challenge2015/pkg/degrees"
"github.com/spf13/cobra"
)

// degreesCmd represents the degrees command
var degreesCmd = &cobra.Command{
Use: "degrees <person1> <person2>",
Short: "Find the degrees of separation between two actors",
Long: `Find the degrees of separation between two actors using a BFS algorithm.

Arguments:
<person1> Name of the first actor
<person2> Name of the second actor

Example:
qubecli degrees amitabh-bachchan robert-de-niro`,
Args: cobra.ExactArgs(2), // Ensure exactly 2 arguments are provided
Run: func(cmd *cobra.Command, args []string) {
start := args[0]
target := args[1]

// Call your BFS function
ans, err := degrees.BfsWithPath(start, target)
if err != nil {
log.Fatalf("Error finding path: %v", err)
}

// Print the result
fmt.Printf("\nDegrees of Separation: %v \n\n", len(ans.Nodes))
for i, node := range ans.Nodes {
fmt.Printf("%v. Movie: %s\n", i+1, node.Movie)
fmt.Printf("%s: %s\n", node.Role1, node.Person1)
fmt.Printf("%s: %s\n\n", node.Role2, node.Person2)
}
},
}

func init() {
rootCmd.AddCommand(degreesCmd)

// Here you will define your flags and configuration settings.

// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// degreesCmd.PersistentFlags().String("foo", "", "A help for foo")

// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// degreesCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
51 changes: 51 additions & 0 deletions cmd/root.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/*
Copyright © 2025 NAME HERE <EMAIL ADDRESS>

*/
package cmd

import (
"os"

"github.com/spf13/cobra"
)



// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Use: "challenge2015",
Short: "A brief description of your application",
Long: `A longer description that spans multiple lines and likely contains
examples and usage of using your application. For example:

Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.`,
// Uncomment the following line if your bare application
// has an action associated with it:
// Run: func(cmd *cobra.Command, args []string) { },
}

// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
err := rootCmd.Execute()
if err != nil {
os.Exit(1)
}
}

func init() {
// Here you will define your flags and configuration settings.
// Cobra supports persistent flags, which, if defined here,
// will be global for your application.

// rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.challenge2015.yaml)")

// Cobra also supports local flags, which will only run
// when this action is called directly.
rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}


9 changes: 9 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
module github.com/sharmayajush/challenge2015

go 1.23.6

require (
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/spf13/cobra v1.9.1 // indirect
github.com/spf13/pflag v1.0.6 // indirect
)
10 changes: 10 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/spf13/cobra v1.9.1 h1:CXSaggrXdbHK9CF+8ywj8Amf7PBRmPCOJugH954Nnlo=
github.com/spf13/cobra v1.9.1/go.mod h1:nDyEzZ8ogv936Cinf6g1RU9MRY64Ir93oCnqb9wxYW0=
github.com/spf13/pflag v1.0.6 h1:jFzHGLGAlb3ruxLB8MhbI6A8+AQX/2eW4qeyNZXNp2o=
github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
12 changes: 12 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/*
Copyright © 2025 NAME HERE <EMAIL ADDRESS>
*/
package main

import (
"github.com/sharmayajush/challenge2015/cmd"
)

func main() {
cmd.Execute()
}
27 changes: 27 additions & 0 deletions makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
APP_NAME = qubecli
BIN_DIR = /usr/local/bin

.PHONY: all build install uninstall clean

# Default target (just runs build)
all: build

# Build the Go binary
build:
go build -o $(APP_NAME)

# Install the binary system-wide
install: build
sudo mv $(APP_NAME) $(BIN_DIR)/
sudo chmod +x $(BIN_DIR)/$(APP_NAME)
echo "Installation complete! Run '$(APP_NAME)' from anywhere."

# Remove the installed binary
uninstall:
sudo rm -f $(BIN_DIR)/$(APP_NAME)
echo "Uninstalled $(APP_NAME)."

# Clean up build artifacts
clean:
rm -f $(APP_NAME)
echo "Cleaned up build files."
5 changes: 5 additions & 0 deletions pkg/constants/constants.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package constants

const (
Url = "https://data.moviebuff.com/"
)
28 changes: 28 additions & 0 deletions pkg/degrees/api.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package degrees

import (
"fmt"
"io"
"net/http"

"github.com/sharmayajush/challenge2015/pkg/constants"
)

func getData(url string) ([]byte, error) {
resp, err := http.Get(constants.Url + url)
if err != nil {
return nil, fmt.Errorf("unable to do get for %s: %w", url, err)
}
defer resp.Body.Close()

if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("status code %d for %s", resp.StatusCode, url)
}

data, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("unable to read the resp body for %s: %w", url, err)
}

return data, nil
}
106 changes: 106 additions & 0 deletions pkg/degrees/bfs.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
package degrees

import (
"encoding/json"
"errors"
"log"
"sync"
)

func BfsWithPath(start, target string) (*Path, error) {
visited := &sync.Map{}
queue := make([]Path, 0)
queue = append(queue, Path{Nodes: []Node{}})
visited.Store(start, true)

for len(queue) > 0 {
currentNodes := queue[0]
queue = queue[1:]
currentPerson := start
if len(currentNodes.Nodes) != 0 {
currentPerson = currentNodes.Nodes[len(currentNodes.Nodes)-1].Url2
}

body, err := getData(currentPerson)
if err != nil {
log.Printf("error getting data for %s. error: %s", currentPerson, err.Error())
continue
}

var actor RespActorDto
err = json.Unmarshal(body, &actor)
if err != nil {
log.Printf("error in unmarshalling actorDTO for %s. error: %s", currentPerson, err.Error())
continue
}

var wg sync.WaitGroup
movieChan := make(chan RespMovieDto, len(actor.Movies))

for _, movie := range actor.Movies {
wg.Add(1)
go func(movie commonConfig) {
defer wg.Done()

if _, loaded := visited.LoadOrStore(movie.Url, true); loaded {
return
}

body, err := getData(movie.Url)
if err != nil {
log.Printf("error getting data for %s. error: %s", movie.Url, err.Error())
return
}

var movieDTO RespMovieDto
err = json.Unmarshal(body, &movieDTO)
if err != nil {
log.Printf("error in unmarshalling movieDTO for %s. error: %s", movie.Url, err.Error())
return
}

movieChan <- movieDTO
}(movie)
}

go func() {
wg.Wait()
close(movieChan)
}()

var role1, person1 string
for movieDTO := range movieChan {
for _, p := range append(movieDTO.Cast, movieDTO.Crew...) {
if p.Url == currentPerson {
role1 = p.Role
person1 = p.Name
break
}
}

for _, p := range append(movieDTO.Cast, movieDTO.Crew...) {
if _, loaded := visited.LoadOrStore(p.Url, true); loaded {
continue
}

newNodes := Path{
Nodes: append(currentNodes.Nodes, Node{
Movie: movieDTO.Name,
Role1: role1,
Person1: person1,
Role2: p.Role,
Person2: p.Name,
Url2: p.Url,
}),
}

if p.Url == target {
return &newNodes, nil
}
queue = append(queue, newNodes)
}
}
}

return &Path{}, errors.New("unable to get a path")
}
40 changes: 40 additions & 0 deletions pkg/degrees/models.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package degrees

// common config for movie or person
type commonConfig struct {
Name string `json:"name"`
Url string `json:"url"`
Role string `json:"role"`
}

// config for getting actor data
type RespActorDto struct {
Url string `json:"url"`
Type string `json:"type"`
Name string `json:"name"`
Movies []commonConfig `json:"movies"`
}

// config for getting movie data
type RespMovieDto struct {
Url string `json:"url"`
Type string `json:"type"`
Name string `json:"name"`
Cast []commonConfig `json:"cast"`
Crew []commonConfig `json:"crew"`
}

// for storing path taken
type Path struct {
Nodes []Node
}

// storing info for path which will be required later
type Node struct {
Person1 string
Role1 string
Person2 string
Role2 string
Url2 string
Movie string
}