Java Code To Run A Complex Store Calculation
Java Code To Run A Complex Store Calculation
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to
change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this
template
*/
/**
*
* azuka bee
*/
//This is a greedy incomplete (does not find solution for all types of connected
graphs)
import java.util.*;
public class ShortestPathGreedy {
public static int N = 5;
public static int adjInfoAll[][] = new int[N][N];// Storing Adjacency Info for
all cities
public static int weightToSource[]= new int[N],pathCost=0;// Storing Adjacency
Info for all cities
static int parents[] = new int[N];
public static class Node
{
int weightInfo[] = new int[N],id;// storing adjacency info for a node
(city)
int adjInfo[] = new int[N];// storing adjacency info for a node (city)
int parent;// storing parent of node
char status;//w (white) new or g (grey) processed
}
public static int getDistance(int id){
return weightToSource[id];
}
// Method for allocating a new node
public static Node newNode(int id,int parent){
return node1;
}
//For a connected Graph, starting from s=0
public static void shortestPaths(int adjInfoAll[][],int s){
int count=0;
Node start = newNode(s,-1);
//start.parent=-1;
parents[start.id]=-1;//This node has no parent
Node min1=start;
int smallId=0,small=100;//10000 is infinite here
System.out.println("The path is: (Path Cost is in bracket)");
System.out.print(start.id+" ->");
while(true){
if(min1.id==start.id)
weightToSource[min1.id]=0;
min1.status='g';
for(int j=0;j<5;j++){
if(adjInfoAll[min1.id][j]!=0&&adjInfoAll[min1.id]
[j]<small&&parents[j]==-2){
small=adjInfoAll[min1.id][j];
smallId=j;
}
}
Node BestFringe = newNode(smallId,min1.id);
parents[smallId]=min1.id;
weightToSource[BestFringe.id]=pathCost+adjInfoAll[min1.id]
[BestFringe.id];
pathCost+=adjInfoAll[min1.id][BestFringe.id];
if(BestFringe.id==4){//Goal node is reached
System.out.print(BestFringe.id+" ( "+pathCost+" )");
break;
}
else
System.out.print(BestFringe.id+" ( "+pathCost+" )->");
min1=BestFringe;
if(++count==15){
System.out.println("Limit of search reached, either no route or bad
path used");
break;
}
}
}
public static void main(String args[]){
for(int j=0;j<5;j++)
parents[j]=-2;//Meaning the node has not been seen yet.
/* Node 0(A) connects to Node 1(B) with a cost of 2
Node 0(A) connects to Node 2(C) with a cost of 3
Node 0(A) connects to Node 3(D) with a cost of 4
Node 1(B) connects to Node 4(E) with a cost of 1
Node 2(C) connects to Node 4(E) with a cost of 2
Node 3(D) connects to Node 4(E) with a cost of 6
*/
int initialM[][] =
{
{0, 2, 3, 4, 100},
{2, 0, 100, 100, 1},
{3, 100, 0, 100, 2},
{4, 100, 100, 0, 6},
{100, 1, 2, 6, 0}
};
for(int i=0;i<5;i++)
for(int j=0;j<5;j++)
adjInfoAll[i][j]=initialM[i][j];
//If you want a different start and end nodes, then rearrange the id with
start node 0 and end node n-1
shortestPaths(adjInfoAll,0);
}