311 SWDA1
Code
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class tour implements ActionListener {
protected JPanel CONTAINER;
protected JPanel container;//top level container
protected JPanel inputArea;
protected JPanel inputAreaA;
protected JTextField input1;
protected JTextField input2;
protected JLabel label1;
protected JLabel label2;
protected JButton button1;
protected JTextField input3;
protected JLabel label3;//starting time label
protected JPanel listArea;
protected DefaultListModel listM;
protected JList list;
protected JLabel pickDes;
protected JScrollPane scroll;
protected JButton button2;
protected JPanel displayArea;
protected JTextPane display;
protected JScrollPane result;
protected JScrollPane scroll2;
public tour(){
container = new JPanel();
container.setLayout(new BorderLayout());
//code for inputArea-----------------------------------------
inputArea = new JPanel();
inputArea.setLayout(new BoxLayout(inputArea, BoxLayout.Y_AXIS));
inputAreaA = new JPanel();
inputAreaA.setLayout(new BorderLayout());
input1 = new JTextField();
input1.setText("http://pearl.ics.hawaii.edu/~sugihara/courses/ics311s13/assign_p1_test_data/digraph01.txt");
input1.addActionListener(this);
input2 = new JTextField();
input2.setText("http://pearl.ics.hawaii.edu/~sugihara/courses/ics311s13/assign_p1_test_data/attractions01.txt");
input2.addActionListener(this);
input3 = new JTextField();
input3.setText("9:45:00");
label1 = new JLabel("Please enter graph url here. ");
label2 = new JLabel("Please enter attraction url here. ");
label3 = new JLabel("Start Time");
button1 = new JButton("Show Destinations");
//button1.setEnabled(false);
button1.addActionListener(this);
inputArea.add(label1);
inputArea.add(input1);
inputArea.add(label2);
inputArea.add(input2);
inputAreaA.add(button1,BorderLayout.LINE_START);
inputAreaA.add(input3, BorderLayout.CENTER);
inputAreaA.add(label3, BorderLayout.LINE_END);
inputArea.add(inputAreaA);
//add inputArea to container
container.add(inputArea, BorderLayout.PAGE_START);
//code for checkbox area-------------------------------------
listArea = new JPanel();
listArea.setLayout(new BorderLayout());
listM = new DefaultListModel();
list = new JList(listM);
list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
scroll = new JScrollPane(list);
pickDes = new JLabel();//Should say pick destination from below after link enter'd
button2 = new JButton("Get my schedule!");
button2.addActionListener(this);
//button2.setEnabled(false);
listArea.add(pickDes, BorderLayout.PAGE_START);
listArea.add(scroll, BorderLayout.CENTER);
listArea.add(button2,BorderLayout.PAGE_END);
container.add(listArea, BorderLayout.CENTER);
//code for result area--------------------------------------
displayArea = new JPanel();
displayArea.setLayout(new BorderLayout());
display = new JTextPane();
scroll2 = new JScrollPane(display);
displayArea.add(scroll2, BorderLayout.CENTER);
//container.add(displayArea, BorderLayout.PAGE_END);
CONTAINER = new JPanel();
CONTAINER.setLayout(new BorderLayout());
CONTAINER.add(container, BorderLayout.LINE_START);
CONTAINER.add(displayArea, BorderLayout.CENTER);
}
public void actionPerformed(ActionEvent ae){
try{
ArrayList<Destination> destinations = new ArrayList<Destination>();;
//----------------action event handler when "Enter" is clicked--------------
if((ae.getSource() == input1) || (ae.getSource() == input2) ){
button1.setEnabled(true);
}
if (ae.getSource() == button1){
display.setText("");
listM.clear();
urlValidate url1v = new urlValidate(input1.getText());
urlValidate url2v = new urlValidate(input2.getText());
if(!url1v.isVal() || !url2v.isVal()){
JOptionPane.showMessageDialog(null, "You've entered an invalid url, please try again.");
}
else{
//first sanitize the 2 urls then extract destination strings from url2
url1v.sanitize();
url2v.sanitize();
ArrayList<String> data = new ArrayList<String>();
data = url2v.getData();
//get the destination string from data and add to destinations
for(int x = 1; x<data.size(); x++){
Destination des = new Destination(data.get(x));
destinations.add(des);
}
//populate list with destination
for(int x = 0; x<destinations.size(); x++){
listM.addElement(destinations.get(x));
}
}
}
//If Get my Schedule button is clicked...
if(ae.getSource() == button2){
urlValidate url1v = new urlValidate(input1.getText());
urlValidate url2v = new urlValidate(input2.getText());
if(!url1v.isVal() || !url2v.isVal()){
JOptionPane.showMessageDialog(null, "Error: Invalid URL(s)");
}
else{
url1v.sanitize();
url2v.sanitize();
ArrayList<String> data = new ArrayList<String>();
data = url2v.getData();
for(int x = 1; x<data.size(); x++){
Destination des = new Destination(data.get(x));
destinations.add(des);
}
ArrayList<Destination> DSelection = new ArrayList<Destination>();
int[] index;
index = list.getSelectedIndices();
if(index.length ==0){
return;
}
for(int x = 0;x<index.length; x++){
Destination d = destinations.get(index[x]);
System.out.println(index[x]);
DSelection.add(d);
}
RoadMap map = new RoadMap(url1v.toString());
BruteForce alg = new BruteForce(map, url2v.toString(), input3.getText(), DSelection);
alg.Optimize();
alg.CalcBestRoute();
if(DSelection.size()>1){
if((alg.TourDuration(alg.bestroute, false)) > 24*3600){
display.setText("Sorry, you can not schedule all the destination you selected into one day."
+"\nPlease reduce the number of selections, try a different combination of" +
" \ndestinations, or set an earlier starting time.");
}
else{
display.setText(alg.content.toString());
}
}
else{
display.setText(alg.content.toString());
}
}
}
}catch(Exception e){
JOptionPane.showMessageDialog(null, "Error: " + e);
}
}
}
Code
import java.util.*;
public class RoadMap{
private int numVertex;
private int[][] matrix;
protected ArrayList<String> data;
protected String[] tokens;
/*
* Constructor for RoadMap that creates a 2d array and loads it with the
* edge values given in the page.
*/
public RoadMap(String url)throws Exception
{
urlValidate val = new urlValidate(url);
val.sanitize();
data = new ArrayList<String>();
data = val.getData();
/*
* After data has the string representation of the page, each line of the page is processed
* by looping through data
*/
for(int x =0; x<data.size();x++){
String delim = "\\t{1,}";
//reads the number of vertices in the first line and makes appropriate sized array.
if(x == 0){
tokens = ((String) data.get(x)).split(delim);
matrix = new int[Integer.parseInt(tokens[0])][Integer.parseInt(tokens[0])];
numVertex = Integer.parseInt(tokens[0]);
for(int i=0;i<Integer.parseInt(tokens[0]);i++){
for(int j=0;j<Integer.parseInt(tokens[0]);j++){
if(j == i){
matrix[i][j] = 0;
}
else{
matrix[i][j] = 99999;
}
}
}
}
else{
//
String[] tokens2 = ((String) data.get(x)).split(delim);
//takes the value of first/second number as the value of matrix being referenced, insert third number
matrix[Integer.parseInt(tokens2[0])-1][Integer.parseInt(tokens2[1])-1] = convertTime(tokens2[2]);
}
}
}
public void Print()
{
for(int x = 0; x < Integer.parseInt(tokens[0]);x++){
for(int y = 0;y < Integer.parseInt(tokens[0]); y++){
if(this.matrix[x][y] <10){
System.out.print("0000" + this.matrix[x][y] + " ");
}
else if(this.matrix[x][y] <100){
System.out.print("000" + this.matrix[x][y] + " ");
}
else if(this.matrix[x][y] <1000){
System.out.print("00" + this.matrix[x][y] + " ");
}
else if(this.matrix[x][y] <10000){
System.out.print("0" + this.matrix[x][y] + " ");
}
else{
System.out.print(this.matrix[x][y] + " ");
}
}
System.out.println();
}
}
public int GetDistanceFrom(int start, int finish)
{
return this.matrix[start][finish];
}
public int[][] getMatrix(){
return this.matrix;
}
public static int convertTime(String input){
String delim = ":";
String[] timeToken = input.split(delim);
return 3600 * Integer.parseInt(timeToken[0]) + 60 * Integer.parseInt(timeToken[1]) + Integer.parseInt(timeToken[2]);
}
}
Code
import org.apache.commons.validator.UrlValidator;
import java.net.*;
import java.util.*;
import java.io.*;
public class urlValidate {
private String url;
private ArrayList<String> data;
/*
* Constructor method that takes a url string as parameter
*/
public urlValidate(String input){
this.url = input;
}
/*
* checks if this.url is valid using apache validator
*/
@SuppressWarnings("deprecation")
public boolean isVal(){
UrlValidator urlValidator = new UrlValidator();
if(urlValidator.isValid(url)){
return true;
}
else{
return false;
}
}
/*
* Sanitizes the string this.url
*/
public void sanitize(){
try{
URL x = new URL(url);
URI aURI = new URI(x.getProtocol(), x.getUserInfo(), x.getHost(), x.getPort(), x.getPath(), x.getQuery(), "");
url = aURI.toURL().toString();
}catch(MalformedURLException e){
System.out.println("bad url");
}catch(URISyntaxException e){
System.out.println("bad uri");
}
}
/*
* Returns an arraylist containing the data from the website.
*/
public ArrayList<String> getData(){
try{
this.data = new ArrayList<String>();
URL aUrl = new URL(this.url);
BufferedReader in = new BufferedReader(new InputStreamReader(aUrl.openStream()));
String inputLine;
while((inputLine = in.readLine())!=null){
data.add(inputLine);
}
in.close();
return data;
} catch(IOException e){
return null;
}
}
public String toString(){
return url;
}
}
Code
import java.util.*;
public class BruteForce {
public class Road
{
public Destination from;
public Destination to;
};
protected RoadMap mymap;
int startTime;
ArrayList<Road> bestroute;
ArrayList<Destination> destinationList;
StringBuilder content;
/*
* takes roadmap, destination url address, starting time as string
*/
public BruteForce(RoadMap map, String destinationURL, String tourS, ArrayList<Destination> D)throws Exception
{
//to hold the data from destination url
ArrayList<String> data = new ArrayList<String>();
startTime = convertTime(tourS);
mymap = map;
bestroute = new ArrayList<Road>();
//create a new urlValidate object with the destination url, get the data arrayList
urlValidate desURL = new urlValidate(destinationURL);
desURL.sanitize();
data = desURL.getData();
this.destinationList = D;
//int zzz = convertTime(data.get(3));
/*
destinationList = new ArrayList<Destination>();
for(int x = 0; x < data.size(); x++){
if(x > 0){
Destination des = new Destination(data.get(x));
destinationList.add(des);
}
}
*/
//destinationList.remove(0);
//destinationList.remove(destinationList.size()-1);
//destinationList.remove(destinationList.size()-2);
//destinationList.remove(destinationList.size()-3);
}
public void Optimize(){
//outer loop 1 iteration per line to cover whole matrix
for(int x =0; x < mymap.getMatrix().length; x++){
shortestPath me = new shortestPath(mymap.getMatrix(),x);
me.getShortestPath();
for(int i = 0; i< mymap.getMatrix().length; i++){
for(int j = 0; j< mymap.getMatrix().length; j++){
if(i == x){
mymap.getMatrix()[i][j] = me.sValues[j];
}
}
}
}
}
public boolean CalcBestRoute()
{
if(destinationList.size()<2){
tourDuration();
}
else{
ArrayList<Road> route = new ArrayList<Road>();
TryRoutes(route);
}
return true;
}
public void PrintN()
{
PrintNUM(this.bestroute);
}
public void PrintNUM(ArrayList<Road> route)
{
if(TourDuration(bestroute, false)> 3600 * 24){
System.out.println("Really Sorry, you can not schedual all the destination you selected into one day."
+"\nPlease reduce the number of selections or try a different combination of destinations.");
}
else{
System.out.println("Route Distance: "+TourDuration(route, false));
System.out.println("=======================================================");
this.TourDuration(route, true);
}
}
private int TryRoutes(ArrayList<Road> route)
{
//when route<> has number of destinations in RoadMap, check if bestroute
if (route.size()== destinationList.size()-1)
{
//Print(route);
if (IsBestRoute(route)==true)
{
bestroute=route;
}
}
else
{
//loop from 0 to total number vertices
for(int i=0;i< destinationList.size();i+=1)
{
Road nextroad = new Road();
//set the starting location to 0 if this list of route<> is empty
if (route.isEmpty()==true){
for(int x = 0; x < destinationList.size();x++){
nextroad.from = destinationList.get(x);
nextroad.to = destinationList.get(i);
//make sure we visit new cities only
}
}
//-----------------------------
else{
Road lastroad = route.get(route.size()-1);
nextroad.from = lastroad.to;
nextroad.to = destinationList.get(i);
//make sure we visit new cities only
}
if (nextroad.to == nextroad.from)
{
continue;
}
if (isOnRoute(route, nextroad.to))
{
continue;
}
ArrayList<Road>testroute = new ArrayList<Road>(route);
testroute.add(nextroad);
TryRoutes(testroute);
}
}
return 0;
}
private boolean IsBestRoute(ArrayList<Road> route)
{
if ( TourDuration(this.bestroute, false) > TourDuration(route, false) )
{
return true;
}
else
{
return false;
}
}
public int TourDuration(ArrayList<Road> route, boolean print){
//store the tour as string inside content
content = new StringBuilder("");
if (route.isEmpty()==true)
{
return java.lang.Integer.MAX_VALUE;
}
int currentT = startTime;
for(int x = 0; x<route.size(); x++){
Road road = route.get(x);
if(x == 0){
if(print){
System.out.println("Starting time : " + convertTime(currentT));
}
content.append("Starting time : " + convertTime(currentT) + " .\n");
}
//For the first road, process both road.from/road.to, for rest process only road.to
if(x == 0){
Destination des = road.from;
if(des.inTimeSlot(currentT, currentT + des.getDuration())){
currentT += des.getDuration();
if(print){
System.out.println("Stay at " + road.from.toString() + " from "+ (convertTime(currentT - des.getDuration()))+ "-"+convertTime(currentT));
}
content.append("Stay at " + road.from.toString() + " from "+ (convertTime(currentT - des.getDuration()))+ "-"+convertTime(currentT)+ ".\n");
}
else{
ArrayList<Integer> tSlots = des.getTimePoints();
for(int t = 0; t < tSlots.size(); t+=2){
if(tSlots.get(t) >= currentT){
currentT = tSlots.get(t) + des.getDuration();
if(print){
System.out.println("Stay at " + road.from.toString() + " from " + (convertTime(currentT - des.getDuration()))+ "-"+convertTime(currentT));
}
content.append("Stay at " + road.from.toString() + " from " + (convertTime(currentT - des.getDuration()))+ "-"+convertTime(currentT) + ".\n");
break;
}
}
}
}
if(print){
System.out.println(convertTime(currentT)+" is current time, " +convertTime(mymap.GetDistanceFrom(road.from.getLocation(), road.to.getLocation()))+" to travel to next des..");
}
content.append(convertTime(currentT)+" is current time, " +convertTime(mymap.GetDistanceFrom(road.from.getLocation(), road.to.getLocation()))+" to travel to next destination. \n");
currentT+= mymap.GetDistanceFrom(road.from.getLocation(), road.to.getLocation());
if(print){
System.out.println("Arrive at " + road.to.toString()+" at " + convertTime(currentT));
}
content.append("Arrive at " + road.to.toString()+" at " + convertTime(currentT) + ".\n");
Destination dest = road.to;
if(dest.inTimeSlot(currentT, currentT + dest.getDuration())){
currentT += dest.getDuration();
if(print){
System.out.println("Stay at " + road.to.toString() + " from " + convertTime((currentT - dest.getDuration()))+ "-"+convertTime(currentT));
}
content.append("Stay at " + road.to.toString() + " from " + convertTime((currentT - dest.getDuration()))+ "-"+convertTime(currentT)+".\n");
}
else{
boolean mark = false;
ArrayList<Integer> tSlots = dest.getTimePoints();
for(int t = 0; t < tSlots.size(); t+=2){
if(tSlots.get(t) >= currentT){
currentT = tSlots.get(t) + dest.getDuration();
mark = true;
if(print){
System.out.println("Stay at " + road.to.toString() + " from "+ convertTime(currentT - dest.getDuration())+ "-"+convertTime(currentT));
}
content.append("Stay at " + road.to.toString() + " from "+ convertTime(currentT - dest.getDuration())+ "-"+convertTime(currentT)+".\n");
break;
}
}
if(!mark){
currentT += 99999;
}
}
}
if(print){
System.out.println("ENDING TIME: " + convertTime(currentT)+".");
//System.out.println("TOTAL TIME OF TOUR IS " + convertTime(currentT - startTime));
System.out.println("TOTAL TIME OF TOUR IS " + currentT + ".");
}
content.append("ENDING TIME: " + convertTime(currentT)+"\n");
content.append("TOTAL TIME OF TOUR IS " + convertTime(currentT - startTime)+".\n");
return currentT;
}
public void tourDuration(){
int currentT = startTime;
content = new StringBuilder();
Destination DES = destinationList.get(0);
content.append("Starting time: " + convertTime(currentT)+"\n");
if(DES.inTimeSlot(currentT, currentT + DES.getDuration())){
content.append("Stay at "+DES+" from " + convertTime(currentT)+"-"+convertTime(currentT + DES.getDuration())+"\n");
currentT+= DES.getDuration();
}
else{
ArrayList<Integer> tSlots = DES.getTimePoints();
for(int t = 0; t < tSlots.size(); t+=2){
if(tSlots.get(t) >= currentT){
content.append("Stay at " + DES + " from " + (convertTime(tSlots.get(t))+ "-"+convertTime(tSlots.get(t)+DES.getDuration()) + ".\n"));
currentT = tSlots.get(t) + DES.getDuration();
break;
}
}
}
content.append("ENDING TIME: " + convertTime(currentT)+"\n");
content.append("TOTAL TIME OF TOUR IS " + convertTime(currentT - startTime)+".\n");
}
private boolean isOnRoute(ArrayList<Road> route, Destination city)
{
for(int i=0;i<route.size();i+=1)
{
Road road = route.get(i);
if (road.from==city || road.to==city)
{
return true;
}
}
return false;
}
public static int convertTime(String input){
String delim = ":";
String[] timeToken = input.split(delim);
return 3600 * Integer.parseInt(timeToken[0]) + 60 * Integer.parseInt(timeToken[1]) + Integer.parseInt(timeToken[2]);
}
public static String convertTime(int input){
int hour;
int minute;
int second;
int left;
if(input > 3600){
hour = input / 3600;
left = input % 3600;
minute = left / 60;
left = left % 60;
second = left;
}
else if(input > 60){
hour = 0;
minute = input / 60;
second = input % 60;
}
else{
hour = 0;
minute = 0;
second = input;
}
String min = Integer.toString(minute);
String sec = Integer.toString(second);
if(minute < 10){
min = '0' + min;
}
if(second < 10){
sec = '0' + sec;
}
return "" + hour + ":" + min + ":" + sec;
}
}
Code
/*
* An implementation of Dijstra's algorithm.
*
*/
public class shortestPath {
private int[][] map;
int[] sValues;
boolean[] cChecked;
boolean[] rChecked;
private int origin;
private int x;
public shortestPath(int[][] me, int start){
x = 0;
this.map = me;
this.origin = start;
sValues = new int[me.length];
cChecked = new boolean[me.length];
rChecked = new boolean[me.length];
rChecked[origin] = true;
cChecked[origin] = true;
for(int x = 0; x < sValues.length; x++){
if(x != start)
sValues[x] = 99999;
}
}
/*
* Takes an input target, finds lowest value in target row, save that
* value into sValues, recursively calls getShortestPath with new target rows
*
*/
public void getShortestPath(){
if( x > map.length){
return;
}
else{
int lowest = Integer.MAX_VALUE;
//loop through the array to find the target row
for(int x = 0; x < map.length; x++){
for(int y = 0; y < map.length; y++){
//if current row is marked true in rChecked
if(rChecked[x] == true){
//make sure it's not counting the path to itself
if((x != y) && (cChecked[y] == false)){
//if current item < lowest value, set it to lowest value
if(map[x][y] + sValues[x] < lowest){
lowest = map[x][y] + sValues[x];
}
}
}
}
}
//check all columns that have lowest value
for(int x = 0; x < map.length; x++){
for(int y = 0; y < map.length; y++){
if( (lowest == map[x][y] + sValues[x]) && (cChecked[y] == false) ){
rChecked[y] = true;
cChecked[y] = true;
sValues[y] = map[x][y] + sValues[x];
}
}
}
/*
System.out.println("UPDATED cCHecked---");
for(boolean a : cChecked){
System.out.print(a + " ");
}
*/
x++;
getShortestPath();
}
}
public void Print(){
System.out.println();
for(int me : sValues){
System.out.print(me + " ");
}
}
}
Code
import java.util.*;
public class Destination {
private int location;
private String name;
private String delim = "\\t{1,}";
private String[] tokens;
private String[] timeOpen;
private ArrayList<Integer> timePoints;
int start;
int finish;
/*
* constructor that takes line of txt file as input
* @param line the input line to be processed
*/
public Destination(String line){
tokens = line.split(delim);
}
public String getName(){
this.name = tokens[1];
return name;
}
public int getLocation(){
this.location = Integer.parseInt(tokens[0]);
return location - 1;
}
public int getDuration(){
return convertTime(tokens[2]);
}
public void setTime(int s, int f){
this.start = s;
this.finish = f;
}
public int getStart(){
return start;
}
public int getFinish(){
return finish;
}
public ArrayList<Integer> getTimePoints(){
timePoints = new ArrayList<Integer>();
for(int x = 3; x < tokens.length; x++){
timeOpen = tokens[x].split("-");
for(int z = 0; z < timeOpen.length; z++){
timePoints.add(convertTime(timeOpen[z]));
}
}
return timePoints;
}
public boolean inTimeSlot(int sTime, int eTime){
boolean me = false;
this.getTimePoints();
//System.out.println(timePoints.toString());
for(int a = 0; a < timePoints.size(); a+=2){
if((sTime >= timePoints.get(a)) && (eTime <= timePoints.get(a+1))){
me = true;
}
}
return me;
}
public String toString(){
return this.getName();
}
public static int convertTime(String input){
String delim = ":";
String[] timeToken = input.split(delim);
return 3600 * Integer.parseInt(timeToken[0]) + 60 * Integer.parseInt(timeToken[1]) + Integer.parseInt(timeToken[2]);
}
}
Code
import java.awt.Dimension;
import javax.swing.*;
public class SWDA1 {
/**
* @param args
*/
public static void main(String[] args) {
JFrame frame = new JFrame("Tour Schedule");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(1000, 700));
tour app = new tour();
frame.setContentPane(app.CONTAINER);
frame.pack();
frame.setVisible(true);
}
}