Shuffle playing cards

Asked

Viewed 330 times

5

I need to make a kind of "Mini-pife", but I’m not able to create the method to shuffle the cards, someone can help me?

public class Baralho
{
    public Carta[] Cartas { get; private set; }

    public Baralho()
    {
        this.Cartas = new Carta[52];

        int c = 0;

        for (int nIdx = 0; nIdx < 4; ++nIdx)
        {
            Naipe naipe = (Naipe)(nIdx + 1);

            for (int vIdx = 0; vIdx < 13; ++vIdx)
            {
                Valor valor = (Valor)(vIdx + 1);

                this.Cartas[c++] = new Carta()
                {
                    Naipe = naipe,
                    Valor = valor
                };
            }
        }
    }

1 answer

5

public class Baralho
{
    public Carta[] Cartas { get; private set; }

    public Baralho()
    {
        this.Cartas = new Carta[52];

        int c = 0;

        for (int nIdx = 0; nIdx < 4; ++nIdx)
        {
            Naipe naipe = (Naipe)(nIdx + 1);

            for (int vIdx = 0; vIdx < 13; ++vIdx)
            {
                Valor valor = (Valor)(vIdx + 1);

                this.Cartas[c++] = new Carta()
                {
                    Naipe = naipe,
                    Valor = valor
                };
            }
        }
        this.Cartas = Embaralha(this.Cartas);
    }

    public Carta[] Embaralha(Carta[] baralho){
        Random rnd = new Random();
        return MyArray.OrderBy(x => rnd.Next()).ToArray();  
    }

}

Removed from here: https://stackoverflow.com/questions/108819/best-way-to-randomize-an-array-with-net

Tip: Wanted to give a tip that will help speed up your studies/work with programming. Your situation is: you have a Array of Cartas and you need to shuffle these Cartas... You don’t need to get stuck in Cartas and yes in the resources you are using(Array).

If each Carta is inside a Array, then you need to randomize a Array what’s inside the Array no matter (in your case are Cartas) that is to say you would have gained much more time if you had sought "How to randomize a Array" and would have already found the solution, would not need to wait for an answer here. Well, it is not a negative criticism but rather constructive I hope it helps you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.