I'm writing a simple dynamic programming in C#.
public class CountDerangementRec
{
public long Derangements(int setsize)
{
var subSolutions = new List<long>(capacity:setsize + 1);
for (int n = 1; n <= setsize; n++)
{
if (n == 1)
subSolutions[n] = 0;
else if (n == 2)
subSolutions[n] = 1;
else
subSolutions[n] = (n - 1) * (subSolutions[n - 1] + subSolutions[n - 2]);
return subSolutions[n];
}
return subSolutions[setsize];
}
}
My main class looks like this: public class Program {
public static void Main()
{
var count = new CountDerangementRec();
Console.WriteLine(count.Derangements(3));
}
}
Every time I run the program , I get the following error:
Unhandled exception. System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'index')
at System.Collections.Generic.List`1.set_Item(Int32 index, T value)
at Dynamic_programing.CountDerangementRec.Derangements(Int32 setsize) in C:\Users\pasob\source\repos\Dynamic programing\CountDerangementRec.cs:line 18
at Dynamic_programing.Program.Main() in C:\Users\pasob\source\repos\Dynamic programing\Program.cs:line 10
I don't know what I'm doing wrong