1

I have this mainArray (dynamically generated):

    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();
}

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]

How can I do it?

1
  • [0,0] [1,1],[2,2] = not uniq; [0,1],[0,1][2,2]=not uniq; , only uniq posibility is the one from my question; Commented Mar 5, 2016 at 14:45

2 Answers 2

1

So initially you have a set of n * k items of n different values where each value is repeated k times. And you want to arrange those n * k items into k sets in such a way that each value in the resulting sets is unique.

You can do it in the following way

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;
Sign up to request clarification or add additional context in comments.

Comments

0

Do you mean to say that all of the arrays have to have different numbers in each array, or that each array must be unique from the others?

If you want to just make arrays with unique numbers, try the following. I'm sure there is a better solution, but I'm fairly certain this may work for your situation.

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;
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.