/** * Checks that actual number of instances with different statuses are equal to expected number of * instances with matching statuses. * * @param instancesResult kind of response from API which should contain information about * instances * <p>All parameters below reflect number of expected instances with some kind of status. * @param totalCount total number of instances. * @param missingCount number of running instances. * @param emptyCount number of suspended instance. * @param partialCount number of waiting instance. * @param availableCount number of killed instance. */ private void validateResponse( FeedInstanceResult instancesResult, int totalCount, int missingCount, int emptyCount, int partialCount, int availableCount) { FeedInstanceResult.Instance[] instances = instancesResult.getInstances(); LOGGER.info("instances: " + Arrays.toString(instances)); Assert.assertNotNull(instances, "instances should be not null"); Assert.assertEquals(instances.length, totalCount, "Total Instances"); List<String> statuses = new ArrayList<>(); for (FeedInstanceResult.Instance instance : instances) { Assert.assertNotNull(instance.getCluster()); Assert.assertNotNull(instance.getInstance()); Assert.assertNotNull(instance.getStatus()); Assert.assertNotNull(instance.getUri()); Assert.assertNotNull(instance.getCreationTime()); Assert.assertNotNull(instance.getSize()); final String status = instance.getStatus(); LOGGER.info("status: " + status + ", instance: " + instance.getInstance()); statuses.add(status); } Assert.assertEquals( Collections.frequency(statuses, "MISSING"), missingCount, "Missing Instances"); Assert.assertEquals(Collections.frequency(statuses, "EMPTY"), emptyCount, "Empty Instances"); Assert.assertEquals( Collections.frequency(statuses, "PARTIAL"), partialCount, "Partial Instances"); Assert.assertEquals( Collections.frequency(statuses, "AVAILABLE"), availableCount, "Available Instances"); }
/** * Derives the list of column names suitable for NATURAL JOIN. These are the columns that occur * exactly once on each side of the join. * * @param leftRowType Row type of left input to the join * @param rightRowType Row type of right input to the join * @return List of columns that occur once on each side */ public static List<String> deriveNaturalJoinColumnList( RelDataType leftRowType, RelDataType rightRowType) { List<String> naturalColumnNames = new ArrayList<String>(); final List<String> leftNames = leftRowType.getFieldNames(); final List<String> rightNames = rightRowType.getFieldNames(); for (String name : leftNames) { if ((Collections.frequency(leftNames, name) == 1) && (Collections.frequency(rightNames, name) == 1)) { naturalColumnNames.add(name); } } return naturalColumnNames; }
public boolean updateCol(int col) { ArrayList<Integer> colList = new ArrayList(); ArrayList<Integer> numsToUpdate = new ArrayList(); ArrayList<Integer> possibleValuesForCol = new ArrayList(); boolean updatedValue = false; for (int i = 0; i < 9; i++) { colList.add(i); } for (Integer rowID : colList) { if (this.cells[rowID][col].value == 0) { possibleValuesForCol.addAll(this.cells[rowID][col].possibleValues); } } for (int i = 1; i < 10; i++) { if (Collections.frequency(possibleValuesForCol, (Integer) i) == 1) { numsToUpdate.add(i); } } for (Integer num : numsToUpdate) { for (Integer rowID : colList) { if (this.cells[rowID][col].possibleValues.contains(num)) { this.cells[rowID][col].value = num; updatedValue = true; } } } return updatedValue; }
private void verifyTrapsAreUnique(Map<String, Tap> traps) { for (Tap tap : traps.values()) { if (Collections.frequency(traps.values(), tap) != 1) throw new PlannerException( "traps must be unique, cannot be reused on different branches: " + tap); } }
private static void coll( Map<Integer, Integer> srcMap, List<Result> src, List<Result> dst, int count, int crt) { if (dst.size() == count) { if (results2.isEmpty() || sumResult(dst) < sumResult(results2)) { List<Integer> temp = new ArrayList<Integer>(); for (Result r : dst) { temp.addAll(r.src); } for (Entry<Integer, Integer> entry : srcMap.entrySet()) { if (Collections.frequency(temp, entry.getKey()) > entry.getValue()) { return; } } System.out.println("rep " + sumResult(results2) + " with " + sumResult(src)); results2 = dst; Collections.sort(results2); } return; } // System.out.println(dst); for (Result r : src) { List<Result> temp = new ArrayList<Result>(dst); temp.add(r); List<Result> temp2 = new ArrayList<Result>(src); temp2.remove(r); coll(srcMap, temp2, temp, 3, sumResult(temp)); } }
public static void main(String[] args) { ArrayList nums = new ArrayList(); nums.add(2); nums.add(-5); nums.add(3); nums.add(0); // 输出:[2, -5, 3, 0] System.out.println(nums); // 输出最大元素,将输出3 System.out.println(Collections.max(nums)); // 输出最小元素,将输出-5 System.out.println(Collections.min(nums)); // 将nums中的0使用1来代替 Collections.replaceAll(nums, 0, 1); // 输出:[2, -5, 3, 1] System.out.println(nums); // 判断-5 在List集合中出现的次数,返回1 System.out.println(Collections.frequency(nums, -5)); // 对nums集合排序 Collections.sort(nums); // 输出:[-5, 1, 2, 3] System.out.println(nums); // 只有排序后的List集合才可用二分法查询,输出3 System.out.println(Collections.binarySearch(nums, 3)); }
public boolean updateBlock(int blockNum) { ArrayList<Integer> blockList = new ArrayList(); ArrayList<Integer> numsToUpdate = new ArrayList(); ArrayList<Integer> possibleValuesForBlock = new ArrayList(); blockList = getBlockMembers(blockNum); boolean updatedValue = false; for (Integer cellID : blockList) { if (cellID == 1) { int a = 0; } if (this.cells[(int) ((cellID - 1) / 9)][(int) ((cellID - 1) % 9)].value == 0) { possibleValuesForBlock.addAll( this.cells[(int) ((cellID - 1) / 9)][((cellID - 1) % 9)].possibleValues); } } for (int i = 1; i < 10; i++) { if (Collections.frequency(possibleValuesForBlock, (Integer) i) == 1) { numsToUpdate.add(i); } } for (Integer num : numsToUpdate) { for (Integer cellID : blockList) { if (this.cells[(int) ((cellID - 1) / 9)][((cellID - 1) % 9)].possibleValues.contains(num) && this.cells[(int) ((cellID - 1) / 9)][((cellID - 1) % 9)].value == 0) { this.cells[(int) ((cellID - 1) / 9)][((cellID - 1) % 9)].value = num; updatedValue = true; } } } return updatedValue; }
public boolean updateRow(int row) { ArrayList<Integer> rowList = new ArrayList(); ArrayList<Integer> numsToUpdate = new ArrayList(); ArrayList<Integer> possibleValuesForRow = new ArrayList(); boolean updatedValue = false; for (int i = 0; i < 9; i++) { rowList.add(i); } for (Integer colID : rowList) { if (this.cells[row][colID].value == 0) { possibleValuesForRow.addAll(this.cells[row][colID].possibleValues); } } for (int i = 1; i < 10; i++) { if (Collections.frequency(possibleValuesForRow, (Integer) i) == 1) { numsToUpdate.add(i); } } for (Integer num : numsToUpdate) { for (Integer colID : rowList) { if (this.cells[row][colID].possibleValues.contains(num)) { this.cells[row][colID].value = num; updatedValue = true; } } } return updatedValue; }
/** * Ensure that the var doesn't exist twice in the same varTable (it can exist in different * varTables) */ public void validate() { Interpreter.writeln("validate", "Validating VARDECL"); if (Collections.frequency(body.varTable, Interpreter.findVar(body, id)) > 1) { Interpreter.error( "VARDECL", lineNum, code, "Var " + id + " cannot be declared more than once!"); } }
public int countRemainingHoles() { int count = 0; for (int i = 0; i < map.size(); ++i) { count += Collections.frequency(map.get(i), '^'); } return count; }
public static void main(String[] args) { // Convert het woord naar chars String woord = "bananen"; ArrayList<Character> chars = new ArrayList<>(); ArrayList<HuffKnoop> knopen = new ArrayList<>(); for (int i = 0; i < woord.length(); i++) { chars.add(woord.charAt(i)); } // 1. Frequentie van tekens Set<Character> uniqueChars = new HashSet<>(chars); for (char c : uniqueChars) { knopen.add(new HuffKnoop(c, Collections.frequency(chars, c), null, null)); } // 2. Sorteer de tekens op frequentie PriorityQueue queue = new PriorityQueue( uniqueChars.size(), new Comparator<HuffKnoop>() { @Override public int compare(HuffKnoop o1, HuffKnoop o2) { return o1.frequentie - o2.frequentie; } }); for (HuffKnoop knoop : knopen) { queue.add(knoop); } // 3. Maken van de huffman boom. while (queue.size() > 1) { HuffKnoop knoopLinks = (HuffKnoop) queue.poll(); HuffKnoop knoopRechts = (HuffKnoop) queue.poll(); queue.add( new HuffKnoop( '\0', knoopLinks.frequentie + knoopRechts.frequentie, knoopLinks, knoopRechts)); } // 4. Aflezen van de codes boom = (HuffKnoop) queue.poll(); generateCodes(boom, ""); Iterator it = codes.entrySet().iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry) it.next(); System.out.println(pair.getKey() + " " + pair.getValue()); } // 5. Coderen String encodedMessage = encodeMessage(woord); System.out.println(encodedMessage); // 6. Decoderen String decodedMessage = decodeMessage(encodedMessage); System.out.println(decodedMessage); }
public static boolean pushCandidateString(String candidateString) { strings.add(candidateString); // check to see if String appears in strings ArrayList more than // "CONFIDENCE_THRESHOLD" times int occurrences = Collections.frequency(strings, candidateString); if (occurrences == CONFIDENCE_THRESHOLD) { return true; } return false; }
private Map<Integer, Integer> getNodeStates() { Map<Integer, Integer> states = new HashMap<>(); List<Integer> visited = game.getVisitedNodes(); for (Integer node : visited) { states.put(node, Collections.frequency(visited, node)); } return states; }
public void countFrequency(Document doc) { Map<String, Integer> wordFrequency = new HashMap<String, Integer>(); for (Iterator iterator = doc.getUniqueWords().iterator(); iterator.hasNext(); ) { String word = (String) iterator.next(); int count = Collections.frequency(doc.getWords(), word); wordFrequency.put(word, count); } doc.setWordFrequency(wordFrequency); }
@Test public void testFailoverOnUndeploy() throws Exception { // Container is unmanaged, so start it ourselves this.start(0); this.deploy(0); final ContextSelector<EJBClientContext> selector = EJBClientContextSelector.setup(CLIENT_PROPERTIES); try { ViewChangeListener listener = context.lookupStateless(ViewChangeListenerBean.class, ViewChangeListener.class); this.establishView(listener, NODES[0]); Stateless bean = context.lookupStateless(StatelessBean.class, Stateless.class); assertEquals(NODES[0], bean.getNodeName()); this.start(1); this.deploy(1); this.establishView(listener, NODES); List<String> results = new ArrayList<String>(10); for (int i = 0; i < 10; ++i) { results.add(bean.getNodeName()); } for (int i = 0; i < NODES.length; ++i) { int frequency = Collections.frequency(results, NODES[i]); Assert.assertTrue(String.valueOf(frequency), frequency > 0); } this.undeploy(0); this.establishView(listener, NODES[1]); assertEquals(NODES[1], bean.getNodeName()); } finally { // reset the selector if (selector != null) { EJBClientContext.setSelector(selector); } // shutdown the containers for (int i = 0; i < NODES.length; ++i) { this.undeploy(i); this.stop(i); } } }
public static void main(String[] args) throws Exception { List<FastaSequence> fastaList = readFastaFile("/Users/Smatlock/pf.fasta"); Map<String, Integer> fastaMap = new TreeMap<String, Integer>(); ArrayList<String> seqs = new ArrayList<String>(); for (FastaSequence fs : fastaList) { seqs.add(fs.getSequence()); } for (String s : seqs) { int occurrences = Collections.frequency(seqs, s); fastaMap.put(s, occurrences); } System.out.println(sortByVal(fastaMap) + "\n"); }
protected void makePieChart(JsonArray datas, PieChart mPieChart, LinearLayout mPieCount) { List<String> titles = new ArrayList<String>(); for (JsonElement element : datas) { String title = element.getAsJsonObject().get("issue").getAsString(); titles.add(title); } Set<String> unique = new HashSet<String>(titles); for (String key : unique) { System.out.println(key + ": " + Collections.frequency(titles, key)); Random rnd = new Random(); String hexes = colorHexes[rnd.nextInt(colorHexes.length)]; int color = Color.parseColor(hexes); int count = Collections.frequency(titles, key); PieModel pieModel = new PieModel(key, count, color); mPieChart.addPieSlice(pieModel); View piechartLegend = getLayoutInflater().inflate(R.layout.piechart_legend_layout, mPieCount, false); CircleView piechartIndicator = (CircleView) piechartLegend.findViewById(R.id.legend_indicator); piechartIndicator.setColorHex(color); TextView piechartText = (TextView) piechartLegend.findViewById(R.id.legend_text); piechartText.setText(key); TextView piechartCount = (TextView) piechartLegend.findViewById(R.id.legend_count); piechartCount.setText(MixUtils.convertToBurmese(String.valueOf(count))); if (isUnicode) { piechartText.setTypeface(typefacelight); piechartCount.setTypeface(typefacelight); } else { MMTextUtils.getInstance(this).prepareMultipleViews(piechartText, piechartCount); } mPieCount.addView(piechartLegend); } mPieChart.startAnimation(); }
// Get frequency element in collection private static void testCount() { Collection<String> collection = Lists.newArrayList("a1", "a2", "a3", "a1"); Iterable<String> iterable = collection; MutableCollection<String> collectionGS = FastList.newListWith("a1", "a2", "a3", "a1"); // Get frequency element in collection int i1 = Iterables.frequency(iterable, "a1"); // using guava int i2 = Collections.frequency(collection, "a1"); // using JDK int i3 = CollectionUtils.cardinality("a1", iterable); // using Apache int i4 = collectionGS.count("a1"::equals); long i5 = collection.stream().filter("a1"::equals).count(); // using stream JDK System.out.println( "count = " + i1 + ":" + i2 + ":" + i3 + ":" + i4 + ":" + i5); // print count = 2:2:2:2:2 }
public boolean isAccountTypeUnique(Integer entityId, String name, boolean isNew) { List<AccountTypeDTO> accountTypeDTOList = new AccountTypeDAS().findAll(entityId); List<String> descriptionList = new ArrayList<String>(); for (AccountTypeDTO accountType1 : accountTypeDTOList) { descriptionList.add(accountType1.getDescription()); } if (isNew) { return !descriptionList.contains(name); } else { return Collections.frequency(descriptionList, name) < 2; } }
/** * Sets the tags to this model. * * @param _tags list of non distinct(!) tags. */ public void setTags(List<String> _tags) { if (_tags.size() != 0) { this.tags.clear(); this.tags = _tags; Iterator<String> itr = this.tags.iterator(); this.map.clear(); while (itr.hasNext()) { String o = itr.next(); int occurrences = Collections.frequency(this.tags, o); this.map.put(o, occurrences); } setChanged(); notifyObservers(this); } }
public static void main(String[] args) { Integer[] src; src = new Integer[] {84, 141, 189, 189, 73, 1101, 785, 768, 762, 756, 756, 377, 366, 356, 352}; src = new Integer[] {141, 189, 189, 73, 1101, 785, 768, 762, 756, 756, 377, 366, 356, 352}; calc(Arrays.asList(src), new ArrayList<Integer>(), 0); System.out.println("Src : " + Arrays.toString(src)); for (Result r : results) { System.out.println(r); } System.out.println("========================"); Map<Integer, Integer> countMap = new HashMap<Integer, Integer>(); for (Integer num : src) { countMap.put(num, Collections.frequency(Arrays.asList(src), num)); } coll(countMap, results, new ArrayList<Result>(), 3, 0); for (Result r : results2) { System.out.println(r); } }
/** * Method calls the bean function getNodeName() {numCalls} times and checks whether all servers * processed at least part of calls. The necessary number of processed calls by each server is * {minPercentage} of the number of all calls. */ private void validateBalancing( Stateless bean, int numCalls, int expectedServers, double minPercentage) { List<String> results = new ArrayList<String>(numCalls); for (int i = 0; i < numCalls; i++) { results.add(bean.getNodeName()); } Set<String> entries = new HashSet<String>(); entries.addAll(results); Assert.assertEquals(expectedServers, entries.size()); double minCalls = minPercentage * numCalls; for (String entry : entries) { int frequency = Collections.frequency(results, entry); Assert.assertTrue(Integer.toString(frequency), frequency >= minCalls); } System.out.println( String.format("All %d servers processed at least %f of calls", expectedServers, minCalls)); }
public static void main(String[] args) { print(list); print( "'list' disjoint (Four)?: " + Collections.disjoint(list, Collections.singletonList("Four"))); print("max: " + Collections.max(list)); print("min: " + Collections.min(list)); print("max w/ comparator: " + Collections.max(list, String.CASE_INSENSITIVE_ORDER)); print("min w/ comparator: " + Collections.min(list, String.CASE_INSENSITIVE_ORDER)); List<String> sublist = Arrays.asList("Four five six".split(" ")); print("indexOfSubList: " + Collections.indexOfSubList(list, sublist)); print("lastIndexOfSubList: " + Collections.lastIndexOfSubList(list, sublist)); Collections.replaceAll(list, "one", "Yo"); print("replaceAll: " + list); Collections.reverse(list); print("reverse: " + list); Collections.rotate(list, 3); print("rotate: " + list); List<String> source = Arrays.asList("in the matrix".split(" ")); Collections.copy(list, source); print("copy: " + list); Collections.swap(list, 0, list.size() - 1); print("swap: " + list); Collections.shuffle(list, new Random(47)); print("shuffled: " + list); Collections.fill(list, "pop"); print("fill: " + list); print("frequency of 'pop': " + Collections.frequency(list, "pop")); List<String> dups = Collections.nCopies(3, "snap"); print("dups: " + dups); print("'list' disjoint 'dups'?: " + Collections.disjoint(list, dups)); // Getting an old-style Enumeration: Enumeration<String> e = Collections.enumeration(dups); Vector<String> v = new Vector<String>(); while (e.hasMoreElements()) v.addElement(e.nextElement()); // Converting an old-style Vector // to a List via an Enumeration: ArrayList<String> arrayList = Collections.list(v.elements()); print("arrayList: " + arrayList); }
@Override public void run() { int currentPOSTagCount = 1; currentPOSTag = nextCategory(state); sentenceHeadRule = sentenceHeadRuleCount == 0 ? currentPOSTag : sentenceHeadRule; sentenceHeadRuleCount = sentenceHeadRuleCount == 0 ? sentenceHeadRuleCount + 1 : sentenceHeadRuleCount; while (currentPOSTagCount > 0 && partialGrammar.indexOf(currentPOSTag) >= 0) { currentPOSTagCount = Collections.frequency(partialGrammar, getRule(currentPOSTag)); int ruleIndex = partialGrammar.indexOf(getRule(currentPOSTag)); // Insert each grammar rule of the current state being processed // into the chart in case the rule is not already in the current // chart (not all of them). String rule = grammar.get(ruleIndex + size); if (!currentChartWithRules.contains(rule) && specialCase(rule) && isRequiredToProcess(rule)) if (enqueue(addStateAndStartEndPointsFields(rule), chart.get(i), i)) { stateLevelCount++; printRule(rule, Methods.PREDICTOR.name(), String.valueOf(i), state); } partialGrammar.set(partialGrammar.indexOf(currentPOSTag), ""); } synchronized (rulesToPredict) { threadCompletedCount++; if (threadCompletedCount >= threadCount) { threadRuleCompleted = true; rulesToPredict.notifyAll(); } } }
@Override public RecommendResponse recommend(RecommendQuery query, Integer maxReuslts) { ModifiableSolrParams solrParams = new ModifiableSolrParams(); QueryResponse response = null; RecommendResponse searchResponse = new RecommendResponse(); long step0ElapsedTime = 0; long step1ElapsedTime; List<String> recommendations = new ArrayList<String>(); try { // STEP 0 - get products from a user if (query.getUser() != null) { if (query.getProductIds() == null || query.getProductIds().size() == 0) { if (alreadyBoughtProducts != null) { query.setProductIds(alreadyBoughtProducts); } else { } } } solrParams = getInteractionsFromMeAndUSersThatILikedOrCommented(query.getUser()); response = SolrServiceContainer.getInstance() .getSocialActionService() .getSolrServer() .query(solrParams); step1ElapsedTime = response.getElapsedTime(); List<SocialAction> socialUsers = response.getBeans(SocialAction.class); if (socialUsers.size() == 0) { searchResponse.setNumFound(0); searchResponse.setResultItems(recommendations); searchResponse.setElapsedTime(-1); return searchResponse; } SocialAction currentUserInteractions = socialUsers.get(0); if (currentUserInteractions.getUserId().equals(query.getUser())) { socialUsers.remove(0); } else { currentUserInteractions = null; } final Map<String, Integer> userInteractionMap = new HashMap<String, Integer>(); if (currentUserInteractions != null) { List<String> usersThatPostedASnapshopToMe = currentUserInteractions.getUsersThatPostedASnapshopToMe(); if (usersThatPostedASnapshopToMe != null) { fillInteractions(usersThatPostedASnapshopToMe, userInteractionMap); } } for (SocialAction socialUser : socialUsers) { Integer userInteraction = userInteractionMap.get(socialUser.getUserId()); if (userInteraction == null) { userInteraction = 0; } if (socialUser.getUsersThatPostedASnapshopToMe() != null) { userInteraction += Collections.frequency(socialUser.getUsersThatPostedASnapshopToMe(), query.getUser()); } userInteractionMap.put(socialUser.getUserId(), userInteraction); } Comparator<String> interactionCountComparator = new Comparator<String>() { @Override public int compare(String a, String b) { if (userInteractionMap.get(a) > userInteractionMap.get(b)) { return -1; } else if (userInteractionMap.get(a).equals(userInteractionMap.get(b))) { return 0; } else { return 1; } } }; TreeMap<String, Integer> sorted_map = new TreeMap<String, Integer>(interactionCountComparator); sorted_map.putAll(userInteractionMap); solrParams = getSTEP2Params(query, maxReuslts, sorted_map); // TODO Facet for confidence value response = SolrServiceContainer.getInstance().getResourceService().getSolrServer().query(solrParams); // fill response object List<Resource> beans = response.getBeans(Resource.class); searchResponse.setResultItems(RecommendationQueryUtils.extractRecommendationIds(beans)); searchResponse.setElapsedTime( step0ElapsedTime + step1ElapsedTime + response.getElapsedTime()); SolrDocumentList docResults = response.getResults(); searchResponse.setNumFound(docResults.getNumFound()); } catch (Exception e) { System.out.println(solrParams); e.printStackTrace(); searchResponse.setNumFound(0); searchResponse.setResultItems(recommendations); searchResponse.setElapsedTime(-1); } return searchResponse; }
private String getOccurrences(List<String> obs, String o, int addition, int max) { int num = Collections.frequency(obs, o); num = Math.min(num, max); return String.valueOf(num + addition); }
@Test public void test() { List<String> worker = new ArrayList<String>(); worker.add("Sunny"); worker.add("Edition"); worker.add("Clinton"); // 排序 Collections.sort(worker); System.out.println(worker); // 二分法查找,必须先排序 int index = Collections.binarySearch(worker, "Sunny"); System.out.println("binary search index=" + index); // 复制,目标列表的个数必须大于等于源列表的个数,此方法比较鸡肋 List<String> list = new ArrayList<String>(); list.add("a"); list.add("b"); list.add("c"); Collections.copy(list, worker); System.out.println("list is " + list); // 替换 Collections.fill(list, "A"); System.out.println("list after fill A is " + list); // 返回指定 collection 中等于指定对象的元素数 int times = Collections.frequency(list, "A"); System.out.println("A frequency is " + times); // 获取最大最小数据 System.out.println("min data of worker is " + Collections.min(worker)); System.out.println("max data of worker is " + Collections.max(worker)); // 复制多次 list = Collections.nCopies(10, "default"); System.out.println("nCopies list is " + list); // 反转 Collections.reverse(worker); System.out.println("reverse worker is " + worker); // 打乱顺序 Collections.shuffle(worker); System.out.println("shuffle worker is " + worker); // 包含指定对象的Set Set<String> set = new HashSet<String>(Collections.singleton("sunny")); System.out.println("singleton set " + set); // 包含指定对象的List list = new ArrayList<String>(Collections.singletonList("sunny")); System.out.println("singletonList is " + list); // 包含指定键值对的Map Map<String, String> map = new HashMap<String, String>(Collections.singletonMap("key", "value")); System.out.println("singletonMap is " + map); // 交换指定位置的元素 Collections.swap(worker, 0, 1); System.out.println("after swap worker is " + worker); }
public void testLinkedListOperations() throws Exception { List<Integer> numbers = new LinkedList<>(Arrays.asList(0, 1, 2, 3, 4)); assertEquals(5, numbers.size()); for (int i = 0; i < numbers.size(); i++) { assertEquals(i, (int) numbers.get(i)); } numbers.add(2, 10); assertEquals(10, (int) numbers.get(2)); Collections.sort(numbers); assertEquals(10, (int) numbers.get(numbers.size() - 1)); int index = Collections.binarySearch(numbers, 10); assertEquals(5, index); System.out.println("Before shuffle:"); for (Integer i : numbers) { System.out.print(i + " "); } Collections.shuffle(numbers); System.out.println("\nAfter shuffle:"); for (int i : numbers) { System.out.print(i + " "); } Collections.sort(numbers); Collections.reverse(numbers); assertEquals(10, (int) numbers.get(0)); assertEquals(0, (int) numbers.get(numbers.size() - 1)); int max = Collections.max(numbers); assertEquals(10, max); int min = Collections.min(numbers); assertEquals(0, min); List<Integer> copy = Arrays.asList(0, 0, 0, 0, 0, 0); Collections.copy(copy, numbers); for (int i = 0; i < copy.size(); i++) { assertEquals((int) copy.get(i), (int) numbers.get(i)); } Collections.fill(numbers, 100); for (int i : numbers) { assertEquals(100, i); } numbers = new LinkedList<>(Arrays.asList(0, 1, 2, 3, 4, 1)); int frequency = Collections.frequency(numbers, 1); assertEquals(2, frequency); copy = Arrays.asList(0, 0, 0, 0, 0, 0); boolean disjoint = Collections.disjoint(numbers, copy); assertFalse(disjoint); copy = Arrays.asList(100, 101, 102); disjoint = Collections.disjoint(numbers, copy); assertTrue(disjoint); }
/** * Gets the kind of the poker player hand. * * @return The first element of the array will be the poker hand kind. The following elements of * the array represent the value or values that determines the quality of the poker hand. The * rest of values will represent the card values left, used to solve draws. If player doesn't * have the five hands the method will return null. * @example The hand [A A A K K] will return {PokerHand.FULL, A, K}. The hand [Q Q 10 9 5] will * return {PokerHand.PAIR, Q, 10, 9, 5}. */ public ArrayList<Object> getPokerHand() { if (playerHand.size() < 5) return null; Collections.sort(playerHand, comparator); int num_jokers = 0; for (FrenchCard c : playerHand) { if (c.isSuit(FrenchSuit.JOKER)) num_jokers++; } if (num_jokers == 5) { return new ArrayList(Arrays.asList(PokerHand.REPOKER, "A")); } Integer frequencies[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; String values[] = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"}; ArrayList<String> cardValues = new ArrayList(); for (FrenchCard c : playerHand) { if (!c.isSuit(FrenchSuit.JOKER)) cardValues.add(c.getValue()); } for (int i = 0; i < 13; i++) { for (FrenchCard c : playerHand) { frequencies[i] += c.isValue(values[i]) ? 1 : 0; } frequencies[i] += num_jokers; } ArrayList<Object> pokerHand = new ArrayList(); PokerHand hand = null; int reps = Collections.max(Arrays.asList(frequencies)); switch (reps) { case 5: hand = PokerHand.REPOKER; pokerHand.add(hand); pokerHand.add(values[Arrays.asList(frequencies).indexOf(5)]); break; case 4: hand = PokerHand.POKER; // 5 A A A A // 3 3 3 3 5 pokerHand.add(hand); pokerHand.add(values[Arrays.asList(frequencies).lastIndexOf(4)]); cardValues.removeAll( Collections.singleton(values[Arrays.asList(frequencies).lastIndexOf(4)])); pokerHand.add(cardValues.get(0)); break; case 3: if (Collections.frequency(Arrays.asList(frequencies), 2 + num_jokers) >= num_jokers + 1) { hand = PokerHand.FULL; pokerHand.add(hand); pokerHand.add(values[Arrays.asList(frequencies).lastIndexOf(3)]); cardValues.removeAll( Collections.singleton(values[Arrays.asList(frequencies).lastIndexOf(3)])); pokerHand.add(cardValues.get(0)); } else { hand = PokerHand.THREESOME; pokerHand.add(hand); pokerHand.add(values[Arrays.asList(frequencies).lastIndexOf(3)]); cardValues.removeAll( Collections.singleton(values[Arrays.asList(frequencies).lastIndexOf(3)])); pokerHand.add(cardValues.get(1)); pokerHand.add(cardValues.get(0)); } break; case 2: if (Collections.frequency(Arrays.asList(frequencies), 2) == 2) { hand = PokerHand.TWO_PAIR; pokerHand.add(hand); pokerHand.add(values[Arrays.asList(frequencies).lastIndexOf(2)]); pokerHand.add(values[Arrays.asList(frequencies).indexOf(2)]); pokerHand.add(values[Arrays.asList(frequencies).indexOf(1)]); } else { hand = PokerHand.PAIR; pokerHand.add(hand); pokerHand.add(values[Arrays.asList(frequencies).lastIndexOf(2)]); cardValues.removeAll( Collections.singleton(values[Arrays.asList(frequencies).lastIndexOf(2)])); pokerHand.add(cardValues.get(2)); pokerHand.add(cardValues.get(1)); pokerHand.add(cardValues.get(0)); } break; } boolean isFlush = true; FrenchSuit flushSuit = null; for (int i = 0; i < 5 && isFlush; i++) { if (flushSuit != null && !playerHand.get(i).isSuit(flushSuit) && !playerHand.get(i).isSuit(FrenchSuit.JOKER)) { isFlush = false; } if (flushSuit == null && !playerHand.get(i).isSuit(FrenchSuit.JOKER)) { flushSuit = playerHand.get(i).getSuit(); } } boolean isStraight = true; int straightFirstIndex = Arrays.asList(values).indexOf(playerHand.get(0).getValue()); int currentIndex = straightFirstIndex; for (int i = 1; i < 5 && isStraight; i++) { if (playerHand.get(i).getSuit() != FrenchSuit.JOKER && (Arrays.asList(values).indexOf(playerHand.get(i).getValue()) == currentIndex || Arrays.asList(values).indexOf(playerHand.get(i).getValue()) - straightFirstIndex > 4)) { isStraight = false; } currentIndex = Arrays.asList(values).indexOf(playerHand.get(i).getValue()); } if (isStraight && straightFirstIndex > 8) straightFirstIndex = 8; // Para Jokers, Q, K, A if (isStraight && isFlush && reps < 5) { pokerHand.clear(); if (values[straightFirstIndex] == "10") { pokerHand.add(PokerHand.ROYAL_FLUSH); } else { pokerHand.add(PokerHand.STRAIGHT_FLUSH); pokerHand.add(values[straightFirstIndex + 4]); } } else if (isFlush && reps < 4) { pokerHand.clear(); pokerHand.add(PokerHand.FLUSH); for (int i = 4; i >= 0; i--) { if (playerHand.get(i).isSuit(FrenchSuit.JOKER)) pokerHand.add("A"); else pokerHand.add(playerHand.get(i).getValue()); } } else if (isStraight && reps < 4 && hand != PokerHand.FULL) { pokerHand.clear(); pokerHand.add(PokerHand.STRAIGHT); pokerHand.add(values[straightFirstIndex + 4]); } else if (pokerHand.isEmpty()) { pokerHand.add(PokerHand.HIGHCARD); pokerHand.add(playerHand.get(4).getValue()); pokerHand.add(playerHand.get(3).getValue()); pokerHand.add(playerHand.get(2).getValue()); pokerHand.add(playerHand.get(1).getValue()); pokerHand.add(playerHand.get(0).getValue()); } return pokerHand; }
/** * It gives the frequency that the card appears in the players hand. * * @param card * @return */ public int frequency(Card card) { return Collections.frequency(this.cards, card); }