Package jsalis.framework

Source Code of jsalis.framework.Graph$Edge

/**
* Represents vertex and edge data.
*
*   @author John Salis
*/

package jsalis.framework;

import java.awt.Point;
import java.util.ArrayList;

public class Graph implements Searchable {

  private class Vertex {

    private int id;
    private Point position;

    private Vertex(int id, int x, int y) {
      this.id = id;
      this.position = new Point(x, y);
    }
  }

  private class Edge {

    private int a, b;
    private float weight;

    private Edge(int a, int b, float weight) {
      this.a = a;
      this.b = b;
      this.weight = weight;
    }
  }

  private ArrayList<Vertex> vertexList = new ArrayList<Vertex>();
  private ArrayList<Edge> edgeList = new ArrayList<Edge>();
  private Vertex start = new Vertex(0, 0, 0);
  private Vertex goal = new Vertex(0, 0, 0);


  public Graph() {
  }


  public void addVertex(int id, int x, int y) {
    vertexList.add(new Vertex(id, x, y));
  }


  public void addEdge(int a, int b, float weight) {
    edgeList.add(new Edge(a, b, weight));
  }


  public boolean testGoal(int state) {
    return goal.id == state;
  }


  public ArrayList<SearchAction> getSearchActions(int state) {
    ArrayList<SearchAction> actionList = new ArrayList<SearchAction>();
    for (Edge edge : edgeList) {
      if (edge.a == state) {
        actionList.add(new SearchAction(edge.b, edge.weight));
      }
      else if (edge.b == state) {
        actionList.add(new SearchAction(edge.a, edge.weight));
      }
    }
    return actionList;
  }


  public boolean setStart(int id) {
    for (Vertex v : vertexList) {
      if (v.id == id) {
        start = v;
        return true;
      }
    }
    return false;
  }


  public int getStart() {
    return start.id;
  }


  public boolean setGoal(int id) {
    for (Vertex v : vertexList) {
      if (v.id == id) {
        goal = v;
        return true;
      }
    }
    return false;
  }


  public int getGoal() {
    return goal.id;
  }


  public void print() {
    for (int i = 0; i < vertexList.size(); i++) {
      Vertex v = vertexList.get(i);
      System.out.println("Vertex\tID : " + v.id + "\tPosition : "
          + v.position);
    }
    for (int i = 0; i < edgeList.size(); i++) {
      Edge e = edgeList.get(i);
      System.out.println("Edge\tA : " + e.a + "\tB : " + e.b
          + "\tWeight : " + e.weight);
    }
  }


  public float estimateCostToGoal(int state) {
    Point current;
    for (Vertex v : vertexList) {
      if (v.id == state) {
        current = v.position;
        return (float) current.distance(goal.position);
      }
    }
    return Float.POSITIVE_INFINITY;
  }
}
TOP

Related Classes of jsalis.framework.Graph$Edge

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.