I am trying to write a piece of Java code which can deduce a 1D integer array from a 2D integer array. My 2D array looks something like this:
Node1 Node2 Path
6 8 501
2 6 500
8 10 505
2 4 502
And my task is as follows. I want to find “Path”s from elements of the first column (Node 1) to the elements of the second column (Node2). I mean something like these:
Path from “2” to “8” would be 500 501 in that order. And path from “2” to “4” would be 502 (not 500 since it terminates at “6”)
I have been trying to achieve this by iterating with simple for loop but have been struggling. Could someone please let me know how I can solve this?
The code snippet which I am trying to write to achieve is this:
PathSequence:
for(int i = 0; i < PathGraphRow; i++){
if(PathGraph[i][0] == source){
if(i==0)
{
nextNode = PathGraph[i][1];
resultantPaths[counter] = PathGraph[i][2];
prev = lightPathGraph[i][2];
if(nextNode == dest){
break PathSequence;
}
counter++;
}else if(i > 0 && prev != PathGraph[i][2])
{
nextNode = PathGraph[i][1];
resultantPaths[counter] = PathGraph[i][2];
prev = PathGraph[i][2];
if(nextNode == dest){
break PathSequence;
}
counter++;
}
}
if(nextNode == PathGraph[i][0] && prev != PathGraph[i][2]){
nextNode = PathGraph[i][1];
resultantPaths[counter] = PathGraph[i][2];
prev = PathGraph[i][2];
if(nextNode == dest){
break PathSequence;
}
counter++;
}
if(i == PathGraphRow-1 && PathGraph[i][2] != resultantPaths[counter]){
if(PathGraph[i][1] != dest){
resultantPaths = new int[PathCount];
}
}
}
}
Thank you.
Regards
Unless I’m overlooking some details the problem is fairly trivial without the sub paths. You just need a single for loop that is very specific.
That is of course pseudo code, but that’s basically how I would do it. I would make each path a three tuple. I still don’t quite get how you intend to store the data, if you put all the values in a 1D int array, how do you know where a path starts and ends? Assuming all paths are defined by a start, end, and result that would work in a 1D array although it would be worse to use than the 2D array. If paths are of arbitrary length there’s no way to store the data in a 1D array. Anyways, here’s code to put the table provided in a 1D array (assuming no greater complexity);
Then to access the array you need to do a bunch of mod 3 crap to know which value you’re getting…