Exemplo n.º 1
0
  public static void main(String args[]) throws IOException {

    String text = "C:\\Users\\Roshan Rajan\\Desktop\\squaredance.txt";
    String gender = "";
    PriorityQueue<String> men = new PriorityQueue<String>();
    PriorityQueue<String> women = new PriorityQueue<String>();
    BufferedReader input = new BufferedReader(new FileReader(text));
    String line = null;
    while ((line = input.readLine()) != null) {
      gender = line.substring(0, 1);
      if (gender.equals("M")) men.add(line.substring(2));
      else women.add(line.substring(2));
    }
    input.close();

    while (!men.isEmpty() && !women.isEmpty()) {
      System.out.println("The couples are ");
      System.out.println(men.poll() + " is Dancing with " + women.poll());
    }
    if (men.isEmpty()) {
      System.out.println(women.size() + " girls are Waiting to Dance");
      System.out.println(women.peek() + " is the first one waiting");
    }
    if (women.isEmpty()) {
      System.out.println(men.size() + " guys are Waiting to Dance");
      System.out.println(men.peek() + " is the first one waiting");
    }
  }
Exemplo n.º 2
0
 private void assertMinimumsAreEqual(
     java.util.PriorityQueue<Integer> oldQueue, PriorityQueue<Integer> newQueue) {
   assertThat(oldQueue.isEmpty()).isEqualTo(newQueue.isEmpty());
   if (!newQueue.isEmpty()) {
     assertThat(oldQueue.peek()).isEqualTo(newQueue.head());
   }
 }
Exemplo n.º 3
0
  /**
   * gives turns for buying to players
   *
   * @throws IOException exception
   */
  private static void buyTurnIncre() throws IOException {
    if (playerOrder.isEmpty()) {
      for (Player p : Configurations.getPlayers()) {
        if (p.getMoney() > 300 && !p.isPassed()) {
          playerOrder.add(p);
        }
      }
      if (playerOrder.isEmpty()) {
        Configurations.setRound(Configurations.getRound() + 1);

        // Applying random event to player 1 during initial game start
        Configurations.getCurPlayer().setMessage(applyRandomEvent());
        Configurations.getGameScreenController()
            .updateText(Configurations.getCurPlayer().getMessage());
        Configurations.getLoopService().start();
        movePhaseTurnIncre();
        return;
      }
    }
    Configurations.setCurPlayer(playerOrder.remove());
    if (Configurations.getCurPlayer().isPassed()) {
      buyTurnIncre();
    }
    Configurations.getGameScreenController().updateText();
  }
Exemplo n.º 4
0
  private static void removeMultipleHits(PriorityQueue<Result> results, int sampleLength) {
    if (results.isEmpty()) return;

    ArrayList<Result> acceptedResults = new ArrayList<Result>();

    boolean isOccupied[] = new boolean[sampleLength];
    while (!results.isEmpty()) {
      Result r = results.poll();

      int hitCount = 0;
      int firstHitPosition = -1;
      for (int i = 0; i < r.getLength(); i++) {
        if (!isOccupied[r.getSampleStartPosition() + i]) {
          if (hitCount == 0) {
            firstHitPosition = r.getSampleStartPosition() + i;
          }
          hitCount++;
          isOccupied[r.getSampleStartPosition() + i] = true;
        } else if (hitCount != 0) {
          break;
        }
      }

      if (hitCount >= FRAME_COUNT_ACCEPTANCE_THRESHOLD) {
        r.setSampleStartPosition(firstHitPosition);
        r.setLength(hitCount);
        acceptedResults.add(r);
      }
    }

    results.addAll(acceptedResults);
  }
Exemplo n.º 5
0
  @Override
  void solve(Set<? extends Job> jobs) {
    Job[] sortedJobs = jobs.toArray(new Job[jobs.size()]);
    Arrays.sort(sortedJobs, Job::compareArrivalTime);

    processTime = totWT = 0;
    long usefulTime = 0;
    int jobCount = jobs.size();
    PriorityQueue<Job> queue = new PriorityQueue<>(Job::compareBurstTime);
    for (Job job : sortedJobs) {
      if (job == null) {
        jobCount--;
        continue;
      }

      while (!queue.isEmpty() && processTime < job.getArrivalTime()) {
        Job nextJob = queue.poll();
        long arrivalTime = nextJob.getArrivalTime();
        long burstTime = nextJob.getBurstTime();

        if (processTime < nextJob.getArrivalTime()) {
          processList.add(new RunningProcess("Idle", arrivalTime - processTime));
          processTime = arrivalTime;
        }

        processList.add(new RunningProcess("P" + nextJob.getId(), burstTime));
        usefulTime += burstTime;
        totWT += processTime - arrivalTime;
        processTime += burstTime;
      }

      queue.add(job);
    }

    while (!queue.isEmpty()) {
      Job nextJob = queue.poll();
      long arrivalTime = nextJob.getArrivalTime();
      long burstTime = nextJob.getBurstTime();

      if (processTime < nextJob.getArrivalTime()) {
        processList.add(new RunningProcess("Idle", arrivalTime - processTime));
        processTime = arrivalTime;
      }

      processList.add(new RunningProcess("P" + nextJob.getId(), burstTime));
      usefulTime += burstTime;
      totWT += processTime - arrivalTime;
      processTime += burstTime;
    }

    totRT = totWT;
    totTAT = totWT + usefulTime;

    avgRT = avgWT = (double) totWT / (double) jobCount;
    avgTAT = (double) totTAT / (double) jobCount;

    utilization = usefulTime * 100.0 / processTime;
  }
Exemplo n.º 6
0
  private void makeAFreeSpace() {

    while ((activeCache.size() + passiveCache.size()) >= CACHE_SIZE && !passiveCache.isEmpty()) {
      passiveCache.poll().getRenderedBitmap().recycle();
    }

    while ((activeCache.size() + passiveCache.size()) >= CACHE_SIZE && !activeCache.isEmpty()) {
      activeCache.poll().getRenderedBitmap().recycle();
    }
  }
Exemplo n.º 7
0
 public static void update(float tpf) {
   if (heap.isEmpty() == false) {
     myTime += (long) (tpf * 1000);
     while (heap.isEmpty() == false && ((Timer) heap.peek()).time < myTime) {
       Timer t = (Timer) heap.peek();
       heap.remove();
       t.execute();
     }
   }
 }
Exemplo n.º 8
0
  /*
   * As per [S. Koenig,2002] except for two main modifications:
   * 1. We stop planning after a number of steps, 'maxsteps' we do this
   *    because this algorithm can plan forever if the start is surrounded  by obstacles
   * 2. We lazily remove states from the open list so we never have to iterate through it.
   */
  private int computeShortestPath() {
    LinkedList<State> s = new LinkedList<State>();

    if (openList.isEmpty()) return 1;

    int k = 0;
    while ((!openList.isEmpty()) && (openList.peek().lt(s_start = calculateKey(s_start)))
        || (getRHS(s_start) != getG(s_start))) {

      if (k++ > maxSteps) {
        System.out.println("At maxsteps");
        return -1;
      }

      State u;

      boolean test = (getRHS(s_start) != getG(s_start));

      // lazy remove
      while (true) {
        if (openList.isEmpty()) return 1;
        u = openList.poll();

        if (!isValid(u)) continue;
        if (!(u.lt(s_start)) && (!test)) return 2;
        break;
      }

      openHash.remove(u);

      State k_old = new State(u);

      if (k_old.lt(calculateKey(u))) { // u is out of date
        insert(u);
      } else if (getG(u) > getRHS(u)) { // needs update (got better)
        setG(u, getRHS(u));
        s = getPred(u);
        for (State i : s) {
          updateVertex(i);
        }
      } else { // g <= rhs, state has got worse
        setG(u, Double.POSITIVE_INFINITY);
        s = getPred(u);

        for (State i : s) {
          updateVertex(i);
        }
        updateVertex(u);
      }
    } // while
    return 0;
  }
Exemplo n.º 9
0
 public static List<Vertex> compute(Graph graph) {
   List<Vertex> resultList = new LinkedList<Vertex>();
   Vertex[] vertexes = graph.getVertexes();
   List<EdgeFrom>[] edgesTo = graph.getEdgesTo();
   double[] d = new double[vertexes.length];
   Arrays.fill(d, Double.MAX_VALUE);
   d[d.length - 1] = 0;
   int[] path = new int[vertexes.length];
   Arrays.fill(path, -1);
   PriorityQueue<State> que = new PriorityQueue<State>();
   que.add(new State(0, vertexes.length - 1));
   while (!que.isEmpty()) {
     State p = que.poll();
     if (d[p.vertex] < p.cost) continue;
     for (EdgeFrom edgeFrom : edgesTo[p.vertex]) {
       if (d[edgeFrom.from] > d[p.vertex] + edgeFrom.weight) {
         d[edgeFrom.from] = d[p.vertex] + edgeFrom.weight;
         que.add(new State(d[edgeFrom.from], edgeFrom.from));
         path[edgeFrom.from] = p.vertex;
       }
     }
   }
   for (int t = 0; t != -1; t = path[t]) {
     resultList.add(vertexes[t]);
   }
   return resultList;
 }
 public static void main(String[] args) throws IOException {
   int n = readInt();
   int[] dogs = new int[n];
   ArrayList<ArrayList<Integer>> adjlist = new ArrayList<ArrayList<Integer>>();
   for (int x = 0; x < n; x++) {
     dogs[x] = readInt();
     adjlist.add(new ArrayList<Integer>());
   }
   int m = readInt();
   for (int x = 0; x < m; x++) {
     int a = readInt() - 1;
     int b = readInt() - 1;
     adjlist.get(a).add(b);
   }
   int time = readInt();
   int[] bark = new int[n];
   PriorityQueue<Dog> moves = new PriorityQueue<Dog>();
   moves.add(new Dog(0, 0));
   bark[0] = 0;
   int[] total = new int[n];
   while (!moves.isEmpty()) {
     Dog curr = moves.poll();
     if (curr.time > time) continue;
     bark[curr.id] = 0;
     total[curr.id]++;
     for (int x = 0; x < adjlist.get(curr.id).size(); x++) {
       int next = adjlist.get(curr.id).get(x);
       if ((bark[next] != 0 && curr.time + dogs[next] > bark[next])) continue;
       moves.remove(new Dog(next, curr.time + dogs[next]));
       bark[next] = curr.time + dogs[next];
       moves.offer(new Dog(next, curr.time + dogs[next]));
     }
   }
   for (int x : total) System.out.println(x);
 }
Exemplo n.º 11
0
  // O(V) + O(V * V + E) = O(V^2 + E) = O(V^2) if queue is un-ordered linked list
  // O(V * logV) + O(V * logV + E * logV) = O((V + E)logV)
  public static final void dijkstra(DijkVertex[] vertices, DijkVertex src) {

    // Initialize vertices prev and cost (intrinsically done already except for source)
    src.cost = 0;

    // Setup priority queue maintaining min cost vertices at the start of queue
    PriorityQueue<DijkVertex> q =
        new PriorityQueue<DijkVertex>(vertices.length, new DijkVertexComparator());
    q.addAll(Arrays.asList(vertices));

    // Go through queue removing min vertex each iteration
    while (!q.isEmpty()) {
      DijkVertex v = q.remove();

      // If cost of next node is MAX, it is not connected to source
      // Due to priority queue, all nodes after next node are also not connected to source
      // so can just return
      if (v.cost == Integer.MAX_VALUE) {
        return;
      }

      // For each edge leaving vertex, relax
      for (int i = 0; i < v.edges.length; i++) {
        if (v.cost + v.edges[i].cost < v.edges[i].dst.cost) {
          v.edges[i].dst.cost = v.cost + v.edges[i].cost;
          v.edges[i].dst.prev = v;

          // Remove and add updated vertex to queue to place it in correct location
          // after being updated
          q.remove(v.edges[i].dst);
          q.add(v.edges[i].dst);
        }
      }
    }
  }
Exemplo n.º 12
0
 /**
  * pesquisa A*
  *
  * @param table_list lista de tabelas
  * @param visited_tables lista de tabelas visitadas
  * @param final_table tabela final/pretendida
  * @return
  */
 public static Node aStarSearch(PriorityQueue<Node> table_list, int[][] final_table) {
   int[][] current_table = new int[3][3];
   int depth = 0;
   String path = new String();
   while (!table_list.isEmpty()) {
     List child_nodes = new List();
     Node current_node = table_list.poll();
     path = current_node.getPath();
     depth = current_node.getDepth();
     current_table = current_node.getTable();
     /*
     System.out.println("custo: "+cost+"depth: "+depth);
     System.out.println("Tabela: ");
     for(int i=0;i<3;i++){
     	for(int j=0;j<3;j++)
     		System.out.print(current_table[i][j]);
     	System.out.println();
     }
     */
     if (isSolution(current_table, final_table)) return new Node(current_table, depth, path, null);
     child_nodes = playBFS(child_nodes, current_table, depth, path);
     // verifica se algum dos filhos já foi visitado
     while (!child_nodes.isEmpty()) {
       int d = child_nodes.getDepth();
       String s = child_nodes.getPath();
       int[][] child_table = child_nodes.remove();
       int c = d + getDistanceTo(child_table, final_table);
       Node child = new Node(child_table, d, s, c, null);
       table_list.add(child);
     }
   }
   throw new Error("Nao encontrou solucao");
 }
Exemplo n.º 13
0
  public void PQOrdering() {
    PriorityQueue<String> pq = new PriorityQueue<String>();
    pq.add("5");
    pq.add("3");
    pq.add("1");
    pq.add("2");
    pq.add("4");
    pq.add("6");

    System.out.println("Unordered: " + pq); // Unordered: [1, 2, 3, 5, 4, 6]

    Iterator<String> itr = pq.iterator();
    System.out.print("Unordered Itr: ");
    while (itr.hasNext()) {
      System.out.print(itr.next() + ", "); // Unordered Itr: 1, 2, 3, 5, 4, 6,
    }

    System.out.println("");
    System.out.print("Unordered Arrays: ");
    Object[] obj = pq.toArray();
    for (Object o : obj) {
      System.out.print(o + ", "); // Unordered Arrays: 1, 2, 3, 5, 4, 6,
    }

    // To order a PQ
    System.out.print("\nOrdered:");
    while (!pq.isEmpty()) {
      System.out.print(pq.poll() + ", "); // Ordered: 1, 2, 3, 4, 5, 6,
    }
    System.out.println("********************************************");
  }
Exemplo n.º 14
0
  @Override
  public synchronized List<T> getTopK() {
    Comparator<T> comparator =
        new Comparator<T>() {
          public int compare(T key1, T key2) {
            return Longs.compare(counts.get(key1), counts.get(key2));
          }
        };
    PriorityQueue<T> topK = new PriorityQueue<T>(k, comparator);

    for (Map.Entry<T, Long> entry : counts.entrySet()) {
      if (topK.size() < k) {
        topK.offer(entry.getKey());
      } else if (entry.getValue() > counts.get(topK.peek())) {
        topK.offer(entry.getKey());
        topK.poll();
      }
    }

    LinkedList<T> sortedTopK = new LinkedList<T>();

    while (!topK.isEmpty()) {
      sortedTopK.addFirst(topK.poll());
    }

    return sortedTopK;
  }
Exemplo n.º 15
0
 /**
  * moves / increments turn based off of players priority queue
  *
  * @throws IOException exception
  */
 private static void movePhaseTurnIncre() throws IOException {
   if (playerOrder.isEmpty()) {
     for (Player p : Configurations.getPlayers()) {
       playerOrder.add(p);
     }
     Configurations.setRound(Configurations.getRound() + 1);
     if (Configurations.getPhase() == 1) {
       produce();
     }
   }
   Configurations.setCurPlayer(playerOrder.remove());
   if (Configurations.getPhase() != 0) {
     if (Math.random() < .27) {
       Configurations.getCurPlayer().setMessage(applyRandomEvent());
       Configurations.getGameScreenController()
           .updateText(Configurations.getCurPlayer().getMessage());
     } else {
       Configurations.getCurPlayer().setMessage("");
       Configurations.getGameScreenController()
           .updateText(Configurations.getCurPlayer().getMessage());
     }
   } else {
     Configurations.getGameScreenController().updateText();
   }
 }
Exemplo n.º 16
0
 public ListNode mergeKLists(ArrayList<ListNode> lists) {
   if (lists == null || lists.isEmpty()) return null;
   PriorityQueue<ListNode> heap =
       new PriorityQueue<ListNode>(
           lists.size(),
           new Comparator<ListNode>() {
             public int compare(ListNode o1, ListNode o2) {
               return o1.data > o2.data ? 1 : (o1.data < o2.data ? -1 : 0);
             }
           });
   for (ListNode node : lists) {
     if (node != null) {
       heap.add(node);
     }
   }
   ListNode head = null, cur = null;
   while (!heap.isEmpty()) {
     if (head == null) {
       head = heap.poll();
       cur = head;
     } else {
       cur.next = heap.poll();
       cur = cur.next;
     }
     if (cur.next != null) {
       heap.add(cur.next);
     }
   }
   return head;
 }
Exemplo n.º 17
0
  public int[] firstK(int arr[], int k) {
    int[] arrK = new int[k];
    // max heap
    PriorityQueue<Integer> heap =
        new PriorityQueue<Integer>(
            k,
            new Comparator<Integer>() {

              @Override
              public int compare(Integer arg0, Integer arg1) {
                return -arg0.compareTo(arg1);
              }
            });

    for (int i = 0; i < arr.length; ++i) {
      heap.add(arr[i]);
      if (heap.size() > k) {
        heap.poll();
      }
    }
    int idx = 0;
    while (!heap.isEmpty()) {
      arrK[idx++] = heap.poll();
    }
    return arrK;
  }
Exemplo n.º 18
0
  public ListNode mergeKLists(ArrayList<ListNode> lists) {
    if (lists == null || lists.isEmpty()) return null;
    ListNode head = new ListNode(0);
    ListNode p = head;

    PriorityQueue<ListNode> queue =
        new PriorityQueue<ListNode>(
            lists.size(),
            new Comparator<ListNode>() {

              @Override
              public int compare(ListNode o1, ListNode o2) {
                return o1.val - o2.val;
              }
            });
    for (ListNode n : lists) {
      if (n != null) {
        queue.offer(n);
      }
    }

    while (!queue.isEmpty()) {
      ListNode n = queue.poll();
      p.next = n;
      p = p.next;
      if (n.next != null) {
        queue.offer(n.next);
      }
    }

    return head.next;
  }
Exemplo n.º 19
0
 public ListNode mergeKLists(ListNode[] lists) {
   ListNode sentinel = new ListNode(0);
   ListNode current = sentinel;
   PriorityQueue<ListNode> heap =
       new PriorityQueue<>(
           (e1, e2) -> {
             if (e1.val > e2.val) {
               return 1;
             } else if (e1.val < e2.val) {
               return -1;
             } else {
               return 0;
             }
           });
   for (ListNode node : lists) {
     if (node != null) {
       heap.add(node);
     }
   }
   while (heap.isEmpty() == false) {
     ListNode nodeWithMinValue = heap.poll();
     current.next = nodeWithMinValue;
     nodeWithMinValue = nodeWithMinValue.next;
     if (nodeWithMinValue != null) {
       heap.add(nodeWithMinValue);
     }
   }
   return sentinel.next;
 }
Exemplo n.º 20
0
  public void reduce(
      Text key, Iterator<Text> values, OutputCollector<Text, Text> output, Reporter reporter)
      throws IOException {

    while (values.hasNext()) {
      String line = values.next().toString();
      String[] tokens = line.split(",");

      try {
        double latitude = (Double.parseDouble(tokens[2]));
        double longitude = (Double.parseDouble(tokens[3]));

        Tuple t = new Tuple(longitude, latitude, line);
        t.setDistance(fp);
        if (queue.size() < k) {
          queue.add(t);
        } else {
          if (t.distance < queue.peek().distance) {
            queue.add(t);
            queue.remove();
          }
        }

      } catch (Exception c) {

      }
    }

    while (!queue.isEmpty()) {
      output.collect(new Text("1"), new Text(queue.remove().tupleData));
    }
  }
Exemplo n.º 21
0
 /**
  * pesquisa gulosa
  *
  * @param table_list lista de tabelas
  * @param visited_tables lista de tabelas visitadas
  * @param final_table tabela final/pretendida
  */
 public static Node greedySearch(
     PriorityQueue<Node> table_list, List visited_tables, int[][] final_table) {
   int[][] current_table = new int[3][3];
   int depth = 0;
   String path = new String();
   while (!table_list.isEmpty()) {
     List child_nodes = new List();
     Node current_node = table_list.poll();
     path = current_node.getPath();
     depth = current_node.getDepth();
     current_table = current_node.getTable();
     if (isSolution(current_table, final_table)) return new Node(current_table, depth, path, null);
     visited_tables.addFirst(current_table, depth, path);
     child_nodes = playBFS(child_nodes, current_table, depth, path);
     // verifica se algum dos filhos já foi visitado
     while (!child_nodes.isEmpty()) {
       int d = child_nodes.getDepth();
       String s = child_nodes.getPath();
       int[][] child_table = child_nodes.remove();
       if (!visited_tables.contains(child_table)) {
         int c = getDistanceTo(child_table, final_table);
         Node child = new Node(child_table, d, s, c, null);
         table_list.add(child);
       }
     }
   }
   throw new Error("Nao encontrou solucao");
 }
Exemplo n.º 22
0
 public static void main(String[] args) {
   Scanner in = new Scanner(System.in);
   PriorityQueue<Node> pq = new PriorityQueue<Node>();
   HashSet<Integer> visited = new HashSet<Integer>();
   int n = in.nextInt();
   int[][] am = new int[n][n];
   for (int i = 0; i < n; i++)
     for (int j = 0; j < n; j++) {
       am[i][j] = in.nextInt();
       if (i == j) am[i][j] = Integer.MAX_VALUE;
     }
   n = in.nextInt();
   int a, b;
   while (n-- > 0) {
     a = in.nextInt() - 1;
     b = in.nextInt() - 1;
     am[a][b] = 0;
     am[b][a] = 0;
   }
   int ret = 0;
   pq.add(new Node(0, 0));
   Node curr;
   while (!pq.isEmpty()) {
     curr = pq.poll();
     if (visited.contains(curr.a)) continue;
     ret += curr.w;
     visited.add(curr.a);
     for (int i = 0; i < am.length; i++) {
       pq.add(new Node(i, am[curr.a][i]));
     }
   }
   System.out.println(ret);
 }
Exemplo n.º 23
0
  private void Loop() {
    while (!H.isEmpty()) {
      Cell v = H.poll();
      if (Log.ON) Log.write("popped: " + potentialField[v.col][v.row]);
      frozenDjogurt[v.col][v.row] = true;
      for (Cell vn : map.doSomeMagic(v)) {
        if (Log.ON) {
          Log.write("\n" + toString(v));
          Log.write("\n" + printStack());
        }
        if (!(map.cells[vn.col][vn.row].type == CellType.OBSTACLE)) {
          if (!frozenDjogurt[vn.col][vn.row]) {
            double d = computeArrivalTime(vn);
            if (d > maxElement) maxElement = d;
            if (!H.contains(vn)) {

              potentialField[vn.col][vn.row] = d;
              H.add(vn);
            } else {
              //							if(potentialField[vn.col][vn.row] > d)
              //							{
              H.remove(vn);
              potentialField[vn.col][vn.row] = d;
              H.add(vn);
              //							}
            }
          }
        }
      }
    }
  }
Exemplo n.º 24
0
  /**
   * piirtää reitin tiedostoon ja reittikartta taulukkoon
   *
   * @param käydytsolmut
   * @throws IOException
   */
  public void piirräreitti(PriorityQueue<Solmu> käydytsolmut) throws IOException {

    String nimi = new String("uk");
    BufferedWriter reittikarttatiedosto = new BufferedWriter(new FileWriter("uk"));
    Solmu solmu = new Solmu(0, 0, null, 0);

    while (!käydytsolmut.isEmpty()) {
      solmu = käydytsolmut.poll();

      for (int n = 0; n < kartankoko; n++) {
        for (int i = 0; i < kartankoko; i++) {
          if (solmu.x == n && solmu.y == i) {
            // reittikartta[i][n] = '-';
            reittikartta[i][n] = (char) (solmu.summaamatkat(0, solmu.annavanhempi()) + 65);
            // reittikarttatiedosto.write("-");
            reittikarttatiedosto.write('-');
          } else {
            reittikarttatiedosto.write(reittikartta[i][n]);
          }
        }
        reittikarttatiedosto.newLine();
      }
    }
    reittikarttatiedosto.close();
    tulostakartta(reittikartta);
  }
Exemplo n.º 25
0
  /** Implementation of dijkstra's algorithm using a binary heap. */
  private void dijkstra(final PriorityQueue<Vertex> q) {
    Vertex u, v;
    while (!q.isEmpty()) {

      u = q.poll(); // vertex with shortest distance (first iteration
      // will return source)
      // System.out.println("id is"+u.getId());
      // System.out.println(u.getDist());
      // System.out.println(u.getNeighborV().size());
      // System.out.println(this.endNodeId)
      if (u.getDist() == Double.MAX_VALUE)
        break; // we can ignore u (and any other remaining vertices)
      // since they are unreachable

      // look at distances to each neighbor
      for (Map.Entry<Vertex, Double> a : u.getNeighborV().entrySet()) {
        v = a.getKey(); // the neighbor in this iteration

        double alternateDist = u.getDist() + a.getValue();
        if (alternateDist < v.getDist()) { // shorter path to neighbor
          // found
          // System.out.println("+++++");
          q.remove(v);
          v.setDist(alternateDist);
          // System.out.println(v.getId());
          // System.out.println(v.getDist());
          v.setPrevious(u);
          q.add(v);
          // System.out.println(q.size());
        }
      }
    }
  }
Exemplo n.º 26
0
  public T receive() {
    lock.lock();
    try {
      while (true) {
        DelayedMessage message = queue.peek();
        if (message == null && stopping) {
          return null;
        }
        if (message == null) {
          condition.await();
          continue;
        }

        long now = timeProvider.getCurrentTime();
        if (message.dispatchTime > now) {
          condition.awaitUntil(new Date(message.dispatchTime));
        } else {
          queue.poll();
          if (queue.isEmpty()) {
            condition.signalAll();
          }
          return message.message;
        }
      }
    } catch (InterruptedException e) {
      throw UncheckedException.throwAsUncheckedException(e);
    } finally {
      lock.unlock();
    }
  }
Exemplo n.º 27
0
  public List<Pair> assignJobsNew(Queue<Integer> jobs, int numWorkers) {
    List<Pair> pairs = new LinkedList<>();

    PriorityQueue<JobThread> priorityQueue =
        new PriorityQueue<>((x, y) -> Long.compare(x.startTime, y.startTime));
    for (int i = 0; i < numWorkers; i++) {
      priorityQueue.add(new JobThread());
    }

    while (!jobs.isEmpty()) {
      int duration = jobs.poll();

      boolean check = true;
      while (check) {
        JobThread peek = priorityQueue.poll();
        if (peek.hasFreeTime()) {
          peek.duration = duration;
          pairs.add(new Pair(peek.workerId, peek.newStartTime()));
        } else {
          peek.tick();
        }

        if (priorityQueue.isEmpty()) {
          check = false;
        }
        priorityQueue.add(peek);
      }
    }
    return pairs;
  }
Exemplo n.º 28
0
 private void expandLandmarkTo() {
   LandmarksToTravelTimeComparator comparator =
       new LandmarksToTravelTimeComparator(this.nodeData, this.landmarkIdx);
   PriorityQueue<Node> pendingNodes = new PriorityQueue<>(100, comparator);
   LandmarksData role = (LandmarksData) this.nodeData.get(this.landmark);
   role.setToLandmarkTravelTime(this.landmarkIdx, 0.0);
   role.setFromLandmarkTravelTime(this.landmarkIdx, 0.0);
   pendingNodes.add(this.landmark);
   while (!pendingNodes.isEmpty()) {
     Node node = pendingNodes.poll();
     double toTravTime =
         ((LandmarksData) this.nodeData.get(node)).getToLandmarkTravelTime(this.landmarkIdx);
     LandmarksData role2;
     for (Link l : node.getInLinks().values()) {
       Node n = l.getFromNode();
       double linkTravTime = this.costFunction.getLinkMinimumTravelDisutility(l);
       role2 = (LandmarksData) this.nodeData.get(n);
       double totalTravelTime = toTravTime + linkTravTime;
       if (role2.getToLandmarkTravelTime(this.landmarkIdx) > totalTravelTime) {
         role2.setToLandmarkTravelTime(this.landmarkIdx, totalTravelTime);
         pendingNodes.add(n);
       }
     }
   }
 }
Exemplo n.º 29
0
  /**
   * Get top N elements
   *
   * @param vec the vec to extract the top elements from
   * @param N the number of elements to extract
   * @return the indices and the sorted top N elements
   */
  private static List<Double> getTopN(INDArray vec, int N) {
    ArrayComparator comparator = new ArrayComparator();
    PriorityQueue<Double[]> queue = new PriorityQueue<>(vec.rows(), comparator);

    for (int j = 0; j < vec.length(); j++) {
      final Double[] pair = new Double[] {vec.getDouble(j), (double) j};
      if (queue.size() < N) {
        queue.add(pair);
      } else {
        Double[] head = queue.peek();
        if (comparator.compare(pair, head) > 0) {
          queue.poll();
          queue.add(pair);
        }
      }
    }

    List<Double> lowToHighSimLst = new ArrayList<>();

    while (!queue.isEmpty()) {
      double ind = queue.poll()[1];
      lowToHighSimLst.add(ind);
    }
    return Lists.reverse(lowToHighSimLst);
  }
Exemplo n.º 30
0
  public static void computePaths(Vertex source, ArrayList<String> ziel) {
    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);
        }
      }
      if (ziel.contains(u.name)) {
        vertexQueue.clear();
        break;
      }
    }
  }