Last active
March 31, 2018 12:35
-
-
Save atori708/52da451aff5aeecec3a4385159fe8236 to your computer and use it in GitHub Desktop.
環状配列(要素数は2のべき乗)。通常の配列の使い方が出来るが、先頭と末尾が環状になってるので要素数がオーバーフローしない。作ったけど用途がないので供養(チーン)
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
/// <summary> | |
/// 環状配列 | |
/// 2のべき乗でしか作れない | |
/// スレッドセーフではない | |
/// </summary> | |
public class RingArray<T> : System.Collections.ICollection | |
{ | |
T[] buffer; | |
int top, bottom; | |
int mask; | |
public T this[int i] { | |
get { return buffer[(i+top) & mask]; } | |
set { buffer[(i+top) & mask] = value; } | |
} | |
public int Count{get{ return buffer.Length;}} | |
bool ICollection.IsSynchronized { | |
get{ return false; } | |
} | |
object ICollection.SyncRoot { | |
get{ return this; } | |
} | |
public RingArray(int capacityPow2) | |
{ | |
int capacity = (int)Mathf.Pow(2, capacityPow2); | |
buffer = new T[capacity]; | |
top = bottom = 0; | |
mask = capacity - 1; | |
} | |
void ICollection.CopyTo(System.Array array, int index) { | |
foreach(T i in array) { | |
buffer.SetValue (i, index); | |
index++; | |
} | |
} | |
IEnumerator IEnumerable.GetEnumerator() { | |
return new Enumerator(buffer); | |
} | |
public class Enumerator : IEnumerator | |
{ | |
private T[] array; | |
private int cursor; | |
object IEnumerator.Current { | |
get { | |
if (cursor < 0 || cursor == array.Length) { | |
throw new System.InvalidOperationException(); | |
} | |
return array[cursor]; | |
} | |
} | |
public Enumerator(T[] array) { | |
this.array = array; | |
cursor = -1; | |
} | |
void IEnumerator.Reset() { | |
cursor = -1; | |
} | |
bool IEnumerator.MoveNext() { | |
if (cursor < array.Length) { | |
cursor++; | |
} | |
return (!(cursor == array.Length)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment