我有一张名为hand
的牌列表Arraylist<Card> hand = new Arraylist<Card>();
hand.add(new Card("As"));
hand.add(new Card("9h"));
...
手中卡的最高限额是五。 我需要通过选择手中的每三张牌而不重复来获得手中的所有组合,并且顺序并不重要。
示例:
[ “AC”, “10K”, “5C”, “7H”, “3小时”]
结果:
[Ac,10k,5c]
[Ac,10k,7h]
[Ac,10k,3h]
[Ac,5c,7h]
[Ac,5c,3h]
[Ac,7h,3h]
[10k,5c,7h]
[10k,5c,3h]
[10k,7h,3h]
[5c,7h,3h]
编辑:我确实找到了与此相关的已回答问题。
Algorithm to return all combinations of k elements from n
这是java中的一个例子,我稍微调整了一下
public static void main(String[] args){
Card[] arr = { new Card(16), new Card(4), new Card(22), new Card(16), new Card(11) };
combinations(arr, 3, 0, new Card[3]);
}
static void combinations(Card[] arr, int len, int startPosition, Card[] result){
if (len == 0){
String str = "";
for(Card card : result)
{
str += card.CardString() + ", ";
}
System.out.println(str);
return;
}
for (int i = startPosition; i <= arr.length-len; i++){
result[result.length - len] = arr[i];
combinations(arr, len-1, i+1, result);
}
}
答案 0 :(得分:0)
好的,你想要一张没有双卡的卡洗牌。
将您的卡放入ArraList。在此之后获得零和列表大小之间的随机数。 在plaze x上获得卡片。然后将其取下并将卡片放入手中。
ArrayList<Card> allCards = new ArrayList<Card>();
.... put all Cards in there
Card[] hand = new Card[5];
Random rnd = new Random();
for(int i = 0;i < 5; ){
int z = rnd.nextInt(allCards.size());
Card c = allCards.get(z);
allCards.remove(z);
hand[i] = c;
}
答案 1 :(得分:0)
这是更多&#34;高级&#34;,获得没有重复的随机卡片组,所有这些都在评论中解释:
import java.util.ArrayList;
import java.util.List;
class Pair {
private int x;
private int y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
class PairSelector {
private List<Pair> pairs;
// holds all possible pair combination
public PairSelector() {
pairs = new ArrayList<Pair>();
// by initiation it's all there - in a List
for (int i = 0; i <= 5; i++) {
for (int j = 0; j <= 5; j++) {
// Making sure we have no duplicates
if (i != j) {
pairs.add(new Pair(i, j));
}
}
}
}
// selecting random pair from List
public Pair getRandomPair() {
return pairs.get((int) (pairs.size() * Math.random()));
}
}
public class RandSelector {
// Tetsing it
public static void main(String[] args) {
// Just create object once
PairSelector ps = new PairSelector();
// Create Pair object
Pair randomPair = ps.getRandomPair();
// Now you can use it in your list like this:
int x = randomPair.getX();
int y = randomPair.getY();
// Preview
System.out.println(x + " " + y);
}
}