6 Replies - 31627 Views - Last Post: 17 October 2007 - 09:44 AM Rate Topic: -----

#1 CrazyJ  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 51
  • Joined: 15-October 07

Instantiate an array, fill with random numbers

Post icon  Posted 15 October 2007 - 09:36 AM

Hello everyone, I am new to C#. I have some background with QBasic and am challenged with OOP/C#. Thank you for a great resource!

I would like to apply the values of 2 int variables, entered by the user, to a 2 dimensional array. My problem is in understanding how to cause the 2 ints to create the array dynamically, if the user enters 3 for int A, and 5 for int B, then the array will consist of 3 rows, and 5 columns.
I would then create a class to generate random numbers that will fill the array with a minValue and a maxValue. I'm not sure how to begin with the algorithm, and how to establish the relationship between the array and the random number generation. I believe the code below will create a random array, but not dynamic, using user input?
Thanks!

 public static void GenRanArray(int nbOfRows,
											   int nbOfCols,
											   int [,] array)
		{
			const int MIN_NUMBER =  1;
			const int MAX_NUMBER = 99;


//		  ---------------------------------------------
//		  Declare the randomNumber object: randomNumber
			Random randomNumber = new Random();
//		  -----------------------------------			
			
			int row;
			int col;

			for (row = 0; row < nbOfRows; row++)
				for (col = 0; col < nbOfCols; col++)
					array[row, col] = randomNumber.Next(MIN_NUMBER,
														MAX_NUMBER);

		} // method GenRanArray
//	  ===============================

//	  ============================================
		public static void OutputArray(int nbOfRows,
									   int nbOfCols,
									   int [,] array)
		{
			int row;
			int col;

			for (row = 0; row < nbOfRows; row++)
				for (col = 0; col < nbOfCols; col++)
					Console.WriteLine("array[" + row + ", " + col + "] = " 
											   + array[row, col]);
			Console.WriteLine();

		} // method GenerateRandomArray
//	  ===============================

	} // class MyMethods
} // namespace Arrays2D


This post has been edited by PsychoCoder: 15 October 2007 - 10:22 AM


Is This A Good Question/Topic? 0
  • +

Replies To: Instantiate an array, fill with random numbers

#2 Martyr2  Icon User is online

  • Programming Theoretician
  • member icon

Reputation: 4337
  • View blog
  • Posts: 12,141
  • Joined: 18-April 07

Re: Instantiate an array, fill with random numbers

Posted 15 October 2007 - 10:16 AM

Hello there CrazyJ. Below I have put a nice little code snippet based on your code to show you how to go about creating the dynamic array based on user input. Some of the highlights include...

1) Removal of the array being passed in. Just pass in the rows and columns to generate the array with.
2) Return value changed from void to a multidimensional integer array
3) Call the function using the two values specified by the user and it will return the array of that size full of random integers.

I hope this is what you were looking for and that you find the code pretty straight forward. If you wanted to make this even more flexible you could add a third and fourth parameter to specify the random number range instead of making them hardcoded like you have it. But that is a design choice best left up to you.

private void button1_Click(object sender, EventArgs e)
{
	  // Generate the array to be 2 x 2
	  int[,] myarray = GenRanArray(2, 2);

	  // Read it out to a listbox just for display purposes
	  for (int row = 0; row < 2; row++)
			for (int col = 0; col < 2; col++)
				  listBox1.Items.Add("Row " + row + " and column " + col + ": " + myarray[row, col]);

}

// Generates and returns a multidimensional array
public static int[,] GenRanArray(int nbOfRows, int nbOfCols)
{
	  const int MIN_NUMBER = 1;
	  const int MAX_NUMBER = 99;


	  // ---------------------------------------------
	  // Declare the randomNumber object: randomNumber
	  Random randomNumber = new Random();
	  // -----------------------------------

	  // Create our dynamic array using values passed in.
	  int[,] newarray = new int[nbOfRows,nbOfCols];

	  // Initialize the array with random numbers
	  for (int row = 0; row < nbOfRows; row++)
			for (int col = 0; col < nbOfCols; col++)
				  newarray[row, col] = randomNumber.Next(MIN_NUMBER,MAX_NUMBER);

	  // Return the array to caller
	  return newarray;

}



In the future you might want to put your code into a code box (highlight your code and press the button with the pound sign # on it). It makes it easier for us to actually scroll through the code and do copy and pastes.

Hope this solution works for you.

Enjoy!

"At DIC we be coding ninjas!" :snap:
Was This Post Helpful? 0
  • +
  • -

#3 CrazyJ  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 51
  • Joined: 15-October 07

Re: Instantiate an array, fill with random numbers

Posted 16 October 2007 - 06:56 AM

Well, Martyr2, thank you very much for the speedy reply. The trouble is, I am not familiar with listBox, and it is outside the context of my program. My goal is this:
Get 2 integers from user, called m and n.
option to iterate if values entered are not valid.
create array using m for rows, and n for cols.

Then Get 2 more integers from user called minValue and maxValue
generate range of random numbers between minValue and maxValue
fill array with random numbers

Here is my program so far, I am getting errors Errors: "No overload for method 'FillArray' takes '5' arguments" "No overload for method 'FillArray' takes '2' arguments" and "int does not contain a definition for Next."

//  =============
	class Program
	{
//	  ==============================
		static void Main(string[] args)
		{
//		  =====
			int m;
			int n;
			int minValue;
			int maxValue;
			int randomDigit;
			int[,] numbers = new int[1,1];
//		  ===================================
			Random randomNumber = new Random(); // randomNumber declaration
//		  ====================================
			MyMethods.Get(out m,2,int.MaxValue);
			MyMethods.Get(out n, 2, int.MaxValue);

			MyMethods.BuildArray(m, n,ref numbers);

			MyMethods.Get(out minValue, int.MinValue, int.MaxValue);
			MyMethods.Get(out maxValue, minValue, int.MaxValue);

			MyMethods.FillArray(m, n, numbers, minValue, maxValue);
			MyMethods.FillArray(randomNumber, randomDigit);
			MyMethods.PrintArray(m, n, numbers);
			Console.ReadLine();


and MyMethods class

	class MyMethods
	{
//	  ================================
		public static void Get(out int value, int min, int max)
		{
			string numString;
			do
			{
				Console.WriteLine("Please enter a number between " + min + " and " + max);
				Console.WriteLine();
				numString = Console.ReadLine();
				value = int.Parse(numString);
			} while (!((value >= min) && (value <= max)));
		}
 //	 ==========================================	   
		public static void BuildArray(int rows, int cols, ref int [,] dynArray )
		{
			dynArray = new int[rows, cols];
		}
//	  ===================================================
		public static void FillArray(int rows, int cols, int[,] dynArray, int min, int max, int randomDigit, int randomNumber)
		{
			int ii;  
			int jj;
			for (ii = 0; ii < rows; ii++)
				for (jj = 0; jj < cols; jj++)
					dynArray[ii, jj] = ii + jj;

			randomDigit = randomNumber.Next(min, max);
			Console.WriteLine(randomDigit);

		}
//	  =======================================
		public static void PrintArray(int rows, int cols, int[,] dynArray)
		{
			int ii;
			int jj;
			for (ii = 0; ii < rows; ii++)
			{
				for (jj = 0; jj < cols; jj++)
					Console.Write(dynArray[ii, jj] + " ");
				Console.WriteLine();
			}



Thanks again for any and all suggestions you can make for me.
CrazyJ
Was This Post Helpful? 0
  • +
  • -

#4 CrazyJ  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 51
  • Joined: 15-October 07

Re: Instantiate an array, fill with random numbers

Posted 16 October 2007 - 08:43 AM

I am posting in regard to an earlier post, "Instantiate an array, fill with random numbers". I got some great feedback, but it is not in the context of my program requirement. I apologize if this is viewed as "leaving the thread" but I wasnt sure if a reply would generate further advice. The following is my psuedocode, and code so far. I am not sure how to remedy this, as I am just picking up on C#. Thanks in advance.

Get 2 integers from user, called m and n.
option to iterate if values entered are not valid.
create array using m for rows, and n for cols.

Then Get 2 more integers from user called minValue and maxValue
generate range of random numbers between minValue and maxValue
fill array with random numbers


I am getting errors Errors: "No overload for method 'FillArray' takes '5' arguments" "No overload for method 'FillArray' takes '2' arguments" and "int does not contain a definition for Next."

//  =============
	class Program
	{
//	  ==============================
		static void Main(string[] args)
		{
//		  =====
			int m;
			int n;
			int minValue;
			int maxValue;
			int randomDigit;
			int[,] numbers = new int[1,1];
//		  ===================================
			Random randomNumber = new Random(); // randomNumber declaration
//		  ====================================
			MyMethods.Get(out m,2,int.MaxValue);
			MyMethods.Get(out n, 2, int.MaxValue);

			MyMethods.BuildArray(m, n,ref numbers);

			MyMethods.Get(out minValue, int.MinValue, int.MaxValue);
			MyMethods.Get(out maxValue, minValue, int.MaxValue);

			MyMethods.FillArray(m, n, numbers, minValue, maxValue);
			MyMethods.FillArray(randomNumber, randomDigit);
			MyMethods.PrintArray(m, n, numbers);
			Console.ReadLine();



and MyMethods

class MyMethods
	{
//	  ================================
		public static void Get(out int value, int min, int max)
		{
			string numString;
			do
			{
				Console.WriteLine("Please enter a number between " + min + " and " + max);
				Console.WriteLine();
				numString = Console.ReadLine();
				value = int.Parse(numString);
			} while (!((value >= min) && (value <= max)));
		}
//	 ==========================================	   
		public static void BuildArray(int rows, int cols, ref int [,] dynArray )
		{
			dynArray = new int[rows, cols];
		}
//	  ===================================================
		public static void FillArray(int rows, int cols, int[,] dynArray, int min, int max, int randomDigit, int randomNumber)
		{
			int ii;  
			int jj;
			for (ii = 0; ii < rows; ii++)
				for (jj = 0; jj < cols; jj++)
					dynArray[ii, jj] = ii + jj;

			randomDigit = randomNumber.Next(min, max);
			Console.WriteLine(randomDigit);

		}
//	  =======================================
		public static void PrintArray(int rows, int cols, int[,] dynArray)
		{
			int ii;
			int jj;
			for (ii = 0; ii < rows; ii++)
			{
				for (jj = 0; jj < cols; jj++)
					Console.Write(dynArray[ii, jj] + " ");
				Console.WriteLine();
			}




Was This Post Helpful? 0
  • +
  • -

#5 Martyr2  Icon User is online

  • Programming Theoretician
  • member icon

Reputation: 4337
  • View blog
  • Posts: 12,141
  • Joined: 18-April 07

Re: Instantiate an array, fill with random numbers

Posted 16 October 2007 - 09:28 AM

Other than maybe creating an array first and passing it to the function to then be filled the advice I gave you last time EXACTLY fits your pseudo code there. Do remember I gave you an example of how to use the function. If you need to pass in the array to be filled, you just add it to the function I gave you and use that instead of creating one inside the function.

I used the listbox and button just to show you the functionality of the function (this is known as a driver program or a test harness)... your answer is the function I wrote. I know the listbox is not part of your project. I never said it was.

I guess the key to your whole thing is that you need to use the user's rows and column numbers in the declaration of the multidimensional array. I show you how right in the function I had given to you in the old post.

And in the future do stick with the old thread because people landing on this thread now have no idea what was proposed earlier. For those who want to see what was said earlier, the thread is listed below. If you are a mod and want to merge them, feel free.

http://www.dreaminco...h...c=35399&hl=

Go back and take another look at that function CrazyJ. If you need to pass an array to the function, add it to the function header and use that instead of declaring "newarray".

:)
Was This Post Helpful? 0
  • +
  • -

#6 Jayman  Icon User is offline

  • Student of Life
  • member icon

Reputation: 418
  • View blog
  • Posts: 9,532
  • Joined: 26-December 05

Re: Instantiate an array, fill with random numbers

Posted 16 October 2007 - 10:22 AM

Merged topics.
Was This Post Helpful? 0
  • +
  • -

#7 CrazyJ  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 51
  • Joined: 15-October 07

Re: Instantiate an array, fill with random numbers

Posted 17 October 2007 - 09:44 AM

I had a feeling I was going to receive a rebuke as a result of my new post/double post. I am just becoming accustomed to this forum, and C#. So, that said, I duly apologize for any inconvenience to the users of this forum, and the mod whom intervened. Thanks for the clarification Martyr2, please forgive my lack of expertise, as stated previously, I am a novice and will no doubt grow my knowledge of C# through many waning hours, coding intermediate programs. :)


View PostMartyr2, on 16 Oct, 2007 - 09:28 AM, said:

Other than maybe creating an array first and passing it to the function to then be filled the advice I gave you last time EXACTLY fits your pseudo code there. Do remember I gave you an example of how to use the function. If you need to pass in the array to be filled, you just add it to the function I gave you and use that instead of creating one inside the function.

I used the listbox and button just to show you the functionality of the function (this is known as a driver program or a test harness)... your answer is the function I wrote. I know the listbox is not part of your project. I never said it was.

I guess the key to your whole thing is that you need to use the user's rows and column numbers in the declaration of the multidimensional array. I show you how right in the function I had given to you in the old post.

And in the future do stick with the old thread because people landing on this thread now have no idea what was proposed earlier. For those who want to see what was said earlier, the thread is listed below. If you are a mod and want to merge them, feel free.

http://www.dreaminco...h...c=35399&hl=

Go back and take another look at that function CrazyJ. If you need to pass an array to the function, add it to the function header and use that instead of declaring "newarray".

:)

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1