Separate number of items

I am trying to "divide" a number into elements X.

I mean, if my number 12and my desired item counter ( X) is equal 6, I want to split for each item 12/6=2, i.e.:

[0] = 2, [1] = 2, [2] = 2, [3] = 2, [4] = 2, [5] = 2 (Total 12)

if my number 13, so 13/6=2.1666in this case, how can I separate for each element? eg:

[0] = 3, [1] = 2, [2] = 2, [3] = 2, [4] = 2, [5] = 2 (Total 13)

Or if my number 10is10/6 = 1.66

[0] = 2, [1] = 2, [2] = 2, [3] = 2, [4] = 1, [5] = 1 (Total 10)

How can i do this?

+4
source share
2 answers

One way to do this:

  • create an array length numberOfParts,
  • repeat at a numbertime
    • increase each element of the array
    • if the end of the array is reached,
      • go back to the beginning of the array and add

In code:

private static int[] SeparateNumber(int number, int parts) {
    var array = new int[parts];
    int index = 0;
    for (int i = 0 ; i < number ; i++) {
        array[index++]++;
        if (index == parts) { // end of array reached
            index = 0;
        }
    }
    return array;
}

, . numberOfStacks, , .

, :

private static int[] SeparateNumber(int number, int count) {
    var remainder = number % count;
    var quotient = number  / count;
    return Enumerable.Repeat(quotient + 1, remainder)
        .Concat(Enumerable.Repeat(quotient, count - remainder)).ToArray();
}
+4

N X, floor(N / X). R, N / X 0...R-1, 1.

:

N = 10, X = 4

// array of X elements, each with the value, floor(10 / 4) = 2
array = [2, 2, 2, 2]

R = remainder 10 / 4 = 2

R 0..(2-1), 1.

array = [3, 3, 2, 2]

, , ,

the first R cells with the value, floor(N / X) + 1

and the rest with the value, floor(N / X)

.

+1

Source: https://habr.com/ru/post/1693487/


All Articles