Minh
Minh

Reputation: 3

Determinant of Matrix using Recursion in C++ and C#

Using C++ to calculate Determinant of Matrix:

int pw(int a){
    if(a%2==0)return 1;else return -1;
}
float det(vector<vector<float> > &arr, int rows){   
    vector<vector<float> > arr2;
    float dett=0,hk;
    if(rows==2){        
       dett= (arr[0][0]*arr[1][1]-arr[0][1]*arr[1][0]);
    } else {        
        for(int i=0;i<rows;i++){            
           hk=arr[0][i];arr2=arr;
           arr2.erase(arr2.begin());
           for(int k=0;k<rows-1;k++)arr2[k].erase(arr2[k].begin()+i);
           dett=dett+pw(i)*hk*det(arr2,rows-1);
         }  
    }
    return dett;
}

The same function in C# has an issue: when the loop reaches i=1, arr isn't the same between the c++ and c#.

    int pw(int a)
    {
        if (a % 2 == 0) return 1; else return -1;
    }
    double det(List<List<double>> arr)
    {

        int rows = arr.Count;
        List<List<double>> arr2;
        double dett = 0, hk;
        if (rows == 2)
        {
            dett = (arr.First().First() * arr.Last().Last() - arr.First().Last() * arr.Last().First());
        }
        else
        {
            for (int i = 0; i < arr.Count; i++)
            {
                hk = arr[0][i]; arr2 = arr;
                arr2.RemoveAt(0);
                foreach (List<double> k in arr2) k.RemoveAt(i);
                dett = dett + pw(i) * hk * det(arr2);
            }
        }
        return dett;
    }

Upvotes: 0

Views: 466

Answers (2)

CanereCurrere
CanereCurrere

Reputation: 58

And I check when the loop reach i=1, "arr" isn't the same when Recursion start.

Yes, that is because you are using arr2 = arr, which doesn't copy the List, arr2 is still the Reference to arr . What you can do is arr2 = new List<List<double>>(arr); to make a new List with the Elements of arr.

EDIT To Copy the List inside of the List, you can do this. arr2 = new List<List<double>>(arr.Select(x => new List<double>(x)));

Upvotes: 3

1201ProgramAlarm
1201ProgramAlarm

Reputation: 32732

The arr2 = arr; statement does different things in the two languages.

In C++, it makes a copy of the data, so that changes to arr2 will not change arr.

In C#, this assignment will update what arr2 refers to, without making a copy. So changes to arr2 will also change arr. You'll need to explicitly make a copy of arr.

Upvotes: 1

Related Questions