예제 #1
0
파일: Main.java 프로젝트: yulonglong/YouSiq
  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);
  }
예제 #2
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);
        }
      }
    }
  }
  public void methodsOfPQ() {
    PriorityQueue<Integer> pq = new PriorityQueue<Integer>(); // Default Constructor:
    //		Queue<Integer> pq = new PriorityQueue<Integer>();
    pq.add(10);
    pq.add(30);
    pq.add(50);
    pq.add(40);
    pq.add(20);
    System.out.println(pq); // [10, 20, 50, 40, 30]

    pq.offer(75); // add element randomly anywhere
    System.out.println(pq); // [10, 20, 50, 40, 30, 75]

    System.out.println(pq.peek()); // 10 | return head of queue and don't touch pq
    System.out.println(pq); // [10, 20, 50, 40, 30, 75]

    System.out.println(pq.poll()); // 10 | return head and also removes head from pq
    System.out.println(pq); // [20, 50, 40, 30, 75]

    System.out.println(pq.element()); // 20 | same as peek but throw exception if pq is empty
    System.out.println(pq); // [20, 50, 40, 30, 75]

    pq.remove(); // 20 | same as poll but throw exception when queue is empty
    System.out.println(pq); // [50, 40, 30, 75]

    List<Integer> ls = new ArrayList<Integer>();
    ls.add(1000);
    ls.add(2000);

    pq.addAll(ls);
    System.out.println(pq); // [30, 40, 50, 75, 1000, 2000]

    pq.removeAll(ls);
    System.out.println(pq); // [30, 40, 50, 75]

    ls.clear(); // empty ls
    ls.add(101);
    ls.add(102);
    pq.addAll(ls);
    pq.retainAll(ls); // all element will be removed except ls
    System.out.println(pq); // [101, 102]

    System.out.println(pq.containsAll(ls)); // true
    System.out.println("********************************************");

    //		Queue<String> q=new PriorityQueue<String>();
  }
예제 #4
0
파일: HW1.java 프로젝트: holasjuraj/vkti2
  public HW1() {
    // initialize
    Scanner in = new Scanner(System.in);
    N = in.nextInt();
    in.nextLine();
    E = new PriorityQueue<Edge>(N * N, EdgeComparator);
    open = new PriorityQueue<Edge>(N * N, EdgeComparator);
    for (int u = 0; u < N; u++) {
      for (int v = 0; v < u; v++) {
        int weight = in.nextInt();
        E.add(new Edge(v, u, weight));
      }
      in.nextLine();
    }
    in.close();

    // find minimum spanning tree
    int[] vDegs = new int[N];
    int v = 0;
    HashSet<Integer> usedV = new HashSet<Integer>(N * 2);
    usedV.add(v);

    while (usedV.size() < N) {
      open.addAll(takeOutgoingEdges(E, v));
      Edge newE = open.poll();
      int u;
      if (usedV.contains(newE.v1)) {
        u = newE.v1;
        v = newE.v2;
      } else {
        u = newE.v2;
        v = newE.v1;
      }
      usedV.add(v);
      vDegs[v]++;
      vDegs[u]++;
      takeOutgoingEdges(open, v);
    }

    // find maximal degree
    int maxI = 0, maxD = 0;
    for (int i = 0; i < N; i++) {
      if (vDegs[i] > maxD) {
        maxD = vDegs[i];
        maxI = i;
      }
    }

    // print
    for (int i = 0; i < N; i++) {
      int d = vDegs[i];
      if (i != maxI) {
        d -= 2;
      }
      System.out.print("" + d + " ");
    }
  }
예제 #5
0
 /**
  * Method to add a collection of elements.
  *
  * @param elements The collection of elements to add.
  * @return Whether they were added successfully.
  */
 public synchronized boolean addAll(java.util.Collection elements) {
   boolean success = delegate.addAll(elements);
   if (success) {
     makeDirty();
     if (ownerOP != null && !ownerOP.getExecutionContext().getTransaction().isActive()) {
       ownerOP.getExecutionContext().processNontransactionalUpdate();
     }
   }
   return success;
 }
  /**
   * A* algorithm
   *
   * @param vehicle the considered vehicle
   * @param available the available tasks of the world
   * @param carried the tasks picked up and currently carried by the vehicle
   * @return a plan (list of actions)
   */
  public static Plan computeAStar(Vehicle vehicle, TaskSet available, TaskSet carried) {
    Plan plan = null;

    ArrayList<Task> availableTasks = new ArrayList<Task>(available);
    ArrayList<Task> carriedTasks = new ArrayList<Task>(carried);

    PriorityQueue<State> Q =
        new PriorityQueue<State>(1, new StateComparator()); // States we will have to visit
    ArrayList<State> C = new ArrayList<State>(); // States we have already visited, prevent cycles

    City initialCity = vehicle.getCurrentCity();
    State initialState =
        new State(
            initialCity, availableTasks, carriedTasks, new ArrayList<Action>(), vehicle, 0, 0);

    Q.add(initialState);

    boolean foundFinalState = false;
    State finalState = null;

    while (!foundFinalState) {

      if (Q.isEmpty()) {
        foundFinalState = true;

      } else {
        State visitingState = Q.poll();

        if (visitingState.isFinal()) {
          finalState = visitingState;
          foundFinalState = true;
        } else if (!C.contains(visitingState)
            || (C.contains(visitingState)
                && C.get(C.indexOf(visitingState)).heuristicValue > visitingState.heuristicValue)) {
          C.add(visitingState);
          Q.addAll(visitingState.next()); // Hopefully at the end of the list
        }
      }
    }

    if (finalState != null) {
      plan = new Plan(vehicle.getCurrentCity(), finalState.actionList);
    }

    return plan;
  }
예제 #7
0
 /**
  * Method to initialise the SCO from an existing value.
  *
  * @param c The object to set from
  * @param forInsert Whether the object needs inserting in the datastore with this value
  * @param forUpdate Whether to update the datastore with this value
  */
 public void initialise(java.util.PriorityQueue c, boolean forInsert, boolean forUpdate) {
   if (c != null) {
     initialiseDelegate();
     delegate.addAll(c);
   } else {
     initialiseDelegate();
   }
   if (NucleusLogger.PERSISTENCE.isDebugEnabled()) {
     NucleusLogger.PERSISTENCE.debug(
         Localiser.msg(
             "023003",
             ownerOP.getObjectAsPrintable(),
             ownerMmd.getName(),
             "" + size(),
             SCOUtils.getSCOWrapperOptionsMessage(true, false, false, false)));
   }
 }
  /**
   * Use A star Search to solve the TSP problem
   *
   * @param question
   * @return
   * @throws Exception
   */
  public static TSPSolution solve(TSPQuestion question) throws Exception {
    TSPStatistics statistics = new TSPStatistics();

    TSPNode initial = new TSPNode(question);
    PriorityQueue<TSPNode> queue = new PriorityQueue<TSPNode>(600000, TSPNode.NodeComparator);
    queue.add(initial);
    statistics.addCounter(1);
    TSPNode current = null;
    while (true) {
      current = queue.poll(); // get the node with the minimal f value
      List<TSPNode> nodeList = current.getSuccessors();
      statistics.addCounter(nodeList.size());
      if (nodeList.isEmpty()) break;
      else queue.addAll(nodeList);
    }
    statistics.timerStop();
    return new TSPSolution(question, current.getVisitedCities(), current.getBackDist(), statistics);
  }
 /**
  * Sorts the operators topologically, i.e. such that operator <var>i</var> in the returned
  * ordering has dependencies (i.e. connected {@link InputPort}s) only from operators
  * <var>0..i-1</var>.
  */
 public Vector<Operator> topologicalSort() {
   final Map<Operator, Integer> originalIndices = new HashMap<Operator, Integer>();
   for (int i = 0; i < operators.size(); i++) {
     originalIndices.put(operators.get(i), i);
   }
   EdgeCounter counter = new EdgeCounter(operators);
   for (Operator child : getOperators()) {
     for (OutputPort out : child.getOutputPorts().getAllPorts()) {
       InputPort dest = out.getDestination();
       if (dest != null) {
         counter.incNumEdges(dest.getPorts().getOwner().getOperator());
       }
     }
   }
   Vector<Operator> sorted = new Vector<Operator>();
   PriorityQueue<Operator> independentOperators =
       new PriorityQueue<Operator>(
           Math.max(1, operators.size()),
           new Comparator<Operator>() {
             @Override
             public int compare(Operator o1, Operator o2) {
               return originalIndices.get(o1) - originalIndices.get(o2);
             }
           });
   independentOperators.addAll(counter.getIndependentOperators());
   while (!independentOperators.isEmpty()) {
     Operator first = independentOperators.poll();
     sorted.add(first);
     for (OutputPort out : first.getOutputPorts().getAllPorts()) {
       InputPort dest = out.getDestination();
       if (dest != null) {
         Operator destOp = dest.getPorts().getOwner().getOperator();
         if (counter.decNumEdges(destOp) == 0) {
           // independentOperators.addFirst(destOp);
           independentOperators.add(destOp);
         }
       }
     }
   }
   return sorted;
 }
예제 #10
0
  public static void main(String[] args) {
    PriorityQueue<Integer> priorityQueue = new PriorityQueue<Integer>();
    Random rand = new Random(47);

    for (int i = 0; i < 10; i++) {
      priorityQueue.offer(rand.nextInt(i + 10));
    }

    QueueDemo.printQueue(priorityQueue);

    List<Integer> ints = Arrays.asList(25, 22, 20, 18, 14, 9, 3, 1, 1, 2, 3, 9, 14, 18, 21, 23, 25);
    priorityQueue = new PriorityQueue<Integer>(ints);
    QueueDemo.printQueue(priorityQueue);
    priorityQueue = new PriorityQueue<Integer>(ints.size(), Collections.reverseOrder());
    priorityQueue.addAll(ints);
    QueueDemo.printQueue(priorityQueue);

    String fact = "EDUCATION SHOULD ESCHEW OBFUSCATION";
    List<String> strings = Arrays.asList(fact.split(""));
    PriorityQueue<String> stringPQ = new PriorityQueue<String>(strings);
    QueueDemo.printQueue(stringPQ);
  }
예제 #11
0
  /** Implementace vlastniho algoritmu Astar */
  public int computeBuckets() {
    /* init */
    int cesta = 0;
    StavyKybliku aktualni = null;
    StavyKybliku startovni = nalevna.getAktualniStav();

    System.out.println("Startuji Astar algoritmus:");
    System.out.println("- startovni stav: " + startovni.getAktualniObsahyString());
    System.out.println("- cilovy stav: " + startovni.getCiloveObsahyString());

    /* vlozime do fronty pocatecni uzel a odstartujeme prubeh */
    prioritniFronta.add(startovni.clone());
    nalevna.addOpenedStav(startovni.clone());

    /* dokud neni fronta prazdna, tak prochazej uzly */
    /* vyjmi prvni uzel ve fronte a expanduj */
    while (!prioritniFronta.isEmpty()) {

      // aktualni = fronta.pop();
      aktualni = prioritniFronta.poll();
      // System.out.println("Vyjimam z fronty " + aktualni.getAktualniObsahyString());
      // System.out.print("Jeho rodice jsou: "); nalevna.vypisFrontuStavu(startovni.getParents());

      // zjistime nasledniky pro zarazeni do fronty a vlozime
      prioritniFronta.addAll(super.ziskejNoveStavy(aktualni));
      cesta++;

      // pokud je to hledany stav, tak return
      if (aktualni.isCilovy()) {
        System.out.println("Nasli jsme cilovy stav " + aktualni.getAktualniObsahyString());
        nalevna.setAktualniStav(aktualni);
        return cesta;
      }
    }
    System.out.println("Nenasli jsme cilovy stav.");
    return cesta;
  }
예제 #12
0
  public void solve() {
    PriorityQueue<PuzzleBoard> queue =
        new PriorityQueue<>(
            1000,
            new Comparator<PuzzleBoard>() {
              @Override
              public int compare(PuzzleBoard lhs, PuzzleBoard rhs) {
                return lhs.priority() - rhs.priority();
              }
            });

    PuzzleBoard currBoard = new PuzzleBoard(puzzleBoard);
    currBoard.initializePreviousBoard();

    queue.add(currBoard);

    while (!queue.isEmpty()) {
      currBoard = queue.poll();
      if (currBoard.resolved()) {
        ArrayList<PuzzleBoard> arrayList = new ArrayList();

        while (currBoard.getPreviousBoard() != null) {
          arrayList.add(currBoard);
          currBoard = currBoard.getPreviousBoard();
        }
        Collections.reverse(arrayList);

        animation = new ArrayList<>();
        animation.addAll(arrayList);
        invalidate();
        break;
      } else {
        queue.addAll(currBoard.neighbours());
      }
    }
  }
예제 #13
0
  public Graph(String dataFile, String outputFile, float cutoff, boolean backwards)
      throws FileNotFoundException {
    this.cutoff = cutoff;
    this.backwards = backwards;
    this.writer = new PrintWriter(outputFile);
    FileReader reader = new FileReader(dataFile);
    Scanner scanner = new Scanner(reader);

    numVertices = scanner.nextInt();
    numEdges = scanner.nextInt();
    vertices = new ArrayList<Vertex>();
    priorityQueue = new PriorityQueue<Vertex>();
    finishedVertices = new HashSet<Vertex>();
    vertices.add(new Vertex(-1, -1, -1, -1, -1));

    for (int i = 0; i < numVertices; i++) {
      if (!backwards ? i == 0 : i == numVertices) {
        vertices.add(new Vertex(i + 1, -1, 0, 0, 0));
      } else {
        vertices.add(new Vertex(i + 1, -1, 0, 0, Long.MAX_VALUE));
      }
    }

    while (scanner.hasNextLine() && scanner.hasNextInt()) {
      int sourceVertex = scanner.nextInt();
      int destVertex = scanner.nextInt();
      ArrayList<Integer> edgeWeight = new ArrayList<Integer>();
      edgeWeight.add(scanner.nextInt());
      edgeWeight.add(scanner.nextInt());
      vertices.get(sourceVertex).adjacencies.put(destVertex, edgeWeight);
      vertices.get(destVertex).adjacencies.put(sourceVertex, edgeWeight);
    }

    priorityQueue.addAll(vertices);
    priorityQueue.remove();
  }
예제 #14
0
파일: Main.java 프로젝트: yulonglong/YouSiq
  private static PriorityQueue<Result> match(
      MFCC mfcc, File sampleFilePath, String databaseFilePath)
      throws FileNotFoundException, IOException, ClassNotFoundException {
    System.err.println("Processing sample...");
    Timer.greset();

    //		Song sample = (Song)ObjectIO.readObject("C:/Users/Ian/Google
    // Drive/Music/TestcaseVideo/tc5.db");
    //		double sampleMfcc[][] = sample.getMfcc();

    short[] sampleData = WaveIO.readWave(sampleFilePath);
    double sampleMfcc[][] = mfcc.process(sampleData);
    int sampleLength = sampleMfcc.length;

    System.err.println("Sample processed. Matching...");
    Timer.gtime();

    ObjectInputStream ois = new ObjectInputStream(new FileInputStream(databaseFilePath));
    PriorityQueue<Result> results = new PriorityQueue<Result>();

    while (true) {
      Song song;
      try {
        song = (Song) ois.readObject();
      } catch (EOFException e) {
        break;
      }

      //			System.out.println(song);
      //			if(!song.getArtist().equals("Steve Jablonsky")) continue;
      //			else System.out.println("Steve Jablonsky");

      PriorityQueue<Result> songResults = new PriorityQueue<Result>();

      int songLength = song.getMfcc().length;

      int i, j, k;
      for (i = 0; i < songLength; i++) {
        for (k = 0; k < sampleLength; k++) { // sampleOffset
          double totalMfccScores = 0.0;

          for (j = k; j < sampleLength && i + j < songLength; j++) {
            double mfccSimilarity = Cosine.getDistance(song.getMfcc()[i + j], sampleMfcc[j]);
            if (mfccSimilarity < MFCC_SIMILARITY_THRESHOLD) break;

            totalMfccScores += mfccSimilarity;
          }

          int frameCount = j - k;

          if (frameCount >= FRAME_COUNT_ACCEPTANCE_THRESHOLD
              && totalMfccScores / frameCount >= MFCC_ACCEPTANCE_THRESHOLD) {
            songResults.add(
                new Result(totalMfccScores / frameCount, i, k, frameCount, song.toString()));
          }
        }
      }

      //			System.out.println("PRE: " + songResults.size());
      flattenResults(songResults, songLength, sampleLength);
      //			System.out.println("POST: " + songResults.size());
      results.addAll(songResults);
    }

    ois.close();

    removeMultipleHits(results, sampleLength);

    //		System.out.println("Results count: " + results.size());
    //		int printCount = 0;
    //		while(!results.isEmpty() && printCount != 100) {
    //			System.err.println(results.poll());
    //			printCount++;
    //		}

    for (Result i : results) System.err.println(i);
    System.err.println();

    // Reorder results by sample start time
    PriorityQueue<Result> tempResults = new PriorityQueue<>(Result.SAMPLE_START_TIME_COMPARATOR);
    tempResults.addAll(results);
    results = tempResults;

    System.err.println("Matching done.");
    Timer.gtime();

    return results;
  }
예제 #15
0
 public ResourceList(PriorityQueue<T> tmp) {
   resources = new PriorityQueue<T>();
   resources.addAll(tmp);
 }
예제 #16
0
 public void makeANewSet() {
   passiveCache.addAll(activeCache);
   activeCache.clear();
 }
예제 #17
0
 /**
  * A convenience function for dumping all the elements of the received list into this class'
  * instance.
  *
  * @param items The list to union.
  */
 public void addResources(ResourceList<T> items) {
   resources.addAll(items.getResourceQueue());
 }