// Option 7
 public void addRoute(String c1, String c2, int distance, double price) {
   if (c1.equals(c2) || distance < 0 || price < 0) {
     System.out.println("Invalid route info");
     return;
   }
   City city1 = null;
   City city2 = null;
   for (int i = 0; i < numCities; i++) {
     if (cities[i].name().equals(c1)) {
       city1 = cities[i];
     }
     if (cities[i].name().equals(c2)) {
       city2 = cities[i];
     }
   }
   if (city1 == null || city2 == null) {
     System.out.println("Invalid city choice(s)");
     return;
   }
   Route r = new Route(city1, city2, distance, price);
   routes.add(r);
   adj[city1.id() - 1].add(r);
   adj[city2.id() - 1].add(r);
   numRoutes++;
 }
  ///// ACCESSORS/////
  public double distance(City cityIn) {
    double changeInX = X - cityIn.getX();
    double changeInY = Y - cityIn.getY();
    double xDistanceSquared = (changeInX * changeInX) + (changeInY * changeInY);
    double xDistance = Math.sqrt(xDistanceSquared);

    return xDistance;
  }
 public City interpret() {
   City resultingCity = new City("Nowhere", 999.9, 999.9);
   for (Expression currentExpression : this.expressions) {
     City currentCity = currentExpression.interpret();
     if (currentCity.getLatitude() < resultingCity.getLatitude()) {
       resultingCity = currentCity;
     }
   }
   return resultingCity;
 }
 // relax edge e and update pq if changed
 private void relaxC(Route r, int v) {
   City city2 = r.other(cities[v]);
   int w = city2.id() - 1;
   if (costTo[w] > costTo[v] + r.price()) {
     costTo[w] = costTo[v] + r.price();
     edgeTo[w] = r;
     if (costPQ.contains(w)) costPQ.change(w, costTo[w]);
     else costPQ.insert(w, costTo[w]);
   }
 }
 private void relaxD(Route r, int v) {
   // relax edge e and update pq if changed
   City city2 = r.other(cities[v]);
   int w = city2.id() - 1;
   if (distTo[w] > distTo[v] + r.distance()) {
     distTo[w] = distTo[v] + r.distance();
     edgeTo[w] = r;
     if (pq.contains(w)) pq.change(w, distTo[w]);
     else pq.insert(w, distTo[w]);
   }
 }
 public City interpret() {
   //	System.out.println("procesando no oeste");
   City resultingCity = new City("Nowhere", 999.9, 999.9);
   for (Expression currentExpression : expressions) {
     City currentCity = currentExpression.interpret();
     if (currentCity.getLongitude() < resultingCity.getLongitude()) {
       resultingCity = currentCity;
     }
   }
   System.out.println(resultingCity.getName());
   return resultingCity;
 }
 public void removeRoute(City city1, City city2) {
   Route route = null;
   for (Route r : adj[city1.id() - 1]) {
     if (r.other(city1).equals(city2)) {
       route = r;
       break;
     }
   }
   adj[city1.id() - 1].remove(route);
   adj[city2.id() - 1].remove(route);
   routes.remove(route);
   numRoutes--;
 }
 // Option 5
 public void shortestByHops(String c1, String c2) {
   System.out.println("FEWEST HOPS from " + c1 + " to " + c2);
   System.out.println("---------------------------------------------");
   City city1 = null;
   City city2 = null;
   for (int i = 0; i < numCities; i++) {
     if (cities[i].name().equals(c1)) {
       city1 = cities[i];
     }
     if (cities[i].name().equals(c2)) {
       city2 = cities[i];
     }
   }
   if (c1.equals(c2) || city1 == null || city2 == null) {
     System.out.println("Invalid city choice(s)");
     return;
   }
   marked = new boolean[numCities];
   distTo = new int[numCities];
   edgeTo = new Route[numCities];
   for (int i = 0; i < numCities; i++) distTo[i] = Integer.MAX_VALUE;
   bfs(city1.id() - 1);
   if (distTo[city2.id() - 1] == Integer.MAX_VALUE) {
     System.out.println("No path");
     return;
   }
   System.out.printf("Fewest hops from %s to %s is %d\n", c1, c2, distTo[city2.id() - 1]);
   City currCity = city2;
   for (Route r = edgeTo[city2.id() - 1]; r != null; r = edgeTo[currCity.id() - 1]) {
     System.out.print(currCity + " ");
     currCity = r.other(currCity);
   }
   System.out.println(currCity);
 }
 // Option 10
 public void removeCity(String c) {
   City city = null;
   for (int i = 0; i < numCities; i++) {
     if (cities[i].name().equals(c)) {
       city = cities[i];
     }
   }
   if (city == null) {
     System.out.println("Invalid city choice");
     return;
   }
   // Remove all routes connected to the city
   for (Route r : adj[city.id() - 1]) {
     City other = r.other(city);
     adj[other.id() - 1].remove(r);
     routes.remove(r);
     numRoutes--;
   }
   cities[city.id() - 1] = null;
   adj[city.id() - 1] = null;
   numCities--;
   // Shift and resize arrays as necessary
   shiftCities(city.id() - 1);
   shiftAdj(city.id() - 1);
   if (numCities < cities.length / 2) { // halve the lengths of the arrays
     resizeCities(cities.length / 2);
     resizeAdj(cities.length / 2);
   }
 }
  private void createEdges() {
    City c1, c2;

    for (int i = 0; i < allCities.size(); i++) {
      for (int j = 0; j < allCities.size(); j++) {
        if (i == j) continue;

        c1 = allCities.get(i);
        c2 = allCities.get(j);

        c1.addCityToMap(c2);
        c2.addCityToMap(c1);

        // System.out.println("c1 " + c1.getName() + " , c2 " + c2.getName() + " dist : " +
        // c1.getdMap().get(c2));
      }
    }
    sortEdges(allCities);
  }
Exemple #11
0
 public static void computePaths(City source) {
   source.minDistance = 0.;
   PriorityQueue<City> cityQueue = new PriorityQueue<City>();
   cityQueue.add(source);
   while (!cityQueue.isEmpty()) {
     City u = cityQueue.poll();
     // Visit each edge exiting u
     for (Route e : u.neighbours) {
       City v = e.target;
       double weight = e.weight;
       double distanceThroughU = u.minDistance + weight;
       if (distanceThroughU < v.minDistance) {
         cityQueue.remove(v);
         v.minDistance = distanceThroughU;
         v.previous = u;
         cityQueue.add(v);
       }
     }
   }
 }
Exemple #12
0
 // Option 4
 public void shortestByCost(String c1, String c2) {
   System.out.println("SHORTEST COST PATH from " + c1 + " to " + c2);
   System.out.println("--------------------------------------------------------");
   City city1 = null;
   City city2 = null;
   for (int i = 0; i < numCities; i++) {
     if (cities[i].name().equals(c1)) {
       city1 = cities[i];
     }
     if (cities[i].name().equals(c2)) {
       city2 = cities[i];
     }
   }
   if (c1.equals(c2) || city1 == null || city2 == null) {
     System.out.println("Invalid city choice(s)");
     return;
   }
   costTo = new double[numCities];
   edgeTo = new Route[numCities];
   for (int i = 0; i < numCities; i++) costTo[i] = Double.POSITIVE_INFINITY;
   costTo[city1.id() - 1] = 0;
   // relax vertices in order of distance from s
   costPQ = new IndexMinPQ<Double>(numCities);
   costPQ.insert(city1.id() - 1, costTo[city1.id() - 1]);
   while (!costPQ.isEmpty()) {
     int v = costPQ.delMin();
     for (Route r : adj[v]) relaxC(r, v);
   }
   if (costTo[city2.id() - 1] == Double.POSITIVE_INFINITY) {
     System.out.println("No path");
     return;
   }
   System.out.printf("Shortest cost from %s to %s is %.2f\n", c1, c2, costTo[city2.id() - 1]);
   System.out.println("Path with edges (in reverse order):");
   City currCity = city2;
   for (Route r = edgeTo[city2.id() - 1]; r != null; r = edgeTo[currCity.id() - 1]) {
     System.out.print(currCity + " " + r.price() + " ");
     currCity = r.other(currCity);
   }
   System.out.println(currCity);
 }
Exemple #13
0
 // Option 3
 public void shortestByDistance(String c1, String c2) {
   System.out.println("SHORTEST DISTANCE PATH from " + c1 + " to " + c2);
   System.out.println("--------------------------------------------------------");
   City city1 = null;
   City city2 = null;
   for (int i = 0; i < numCities; i++) {
     if (cities[i].name().equals(c1)) {
       city1 = cities[i];
     }
     if (cities[i].name().equals(c2)) {
       city2 = cities[i];
     }
   }
   if (c1.equals(c2) || city1 == null || city2 == null) {
     System.out.println("Invalid city choice(s)");
     return;
   }
   distTo = new int[numCities];
   edgeTo = new Route[numCities];
   for (int i = 0; i < numCities; i++) distTo[i] = Integer.MAX_VALUE;
   distTo[city1.id() - 1] = 0;
   // relax vertices in order of distance from s
   pq = new IndexMinPQ<Integer>(numCities);
   pq.insert(city1.id() - 1, distTo[city1.id() - 1]);
   while (!pq.isEmpty()) {
     int v = pq.delMin();
     for (Route r : adj[v]) relaxD(r, v);
   }
   if (distTo[city2.id() - 1] == Integer.MAX_VALUE) {
     System.out.println("No path");
     return;
   }
   System.out.printf("Shortest distance from %s to %s is %d\n", c1, c2, distTo[city2.id() - 1]);
   System.out.println("Path with edges (in reverse order):");
   City currCity = city2;
   for (Route r = edgeTo[city2.id() - 1]; r != null; r = edgeTo[currCity.id() - 1]) {
     System.out.print(currCity + " " + r.distance() + " ");
     currCity = r.other(currCity);
   }
   System.out.println(currCity);
 }
  @RequestMapping(
      value = "/getCityApi",
      method = {RequestMethod.GET, RequestMethod.POST})
  public String getCityApi(
      HttpServletRequest request,
      @RequestParam(value = "locationname") String locationname,
      ModelMap model) {

    Map<Object, Object> map = new HashMap<Object, Object>();
    JSONArray jSONArray = new JSONArray();
    try {
      String status = "active";
      List<City> cityList = cityService.getCityApi(locationname, status);
      if (cityList != null && cityList.size() > 0) {
        for (int i = 0; i < cityList.size(); i++) {
          City city = (City) cityList.get(i);
          String cityName = (String) city.getCity();
          String stateName = (String) city.getState();

          int ID = (Integer) (city.getId());
          JSONObject jSONObject = new JSONObject();

          jSONObject.put("id", ID);
          jSONObject.put("text", cityName);
          jSONArray.put(jSONObject);
        }
        utilities.setSuccessResponse(response, jSONArray.toString());
      } else {
        throw new ConstException(ConstException.ERR_CODE_NO_DATA, ConstException.ERR_MSG_NO_DATA);
      }
    } catch (Exception ex) {
      logger.error("getCity :" + ex.getMessage());
      utilities.setErrResponse(ex, response);
    }
    model.addAttribute("model", jSONArray.toString());
    return "home";
  }
Exemple #15
0
  public static void main(String[] args) {
    City a = new City("A");
    City b = new City("B");
    City c = new City("C");
    City d = new City("D");
    City e = new City("E");
    a.neighbours = new Vector<Route>();
    a.neighbours.add(new Route(b, 5));
    a.neighbours.add(new Route(d, 5));
    a.neighbours.add(new Route(e, 7));
    b.neighbours = new Vector<Route>();
    b.neighbours.add(new Route(c, 4));
    c.neighbours = new Vector<Route>();
    c.neighbours.add(new Route(d, 8));
    c.neighbours.add(new Route(e, 2));
    d.neighbours = new Vector<Route>();
    d.neighbours.add(new Route(c, 8));
    d.neighbours.add(new Route(e, 6));
    e.neighbours = new Vector<Route>();
    e.neighbours.add(new Route(b, 3));

    City[] vertices = {a, b, c, d, e};
    HashMap<String, City> edges = new HashMap<String, City>();
    for (City _city : vertices) {
      edges.put(_city.name, _city);
    }
    String[] cities = new String[vertices.length];
    for (int i = 0; i < vertices.length; i++) {
      cities[i] = vertices[i].name;
    }

    computePaths(a);
    /**
     * for (City v : vertices) { System.out.println("Distance to " + v + ": " + v.minDistance);
     * List<City> path = getShortestPathTo(v); System.out.println("Path: " + path); }
     */
    Scanner scanner = new Scanner(System.in);
    String input = null;
    String[] inputsplit = null;
    while (true) {
      input = scanner.next();
      if (input.equalsIgnoreCase("quit")) {
        break;
      }
      inputsplit = input.split("-");
      Trip trip = new Trip();
      Route lastvisited = trip.route.lastElement();
      for (String str : inputsplit) {
        System.out.print(str + ' ');
        City city;
        if (edges.containsKey(str)) {
          city = edges.get(str);
        } else {
          System.out.println("NO SUCH City"); // TODO change name
          break;
        }

        if (trip.route == null) {
          trip.addRoute(edges.get(city.name));
        }

        System.out.println(trip.toString());
      }
      System.out.println(trip.distance);
    }
  }
Exemple #16
0
 private void recPaths(double maxCost, double currCost, City currCity) {
   // Backtrack if above max cost
   if (currCost > maxCost) {
     marked[currCity.id() - 1] = false;
     return;
   }
   // Print current path before continuing along routes
   if (edgeTo[currCity.id() - 1] != null) {
     System.out.printf("Cost: %.0f Path (reversed): ", currCost);
     City temp = currCity;
     for (Route r = edgeTo[temp.id() - 1]; r != null; r = edgeTo[temp.id() - 1]) {
       System.out.printf("%s %.0f ", temp, r.price());
       temp = r.other(temp);
     }
     System.out.println(temp);
   }
   // Recursion
   marked[currCity.id() - 1] = true;
   for (Route r : adj[currCity.id() - 1]) {
     City other = r.other(currCity);
     // Don't follow route if other city already in path
     if (!marked[other.id() - 1]) {
       edgeTo[other.id() - 1] = r;
       recPaths(maxCost, currCost + r.price(), other);
     }
   }
   // traversed all paths from currCity, backtrack to previous city
   marked[currCity.id() - 1] = false;
 }
Exemple #17
0
  public synchronized void paint(Graphics graphics) {

    Graphics2D g = (Graphics2D) graphics;

    Image water = Toolkit.getDefaultToolkit().getImage("catanui/water.jpg");
    g.drawImage(water, 0, 0, this);

    for (Hex o : _hexes) {
      o.paint(g, _display_offset[0], _display_offset[1]);
    }

    g.translate(_display_offset[0] + 2, _display_offset[1] - 1);
    synchronized (portContents) {
      for (Pair c : portContents.keySet()) {

        int lowx =
            hexleft
                + (((CoordPair) c.getA()).getX() - (((CoordPair) c.getA()).getX() % 2))
                    / 2
                    * intervalSide[0]
                + (((CoordPair) c.getA()).getX() - (((CoordPair) c.getA()).getX() % 2))
                    / 2
                    * intervalSide[1]
                + (((CoordPair) c.getA()).getX() % 2) * intervalSide[0];
        int lowy = hextop + ((CoordPair) c.getA()).getY() * intervalUp;
        int highx =
            hexleft
                + (((CoordPair) c.getB()).getX() - (((CoordPair) c.getB()).getX() % 2))
                    / 2
                    * intervalSide[0]
                + (((CoordPair) c.getB()).getX() - (((CoordPair) c.getB()).getX() % 2))
                    / 2
                    * intervalSide[1]
                + (((CoordPair) c.getB()).getX() % 2) * intervalSide[0];
        int highy = hextop + ((CoordPair) c.getB()).getY() * intervalUp;

        int dx = highx - lowx;
        int dy = highy - lowy;
        double rad = Math.atan((1.0) * dy / dx);

        if (dx < 0) rad += Math.PI;

        g.translate(lowx, lowy);
        g.rotate(rad);
        g.drawImage(
            BoardObject.images.get(BoardObject.type2port.get(portContents.get(c))), 0, -75, null);
        g.rotate(-rad);
        g.translate((-1) * lowx, (-1) * lowy);
      }
    }
    g.translate((-1) * _display_offset[0], (-1) * _display_offset[1]);

    synchronized (roadContents) {
      for (Pair c : roadContents.keySet()) {

        Road r =
            new Road(
                hexleft
                    + (((CoordPair) c.getA()).getX() - (((CoordPair) c.getA()).getX() % 2))
                        / 2
                        * intervalSide[0]
                    + (((CoordPair) c.getA()).getX() - (((CoordPair) c.getA()).getX() % 2))
                        / 2
                        * intervalSide[1]
                    + (((CoordPair) c.getA()).getX() % 2) * intervalSide[0],
                hextop + ((CoordPair) c.getA()).getY() * intervalUp);

        r.setX2(
            hexleft
                + (((CoordPair) c.getB()).getX() - (((CoordPair) c.getB()).getX() % 2))
                    / 2
                    * intervalSide[0]
                + (((CoordPair) c.getB()).getX() - (((CoordPair) c.getB()).getX() % 2))
                    / 2
                    * intervalSide[1]
                + (((CoordPair) c.getB()).getX() % 2) * intervalSide[0]);
        r.setY2(hextop + ((CoordPair) c.getB()).getY() * intervalUp);

        r.setColor(roadContents.get(c));
        r.paint(g, _display_offset[0], _display_offset[1]);
      }
    }

    synchronized (vertexContents) {
      for (CoordPair c : vertexContents.keySet()) {
        int newx =
            hexleft
                + ((c._x - (c._x % 2)) / 2 * intervalSide[0]
                    + (c._x - (c._x % 2)) / 2 * intervalSide[1]
                    + (c._x % 2) * intervalSide[0])
                - 20;
        int newy = hextop + c._y * intervalUp - 20;

        if ((BoardObject.type) (vertexContents.get(c).getA()) == BoardObject.type.SETTLEMENT) {
          Settlement s = new Settlement(newx, newy, (Integer) (vertexContents.get(c).getB()));
          s.paint(g, _display_offset[0], _display_offset[1]);
        } else if ((BoardObject.type) (vertexContents.get(c).getA()) == BoardObject.type.CITY) {
          City s = new City(newx, newy, (Integer) (vertexContents.get(c).getB()));
          s.paint(g, _display_offset[0], _display_offset[1]);
        } else System.out.println("neither -_-");
      }
    }

    g.setColor(Color.GRAY);
    g.fill(new Rectangle(0, 0, 110, 60));
    g.setColor(Color.LIGHT_GRAY);
    g.fill(new Rectangle(3, 3, 104, 56));
    if (_dieRoll > 0) {
      BufferedImage r1img =
          diceImage.getSubimage((int) (Math.floor((twoDice[0] - 1) * 94.7)), 0, 94, 93);
      g.drawImage(r1img, 5, 7, 48, 47, null);
      BufferedImage r2img =
          diceImage.getSubimage((int) (Math.floor((twoDice[1] - 1) * 94.7)), 0, 94, 93);
      g.drawImage(r2img, 55, 7, 48, 47, null);
    }

    if (_up != null) _up.paint(g);

    if (!_gameOver.equals("") && !_dismiss) {
      _currAlpha += 0.007;
    }
    g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, _currAlpha));
    g.setColor(Color.GRAY);
    g.fill(new Rectangle(-20, 0, 1020, 650));
    g.setColor(Color.BLACK);
    g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, (float) 1.0));
    if (!_gameOver.equals("")) {

      if (_currAlpha >= 0.8) {
        if (_gameOver.equals(gameLogic._name)) {
          g.drawString("Congratulations, you won!", 350, 200);
        } else {
          g.drawString(_gameOver + " has won!", 350, 200);
        }
        _dismiss = true;
      } else repaint();
    }
  }
 private void sortEdges(List<City> allCities) {
   for (City city : allCities) {
     city.setdMap(sortByValues(city.getdMap()));
   }
 }