C# quickest way to shift array

前端 未结 20 1314
礼貌的吻别
礼貌的吻别 2020-12-01 01:35

How can I quickly shift all the items in an array one to the left, padding the end with null?

For example, [0,1,2,3,4,5,6] would become [1,2,3,4,5,6,null]

Ed

20条回答
  •  时光说笑
    2020-12-01 02:34

    Here is my solution, similar to Task's in that it is a simple Array wrapper and that it takes O(1) time to shift the array to the left.

    public class ShiftyArray
    {
        private readonly T[] array;
        private int front;
    
        public ShiftyArray(T[] array)
        {
            this.array = array;
            front = 0;
        }
    
        public void ShiftLeft()
        {
            array[front++] = default(T);
            if(front > array.Length - 1)
            {
                front = 0;
            }
        }
    
        public void ShiftLeft(int count)
        {
            for(int i = 0; i < count; i++)
            {
                ShiftLeft();
            }
        }
    
        public T this[int index]
        {
            get
            {
                if(index > array.Length - 1)
                {
                    throw new IndexOutOfRangeException();
                }
    
                return array[(front + index) % array.Length];
            }
        }
    
        public int Length { get { return array.Length; } }
    }
    

    Running it through Jason Punyon's test code...

    int?[] intData = Enumerable.Range(1, 100).Cast().ToArray();
    ShiftyArray array = new ShiftyArray(intData);
    
    Stopwatch watch = new Stopwatch();
    watch.Start();
    
    for(int i = 0; i < 1000000; i++)
    {
        array.ShiftLeft();
    }
    
    watch.Stop();
    
    Console.WriteLine(watch.ElapsedMilliseconds);
    

    Takes ~29ms, regardless of the array size.

提交回复
热议问题