G
G
gelix12672020-08-11 23:18:17
Mathematics
gelix1267, 2020-08-11 23:18:17

Number of combinations of JavaScript numbers?

How to find the number of combinations of numbers from a string from 4 to 12 characters. Condition: the number of separating points is 3, the characters between the points are from 1 to 3, the numbers do not change places. For example, String '1234'. Possible combinations: '1.2.3.4' Number of combinations = '1. The string '12345'. Possible combinations: '1.2.3.45', '1.2.34.5', '1.23.4.5', '12.3.4.5' Number of combinations = '4'

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
alekseyHunter, 2020-08-12
@alekseyHunter

1) Use the formula from probability theory to find the number of combinations.
2) You can make a recursion. Exit from it - the number of calls is equal to the number of combinations. Add the resulting line to the tail.

W
Wataru, 2020-08-12
@wataru

In stupid it is possible to count up 2 nested cycles.

ans = 0;
for (i = 1; i <= 3; ++i) {
  for (j = 1; j <= 3; ++j) {
    mn = max(n - i - j - 3, 1);
    mx = n - i - j - 1;
    if (mn <= mx)
      ans += mx - mn + 1;
  }
}

It works like this - we sort out how many characters are in the first and second block. After that, we consider how many minimum and maximum characters can be in the third block (leaving 1 to 3 characters for the last one). We add to the answer the number of possible options for the length of the third block.
But this is if your parameters are fixed (4 blocks of 1-3 characters). If the parameters can change, then the solution is dynamic programming f(i,k) - how many ways to split the first i characters into k blocks.
Base: f(0,0) = 1, f(0, k>0) = 0, f (i>0, 0) = 0;
Recalculation: f(i,k) = sum_{l=min_length...min(max_length, i)}(f(il,k-1)).
Answer: f(n, num_blocks).

G
Griboks, 2020-08-12
@Griboks

You can read a math textbook and draw up a formula on a piece of paper, then implement it not in js.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question