dtsn

Hi,

I'm trying to build a GA to solve Sudoku but i have seemed to come across a strange problem i've never seen before. I am calling a variable through a procedure and assigning it to another variable however when one variable changes so does the other and it's all in a for loop.

Code Snippet
public class suduko
{
public int Fitness = 0;
public int[,] grid = new int[9, 9];
}

public void Create(int [,] game)
{
Random Random = new Random();
int dummy = 0;

// populate population with random numbers
suduko su = new suduko();

for (int i = 0; i < PopSize; i++)
{
su.grid = game;

for (int j = 0; j < 9; j++)
{
for (int k = 0; k < 9; k++)
{
dummy = Random.Next(1, 10);
if (su.grid[j, k] == 0) { su.grid[j, k] = dummy; }
}
}
su.Fitness = fitness(su.grid);
pop.Add(su);
}
evolve(pop);
}

So game changes every for loop to whatever su.grid is even though game is never assigned to! Anyone have any ideas

Thanks

Daniel


Re: Visual C# General Variable problems

decyclone

Try this :

Change 'su.grid = game;' to 'su.grid = game.Clone();'




Re: Visual C# General Variable problems

dtsn

Thanks, works a treat now! Do you know why it happens

Since it requires unboxing heres the code:

object a = game.Clone();
su.grid = (int[,])a;

Thanks

Daniel




Re: Visual C# General Variable problems

decyclone

The Clone() method creates a shallow copy of the object. So, making change in one object doesn't change the others.

For example,

class Person : ICloneable
{
public Person(string InName)
{
Name = InName;
}

public string Name;

#region ICloneable Members

public object Clone()
{
// Read the documentation to know about this function
// Basically it creates a shallow copy of an object
return MemberwiseClone();
}

#endregion

static void Main(string[] args)
{
Person Joe = new Person("Joe"); // Creates a Person object on Heap
Person Joe2 = Joe; // This one just references Joe2 to Joe. So, both of them now Point to same obect in Heap

Joe2.Name = "Joe2"; // This will also change Joe.Name to "Joe2"

Person Joe3 = Joe.Clone(); // This creates another Person object on Heap

Joe3.Name = "Joe3"; // This will not change Joe.Name and Joe2.Name to "Joe3"
}
}