I\'m trying to reorganize an array based on the first occurrence of a value (thus simulating similar functionality to a circular array.)
For example, in the followin
As an alternative to creating a new array, you can wrap it with a class:
class CircularList<T> : IList<T>
{
static IEnumerable<T> ToEnumerator(CircularList<T> list)
{
for (int i = 0; i < list.Count; i++)
{
yield return list[i];
}
}
IList<T> arr;
public int Shift { get; private set; }
public CircularList(IList<T> arr, int shift)
{
this.arr = arr;
this.Shift = shift;
}
int shiftIndex(int baseIndex)
{
return (baseIndex + Shift) % arr.Count;
}
#region IList<T> Members
public int IndexOf(T item) { throw new NotImplementedException(); }
public void Insert(int index, T item) { throw new NotImplementedException(); }
public void RemoveAt(int index) { throw new NotImplementedException(); }
public T this[int index]
{
get { return arr[shiftIndex(index)]; }
set { arr[shiftIndex(index)] = value; }
}
#endregion
#region ICollection<T> Members
public void Add(T item) { throw new NotImplementedException(); }
public void Clear() { throw new NotImplementedException(); }
public bool Contains(T item) { throw new NotImplementedException(); }
public void CopyTo(T[] array, int arrayIndex) { throw new NotImplementedException(); }
public int Count { get { return arr.Count; } }
public bool IsReadOnly { get { throw new NotImplementedException(); } }
public bool Remove(T item) { throw new NotImplementedException(); }
#endregion
#region IEnumerable<T> Members
public IEnumerator<T> GetEnumerator()
{
return ToEnumerator(this).GetEnumerator();
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return ToEnumerator(this).GetEnumerator();
}
#endregion
}
This program:
class Program
{
static void Main(string[] args)
{
int[] myArray = { 2, 3, 6, 1, 7, 6 };
CircularList<int> circularList =
new CircularList<int>(myArray, Array.IndexOf<int>(myArray, 6));
foreach (int i in circularList)
{
Console.WriteLine(i);
}
}
}
Prints the following:
6 1 7 6 2 3
C# answer: input : { 1, 2, 3, 5, 6, 7, 8 }; Output : { 8, 7 1, 2, 3, 5, 6};
{
static void Main(string[] args)
{
int[] array = { 1, 2, 3, 5, 6, 7, 8 };
int index = 2;
int[] tempArray = new int[array.Length];
array.CopyTo(tempArray, 0);
for (int i = 0; i < array.Length - index; i++)
{
array[index + i] = tempArray[i];
}
for (int i = 0; i < index; i++)
{
array[i] = tempArray[array.Length -1 - i];
}
}
}