I need to randomly generate three cards from array i have the array of 52 cards names from card1 to card52
String rank[]=new String[52];
for(int i=0;i<rank.length;i++)
{
rank[i]= "card"+i;
}
Now i need to select three cards from the array and it should not be repetable.
can anybody help me. actually i m doing this bt cards are repeting. pls provide me the sollution.
Thanks in Advance.
You can try Collections.shuffle(List list) method:
String rank[] = new String[52];
for (int i = 0; i < rank.length; i++) {
rank[i] = "card" + i;
}
List<String> cards = Arrays.asList(rank);
Collections.shuffle(cards);
List<String> selectedCards = cards.subList(0, 3);
If you convert your array to a List
you can use Collections.shuffle()
to randomise it. Then if you just take the first three entries of the list you'll get three random cards with no repeats.
List<String> ranklist = Arrays.asList(rank);
Collections.shuffle(ranklist);
String rank1 = ranklist.get(0);
String rank2 = ranklist.get(1);
String rank3 = ranklist.get(2);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With