please i want to write a program that will produce sets of random numbers in c#, i need someone to put me through on how will i start and the style to use and please i need a very good ebook on progamming in c# for dummies.

Here is a simple example using Randiom class:

static void Main(string[] args)
        {
            Random r = new Random();
            int[] numbers = new int[5]; //lets create an integer array (here we only create indexes, no values inside yet
            for (int i = 0; i < numbers.Length; i++) //lets loop through indexes to fill up numbers
            {
                int num;
                do
                {
                    num = r.Next(1, 6); //get random number
                }
                while (numbers.Contains(num)); //if this current random number exists in array of numbers, repeat and get nre number (until this number does not exits in array)
                numbers[i] = num; //add new number to array (number which dones not exist yet).
            }

            //convert int[] to string[]:   (this is not needed)!
            string[] strArray = Array.ConvertAll<int, string>(numbers, new Converter<int, string>(ConvertIntToString));
            //lets display numbers:
            Console.WriteLine("Numbers are: {0}", String.Join(",", strArray));
            Console.ReadLine();
        }

        private static string ConvertIntToString(int intParameter)
        {
            return intParameter.ToString();
        }

This may also be a helpful snippet:

public static int GetRandom(int min, int max)
    {
      byte[] b = new byte[sizeof(int)];
      new System.Security.Cryptography.RNGCryptoServiceProvider().GetBytes(b);
      int i = BitConverter.ToInt32(b, 0);
      Random r = new Random(i);
      return r.Next(min, max);
    }

This may also be a helpful snippet:

public static int GetRandom(int min, int max)
    {
      byte[] b = new byte[sizeof(int)];
      new System.Security.Cryptography.RNGCryptoServiceProvider().GetBytes(b);
      int i = BitConverter.ToInt32(b, 0);
      Random r = new Random(i);
      return r.Next(min, max);
    }

Is it appropriate to seed the Random class every call like that? I was just thinking it would be more appropriate to make a static Random seeded once for the lifetime of the application (as is typical with C rand() function).

Yeah that kind of seems like overkill. I am not sure how many CPU cycles all that would take, but if you are using the random numbers for something useful (like a statistical simulation) the less CPU the better. I would say seeding Random() once with that method should suffice. But you have far more posts than me and are a 'featured poster' so maybe I don't have any merit to question you.

You are both correct. Always question things that don't make sense to you. Its how you learn, and learn if the person talking to you knows what they are doing.

Yes it is overkill. The parameterless Random ctor is time-dependent so if you create two instances at the same time they will yield the same result. If you were doing a lot of random number generation you could do what pseudorandom21 said, use RNGCryptoServiceProvider to create a seeded Random instance then hold on to the instance. I don't generate many random numbers so I left it static. Not really a good reason.

Anyway how that came to be is because I had a third party API where we each generated random numbers that needed to be different. I had a high number of collisions so I started using the method above.

Basically my problem in a nutshell:

int m_threadCount;
    ManualResetEvent mre_startExecution = new ManualResetEvent(false);
    AutoResetEvent mre_allThreadsStarted = new AutoResetEvent(false);
    AutoResetEvent mre_allThreadsFinished = new AutoResetEvent(false);
    //ManualResetEvent mre_all
    void button8_Click(object sender, EventArgs e)
    {
      Debug.Assert(m_threadCount == 0);
      mre_startExecution.Reset();
      mre_allThreadsStarted.Reset();
      mre_allThreadsFinished.Reset();

      for (int i1 = 0; i1 < Environment.ProcessorCount; i1++)
      {
        ThreadPool.QueueUserWorkItem(s => RandomizeStartAndWait());
      }
      
      mre_allThreadsStarted.WaitOne();
      mre_startExecution.Set();
      mre_allThreadsFinished.WaitOne();
      MessageBox.Show("Done");
    }

    void RandomizeStartAndWait()
    {
      if (Interlocked.Increment(ref m_threadCount) >= Environment.ProcessorCount)
      {
        mre_allThreadsStarted.Set();
      }
      try
      {
        mre_startExecution.WaitOne();
        PrintRandoms();
      }
      finally
      {
        if (Interlocked.Decrement(ref m_threadCount) <= 0)
        {
          mre_allThreadsFinished.Set();
        }
      }
    }
    void PrintRandoms()
    {
      const int cnt = 10;
      int[] arr = new int[cnt];
      Random r = new Random();
      for (int i1 = 0; i1 < cnt; i1++)
      {
        arr[i1] = (r.Next(int.MinValue, int.MaxValue));
      }
      Console.WriteLine(string.Format("Thread #{0}: {1}",
        Thread.CurrentThread.ManagedThreadId.ToString("F0").PadLeft(2, '0'),
        string.Join(", ", Array.ConvertAll<int, string>(arr, Convert.ToString))));
    }

Yields

Thread #14: -1398654100, -934866498, -40531697, 414798476, 139435000, 493170039, 1853050734, -1354897786, 1073651648, 1702706023
Thread #16: -1398654100, -934866498, -40531697, 414798476, 139435000, 493170039, 1853050734, -1354897786, 1073651648, 1702706023
Thread #13: -1398654100, -934866498, -40531697, 414798476, 139435000, 493170039, 1853050734, -1354897786, 1073651648, 1702706023
Thread #12: -1398654100, -934866498, -40531697, 414798476, 139435000, 493170039, 1853050734, -1354897786, 1073651648, 1702706023
Thread #10: -1398654100, -934866498, -40531697, 414798476, 139435000, 493170039, 1853050734, -1354897786, 1073651648, 1702706023
Thread #15: -1398654100, -934866498, -40531697, 414798476, 139435000, 493170039, 1853050734, -1354897786, 1073651648, 1702706023
Thread #06: -1398654100, -934866498, -40531697, 414798476, 139435000, 493170039, 1853050734, -1354897786, 1073651648, 1702706023
Thread #11: -1398654100, -934866498, -40531697, 414798476, 139435000, 493170039, 1853050734, -1354897786, 1073651648, 1702706023

Ahh that makes sense.

Some guy on here a while ago didn't like how un-random Random() was. We discussed ways to be more random then just to base it on time, and he ended up using the microvolt noise from his microphone jack to seed Random(). Try and replicate electrostatic noise!

Ahh that makes sense.

Some guy on here a while ago didn't like how un-random Random() was. We discussed ways to be more random then just to base it on time, and he ended up using the microvolt noise from his microphone jack to seed Random(). Try and replicate electrostatic noise!

Sweet idea, I like it.

wow... that is a novel approach and quite possibly one of the most interesting/funny ways to solve this problem. I'm not going to lie -- it made me LOL. Too bad I don't have a mic :(

using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
 
namespace pe7_4
{
    class Program
    {
        static void Main(string[] args)
        {
            Random rand = new Random();
            double[] aOne = new double[10];
            double[] aTwo = new double[10];
            double[] aThree = new double[10];
            int randNum = rand.Next(20);
            string result = "The product of 2 random numbers is: \n";
 
            for (int i = 0; i < 10; i++)
            {
                aOne[i] = rand.Next(20);
                aTwo[i] = rand.Next(20);
                aThree[i] = aOne[i] * aTwo[i];
                result += aOne[i] + " * " + aTwo[i] + " = " + aThree[i] + "\n";
            }//end for loop
 
            MessageBox.Show(result, "Random numbers and their squares. ",
                            MessageBoxButtons.YesNo, MessageBoxIcon.Information);
 
        }//end Main method
    }
}

Edited 5 Years Ago by peter_budo: Adding code tags

This article has been dead for over six months. Start a new discussion instead.