Java Code Examples for java.util.TreeSet#pollFirst()

The following examples show how to use java.util.TreeSet#pollFirst() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
/**
 * retainAll(c) retains only those elements of c and reports true if changed
 */
public void testRetainAll() {
    TreeSet q = populatedSet(SIZE);
    TreeSet p = populatedSet(SIZE);
    for (int i = 0; i < SIZE; ++i) {
        boolean changed = q.retainAll(p);
        if (i == 0)
            assertFalse(changed);
        else
            assertTrue(changed);

        assertTrue(q.containsAll(p));
        assertEquals(SIZE - i, q.size());
        p.pollFirst();
    }
}
 
Example 2
private BiMap<String, String> mapConfiguredToRegisteredClientNames(List<String> configuredClientNamesForTest, ClientRegistry clientRegistry)
{
    BiMap<String, String> configuredToRegisteredNameMap = HashBiMap.create();

    TreeSet<String> registeredClients = new TreeSet<String>(clientRegistry.getClients());
    for (String configuredClientName : configuredClientNamesForTest)
    {
        String allocatedClientName = registeredClients.pollFirst();
        if (allocatedClientName == null)
        {
            throw new IllegalArgumentException("Too few clients in registry " + clientRegistry + " configured clients " + configuredClientNamesForTest);
        }
        configuredToRegisteredNameMap.put(configuredClientName, allocatedClientName);
    }

    return configuredToRegisteredNameMap;
}
 
Example 3
Source Project: j2objc   File: TreeSetTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * size changes when elements added and removed
 */
public void testSize() {
    TreeSet q = populatedSet(SIZE);
    for (int i = 0; i < SIZE; ++i) {
        assertEquals(SIZE - i, q.size());
        q.pollFirst();
    }
    for (int i = 0; i < SIZE; ++i) {
        assertEquals(i, q.size());
        q.add(new Integer(i));
    }
}
 
Example 4
/**
 * size changes when elements added and removed
 */
public void testSize() {
    TreeSet q = populatedSet(SIZE);
    for (int i = 0; i < SIZE; ++i) {
        assertEquals(SIZE - i, q.size());
        q.pollFirst();
    }
    for (int i = 0; i < SIZE; ++i) {
        assertEquals(i, q.size());
        q.add(new Integer(i));
    }
}
 
Example 5
Source Project: j2objc   File: TreeSetTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * removeAll(c) removes only those elements of c and reports true if changed
 */
public void testRemoveAll() {
    for (int i = 1; i < SIZE; ++i) {
        TreeSet q = populatedSet(SIZE);
        TreeSet p = populatedSet(i);
        assertTrue(q.removeAll(p));
        assertEquals(SIZE - i, q.size());
        for (int j = 0; j < i; ++j) {
            Integer x = (Integer)(p.pollFirst());
            assertFalse(q.contains(x));
        }
    }
}
 
Example 6
/**
 * removeAll(c) removes only those elements of c and reports true if changed
 */
public void testRemoveAll() {
    for (int i = 1; i < SIZE; ++i) {
        TreeSet q = populatedSet(SIZE);
        TreeSet p = populatedSet(i);
        assertTrue(q.removeAll(p));
        assertEquals(SIZE - i, q.size());
        for (int j = 0; j < i; ++j) {
            Integer x = (Integer)(p.pollFirst());
            assertFalse(q.contains(x));
        }
    }
}
 
Example 7
Source Project: AlgoCS   File: ThirdMaximum_414.java    License: MIT License 5 votes vote down vote up
public static int thirdMax(int[] nums) {
    TreeSet<Integer> set = new TreeSet<>();
    for (int i = 0; i < nums.length; i++) {
        set.add(nums[i]);
        if (set.size() > 3) set.pollFirst();
    }
    return set.size() < 3 ? set.last() : set.first();
}
 
Example 8
public Set<WordEntry> distance(String queryWord) {

		float[] center = wordMap.get(queryWord);
		if (center == null) {
			return Collections.emptySet();
		}

		int resultSize = wordMap.size() < topNSize ? wordMap.size() : topNSize;
		TreeSet<WordEntry> result = new TreeSet<WordEntry>();

		double min = Float.MIN_VALUE;
		for (Entry<String, float[]> entry : wordMap.entrySet()) {
			float[] vector = entry.getValue();
			float dist = 0;
			for (int i = 0; i < vector.length; i++) {
				dist += center[i] * vector[i];
			}

			if (dist > min) {
				result.add(new WordEntry(entry.getKey(), dist));
				if (resultSize < result.size()) {
					result.pollLast();
				}
				min = result.last().score;
			}
		}
		result.pollFirst();

		return result;
	}
 
Example 9
public Set<WordEntry> distance(List<String> words) {

		float[] center = null;
		for (String word : words) {
			center = sum(center, wordMap.get(word));
		}

		if (center == null) {
			return Collections.emptySet();
		}

		int resultSize = wordMap.size() < topNSize ? wordMap.size() : topNSize;
		TreeSet<WordEntry> result = new TreeSet<WordEntry>();

		double min = Float.MIN_VALUE;
		for (Entry<String, float[]> entry : wordMap.entrySet()) {
			float[] vector = entry.getValue();
			float dist = 0;
			for (int i = 0; i < vector.length; i++) {
				dist += center[i] * vector[i];
			}

			if (dist > min) {
				result.add(new WordEntry(entry.getKey(), dist));
				if (resultSize < result.size()) {
					result.pollLast();
				}
				min = result.last().score;
			}
		}
		result.pollFirst();

		return result;
	}
 
Example 10
public static void main (String [] args) throws Exception {
	boolean [] notPrime=new boolean [1000001];
	for (int i=2;i*i<notPrime.length;i++) if (!notPrime[i]) for (int i2=i*i;i2<notPrime.length;i2+=i) notPrime[i2]=true;
	for (int i=2;i<notPrime.length;i++) if (!notPrime[i]) primes.add(i);
	
	BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
	int T=Integer.parseInt(br.readLine());
	for (int t=0;t<T;t++) {
		StringTokenizer st=new StringTokenizer(br.readLine());
		int min=Integer.parseInt(st.nextToken());
		int max=Integer.parseInt(st.nextToken());
		
		HashMap<Integer, Integer> counter=new HashMap<>();
		TreeSet<Integer> subset = new TreeSet<>(primes.subSet(min, max+1));
		Integer lastNum=subset.pollFirst();
		if (lastNum!=null) {
			for (int n : subset) {
				int diff=n-lastNum;
				lastNum=n;
				counter.put(diff,counter.getOrDefault(diff,0)+1);
			}
		}
		
		int maxCounter=-1;
		for (int v : counter.values()) maxCounter=Math.max(maxCounter, v);
		
		int maxCounterCount=0;
		int maxCounterKey=-1;
		for (int key : counter.keySet()) if (counter.get(key)==maxCounter) {
			maxCounterKey=key;
			maxCounterCount++;
		}
		
		if (maxCounterKey==-1 || maxCounterCount>1) System.out.println("No jumping champion");
		else System.out.println("The jumping champion is "+maxCounterKey);
	}
}
 
Example 11
private void handleDemandedTick() throws IOException {
    wantedTick = demandedTick;
    demandedTick = null;
    int diff = wantedTick - tick;

    if (diff >= 0 && diff <= 5) {
        return;
    }

    resetSteps = new LinkedList<>();
    resetSteps.add(new ResetStep(LoopController.Command.RESET_START, null));
    if (diff < 0 || engineType.isFullPacketSeekAllowed()) {
        TreeSet<PacketPosition> seekPositions = getResetPacketsBeforeTick(wantedTick);
        resetSteps.add(new ResetStep(LoopController.Command.RESET_CLEAR, null));
        while (seekPositions.size() > 0) {
            PacketPosition pp = seekPositions.pollFirst();
            switch (pp.getKind()) {
                case STRINGTABLE:
                case FULL_PACKET:
                    resetSteps.add(new ResetStep(LoopController.Command.CONTINUE, pp.getOffset()));
                    resetSteps.add(new ResetStep(LoopController.Command.RESET_ACCUMULATE, null));
                    if (seekPositions.size() == 0) {
                        resetSteps.add(new ResetStep(LoopController.Command.RESET_APPLY, null));
                    }
                    break;
                case SYNC:
                    if (seekPositions.size() == 0) {
                        resetSteps.add(new ResetStep(LoopController.Command.CONTINUE, pp.getOffset()));
                        resetSteps.add(new ResetStep(LoopController.Command.RESET_APPLY, null));
                    }
                    break;
            }
        }
    }
    resetSteps.add(new ResetStep(LoopController.Command.RESET_FORWARD, null));
    resetSteps.add(new ResetStep(LoopController.Command.RESET_COMPLETE, null));
    loopController.controllerFunc = seekLoopControl;
}
 
Example 12
Source Project: j2objc   File: TreeSetTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * isEmpty is true before add, false after
 */
public void testEmpty() {
    TreeSet q = new TreeSet();
    assertTrue(q.isEmpty());
    q.add(new Integer(1));
    assertFalse(q.isEmpty());
    q.add(new Integer(2));
    q.pollFirst();
    q.pollFirst();
    assertTrue(q.isEmpty());
}
 
Example 13
Source Project: gifencoder   File: MedianCutQuantizer.java    License: Apache License 2.0 5 votes vote down vote up
@Override public Set<Color> quantize(Multiset<Color> originalColors, int maxColorCount) {
  TreeSet<Cluster> clusters = new TreeSet<>(new ClusterSpreadComparator());
  clusters.add(new Cluster(originalColors));

  while (clusters.size() < maxColorCount) {
    Cluster clusterWithLargestSpread = clusters.pollFirst();
    clusters.addAll(clusterWithLargestSpread.split());
  }

  Set<Color> clusterCentroids = new HashSet<>();
  for (Cluster cluster : clusters) {
    clusterCentroids.add(Color.getCentroid(cluster.colors));
  }
  return clusterCentroids;
}
 
Example 14
private Set<String> expandDependencies ( final Set<String> aspects )
{
    try ( Handle handle = Profile.start ( ModifiableChannelAdapter.class.getName () + ".expandDependencies" ) )
    {
        final Map<String, ChannelAspectInformation> all = this.aspectProcessor.getAspectInformations ();

        final Set<String> result = new HashSet<> ();
        final TreeSet<String> requested = new TreeSet<> ();
        requested.addAll ( aspects );

        while ( !requested.isEmpty () )
        {
            final String id = requested.pollFirst ();

            if ( result.add ( id ) )
            {
                final ChannelAspectInformation asp = all.get ( id );

                final Set<String> reqs = new HashSet<> ( asp.getRequires () );
                reqs.removeAll ( requested ); // remove all which are already present
                requested.addAll ( reqs ); // add to request list
            }
        }

        return result;
    }
}
 
Example 15
Source Project: Word2Vec   File: Word2VEC.java    License: Apache License 2.0 5 votes vote down vote up
public Set<WordEntry> distance(List<String> words) {

		float[] center = null;
		for (String word : words) {
			center = sum(center, wordMap.get(word));
		}

		if (center == null) {
			return Collections.emptySet();
		}

		int resultSize = wordMap.size() < topNSize ? wordMap.size() : topNSize;
		TreeSet<WordEntry> result = new TreeSet<WordEntry>();

		double min = Float.MIN_VALUE;
		for (Map.Entry<String, float[]> entry : wordMap.entrySet()) {
			float[] vector = entry.getValue();
			float dist = 0;
			for (int i = 0; i < vector.length; i++) {
				dist += center[i] * vector[i];
			}

			if (dist > min) {
				result.add(new WordEntry(entry.getKey(), dist));
				if (resultSize < result.size()) {
					result.pollLast();
				}
				min = result.last().score;
			}
		}
		result.pollFirst();

		return result;
	}
 
Example 16
Source Project: Word2Vec   File: Word2Vec.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 获取相似词语
 * @param word
 * @param maxReturnNum
 * @return
 */
public Set<WordEntry> getSimilarWords(String word, int maxReturnNum) {
    if (loadModel == false)
        return null;
    float[] center = getWordVector(word);
    if (center == null) {
        return Collections.emptySet();
    }
    int resultSize = vec.getWords() < maxReturnNum ? vec.getWords() : maxReturnNum;
    TreeSet<WordEntry> result = new TreeSet<WordEntry>();
    double min = Double.MIN_VALUE;
    for (Map.Entry<String, float[]> entry : vec.getWordMap().entrySet()) {
        float[] vector = entry.getValue();
        float dist = calDist(center, vector);
        if (result.size() <= resultSize) {
            result.add(new WordEntry(entry.getKey(), dist));
            min = result.last().score;
        } else {
            if (dist > min) {
                result.add(new WordEntry(entry.getKey(), dist));
                result.pollLast();
                min = result.last().score;
            }
        }
    }
    result.pollFirst();
    return result;
}
 
Example 17
public void testMultipleMessageWriting() throws Exception {
  // Randomly write a mixture of open and close events and random junk
  try (TestDirectory dir = new TestDirectory()) {
    final FileUsageLoggingClient client = new FileUsageLoggingClient(dir, new UsageConfiguration(new Properties()), false);
    final Date date = new Date();
    final SimpleDateFormat df = new SimpleDateFormat("yyyy-MM");
    final String expectedFilename = df.format(date) + ".usage";
    final File file = new File(dir, expectedFilename);
    final Random r = new Random();
    final TreeSet<UUID> notYetEnded = new TreeSet<>();
    for (int k = 0; k < 200; ++k) {
      switch (r.nextInt(3)) {
        case 0:
          final UUID code = UUID.randomUUID();
          client.recordBeginning("unitTest", code);
          notYetEnded.add(code);
          break;
        case 1:
          final UUID closeCode = notYetEnded.pollFirst();
          if (closeCode != null) {
            client.recordEnd(r.nextInt(), "unitTest", closeCode, true);
          }
          break;
        default:
          FileUtils.appendToFile(file,  JUNK[r.nextInt(JUNK.length)] + StringUtils.LS);
          break;
      }
    }
    // Some messages will not be ended, but that is ok
    final File[] files = dir.listFiles();
    assertNotNull(files);
    assertEquals(1, files.length);
    final File usageOut = files[0];
    assertEquals(df.format(new Date()) + ".usage", usageOut.getName());
    final String str = FileUtils.fileToString(usageOut);
    //System.out.println(str);
    final String[] outputLines = str.split("\r\n|\n");
    String prevHash = "";
    for (final String line : outputLines) {
      final String[] line1 = line.split("\tS="); //splits into message and md5 sum
      if (line1.length > 1) {
        assertEquals(MD5Utils.md5(prevHash + line1[0]), line1[1]);
        prevHash = line1[1];
      }
    }
  }
}
 
Example 18
/**
 * Constructor for the decomposition.
 *
 * @param matrix real matrix.
 */
public OrderedComplexEigenDecomposition(final RealMatrix matrix) {
    super(matrix);

    final FieldMatrix<Complex> D = this.getD();
    final FieldMatrix<Complex> V = this.getV();

    // getting eigen values
    TreeSet<Complex> eigenValues = new TreeSet<>(new ComplexComparator());
    for (int ij = 0; ij < matrix.getRowDimension(); ij++) {
        eigenValues.add(D.getEntry(ij, ij));
    }

    // ordering
    for (int ij = 0; ij < matrix.getRowDimension() - 1; ij++) {
        final Complex eigValue = eigenValues.pollFirst();
        int currentIndex = -1;
        // searching the current index
        for (currentIndex = ij; currentIndex < matrix.getRowDimension(); currentIndex++) {
            Complex compCurrent = D.getEntry(currentIndex, currentIndex);
            if (eigValue.equals(compCurrent)) {
                break;
            }
        }

        if (ij == currentIndex) {
            continue;
        }

        // exchanging D
        Complex previousValue = D.getEntry(ij, ij);
        D.setEntry(ij, ij, eigValue);
        D.setEntry(currentIndex, currentIndex, previousValue);

        // exchanging V
        final Complex[] previousColumnV = V.getColumn(ij);
        V.setColumn(ij, V.getColumn(currentIndex));
        V.setColumn(currentIndex, previousColumnV);
    }

    checkDefinition(matrix);
}
 
Example 19
@Override
public void finish() throws IOException {
  NamedList<Double> analytics = new NamedList<Double>();
  @SuppressWarnings({"unchecked", "rawtypes"})
  NamedList<Integer> topFreq = new NamedList();

  @SuppressWarnings({"unchecked", "rawtypes"})
  NamedList<Integer> allFreq = new NamedList();

  rb.rsp.add("featuredTerms", analytics);
  rb.rsp.add("docFreq", topFreq);
  rb.rsp.add("numDocs", count);

  TreeSet<TermWithScore> topTerms = new TreeSet<>();

  double numDocs = count;
  double pc = numPositiveDocs / numDocs;
  double entropyC = binaryEntropy(pc);

  Terms terms = ((SolrIndexSearcher)searcher).getSlowAtomicReader().terms(field);
  TermsEnum termsEnum = terms == null ? TermsEnum.EMPTY : terms.iterator();
  BytesRef term;
  PostingsEnum postingsEnum = null;
  while ((term = termsEnum.next()) != null) {
    postingsEnum = termsEnum.postings(postingsEnum);
    int xc = 0;
    int nc = 0;
    while (postingsEnum.nextDoc() != DocIdSetIterator.NO_MORE_DOCS) {
      if (positiveSet.get(postingsEnum.docID())) {
        xc++;
      } else if (negativeSet.get(postingsEnum.docID())) {
        nc++;
      }
    }

    int docFreq = xc+nc;

    double entropyContainsTerm = binaryEntropy( (double) xc / docFreq );
    double entropyNotContainsTerm = binaryEntropy( (double) (numPositiveDocs - xc) / (numDocs - docFreq + 1) );
    double score = entropyC - ( (docFreq / numDocs) * entropyContainsTerm + (1.0 - docFreq / numDocs) * entropyNotContainsTerm);

    topFreq.add(term.utf8ToString(), docFreq);
    if (topTerms.size() < numTerms) {
      topTerms.add(new TermWithScore(term.utf8ToString(), score));
    } else  {
      if (topTerms.first().score < score) {
        topTerms.pollFirst();
        topTerms.add(new TermWithScore(term.utf8ToString(), score));
      }
    }
  }

  for (TermWithScore topTerm : topTerms) {
    analytics.add(topTerm.term, topTerm.score);
    topFreq.add(topTerm.term, allFreq.get(topTerm.term));
  }

  if (this.delegate instanceof DelegatingCollector) {
    ((DelegatingCollector) this.delegate).finish();
  }
}
 
Example 20
/**
 * Uses an A* search to find the "optimal" path to the destination coordinates.
 * Ignores move cost and makes note of hexes that need to be cleared for the path to
 * be viable.
 */
public BulldozerMovePath findPathToCoords(Entity entity, Set<Coords> destinationCoords, boolean jump, BoardClusterTracker clusterTracker) {
    BulldozerMovePath startPath = new BulldozerMovePath(entity.getGame(), entity);
    
    // if we're calculating a jump path and the entity has jump mp and can jump, start off with a jump
    // if we're trying to calc a jump path and the entity does not have jump mp, we're done
    if(jump && (startPath.getCachedEntityState().getJumpMPWithTerrain() > 0) &&
            !entity.isProne() && !entity.isHullDown() && 
            (entity.getGame().getPlanetaryConditions().getWindStrength() != PlanetaryConditions.WI_TORNADO_F4)) {
        startPath.addStep(MoveStepType.START_JUMP);
    // if we specified a jump path, but can't actually jump
    } else if (jump) {
        return null;
    // can't "climb into" anything while jumping
    } else { 
        if(entity.hasETypeFlag(Entity.ETYPE_INFANTRY)) {
            startPath.addStep(MoveStepType.CLIMB_MODE_OFF);
        } else {
            startPath.addStep(MoveStepType.CLIMB_MODE_ON);
        }
    }
    
    // if we're on the ground, let's try to get up first before moving 
    if(entity.isProne() || entity.isHullDown()) {
        startPath.addStep(MoveStepType.GET_UP);
        
        // if we can't even get up, no need to do anything else
        if(!startPath.isMoveLegal()) {
            return null;
        }
    }

    Coords closest = getClosestCoords(destinationCoords, entity);
    // if we can't at all get to the coordinates with this entity, don't bother with the rest 
    if (closest == null) {
        return null;
    }
    
    movePathComparator = new AStarComparator(closest);
    maximumCost = Integer.MAX_VALUE;
    
    TreeSet<BulldozerMovePath> candidates = new TreeSet<>(movePathComparator);
    candidates.add(startPath);

    // a collection of coordinates we've already visited, so we don't loop back.
    Map<Coords, BulldozerMovePath> shortestPathsToCoords = new HashMap<>();
    shortestPathsToCoords.put(startPath.getFinalCoords(), startPath);
    BulldozerMovePath bestPath = null;

    while(!candidates.isEmpty()) {
        BulldozerMovePath currentPath = candidates.pollFirst();
        
        candidates.addAll(generateChildNodes(currentPath, shortestPathsToCoords, clusterTracker, closest));      
        
        if(destinationCoords.contains(currentPath.getFinalCoords()) &&
                ((bestPath == null) || (movePathComparator.compare(bestPath, currentPath) > 0))) {
            bestPath = currentPath;
            maximumCost = bestPath.getMpUsed() + bestPath.getLevelingCost();
        }
    }
  
    return bestPath;
}