Created
March 10, 2013 01:42
-
-
Save michaelbartnett/5126705 to your computer and use it in GitHub Desktop.
Wraps 1d C# arrays in a class via which you can easily index via 2D. Will add 3D later.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace Eppy | |
{ | |
using System; | |
using System.Collections; | |
using System.Collections.Generic; | |
public class MultiArray2D<T> : IEnumerable<T>, IEnumerable | |
{ | |
public int Width { get; private set; } | |
public int Height { get; private set; } | |
public int Count { get { return Width * Height; } } | |
public T[] UnderlyingArray { get; private set; } | |
public MultiArray2D(int width, int height) | |
{ | |
this.Width = width; | |
this.Height = height; | |
UnderlyingArray = new T[width * height]; | |
} | |
public static MultiArray2D<T> FromSource(T[] sourceArray, int width, int height) | |
{ | |
var result = new MultiArray2D<T>(width, height); | |
Array.Copy( | |
sourceArray, | |
result.UnderlyingArray, | |
Math.Min(sourceArray.Length, result.UnderlyingArray.Length)); | |
return result; | |
} | |
public MultiArray2D<T> Copy() | |
{ | |
var result = new MultiArray2D<T>(this.Width, this.Height); | |
Array.Copy(this.UnderlyingArray, result.UnderlyingArray, this.UnderlyingArray.Length); | |
return result; | |
} | |
public T this[int i] { | |
get { | |
return UnderlyingArray[i]; | |
} | |
set { | |
UnderlyingArray[i] = value; | |
} | |
} | |
public T this[int x, int y] { | |
get { | |
return UnderlyingArray[x + Width * y]; | |
} | |
set { | |
UnderlyingArray[x + Width * y] = value; | |
} | |
} | |
public bool HasIndex(int linearIndex) | |
{ | |
return linearIndex < Width * Height && linearIndex >= 0; | |
} | |
public bool HasIndex2D(int x, int y) | |
{ | |
return x < Width && y < Height && x >= 0 && y >= 0; | |
} | |
public IEnumerator<T> GetEnumerator() | |
{ | |
return EnumerateUnderlyingArray(); | |
} | |
IEnumerator IEnumerable.GetEnumerator() | |
{ | |
return UnderlyingArray.GetEnumerator(); | |
} | |
private IEnumerator<T> EnumerateUnderlyingArray() | |
{ | |
int bound = Count; | |
for (int i = 0; i < bound; i++) { | |
yield return UnderlyingArray[i]; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Can probably make the enumerator functions produce close-to-zero garbage...but it's not worth it to me to think about that for this code at the moment. Please share back if you do make a hyper-efficient version.