Skip to content

Instantly share code, notes, and snippets.

@adam-singer
Created January 5, 2012 07:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adam-singer/1564143 to your computer and use it in GitHub Desktop.
Save adam-singer/1564143 to your computer and use it in GitHub Desktop.
A simple card shuffle in Dart
// Example borrowed from http://algs4.cs.princeton.edu/
class cardShuffle {
String _cards;
cardShuffle() {
}
void run() {
_cards = "2C 3C 4C 5C 6C 7C 8C 9C 10C JC QC KC AC " +
"2D 3D 4D 5D 6D 7D 8D 9D 10D JD QD KD AD " +
"2H 3H 4H 5H 6H 7H 8H 9H 10H JH QH KH AH " +
"2S 3S 4S 5S 6S 7S 8S 9S 10S JS QS KS AS";
List<String> cards = _cards.split(' ');
f(var l) {
String s = "";
for(var c in l) {
s += (c + " ");
}
print(s);
}
f(cards);
int N = cards.length;
for (int i = 0; i<N; i++) {
int r = i + (Math.random() * (N - i)).toInt();
String swap = cards[r];
cards[r] = cards[i];
cards[i] = swap;
}
f(cards);
}
}
void main() {
new cardShuffle().run();
}
@atebitftw
Copy link

I like! I wrote a solitaire game a while back for Silverlight and used a list swapping technique for the shuffle:

List<String> cards = new List<String>();
List<String> swapCards = _cards.split(' ');

while(!swapCards.isEmpty()){
  int r = (Math.random() * swapCards.length).toInt();
  cards.add(swapCards[r]); 
  swapCards.removeRange(r, 1);
 }

About the same lines of code but slightly fewer math operations, although perhaps trading off with the list operations.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment