对于循环重构?

For loop refactoring?

给定数组 nums 由 [x1,x2,...,xn,y1,y2,...,yn] 形式的 2n 个元素组成。

Return [x1,y1,x2,y2,...,xn,yn] 形式的数组。

示例 1:

输入:nums = [2,5,1,3,4,7], n = 3

输出:[2,3,5,4,1,7]

public int[] Shuffle(int[] nums, int n) {
    int[] result = new int[nums.Length];
    
    int z = 0;

    for (int x = 0; x < (2 * n); x += 2) {
        result[x] = nums[z]; 
        z++;
    }
    
    z = 0;

    for (int y = n; y < (2 * n); y++) {
        result[z + 1] = nums[y];
        z += 2;
    }

    return result;
}

我们开始了:

void Main()
{
    var nums = new[] { 2, 5, 1, 3, 4, 7 };
    
    var result = Shuffle(nums, 3);
    Console.WriteLine(String.Join(",", result));
}

public int[] Shuffle(int[] nums, int n) =>
    nums
        .Take(n)
        .Zip(nums.Skip(n), (x, y) => new[] { x, y })
        .SelectMany(z => z)
        .ToArray();

这给了我:

2,3,5,4,1,7

或者这样:

public int[] Shuffle(int[] nums, int n) =>
(
    from zs in nums.Take(n).Zip(nums.Skip(n), (x, y) => new[] { x, y })
    from z in zs
    select z
).ToArray();

您可以计算应该将哪个项目放置在第 i 个索引处:

public static int[] Shuffle(int[] nums) {
  // Since we have public method, we should validate input
  if (null == nums)
    throw new ArgumentNullException(nameof(nums));

  if (nums.Length % 2 != 0)
    throw new ArgumentOutOfRangeException(nameof(nums));

  int[] result = new int[nums.Length];

  // All we have to do is to place right item at i-th index:
  for (int i = 0; i < nums.Length; ++i)
    result[i] = nums[i / 2 + (i % 2) * (nums.Length / 2)];

  return result;
}

请注意,我们可以去掉 n,因为我们可以很容易地将其计算为 n == nums.Length / 2

同样的想法通过 Linq 实现:

public static int[] Shuffle(int[] nums) {
  if (null == nums)
    throw new ArgumentNullException(nameof(nums));

  if (nums.Length % 2 != 0)
    throw new ArgumentOutOfRangeException(nameof(nums));

  return Enumerable
    .Range(0, nums.Length)
    .Select(i => nums[i / 2 + (i % 2) * (nums.Length / 2)])
    .ToArray();
}