Calculate index for numerical combinations

I have a vector that contains a value for every possible combination of two numbers from a larger group of n numbers (from 0 to (n-1)), excluding combinations where both numbers are the same. For example, if n = 4, combinations will be displayed in the columns number1 and number2.

    number1  number2 vector-index value
    0        1       0             3
    0        2       1             98
    0        3       2             0
    1        0       3             44
    1        2       4             6
    1        3       5             3
    2        0       6             2
    2        1       7             43
    2        3       8             23
    3        0       9             11
    3        1       10            54
    3        2       11            7

There are always combinations n*(n-1), and therefore this is the number of elements in the vector (12 elements in the above example).

Problem

To access the values ​​in the vector, I need an expression that allows me to calculate the corresponding index number for each combination. If combinations were included, where number1 = number2, the index number could be determined using:

    index = number1*(n-1)+number2

This question is related, but also includes combinations where number1 = number2.

- ?

+4
2

-, , (n-1), n - . , (i, j) , , (n-1). , i. j < i, j . j-1 .

int index = i * (n - 1) + (j < i? j : j - 1);
+2

, , number2 , number1, , number2 , , - :

index = number1 * (n - 1) + number2 - (number2 > number1 ? 1 : 0)
0

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


All Articles