Index OutOfRangeException - c#

I am trying to put an integer inside the array by subtracting the initialized value in every loop. This code seems right for me, but the compiler always claims that "Index was outside the bounds of the array.". Am I doing something wrong here particularly in itr part?
static void Main()
{
int itr = 0;
int[] arr = {};
for(int i = 2305; i > 0; i-=576)
{
arr[itr] = i;
itr+=1;
}
Console.ReadLine();
}

This line creates an empty array (so the Length is 0):
int[] arr = {};
You should specify a size for your array.In your case the size could be:
int[] arr = new int[2305 / 576 + 1];

Your int array 'arr' is of length 0;
Because you aren't setting a size, or values for it, the array has no value at all.
this is an iteration that will work;
int[] arr = new int[ 1000 ];
int itr = 2305;
for ( int i = arr.Length-1; i > -1; i-- ) {
itr -= 576;
arr[ i ] = itr;
}

Related

Pass reference array as argument in c# [duplicate]

This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed 1 year ago.
dears ,
i had create a method that will retrieve three arrays after filling them using the ref option
the following error is presented "System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'"
the code as below. how I can fix it
namespace ConsoleApp9
{
class Program
{
public static int getarrays(ref string[] patternName, ref int[] loadindex, ref double[] loadFactor)
{
int status = 0;
for (int i = 0; i < 4; i++)
{
patternName[i] = "test";
}
for (int i = 0; i < 5; i++)
{
loadindex[i] = i;
}
for (int i = 0; i < 8; i++)
{
loadFactor[i] = i/10;
}
return status;
}
static void Main(string[] args)
{
string[] ptt = new string[1];
int[] index = new int[1];
double[] factor = new double[1];
getarrays(ref ptt,ref index, ref factor);
}
}
}
Your arrays all have a size of 1, but your loops go to 4, 5 and 8 respectively. Instead, use the Length property of your arrays in your loops:
for (int i = 0; i < patternName.Length; i++)
{
patternName[i] = "test";
}
This is helpful, because the size of your array is only located in one place (at the creation of the arrays).
You are passing arrays with fixed size of 1. Inside your method, you are iterating for 4, 5 and 8 times while your arrays have length of 1. You should make a constants of pttSize, indexSize and factorSize and use them as arrays size and loops length.
You are passing arrays of length 1 to the function and then try to access indices greater than 0.
Adapt your Main method to pass arrays of the correct length:
string[] ptt = new string[4];
int[] index = new int[5];
double[] factor = new double[8];

Loop nested loops

I would like to create a nested loop where the nesting depth determined by the size on an array. For example I have an array of integers and I would like to check all tuples where . Is there a way to do this simply in c# (or any other language)?
The only easy idea I had was to just multiply the numbers and do a for loop up to that number but unfortunately the product reaches the int limit. Also in this case I have no way to add extra conditions on each level.
Here's a small example and the product approach:
int[] a = new int[]{2, 3, 2}; //we have an array like this. In the description above it is a_1, a_2, a_3
void f(int[] i) //I have a function that works on an array input
{...}
bool check(int[] i) //I have a checker function, with an array parameter too
{...}
//And I would like to perform this function on all these arrays
//f({0, 0, 0})
//f({0, 0, 1})
//010
//011
//020
//021
//100
//101
//110
//111
//120
//f({1, 2, 1})
//But if let's say check({1, 0}) is false then don't perform the f function on {1, 0, 0} and {1, 0, 1}
//A simple implementation if we know the size of the array a is the following
for(int i1=0;i1<a[0];i1++)
{
if(!check({i1}))
continue;
for(int i2=0;i2<a[1];i2++)
{
if(!check({i1, i2}))
continue;
for(int i3=0;i3<a[2];i3++)
{
if(!check({i1, i2, i3}))
continue;
f({i1, i2, i3});
}
}
}
//But this obviously fails as we have no idea apriori of the size of the array a
//An alternative I have is the following:
int prod = 1;
foreach(int x in a)
{
prod *= x;
}
for(int c=0;c<prod;c++)
{
int d=c;
int[] i = new int[a.Length];
for(int l=0;l<a.Length;l++)
{
i[l]=d%(a[l]);
d /= a[l];
}
f(i);
}
//But the problem with this implementation is that in my case prod is larger than the int limit. Also this loops through all the incorrect cases too, where the check function can highly reduce the number of cases to calculate.
I've managed to solve the problem. The idea is that increasing the i value by one is really easy and we can check the condition that we don't overstep the a values and don't violate the check function easily. Below is a code that works
int[] a = ...;
void f(int[] i){...}
bool check(int[] i){...}
int n = a.Length;
int[] i = new int[n];
while (true) //keep increasing the coordinates of i, while we can
{
for (int l = 0; l < n; l++)
{
int[] il = copyFirst(i, l);
while(!check(il)) //check for all first few coordinates if it is correct, skip if incorrect.
//There is a way to improve this even further, as we don't have to check the first few
// coords if it was correct before, so should only care about the recently changed section
{
i = increase(a, i, l);
if (i == null)
{
return;
}
else
{
il = copyFirst(i, l);
}
}
}
f(i);
i = increase(a, i, n-1);
if (i == null) return;
}
int[] copyFirst(int[] i, int l) //this is just a small helper function to copy the first few elements of i, to use in the check
{
int[] ret = new int[l];
for (int k = 0; k < l; k++)
{
ret[k] = i[k];
}
return ret;
}
int[] increase(int[] a, int[] i, int l) //this results in the increased vector and in null if we've reached the end
{
for (int k = l; k >= 0; k--)
{
i[k] = i[k] + 1;
if (i[k] >= a[k])
{
i[k] = 0;
}
else
{
return i;
}
}
return null;
}

Populating an array with elements [duplicate]

Consider I have an Array,
int[] i = {1,2,3,4,5};
Here I have assigned values for it. But in my problem I get these values only at runtime.
How can I assign them to an array.
For example:
I get the max size of array from user and the values to them now how do I assign them to the array int [].
Or can I use anyother data types like ArrayList etc which I can cast to Int[] at the end?
Well, the easiest is to use List<T>:
List<int> list = new List<int>();
list.Add(1);
list.Add(2);
list.Add(3);
list.Add(4);
list.Add(5);
int[] arr = list.ToArray();
Otherwise, you need to allocate an array of suitable size, and set via the indexer.
int[] arr = new int[5];
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
arr[3] = 4;
arr[4] = 5;
This second approach is not useful if you can't predict the size of the array, as it is expensive to reallocate the array every time you add an item; a List<T> uses a doubling strategy to minimize the reallocations required.
You mean?
int[] array = { 1, 2, 3, 4, 5 };
array = new int[] { 1, 3, 5, 7, 9 };
array = new int[] { 100, 53, 25, 787, 39 };
array = new int[] { 100, 53, 25, 787, 39, 500 };
Use List<int> and then call ToArray() on it at the end to create an array. But do you really need an array? It's generally easier to work with the other collection types. As Eric Lippert wrote, "arrays considered somewhat harmful".
You can do it explicitly though, like this:
using System;
public class Test
{
static void Main()
{
int size = ReadInt32FromConsole("Please enter array size");
int[] array = new int[size];
for (int i=0; i < size; i++)
{
array[i] = ReadInt32FromConsole("Please enter element " + i);
}
Console.WriteLine("Finished:");
foreach (int i in array)
{
Console.WriteLine(i);
}
}
static int ReadInt32FromConsole(string message)
{
Console.Write(message);
Console.Write(": ");
string line = Console.ReadLine();
// Include error checking in real code!
return int.Parse(line);
}
}
If you want an array, whose size varies during the execution, then you should use another data structure. A generic List will do. Then, you can dynamically add elements to it.
Edit: Marc posted his answer while I was writing mine. This was exactly what I meant.
You could just use the below line instead of calling a separate function:
using System;
public class Test
{
static void Main()
{
Console.WriteLine("Please enter array size");
int size = Convert.ToInt32(Console.ReadLine());
int[] array = new int[size];
for (int i=0; i < size; i++)
{
Console.WriteLine("Please enter element " + i);
array[i] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("Finished:");
foreach (int i in array)
{
Console.WriteLine(i);
}
}

C# Array Length Update

I am solving the problem from this link: https://www.hackerrank.com/challenges/cut-the-sticks (I added the link for more details if my explanation wasn't enough or wasn't quite clear.)
The point here from the exercise that I in the first I give a (int) number of sticks that I will use in the operation. the second line I enter the sticks length. So I must find the smallest stick(k), then subtract it from the rest of the sticks, then make the program print the number of total sticks that I have cut. So if the stick was cut before or its original value is 0 I have to remove it and don't count it. Then this should repeat over to redefine the value of the k because the min array value will be changed because all the sticks are cutted.
Here is my code that I used:
int n = Convert.ToInt32(Console.ReadLine());
string[] userinput = Console.ReadLine().Split(' ');
int[] arr = new int[n];
arr = Array.ConvertAll(userinput, Int32.Parse);
for (int i = 0; i < n - 1; i++)
{
arr = arr.Where(s => s != '0').ToArray();
int k = arr.Min();
arr[i] -= k;
Console.WriteLine(arr.Length);
}
Console.ReadKey();
The problem is it keeps printing the n value, which is the array's original size, it doesn't modify after the removing of the 0. So how can I fix it to just print the number of cutted sticks and when the all sticks is 0 so break?
I'm sorry for my English and if my explanation is a bit hard, but I am just new to C#.
This is the working code as you expected and tested.
Note: I just reused all the variable names and naming conventions as you did which can be refactored further.
class Program
{
static void Main(string[] args)
{
int n = Convert.ToInt32(Console.ReadLine());
string[] userinput = Console.ReadLine().Split(' ');
int[] arr = new int[n];
arr = Array.ConvertAll(userinput, Int32.Parse);
CutTheStick(arr);
Console.ReadKey();
}
private static void CutTheStick(int[] arr)
{
arr = arr.Where(s => s != 0).ToArray();
if (arr.Length > 0)
{
Console.WriteLine(arr.Length);
int k = arr.Min();
for (int i = 0; i < arr.Length; i++)
{
arr[i] -= k;
}
CutTheStick(arr);
}
}
}
If you had web/winForm based application, remove the static keyword accordingly.
There is an evident error in your code. The char '0' is not the integer 0. The automatic conversion between char and int allows this code to compile and run but you are not testing correctly your inputs
For example
int[] arr = new int[] {0,1,2,3,4};
if(arr[0] == '0')
Console.WriteLine("Is Zero");
will never print "Is Zero", while
int[] arr = new int[] {48,1,2,3,4};
if(arr[0] == '0')
Console.WriteLine("Is Zero");
will print "Is Zero" because the integer value of the char '0' is 48.
Now to give a solution to your problem I could post this code
int cutCount = 1;
int n = Convert.ToInt32(Console.ReadLine());
string[] userinput = Console.ReadLine().Split(' ');
int[] arr = Array.ConvertAll(userinput, Int32.Parse);
// Loop until we finish to empty the array
while (true)
{
// remove any zero present in the array
arr = arr.Where(s => s != 0).ToArray();
// If we don't have any more elements we have finished
if(arr.Length == 0)
break;
// find the lowest value
int k = arr.Min();
// Start a loop to subtract the lowest value to all elements
for (int i = 0; i < arr.Length; i++)
arr[i] -= k;
// Just some print to let us follow the evolution of the array elements
Console.WriteLine($"After cut {cutCount} the array length is {arr.Length}");
Console.Write("Array is composed of: ");
foreach(int x in arr)
Console.Write(x + " ");
Console.WriteLine();
}
Console.ReadLine();
But please study it carefully because otherwise my solution is no help for you in future programming tasks

Defining Dynamic Array

How can I define a dynamic array in C#?
C# doesn't provide dynamic arrays. Instead, it offers List class which works the same way.
To use lists, write at the top of your file:
using System.Collections.Generic;
And where you want to make use of a list, write (example for strings):
List<string> mylist = new List<string>();
mylist.Add("First string in list");
Take a look at Array.Resize if you need to resize an array.
// Create and initialize a new string array.
String[] myArr = {"The", "quick", "brown", "fox", "jumps",
"over", "the", "lazy", "dog"};
// Resize the array to a bigger size (five elements larger).
Array.Resize(ref myArr, myArr.Length + 5);
// Resize the array to a smaller size (four elements).
Array.Resize(ref myArr, 4);
Alternatively you could use the List class as others have mentioned. Make sure you specify an initial size if you know it ahead of time to keep the list from having to resize itself underneath. See the remarks section of the initial size link.
List<string> dinosaurs = new List<string>(4);
Console.WriteLine("\nCapacity: {0}", dinosaurs.Capacity);
dinosaurs.Add("Tyrannosaurus");
dinosaurs.Add("Amargasaurus");
dinosaurs.Add("Mamenchisaurus");
dinosaurs.Add("Deinonychus");
If you need the array from the List, you can use the ToArray() function on the list.
string[] dinos = dinosaurs.ToArray();
C# does provide dynamic arrays and dynamic array manipulation. The base of an array is dynamic and can be modified with a variable. You can find the array tutorial here (https://msdn.microsoft.com/en-us/library/aa288453%28v=vs.71%29.aspx). I have also included code that demonstrates an empty set array and a dynamic array that can be resized at run time.
class Program
{
static void Main(string[] args)
{
int x = Convert.ToInt32(Console.ReadLine());
int y = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(x);
{
int[] dynamicArray1 = { };//empty array
int[] numbers;//another way to declare a variable array as all arrays start as variable size
numbers = new int[x];//setting this array to an unknown variable (will be user input)
for (int tmpInt = 0; tmpInt < x; tmpInt++)//build up the first variable array (numbers)
{
numbers[tmpInt] = tmpInt;
}
Array.Resize(ref numbers,y);// resize to variable input
dynamicArray1 = numbers;//set the empty set array to the numbers array size
for (int z = 0; z < y; z++)//print to the new resize
{
Console.WriteLine(numbers[z].ToString());//print the numbers value
Console.WriteLine(dynamicArray1[z].ToString());//print the empty set value
}
}
Console.Write("Dynamic Arrays ");
var name = Console.ReadLine();
}
}
Actually you can have Dynamic Arrays in C# it's very simple.
keep in mind that the response to your question above is also correct you could declare a
List Generic
The way to Create a Dynamic Array would be to declare your Array for example
string[] dynamicArry1 = { };//notice I did not declare a size for the array
List<String> tmpList = new List<string>();
int i = 1;
for(int tmpInt = 0; tmpInt < 5; tmpInt++)
{
tmpList.Add("Testing, 1.0." + tmpInt + ", 200, 3.4" + tmpInt +"," + DateTime.Now.ToShortDateString());
//dynamicArry1[tmpInt] = new string[] { tmpList[tmpInt].ToCharArray() };
}
dynamicArry1 = tmpList.ToArray();
how about ArrayList ?
If I'm not wrong ArrayList is an implementation of dynamic arrays
Example of Defining Dynamic Array in C#:
Console.WriteLine("Define Array Size? ");
int number = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter numbers:\n");
int[] arr = new int[number];
for (int i = 0; i < number; i++)
{
arr[i] = Convert.ToInt32(Console.ReadLine());
}
for (int i = 0; i < arr.Length; i++ )
{
Console.WriteLine("Array Index: "+i + " AND Array Item: " + arr[i].ToString());
}
Console.ReadKey();
like so
int nSize = 17;
int[] arrn = new int[nSize];
nSize++;
arrn = new int[nSize];

Categories