Get Edge list between two graph Vertex - java

I have the own data structure for the graph, and I need the implementation method:
List<Edge<T>> getPath(T start, T finish)
Performance not important, I search the simplest and most readable way. But my data structure should support the directed and undirected graph types and I stuck with it.
public class Graph<T> {
private boolean isDirected = false;
private Map<Vertex<T>, List<Edge<T>>> graph = new HashMap<>();
public Graph() {
}
public Graph(boolean isDirected) {
this.isDirected = isDirected;
}
public List<Edge<T>> getPath(T start, T finish) {
if (start.equals(finish)) {
return new ArrayList<>();
}
// TODO here is the method I'm stuck with.
if (isDirected) {
// Call search for directed graph
} else {
// Call search for undirected graph
}
}
public void addEdge(T first, T second) {
final Vertex<T> master = new Vertex<>(first);
final Vertex<T> slave = new Vertex<>(second);
final Set<Vertex<T>> vertices = graph.keySet();
if (!vertices.contains(master) || !vertices.contains(slave)) {
throw new IllegalArgumentException();
}
graph.get(master).add(new Edge<>(master, slave));
if (!isDirected) {
graph.get(slave).add(new Edge<>(slave, master));
}
}
public void addVertex(T value) {
final List<Edge<T>> result = graph.putIfAbsent(new Vertex<>(value), new ArrayList<>());
if (result != null) {
throw new IllegalArgumentException();
}
}
}
This Vertex and Edge class:
#Data
#AllArgsConstructor
#EqualsAndHashCode
public class Vertex<T> {
private T value;
}
#Data
#NoArgsConstructor
#AllArgsConstructor
public class Edge<T> {
private Vertex<T> first;
private Vertex<T> second;
}
I will be very grateful for Your help.

It is not totally clear what kind of path you want to find. The shortest path, any path,...?
If you want to find the shortest path, A* is a really simple algorithm to implement. The pseudo code can be found here. A* is a best-first search algorithm for a weighted graph (E.g. the distance of an edge or another kind of cost to travel on the edge like time). The algorithm uses a heuristic function to select the next node/vertex to evaluate. A* basically repeats the following steps:
Select a next node/vertex which has not already been visited. The selection is made using the heuristic function
If this new node equals the goal position, return the shortest path found
Evaluate all paths currently known and select the one with the lowest cost
I could also provide a Java code snippet (based on the pseudo code) if it's necessary. Be aware that the pseudo code in the end constructs the shortest path backwards (from goal to start).
You are also using a generic for your graph. Both your Vertext and Edge class use this generic. Let's assume that this generic T is a double. In your code this means that your Vertex is only a one-dimensional double. This does not make sense when you want to represent a graph of 2D or 3D points.
Is it even really necessary to use this generic? Wouldn't it be sufficient to simply support vertices which consists of floats, doubles or integers? Using a generic type or more abstract class (like Number) might give some problems when you for example want to compute the distance between vertices.

Related

Trouble with Java Public Enum

I am attempting to simulate a BB84 protocol using Java programming language. Anyway, I am having some trouble with getting the complimentary/invert set of data from the result.
In my program, there is a total of 3 steps involved.
1. Generate 5 random binary number **check**
---> exp: 10010
2. Random bases to represent each bits (either rectilinear or diagonal) **check**
---> exp: RECTILINEAR, RECTILINEAR, DIAGONAL, DIAGONAL, RECTILINEAR
3. Complimentary bases (Invert bases used in second step) **not check**
---> exp: DIAGONAL, DIAGONAL, RECTILINEAR, RECTILINEAR, DIAGONAL
This is my runnable program: here
As you can see, I've attempted to write a class Basis complimentary() in Basis.java that will take in random basis generated and invert the bases used.
public enum Basis {
RECTILINEAR,
DIAGONAL;
public static Basis random() {
int i = (int)(Math.random()*2);
if(i==0)
return Basis.RECTILINEAR;
else
return Basis.DIAGONAL;
}
public static Basis complimentary() {
if (Basis.random()==Basis.RECTILINEAR)
{
return Basis.DIAGONAL;
}
else
{
return Basis.RECTILINEAR;
}
}
}
But I notice it is generating random bases all over again and my third step does not seem to output the invert set used in the second step. Help is appreciated.
Edited:
So, in the FilterScheme2.java, i referenced FilterScheme1.java in the constructor like this.
public class FilterScheme2 extends AbstractScheme{
private Filter[] filters;
public FilterScheme2(int size) {
super(size);
filters = new Filter[size];
FilterScheme1 f = new FilterScheme1(size);//reference to FilterScheme1.java
for(int i=0;i<size;i++) {
filters[i] = new Filter(filters[i].getBasis().complimentary()); //generate the second set of complimentary bases (rectilinear/diagonal)
}
}
I tried to output System.out.println(f.toString()); to make sure that I get the same data as FilterScheme1 but it seems like it generate random bases again. What could be the problem?
You need to reference what exact instance you want the compliment of. This can be done by passing as argument, or by making complimentary non-static:
public static Basis complimentary(Basis subject) {
if (subject == Basis.RECTILINEAR)
{
return Basis.DIAGONAL;
}
else
{
return Basis.RECTILINEAR;
}
}
…
Basis.complimentary(Basis.DIAGONAL); // RECTILINEAR
Or
public Basis complimentary() {
if (this == Basis.RECTILINEAR)
{
return Basis.DIAGONAL;
}
else
{
return Basis.RECTILINEAR;
}
}
…
Basis.DIAGONAL.complimentary(); // RECTILINEAR

Which design pattern to use (Active and passive methods)?

I have a player which can feed a dog or chop a tree.
Below are the classes I have written:
public class Dog {
private int health;
public void feed(Food food){
health = health + food.getNutritionalValue();
}
}
public class Player{
public void feed(Dog dog, Food food) {
dog.feed(food);
}
Player and Dog both have methods that are "active".
Player feeds the dog and dog starts eating the food (I am not really sure if it is good to couple methods in this way).
On the other hand, I have tree. And player is able to chop the tree.
public class Player{
public void chop(Tree tree) {
//At this point I am not sure
}
I am not sure if I would use getters and setters of Tree class to interact with the Tree.
Or if I should write an own method for this because the tree gets chopped so it is nothing really active I would call.
So, in the end, there would be two or more kinds of implementations but the two I am thinking of are:
tree.setAmountofWood = x
or
tree.gettingChopped(Damage int)
I think I should make an own method for this chopping-process.
Or is there any design principle I should follow?
I see 3 principles here,
SRP - It is the responsibility of the Tree to get chopped and fall down, but to cut is the responsibility of the Person!
Demeter's law - looks good from my POV.
OCP - The tree must be able to do further actions when get cut.
So you must use
tree.gettingChopped(Damage damage)
To your code:
The method Dog.feed is wrong, rename it to Dog.eat because the Dog is not feeding, the dog is eating. By the way, the food must reduce its NutritionalValue.
The health is an integer value, this is bad because in reality there is nothing like a numeral health. We may have a handicapped numeral value in percent, but this is more a byte who not can be in negative value. You should create a custom class for the Health! This way your code is open(OCP) for extensions like to be toxified or depresive.
I would start from something like this.
Tree can grow and receive damage.
public class Tree {
private int lumber;
public Tree(int size) {
this.lumber = size;
}
public void grow() {
this.lumber++;
}
public void grow(int size) {
this.lumber += size;
}
public int receiveDamage(int damage) {
int lumber = 0;
if (damage > this.lumber) {
lumber = this.lumber;
this.lumber = 0;
} else {
lumber = damage;
this.lumber -= damage;
}
return lumber;
}
}
Food just stores nutritional value.
public class Food {
private int nutrition;
public Food(int nutrition) {
this.nutrition = nutrition;
}
public int getNutritionalValue() {
return this.nutrition;
}
}
I'm not sure if all types of player can chop trees, so I created a class to separate responsibilities. You can move methods to the Player class if you like.
public class Woodcutter extends Player {
public int chop(Tree tree) {
// lumber amount may depend on a tool,
// i.e. axe, chainsaw, etc.
return tree.receiveDamage(10);
}
// fell down the tree
public int fell(Tree tree) {
int result = 0;
int lumber = 0;
do {
lumber = chop(tree);
result += lumber;
} while (lumber > 0);
return result;
}
}
Somewhere in your code
// create a tree and let it grow for a while
Tree tree = new Tree(10);
tree.grow(90);
// Start chopping
Woodcutter woodcutter = new Woodcutter();
System.out.println("Lumber received: " + woodcutter.chop(tree));
System.out.println("Lumber received: " + woodcutter.fell(tree));
Dog dog = new Dog();
Food food = new Food(5);
woodcutter.feed(dog, food);
I wouldn't dive into passive/active methods here. An 'active tree' may indeed be a misnomer.
I would rather consider calling an object's method as passing a message to the object. And you apparently need to send the message to the tree that it is currently being cut by someone, and let the tree decide when to e.g. fall() or to bend(), or to shake().
The tree has some internal state (strength? thickness of its trunk? health?). 'Sending a message' to the tree means to call its method, e.g. beingCut(), which in turn deteriorates the state of the tree. After the state of the tree reaches a certain limit, other actions (=consequences of tree's bad state) may be started by the tree.
Of course, as in every iteration of your main loop you tree has also the chance to get the message to grow(), so its state may improve a little each time, so eventually it may even recover from being only partially cut and reach its initial, perfect state back.
So, yes, while trees seem rather passive, they still react to messages/stimulus. :-)

Depth First Search Issue

I'm currently learning algorithms and was trying to adapt some code from Algorithms by Robert Sedgewick. Here's a link to the part of the code I'm having problems with: http://algs4.cs.princeton.edu/44sp/DirectedCycle.java.html.
For my code the dependencies are a Vertex class with a constructor that just takes a vertex number. I also have a DirectedEdge class, that has a fromVertex, a toVertex and a weight. Finally, I have an EdgeWeightedDigraph class that has a list of the vertices within the graph and a DirectedEdge adjacency list that holds a list of the edges adjacent to a particular vertex and a test class that just initializes the various instances variables with the data in addition to executing the DirectedCycle.java program. The code compiles and runs but returns a wrong cycle using the data supplied by the book (http://algs4.cs.princeton.edu/42digraph/tinyDG.txt). The book specifies a Directed cycle: 3 5 4 3 but my code returns 3 2 3 instead. I noticed that the code runs fine until it encounters an already marked vertex and the onStack else-if code executes. For some reason the loop that contains the first call to dfs() iterates only once for index = 0 so after a marked vertex is encountered it does not retrace its steps and continue with the next vertex as it should with a depth first search. Not sure what I'm missing but any help will be appreciated. Please let me know if you need me to include the other code for the dependent classes listed above.
Here's my own code:
import java.util.Stack;
public class DirectedCycle {
private boolean[] marked;
private Vertex[] edgeTo;
private Stack<Vertex> cycle;
private boolean[] onStack;
public DirectedCycle(EdgeWeightedDigraph graph) {
onStack = new boolean[graph.getNumOfVertices()];
edgeTo = new Vertex[graph.getNumOfVertices()];
marked = new boolean[graph.getNumOfVertices()];
for (int index = 0; index < graph.getVertices().size(); index++) {
if (!marked[index] && cycle == null) {
dfs(graph, graph.getVertex(index));
}
}
}
private void dfs(EdgeWeightedDigraph graph, Vertex vertex) {
onStack[vertex.getVertexNumber()] = true;
marked[vertex.getVertexNumber()] = true;
for (DirectedEdge w : graph.adjacent(vertex)) {
if (this.hasCycle()) {
return;
}
else if (!marked[w.toVertex().getVertexNumber()]) {
edgeTo[w.toVertex().getVertexNumber()] = vertex;
dfs(graph, w.toVertex());
}
else if (onStack[w.toVertex().getVertexNumber()]) {
cycle = new Stack<>();
for (Vertex v = vertex;
v.getVertexNumber() != w.toVertex().getVertexNumber();
v = edgeTo[v.getVertexNumber()]) {
cycle.push(v);
}
cycle.push(w.toVertex());
cycle.push(vertex);
}
}
onStack[vertex.getVertexNumber()] = false;
}
public boolean hasCycle() {
return cycle != null;
}
public Iterable<Vertex> cycle() {
return cycle;
}
}

Good way to balance readability and performance of my code?

I am writing a Java program to do a simple math problem and I can't find a good way to get both code readability and performance :
Given a List of Node class and initial value of rank ( a double value with some mathematical meaning ) for each Node.
Calculate new rank for each node based on old rank value using some algorithm. Use the newly calculated rank value as old value and repeat the calculation process for multiple times.
// this code snippet is pseudo code and does not compile
class Node {
private int property1;
....
private int propertyN;
.... //getters and setters
}
List<Node> nodes;
Map<Node,Double> rankold;
Map<Node,Double> ranknew;
void doOneIteration() {
foreach (node in nodes) {
ranknew.put(node,someAlgorithm(rankold));
}
rankold = ranknew;
ranknew = {};
}
void doCalcuation(int times) {
nodes = [...];
rankold = {...};
ranknew = {};
while (times-->0) {
doOneIteration();
}
}
This code snippet are easiest to read. It separates rank logic from the node classes so it's easy to maintain.
The problem is about performance.
Creating HashMap and Double instances uses some extra CPU and Memory resources. and someAlgorithm() is simple but the number of Nodes is large.
And I wrote another version without using map:
class Node {
private int property1;
....
private int propertyN;
private double rank1;
private double rank2;
.... //getters and setters
}
List<Node> nodes;
boolean useRank1 = true;
void doOneIteration() {
if (useRank1 ) {
someAlgorithmUseRank1(nodes));
} else {
someAlgorithmUseRank2(nodes));
}
useRank1 = !useRank1;
}
This code snippet minimize memory usage but I will copy code of someAlgorithm() twice and if I made any change to someAlgorithm() there are two block of code to edit and I think this is "not elegant".
Here's a third code snippet I considered:
boolean useRank1 = true;
class Node {
private double rank1;
private double rank2;
double getRank() { if (useRank1) return rank1; else return rank2;}
void setRank(double r) { if (useRank1) rank2=r; else rank1=r;}
}
List<Node> nodes;
void doOneIteration() {
someAlgorithm(nodes);
useRank1 = !useRank1;
}
The problem is that the if branch in the getter and setter will be called multiple times which is not necessary. There is branch prediction and other many runtime optimizations in modern CPU and compilers but I am not sure how good will they work. Another concern is that this code snippet slightly increase the memory use of Node class since Node will have a pointer to the class holding useRank1 (although compared to object header one pointer is small)
The question is that is there good way to write "good" code for my problem? (good at CPU & Mem, and easy to read / maintain)

Make Logic in Function Recursive

Background: Imagine I have a little Robot. I place this Robot at some Node in a Map (Graph). The Robot can call the giveMeMapCopy() method to get a copy of the whole map that he is sat in. I want to give my little Robot a function by which he can use a breadth first traversal to find the shortest path to the Exit node. Here is an example of such a map:
I have watched videos on YouTube on how to do a breadth first traversal of a graph, so I have a good idea of what needs to be done. The problem is, I am finding it hard to make my logic recursive. Here is my code:
public class Robot
{
// fields required for traversal
private Queue<ArrayList<String>> queue;
private ArrayList<ArrayList<String>> result;
private String workingNode;
private ArrayList<String> routeSoFar;
private Queue<String> knownShortestPath;
public Robot() {
queue = new LinkedList<ArrayList<String>>();
result = new ArrayList<ArrayList<String>>();
routeSoFar = new ArrayList<String>();
knownShortestPath = new LinkedList<String>();
}
// Runs when Robot has reached a node.
public void enterNodeActions() {
knownShortestPath = determineIdealPath();
}
// Runs to determine where to go next
public String chooseNextNode() {
if(!knownShortestPath.isEmpty())
{
// TODO: Need to go through the
}
}
public LinkedList<String> determineIdealPath()
{
try {
// Get the map
Map m = giveMeMapCopy();
// Get all entry nodes of map
Set<String> entryNodes = m.getEntryNodes();
/*
* Loop through all Entry nodes, and find out where we are.
* Set that as current working node.
*/
for (String n : entryNodes) {
if(n == getMyLocation())
{
workingNode = n;
}
}
// All enighbours of working node.
Set<String> neighboursNames = getNeighboursNames(workingNode);
/*
* For each neighbour, construct a path from working node to the neighbour node
* And add path to Queue and Result (if not already present).
*/
for(String node : neighboursNames)
{
if(!node.equals(getMyLocation()))
{
ArrayList<String> route = new ArrayList<String>();
route.add(getMyLocation());
route.add(node);
if(!containsRoute(result, route))
{
if(!containsRoute(queue, route))
{
queue.add(route);
}
result.add(route);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Where I want the recursion to happen is after I have gone through all neighbours of the Entry node [ A ], I want to move to the next [ B ] and do the same for that, i.e. go through each of its neighbours (ignoring A, cause it is already present in Result list) and add them to the Queue and Result lists.
I hope the problem is clear, if not please let me know, and I'll try to clarify anything is not clear.
Breadth-first search is typically done without recursion as it is based on a queue (of partial path in your case). Depth-first search on the other hand is based on a stack, wich can be implemented quite naturally using the call-stack of a recursive function.
Essentially, what you want is to implement Dijkstra's algorithm or something similar to find the shortest path between a source and destination in a graph.
You can find such implementation in Java here. Just set all the weights at 1.

Categories