I have a data structure as the image below illustrates. I need to quickly figure out the index of the cells to the right or left of the highlighted cell group.
You can see in the code below I am naively looping through ALL cells at every index to determine if there is a cell at the requested index. This works great when I have a few (hundred) cells, but breaks down quickly when I have thousands of cells.
In this particular case the highlighted group is mobile, and can only move to the index before or after the previous/next occupied cell. So groupMinX/maxX is the minimum and maximum x value it can move based on the position of other cells in the row.
private var movingGroup:CellGroup; //selected group
public function getCellAtIndex(index:int):ICell
{
for each(var cell:ICell in cells)
{
if(cell.index==index)
return cell;
}
return null;
}
public function groupMinX(xPos:Number):Number
{
var index:int = xPos/cellSize;
var cellsOnLeft:Array = getAllCellsOnLeft(index-1);
if(cellsOnLeft.length > 0)
return cellsOnLeft[cellsOnLeft.length-1].x + cellSize;
return 0;
}
public function groupMaxX(xPos:Number):Number
{
var index:int = xPos/cellSize;
var cellsOnRight:Array = getAllCellsOnRight(index);
if(cellsOnRight.length > 0)
return cellsOnRight[0].x;
return (maxIndex)*cellSize;
}
private function getAllCellsOnLeft(ofIndex:int):Array
{
var index:int = 1;
var cells:Array = [];
while( ofIndex >= 0 )
{
var cell:ICell = getCellAtIndex(ofIndex);
if(cell && !movingGroup.containsCell(cell))
cells.unshift( cell );
ofIndex--;
}
return cells;
}
private function getAllCellsOnRight(ofIndex:int):Array
{
var index:int = 1;
var cells:Array = [];
while( index <= maxIndex )
{
var cell:ICell = getCellAtIndex( ofIndex + index );
if(cell && !movingGroup.containsCell(cell))
cells.push( cell );
index++;
}
return cells;
}
What I am looking for is an efficient method for scanning/tracking the cells. The array I am looping through doesn't actually contain the blank cells, but it has the cells with the index property.