This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed 6 years ago.
The following piece of code generates a IndexOutOfRangeException was unhandled, but I dont know why. The a for-loop is set to be smaller than the i for-loop because the array of arrays is 3x2. I did try to prey the i and a but with no luck. Can you see the error?
namespace text_test
{
class txt_program
{
// () You don't use "args" in the method
public void txt()
{
int[][] names = { new int[] { 2, 3, 4}, new int[] { 5, 6, 7} };
using (StreamWriter SW = new StreamWriter(#"txt.txt"))
{
for (int i = 0; i < 4; i++)
{
for (int a = 0; a < 3; a++)
{
SW.Write(" " + names[i][a]);
}
SW.WriteLine(names);
}
}
}
}
}
The expected output would be a .txt file :
2 3 4
5 6 7
loop A repeated 4 times instead of 2 times
Instead of using magic numbers use GetLength()
for (int i = 0; i < names.GetLength(0); i++)
{
for (int a = 0; a < names.GetLength(1); a++)
{
SW.Write(" " + names[i][a]);
}
SW.WriteLine(names);
}
Related
I'm translating some code from C++ to C#. The code is simple enough and most of the syntax involved is almost the same, however the C++ version uses a vector<vector<int>> structure that doesn't exists in C#, so I replaced it with a List<List<int>> which I initialized with empty "rows" since I need it to represent a table with a fixed number of rows (See the code below).
The logic is exactly the same but somehow i'm not getting the same outputs. I suspect it has to do with the behaviour of List<List<int>> but I'm not sure. Any hints would be appreciated.
This is the original C++ code:
void LIS(int arr[], int n)
{
vector<vector<int>> L(n);
L[0].push_back(arr[0]);
for (int i = 1; i < n; i++)
{
for (int j = 0; j < i; j++)
{
if ((arr[i] > arr[j]) && (L[i].size() < L[j].size() + 1)){
L[i] = L[j];
}
}
L[i].push_back(arr[i]);
}
vector<int> max = L[0];
for (vector<int> x : L)
if (x.size() > max.size())
max = x;
for(int e : max){
cout<<e<<endl;
}
}
This is my C# version:
public static void LIS(int[] arr, int n)
{
// Here I replace the vector<vector<int>> with a List<List<int>>
// and I fill it with n empty lists.
List<List<int>> L = new List<List<int>>();
for(int x = 0; x < n; x++)
{
L.Add(new List<int>());
}
L[0].Add(arr[0]);
for (int i = 1; i < n; i++)
{
for (int j = 0; j < i; j++)
{
if ((arr[i] > arr[j]) && (L[i].Count < L[j].Count + 1))
{
L[i] = L[j];
}
}
L[i].Add(arr[i]);
}
List<int> max = L[0];
foreach (List<int> x in L)
{
if (x.Count > max.Count)
{
max = new List<int>(x);
}
}
foreach(int e in max){
Console.WriteLine(e);
}
I'm testing with this array:
int[] arr = { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 };
int n = arr.Length;
In the C++ version I get:
0 2 6 9 11 15
and in the C# version I get:
0 8 4 12 2 10 6 14 1 9 5 13 3 11 7 15
In the C++ code doesn't L[i] = L[j]; make a copy of the vector at L[j] and store it in L[i] (similar thing for the variable max)? To achieve a similar result in C#, you could do L[i] = L[j].ToList() to copy the list.
This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed 3 years ago.
These codes aren't running.When inside the nested loop I'm trying to assign integer value on totalMembers[j] array index , the compiler throws mentioned exeption.please help so that this program can run.
int totalHours = 0, memArraySize = 0;
int[] totalMembers = new int[memArraySize];
int[] memHours = new int[memArraySize];
for (int i = 0; i < 2; i++)
{
var stringNumbers = Console.ReadLine();
var numbers = stringNumbers.Split(' ');
int.TryParse(numbers[0], out totalHours);
int.TryParse(numbers[1], out memArraySize);
for (int j = 0; j < 2; j++)
{
totalMembers[j] = Convert.ToInt32(Console.ReadLine());
memHours[i] = memHours[i] + totalMembers[j];
}
}
int totalHours, memArraySize;
int[] totalMembers;
int[] memHours;
for (int i = 0; i < 2; i++)
{
var stringNumbers = Console.ReadLine();
var numbers = stringNumbers.Split(' ');
int.TryParse(numbers[0], out totalHours);
int.TryParse(numbers[1], out memArraySize);
totalMembers = new int[memArraySize];
memHours = new int[memArraySize];
for (int j = 0; j < 2; j++)
{
totalMembers[j] = Convert.ToInt32(Console.ReadLine());
memHours[i] = memHours[i] + totalMembers[j];
}
}
so that the arrays totalMembers and memHours can contain values.
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 4 years ago.
Hello why in this function data could not be read(assigned)?
Error is in the line with comments(Object reference not set to an instance of an object.)
protected static int[][] GetMapFromFile(ref int size)
{
using (StreamReader sr = new StreamReader(#"C:\Users\doman\OneDrive\Desktop\Antras semestras\Programavimas\Laboras1\Laboras1\Duomenys.txt"))
{
string skyr = " ,.;";
size = Convert.ToInt32(sr.ReadLine());
int[][] map = new int[size][];
for (int i = 0; i < size; i++)
{
string line = sr.ReadLine();
string[] values = line.Split(skyr.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
for (int j = 0; j < values.Length; j++)
{
map[i][j] = Convert.ToInt32(values[j]); // Error here
Console.Write(map[i][j]);
}
Console.WriteLine();
}
return map;
}
}
My data file
5
0 1 3 4 2
1 0 4 2 6
3 4 0 7 1
4 2 7 0 7
2 6 1 7 0
You need to create each "sub" array. Add map[i] = new int[values.Length] before the second for loop.
This question already has answers here:
C# dictionary value clearing out when I clear list previously assigned to it....why?
(6 answers)
Closed 6 years ago.
I am trying to create a list of an array of 2 items. The problem I have is the final iteration in my loop sets all the list's arrays to the same (my guess is due to a reference?). I was wondering how I can prevent this from happening.
This is what I am trying to do:
PathTiles[] links = new PathTiles[2];
int j;
for(int i = 0; i < path.Count; i++)
{
if(i+1 < path.Count)
{
links[0] = path[i];
links[1] = path[i];
for(j = i+1; j < path.Count; j++)
{
if(path[j].x == links[1].x && Mathf.Abs(path[j].y-links[1].y) == 1)
{
links[1] = path[j];
i = j;
}
else
{
break;
}
}
validPath.Add(links);
for(int k = 0; k < validPath.Count;k++)
{
Debug.Log(validPath[k].x+", "+validPath[k].y);
}
Debug.Log("=====");
}
}
So the console shows this:
0, 0
=====
1, 1 <-- why did this become 1, 1 and not stay as 0, 0
1, 1
=====
Does any one know how I can retain the first data value and not have it overwritten? I am currently under the impression it is because it stores a reference and so I changed the values, but I don't know how to stop it doing that.
Try adding the PathTiles[] links = new PathTiles[2]; within the 1st for loop statement. As you said this is a problem of references. As you were addiing the same modified links to the list. the 1st data value is overwritten.
int j;
for (int i = 0; i < path.Count; i++)
{
PathTiles[] links = new PathTiles[2]; //<-- here
if (i + 1 < path.Count)
{
links[0] = path[i];
links[1] = path[i];
...
This question already has answers here:
Generate N random and unique numbers within a range
(7 answers)
Best way to randomize an array with .NET
(19 answers)
Closed 6 years ago.
Okay I know there are few posts like this but I need to use only loops (for,do,while) and if, else to fill array with random but unique numbers so how shall i edit this code
int[] x = new int[10];
Random r = new Random();
int i;
for (i = 0; i < x.Length; i++) {
x[i] = r.Next(10);
Console.WriteLine("x[{0}] = {1}", i, x[i]);
}
You could check if the newly generated number already exists in the array, if not then add it to the array, if yes then generate a new one.
For examle:
class Program
{
static void Main(string[] args)
{
int[] x = new int[10];
Random r = new Random();
int i;
for (i = 0; i < x.Length; i++)
{
var next = 0;
while (true)
{
next = r.Next(10);
if (!Contains(x, next)) break;
}
x[i] = next;
Console.WriteLine("x[{0}] = {1}", i, x[i]);
}
Console.ReadLine();
}
static bool Contains(int[] array, int value)
{
for (int i = 0; i < array.Length; i++)
{
if (array[i] == value) return true;
}
return false;
}
}
Without checking that generated number is already presented in array you can't to solve this task.
So you must generate new number and before inserting it into array check for uniq.