I have an algorithm problem with recursion:
i have a route from A to D and it looks like this
[A, B, C, D]
the alphabet in the above list is an object of a class, lets call that class Nodes
each of this Nodes object they have some attributes... these are of type set..
the first set will store a bunch of other Nodes (these represent the current nodes neighbour)
the second set will store a bunch of tracks (Integer object representing what tracks the current nodes belong to)
(... bare with me here... )
so now i write up some code that initialise all the nodes... and here is the output...
A: [B, Z, E] // A's next neighbour
A: [2, 1, 3] // A belongs to these tracks
B: [C, A]
B: [1]
C: [B, D]
C: [4, 1]
D: [F, C]
D: [4]
and here is the code: (i removed the System.out... to shorten the code..)
public class Path {
private Nodes a, b, c, d, e, f, z;
private List path = new ArrayList();
public Path() {
a = new Nodes("A"); //used nodes
b = new Nodes("B"); //used nodes
c = new Nodes("C"); //used nodes
d = new Nodes("D"); //used nodes
e = new Nodes("E"); // wont be used directly
f = new Nodes("F"); // wont be used directly
z = new Nodes("Z"); // wont be used directly
path.add(a);
path.add(b);
path.add(c);
path.add(d);
// setting Nodes a
a.getNext().add(b);
a.getNext().add(e);
a.getNext().add(z);
Integer[] iA = {1, 2, 3};
a.getTrackID().addAll(Arrays.asList(iA));
// setting Nodes b
b.getNext().add(a);
b.getNext().add(c);
b.getTrackID().add(Integer.valueOf(1));
// setting Nodes c
c.getNext().add(b);
c.getNext().add(d);
c.getTrackID().add(Integer.valueOf(1));
c.getTrackID().add(Integer.valueOf(4));
// setting Nodes d
d.getNext().add(c);
d.getNext().add(f);
d.getTrackID().add(Integer.valueOf(4));
}
public static void main(String[] args) { new Path();}
}
class Nodes{
private Set next = new HashSet();
private Set trackID = new HashSet();
private String name = "";
Nodes(String name){ this.name = name;}
public Set getNext() { return next;}
public Set getTrackID() { return trackID;}
public String toString() {return this.name;}
}
what i want to do is to come up with some recursive algorithm so that it would print out something like this...
Path = A - B - C - D
A to C track 1
C to D track 4
so i've come up with a pseudo code...
method1(Node startNode, List path){
iterate through startNode.getNext set
if nodes return is in the list path{
newNodes = returned nodes;
path.remove(startNodes);
if(startNodes.getTrack() == newNodes.getTrack())
{ // if startNodes shares the same track as the next nodes
then line = the track;
method1(newNodes, path);
}else{
print startNode "to" newNodes "track" line
if there is still some journey
method(newNodes, path)
}
}
}
i've also come up with an actuall code but for some reason it'll only prints out the first step...
the code for this to follow...