So, I'm going to use a generic list to replace the Stick array (called “grid[]” in the code). I haven't done enough with generic lists to feel like I understand them, but based on how easy it was for me to make the changes I describe here, I guess I must understand them.
Here are the changes I made.
Old:
// The board of sticks, numbered 0 to 59, but referred to in the code as 1 to 60.
private Stick[] grid = new Stick[60]; // FLAG: the grid is actually 1-based.
New:
List
At this point, it occurred to me that each stick would have to know its own position, since the index of the array would no longer exist. I had forgotten that Stick already has a Location property.
Old:
/* Returns the number of sticks (value of true) on the board. */
public int Value
{
get
{
int temp = 0;
for (int i = 0; i < 60; i++)
{
if (grid[i].Value) temp++;
}
return temp;
}
}
New:
/* Returns the number of sticks (value of true) on the board. */
public int Value
{
get
{
int temp = 0;
foreach (Stick i in stickList)
{
if (i.Value) temp++;
}
return temp;
}
}
The public methods (addStick, removeStick, moveStick) don't use the grid array. I wrote them this way intentionally.
Old:
private Stick getStick(int location)
{
if (isValid(location)) {
foreach (Stick x in grid) {
if (x.Location == location) return x;
}
}
return null; // Not sure this is great code. It prevents a compiler warning.
}
New: Just change “grid” to stickList.
Old:
private bool isValid(int candidate)
{
foreach (Stick x in grid)
{
if (x.Location == candidate) return true;
}
return false;
}
New: Just change “grid” to stickList.
Old:
public Stick test_getStick(int loc)
{
return grid[loc];
}
This code is used only in testing, so I'm going to have to run the tests to see whether anything breaks, but here's my first run at replacing it:
public Stick test_getStick(int loc)
{
if (isValid(loc)) {
return getStick(loc));
}
return new Stick(0); // Return to this later
}
I didn't want to return null, but using a “0” stick as some kind of exception condition is new. Maybe it will be useful, somehow, but, if not, this is still only testing code.
OK, that is it.
If I click the “Run” button, it should compile.
Well, it didn't. Here's the error:
The type or namespace name 'List' could not be found (are you missing a using directive or an assembly reference?)
I thought that List was included in the System namespace. When I added a using directive for System.Collections.Generic, it doesn't produce the error.
OK, after I fixed the getHashCode method and fixed one typo, it compiles. Let's run the tests.
And I have a ton of FAILs.
I need to work on the public methods (addStick, removeStick, moveStick) to use the new stickList correctly.
But that will be tomorrow's post.
No comments:
Post a Comment