1

I have a problem with my program. I want to set up how much indexes have my array and then for each index make his own random value. Instead of that loop foreach make one value to each index. I tried with for and Length of array but it didn't work. What I've done wrong?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Set the number of arguments in mineArray:");
            string argumentsNumber = Console.ReadLine();
            int argumentsNumberInt = Convert.ToInt32(argumentsNumber);
            int[] mineArray = new int[argumentsNumberInt];

            //set up values to each index of array
            for (int i = 0; i < mineArray.Length; i++)
            {
                Random rand = new Random();
                mineArray[i] = rand.Next(0, 100);
                Console.WriteLine(Convert.ToString(mineArray[i]));

            }
            //end of the program
            Console.ReadLine();

        }
    }
}
Perisher
  • 49
  • 3

1 Answers1

0

Initialize Random outside of loop:

Random rand = new Random();

for (int i = 0; i < mineArray.Length; i++)
{           
    mineArray[i] = rand.Next(0, 100);
    Console.WriteLine(mineArray[i]); // you don't need to convert to string
}

When you create instance of Random class, it uses current system ticks as seed for pseudo random numbers generation. If you create several instances of Random pretty quickly, they got same seed and you will have same numbers in array.

Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
  • Now I have another problem. My program assigns random number to each argument of array. But at the end the last number fills all arguments. Like radoming 6,7,8,4,5,3 but I obtain 3,3,3,3,3,3 – Perisher Jul 08 '14 at 17:02
  • @user3297615 here is how SO works - if one problem solved, you should accept answer. If you have another problem which you cannot solve, then create new question. It's hard to tell whats went wrong without seeing your code. You are overwriting items at some point – Sergey Berezovskiy Jul 08 '14 at 17:15