Easiest way to Rotate a List in c#

后端 未结 16 3132
鱼传尺愫
鱼传尺愫 2020-12-01 07:06

Lists say I have a list List {1,2,3,4,5}

Rotate means:

=> {2,3,4,5,1} => {3,4,5,1,2} => {4,5,1,2,3}
16条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-01 07:34

    How about using modular arithmetic :

    public void UsingModularArithmetic()
    { 
      string[] tokens_n = Console.ReadLine().Split(' ');
      int n = Convert.ToInt32(tokens_n[0]);
      int k = Convert.ToInt32(tokens_n[1]);
      int[] a = new int[n];
    
      for(int i = 0; i < n; i++)
      {
        int newLocation = (i + (n - k)) % n;
        a[newLocation] = Convert.ToInt32(Console.ReadLine());
      }
    
      foreach (int i in a)
        Console.Write("{0} ", i);
    }
    

    So basically adding the values to the array when I am reading from console.

提交回复
热议问题