i'm trying shuffle or randomize linkedlist of images in case way i've set seems go on indefinetely
the shuffling simple, have list, note last entry, take first entry , put @ random spot in list, , next first entry, etc. until top entry entry noted last, put entry in random place in list , list shuffled.
here's code:
class shuffleclass { private linkedlist<image> library; private image lastcard; private image topcard; private random rng; private int place; private linkedlistnode<image> node; public linkedlist<image> shuffle(linkedlist<image> library) { this.library = library; lastcard = library.last.value; rng = new random(); while (library.first.value != lastcard) { topcard = library.first.value; library.removefirst(); place = rng.next(1,library.count+1); if (place == library.count) { library.addbefore(library.last, topcard); } else { node = library.find(library.elementat(place)); library.addbefore(node, topcard); } } topcard = library.first.value; library.removefirst(); place = rng.next(0,library.count+1); if(place == library.count) { library.addbefore(library.last, topcard); } else { node = library.find(library.elementat(place)); library.addbefore(node, topcard); } return library; } }
you can use random class shuffle list:
public static void shuffle() { random rand = new random(); linkedlist<int> list = new linkedlist<int>(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 }); foreach (int in list) console.write("{0} ", i); console.writeline(); int size = list.count; //shuffle list list = new linkedlist<int>(list.orderby((o) => { return (rand.next() % size); })); foreach (int in list) console.write("{0} ", i); console.writeline(); }
the output may this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 10 2 17 7 9 15 8 14 1 12 13 16 4 18 3 5 11 20 19 6
Comments
Post a Comment