Random Array generator in c # - c#

I need to create an array with a specific number of rows and columns based on user input.
So far I have :
Console.WriteLine("Please enter the number of rows: ");
int rows = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please enter the number of columns: ");
int cols = Convert.ToInt32(Console.ReadLine());
int[,] board = new int[rows, cols];
How do I take this information and then make a random list that goes up based on the entered information?
so it looks like this,
rows=2 colums =3
1 2 3
4 5 6

The program you want has two steps, but can be achieved in one. First create the 2d array, then set the value for each grid index. This can be achieved in one method.
First declare your new grid and counter. Then loop through every column in every row and set the value of each index as the counter + 1. This will count as the loop goes through ever position. For clarity here's an image of what this method would look like, having it take the number of rows and columns as a parameter.
void CreateGrid(int rows, int cols)
{
int[,] Grid = new int[cols, rows];
//create the grid
int counter = 0;
//Intailized the counter
for(int i = 0; i < rows; i++)
{
//loops through every column
Console.WriteLine("");
//Creates a newline to write the columns on.
for (int j = 0; j < cols; j++)
{
//Gos through every column.
Grid[j, i] = counter++;
//Sets the current grid position
//as the current counter number.
Console.Write(" " + Grid[j, i]);
//Writes that grid number in the current line
}
}
}

You need to use two loops for each row and column.
Console.WriteLine("Please enter the number of rows: ");
int rows = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please enter the number of columns: ");
int cols = Convert.ToInt32(Console.ReadLine());
int[,] board = new int[rows, cols];
var r = new Random();
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
board[i, j] = r.Next(0, 10);
Console.Write(board[i, j]);
}
Console.WriteLine();
}
Then it gives an output like this:

Create a factory class that contains all the methods to generate array structures.
public static class Factory
{
static readonly Random rng = new Random();
public static int[] CreateRandomArray(int size, int minValue, int maxValue)
=> CreateRandomArray(rng, size, minValue, maxValue);
public static int[] CreateRandomArray(this Random rng, int size, int minValue, int maxValue)
{
var array = new int[size];
for (int i = 0; i < array.Length; i++)
{
array[i] = rng.Next(minValue, maxValue);
}
return array;
}
public static int[,] CreateRandomArray2(int rows, int cols, int minValue, int maxValue)
=> CreateRandomArray2(rng, rows, cols, minValue, maxValue);
public static int[,] CreateRandomArray2(this Random rng, int rows, int cols, int minValue, int maxValue)
{
var matrix = new int[rows, cols];
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
matrix[i, j] = rng.Next(minValue, maxValue);
}
}
return matrix;
}
public static double[] CreateRandomVector(int size, double minValue, double maxValue)
=> CreateRandomVector(rng, size, minValue, maxValue);
public static double[] CreateRandomVector(this Random rng, int size, double minValue, double maxValue)
{
var array = new double[size];
for (int i = 0; i < array.Length; i++)
{
array[i] = minValue + (maxValue-minValue) * rng.NextDouble();
}
return array;
}
public static double[,] CreateRandomMatrix(int rows, int cols, double minValue, double maxValue)
=> CreateRandomMatrix(rng, rows, cols, minValue, maxValue);
public static double[,] CreateRandomMatrix(this Random rng, int rows, int cols, double minValue, double maxValue)
{
var matrix = new double[rows, cols];
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
matrix[i, j] = minValue + (maxValue-minValue) * rng.NextDouble();
}
}
return matrix;
}
}
To be used like:
class Program
{
static void Main(string[] args)
{
int[,] A = Factory.CreateRandomArray2(rows: 2, cols: 3, minValue: 0, maxValue: 9);
double[] b = Factory.CreateRandomVector(size: 9, minValue: -1.0, maxValue: 1.0);
}
}
or as an extension method to an existing random number generator Random
class Program
{
static readonly Random random = new Random();
static void Main(string[] args)
{
int[,] A = random.CreateRandomArray2(rows: 2, cols: 3, minValue: 0, maxValue: 9);
double[] b = random.CreateRandomVector(size: 9, minValue: -1.0, maxValue: 1.0);
}
}

Related

how can i sort a matrix's each row from smallest to largest and then find the matrix's peak value?

i need to write a program that takes 1 to 100 integers randomly, then i need to take this program's transpose, then I need to sort this matrix (each row in itself) from smallest to largest.
and finally, i need to find this matrix's peak value. here is what i have written for the program. for now, it creates a random matrix (20x5) and then it takes its transpose. can you help me with finding its peak value and then sort its each row?
PS.: using classes is mandatory!
using System;
namespace my_matrix;
class Program
{
public int[,] Create(int[,] myarray, int Row, int Clm)
{
Random value = new Random();
myarray = new int[Row, Clm];
int i = 0;
int j = 0;
while (i < Row)
{
while (j < Clm)
{
myarray[i, j] = value.Next(1, 100);
j++;
}
i++;
j = 0;
}
return myarray;
}
public int[,] Print(int[,] myarray, int Row, int Clm)
{
Console.WriteLine("=====ARRAY=====");
for (int a = 0; a < Row; a++)
{
for (int b = 0; b < Clm; b++)
{
Console.Write(myarray[a, b] + " ");
}
Console.WriteLine();
}
return null;
}
public int[,] Transpose(int[,] myarray, int Row, int Clm)
{
for (int b = 0; b < Clm; b++)
{
for (int a = 0; a < Row; a++)
{
Console.Write(myarray[a, b] + " ");
}
Console.WriteLine();
}
return myarray;
}
public int[,] Print_Transpose(int[,] myarray, int Row, int Clm)
{
Console.WriteLine("=====TRANSPOSE=====");
for (int b = 0; b < Clm; b++)
{
for (int a = 0; a < Row; a++)
{
Console.Write(myarray[a, b] + " ");
}
Console.WriteLine();
}
return null;
}
static void Main(string[] args)
{
Program x = new Program();
int[,] myarray = new int[20, 5];
int[,] a = x.Create(myarray, 20, 5);
x.Print(a, 20, 5);
x.Print_Transpose(a, 20, 5);
}
}
i don't know how to make a class which sorta each row from smallest to largest and also i dont know how to create a class which finds the matrix's peak value.
You can run over the array, keeping the maxNum:
public int getMax(int[,] fromArray)
{
int maxNum = 0;
for (int b = 0; b < fromArray.GetUpperBound(1); b++)
{
for (int a = 0; a < fromArray.GetUpperBound(0); a++)
{
if (maxNum < fromArray[a,b])
{
maxNum = fromArray[a, b];
}
}
}
return maxNum;
}
Call the function like:
Console.Write("Max number = {0:D}", x.getMax (a));
If you want a sort method, you can place all values in a List, sort them and convert back to array.
public int[] SortArray(int[,] fromArray)
{
List<int> newList = new List<int>(fromArray.Length);
for (int b = 0; b < fromArray.GetUpperBound(1); b++)
{
for (int a = 0; a < fromArray.GetUpperBound(0); a++)
{
newList.Add (fromArray[a, b]);
}
}
newList.Sort();
return newList.ToArray<int>();
}

I want to return the sum of the numbers of each row of the matrix, but my program returns zero. What is the problem with my program?

I want to return the sum of the numbers of each row of the matrix, but my program returns zero. What is the problem with my program?
public class Row_summer
{
public int[] summ(int[,] input, int rows, int columns)
{
int sum=0;
int[] sum_of_rows = new int[rows];
input = new int[rows, columns];
for(int i = 0; i >=rows; i++)
{
for(int j=0; j >= columns;j++)
{
sum = sum + input[i, j];
}
sum_of_rows[i] = sum;
}
return sum_of_rows;
}
}
I changed all the values to integer but it still returns zero value. I noticed that it exits the loop before completing the loop count
you use >= instead of < in the loop condition.
Correct code would look something like this:
public class Row_summer
{
public int[] summ(int[,] input, int rows, int columns)
{
int sum=0;
int[] sum_of_rows = new int[rows];
input = new int[rows, columns];
for(int i = 0; i < rows; i++)
{
for(int j=0; j < columns;j++)
{
sum = sum + input[i, j];
}
sum_of_rows[i] = sum;
}
return sum_of_rows;
}
}
Also, you may want to move int sum = 0 into the outer loop:
public class Row_summer
{
public int[] summ(int[,] input, int rows, int columns)
{
int[] sum_of_rows = new int[rows];
input = new int[rows, columns];
for(int i = 0; i < rows; i++)
{
int sum=0;
for(int j=0; j < columns;j++)
{
sum = sum + input[i, j];
}
sum_of_rows[i] = sum;
}
return sum_of_rows;
}
}

SubArray of a 2d array with non-zero lower bounds

The extension :
public static T[,] SubArray<T>(this T[,] values, int row_min, int row_max, int col_min, int col_max)
{
int num_rows = row_max - row_min + 1;
int num_cols = col_max - col_min + 1;
T[,] result = new T[num_rows, num_cols];
int total_cols = values.GetUpperBound(1) + 1;
int from_index = row_min * total_cols + col_min;
int to_index = 0;
for (int row = 0; row <= num_rows - 1; row++)
{
Array.Copy(values, from_index, result, to_index, num_cols);
from_index += total_cols;
to_index += num_cols;
}
return result;
}
work well for 2D arrays arrays whose GetLowerBound(0) and GetLowerBound(1) are equal to zero. For instance if
int[,] arr1 = new int[5, 4];
for (int i = 0; i < 5; ++i)
{
for (int j = 0; j < 4; ++j)
{
arr1[i, j] = i + j;
}
}
var arr1sub = arr1.SubArray(2, 3, 1, 3);
Then arr1sub is the 2d array with 2 rows and 3 colums (boths with indexes starting at 0)
3 4 5
5 6 7
Now if I look at the case where the initial array as indexes not starting at zero :
int[,] arr2 = (int[,])Array.CreateInstance(typeof(int), new int[] { 5, 4 }, new int[] { 3, 1 });
for (int i = arr2.GetLowerBound(0); i <= arr2.GetUpperBound(0); ++i)
{
for (int j = arr2.GetLowerBound(1); j <= arr2.GetUpperBound(1); ++j)
{
arr2[i, j] = i - arr2.GetLowerBound(0) + j - arr2.GetLowerBound(1);
}
}
var arr2sub = arr2.SubArray(5, 6, 2, 4);
the last line of previous code snippet will trigger an exception in the SubArray extension function at the line
Array.Copy(values, from_index, result, to_index, num_cols);
for row equal to zero.
I understand of the 2d array arr1 (with zero based indexes) is layed out in memory but not how the 2d array arr2 (with non-zero-based indexes) is layed out in memory, hence my use of Array.Copy must be wrong in this case, but I don't see why.
You are not calculating total_cols and from_index correctly.
public static T[,] SubArray<T>(this T[,] values, int row_min, int row_max, int col_min, int col_max)
{
int num_rows = row_max - row_min + 1;
int num_cols = col_max - col_min + 1;
T[,] result = new T[num_rows, num_cols];
int total_cols = values.GetLength(1);
int from_index = (row_min - values.GetLowerBound(0)) * total_cols + (col_min - values.GetLowerBound(1)) + values.GetLowerBound(0);
int to_index = 0;
for (int row = 0; row <= num_rows - 1; row++)
{
Array.Copy(values, from_index, result, to_index, num_cols);
from_index += total_cols;
to_index += num_cols;
}
return result;
}
total_cols is the obvious one; as for from_index, I cannot find any documentation on that, but it would appear that sourceIndex in Array.Copy starts counting from sourceArray.GetLowerBound(0) and not from zero, which is not necessarily immediately obvious given that this index keeps growing across rows and columns.

Random 2D array without 3 same in a row or column

Hello looking for solution to fill 2D array with random values from 1-8 without 3 same numbers next to each other in a column or in a row.
Random random = new Random();
for (var row = 0; row < RowCount; row++)
{
for (var column = 0; column < RowCount; column++)
{
tiles[row, column] = random.Next(1, 8);
}
}
Idea is simple: fill your matrix from right to left and from top to down. To avoid duplicates at any cell look two cells up and two cells left, and if they have same value, call random.Next(..) again. Next code will create that matrix:
// this method checks cells that up to current
private static bool EqualsUp(int i, int j, int[,] matrix, int value) => i >= 0 && matrix[i, j] == value;
// this method checks cells that left to current
private static bool EqualsLeft(int i, int j, int[,] matrix, int value) => j >= 0 && matrix[i, j] == value;
public static int[,] GenerateMatrix(int h, int w)
{
var matrix = new int[h, w];
var random = new Random();
for (var i = 0; i < h; ++i)
for (var j = 0; j < w; ++j)
while (true)
{
var cellValue = random.Next(1, 9); // note: second value is exclusive, so to generate values from 1 to 8 pass 9 as second argument
if (EqualsUp(i - 1, j, matrix, cellValue) && EqualsUp(i - 2, j, matrix, cellValue))
continue; // need to regenerate cellValue
if (EqualsLeft(i, j - 1, matrix, cellValue) && EqualsLeft(i, j - 2, matrix, cellValue))
continue; // need to regenerate cellValue
matrix[i, j] = cellValue;
break;
}
return matrix;
}

returning random int from method to array

In my code i have static int method that should return an array of random integers. The problem is when i print an array, only the last number is random int, and other ints are all zeros.
static void Main(string[] args)
{
int a = int.Parse(Console.ReadLine());
int[] array = mtd(a);
for (int i = 0; i < array.Length; i++)
{
Console.WriteLine(array[i]);
}
}
public static int[] mtd(int b)
{
int[] arr = new int[b];
Array.Resize<int>(ref arr, b);
Random rand = new Random();
for (int i = 0; i < arr.Length; i++)
{
arr.SetValue(rand.Next(1, 5), arr.Length - 1);
}
return arr;
}
In the for loop in your method mtd you are always setting the last value of your array arr by using arr.Length - 1. Use i instead:
for (int i = 0; i < arr.Length; i++)
{
arr[i] = rand.Next(1, 5);
}
Or with arr.SetValue:
for (int i = 0; i < arr.Length; i++)
{
arr.SetValue(rand.Next(1, 5), i);
}
Working one :
public static int[] mtd(int b)
{
int[] arr = new int[b];
Random rand = new Random();
for (int i = 0; i < arr.Length; i++)
{
arr.SetValue(rand.Next(1, 5), i);
}
return arr;
}
EDIT : Btw the Array.resize is useless here, you already define the length of your array. ( new int[b] set the length of the array to b )
Your problem was that you never used i, so you just set the value of the last value of your array.
I modified and simplified your code:
public static int[] mtd(int b)
{
int[] arr = new int[b];
Random rand = new Random();
for (int i = 0; i < arr.Length; i++)
arr[i] = rand.Next(1, 5);
return arr;
}

Categories