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];
Related
When I run this code the array has a new size after, is there anything wrong or bad about it ?
static int[] ExpandArray(int[] input, int add_size)
{
for (int i = 0; i < add_size; i++)
{
int[] temp = input;
input = new int[input.Length + 1];
for (var j = 0; j < temp.Length; j++)
{
input[j] = temp[j];
}
}
return input;
}
static void Main(string[] args)
{
int[] ovride = new int[3] { 1, 2, 3 };
ovride = ExpandArray(ovride, 10);
ovride = ExpandArray(ovride, 10);
Console.WriteLine(ovride.Length);
}
is there anything wrong or bad about it ?
This isn't code review, but:
Yes. You should not resize arrays. This involves a new allocation and a copy of all elements. As does Array.Resize(), by the way.
Hey, there is a method that already does this: Array.Resize(). Don't reinvent the wheel.
You definitely should not do the resize in a loop.
So to clean up the code a little:
static int[] ExpandArray(int[] input, int sizeToAdd)
{
// Create a new array with the desired size
var ouput = new int[input.Length + sizeToAdd];
// Copy all elements from input to output
for (int i = 0; i < input.Length; i++)
{
output[i] = input[i];
}
// Return the new array, having the remaining
// items set to their default (0 for int)
return output;
}
You'd actually want input to be updatable by ref, and then end with input = output.
Ultimately, just use a List<int>, as that allows for more efficient resizing, and does so automatically when necessary.
You can use Array.Resize which:
Changes the number of elements of a one-dimensional array to the specified new size.
int[] ovride = new int[3] { 1, 2, 3 };
Array.Resize(ref ovride, ovride.Length + 10);
Array.Resize(ref ovride, ovride.Length + 10);
Console.WriteLine(ovride.Length); // prints 23
But if you expect collection size changes List can be a more suitable option for your goal.
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);
}
}
This question already has answers here:
How do I check if my array has repeated values inside it?
(8 answers)
Closed 5 years ago.
I would like to check the array I passed in the shuffle method for any duplicates.
I would like to also generate a random number that is the size of a.length.
The thing is that I can't figure out how to check if the array has duplicates and if it does it would generate another number until it is unique from the rest.
public int[] Shuffle(int[] a)
{
//check if the array has duplicates
for (int i = 0; i < a.Length; i++)
{
int curValue = random.Next(a.Length);
if(a.Contains(curValue))
{
curValue = random.Next(a.Length);
}
else
{
a[i] = curValue;
}
}
for (int i = 0; i < a.Length; i++)
{
int r = random.Next(a.Length);
int t = a[r];
a[r] = a[i];
a[i] = t;
}
return a;
}
Can anyone help me?
Here is a function that does what you ask as I presume. Include using System.Linq to run it. I went on the basis of your text, because the code did not make your question clear to me. If you meant something differently please clarify.
static int[] Shuffle(int[] a)
{
Random rnd = new Random();
//Remove duplicates from array
int[] distinct = a.Distinct().ToArray();
//Add the same amount of unique numbers that have been removed as duplicates
int len = a.Length - distinct.Length;
int[] newNumbers = new int[len];
int i = 0;
while(i < len)
{
newNumbers[i] = rnd.Next(a.Length); //NOTE: here i put in the length of array a, but with an int array this will always resolve in a shuffled array containing all digits from 0 to the length-1 of the array.
if (!distinct.Contains(newNumbers[i]) && !newNumbers.Take(i).Contains(newNumbers[i]))
{
++i;
}
}
//Randomize the array
int[] b = a.OrderBy(x => rnd.Next()).ToArray();
//Concatenate the two arrays and return it (shuffled numbers and new unique numbers)
return distinct.Concat(newNumbers).ToArray();
}
As I said in the note, if you remain with an integer array and only allow adding of new random replacement number lower than the length of the array, you and up with a shuffled array of all numbers from 0 to the array length.
Since a new array for newNumbers is generated, you also need to check if a newly generated number is not in that array.
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;
}
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];