2023-09-30
This commit is contained in:
parent
a3bd2c4043
commit
49002af1f8
10 changed files with 30 additions and 30 deletions
|
@ -7,9 +7,9 @@ url: "https://pomodoro2.mircloud.ru"
|
||||||
# подпапка этой сборки для относительных URLs
|
# подпапка этой сборки для относительных URLs
|
||||||
baseurl: "/color"
|
baseurl: "/color"
|
||||||
# ссылка в верхнем левом углу заглавных страниц
|
# ссылка в верхнем левом углу заглавных страниц
|
||||||
homepage_url: "https://gitea.com/pomodoro/2"
|
homepage_url: "https://git.org.ru/pomodoro/2"
|
||||||
# представление ссылки
|
# представление ссылки
|
||||||
homepage_name: "GITEA"
|
homepage_name: "GIT.ORG.RU"
|
||||||
# подпапка альтернативной сборки
|
# подпапка альтернативной сборки
|
||||||
older_tomato_baseurl: ""
|
older_tomato_baseurl: ""
|
||||||
# часовой пояс для формата даты ISO-8601
|
# часовой пояс для формата даты ISO-8601
|
||||||
|
|
|
@ -7,9 +7,9 @@ url: "https://pomodoro2.mircloud.ru"
|
||||||
# подпапка этой сборки для относительных URLs
|
# подпапка этой сборки для относительных URLs
|
||||||
baseurl: ""
|
baseurl: ""
|
||||||
# ссылка в верхнем левом углу заглавных страниц
|
# ссылка в верхнем левом углу заглавных страниц
|
||||||
homepage_url: "https://gitea.com/pomodoro/2"
|
homepage_url: "https://git.org.ru/pomodoro/2"
|
||||||
# представление ссылки
|
# представление ссылки
|
||||||
homepage_name: "GITEA"
|
homepage_name: "GIT.ORG.RU"
|
||||||
# подпапка альтернативной сборки
|
# подпапка альтернативной сборки
|
||||||
color_tomato_baseurl: "/color"
|
color_tomato_baseurl: "/color"
|
||||||
# часовой пояс для формата даты ISO-8601
|
# часовой пояс для формата даты ISO-8601
|
||||||
|
|
|
@ -58,7 +58,7 @@ result3: [[A,E,H],[A,E,I],[A,F,H],[A,F,I],[A,G,H],...[D,G,I]]
|
||||||
result4: [[A,E,H,J],[A,E,I,J],[A,F,H,J],[A,F,I,J],[A,G,H,J],...[D,G,I,J]]
|
result4: [[A,E,H,J],[A,E,I,J],[A,F,H,J],[A,F,I,J],[A,G,H,J],...[D,G,I,J]]
|
||||||
```
|
```
|
||||||
|
|
||||||
### Combinations by columns {#combinations-by-columns}
|
{% include heading.html text="Combinations by columns" hash="combinations-by-columns" type="3" %}
|
||||||
|
|
||||||
```
|
```
|
||||||
Number of combinations: 24
|
Number of combinations: 24
|
||||||
|
@ -70,7 +70,7 @@ Number of combinations: 24
|
||||||
[A, G, I, J] [B, G, I, J] [C, G, I, J] [D, G, I, J]
|
[A, G, I, J] [B, G, I, J] [C, G, I, J] [D, G, I, J]
|
||||||
```
|
```
|
||||||
|
|
||||||
## Cartesian product of lists {#cartesian-product-of-lists}
|
{% include heading.html text="Cartesian product of lists" hash="cartesian-product-of-lists" %}
|
||||||
|
|
||||||
The list can contain a *modifiable number* of elements. This simplifies the code.
|
The list can contain a *modifiable number* of elements. This simplifies the code.
|
||||||
|
|
||||||
|
@ -137,7 +137,7 @@ public static void main(String[] args) {
|
||||||
|
|
||||||
The output for this and the following code is the same, see above: [combinations by columns](#combinations-by-columns).
|
The output for this and the following code is the same, see above: [combinations by columns](#combinations-by-columns).
|
||||||
|
|
||||||
## Cartesian product of arrays {#cartesian-product-of-arrays}
|
{% include heading.html text="Cartesian product of arrays" hash="cartesian-product-of-arrays" %}
|
||||||
|
|
||||||
The array contains a *fixed number* of elements. The code looks a little more complicated.
|
The array contains a *fixed number* of elements. The code looks a little more complicated.
|
||||||
|
|
||||||
|
|
|
@ -64,7 +64,7 @@ res0 * col1 = res1 * col2 = res2 * col3 = res3 * col4 = res4
|
||||||
1 * 4 = 4 * 2 = 8 * 1 = 8 * 3 = 24
|
1 * 4 = 4 * 2 = 8 * 1 = 8 * 3 = 24
|
||||||
```
|
```
|
||||||
|
|
||||||
### Combinations by columns {#combinations-by-columns}
|
{% include heading.html text="Combinations by columns" hash="combinations-by-columns" type="3" %}
|
||||||
|
|
||||||
```
|
```
|
||||||
Number of combinations: 24
|
Number of combinations: 24
|
||||||
|
@ -76,7 +76,7 @@ Number of combinations: 24
|
||||||
[A1, B2, C1, D3] [A2, B2, C1, D3] [A3, B2, C1, D3] [A4, B2, C1, D3]
|
[A1, B2, C1, D3] [A2, B2, C1, D3] [A3, B2, C1, D3] [A4, B2, C1, D3]
|
||||||
```
|
```
|
||||||
|
|
||||||
## Cartesian product by columns {#cartesian-product-by-columns}
|
{% include heading.html text="Cartesian product by columns" hash="cartesian-product" %}
|
||||||
|
|
||||||
The code will look simpler if you first *transpose* an array of arrays, but if
|
The code will look simpler if you first *transpose* an array of arrays, but if
|
||||||
this cannot be done, then in the outer loop, pass through the table columns as
|
this cannot be done, then in the outer loop, pass through the table columns as
|
||||||
|
|
|
@ -21,7 +21,7 @@ where {<code>k ≤ n</code>}. If {<code>k = n</code>}, then
|
||||||
is a *permutation*. For the universality of the solution, we'll also consider *permutations* as
|
is a *permutation*. For the universality of the solution, we'll also consider *permutations* as
|
||||||
a special case of *arrangement*.
|
a special case of *arrangement*.
|
||||||
|
|
||||||
## Number of possible combinations {#number-of-possible-combinations}
|
{% include heading.html text="Number of possible combinations" hash="number-of-combinations" %}
|
||||||
|
|
||||||
For clarity, we'll take a sequence of three elements {`XYZ`}, draw all possible subsets
|
For clarity, we'll take a sequence of three elements {`XYZ`}, draw all possible subsets
|
||||||
of this set, add permutations to them and calculate the number of combinations.
|
of this set, add permutations to them and calculate the number of combinations.
|
||||||
|
@ -64,7 +64,7 @@ static int factorial(int n) {
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
## Combinations of three elements {#combinations-of-elements}
|
{% include heading.html text="Combinations of three elements" hash="combinations-of-elements" %}
|
||||||
|
|
||||||
Let's compare two sequences of three elements: digits {`123`} and letters {`XYZ`}.
|
Let's compare two sequences of three elements: digits {`123`} and letters {`XYZ`}.
|
||||||
The type of elements is different — combinations are the same, because the sequence
|
The type of elements is different — combinations are the same, because the sequence
|
||||||
|
@ -99,7 +99,7 @@ n number of variants
|
||||||
Consider a problem where you need to limit the possible variants
|
Consider a problem where you need to limit the possible variants
|
||||||
by the maximum number of elements contained in them.
|
by the maximum number of elements contained in them.
|
||||||
|
|
||||||
## Table setting problem {#table-setting-problem}
|
{% include heading.html text="Table setting problem" hash="table-setting-problem" %}
|
||||||
|
|
||||||
Four guests are invited to dinner {<code>n = 4</code>}, of whom it is known
|
Four guests are invited to dinner {<code>n = 4</code>}, of whom it is known
|
||||||
that no more than two people will arrive {<code>k = 2</code>}, and the order
|
that no more than two people will arrive {<code>k = 2</code>}, and the order
|
||||||
|
@ -107,7 +107,7 @@ of their appearance is important, since the table setting depends on it. It is a
|
||||||
known that when the first one arrives, this person will say who will be the second and
|
known that when the first one arrives, this person will say who will be the second and
|
||||||
whether this person will arrive. Calculate the possible variants for table setting.
|
whether this person will arrive. Calculate the possible variants for table setting.
|
||||||
|
|
||||||
### Solution approach {#solution-approach}
|
{% include heading.html text="Solution approach" hash="solution-approach" type="3" %}
|
||||||
|
|
||||||
Let's write a method in Java for solving such problems, which will take three
|
Let's write a method in Java for solving such problems, which will take three
|
||||||
parameters as input: sequence size, minimum and maximum number of elements in
|
parameters as input: sequence size, minimum and maximum number of elements in
|
||||||
|
@ -148,14 +148,14 @@ number of variants: 17
|
||||||
[][1][2][3][4][12][13][14][21][23][24][31][32][34][41][42][43]
|
[][1][2][3][4][12][13][14][21][23][24][31][32][34][41][42][43]
|
||||||
```
|
```
|
||||||
|
|
||||||
## Combinations of elements of specified length {#combinations-of-length}
|
{% include heading.html text="Combinations of elements of specified length" hash="combinations-of-length" %}
|
||||||
|
|
||||||
We write a method in Java using three nested `for` loops. Next, to check, we
|
We write a method in Java using three nested `for` loops. Next, to check, we
|
||||||
call this method without selection {<code>min=0; max=size</code>} and get
|
call this method without selection {<code>min=0; max=size</code>} and get
|
||||||
all possible combinations. For example, let's take two sequences of three
|
all possible combinations. For example, let's take two sequences of three
|
||||||
elements: digits {`123`} and letters {`XYZ`}.
|
elements: digits {`123`} and letters {`XYZ`}.
|
||||||
|
|
||||||
### Method description {#method-description}
|
{% include heading.html text="Method description" hash="method-description" type="3" %}
|
||||||
|
|
||||||
We prepare two lists of combinations: the resulting list and the current list.
|
We prepare two lists of combinations: the resulting list and the current list.
|
||||||
In the current list, the number of elements in all combinations will be the same.
|
In the current list, the number of elements in all combinations will be the same.
|
||||||
|
|
|
@ -68,7 +68,7 @@ result3: [[A1,A2,A3],[A1,A2,B3],[A1,B2,A3],[A1,B2,B3],[A1,C2,A3],...[D1,C2,B3]]
|
||||||
result4: [[A1,A2,A3,A4],[A1,A2,B3,A4],[A1,B2,A3,A4],[A1,B2,B3,A4],...[D1,C2,B3,A4]]
|
result4: [[A1,A2,A3,A4],[A1,A2,B3,A4],[A1,B2,A3,A4],[A1,B2,B3,A4],...[D1,C2,B3,A4]]
|
||||||
```
|
```
|
||||||
|
|
||||||
### Combinations by columns {#combinations-by-columns}
|
{% include heading.html text="Combinations by columns" hash="combinations-by-columns" type="3" %}
|
||||||
|
|
||||||
```
|
```
|
||||||
Number of combinations: 24
|
Number of combinations: 24
|
||||||
|
@ -80,7 +80,7 @@ Number of combinations: 24
|
||||||
[A1, C2, B3, A4] [B1, C2, B3, A4] [C1, C2, B3, A4] [D1, C2, B3, A4]
|
[A1, C2, B3, A4] [B1, C2, B3, A4] [C1, C2, B3, A4] [D1, C2, B3, A4]
|
||||||
```
|
```
|
||||||
|
|
||||||
## Combinations of elements in parallel streams {#combinations-of-elements-in-parallel-streams}
|
{% include heading.html text="Combinations of elements in parallel streams" hash="combinations-of-elements" %}
|
||||||
|
|
||||||
In parallel mode, the speed of the algorithm increases when multiplying a *large number of small lists*,
|
In parallel mode, the speed of the algorithm increases when multiplying a *large number of small lists*,
|
||||||
for example, 20 lists of 2 elements or 15 lists of 3 elements. The computation time reduces by *one and
|
for example, 20 lists of 2 elements or 15 lists of 3 elements. The computation time reduces by *one and
|
||||||
|
|
|
@ -57,7 +57,7 @@ result3: [[A,E,H],[A,E,I],[A,F,H],[A,F,I],[A,G,H],...[D,G,I]]
|
||||||
result4: [[A,E,H,J],[A,E,I,J],[A,F,H,J],[A,F,I,J],[A,G,H,J],...[D,G,I,J]]
|
result4: [[A,E,H,J],[A,E,I,J],[A,F,H,J],[A,F,I,J],[A,G,H,J],...[D,G,I,J]]
|
||||||
```
|
```
|
||||||
|
|
||||||
### Комбинации по столбцам {#combinations-by-columns}
|
{% include heading.html text="Комбинации по столбцам" hash="combinations-by-columns" type="3" %}
|
||||||
|
|
||||||
```
|
```
|
||||||
Количество комбинаций: 24
|
Количество комбинаций: 24
|
||||||
|
@ -69,7 +69,7 @@ result4: [[A,E,H,J],[A,E,I,J],[A,F,H,J],[A,F,I,J],[A,G,H,J],...[D,G,I,J]]
|
||||||
[A, G, I, J] [B, G, I, J] [C, G, I, J] [D, G, I, J]
|
[A, G, I, J] [B, G, I, J] [C, G, I, J] [D, G, I, J]
|
||||||
```
|
```
|
||||||
|
|
||||||
## Декартово произведение списков {#cartesian-product-of-lists}
|
{% include heading.html text="Декартово произведение списков" hash="cartesian-product-of-lists" %}
|
||||||
|
|
||||||
Список может содержать *изменяемое количество* элементов. Это упрощает код.
|
Список может содержать *изменяемое количество* элементов. Это упрощает код.
|
||||||
|
|
||||||
|
@ -136,7 +136,7 @@ public static void main(String[] args) {
|
||||||
|
|
||||||
Вывод для этого и следующего кода одинаковый, см. выше: [комбинации по столбцам](#combinations-by-columns).
|
Вывод для этого и следующего кода одинаковый, см. выше: [комбинации по столбцам](#combinations-by-columns).
|
||||||
|
|
||||||
## Декартово произведение массивов {#cartesian-product-of-arrays}
|
{% include heading.html text="Декартово произведение массивов" hash="cartesian-product-of-arrays" %}
|
||||||
|
|
||||||
Массив содержит *фиксированное количество* элементов. Код выглядит немного сложнее.
|
Массив содержит *фиксированное количество* элементов. Код выглядит немного сложнее.
|
||||||
|
|
||||||
|
|
|
@ -63,7 +63,7 @@ res0 * col1 = res1 * col2 = res2 * col3 = res3 * col4 = res4
|
||||||
1 * 4 = 4 * 2 = 8 * 1 = 8 * 3 = 24
|
1 * 4 = 4 * 2 = 8 * 1 = 8 * 3 = 24
|
||||||
```
|
```
|
||||||
|
|
||||||
### Комбинации по столбцам {#combinations-by-columns}
|
{% include heading.html text="Комбинации по столбцам" hash="combinations-by-columns" type="3" %}
|
||||||
|
|
||||||
```
|
```
|
||||||
Количество комбинаций: 24
|
Количество комбинаций: 24
|
||||||
|
@ -75,7 +75,7 @@ res0 * col1 = res1 * col2 = res2 * col3 = res3 * col4 = res4
|
||||||
[A1, B2, C1, D3] [A2, B2, C1, D3] [A3, B2, C1, D3] [A4, B2, C1, D3]
|
[A1, B2, C1, D3] [A2, B2, C1, D3] [A3, B2, C1, D3] [A4, B2, C1, D3]
|
||||||
```
|
```
|
||||||
|
|
||||||
## Декартово произведение по столбцам {#cartesian-product-by-columns}
|
{% include heading.html text="Декартово произведение по столбцам" hash="cartesian-product" %}
|
||||||
|
|
||||||
Код будет выглядеть проще, если предварительно *транспонировать* массив массивов, но если этого
|
Код будет выглядеть проще, если предварительно *транспонировать* массив массивов, но если этого
|
||||||
нельзя сделать, тогда во внешнем цикле обходим колонки массива до тех пор, пока они ещё есть.
|
нельзя сделать, тогда во внешнем цикле обходим колонки массива до тех пор, пока они ещё есть.
|
||||||
|
|
|
@ -20,7 +20,7 @@ date: 2021.09.20
|
||||||
упорядоченный набор называется *перестановкой*. Для универсальности решения *перестановки* тоже
|
упорядоченный набор называется *перестановкой*. Для универсальности решения *перестановки* тоже
|
||||||
будем учитывать как частный случай *размещения*.
|
будем учитывать как частный случай *размещения*.
|
||||||
|
|
||||||
## Количество возможных комбинаций {#number-of-possible-combinations}
|
{% include heading.html text="Количество возможных комбинаций" hash="number-of-combinations" %}
|
||||||
|
|
||||||
Для наглядности возьмём последовательность из трёх элементов {`XYZ`}, нарисуем все возможные
|
Для наглядности возьмём последовательность из трёх элементов {`XYZ`}, нарисуем все возможные
|
||||||
подмножества этого множества, добавим к ним перестановки и подсчитаем количество комбинаций.
|
подмножества этого множества, добавим к ним перестановки и подсчитаем количество комбинаций.
|
||||||
|
@ -63,7 +63,7 @@ static int factorial(int n) {
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
## Комбинации из трёх элементов {#combinations-of-elements}
|
{% include heading.html text="Комбинации из трёх элементов" hash="combinations-of-elements" %}
|
||||||
|
|
||||||
Сравним две последовательности из трёх элементов: цифр {`123`} и букв {`XYZ`}. Тип элементов
|
Сравним две последовательности из трёх элементов: цифр {`123`} и букв {`XYZ`}. Тип элементов
|
||||||
разный — комбинации одинаковые, потому что порядковые номера у элементов те же самые.
|
разный — комбинации одинаковые, потому что порядковые номера у элементов те же самые.
|
||||||
|
@ -97,14 +97,14 @@ n Кол-во вариантов
|
||||||
Рассмотрим задачу, где нужно ограничить возможные варианты
|
Рассмотрим задачу, где нужно ограничить возможные варианты
|
||||||
по максимальному количеству входящих в них элементов.
|
по максимальному количеству входящих в них элементов.
|
||||||
|
|
||||||
## Задача о сервировке стола {#table-setting-problem}
|
{% include heading.html text="Задача о сервировке стола" hash="table-setting-problem" %}
|
||||||
|
|
||||||
На ужин приглашено четверо гостей {<code>n = 4</code>}, из которых известно, что
|
На ужин приглашено четверо гостей {<code>n = 4</code>}, из которых известно, что
|
||||||
приедут не более двух человек {<code>k = 2</code>}, причём порядок их появления
|
приедут не более двух человек {<code>k = 2</code>}, причём порядок их появления
|
||||||
важен, поскольку от этого зависит сервировка стола. Известно также, что когда приедет первый,
|
важен, поскольку от этого зависит сервировка стола. Известно также, что когда приедет первый,
|
||||||
то он скажет, кто будет второй и приедет ли он. Рассчитать возможные варианты сервировки стола.
|
то он скажет, кто будет второй и приедет ли он. Рассчитать возможные варианты сервировки стола.
|
||||||
|
|
||||||
### Способ решения {#solution-approach}
|
{% include heading.html text="Способ решения" hash="solution-approach" type="3" %}
|
||||||
|
|
||||||
Напишем метод на Java для решения подобных задач, который будет принимать на вход три параметра:
|
Напишем метод на Java для решения подобных задач, который будет принимать на вход три параметра:
|
||||||
размер последовательности, минимальное и максимальное количество элементов в комбинации.
|
размер последовательности, минимальное и максимальное количество элементов в комбинации.
|
||||||
|
@ -145,13 +145,13 @@ public static void main(String[] args) {
|
||||||
[][1][2][3][4][12][13][14][21][23][24][31][32][34][41][42][43]
|
[][1][2][3][4][12][13][14][21][23][24][31][32][34][41][42][43]
|
||||||
```
|
```
|
||||||
|
|
||||||
## Комбинации элементов указанной длины {#combinations-of-length}
|
{% include heading.html text="Комбинации элементов указанной длины" hash="combinations-of-length" %}
|
||||||
|
|
||||||
Пишем метод на Java с использованием трёх вложенных циклов `for`. Далее для проверки вызываем
|
Пишем метод на Java с использованием трёх вложенных циклов `for`. Далее для проверки вызываем
|
||||||
этот метод без отбора {<code>min=0; max=size</code>} и получаем все возможные комбинации.
|
этот метод без отбора {<code>min=0; max=size</code>} и получаем все возможные комбинации.
|
||||||
Для примера возьмём две последовательности из трёх элементов: цифр {`123`} и букв {`XYZ`}.
|
Для примера возьмём две последовательности из трёх элементов: цифр {`123`} и букв {`XYZ`}.
|
||||||
|
|
||||||
### Описание метода {#method-description}
|
{% include heading.html text="Описание метода" hash="method-description" type="3" %}
|
||||||
|
|
||||||
Подготавливаем два списка комбинаций: результирующий список и текущий список. В текущем списке
|
Подготавливаем два списка комбинаций: результирующий список и текущий список. В текущем списке
|
||||||
количество элементов во всех комбинациях будет одинаковым. Максимальное количество элементов
|
количество элементов во всех комбинациях будет одинаковым. Максимальное количество элементов
|
||||||
|
|
|
@ -68,7 +68,7 @@ result3: [[A1,A2,A3],[A1,A2,B3],[A1,B2,A3],[A1,B2,B3],[A1,C2,A3],...[D1,C2,B3]]
|
||||||
result4: [[A1,A2,A3,A4],[A1,A2,B3,A4],[A1,B2,A3,A4],[A1,B2,B3,A4],...[D1,C2,B3,A4]]
|
result4: [[A1,A2,A3,A4],[A1,A2,B3,A4],[A1,B2,A3,A4],[A1,B2,B3,A4],...[D1,C2,B3,A4]]
|
||||||
```
|
```
|
||||||
|
|
||||||
### Комбинации по столбцам {#combinations-by-columns}
|
{% include heading.html text="Комбинации по столбцам" hash="combinations-by-columns" type="3" %}
|
||||||
|
|
||||||
```
|
```
|
||||||
Количество комбинаций: 24
|
Количество комбинаций: 24
|
||||||
|
@ -80,7 +80,7 @@ result4: [[A1,A2,A3,A4],[A1,A2,B3,A4],[A1,B2,A3,A4],[A1,B2,B3,A4],...[D1,C2,B3,A
|
||||||
[A1, C2, B3, A4] [B1, C2, B3, A4] [C1, C2, B3, A4] [D1, C2, B3, A4]
|
[A1, C2, B3, A4] [B1, C2, B3, A4] [C1, C2, B3, A4] [D1, C2, B3, A4]
|
||||||
```
|
```
|
||||||
|
|
||||||
## Комбинации элементов в параллельных потоках {#combinations-of-elements-in-parallel-streams}
|
{% include heading.html text="Комбинации элементов в параллельных потоках" hash="combinations-of-elements" %}
|
||||||
|
|
||||||
В параллельном режиме скорость работы алгоритма увеличивается при перемножении *большого количества
|
В параллельном режиме скорость работы алгоритма увеличивается при перемножении *большого количества
|
||||||
маленьких списков*, например 20 списков по 2 элемента или 15 списков по 3 элемента. Время вычислений
|
маленьких списков*, например 20 списков по 2 элемента или 15 списков по 3 элемента. Время вычислений
|
||||||
|
|
Loading…
Add table
Reference in a new issue