Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shuffling a Stack<T>

    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!

like image 227
Nick Hadley Avatar asked Jan 18 '26 15:01

Nick Hadley


1 Answers

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();
like image 153
Yacoub Massad Avatar answered Jan 21 '26 06:01

Yacoub Massad