Reputation: 23
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
Upvotes: 2
Views: 344
Reputation: 345
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.
Upvotes: 1