如何在唯一数组中动态拆分数组

本文关键字:数组 拆分 动态 唯一 | 更新日期: 2023-09-27 18:37:27

我有这个mainArray(动态生成):

    static void Main()
{
    var n = 3;
    var k = 2;
    var a = n * k;
    var mainArray = new int[a];
    var index = 0;
    for (var i = 0; i < n; i++)
    {
        for (var j = 0; j < k; j++)
        {
            mainArray[index] = i;
            index++;
        }
    }
    //=> mainArray=[0,0,1,1,2,2]
    // How to split this array in 3 uniq arrays, like:
    //array1=[0,1]
    //array2=[1,2]
    //array3=[0,2]
    Console.WriteLine(String.Join(",", mainArray));
    Console.ReadLine();
}

主数组=[0,0,1,1,2,2]

如何将此数组拆分为 3 个 uniq 数组,例如:

数组1=[0,1]

数组2=[1,2]

数组3=[0,2]

我该怎么做?

如何在唯一数组中动态拆分数组

因此,

最初您有一组n * kn个不同的值,其中每个值重复k次。并且您希望将这些n * k项排列到k集中,以使结果集中的每个值都是唯一的。

您可以通过以下方式进行操作

int[][] res = Enumerable.Range(0, n).Select(x => new int[k]).ToArray();
for(int i = 0; i < n; i++)
    for(int j = 0; j < k; j++)
        res[i][j] = (i + j) % n;

你的意思是说所有数组在每个数组中必须有不同的数字,还是每个数组必须与其他数组不同?

如果您只想使用唯一数字创建数组,请尝试以下操作。我相信有更好的解决方案,但我相当确定这可能适用于您的情况。

public static int[][] splitUnique(int[] input, int length)
    {
        if (input.Length % length != 0) throw new Exception("Length cannot yield full arrays of length " + length);
        List<int> numbers = new List<int>(input);
        int[][] data = new int[input.Length / length][];
        int dataIndex = 0;
        while (numbers.Count != 0)
        {
            int[] temp = new int[length];
            int tempIndex = 0;
            foreach (int num in numbers)
            {
                if (!temp.Contains(num))
                {
                    temp[tempIndex] = num;
                    tempIndex++;
                }
                if (tempIndex >= length)
                {
                    break;
                }
            }
            foreach (int num in temp)
            {
                numbers.Remove(num);
            }
            data[dataIndex] = temp;
            dataIndex++;
        }
        return data;
    }