I have the following classes:
class Sport {
private String sportsName;
private List<People> peopleWhoPlayThisSport;
//...
}
class People {
private String name;
private long uniqueId;
// ...
}
My input is a list of sport objects, for simplicity consider the below examples:
sport1 - Football, <Sam, Dylan>
sport2 - Basketball, <Tyler, John>
sport3 - Baseball, <Carter, Dylan>
sport4 - Hockey, <Kane, Michael>
sport5 - Soccer, <Carter, Frank>
I have to create a List<List<>>
, such that the inner list is all the sports which have at least 1 common player (Transitive property applies here). In the above example, the output should be,
<<sport1,sport3,sport5> , <sport2> , <sport4>>
Any suggestions on solving this and/or pseudo-code?
Sounds like graph problem to me. What I would do is following:
So the graph would grow this way:
And "applying sports" :
==> (Football, Baseball, Soccer), (Basketball), (Hockey)
Edit: Optionally you may optimize the algorithm that for every component, you will remember what sports are tied to it. In other words, when creating an edge, you will add a sport to the component's collection of sports. Then "apply sports" step won't be no longer needed. One simple rule, when two components get connected, you will union sport collections before adding a new sport. The algorithm then would go:
Please note that usage of graph is not neccessary. You can still go away with simple collections but the graph seemed as the cleanest way and algorithm-optimal way to do so. It also allows further extensibility because it models the data in natural way - for example you can further find out why Sam is in group with Carter (because their common friend Dylan plays a different sport with both of them).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With