public static void Shuffle<T> ( this Stack<T> stack )
{
List<T> list = stack.ToList ();
list.Shuffle ();
stack = list.ToStack ();
}
public static void Shuffle<T> ( this List<T> list )
{
for ( int i = 0; i < list.Count; i++ )
{
int num = Form1.rnd.Next ( list.Count );
T temp = list[i];
list[i] = list[num];
list[num] = temp;
}
}
public static Stack<T> ToStack<T> ( this List<T> list )
{
Stack<T> stack = new Stack<T> ();
foreach ( T t in list )
stack.Push ( t );
return stack;
}
Above is my attempt to shuffle a generic stack. However, although the List Shuffle extension method works, the Stack Shuffle does not work as intended. It is as if the Shuffle call in the middle isn't called at all. Instead, it remains the same list, un-shuffled. So I presume the problem is in the ToStack function. Can someone please explain my error? Thanks in advance!
The Shuffle method (that takes a Stack<T>) takes the stack parameter by value. So when you invoke stack = list.ToStack ();, you are changing a variable (stack) that is local to the method.
One solution is to do as you did with the List<T> shuffle method like this:
public static Stack<T> Shuffle<T>(this Stack<T> stack)
{
List<T> list = stack.ToList();
list.Shuffle();
return list.ToStack();
}
This method takes a stack as input as generates a new shuffled stack. You can use it like this:
Stack<int> stack = new Stack<int>();
for(int i = 0 ; i < 10 ; i++)
stack.Push(i);
stack = stack.Shuffle();
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