Skip to content

Instantly share code, notes, and snippets.

@GeirGrusom
Created November 27, 2014 08:03
Show Gist options
  • Save GeirGrusom/48eed077d8bede601f78 to your computer and use it in GitHub Desktop.
Save GeirGrusom/48eed077d8bede601f78 to your computer and use it in GitHub Desktop.
Sparse Matrix
public struct Position : IEquatable<Position>
{
private readonly int _x;
private readonly int _y;
public int X { get { return _x; } }
public int Y { get { return _y; } }
public Position(int x, int y)
{
_x = x;
_y = y;
}
public override int GetHashCode()
{
unchecked
{
int hash = 17;
hash = hash * 23 + X.GetHashCode();
hash = hash * 23 + Y.GetHashCode();
return hash;
}
}
public override bool Equals(object obj)
{
if (obj is Position)
return Equals((Position)obj);
return false;
}
public bool Equals(Position other)
{
return X == other.X && Y == other.Y;
}
public static bool operator ==(Position lhs, Position rhs)
{
return lhs.X == rhs.X && lhs.Y == rhs.Y;
}
public static bool operator !=(Position lhs, Position rhs)
{
return lhs.X != rhs.X || lhs.Y != rhs.Y;
}
}
public class SparseMatrix<TCell>
: IEnumerable<KeyValuePair<Position, TCell>>
{
private readonly IDictionary<Position, TCell> _cells;
public SparseMatrix()
{
_cells = new Dictionary<Position, TCell>();
}
public int Count { get { return _cells.Count; } }
public TCell this[int x, int y]
{
get
{
TCell ret;
if (_cells.TryGetValue(new Position(x, y), out ret))
return ret;
return default(TCell);
}
set
{
if (_cells.ContainsKey(new Position(x, y)))
{
if (Equals(value, default(TCell)))
_cells.Remove(new Position(x, y));
else
_cells[new Position(x, y)] = value;
}
else
{
if (Equals(value, default(TCell)))
return;
_cells.Add(new Position(x, y), value);
}
}
}
public IEnumerator<KeyValuePair<Position, TCell>> GetEnumerator()
{
return _cells.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment