I have this Dijkstra algorithm java code below. I downloaded the code. I want to make changes to this program and store the data in file and read it in rather than put it in the source code. What would be the best ways to do this?
import java.util.PriorityQueue;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
class Vertex implements Comparable<Vertex>
{
public final String name;
public Edge[] adjacencies;
public double minDistance = Double.POSITIVE_INFINITY;
public Vertex previous;
public Vertex(String argName) {
name = argName;
}
public String toString() {
return name;
}
public int compareTo(Vertex other)
{
return Double.compare(minDistance, other.minDistance);
}
}
class Edge
{
public final Vertex target;
public final double weight;
public Edge(Vertex argTarget, double argWeight) {
target = argTarget;
weight = argWeight;
}
}
public class Dijkstra
{
public static void computePaths(Vertex source)
{
source.minDistance = 0.;
PriorityQueue<Vertex> vertexQueue = new PriorityQueue<Vertex>();
vertexQueue.add(source);
while (!vertexQueue.isEmpty()) {
Vertex u = vertexQueue.poll();
// Visit each edge exiting u
for (Edge e : u.adjacencies)
{
Vertex v = e.target;
double weight = e.weight;
double distanceThroughU = u.minDistance + weight;
if (distanceThroughU < v.minDistance) {
vertexQueue.remove(v);
v.minDistance = distanceThroughU ;
v.previous = u;
vertexQueue.add(v);
}
}
}
}
public static List<Vertex> getShortestPathTo(Vertex target)
{
List<Vertex> path = new ArrayList<Vertex>();
for (Vertex vertex = target; vertex != null; vertex = vertex.previous)
path.add(vertex);
Collections.reverse(path);
return path;
}
public static void main(String[] args)
{
Vertex v0 = new Vertex("Nottinghill_Gate");
Vertex v1 = new Vertex("High_Street_kensignton");
Vertex v2 = new Vertex("Glouchester_Road");
Vertex v3 = new Vertex("South_Kensignton");
Vertex v4 = new Vertex("Sloane_Square");
Vertex v5 = new Vertex("Victoria");
Vertex v6 = new Vertex("Westminster");
v0.adjacencies = new Edge[]{new Edge(v1, 79.83), new Edge(v6, 97.24)};
v1.adjacencies = new Edge[]{new Edge(v2, 39.42), new Edge(v0, 79.83)};
v2.adjacencies = new Edge[]{new Edge(v3, 38.65), new Edge(v1, 39.42)};
v3.adjacencies = new Edge[]{new Edge(v4, 102.53), new Edge(v2, 38.65)};
v4.adjacencies = new Edge[]{new Edge(v5, 133.04), new Edge(v3, 102.53)};
v5.adjacencies = new Edge[]{new Edge(v6, 81.77), new Edge(v4, 133.04)};
v6.adjacencies = new Edge[]{new Edge(v0, 97.24), new Edge(v5, 81.77)};
Vertex[] vertices = { v0, v1, v2, v3, v4, v5, v6 };
computePaths(v0);
for (Vertex v : vertices)
{
System.out.println("Distance to " + v + ": " + v.minDistance);
List<Vertex> path = getShortestPathTo(v);
System.out.println("Path: " + path);
}
}
}
The code is based on http://en.literateprograms.org/Special:Downloadcode/Dijkstra%27s_algorithm_%28Java%29 [last accessed on 6th January 2011]
I'd recommend describing your graph in Trivial Graph Format.
This is what it will look like:
v0 Harrisburg
v1 Baltimore
v2 Washington
v3 Philadelphia
v4 Binghamton
v5 Allentown
v6 New York
#
v0 v1 79.83
v0 v5 81.15
v1 v0 79.75
v1 v2 39.42
v1 v3 103.00
v2 v1 38.65
v3 v1 102.53
v3 v5 61.44
v3 v6 96.79
v4 v5 133.04
v5 v0 81.77
v5 v3 62.05
v5 v4 134.47
v5 v6 91.63
v6 v3 97.24
v6 v5 87.94
You can then parse this file and create the Vertex and Edge objects.
Here is the complete code:
class Vertex implements Comparable<Vertex> {
public final String name;
public List<Edge> adjacencies;
public double minDistance = Double.POSITIVE_INFINITY;
public Vertex previous;
public Vertex(String argName) {
name = argName;
adjacencies = new ArrayList<Edge>();
}
public void addEdge(Edge e) {
adjacencies.add(e);
}
public String toString() {
return name;
}
public int compareTo(Vertex other) {
return Double.compare(minDistance, other.minDistance);
}
}
class Edge {
public final Vertex target;
public final double weight;
public Edge(Vertex argTarget, double argWeight) {
target = argTarget;
weight = argWeight;
}
}
public class Dijkstra {
public static void computePaths(Vertex source) {
source.minDistance = 0.;
PriorityQueue<Vertex> vertexQueue = new PriorityQueue<Vertex>();
vertexQueue.add(source);
while (!vertexQueue.isEmpty()) {
Vertex u = vertexQueue.poll();
// Visit each edge exiting u
for (Edge e : u.adjacencies) {
Vertex v = e.target;
double weight = e.weight;
double distanceThroughU = u.minDistance + weight;
if (distanceThroughU < v.minDistance) {
vertexQueue.remove(v);
v.minDistance = distanceThroughU;
v.previous = u;
vertexQueue.add(v);
}
}
}
}
public static List<Vertex> getShortestPathTo(Vertex target) {
List<Vertex> path = new ArrayList<Vertex>();
for (Vertex vertex = target; vertex != null; vertex = vertex.previous)
path.add(vertex);
Collections.reverse(path);
return path;
}
public static void main(String args[]) {
Map<String, Vertex> vertexMap = new HashMap<String, Vertex>();
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader("graph.txt"));
String line;
boolean inVertex = true;
while ((line = in.readLine()) != null) {
if (line.charAt(0) == '#') {
inVertex = false;
continue;
}
if (inVertex) {
//store the vertices
int indexOfSpace = line.indexOf(' ');
String vertexId = line.substring(0, indexOfSpace);
String vertexName = line.substring(indexOfSpace + 1);
Vertex v = new Vertex(vertexName);
vertexMap.put(vertexId, v);
} else {
//store the edges
String[] parts = line.split(" ");
String vFrom = parts[0];
String vTo = parts[1];
double weight = Double.parseDouble(parts[2]);
Vertex v = vertexMap.get(vFrom);
if (v != null) {
v.addEdge(new Edge(vertexMap.get(vTo), weight));
}
}
}
} catch (IOException e) {
e.printStackTrace();
return;
}
finally{
if(in!= null)
try {
in.close();
} catch (IOException ignore) {
}
}
//get a list of all the vertices
Collection<Vertex> vertices = vertexMap.values();
Vertex source = vertices.iterator().next();
System.out.println("Computing paths from " + source);
computePaths(source);
for (Vertex v : vertices) {
System.out.println("Distance to " + v + ": " + v.minDistance);
List<Vertex> path = getShortestPathTo(v);
System.out.println("Path: " + path);
}
}
}
Basically you can store the data in the text file in a methodical manner, such as leave a space between every other data. Thereafter you can use the Java File Reader and read the contents of that file into an array. Once its in the array you can pass the array index into the respective places where the data has to be added in your code.
For example it would look similar to this, (here the String type array as is used to store the data from the text file. Therefore you can use its indexes to add the data to your code.
FileInputStream fileinputstream = new FileInputStream("FileName.txt");
DataInputStream datainputstream = new DataInputStream(fileinputstream);
BufferedReader bufferedreader1 = new BufferedReader(new InputStreamReader(datainputstream));
do{
String s1;
if((s1 = bufferedreader1.readLine()) == null){
break;
}
String as[] = s1.split(" ");
} while(true);
datainputstream.close();
}
Related
I was trying to build innerbuffers . My task is it to make buffer from polygon so small that the new buffers were maximal 5% of the original size of the polygon but never 0!
I was trying something like that:
public Point getInnerBufferCentroid(MapContent mapContent) throws Exception {
JLabel label = new JLabel("Wählen Sie einen Layer aus:");
List<Layer> layerList = mapContent.layers();
String[] layerNames = new String[layerList.size()];
for (int i = 0; i < layerList.size(); i++) {
layerNames[i] = layerList.get(i).getFeatureSource().getName().toString();
}
String selectedLayer = (String) JOptionPane.showInputDialog(null, label,
"Layerauswahl", JOptionPane.QUESTION_MESSAGE, null, layerNames, layerNames[0]);
FeatureLayer selectedFeatureLayer = null;
for (Layer layer : layerList) {
if (layer.getFeatureSource().getName().toString().equals(selectedLayer)) {
selectedFeatureLayer = (FeatureLayer) layer;
break;
}
}
SimpleFeatureSource featureSource = (SimpleFeatureSource)
selectedFeatureLayer.getFeatureSource();
SimpleFeatureCollection featureCollection = featureSource.getFeatures();
SimpleFeatureIterator featureIterator = featureCollection.features();
SimpleFeature feature = featureIterator.next();
Geometry geometry = (Geometry) feature.getDefaultGeometry();
double originalArea = geometry.getArea();
double bufferArea = originalArea;
Geometry buffer = geometry.buffer(0);
while (bufferArea >= originalArea * 0.05 && bufferArea > 0) {
buffer = buffer.buffer(-1);
bufferArea = buffer.getArea();
}
Point centroid;
if (buffer instanceof Polygon) {
centroid = ((Polygon) buffer).getInteriorPoint();
} else {
MultiPolygon multiPolygon = (MultiPolygon) buffer;
int numGeometries = multiPolygon.getNumGeometries();
Polygon largestPolygon = null;
double largestArea = 0;
for (int i = 0; i < numGeometries; i++) {
Polygon polygon = (Polygon) multiPolygon.getGeometryN(i);
double area = polygon.getArea();
if (area > largestArea) {
largestArea = area;
largestPolygon = polygon;
}
}
centroid = largestPolygon.getCentroid();
}
return centroid;
}
but getInteriorPoint() and geCEntroid aren't existing. Did someone know a other strategy?
So I am making a "game" with LWJGL, and I started loading 3D Models (Using Wavefront .obj files). I have successfully loaded the model, but instead of having textures, I wanted to try out the .mtl files, to specify the materials. I "sort of" made it, but it seems to be not completely working. Here is my code, and a picture of the Tree model I tried to render:
Tree Model
Now here is my code:
private static OBJMesh mesh;
public static Mesh load3DModel(String objFileName)
{
mesh = new OBJMesh();
BufferedReader reader = null;
try
{
reader = new BufferedReader(new FileReader(new File(objFileName)));
}
catch (FileNotFoundException e)
{
System.err.println("Could not locate OBJ File at " + objFileName);
e.printStackTrace();
}
String mtlFileName = null;
String line = null;
String currentFaceMat = null;
try
{
while ((line = reader.readLine()) != null)
{
String[] lineParts = line.split(" ");
switch (line.substring(0, 2))
{
case "v ":
Vertex v = new Vertex(lineParts[1], lineParts[2], lineParts[3]);
mesh.addVertex(v);
break;
case "vn":
Normal n = new Normal(lineParts[1], lineParts[2], lineParts[3]);
mesh.addNormal(n);
break;
case "mt":
mtlFileName = FileHelper.getDirectory(objFileName) + lineParts[1];
break;
case "us":
currentFaceMat = lineParts[1];
break;
case "f ":
Face face = createFace(currentFaceMat, lineParts);
mesh.addFace(face);
break;
}
}
reader = new BufferedReader(new FileReader(mtlFileName));
Material mat = null;
while ((line = reader.readLine()) != null)
{
String[] lineParts = line.split(" ");
if (line.length() > 1)
{
switch (line.substring(0, 2))
{
case "ne":
mat = new Material(lineParts[1]);
mesh.addMaterial(lineParts[1], mat);
break;
case "Ka":
mat.setKa(createVector(lineParts));
break;
case "Kd":
mat.setKd(createVector(lineParts));
break;
case "Ks":
mat.setKs(createVector(lineParts));
break;
case "Ns":
mat.setNs(Float.parseFloat(lineParts[1]));
break;
case "d ":
mat.setD(Float.parseFloat(lineParts[1]));
break;
case "il":
mat.setIllum(Integer.parseInt(lineParts[1]));
break;
}
}
}
reader.close();
}
catch (IOException e)
{
e.printStackTrace();
}
mesh.normalArray = new float[mesh.vertices.size() * 3];
for (Face face : mesh.faces)
{
decodeNormals(face.indices1);
decodeNormals(face.indices2);
decodeNormals(face.indices3);
}
mesh.vertexArray = new float[mesh.vertices.size() * 3];
mesh.indexArray = new int[mesh.indices.size() * 3];
mesh.colorArray = new float[mesh.faces.size() * 3];
int vertexPointer = 0;
for (Vertex vertex : mesh.vertices)
{
mesh.vertexArray[vertexPointer++] = vertex.x;
mesh.vertexArray[vertexPointer++] = vertex.y;
mesh.vertexArray[vertexPointer++] = vertex.z;
}
for (int i = 0; i < mesh.indices.size(); i++)
{
mesh.indexArray[i] = mesh.indices.get(i);
}
int colorPointer = 0;
for (Face face : mesh.faces)
{
mesh.colorArray[colorPointer++] = mesh.materials.get(face.material).Kd.x;
mesh.colorArray[colorPointer++] = mesh.materials.get(face.material).Kd.y;
mesh.colorArray[colorPointer++] = mesh.materials.get(face.material).Kd.z;
}
return MeshLoader.genVertexModel(mesh.vertexArray, mesh.indexArray, mesh.colorArray);
}
private static Face createFace(String materialName, String[] lineData)
{
String[] indices1 = General.replaceEmptySlashes(lineData[1]).split("/");
String[] indices2 = General.replaceEmptySlashes(lineData[2]).split("/");
String[] indices3 = General.replaceEmptySlashes(lineData[3]).split("/");
return new Face(materialName, indices1, indices2, indices3);
}
private static Vector3f createVector(String[] lineData)
{
float x = Float.parseFloat(lineData[1]);
float y = Float.parseFloat(lineData[2]);
float z = Float.parseFloat(lineData[3]);
return new Vector3f(x, y, z);
}
private static void decodeNormals(Vector3f vertex)
{
int vertexPointer = (int) vertex.x - 1;
mesh.indices.add(vertexPointer);
Normal normal = mesh.normals.get((int) vertex.z - 1);
mesh.normalArray[vertexPointer * 3] = normal.x;
mesh.normalArray[vertexPointer * 3 + 1] = normal.y;
mesh.normalArray[vertexPointer * 3 + 2] = normal.z;
}
The OBJMesh class:
public List<Vertex> vertices = new ArrayList<Vertex>();
public List<Normal> normals = new ArrayList<Normal>();
public List<Integer> indices = new ArrayList<Integer>();
public List<Face> faces = new ArrayList<Face>();
public Map<String, Material> materials = new HashMap<String, Material>();
public float[] vertexArray;
public float[] normalArray;
public float[] colorArray;
public int[] indexArray;
public void addVertex(Vertex vertex)
{
vertices.add(vertex);
}
public void addNormal(Normal normal)
{
normals.add(normal);
}
public void addMaterial(String name, Material material)
{
materials.put(name, material);
}
public void addFace(Face face)
{
faces.add(face);
}
The Face class:
public Vector3f indices1;
public Vector3f indices2;
public Vector3f indices3;
public String material;
public Face(String material, String[] v1, String[] v2, String[] v3)
{
this.material = material;
this.indices1 = new Vector3f(Float.parseFloat(v1[0]), Float.parseFloat(v1[1]), Float.parseFloat(v1[2]));
this.indices2 = new Vector3f(Float.parseFloat(v2[0]), Float.parseFloat(v2[1]), Float.parseFloat(v2[2]));
this.indices3 = new Vector3f(Float.parseFloat(v3[0]), Float.parseFloat(v3[1]), Float.parseFloat(v3[2]));
}
The Material class just contains RGB values.
If you could find something, let me know; I have been searching for weeks (No joke!). Thank you
OpenGL expects all vertex attributes to be, well, per-vertex. The way you are at the moment populating your colorArray suggests you are only doing this per-face. Change this and it should give the correct results.
I'm trying to iterate through a HashMap contain ArrayLists of Directed Edges, for a Edgeweighted Directed Graph. I've followed instructions from similar questions, but it's not working correctly.
I want to:
Iterate through the HashMap, retrieve each ArrayList.
Then iterate through the directedEdges in the ArrayList.
Print out the Directed Edge, which has the following toString method:
public String toString(){
return String.format("%s->%s %d", v, w, weight);
}
Below full EdgeDirectedGraph class, toString method I'm querying is at the bottom.
import java.util.*;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class EdgeWeightedDiGraph{
private static final String NEWLINE = System.getProperty("line.separator");
private int V;
private int E;
private HashMap<String, ArrayList<DirectedEdge>> adjacencyList;
public EdgeWeightedDiGraph(String filename, String delim){
BufferedReader br = null;
try{
br = new BufferedReader(new FileReader(filename));
E = 0;
V = Integer.parseInt(br.readLine());
//System.out.println(V);
String line = null;
this.adjacencyList = new HashMap<String, ArrayList<DirectedEdge>>();
while ((line = br.readLine()) != null) {
//adj = (Bag<Integer>[]) new Bag[V];
String arr[] = line.split(delim); // properties
String v = arr[0];
String w = arr[1];
int e = Integer.parseInt(arr[2]);
DirectedEdge dEdge = new DirectedEdge(v, w, e);
addEdge(dEdge);
System.out.println(dEdge.from()+dEdge.to()+dEdge.weight());
}
}
catch (FileNotFoundException ex) {
System.out.println("Error: File not found");
Logger.getLogger(EdgeWeightedDiGraph.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IOException ex) {
Logger.getLogger(EdgeWeightedDiGraph.class.getName()).log(Level.SEVERE, null, ex);
}
finally{
try {
br.close();
}
catch (IOException ex) {
Logger.getLogger(EdgeWeightedDiGraph.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public HashMap getMap(){
return adjacencyList;
}
public int V(){
return V;
}
public int E(){
return E;
}
public void addEdge(DirectedEdge e)
{
String v = e.from();
String w = e.to();
ArrayList<DirectedEdge> item = new ArrayList<DirectedEdge>();
item.add(e);
adjacencyList.put(v, item);
System.out.println(v+item);
E++;
}
public Iterable<DirectedEdge> adjacencyList(String v){
return adjacencyList.get(v);
}
public Iterable<DirectedEdge> edges()
{
public String toString() {
StringBuilder s = new StringBuilder();
s.append(V + " " + E + NEWLINE);
for (HashMap.Entry<String, ArrayList<DirectedEdge>> entry : adjacencyList.entrySet()){
ArrayList<DirectedEdge> arrList = entry.getValue();
for(DirectedEdge e : arrList){
s.append(e + " "); }
s.append(NEWLINE);
}
return s.toString();
}
}
Below is the output:
I can see that the Directed Edges are being added to the graph, but only half are printing out in the toString() method.
Print out of edges being added
A[A->B 5]
AB5,
B[B->C 4]
BC4,
C[C->D 8]
CD8,
D[D->C 8]
DC8,
D[D->E 6]
DE6 ,
A[A->D 5]
AD5,
C[C->E 2]
CE2,
E[E->B 3]
EB3,
A[A->E 7]
AE7
"toString() output : A->E 7 B->C 4 C->E 2 D->E 6 E->B 3 "
The issue is you are always creating a new DirectedEdge list when you add and edge instead of using the existing list if it exists.
public void addEdge(DirectedEdge e)
{
String v = e.from();
String w = e.to();
// Check if there is already an edge array
ArrayList<DirectedEdge> item = adjacencyList.get(v);
if(item == null) {
// Does not exist, create it
item = new ArrayList<DirectedEdge>();
}
item.add(e);
adjacencyList.put(v, item);
System.out.println(v+item);
}
I found Dijkstra's Algorithm from internet (here the original code) , and I try to use multiple source instead multiple destination. But when I run the code, output isn't right, it just shows first vertex for all output.
import java.util.PriorityQueue;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
class Vertex implements Comparable<Vertex> {
public final String name;
public Edge[] adjacencies;
public double minDistance = Double.POSITIVE_INFINITY;
public Vertex previous;
public Vertex(String argName) { name = argName; }
public String toString() { return name; }
public int compareTo(Vertex other) {
return Double.compare(minDistance, other.minDistance);
}
}
class Edge {
public final Vertex target;
public final double weight;
public Edge(Vertex argTarget, double argWeight) {
target = argTarget;
weight = argWeight;
}
}
public class tes_dijkstra {
public static void computePaths(Vertex source) {
source.minDistance = 0.;
PriorityQueue<Vertex> vertexQueue = new PriorityQueue<Vertex>();
vertexQueue.add(source);
while (!vertexQueue.isEmpty()) {
Vertex u = vertexQueue.poll();
// Visit each edge exiting u
for (Edge e : u.adjacencies) {
Vertex v = e.target;
double weight = e.weight;
double distanceThroughU = u.minDistance + weight;
if (distanceThroughU < v.minDistance) {
vertexQueue.remove(v);
v.minDistance = distanceThroughU ;
v.previous = u;
vertexQueue.add(v);
}
}
}
}
public static List<Vertex> getShortestPathTo(Vertex target) {
List<Vertex> path = new ArrayList<Vertex>();
for (Vertex vertex = target; vertex != null; vertex = vertex.previous)
path.add(vertex);
Collections.reverse(path);
return path;
}
public static void main(String[] args) {
Vertex v0 = new Vertex("Redvile");
Vertex v1 = new Vertex("Blueville");
Vertex v2 = new Vertex("Greenville");
Vertex v3 = new Vertex("Orangeville");
Vertex v4 = new Vertex("Purpleville");
v0.adjacencies = new Edge[]{ new Edge(v1, 5),
new Edge(v2, 10),
new Edge(v3, 8) };
v1.adjacencies = new Edge[]{ new Edge(v0, 5),
new Edge(v2, 3),
new Edge(v4, 7) };
v2.adjacencies = new Edge[]{ new Edge(v0, 10),
new Edge(v1, 3) };
v3.adjacencies = new Edge[]{ new Edge(v0, 8),
new Edge(v4, 2) };
v4.adjacencies = new Edge[]{ new Edge(v1, 7),
new Edge(v3, 2) };
Vertex[] start = { v1, v2, v3, v4 };
Vertex[] end ={v2};
for (int i = 0; i < start.length; i++){
for(int j = 0; j < end.length; j++){
computePaths(start[i]);
System.out.println("Distance to " + end[j] + ": " + end[j].minDistance);
List<Vertex> path = getShortestPathTo(end[j]);
System.out.println("Path: " + path);
}
}
}
}
and this is how the output looks like :
Distance to Greenville: 3.0
Path: [Blueville, Greenville]
Distance to Greenville: 0.0
Path: [Blueville, Greenville]
Distance to Greenville: 0.0
Path: [Blueville, Greenville]
Distance to Greenville: 0.0
Path: [Blueville, Greenville]
The output just shows first vertex from Vertex[] start (v1 = Blueville) for all output.
I don't know where is wrong, is path stored somewhere? I kinda new in java and I want to learn this algorithm for my assignment, so please help. Thank you
Yes the vertices store information about the cost and the path that is constructed. The problem is not that much that the path itself is constructed but the minDistance is the distance from a given start vertex. You can implement a method reset in the Vertex class
void reset () {
this.minDistance = Double.POSITIVE_INFINITY;
}
And furthermore you need to reset all vertices of the graph when you want to perform the next Dijkstra's algorithm:
public static List<Vertex> getShortestPathTo(Vertex target) {
List<Vertex> path = new ArrayList<Vertex>();
for (Vertex vertex = target; vertex != null; vertex = vertex.previous)
path.add(vertex);
Collections.reverse(path);
return path;
}
public static void main(String[] args) {
Vertex v0 = new Vertex("Redvile");
Vertex v1 = new Vertex("Blueville");
Vertex v2 = new Vertex("Greenville");
Vertex v3 = new Vertex("Orangeville");
Vertex v4 = new Vertex("Purpleville");
v0.adjacencies = new Edge[]{ new Edge(v1, 5),
new Edge(v2, 10),
new Edge(v3, 8) };
v1.adjacencies = new Edge[]{ new Edge(v0, 5),
new Edge(v2, 3),
new Edge(v4, 7) };
v2.adjacencies = new Edge[]{ new Edge(v0, 10),
new Edge(v1, 3) };
v3.adjacencies = new Edge[]{ new Edge(v0, 8),
new Edge(v4, 2) };
v4.adjacencies = new Edge[]{ new Edge(v1, 7),
new Edge(v3, 2) };
Vertex[] start = { v1, v2, v3, v4 };
Vertex[] end = {v2};
Vertex[] all = {v0, v1, v2, v3, v4};
for (int i = 0; i < start.length; i++){
for(int j = 0; j < end.length; j++){
computePaths(start[i]);
System.out.println("Distance to " + end[j] + ": " + end[j].minDistance);
List<Vertex> path = getShortestPathTo(end[j]);
System.out.println("Path: " + path);
}
//a new start vertex: reset the graph
for(Vertex v : all) {
v.reset();
}
}
}
EDIT: I have posted it earlier for java. But it working in Java but not in android. So I am posting the android code now.
I am trying to use a custom class into a HashMap in my android application. But it is not giving my desired output. Please help.
I want to do something like this...
//Code for android application:
//Point class
class Point{
private int x;
private int y;
public Point(){
}
public Point(int _x, int _y){
this.x = _x;
this.y = _y;
}
}
DataManager.java
public class DataManager {
private Vector<Integer> RSSI = null;
private int numOfRSSI;
private Map<Vector<Integer>, Point> SingleData = null;
private Vector<Map<Vector<Integer>, Point>> Data = null;
private Context context;
public DataManager(Context _context) {
this.context = _context;
Data = new Vector<Map<Vector<Integer>, Point>>();
}
public void loadData(String filename) {
if (Data == null) {
System.out.println("***ERROR: DataSet not initalized!!!\n");
}
readFile(filename);
}
public void printData(){
Vector<Integer> rssi = null;
Map<Vector<Integer>, Point> single = null;
Point point = null;
for(int i=0;i<Data.size();i++){
single = new HashMap<Vector<Integer>, Point>() ;
single = Data.get(0);
for (Map.Entry<Vector<Integer>, Point> entry :single.entrySet()) {
rssi = new Vector<Integer>();
point = new Point();
rssi = entry.getKey();
point = entry.getValue();
System.out.print("("+point.x+" "+point.y+") ");
for(int j = 0;j<rssi.size(); j++){
System.out.print(rssi.get(j)+" ");
}
System.out.println("");
}
}
}
private void readFile(String filename) {
InputStream is = null;
try {
is = context.getResources().getAssets().open("datasets.txt");
} catch (IOException e) {
e.printStackTrace();
System.out.println("error file reading");
}
if (is != null) {
StringBuilder text = new StringBuilder();
int flag = 0;
try {
BufferedReader br = new BufferedReader(
new InputStreamReader(is));
String line;
while ((line = br.readLine()) != null) {
if(flag==0){
flag=1;
this.numOfRSSI = Integer.parseInt(line);
System.out.println("number of RSSI: "+numOfRSSI);
}
else if(flag==1){
parseLine(line);
}
}
} catch (IOException e) {
// Error reading file
}
finally {
// myHelper.print(text.toString());
}
}
}
private void parseLine(String line) {
RSSI = new Vector<Integer>();
SingleData = new HashMap<Vector<Integer>, Point>();
StringTokenizer st = new StringTokenizer(line, ",");
int co = 0;
int x=0,y=0;
while (st.hasMoreTokens()) {
if(co < this.numOfRSSI){
RSSI.add(Integer.parseInt(st.nextToken()));
co++;
}
else{
x = Integer.parseInt(st.nextToken());
y = Integer.parseInt(st.nextToken());
}
}
Point point = new Point(x,y);
SingleData.put(RSSI, point);
Data.add(SingleData);
}
}
MainActivity.java
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
DataManager dataManager = new DataManager(MainActivity.this);
dataManager.loadData("datasets.txt");
dataManager.printData();
}
}
datasets.txt
5
-61,-51,-46,-41,-28,1,0
-60,-50,-51,-47,-34,2,0
-72,-52,-53,-55,-37,3,0
-60,-44,-58,-53,-40,3,1
-68,-55,-46,-47,-45,2,1
-66,-60,-48,-43,-37,1,1
-62,-57,-49,-45,-34,0,2
Output is showing.....
1 0 -61 -51 -46 -41-28
1 0 -60 -50 -51 -47 -34
1 0 -72 -52 -53 -55 -37
etc.....
But it should be...
1 0 -61 -51 -46 -41-28
2 0 -60 -50 -51 -47 -34
etc...
So this is my problem.
Below is working fine on my machine :-
import java.util.Map;
import java.util.Vector;
public class Demo {
public static void main(String[] args) {
Map<Vector<Integer>, Point> vectorPointMap = new HashMap<Vector<Integer>, Point>();
Vector<Integer> vector1 = new Vector<Integer>();
vector1.add(1);
vector1.add(2);
vector1.add(3);
vectorPointMap.put(vector1, new Point(10, 10));
Vector<Integer> vector2 = new Vector<Integer>();
vector2.add(4);
vector2.add(5);
vector2.add(6);
vectorPointMap.put(vector2, new Point(20, 20));
// Print data
for (Map.Entry<Vector<Integer>, Point> entry : vectorPointMap.entrySet()) {
Vector<Integer> keyVector = entry.getKey();
Point valuePoint = entry.getValue();
System.out.print("(" + valuePoint.x + " " + valuePoint.y + ") ");
for (int j = 0; j < keyVector.size(); j++) {
System.out.print(keyVector.get(j) + " ");
}
System.out.println("");
}
}
}
You should change this from
for(int i=0;i<Data.size();i++){
single = new HashMap<Vector<Integer>, Point>() ;
single = Data.get(0);
}
to
for(int i=0;i<Data.size();i++){
single = new HashMap<Vector<Integer>, Point>() ;
single = Data.get(i);
}
try changing:
single = Data.get(0);
to
single = Data.get(i);
What does it mean, "it does not give right"?
You can put your own classes to Map, there is no problem. But remember, when you put items to HashMap in some order, there is no guarantee, it will come out in the same order. If you need to have same order on output, as on input, instead HashMap use LinkedHashMap. You can use it in the same way as HashMap, but it preserves order of inserted items.