Question

Problem: Who Is within D Degrees of Separation? Given a series of knows relationships such as Alice knows Bob, a degree D
and V are single-word names of people. Eg, Alice knows Bob. The section is termmated by a single word done The second sec
Background: Six Degrees of Separation There is a famous idea by Frigyes Karinthy (1929) that states that any two people in th
Problem: Who Is within D Degrees of Separation? Given a series of "knows" relationships such as "Alice knows Bob", a degree D, and a person P, output the group of people that are within D degrees of separation of person P For example, given the input, which consists of a network of acquaintances followed by one or more queries of the form "degree person" such as Alice knows Bob Carol knows Dave Carol knows Bob Bob knows Eve Eve knows Carol Eve knows Fred done 2 Carol done Figure 2: Sample network of acquaintance and a query. The output is the group of acquaintances within the specified degree Carol is within 2 degrees of separation from: Bob Dave Eve Figure 3: The answer to theq Your task is to create a program that computes the group of people within a specified degree of separation for a person in a social network. Write a program called InDDegrees.java that reads in a series of "knows" relationships from the console (System.in), representing a social network, followed by one or more queries, and outputs the corresponding groups. Your InDDegrees class must contain the mainO method where your program starts running Input Your program should read in the input using a Scanner object, which is instantiated with System.in. The input will comprise two sections with one or more lines in each section. The first section denotes the social network and comprises zero or more lines of the form X knows Y
and V are single-word names of people. Eg, "Alice knows Bob". The section is termmated by a single word "done" The second section denotes the queries and comprises zero or more lines of the form D X where D is the degree and X is the person for which the program should compute the group of people in the social network that are within D degrees of separation from X. E.g., "2 Carol". The section is terminated by a single word "done" Hint: All you need to use are the nextO and nextInt O methods of the Scanner object. Semantics As mentioned previously, the "knows" relationship is not bidirectional. Le., Alice knows Bob does not imply that Bob knows Alice. All queries will be valid, meaning that the person being queried is guaranteed to be in the network. Le., for query D X, X wll be in the social network. The maximum value for D is 10000. The maximum size of the social network will be 100000 people. Output Your program should output to System.out. Each line should be terminated by a new line character. For each query D X, the output should begin with the line: X is within D degrees of separation from followed by the people who are within D degrees of X. The people should be listed in sorted (alphabetical) order, one person per line, indented two (2) spaces. See Figure 3 for an example. Note: X should not be part of the list Example Sample Input Sample Output Alice knows Bob Carol knows Dave Carol knows Bob Bob knows Eve Eve knows Carol Eve knows Fred done 2 Carol 3 Fred 3 Eve done Carol is within 2 degrees of separation from Bob Dave Eve Fred is within 3 degrees of separation from Eve is vithin 3 degrees of separation from Bob Carol Dave Fred
Background: Six Degrees of Separation There is a famous idea by Frigyes Karinthy (1929) that states that any two people in the world are connected by at most six steps, where each step is a friend or friend of a friend That is for any two people X and Y, X knows A who knows B who knows C who knows Y. This idea is also prevalent in social networks. A common problem in social networks is given a social network, a person P, and a degree D, who are the people within degree D of P. For example, for D1, this group (S) would consist of all the people that P knows. For D 2, this group (S2) would include S and all the people that people in Si know. Note that just because person X knows Y, does not mean that Y knows X. For example, I may know the Prime Minister of Canada, but it is unlikely that the Prime Minister of Canada knows me
0 0
Add a comment Improve this question Transcribed image text
Answer #1


// Java Code

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import java.util.Scanner;

public class InDDegrees {
  
/**
* The below functions returns a list of people who are within
* D degrees of separation from 'Person'
* The Algorithm used is BFS ('Breadth First Search')
*/
  
public static ArrayList<String> findFriends(Map<String, ArrayList<String>> graph, int D, String Person){
ArrayList<String> friends = new ArrayList<String>();
  
// Queue for running BFS
Queue<String> curList = new LinkedList<String>();
curList.add(Person);
  
// visitedPersons contain the list of all the persons visited so far in BFS
// the value for 'key' is the degree of separation from 'Person'
Map<String,Integer> visitedPersons = new HashMap<String,Integer>();
visitedPersons.put(Person,0);
  
while(!curList.isEmpty()) {
String curPerson = curList.poll();
Integer degree = visitedPersons.get(curPerson);
if(degree >= D) {
break;
}
  
//find the persons who are known to 'curPerson'
if(graph.get(curPerson) != null) {
ArrayList<String> knownToCurPerson = graph.get(curPerson);
  
for(String p : knownToCurPerson) {
// if 'p' doesn't exist in visited, add 'p' to visited and queue
if(!visitedPersons.containsKey(p)) {
visitedPersons.put(p,degree+1);
curList.add(p);
}
}
  
}
  
}
// put all the keys for which value >=1 in 'friends'
for(String p : visitedPersons.keySet()) {
if(visitedPersons.get(p) > 0)
friends.add(p);
}
  
return friends;
  
}
  
  
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
ArrayList<String> relationships = new ArrayList<String>();
String s = in.nextLine();
while(!s.equals("done")) {
relationships.add(s);
s = in.nextLine();
}
ArrayList<String> queries = new ArrayList<String>();
s = in.nextLine();
while(!s.equals("done")) {
queries.add(s);
s = in.nextLine();
}
  
// now build a directed graph using relationship List
// The Directed graph is stored as a Map.
Map< String, ArrayList<String> > graph = new HashMap< String, ArrayList<String>>();
// the Key consists of name of a person (e.g "Alice","Bob" etc)
// the value consists of an ArrayList which contains the all the persons known to 'key'
  
for (String r:relationships) {
// Assuming that 'r' is of the form "<String> knows <String>"
String[] names = r.split(" ");
// the first and third string would be the names of the persons
String key = names[0];
  
if(!graph.containsKey(key)) {
ArrayList<String> val = new ArrayList<String>();
val.add(names[2]);
graph.put(key, val);
}else {
ArrayList<String> val = graph.get(key)
;
val.add(names[2]);
graph.replace(key, val);
}
  
}
  
  
// Now get queries
for (String q : queries) {
// Assuming that 'q' is of the form "<Integer> knows <String>"
String[] query = q.split(" ");
int degree = Integer.parseInt(query[0]);
String person = query[1];
System.out.println(person + " is within " + query[0] + " degrees of separation from:");
ArrayList<String> knownPersons = findFriends(graph, degree, person);
  
// sort the list 'knownPersons' and then print the contents
Collections.sort(knownPersons);
for(String per : knownPersons){
System.out.println(" "+per);
}
  
}
  
in.close();

}

}

------------------------------------------------------------------------------------------------------

Alice knows Bob Carol knows Dave Carol knows Bob Bob knows Eve Eve knows Caro Eve knows Fred 2 Carol 3 Fred 3 Eve done Carol

Add a comment
Know the answer?
Add Answer to:
Problem: Who Is within D Degrees of Separation? Given a series of "knows" relationships such as "...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • NOTE: LANGUAGE IS PYTHON CS160 Computer Science Lab 17 Objectives Work with dictionaries Work with functions...

    NOTE: LANGUAGE IS PYTHON CS160 Computer Science Lab 17 Objectives Work with dictionaries Work with functions Work with files Overview This lab will have you store the birthdays for a group of people. This program will store the information with the focus on the date of the month and not on the individual. The point of this program is to be able to see who has a birthday on a given day or to create a table of birthdays, in...

  • NOTE: LANGUAGE IS PYTHON CS160 Computer Science Lab 17 Objectives Work with dictionaries Work with functions...

    NOTE: LANGUAGE IS PYTHON CS160 Computer Science Lab 17 Objectives Work with dictionaries Work with functions Work with files Overview This lab will have you store the birthdays for a group of people. This program will store the information with the focus on the date of the month and not on the individual. The point of this program is to be able to see who has a birthday on a given day or to create a table of birthdays, in...

  • Scott Rock Consultants (SRC) is a professional services firm that provides consulting services to improve business...

    Scott Rock Consultants (SRC) is a professional services firm that provides consulting services to improve business processes. Many of SRC services fall under the areas of organizational design, work-flow analysis, efficiency improvement, and leveraging technology to improve business outcome effectiveness. Founded over 40 years ago by Wes Scott and Eli Rock, SRC, is similar to other firms of this type (e.g., law or accounting firms) in that the same people who sell the services are also those that do the...

  • Bradford Consultants (BC) is a professional services firm that provides consulting services to improve business processes....

    Bradford Consultants (BC) is a professional services firm that provides consulting services to improve business processes. Many of BC services fall under the areas of organizational design, work-flow analysis, efficiency improvement, and leveraging technology to improve business outcome effectiveness. Founded over 40 years ago , BC, is similar to other firms of this type (e.g., law or accounting firms) in that the same people who sell the services are also those that do the work. As in a large law...

  • What an Executive Summary Is An executive summary is a specific type of document that does...

    What an Executive Summary Is An executive summary is a specific type of document that does two things: it summarizes a research article, and it offers recommendations as to how information from the article can be used. Some long reports can contain an executive summary section, as indicated in the Pearson handbook. Write a 2 pahe Executive Summary In business contexts, an executive summary is always written for a specific purpose: to explain the information in the article to a...

  • THE COMPANY: MORE POWER, INC. More Power, Inc., is a large, local retail store specializing in...

    THE COMPANY: MORE POWER, INC. More Power, Inc., is a large, local retail store specializing in the sale and service of hardware, tools, lawn and garden implements, and other materials for the home. More Power operates seven days a week, dawn to dusk. Approximately 120 employees work in distinct divisions within the store, including customer service/return desk; warehouse and delivery; service and repair; and three distinct sections focused on (1) hardware and tools, (2) lawn and garden and outdoors, and...

  • Read and Complete Case Study #2 –Managing People. The central components of your analysis should include issue identific...

    Read and Complete Case Study #2 –Managing People. The central components of your analysis should include issue identification, issue analysis, solutions, and potential limitations to your solutions. The case analyses serve to: a) Provide an opportunity to apply the class concepts in the solution of practical problems. b) Provide you with a common task through which you can learn to be more effective thinkers and problem-solves in your organizations. The written case analysis will be evaluated based on your effectiveness...

  • Using the book, write another paragraph or two: write 170 words: Q: Compare the assumptions of...

    Using the book, write another paragraph or two: write 170 words: Q: Compare the assumptions of physician-centered and collaborative communication. How is the caregiver’s role different in each model? How is the patient’s role different? Answer: Physical-centered communication involves the specialists taking control of the conversation. They decide on the topics of discussion and when to end the process. The patient responds to the issues raised by the caregiver and acts accordingly. On the other hand, Collaborative communication involves a...

  • I need help with my very last assignment of this term PLEASE!!, and here are the instructions: After reading Chapter T...

    I need help with my very last assignment of this term PLEASE!!, and here are the instructions: After reading Chapter Two, “Keys to Successful IT Governance,” from Roger Kroft and Guy Scalzi’s book entitled, IT Governance in Hospitals and Health Systems, please refer to the following assignment instructions below. This chapter consists of interviews with executives identifying mistakes that are made when governing healthcare information technology (IT). The chapter is broken down into subheadings listing areas of importance to understand...

  • Risk management in Information Security today Everyday information security professionals are bombarded with marketing messages around...

    Risk management in Information Security today Everyday information security professionals are bombarded with marketing messages around risk and threat management, fostering an environment in which objectives seem clear: manage risk, manage threat, stop attacks, identify attackers. These objectives aren't wrong, but they are fundamentally misleading.In this session we'll examine the state of the information security industry in order to understand how the current climate fails to address the true needs of the business. We'll use those lessons as a foundation...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT