Created
August 19, 2013 02:01
-
-
Save SteveSwink/6265217 to your computer and use it in GitHub Desktop.
Mike Stevenson's shufflebag helper class
This file contains hidden or 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
using UnityEngine; | |
using System.Collections; | |
using System.Collections.Generic; | |
public class ShuffleBag<T> : ICollection<T>, IList<T> | |
{ | |
private List<T> data = new List<T> (); | |
private int cursor = -1; | |
private T last; | |
public ShuffleBag () | |
{ | |
} | |
public ShuffleBag (IEnumerable<T> contents) | |
{ | |
foreach (var item in contents) { | |
Add (item); | |
} | |
cursor = -1; | |
} | |
public T Next () | |
{ | |
if (cursor < 1) { | |
cursor = data.Count - 1; | |
if (data.Count < 1) | |
return default(T); | |
last = data [0]; | |
return data [0]; | |
} | |
T temp; | |
do { | |
int grab = Mathf.FloorToInt (Random.value * (cursor + 1)); | |
temp = data [grab]; | |
data [grab] = data [cursor]; | |
data [cursor] = temp; | |
cursor--; | |
} while (last.Equals (temp) && data.Count > 1); | |
last = temp; | |
return temp; | |
} | |
#region IList[T] implementation | |
public int IndexOf (T item) | |
{ | |
return data.IndexOf (item); | |
} | |
public void Insert (int index, T item) | |
{ | |
data.Insert (index, item); | |
} | |
public void RemoveAt (int index) | |
{ | |
data.RemoveAt (index); | |
} | |
public T this[int index] { | |
get { | |
return data [index]; | |
} | |
set { | |
data [index] = value; | |
} | |
} | |
#endregion | |
#region IEnumerable[T] implementation | |
IEnumerator<T> IEnumerable<T>.GetEnumerator () | |
{ | |
return data.GetEnumerator (); | |
} | |
#endregion | |
#region ICollection[T] implementation | |
public void Add (T item) | |
{ | |
data.Add (item); | |
cursor = data.Count - 1; | |
} | |
public int Count { | |
get { | |
return data.Count; | |
} | |
} | |
public void Clear () | |
{ | |
data.Clear (); | |
} | |
public bool Contains (T item) | |
{ | |
return data.Contains (item); | |
} | |
public void CopyTo (T[] array, int arrayIndex) | |
{ | |
foreach (T item in data) { | |
array.SetValue (item, arrayIndex); | |
arrayIndex = arrayIndex + 1; | |
} | |
} | |
public bool Remove (T item) | |
{ | |
return data.Remove (item); | |
} | |
public bool IsReadOnly { | |
get { | |
return false; | |
} | |
} | |
#endregion | |
#region IEnumerable implementation | |
IEnumerator IEnumerable.GetEnumerator () | |
{ | |
return data.GetEnumerator (); | |
} | |
#endregion | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment