Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random card generation

Tags:

java

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.

like image 720
vivek_Android Avatar asked Nov 29 '22 04:11

vivek_Android


2 Answers

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);
like image 120
Vitalii Fedorenko Avatar answered Dec 08 '22 19:12

Vitalii Fedorenko


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);
like image 32
Dave Webb Avatar answered Dec 08 '22 20:12

Dave Webb