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());
   }
 }
  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");
    }
  }
  @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;
  }
Exemple #4
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;
  }
Exemple #5
0
  public List<Task> mockRunTaks(List<Task> tasks) {
    PriorityQueue<Task> taskQueue =
        new PriorityQueue<Task>(
            new Comparator<Task>() {
              @Override
              public int compare(Task t1, Task t2) {
                return t1.priority - t2.priority;
              }
            });
    List<Task> runOrder = new ArrayList<Task>();
    HashMap<Task, Integer> taskIndegrees = new HashMap<Task, Integer>();

    for (Task task : tasks) {
      taskIndegrees.put(task, task.dependencies.size());
      if (task.dependencies.size() == 0) {
        taskQueue.offer(task);
      }
    }
    while (!taskQueue.isEmpty()) {
      Task curTask = taskQueue.poll();
      runOrder.add(curTask);

      for (Task task : curTask.dependencies) {
        taskIndegrees.put(task, taskIndegrees.get(task) - 1);
        if (taskIndegrees.get(task) == 0) taskQueue.offer(task);
      }
    }

    return runOrder;
  }
  /**
   * 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);
  }
Exemple #7
0
  public static SearchResult generic(SearchProblem prob, Comparator<SearchNode> cmp) {
    PriorityQueue<SearchNode> frontier = new PriorityQueue<SearchNode>(10000, cmp);
    frontier.offer(prob.startNode());

    Set<State> explored = new HashSet<State>();

    while (!frontier.isEmpty()) {
      SearchNode candidate = frontier.poll();

      if (candidate.isGoal()) {
        return new SearchResult(candidate, explored.size(), frontier.size());
      }

      List<Action> nextActions = prob.actions(candidate.state);
      for (Action action : nextActions) {
        SearchNode child = prob.childNode(candidate, action);
        if (!explored.contains(child.state)) {
          frontier.offer(child);
          explored.add(candidate.state);
        }
      }
    }

    return null;
  }
Exemple #8
0
  /*
   * Initialise Method
   * @params start and goal coordinates
   */
  public void init(int sX, int sY, int gX, int gY) {
    cellHash.clear();
    path.clear();
    openHash.clear();
    while (!openList.isEmpty()) openList.poll();

    k_m = 0;

    s_start.x = sX;
    s_start.y = sY;
    s_goal.x = gX;
    s_goal.y = gY;

    CellInfo tmp = new CellInfo();
    tmp.g = 0;
    tmp.rhs = 0;
    tmp.cost = C1;

    cellHash.put(s_goal, tmp);

    tmp = new CellInfo();
    tmp.g = tmp.rhs = heuristic(s_start, s_goal);
    tmp.cost = C1;
    cellHash.put(s_start, tmp);
    s_start = calculateKey(s_start);

    s_last = s_start;
  }
  /**
   * 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);
  }
Exemple #10
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);
 }
Exemple #11
0
  static void test00() {
    Aron.beg();
    PriorityQueue<Interval> queue = new PriorityQueue<Interval>();
    Stack<Interval> stack = new Stack<Interval>();
    int[] arr1 = {4, 1, 2, 6, 9};
    int[] arr2 = {5, 1, 4, 9, 10};

    for (int i = 0; i < arr1.length; i++) {
      queue.add(new Interval(arr1[i], arr2[i]));
    }
    if (queue.size() > 0) {
      stack.push(queue.remove());
    }
    while (!queue.isEmpty()) {
      Interval top = stack.peek();
      Interval inter = queue.remove();
      if (top.end < inter.begin) stack.push(inter);
      else {
        stack.peek().end = Math.max(stack.peek().end, inter.end);
      }
    }
    while (!stack.empty()) {
      System.out.println("[" + stack.peek().begin + " " + stack.peek().end + "]");
      stack.pop();
    }

    Aron.end();
  }
Exemple #12
0
 /**
  * This method is used for the UI to display the list of movies in priority order.
  *
  * @pre
  * @post the movies will be in the order of the priority the user queued them in, if two movies
  *     have the same priority then they appear in FIFO order
  * @return an array of {@link Movie} objects that are in priority order
  */
 public Movie[] displayWaitingMoviesByPriority() {
   @SuppressWarnings("unchecked")
   PriorityQueue<Movie> cloneOfP = (PriorityQueue<Movie>) DeepCopier.copy(waitingQueue);
   Movie[] movieList = new Movie[cloneOfP.getSize()];
   int i = 0;
   while (!cloneOfP.isEmpty()) {
     movieList[i] = cloneOfP.dequeueByPriority();
     i++;
   }
   return movieList;
 }
  public static void main(String[] args) {
    PriorityQueue<String> pque = new PriorityQueue<>();

    System.out.println("Empty? " + pque.isEmpty());
    pque.insert(0, "Mark");
    System.out.println("Empty? " + pque.isEmpty());
    System.out.println("Get min: " + pque.min());
    System.out.println("Remove min: " + pque.removeMin());

    pque.insert(6, "Hans");
    pque.insert(3, "Ib");
    pque.insert(6, "Jens");
    pque.insert(4, "Mads");
    pque.insert(6, "Lene");
    pque.insert(2, "Finn");
    System.out.println(pque);
    System.out.println(pque.size());
    System.out.println(pque.removeMin());
    System.out.println(pque);
    System.out.println(pque.removeMin());
    System.out.println(pque.removeMin());
    System.out.println(pque.removeMin());
    System.out.println(pque.removeMin());
    System.out.println(pque.isEmpty());
    System.out.println(pque.removeMin());
    System.out.println(pque.isEmpty());
    try {
      System.out.println(pque.removeMin());
    } catch (NoSuchElementException e) {
      System.out.print("Got it.");
    }
    try {
      System.out.println(pque.min());
    } catch (NoSuchElementException e) {
      System.out.print("... Got it again.");
    }
    System.out.println(", size: " + pque.size());
    pque.insert(-1, "neg kasper");
    pque.insert(500, "stor kasper");
    System.out.println(pque);
  }
  static void sweep(ArrayList<Integer> indexes) {
    PriorityQueue<Event> pq = new PriorityQueue<Event>();
    for (int i = 0; i < indexes.size(); i++) {
      pq.offer(new Event(lo[val[indexes.get(i)]] + 1, 1, indexes.get(i)));
      pq.offer(new Event(hi[val[indexes.get(i)]], -1, indexes.get(i)));
    }

    TreeSet<Integer> active = new TreeSet<Integer>();
    while (!pq.isEmpty()) {
      Event curr = pq.poll();
      if (curr.type == 1) active.add(curr.index);
      else if (curr.type == -1) {
        active.remove(curr.index);
        Integer lower = active.lower(curr.index);
        if (lower != null && lower > lo[val[curr.index]]) {
          Interval add = new Interval(lower, curr.index);
          Interval prev = intervals.floor(add);
          Interval next = intervals.ceiling(add);
          boolean intersectPrev = true;
          boolean intersectNext = true;

          if (prev != null) {
            if (Math.max(add.l, prev.l) < Math.min(add.r, prev.r)) {
              if (add.r - add.l <= prev.r - prev.l) {
                intervals.remove(prev);
                intersectPrev = false;
              }
            } else {
              intersectPrev = false;
            }
          } else {
            intersectPrev = false;
          }

          if (next != null) {
            if (Math.max(add.l, next.l) < Math.min(add.r, next.r)) {
              if (add.r - add.l <= next.r - next.l) {
                intervals.remove(next);
                intersectNext = false;
              }
            } else {
              intersectNext = false;
            }
          } else {
            intersectNext = false;
          }

          if (!intersectPrev && !intersectNext) intervals.add(add);
        }
      }
    }
  }
  public static void main(String[] args) {
    PriorityQueue<GregorianCalendar> pq =
        new PriorityQueue<GregorianCalendar>(); // 优先级队列对GC设置优先级:月->日
    pq.add(new GregorianCalendar(1906, Calendar.DECEMBER, 9)); // G. Hopper
    pq.add(new GregorianCalendar(1815, Calendar.DECEMBER, 10)); // A. Lovelace
    pq.add(new GregorianCalendar(1923, Calendar.DECEMBER, 3)); // J. von Neumann
    pq.add(new GregorianCalendar(1910, Calendar.JUNE, 22)); // K. Zuse

    System.out.println("Iterating over elements...");
    for (GregorianCalendar date : pq) System.out.println(date.get(Calendar.YEAR));
    System.out.println("Removing elements...");
    while (!pq.isEmpty()) System.out.println(pq.remove().get(Calendar.YEAR));
  }
  public void testPriorityQueueAscending() {
    PriorityQueue pq = new PriorityQueue();

    try {
      pq.dequeue();

      fail("NoSuchElementException not thrown on empty queue");
    } catch (NoSuchElementException e) {
    }

    pq.enqueue("Test 2", 2);
    pq.enqueue("Test 3", 3);
    pq.enqueue("Test 1", 1);

    assertTrue("isEmpty is returned true on an nonempty queue", !pq.isEmpty());

    String peek1 = (String) pq.peek();
    String s1 = (String) pq.dequeue();
    String peek2 = (String) pq.peek();
    String s2 = (String) pq.dequeue();
    String s3 = (String) pq.dequeue();

    assertTrue("size was incorrect (should be 3)", pq.size() != 3);
    assertTrue("isEmpty is returned false on an empty queue", pq.isEmpty());

    try {
      pq.dequeue();

      fail("NoSuchElementException not thrown on empty queue");
    } catch (NoSuchElementException e) {
    }

    assertTrue("Peek #1 incorrect", peek1.equals("Test 1"));
    assertTrue("Peek #2 incorrect", peek2.equals("Test 2"));
    assertTrue("Dequeue #1 incorrect", s1.equals("Test 1"));
    assertTrue("Dequeue #2 incorrect", s2.equals("Test 2"));
    assertTrue("Dequeue #3 incorrect", s3.equals("Test 3"));
  }
  public void getIndexInfo(String indexdir, int freqThreshold) {
    IndexReader reader = null;

    try {
      Directory dir = FSDirectory.open(new File(indexdir));
      System.out.println(dir);
      reader = IndexReader.open(dir);

      System.out.println("document num:" + reader.numDocs());
      System.out.println("======================");

      TermEnum terms = reader.terms();
      sortedTermQueue.clear();
      maxDocNum = reader.maxDoc();
      linkMap.clear();
      termList.clear();
      while (terms.next()) {
        // System.out.print(terms.term() + "\tDocFreq:" +
        TermDocs termDocs = reader.termDocs(terms.term());
        MyTerm temp = new MyTerm(terms.term(), termDocs, maxDocNum);
        if (temp.totalFreq < freqThreshold) {
          continue;
        } /*
           * if(temp.originTrem.text().length()==1){ continue; }
           */
        linkMap.put(temp.originTrem.text(), temp);
        sortedTermQueue.add(temp);
        termList.add(temp);
      }
      System.out.println("total Size:" + sortedTermQueue.size());
      System.out.println("mapsize:" + linkMap.keySet().size());
      // System.exit(0);
      int num = 0;
      this.maxFreq = sortedTermQueue.peek().totalFreq;
      while (!sortedTermQueue.isEmpty()) {
        num++;
        System.out.println(num + ":" + sortedTermQueue.poll());
      }
      System.out.println("read index info done");
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        reader.close();

      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
 /*
  * 获取客户极坐标的排序
  *
  * */
 public Queue<Client> sortClientsByPolarCoordinate(Client[] clients) {
   Queue<Client> queue = new LinkedList<Client>();
   ClientPolarCoordinateComparator clientPolarCoordinateComparator =
       new ClientPolarCoordinateComparator();
   PriorityQueue<Client> priorityQueue =
       new PriorityQueue<Client>(clients.length - 1, clientPolarCoordinateComparator);
   for (int i = 1; i < clients.length; i++) {
     priorityQueue.add(clients[i]);
   }
   while (!priorityQueue.isEmpty()) {
     queue.add(priorityQueue.remove());
   }
   return queue;
 }
Exemple #19
0
  // You can add extra function if needed
  // --------------------------------------------
  int dijkstra() {
    IntegerPair current;
    while (!q.isEmpty()) {

      current = q.poll();
      if (weights.get(current.first()) == current.second())
        for (IntegerPair next : AdjList.get(current.first())) {
          if (weights.get(next.first()) > current.second() + next.second()) {
            weights.set(next.first(), current.second() + next.second());
            q.offer(new IntegerPair(next.first(), weights.get(next.first())));
          }
        }
    }
    return weights.get(1);
  }
Exemple #20
0
    private void advance() {

      nextAlignment = null;
      Row nextRow = null;
      while (nextAlignment == null && !rows.isEmpty()) {
        while ((nextRow = rows.poll()) != null) {
          if (nextRow.hasNext()) {
            nextAlignment = nextRow.nextAlignment();
            break;
          }
        }
      }
      if (nextRow != null && nextAlignment != null) {
        rows.add(nextRow);
      }
    }
  public int nthUglyNumber(int n) {
    if (n <= 0) return 0;

    PriorityQueue<Long> queue = new PriorityQueue<>();
    queue.add(1l);

    long result = 0;
    for (int i = 1; i <= n; i++) {
      result = queue.poll();
      while (!queue.isEmpty() && queue.peek() == result) queue.poll();
      queue.add(result * 2);
      queue.add(result * 3);
      queue.add(result * 5);
    }
    return (int) result;
  }
Exemple #22
0
  // returns the single move to make given a board, depth, piecelist, heuristic
  // whill choose the best terminal board at the max depth,
  // or if none exists, the best board with no children (inevitable death)
  public Board.Direction nextMove(Board start, List<Integer> nextPiece) {
    int maxDepth = Math.min(exploreDepth, nextPiece.size());

    double bestLiveScore = -1;
    Board.Direction bestLiveDirection = null; // cus why not?

    // add the first round seperately so we know which move to return
    for (Board.Direction d : Board.Direction.values()) {
      Board next = start.move(d, nextPiece.get(0));
      if (next != null) {
        PriorityQueue<Double> pq = new PriorityQueue<Double>();

        Deque<StackItem> stack = new ArrayDeque<StackItem>();
        stack.push(new StackItem(next, 1, d));
        // DFS
        while (!stack.isEmpty()) {
          StackItem cur = stack.pop();

          // add more moves if not beyond max depth
          if (cur.d < maxDepth) {
            for (Board.Direction d2 : Board.Direction.values()) {
              Board next2 = cur.b.move(d2, nextPiece.get(cur.d));
              if (next2 != null) {
                stack.push(new StackItem(next2, cur.d + 1, cur.move));
              }
            }
          }
          // update live only at the bottom of the tree
          if (cur.d == maxDepth) {
            pq.add(heuristic.useHeuristic(cur.b));
            if (pq.size() > 10) pq.poll();
          }
        }
        double sum = 0;
        int count = 0;
        count = pq.size();
        while (!pq.isEmpty()) sum += pq.poll();
        if (count > 0 && sum / count > bestLiveScore) {
          bestLiveScore = sum / count;
          bestLiveDirection = d;
        }
      }
    }
    return bestLiveDirection;
  }
 public List<int[]> getSkyline(int[][] buildings) {
   List<int[]> result = new ArrayList<>();
   if (buildings == null || buildings.length == 0) {
     return result;
   }
   Comparator<Point> comp =
       new Comparator<Point>() {
         @Override
         public int compare(Point a, Point b) {
           if (a.x != b.x) {
             return a.x - b.x;
           } else {
             return a.y - b.y;
           }
         }
       };
   PriorityQueue<Point> pq = new PriorityQueue<>(5, comp);
   for (int[] data : buildings) {
     pq.add(new Point(data[0], -data[2]));
     pq.add(new Point(data[1], data[2]));
   }
   TreeMap<Integer, Integer> map = new TreeMap<>();
   map.put(0, 1);
   int max = 0;
   while (!pq.isEmpty()) {
     Point cur = pq.poll();
     if (cur.y < 0) {
       if (!map.containsKey(-cur.y)) {
         map.put(-cur.y, 0);
       }
       map.put(-cur.y, map.get(-cur.y) + 1);
     } else {
       map.put(cur.y, map.get(cur.y) - 1);
       if (map.get(cur.y) == 0) {
         map.remove(cur.y);
       }
     }
     int curMax = map.lastEntry().getKey();
     if (curMax != max) {
       result.add(new int[] {cur.x, curMax});
       max = curMax;
     }
   }
   return result;
 }
Exemple #24
0
  public LazyPrimMST(EdgeWeightedGraph G) {
    pq = new PriorityQueue<>(Collections.reverseOrder());
    marked = new boolean[G.V()];

    mst = new LinkedList<>();
    visit(G, 0);
    while (!pq.isEmpty()) {
      Edge e = pq.poll();
      int v = e.either();
      int w = e.other(v);
      if (marked[v] && marked[w]) continue;
      mst.offer(e);

      if (!marked[v]) visit(G, v);

      if (!marked[w]) visit(G, w);
    }
  }
Exemple #25
0
  public boolean resolve(LinkedList<Clause> clauses) {
    // Storing onto the stack to verify clauses in reverse order
    // LinkedList<Clause> expansionStack = new LinkedList<Clause>();
    PriorityQueue<Clause> expansionQueue =
        new PriorityQueue<Clause>(10000, new ClauseSizeComparator());

    for (int count = 0; count < clauses.size(); count++) {
      expansionQueue.add(clauses.get(count));
    }

    while (!expansionQueue.isEmpty()) // Until the stack is empty
    {

      Clause lastClause = expansionQueue.poll();

      for (int clauseCount = 0; clauseCount < lastClause.getClauseID() - 1; clauseCount++) {
        // If any new clauses are added since last execution
        // if(!clauses.getLast().equals(lastClause))
        {
          // break;
        }

        Clause tempClause = clauses.get(clauseCount);
        int numClausesBeforeExpansion = clauses.size();
        boolean result = lastClause.resolution(tempClause, clauses);

        if (!result) {
          return false;
        }

        int numClausesAfterExpansion = clauses.size();

        // System.out.println(numClausesAfterExpansion - numClausesBeforeExpansion); //Size does not
        // change

        // If new clauses are added, expand the newly added clause before expanding any other clause
        if (numClausesAfterExpansion - numClausesBeforeExpansion > 0) {
          expansionQueue.add(clauses.getLast());
        }
      }
    }

    return true;
  }
Exemple #26
0
  /*
   * This is somewhat of a hack, to change the position of the goal we
   * first save all of the non-empty nodes on the map, clear the map, move the
   * goal and add re-add all of the non-empty cells. Since most of these cells
   * are not between the start and goal this does not seem to hurt performance
   * too much. Also, it frees up a good deal of memory we are probably not
   * going to use.
   */
  public void updateGoal(int x, int y) {
    List<Pair<ipoint2, Double>> toAdd = new ArrayList<Pair<ipoint2, Double>>();
    Pair<ipoint2, Double> tempPoint;

    for (Map.Entry<State, CellInfo> entry : cellHash.entrySet()) {
      if (!close(entry.getValue().cost, C1)) {
        tempPoint =
            new Pair(new ipoint2(entry.getKey().x, entry.getKey().y), entry.getValue().cost);
        toAdd.add(tempPoint);
      }
    }

    cellHash.clear();
    openHash.clear();

    while (!openList.isEmpty()) openList.poll();

    k_m = 0;

    s_goal.x = x;
    s_goal.y = y;

    CellInfo tmp = new CellInfo();
    tmp.g = tmp.rhs = 0;
    tmp.cost = C1;

    cellHash.put(s_goal, tmp);

    tmp = new CellInfo();
    tmp.g = tmp.rhs = heuristic(s_start, s_goal);
    tmp.cost = C1;
    cellHash.put(s_start, tmp);
    s_start = calculateKey(s_start);

    s_last = s_start;

    Iterator<Pair<ipoint2, Double>> iterator = toAdd.iterator();
    while (iterator.hasNext()) {
      tempPoint = iterator.next();
      updateCell(tempPoint.first().x, tempPoint.first().y, tempPoint.second());
    }
  }
Exemple #27
0
 public int astar(Vertex start, Vertex goal, Heuristic h) {
   int count;
   Collection<Vertex> vertices_;
   Comparator<Vertex> comp;
   PriorityQueue<Vertex> fringe;
   count = 0;
   vertices_ = vertices.values();
   comp =
       new Comparator<Vertex>() {
         public int compare(Vertex i, Vertex j) {
           return (i.cost + i.estimate - j.cost - j.estimate);
         }
       }; // use estimates
   fringe = new PriorityQueue<Vertex>(20, comp);
   for (Vertex v : vertices_) {
     v.visited = false;
     v.cost = 999999;
   }
   start.cost = 0;
   start.parent = null;
   fringe.add(start);
   while (!fringe.isEmpty()) {
     Vertex v = fringe.remove(); // lowest-cost
     count++; // count nodes
     if (v.equals(goal)) { // if the goal is found, quit
       break;
     }
     if (!v.visited) {
       v.visited = true;
       for (Edge e : v.edges) {
         int newcost = v.cost + e.cost;
         if (newcost < e.target.cost) {
           e.target.cost = newcost;
           e.target.parent = v;
           e.target.estimate = h.fn(e.target, goal); // use heuristic
           fringe.add(e.target);
         }
       }
     }
   }
   return count;
 }
Exemple #28
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 #29
0
 public int dijkstra(Vertex s) {
   int count;
   Collection<Vertex> vertices_;
   Comparator<Vertex> comp;
   PriorityQueue<Vertex> fringe;
   count = 0;
   vertices_ = vertices.values();
   comp =
       new Comparator<Vertex>() {
         public int compare(Vertex i, Vertex j) {
           return (i.cost - j.cost);
         }
       };
   fringe = new PriorityQueue<Vertex>(20, comp);
   for (Vertex v : vertices_) {
     v.visited = false;
     v.cost = 999999;
   }
   s.cost = 0;
   s.parent = null;
   fringe.add(s);
   while (!fringe.isEmpty()) {
     Vertex v = fringe.remove(); // lowest-cost
     count++; // count nodes
     if (!v.visited) {
       v.visited = true;
       for (Edge e : v.edges) {
         int newcost = v.cost + e.cost;
         if (newcost < e.target.cost) {
           if (e.target.cost < 999999) // target on queue already?
           fringe.remove(e.target); // if yes, remove it.
           e.target.cost = newcost;
           e.target.parent = v;
           fringe.add(e.target);
         }
       }
     }
   }
   return count;
 }
Exemple #30
0
  static void solve(Scanner sc) throws IOException {
    int h = sc.nextInt();
    int w = sc.nextInt();
    int k = sc.nextInt();
    PriorityQueue<Node> pq = new PriorityQueue<Node>();
    for (int i = 0; i < h; i++) {
      String s = sc.next();
      for (int j = 0; j < w; j++) {
        grid[i][j] = s.charAt(j);
        dis[i][j] = grid[i][j] == '#' ? 0 : inf;
        if (grid[i][j] == 'S') pq.offer(new Node(i, j, 0));
      }
    }

    // Dijkstra
    // There is always a solution according to problem statement
    while (!pq.isEmpty()) {
      Node z = pq.poll();
      int x = z.x;
      int y = z.y;
      int d = z.dis;
      if (d > dis[x][y]) continue;
      if (x == 0 || x == h - 1 || y == 0 || y == w - 1) {
        System.out.println(d + 1);
        break;
      }
      for (int i = 0; i < 4; i++) {
        int nx = x + dx[i];
        int ny = y + dy[i];
        // if(nx<0||nx>=h||ny<0||ny>=w)
        //    continue;
        int nd = d + 1 + (grid[nx][ny] == '@' ? k : 0);
        if (nd < dis[nx][ny]) {
          dis[nx][ny] = nd;
          pq.offer(new Node(nx, ny, nd));
        }
      }
    }
  }