我正在用 C# 编写一个简单的爬山算法,并尝试以下方法:
获取初始解决方案
将解决方案复制到新对象
应用算法复制
将初始解决方案的 obj 值与副本的 obj 值进行比较,
如果更好 - 复制回初始解决方案。
我知道这个话题在前一篇文章中已经提到过,并尝试在那里实现这个建议——使用 IClonable 类。这是我尝试过的:
我的解决方案类:
class Solution : ICloneable
{
public Dictionary<Room, List<Patient>> solution { get; set; }
public Solution()
{
solution = new Dictionary<Room, List<Patient>>();
}
public object Clone()
{
return this.MemberwiseClone();
}
}
算法:
public static void swap (Solution solution, Output input, Random rand)
{
Solution intSoln = new Solution();
intSoln = (Solution)solution.Clone();
//Moving things around in intSoln here
Console.WriteLine("new solution = " + objValue(intSoln, input));
Console.WriteLine("old solution = " + objValue(solution, input));
if (objValue(intSoln, input) < objValue(solution, input))
{
solution = (Solution)intSoln.Clone();
}
}
查看新旧解决方案的打印输出,它们总是相同的,这意味着代码显然仍然通过引用进行复制。我很困惑,不知道该怎么做。任何帮助将非常感激。