forum

Home / DeveloperSection / Forums / How to generate Random Number in c#?

How to generate Random Number in c#?

Anonymous User 2049 26-Oct-2014
Hi Can anyone help me, i am trying the build a deck of Crads the problem i am having is producing enough random numbers to fill the deck i get to 16 cards and then it seems i am not producing the remaining cards i need to fill the deck.
 
code is below. 
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace TexasHoldEmTest
{
    public enum Suit { Clubs = 1, Diamonds = 2, Hearts = 3, Spades = 4 }
    public enum CardNumber { Ace = 1, Two = 2, Three = 3, Four = 4, Five = 5, Six = 6, Seven = 7, Eight = 8, Nine = 9, Ten = 10, Jack = 11, Queen = 12, King = 13 }
    public class Card
    {
        public Suit suit;
        public CardNumber number;
        public bool isUsed = false;
        public Card()
        {
            Thread.Sleep(1);
            Random suit1 = new Random();
            Random number1 = new Random();
            suit = (Suit)suit1.Next(1, 5);
            number = (CardNumber)number1.Next(1, 14);
        }
        
        public void showCard(List<Card> c)
        {
            Console.WriteLine("{0} of {1}",number, suit);
        }
        
        public void Deck(List<Card> c)
        {
            do
            {
                Card card = new Card();
                bool exists = c.Exists(x => x.suit == card.suit && x.number == card.number);
                if (exists == false)
                {
                    c.Add(card);
                    Console.WriteLine("Generating Card {0}", c.Count);
                }
            }           
            while (c.Count < 52);
        }
    }
    class Game
    {
        static void Main(string[] args)
        {
            Card card = new Card();
            List<Card> deckOfCards = new List<Card>();
            card.Deck(deckOfCards);
            foreach (Card c in deckOfCards)
            {
                c.showCard(deckOfCards);
            }
            Console.ReadLine();
        }
    }
}

c# c# 
Updated on 26-Oct-2014
I am a content writter !

Can you answer this question?


Answer

1 Answers

Liked By