SparseGrid Class:
import java.util.*;
import info.gridworld.grid.*;
import info.gridworld.actor.*;
public class SparseGrid<E> extends AbstractGrid<E>
{
SparseGridNode[] arr;
int row, col;
public SparseGrid(int r, int c)
{
row = r;
col = c;
arr = new SparseGridNode[row];
}
public boolean isValid(Location loc)
{
if ((loc.getRow() <= row && loc.getRow() >= 0) && (loc.getCol() <= col && loc.getCol() >= 0))
return true;
else
return false;
}
public int getNumRows()
{
return row;
}
public int getNumCols()
{
return col;
}
public E put(Location loc, E obj)
{
if (!isValid(loc))
throw new IllegalArgumentException("Location " + loc + " is evil");
if (obj == null)
throw new NullPointerException("obj is evil");
if (arr[loc.getRow()] != null)
{
SparseGridNode temp = arr[loc.getRow()];
while (temp.getColIndex() != loc.getCol())
{
temp = temp.getNext();
}
temp.setOccupant(obj);
}
return obj;
}
public ArrayList<Location> getOccupiedLocations()
{
ArrayList<Location> temp = new ArrayList<Location>();
for (int i = 0; i < row; i++)
{
SparseGridNode node = arr[i];
while(node != null)
{
temp.add(new Location (i, node.getColIndex()));
node = node.getNext();
}
}
return temp;
}
public E remove(Location loc)
{
if (!isValid(loc))
throw new IllegalArgumentException("Location " + loc + " is evil");
SparseGridNode node = arr[loc.getRow()];
SparseGridNode prev;
if (node.getColIndex() == loc.getCol())
{
E temp = (E) node.getOccupant();
arr[loc.getRow()] = node.getNext();
return temp;
}
else
{
prev = node;
node = node.getNext();
while(node != null)
{
if (node.getColIndex() == loc.getCol())
{
prev.setNext(node.getNext());
E temp = get(loc);
return temp;
}
prev = node;
node = node.getNext();
}
}
return null;
}
public E get(Location loc)
{
if (!isValid(loc))
throw new IllegalArgumentException("Location " + loc + " is evil");
SparseGridNode node = arr[loc.getRow()];
while (node != null)
{
if (loc.getCol() == node.getColIndex())
{
E temp = (E)node.getOccupant();
return temp;
}
node = node.getNext();
}
return null;
}
//
}
SparseGridNode Class:
public class SparseGridNode
{
int colIndex;
SparseGridNode next;
Object occupant;
public SparseGridNode(int c, Object o)
{
colIndex = c;
occupant = o;
}
public int getColIndex()
{
return colIndex;
}
public Object getOccupant()
{
return occupant;
}
public void setOccupant(Object e)
{
occupant = e;
}
public void setNext(SparseGridNode node)
{
next = node;
}
public SparseGridNode getNext()
{
return next;
}
}
Tester:
import java.util.*;
import info.gridworld.grid.*;
import info.gridworld.actor.*;
public class SparseGridTester
{
public static void main (String[] args)
{
ActorWorld world = new ActorWorld();
world.addGridClass("SparseGrid");
world.add(new Location(0, 5), new Critter());
world.show();
}
}
This post has been edited by Rekmesh: 12 March 2009 - 08:27 PM

New Topic/Question
Reply



MultiQuote



|