Java 设计可按发生频率排序的列表列表 设置
我有一个整数对的列表:((1,2),(1,3),(2,5),(1,6),(2,8),(9,8),(8,11)等等)。在给定的一对中,数字必须是不同的,但是当你把列表看作一个整体时,会有很多重复。p> 虽然这些信息与问题并不严格相关,但每个数字代表一副牌中的一张牌(包括1到52张),每对代表一个玩家可能的一张牌 问题 我们希望对这些数字对进行排序,以使包含整个列表中最频繁卡片的数字对排在第一位。然后,这些对按第二个数字升序排列。然后,我们使用列表上剩余的对重复这个过程。打破联系的规则是先用较小的数字。让我们使用上面的列表做一个示例:Java 设计可按发生频率排序的列表列表 设置,java,design-patterns,Java,Design Patterns,我有一个整数对的列表:((1,2),(1,3),(2,5),(1,6),(2,8),(9,8),(8,11)等等)。在给定的一对中,数字必须是不同的,但是当你把列表看作一个整体时,会有很多重复。p> 虽然这些信息与问题并不严格相关,但每个数字代表一副牌中的一张牌(包括1到52张),每对代表一个玩家可能的一张牌 问题 我们希望对这些数字对进行排序,以使包含整个列表中最频繁卡片的数字对排在第一位。然后,这些对按第二个数字升序排列。然后,我们使用列表上剩余的对重复这个过程。打破联系的规则是先用较小的数
(1,2)
(1,3)
(1,6)
(1,2)
(1,3)
(1,6)
(2,8) <-- Note 2 is the smallest of the "other" numbers amongst the 8 group
(9,8)
(8,11)
(2,5) <-- This gets added in step 3, but since there is only 1 left we add it now
(1,2)
(1,3)
(1,6)
(1,2)
(1,3)
(1,6)
(2,8) <-- Note 2 is the smallest of the "other" numbers amongst the 8 group
(9,8)
(8,11)
(2,5) <-- This gets added in step 3, but since there is only 1 left we add it now
(1,2)
(1,3)
(1,6)
(2,8)我认为这不符合设计模式。您确实需要考虑您的设计,但这将是一个非常常见的问题,以符合模式的要求,但事实并非如此
public class CardAndPairs implements Comparable<CardAndPairs> {
Card card;
List<Pair> pairs;
public CardAndPairs(Card card, Set<Pair> allPairs) {
this.card = card;
pairs = new HashSet<>();
for (Pair pair : allPairs)
if (pair.contains(card))
pairs.add(pair);
// You could then reorder "pairs" by the value of the other card
// ... see below
}
@Override
public int compareTo(CardAndPairs other) {
int diff = pairs.size() - other.pairs.size();
if (diff > 0)
return 1;
if (diff == 0)
return card.compareTo(other.card);
return 1;
}
}
然后需要通过CardAndPairs
的构造函数中的List pairs
来更改List pairs
。当你向列表中添加一对时,你必须进行配对。添加(新的配对,带有givencard(card,pair))
而不是配对。添加(配对)
。最后,您只需调用Collections.sort(pairs)
在CardAndPairs
的构造函数末尾,看起来您正在以一种特殊的方式对Texas Hold'em holecards进行排序。你能详细说明一下你在做什么吗?托托,这是我得到的最彻底的答案之一。谢谢