Int array throw an exception in c# - c#

Why this code is throw an exception?
int n = 10;
int[] arr = null;
for (int i = 0; i < n; i++)
{
arr[i] = i * 2;
}
Any one can help?

You have to init your array first int[] arr = new int[n];
int n = 10;
int[] arr = new int[n];
for (int i = 0; i < n; i++)
{
arr[i] = i * 2;
}

You have to initialize an array. This also has to be a fixed size, you cannot expand the lend of an array like you can with a List
you could do:
int n = 10;
int[] arr = new int[n];
for (int i = 0; i < n; i++)
{
arr[i] = i * 2;
}
This will initialise an array of length 10 then populate numbers.
Or with a list:
int n = 10;
List<int> arr = new List<int>();
for (int i = 0; i < n; i++)
{
arr.Add(i * 2);
}
Notice we do not define the length of the list like we do for the array. We then go on and add elements as we want rather than a maximum of n.

You have to declare a new array with defined values instead of null. Like the code below. :).
int n = 10;
int[] arr = new int[n];
for (int i = 0; i < n; i++)
{
arr[i] = i * 2;
}

Related

Fill 2d array with unique random numbers from 0 to 15 C#

I can't fill it with numbers to 0 - 15 then shuffle the array, so that's not the solution
I used this code in C but now in c# it doesn't work, for some reason this code let some numbers pass the do while.
Random r = new Random();
bool unique;
int rand_num;
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
do
{
unique = true;
rand_num = r.Next(16);
for (int k = 0; k < 4; k++)
{
for (int l = 0; l < 4; l++)
{
if (numbers[k, j] == rand_num)
{
unique = false;
}
}
}
} while (!unique);
numbers[i, j] = rand_num;
}
}
}
If the list of possible numbers is small, as in this case, just create the full list and randomise it first, then take the items in the order they appear. In your case, you can put the randomised numbers into a queue, then dequeue as required.
var r = new Random();
var numberQueue = new Queue<int>(Enumerable.Range(0, 16).OrderBy(n => r.NextDouble()));
var numbers = new int[4, 4];
for (var i = 0; i <= numbers.GetUpperBound(0); i++)
{
for (var j = 0; j <= numbers.GetUpperBound(1); j++)
{
numbers[i, j] = numberQueue.Dequeue();
}
}
I suggest you to use the Fisher-Yates algorithm to generate your non-repeatable sequence of random numbers.
It would be very straight-forward to implement a code to fill in a 2d array with those numbers, then.
List<int> seq = Enumerable.Range(0,16).ToList();
int[,] numbers = new int[4,4];
Random r = new();
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
int n = r.Next(0, seq.Count);
numbers[i,j] = seq[n];
seq.RemoveAt(n);
}
}
The approach you have taken may end up in continuous looping and take lot of time to complete.
Also checking for value in 2D using nested for loop is not efficient.
You can use HashSet to keep track of unique value. Searching in HashSet is fast.
following is the code approach I suggest.
var hashSet = new HashSet<int>();
var r = new Random();
var arr = new int[4, 4];
for(var i = 0;i<4;i++)
{
for(var j = 0;j<4;j++)
{
// Generate random value between 0 and 16.
var v = r.Next(0, 16);
// Check if the hashSet has the newly generated random value.
while(hashSet.Contains(v))
{
// generate new random value if the hashSet has the earlier generated value.
v = r.Next(0, 16);
}
//Add value to the hashSet.
hashSet.Add(v);
// add value to the 2D array.
arr[i, j] = v;
}
}
I hope this will help solving your issue.
The problem with your current approach is that as you get closer to the end of the array, you have to work harder and harder to get the next random value.
Imagine you roll a die, and each time you want to get a unique value. The first time you roll, any result will be unique. The next time, you have a 1/6 chance of getting a number that has already been obtained. And then a 2/6 chance, etc. and in the end most of your rolls will be non-unique.
In your example, you have 16 places that you want to fill with numbers 0 to 15. This is not a case of randomly generating numbers, but randomly placing them. How do we do this with a deck of cards? We shufle them!
My proposal is that you fill the array with unique sequential values and then shuffle them:
Random random = new Random();
int dim1 = array.GetLength(0);
int dim2 = array.GetLength(1);
int length = dim1 * dim2;
for (int i = 0; i < length; ++i)
{
int x = i / dim1;
int y = i % dim1;
array[x, y] = i; // set the initial values for each cell
}
// shuffle the values randomly
for (int i = 0; i < length; ++i)
{
int x1 = i / dim1;
int y1 = i % dim1;
int randPos = random.Next(i, length);
int x2 = randPos / dim1;
int y2 = randPos % dim1;
int tmp = array[x1, y1];
array[x1, y1] = array[x2, y2];
array[x2, y2] = tmp;
}
The shuffle in this code is based on the shuffle found here
int[,] numbers = new int[4, 4];
Random r = new Random();
bool unique;
int rand_num;
List<int> listRandom = new List<int> { };
for ( int i = 0; i < 4; i++ )
{
for ( int j = 0; j < 4; j++ )
{
do
{
unique = false;
if (!listRandom.Contains( rand_num = r.Next( 0, 16 )))
{
listRandom.Add( rand_num );
numbers[i, j] = rand_num;
unique = true;
}
} while ( !unique );
}
}

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;
}

Variable parameter in the definition of array

I have the following code, which creates a 2D array in a nested loop, What I want to do is to create this 2D array each iteration but with name concatenated to "j" value . For example,
In first iteration the result will be : double[,] visualmatrix1.
I tried to put +j but it fails.
ExtractDescriptorsForm ex = new ExtractDescriptorsForm(65,10);
int a = ex.m_maxExtract;
for (int i = 0; i < m_descriptor.visualword.Length; i++)
{
for (int j = 0; j < a; j++)
{
double[,] visualmatrix = new double[m_descriptor.visualword.Length, 2];
visualmatrix[i, 0] = m_descriptor.visualword[i].identifier;
visualmatrix[i, 1] = (m_descriptor.visualword[i].tf) * (m_descriptor.visualword[i].idf);
}
}
Since your code lost the new-created array inside the loops, you should use a list to store the 2D arrays.
List<double[,]> arrays = new List<double[,]>();
ExtractDescriptorsForm ex = new ExtractDescriptorsForm(65,10);
int a = ex.m_maxExtract;
for (int i = 0; i < m_descriptor.visualword.Length; i++)
{
for (int j = 0; j < a; j++)
{
double[,] visualmatrix = new double[m_descriptor.visualword.Length, 2];
visualmatrix[i, 0] = m_descriptor.visualword[i].identifier;
visualmatrix[i, 1] = (m_descriptor.visualword[i].tf) * (m_descriptor.visualword[i].idf);
arrays.Add(visualmatrix);
}
}
Then access it by
arrays[n]

Create number for random and non repeat

i'm code:
Random rand = new Random();
int[] arr = new int[4];
for (int i = 0; i < 4; i++)
{
for (int k = 0; k < 4; k++)
{
int rad = rand.Next(1, 5);
if (arr[k] != rad)
arr[i] = rad;
}
}
for (int i = 0; i < 4; i++)
MessageBox.Show(arr[i].ToString());
I wanna production numbers from 1 to 4 am and unequal with each other.
tnx.
Think it the other way round:
instead of:
generating a number and then check it if it is not duplicate
you make it such that:
you already have a set of non-duplicate numbers, then you take it
one-by-one - removing the possibilities of duplicates.
Something like this will do:
List<int> list = Enumerable.Range(1, 4).ToList();
List<int> rndList = new List<int>();
Random rnd = new Random();
int no = 0;
for (int i = 0; i < 4; ++i) {
no = rnd.Next(0, list.Count);
rndList.Add(list[no]);
list.Remove(list[no]);
}
The result is in your rndList.
This way, no duplicate will occur.
Create an array with unique elements and then shuffle it, like in the code below, it will shuffle an array in uniformly random order it uses Fisher-Yates shuffle algorithm:
int N = 20;
var theArray = new int[N];
for (int i = 0; i < N; i++)
theArray[i] = i;
Shuffle(theArray);
public static void Shuffle(int[] a) {
if (a == null) throw new ArgumentNullException("Array is null");
int n = a.Length;
var theRandom = new Random();
for (int i = 0; i < n; i++) {
int r = i + theRandom.Next(n-i); // between i and n-1
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
Explanation and template version of algorithm could be found in this post with nice answer from Jon Skeet.
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source, Random rng)
{
T[] elements = source.ToArray();
// Note i > 0 to avoid final pointless iteration
for (int i = elements.Length-1; i > 0; i--)
{
// Swap element "i" with a random earlier element it (or itself)
int swapIndex = rng.Next(i + 1);
T tmp = elements[i];
elements[i] = elements[swapIndex];
elements[swapIndex] = tmp;
}
// Lazily yield (avoiding aliasing issues etc)
foreach (T element in elements)
{
yield return element;
}
}
Create a list containing the numbers you want, then shuffle them:
var rnd = new Random();
List<int> rndList = Enumerable.Range(1, 4).OrderBy(r => rnd.Next()).ToList();
If you want an array instead of a list:
var rnd = new Random();
int[] rndArray = Enumerable.Range(1, 4).OrderBy(r => rnd.Next()).ToArray();
int[] arr = new int[5];
int i = 0;
while (i < 5)
{
Random rand = new Random();
int a = rand.Next(1,6);
bool alreadyexist = false;
for (int j = 0; j < 5; j++)
{
if (a == arr[j])
{
alreadyexist = true;
}
}
if (alreadyexist == false)
{
arr[i] = a;
i++;
}
}
for (int k = 0; k < 5; k++)
{
MessageBox.Show(arr[k].ToString());
}

C# Resorting an array in a unique way

I am wanting to create multiple arrays of ints(in C#). However they all must have a unique number in the index, which no other array has that number in that index. So let me try show you what I mean:
int[] ints_array = new int[30];
for (int i = 0; i < ints_array.Count(); i++)
ints_array[i] = i;
//create a int array with 30 elems with each value increment by 1
List<int[]> arrayList = new List<int[]>();
for(int i = 0; i < ints_array.Count(); i++)
arrayList.Add(ints_array[i]. //somehow sort the array here randomly so it will be unique
So I am trying to get the arrayList have 30 int[] arrays and each is sorted so no array has the same int in the same index as another.
Example:
arrayList[0] = {5,2,3,4,1,6,7,8,20,21... etc }
arrayList[1] = {1,0,5,2,9,10,29,15,29... etc }
arrayList[2] = {0,28,4,7,29,23,22,17... etc }
So would this possible to sort the array in this unique kind of way? If you need anymore information just ask and ill fill you in :)
Wouldn't it be easier to create the arrays iteratively using an offset pattern?
What I mean is that if you created the first array using 1-30 where 1 is at index 0, the next array could repeat this using 2-30 where 2 is at index 0 and then wrap back to 1 and start counting forward again as soon as you go past 30. It would be an easy and repeatable way to make sure no array shared the same value/index pair.
You can do it like that:
List<int[]> arrayList = new List<int[]>();
Random rnd = new Random();
for (int i = 0; i < ints_array.Length; i++)
{
ints_array = ints_array.OrderBy(x => rnd.Next()).ToArray();
var isDuplicate = arrayList.Any(x => x.SequenceEqual(ints_array));
if (isDuplicate)
{
while (arrayList.Any(x => x.SequenceEqual(ints_array)))
{
ints_array = ints_array.OrderBy(x => rnd.Next()).ToArray();
}
}
arrayList.Add(ints_array);
}
I think, this wouldn't be so efficient for bigger numbers than 30.But in this case it shouldn't be a problem, in my machine it takes 7 milliseconds.
Jesse's idea would be best unless you needed a pure random pattern. In that case I would recommend generating a random number, checking all your previous arrays, and then placing it in an array if it did not match any other arrays current index. Otherwise, generate a new random number until you find a fresh one. Put that into a loop until all your arrays are filled.
Use a matrix (2D-array). It is easier to handle than a list of arrays. Create a random number generator. Make sure to initialize it only once, otherwise random number generator may create bad random numbers, if created in too short time intervals, since the slow PC-clock might not have ticked in between. (The actual time is used as seed value).
private static Random random = new Random();
Create two helper arrays with shuffeled indexes for rows and columns:
const int N = 30;
int[] col = CreateUniqueShuffledValues(N);
int[] row = CreateUniqueShuffledValues(N);
Then create and initialize the matrix by using the shuffeled row and column indexes:
// Create matrix
int[,] matrix = new int[N, N];
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
matrix[row[i], col[j]] = (i + j) % N;
}
}
The code uses these two helper methods:
private static int[] CreateUniqueShuffledValues(int n)
{
// Create and initialize array with indexes.
int[] array = new int[n];
for (int i = 0; i < n; i++) {
array[i] = i;
}
// Shuffel array using one variant of Fisher–Yates shuffle
// http://en.wikipedia.org/wiki/Fisher-Yates_shuffle#The_modern_algorithm
for (int i = 0; i < n; i++) {
int j = random.Next(i, n);
Swap(array, i, j);
}
return array;
}
private static void Swap(int[] array, int i, int j)
{
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
int size = 10;
// generate table (no duplicates in rows, no duplicates in columns)
// 0 1 2
// 1 2 0
// 2 0 1
int[,] table = new int[size, size];
for (int y = 0; y < size; y++)
for (int x = 0; x < size; x++)
table[y, x] = (y + x) % size;
// shuffle rows
Random rnd = new Random();
for (int i = 0; i < size; i++)
{
int y1 = rnd.Next(0, size);
int y2 = rnd.Next(0, size);
for (int x = 0; x < size; x++)
{
int tmp = table[y1, x];
table[y1, x] = table[y2, x];
table[y2, x] = tmp;
}
}
// shuffle columns
for (int i = 0; i < size; i++)
{
int x1 = rnd.Next(0, size);
int x2 = rnd.Next(0, size);
for (int y = 0; y < size; y++)
{
int tmp = table[y, x1];
table[y, x1] = table[y, x2];
table[y, x2] = tmp;
}
}
// sample output
for (int y = 0; y < size; y++)
{
for (int x = 0; x < size; x++)
Console.Write("{0} ", table[y, x]);
Console.WriteLine();
}

Categories