Distribute values ​​based on the start and end values ​​and the number of value holders.

I am trying to distribute values ​​over a specific number of value holders based on the values ​​of Start and End.

If the number of value holders is equal to the difference between the starting and ending values, it will just be an iteration:

Start Value  : 1
End Value    : 10
Value Holders: 10
|
Expected Result: 1 2 3 4 5 6 7 8 9 10

If the number of value holders is less than the difference between the initial and final values, we need to skip some numbers. The goal is to try to distribute the values ​​as evenly as possible.

NOTE. Relying on neither the right nor the left is not important :)

Start Value  : 1
End Value    : 10
Value Holders: 5
|
Expected Result: 1 3 5 8 10
                 or
                 1 3 6 8 10

Start Value  : 1
End Value    : 10
Value Holders: 3
|
Expected Result: 1 5 10
                 or
                 1 6 10

If the number of value holders is greater than the difference between the start and end values, we will repeat some numbers.

Start Value  : 1
End Value    : 10
Value Holders: 15
|
Expected Result: 1 2 3 4 4 5 5 6 6 7 7 8 8 9 10
                 (or something similar)

How can I implement this in C #?

+4
source share
2

a1 ( ), N ( ) aN ( ).

:
enter image description here

d, .

d = (aN - a1) / (N - 1)

, :

public int[] GetValues(int a, int b, int count)
{
    double d = (b - a) / (double)(count - 1);

    return Enumerable.Range(0, count)
       .Select(i => (int)Math.Round(a + d * i))
       .ToArray();
}

// Usage:
int[] r1 = GetValues(1, 10, 10); // 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
int[] r2 = GetValues(1, 10, 5); // 1, 3, 6, 8, 10
int[] r3 = GetValues(1, 10, 15); // 1, 2, 2, 3, 4, 4, 5, 6, 6, 7, 7, 8, 9, 9, 10

(int)Math.Round(), .

+4

"" - . (end-start) "" (holders - 1). step , .

static List<int> Distribute(int start, int end, int holders)
{
    List<int> result = new List<int>();

    // First value will always be the start
    result.Add(start);

    // Calculate the step size for the middle values
    double range = end - start;
    double step = range / (holders - 1);

    // Generate the middle values using the step spacing
    for (int i = 1; i < holders - 1; i++)
    {
        double target = step * i + start;
        result.Add((int)Math.Round(target));
    }

    // Last value is the end
    result.Add(end);
    return result;
}

, "". Math.Round . Math.Ceiling , Math.Floor , .

+2

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


All Articles