Compare commits
10 commits
a3bd2c4043
...
2fede2185f
Author | SHA1 | Date | |
---|---|---|---|
2fede2185f | |||
5946c94ca1 | |||
ef0f2439ed | |||
ecba06df98 | |||
25fd0a8d5a | |||
992ceb2e73 | |||
2ee79646bc | |||
932a34b2f8 | |||
8053b56b0a | |||
49002af1f8 |
19 changed files with 92 additions and 104 deletions
|
@ -3,9 +3,6 @@
|
|||
<pre>
|
||||
<a href='.'>.</a>
|
||||
├─ <a href='jekyll_site'>jekyll_site</a>
|
||||
│ ├─ <a href='jekyll_site/_includes'>_includes</a>
|
||||
│ │ ├─ <a href='jekyll_site/_includes/counters_body.html'>counters_body.html</a>
|
||||
│ │ └─ <a href='jekyll_site/_includes/counters_head.html'>counters_head.html</a>
|
||||
│ ├─ <a href='jekyll_site/en'>en</a>
|
||||
│ │ ├─ <a href='jekyll_site/en/2021'>2021</a>
|
||||
│ │ │ ├─ <a href='jekyll_site/en/2021/09'>09</a>
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
© Головин Г.Г., 2021-2023
|
||||
© Головин Г.Г., 2021-2024
|
||||
|
||||
Опубликовано под [Открытой лицензией 1.1](OPEN_LICENSE.txt)
|
||||
|
||||
|
@ -8,7 +8,7 @@
|
|||
|
||||
---
|
||||
|
||||
© Golovin G.G., translation from Russian, 2021-2023
|
||||
© Golovin G.G., translation from Russian, 2021-2024
|
||||
|
||||
Published under the [Open License 1.1](OPEN_LICENSE.txt)
|
||||
|
||||
|
|
83
build.sh
83
build.sh
|
@ -1,37 +1,34 @@
|
|||
#!/bin/bash
|
||||
echo "Сборка сайта в двух помидорных темах и оптимизация результатов."
|
||||
currentTimeMillis=$(date '+%s%3N')
|
||||
rm -rf _site
|
||||
rm -rf _site_older
|
||||
rm -rf _site_color
|
||||
echo "Сборка старого помидора."
|
||||
mkdir -p _site_older
|
||||
cp -r jekyll_site/_includes _site_older
|
||||
cp -r jekyll_site/ru _site_older
|
||||
cp -r jekyll_site/en _site_older
|
||||
cp -r jekyll_site/ru/index.md _site_older
|
||||
cp -r jekyll_site/_config_older.yml _site_older/_config.yml
|
||||
cp -r jekyll_site/Gemfile_older _site_older/Gemfile
|
||||
cd _site_older || exit
|
||||
jekyll build --disable-disk-cache
|
||||
cp -r _site ..
|
||||
cd ..
|
||||
echo "Сборка цветного помидора."
|
||||
mkdir -p _site_color
|
||||
cp -r jekyll_site/_includes _site_color
|
||||
cp -r jekyll_site/ru _site_color
|
||||
cp -r jekyll_site/en _site_color
|
||||
cp -r jekyll_site/ru/index.md _site_color
|
||||
cp -r jekyll_site/_config_color.yml _site_color/_config.yml
|
||||
cp -r jekyll_site/Gemfile_color _site_color/Gemfile
|
||||
cd _site_color || exit
|
||||
jekyll build --disable-disk-cache
|
||||
cp -r _site ../_site/color
|
||||
cd ..
|
||||
echo "Копирование без сборки."
|
||||
time_ms="$(date '+%s%3N')"
|
||||
# удаление каталогов предыдущей сборки, если таковые имеются
|
||||
find . -maxdepth 1 -type d -name "_site*" -exec rm -rf {} \;
|
||||
# сборка сайта в двух помидорных темах
|
||||
function jekyll_build {
|
||||
case "$1" in
|
||||
"older") echo "Сборка старого помидора." ;;
|
||||
"color") echo "Сборка цветного помидора." ;;
|
||||
*) return ;; # две помидорные темы оформления
|
||||
esac
|
||||
mkdir -p "_site_$1"
|
||||
cp -r "jekyll_site/ru" "_site_$1"
|
||||
cp -r "jekyll_site/en" "_site_$1"
|
||||
cp -r "jekyll_site/ru/index.md" "_site_$1"
|
||||
cp -r "jekyll_site/_config_$1.yml" "_site_$1/_config.yml"
|
||||
cp -r "jekyll_site/Gemfile_$1" "_site_$1/Gemfile"
|
||||
cd "_site_$1" || return
|
||||
jekyll build --disable-disk-cache --quiet
|
||||
}
|
||||
export -f jekyll_build
|
||||
# запуск параллельной сборки сайта в двух помидорных темах оформления
|
||||
printf 'jekyll_build "%s"\0' {older,color} | xargs -n1 -0 -P0 bash -c
|
||||
# объединение двух сборок
|
||||
cp -r _site_older/_site .
|
||||
cp -r _site_color/_site ./_site/color
|
||||
# копирование без сборки
|
||||
cp -r jekyll_site/img _site
|
||||
cp -r jekyll_site/robots.txt _site
|
||||
echo "Оптимизация собранного контента."
|
||||
# оптимизация собранного контента
|
||||
cd _site || exit
|
||||
cp -r assets/* .
|
||||
rm -r assets
|
||||
|
@ -39,13 +36,19 @@ rm -r color/assets/favicon.ico
|
|||
cp -r color/assets/* .
|
||||
rm -r color/assets
|
||||
rm -r color/404.html
|
||||
find . -type f -name '*.html' | sort -r | while read -r file; do
|
||||
sed -i 's/layout-padding=""/layout-padding/g' "$file"
|
||||
sed -i 's/ class="language-plaintext highlighter-rouge"//g' "$file"
|
||||
sed -i 's/ class="language-java highlighter-rouge"//g' "$file"
|
||||
sed -i 's/<div><div class="highlight"><pre class="highlight">/<div class="highlight"><pre class="highlight">/g' "$file"
|
||||
sed -i 's/<\/code><\/pre><\/div><\/div>/<\/code><\/pre><\/div>/g' "$file"
|
||||
sed -i 's/<hr \/>/<hr>/g' "$file"
|
||||
sed -i -r 's/<img(.+) \/>/<img\1>/g' "$file"
|
||||
done
|
||||
echo "Время выполнения сборки: $(("$(date '+%s%3N')" - "$currentTimeMillis")) мс."
|
||||
rm -r color/return.html
|
||||
# шаблоны для оптимизации ряда тегов
|
||||
expr+=('s|layout-padding=""|layout-padding|g')
|
||||
expr+=('s| class="language-plaintext highlighter-rouge"||g')
|
||||
expr+=('s| class="language-java highlighter-rouge"||g')
|
||||
expr+=('s|<div><div class="highlight">|<div class="highlight">|g')
|
||||
expr+=('s|</pre></div></div>|</pre></div>|g')
|
||||
expr+=('s|<hr />|<hr>|g')
|
||||
expr+=('s|<img(.+) />|<img\1>|g')
|
||||
# запуск параллельной обработки собранных страниц и оптимизация ряда тегов
|
||||
find . -type f -name "*.html" -printf '%p\0' | xargs -I{} -n1 -0 -P0 bash -c \
|
||||
"echo 'Оптимизация: {}' && sed -i -E $(printf " -e '%s'" "${expr[@]}") '{}'"
|
||||
# переход в корень сайта для каталогов без заглавной страницы
|
||||
find . -type d -exec cp -n return.html {}/index.html \;
|
||||
rm -r return.html
|
||||
echo "Общее время выполнения: $(($(date '+%s%3N') - time_ms)) мс."
|
||||
|
|
|
@ -4,7 +4,7 @@ name: "Код с комментариями"
|
|||
name_translated: "Code with comments"
|
||||
# URL адрес сайта, включая протокол
|
||||
url: "https://pomodoro2.mircloud.ru"
|
||||
# подпапка этой сборки для относительных URLs
|
||||
# подпапка этой сборки для относительных URL-ов
|
||||
baseurl: "/color"
|
||||
# ссылка в верхнем левом углу заглавных страниц
|
||||
homepage_url: "https://gitea.com/pomodoro/2"
|
||||
|
@ -20,6 +20,9 @@ author: "Головин Г.Г."
|
|||
author_translated: "Golovin G.G."
|
||||
# дополнение к подписи в футере для переведённых страниц
|
||||
translation_caption: "translation from Russian"
|
||||
# номера счётчиков для страниц
|
||||
live_internet: "pomodoro"
|
||||
yandex_metrika: "95699482"
|
||||
# тема оформления для сборки
|
||||
theme: color-tomato-theme
|
||||
# макет для сборки
|
||||
|
|
|
@ -4,7 +4,7 @@ name: "Код с комментариями"
|
|||
name_translated: "Code with comments"
|
||||
# URL адрес сайта, включая протокол
|
||||
url: "https://pomodoro2.mircloud.ru"
|
||||
# подпапка этой сборки для относительных URLs
|
||||
# подпапка этой сборки для относительных URL-ов
|
||||
baseurl: ""
|
||||
# ссылка в верхнем левом углу заглавных страниц
|
||||
homepage_url: "https://gitea.com/pomodoro/2"
|
||||
|
@ -20,6 +20,9 @@ author: "Головин Г.Г."
|
|||
author_translated: "Golovin G.G."
|
||||
# дополнение к подписи в футере для переведённых страниц
|
||||
translation_caption: "translation from Russian"
|
||||
# номера счётчиков для страниц
|
||||
live_internet: "pomodoro"
|
||||
yandex_metrika: "95699482"
|
||||
# тема оформления для сборки
|
||||
theme: older-tomato-theme
|
||||
# макет для сборки
|
||||
|
|
|
@ -1,2 +0,0 @@
|
|||
<noscript><div><img src="https://mc.yandex.ru/watch/85876478" style="position:absolute; left:-9999px;" alt=""></div></noscript>
|
||||
<!-- /Yandex.Metrika counter -->
|
|
@ -1,16 +0,0 @@
|
|||
<!-- Google tag (gtag.js) -->
|
||||
<script async src="https://www.googletagmanager.com/gtag/js?id=G-CGTC57DX5F"></script>
|
||||
<script>
|
||||
window.dataLayer = window.dataLayer || [];
|
||||
function gtag(){dataLayer.push(arguments);}
|
||||
gtag('js', new Date());
|
||||
gtag('config', 'G-CGTC57DX5F');
|
||||
</script>
|
||||
<!-- Yandex.Metrika counter -->
|
||||
<script>
|
||||
(function(m,e,t,r,i,k,a){m[i]=m[i]||function(){(m[i].a=m[i].a||[]).push(arguments)};
|
||||
m[i].l=1*new Date();for(var j=0;j<document.scripts.length;j++){if(document.scripts[j].src===r){return;}}
|
||||
k=e.createElement(t),a=e.getElementsByTagName(t)[0],k.async=1,k.src=r,a.parentNode.insertBefore(k,a)})
|
||||
(window,document,"script","https://mc.yandex.ru/metrika/tag.js","ym");
|
||||
ym(85876478,"init",{clickmap:true,trackLinks:true,accurateTrackBounce:true,webvisor:true});
|
||||
</script>
|
|
@ -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]]
|
||||
```
|
||||
|
||||
### Combinations by columns {#combinations-by-columns}
|
||||
{% include heading.html text="Combinations by columns" hash="combinations-by-columns" type="3" %}
|
||||
|
||||
```
|
||||
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]
|
||||
```
|
||||
|
||||
## 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.
|
||||
|
||||
|
@ -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).
|
||||
|
||||
## 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.
|
||||
|
||||
|
|
|
@ -12,7 +12,7 @@ lang: en
|
|||
|
||||
In a two-dimensional array, data is stored row-wise. Consider an algorithm for obtaining
|
||||
a *Cartesian product* by columns using three nested loops. The number of rows and columns
|
||||
of the table can be arbitrary. We multiply the columns sequentially and accumulate the
|
||||
can be arbitrary. We multiply the columns of the table sequentially and accumulate the
|
||||
result. The values do not necessarily have to be populated — we discard the null elements.
|
||||
|
||||
For example, let's take a partially filled *jagged two-dimensional array*:
|
||||
|
@ -64,7 +64,7 @@ res0 * col1 = res1 * col2 = res2 * col3 = res3 * col4 = res4
|
|||
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
|
||||
|
@ -76,7 +76,7 @@ Number of combinations: 24
|
|||
[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
|
||||
this cannot be done, then in the outer loop, pass through the table columns as
|
||||
|
|
|
@ -12,7 +12,7 @@ lang: en
|
|||
|
||||
Consider a problem where you need to get all possible combinations of sequence elements, in which
|
||||
the number of elements in the combination does not exceed a given maximum, and let's write a method
|
||||
in Java with the appropriate filter for the minimum and maximum number of elements.
|
||||
for solving in Java with the appropriate filter for the minimum and maximum number of elements.
|
||||
|
||||
*[Table setting problem](#table-setting-problem) • [Method for solving in Java](#combinations-of-length)*
|
||||
|
||||
|
@ -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
|
||||
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
|
||||
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`}.
|
||||
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
|
||||
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
|
||||
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
|
||||
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
|
||||
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]
|
||||
```
|
||||
|
||||
## 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
|
||||
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
|
||||
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.
|
||||
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]]
|
||||
```
|
||||
|
||||
### Combinations by columns {#combinations-by-columns}
|
||||
{% include heading.html text="Combinations by columns" hash="combinations-by-columns" type="3" %}
|
||||
|
||||
```
|
||||
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]
|
||||
```
|
||||
|
||||
## 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*,
|
||||
for example, 20 lists of 2 elements or 15 lists of 3 elements. The computation time reduces by *one and
|
||||
|
|
|
@ -27,7 +27,7 @@ loops.
|
|||
{%- capture article_brief %}
|
||||
Consider a problem where you need to get all possible combinations of sequence elements, in which
|
||||
the number of elements in the combination does not exceed a given maximum, and let's write a method
|
||||
in Java with the appropriate filter for the minimum and maximum number of elements.
|
||||
for solving in Java with the appropriate filter for the minimum and maximum number of elements.
|
||||
|
||||
An *arrangement* is an ordered set of {`k`} distinct elements from a set of {`n`} distinct elements,
|
||||
where {<code>k ≤ n</code>}. If {<code>k = n</code>}, then this ordered set
|
||||
|
@ -39,7 +39,7 @@ a special case of *arrangement*.
|
|||
{%- capture article_brief %}
|
||||
In a two-dimensional array, data is stored row-wise. Consider an algorithm for obtaining
|
||||
a *Cartesian product* by columns using three nested loops. The number of rows and columns
|
||||
of the table can be arbitrary. We multiply the columns sequentially and accumulate the
|
||||
can be arbitrary. We multiply the columns of the table sequentially and accumulate the
|
||||
result. The values do not necessarily have to be populated — we discard the null elements.
|
||||
{%- endcapture %}
|
||||
{%- assign articles = articles | push: article_brief %}
|
||||
|
|
|
@ -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]]
|
||||
```
|
||||
|
||||
### Комбинации по столбцам {#combinations-by-columns}
|
||||
{% include heading.html text="Комбинации по столбцам" hash="combinations-by-columns" type="3" %}
|
||||
|
||||
```
|
||||
Количество комбинаций: 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]
|
||||
```
|
||||
|
||||
## Декартово произведение списков {#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).
|
||||
|
||||
## Декартово произведение массивов {#cartesian-product-of-arrays}
|
||||
{% include heading.html text="Декартово произведение массивов" hash="cartesian-product-of-arrays" %}
|
||||
|
||||
Массив содержит *фиксированное количество* элементов. Код выглядит немного сложнее.
|
||||
|
||||
|
|
|
@ -11,7 +11,7 @@ date: 2021.09.13
|
|||
|
||||
В двухмерном массиве данные хранятся построчно. Рассмотрим алгоритм получения *декартова
|
||||
произведения* по столбцам с использованием трёх вложенных циклов. Количество строк и
|
||||
колонок таблицы может быть произвольным. Последовательно перемножаем колонки и накапливаем
|
||||
колонок может быть произвольным. Последовательно перемножаем колонки таблицы и накапливаем
|
||||
результат. Значения необязательно должны быть заполнены — нулевые элементы отбрасываем.
|
||||
|
||||
Для примера возьмём частично заполненный *зубчатый двухмерный массив*:
|
||||
|
@ -63,7 +63,7 @@ res0 * col1 = res1 * col2 = res2 * col3 = res3 * col4 = res4
|
|||
1 * 4 = 4 * 2 = 8 * 1 = 8 * 3 = 24
|
||||
```
|
||||
|
||||
### Комбинации по столбцам {#combinations-by-columns}
|
||||
{% include heading.html text="Комбинации по столбцам" hash="combinations-by-columns" type="3" %}
|
||||
|
||||
```
|
||||
Количество комбинаций: 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]
|
||||
```
|
||||
|
||||
## Декартово произведение по столбцам {#cartesian-product-by-columns}
|
||||
{% include heading.html text="Декартово произведение по столбцам" hash="cartesian-product" %}
|
||||
|
||||
Код будет выглядеть проще, если предварительно *транспонировать* массив массивов, но если этого
|
||||
нельзя сделать, тогда во внешнем цикле обходим колонки массива до тех пор, пока они ещё есть.
|
||||
|
|
|
@ -10,8 +10,8 @@ date: 2021.09.20
|
|||
---
|
||||
|
||||
Рассмотрим задачу, в которой нужно получить все возможные комбинации элементов последовательности,
|
||||
где количество элементов в комбинации не превышает заданного максимума, и напишем метод на Java
|
||||
с соответствующим отбором по минимальному и максимальному количеству элементов.
|
||||
где количество элементов в комбинации не превышает заданного максимума, и напишем метод для решения
|
||||
на Java с соответствующим отбором по минимальному и максимальному количеству элементов.
|
||||
|
||||
*[Задача о сервировке стола](#table-setting-problem) • [Метод для решения на Java](#combinations-of-length)*
|
||||
|
||||
|
@ -20,7 +20,7 @@ date: 2021.09.20
|
|||
упорядоченный набор называется *перестановкой*. Для универсальности решения *перестановки* тоже
|
||||
будем учитывать как частный случай *размещения*.
|
||||
|
||||
## Количество возможных комбинаций {#number-of-possible-combinations}
|
||||
{% include heading.html text="Количество возможных комбинаций" hash="number-of-combinations" %}
|
||||
|
||||
Для наглядности возьмём последовательность из трёх элементов {`XYZ`}, нарисуем все возможные
|
||||
подмножества этого множества, добавим к ним перестановки и подсчитаем количество комбинаций.
|
||||
|
@ -63,7 +63,7 @@ static int factorial(int n) {
|
|||
}
|
||||
```
|
||||
|
||||
## Комбинации из трёх элементов {#combinations-of-elements}
|
||||
{% include heading.html text="Комбинации из трёх элементов" hash="combinations-of-elements" %}
|
||||
|
||||
Сравним две последовательности из трёх элементов: цифр {`123`} и букв {`XYZ`}. Тип элементов
|
||||
разный — комбинации одинаковые, потому что порядковые номера у элементов те же самые.
|
||||
|
@ -97,14 +97,14 @@ n Кол-во вариантов
|
|||
Рассмотрим задачу, где нужно ограничить возможные варианты
|
||||
по максимальному количеству входящих в них элементов.
|
||||
|
||||
## Задача о сервировке стола {#table-setting-problem}
|
||||
{% include heading.html text="Задача о сервировке стола" hash="table-setting-problem" %}
|
||||
|
||||
На ужин приглашено четверо гостей {<code>n = 4</code>}, из которых известно, что
|
||||
приедут не более двух человек {<code>k = 2</code>}, причём порядок их появления
|
||||
важен, поскольку от этого зависит сервировка стола. Известно также, что когда приедет первый,
|
||||
то он скажет, кто будет второй и приедет ли он. Рассчитать возможные варианты сервировки стола.
|
||||
|
||||
### Способ решения {#solution-approach}
|
||||
{% include heading.html text="Способ решения" hash="solution-approach" type="3" %}
|
||||
|
||||
Напишем метод на 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]
|
||||
```
|
||||
|
||||
## Комбинации элементов указанной длины {#combinations-of-length}
|
||||
{% include heading.html text="Комбинации элементов указанной длины" hash="combinations-of-length" %}
|
||||
|
||||
Пишем метод на Java с использованием трёх вложенных циклов `for`. Далее для проверки вызываем
|
||||
этот метод без отбора {<code>min=0; max=size</code>} и получаем все возможные комбинации.
|
||||
Для примера возьмём две последовательности из трёх элементов: цифр {`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]]
|
||||
```
|
||||
|
||||
### Комбинации по столбцам {#combinations-by-columns}
|
||||
{% include heading.html text="Комбинации по столбцам" hash="combinations-by-columns" type="3" %}
|
||||
|
||||
```
|
||||
Количество комбинаций: 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]
|
||||
```
|
||||
|
||||
## Комбинации элементов в параллельных потоках {#combinations-of-elements-in-parallel-streams}
|
||||
{% include heading.html text="Комбинации элементов в параллельных потоках" hash="combinations-of-elements" %}
|
||||
|
||||
В параллельном режиме скорость работы алгоритма увеличивается при перемножении *большого количества
|
||||
маленьких списков*, например 20 списков по 2 элемента или 15 списков по 3 элемента. Время вычислений
|
||||
|
|
|
@ -25,8 +25,8 @@ title_translated: Code with comments
|
|||
{%- assign articles = articles | push: "Комбинации элементов последовательности" %}
|
||||
{%- capture article_brief %}
|
||||
Рассмотрим задачу, в которой нужно получить все возможные комбинации элементов последовательности,
|
||||
где количество элементов в комбинации не превышает заданного максимума, и напишем метод на Java
|
||||
с соответствующим отбором по минимальному и максимальному количеству элементов.
|
||||
где количество элементов в комбинации не превышает заданного максимума, и напишем метод для решения
|
||||
на Java с соответствующим отбором по минимальному и максимальному количеству элементов.
|
||||
|
||||
*Размещением* называется упорядоченный набор {`k`} различных элементов из множества {`n`} различных
|
||||
элементов, где {<code>k ≤ n</code>}. Если {<code>k = n</code>}, то такой
|
||||
|
@ -38,7 +38,7 @@ title_translated: Code with comments
|
|||
{%- capture article_brief %}
|
||||
В двухмерном массиве данные хранятся построчно. Рассмотрим алгоритм получения *декартова
|
||||
произведения* по столбцам с использованием трёх вложенных циклов. Количество строк и
|
||||
колонок таблицы может быть произвольным. Последовательно перемножаем колонки и накапливаем
|
||||
колонок может быть произвольным. Последовательно перемножаем колонки таблицы и накапливаем
|
||||
результат. Значения необязательно должны быть заполнены — нулевые элементы отбрасываем.
|
||||
{%- endcapture %}
|
||||
{%- assign articles = articles | push: article_brief %}
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
#!/bin/bash
|
||||
echo "Подготовка архива для последующего развёртывания."
|
||||
echo "Создание архива для последующего развёртывания."
|
||||
cd _site || exit
|
||||
rm -rf ../pomodoro2.zip
|
||||
7z a ../pomodoro2.zip ./*
|
||||
7z a ../pomodoro2.zip . | grep -E '\S'
|
||||
|
|
2
serve.sh
2
serve.sh
|
@ -1,4 +1,4 @@
|
|||
#!/bin/bash
|
||||
echo "Локальное развёртывание для проверки корректности сборки."
|
||||
jekyll serve --skip-initial-build --disable-disk-cache --host localhost
|
||||
jekyll serve --skip-initial-build --no-watch --disable-disk-cache --host localhost
|
||||
echo "Адрес сервера: http://localhost:4000"
|
||||
|
|
Loading…
Add table
Reference in a new issue