HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Memory usage in Reversi board state

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
reversiusagestatememoryboard

Problem

I'm coding a Reversi game, with an artificial intelligence using the MinMax as the search algorithm. My concern is that (most) search algorithms needs to store a lot of instances of "states", in my case, board states. What I want is to represent a BoardState with 64 SlotState (Empty, White Disk or Black Disk), with the minimum RAM usage as possible. My current implementation uses a System.Collections.BitArray for storage.

```
public enum SlotState : byte {
Empty = 0,
White = 1,
Black = 2
}
public sealed class BoardState {

private const int BitsPerSlot = 2;
private const int SlotsPerRow = 8;
private const int SlotsInBoard = 64;
private const int BitsPerRow = SlotsPerRow * BitsPerSlot;
private const int BitsInBoard = SlotsInBoard * BitsPerSlot;

// stores state in big-endian row-major
private BitArray State;

public BoardState() {
State = new BitArray(BitsInBoard);
this[3, 3] = SlotState.White;
this[4, 4] = SlotState.White;
this[3, 4] = SlotState.Black;
this[4, 3] = SlotState.Black;
}

public BoardState(BoardState original) {
State = new BitArray(original.State);
}

public SlotState this[int x, int y] {
get {
if (!(IsValidCoordinate(x) && IsValidCoordinate(y))) {
throw new IndexOutOfRangeException();
}
int position = GetPosition(x, y);
bool majorBit = State[position];
bool minorBit = State[position + 1];
if (majorBit && !minorBit) {
return SlotState.Black;
} else if (!majorBit && minorBit) {
return SlotState.White;
} else {
return SlotState.Empty;
}
}
set {
if (!(IsValidCoordinate(x) && IsValidCoordinate(y))) {
throw new IndexOutOfRangeException();
}
int position = GetPosition(x, y);
State[position]

Solution

I agree with other commenters that you should have your memory usage measured first, so you know for sure you need to solve this. That said, I don't think MinMax requires storing all board states of the tree. Why do you need to have more boards in the memory than the level of the tree search? That should be 10-15 boards in the memory tops, no? I would even think about storing just one board in the memory and passing just the "moves" down the recursion. You will perform the move when you go down the recursion and undo the move when going up.

Context

StackExchange Code Review Q#62554, answer score: 4

Revisions (0)

No revisions yet.