views:

58

answers:

1

I have a two dimensional grid of cells. In this simulation, cells may request to switch position with another cell. The request also has a priority.

The problem is that Im having a hard time coming up with a good way to structure this. If A wants to switch with B, and B also wants to switch with A, they currently can be switched and switched back in a single logic tick (which should be impossible).

The solution probably involves making sure (A to B)==(B to A) and insertion sorting them into a list by their priority.

Does such data structure have a name? Anyone recognise the problem and can provide some good links for reading?

+1  A: 

I can't say that I've come across an example like this before, so I don't know what it would be called, but perhaps something like this would work...

Cell - a class or struct

  • CellId
  • XCoordinate
  • YCoordinate

SwitchRequest - a class or struct

  • RequestingCell
  • TargetCell
  • Priority
  • CanSwitch

SwitchRequests - an array of SwitchRequests

AlreadySwitchedCells - an array of Cells

Algorithm

For each tick:

clear AlreadySwitchedCells
build list of SwitchRequests
sort SwitchRequests by Priority (highest to lowest)
loop through each SwitchRequest
{
  if (RequestingCell is not in AlreadySwitchedCells and TargetCell is not in AlreadySwitchedCells)
  {
    add RequestingCell and TargetCell to AlreadySwitchedCells
    SwapCellIds(RequestingCell, TargetCell)
  }
}

Note: There are some options here, like whether you should make the coordinates properties of a Cell or just store the CellIds in an two-dimensional array, but hopefully this gives you a starting point.

DanM
Forgot to accept this, and I doubt the question will see much more activity. Thanks! :)
mizipzor