Compare commits

...

10 commits

Author SHA1 Message Date
2fede2185f 2024-12-29 2024-12-29 10:39:46 +03:00
5946c94ca1 2024-09-30 2024-10-01 18:02:31 +03:00
ef0f2439ed 2024-08-31 2024-09-01 08:46:26 +03:00
ecba06df98 2024-07-31 2024-07-31 21:11:54 +03:00
25fd0a8d5a 2024-03-31 2024-03-31 02:15:32 +03:00
992ceb2e73 2024-02-29 2024-02-29 22:57:20 +03:00
2ee79646bc 2023-12-30 2023-12-30 23:58:04 +03:00
932a34b2f8 2023-11-30 2023-12-17 09:49:57 +03:00
8053b56b0a 2023-10-31 2023-12-17 09:39:45 +03:00
49002af1f8 2023-09-30 2023-12-17 08:48:55 +03:00
19 changed files with 92 additions and 104 deletions

View file

@ -3,9 +3,6 @@
<pre> <pre>
<a href='.'>.</a> <a href='.'>.</a>
├─ <a href='jekyll_site'>jekyll_site</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'>en</a>
│ │ ├─ <a href='jekyll_site/en/2021'>2021</a> │ │ ├─ <a href='jekyll_site/en/2021'>2021</a>
│ │ │ ├─ <a href='jekyll_site/en/2021/09'>09</a> │ │ │ ├─ <a href='jekyll_site/en/2021/09'>09</a>

View file

@ -1,4 +1,4 @@
© Головин Г.Г., 2021-2023 © Головин Г.Г., 2021-2024
Опубликовано под [Открытой лицензией 1.1](OPEN_LICENSE.txt) Опубликовано под [Открытой лицензией 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) Published under the [Open License 1.1](OPEN_LICENSE.txt)

View file

@ -1,37 +1,34 @@
#!/bin/bash #!/bin/bash
echo "Сборка сайта в двух помидорных темах и оптимизация результатов." echo "Сборка сайта в двух помидорных темах и оптимизация результатов."
currentTimeMillis=$(date '+%s%3N') time_ms="$(date '+%s%3N')"
rm -rf _site # удаление каталогов предыдущей сборки, если таковые имеются
rm -rf _site_older find . -maxdepth 1 -type d -name "_site*" -exec rm -rf {} \;
rm -rf _site_color # сборка сайта в двух помидорных темах
echo "Сборка старого помидора." function jekyll_build {
mkdir -p _site_older case "$1" in
cp -r jekyll_site/_includes _site_older "older") echo "Сборка старого помидора." ;;
cp -r jekyll_site/ru _site_older "color") echo "Сборка цветного помидора." ;;
cp -r jekyll_site/en _site_older *) return ;; # две помидорные темы оформления
cp -r jekyll_site/ru/index.md _site_older esac
cp -r jekyll_site/_config_older.yml _site_older/_config.yml mkdir -p "_site_$1"
cp -r jekyll_site/Gemfile_older _site_older/Gemfile cp -r "jekyll_site/ru" "_site_$1"
cd _site_older || exit cp -r "jekyll_site/en" "_site_$1"
jekyll build --disable-disk-cache cp -r "jekyll_site/ru/index.md" "_site_$1"
cp -r _site .. cp -r "jekyll_site/_config_$1.yml" "_site_$1/_config.yml"
cd .. cp -r "jekyll_site/Gemfile_$1" "_site_$1/Gemfile"
echo "Сборка цветного помидора." cd "_site_$1" || return
mkdir -p _site_color jekyll build --disable-disk-cache --quiet
cp -r jekyll_site/_includes _site_color }
cp -r jekyll_site/ru _site_color export -f jekyll_build
cp -r jekyll_site/en _site_color # запуск параллельной сборки сайта в двух помидорных темах оформления
cp -r jekyll_site/ru/index.md _site_color printf 'jekyll_build "%s"\0' {older,color} | xargs -n1 -0 -P0 bash -c
cp -r jekyll_site/_config_color.yml _site_color/_config.yml # объединение двух сборок
cp -r jekyll_site/Gemfile_color _site_color/Gemfile cp -r _site_older/_site .
cd _site_color || exit cp -r _site_color/_site ./_site/color
jekyll build --disable-disk-cache # копирование без сборки
cp -r _site ../_site/color
cd ..
echo "Копирование без сборки."
cp -r jekyll_site/img _site cp -r jekyll_site/img _site
cp -r jekyll_site/robots.txt _site cp -r jekyll_site/robots.txt _site
echo "Оптимизация собранного контента." # оптимизация собранного контента
cd _site || exit cd _site || exit
cp -r assets/* . cp -r assets/* .
rm -r assets rm -r assets
@ -39,13 +36,19 @@ rm -r color/assets/favicon.ico
cp -r color/assets/* . cp -r color/assets/* .
rm -r color/assets rm -r color/assets
rm -r color/404.html rm -r color/404.html
find . -type f -name '*.html' | sort -r | while read -r file; do rm -r color/return.html
sed -i 's/layout-padding=""/layout-padding/g' "$file" # шаблоны для оптимизации ряда тегов
sed -i 's/ class="language-plaintext highlighter-rouge"//g' "$file" expr+=('s|layout-padding=""|layout-padding|g')
sed -i 's/ class="language-java highlighter-rouge"//g' "$file" expr+=('s| class="language-plaintext highlighter-rouge"||g')
sed -i 's/<div><div class="highlight"><pre class="highlight">/<div class="highlight"><pre class="highlight">/g' "$file" expr+=('s| class="language-java highlighter-rouge"||g')
sed -i 's/<\/code><\/pre><\/div><\/div>/<\/code><\/pre><\/div>/g' "$file" expr+=('s|<div><div class="highlight">|<div class="highlight">|g')
sed -i 's/<hr \/>/<hr>/g' "$file" expr+=('s|</pre></div></div>|</pre></div>|g')
sed -i -r 's/<img(.+) \/>/<img\1>/g' "$file" expr+=('s|<hr />|<hr>|g')
done expr+=('s|<img(.+) />|<img\1>|g')
echo "Время выполнения сборки: $(("$(date '+%s%3N')" - "$currentTimeMillis")) мс." # запуск параллельной обработки собранных страниц и оптимизация ряда тегов
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)) мс."

View file

@ -4,7 +4,7 @@ name: "Код с комментариями"
name_translated: "Code with comments" name_translated: "Code with comments"
# URL адрес сайта, включая протокол # URL адрес сайта, включая протокол
url: "https://pomodoro2.mircloud.ru" url: "https://pomodoro2.mircloud.ru"
# подпапка этой сборки для относительных URLs # подпапка этой сборки для относительных URL-ов
baseurl: "/color" baseurl: "/color"
# ссылка в верхнем левом углу заглавных страниц # ссылка в верхнем левом углу заглавных страниц
homepage_url: "https://gitea.com/pomodoro/2" homepage_url: "https://gitea.com/pomodoro/2"
@ -20,6 +20,9 @@ author: "Головин Г.Г."
author_translated: "Golovin G.G." author_translated: "Golovin G.G."
# дополнение к подписи в футере для переведённых страниц # дополнение к подписи в футере для переведённых страниц
translation_caption: "translation from Russian" translation_caption: "translation from Russian"
# номера счётчиков для страниц
live_internet: "pomodoro"
yandex_metrika: "95699482"
# тема оформления для сборки # тема оформления для сборки
theme: color-tomato-theme theme: color-tomato-theme
# макет для сборки # макет для сборки

View file

@ -4,7 +4,7 @@ name: "Код с комментариями"
name_translated: "Code with comments" name_translated: "Code with comments"
# URL адрес сайта, включая протокол # URL адрес сайта, включая протокол
url: "https://pomodoro2.mircloud.ru" url: "https://pomodoro2.mircloud.ru"
# подпапка этой сборки для относительных URLs # подпапка этой сборки для относительных URL-ов
baseurl: "" baseurl: ""
# ссылка в верхнем левом углу заглавных страниц # ссылка в верхнем левом углу заглавных страниц
homepage_url: "https://gitea.com/pomodoro/2" homepage_url: "https://gitea.com/pomodoro/2"
@ -20,6 +20,9 @@ author: "Головин Г.Г."
author_translated: "Golovin G.G." author_translated: "Golovin G.G."
# дополнение к подписи в футере для переведённых страниц # дополнение к подписи в футере для переведённых страниц
translation_caption: "translation from Russian" translation_caption: "translation from Russian"
# номера счётчиков для страниц
live_internet: "pomodoro"
yandex_metrika: "95699482"
# тема оформления для сборки # тема оформления для сборки
theme: older-tomato-theme theme: older-tomato-theme
# макет для сборки # макет для сборки

View file

@ -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 -->

View file

@ -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>

View file

@ -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.

View file

@ -12,7 +12,7 @@ lang: en
In a two-dimensional array, data is stored row-wise. Consider an algorithm for obtaining 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 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. 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*: 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 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

View file

@ -12,7 +12,7 @@ lang: en
Consider a problem where you need to get all possible combinations of sequence elements, in which 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 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)* *[Table setting problem](#table-setting-problem) [Method for solving in Java](#combinations-of-length)*
@ -21,7 +21,7 @@ where {<code>k&nbsp;&le;&nbsp;n</code>}. If {<code>k&nbsp;=&nbsp;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&nbsp;=&nbsp;4</code>}, of whom it is known Four guests are invited to dinner {<code>n&nbsp;=&nbsp;4</code>}, of whom it is known
that no more than two people will arrive {<code>k&nbsp;=&nbsp;2</code>}, and the order that no more than two people will arrive {<code>k&nbsp;=&nbsp;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;&nbsp;max=size</code>} and get call this method without selection {<code>min=0;&nbsp;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.

View file

@ -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

View file

@ -27,7 +27,7 @@ loops.
{%- capture article_brief %} {%- capture article_brief %}
Consider a problem where you need to get all possible combinations of sequence elements, in which 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 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, An *arrangement* is an ordered set of {`k`} distinct elements from a set of {`n`} distinct elements,
where {<code>k&nbsp;&le;&nbsp;n</code>}. If {<code>k&nbsp;=&nbsp;n</code>}, then this ordered set where {<code>k&nbsp;&le;&nbsp;n</code>}. If {<code>k&nbsp;=&nbsp;n</code>}, then this ordered set
@ -39,7 +39,7 @@ a special case of *arrangement*.
{%- capture article_brief %} {%- capture article_brief %}
In a two-dimensional array, data is stored row-wise. Consider an algorithm for obtaining 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 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. result. The values do not necessarily have to be populated we discard the null elements.
{%- endcapture %} {%- endcapture %}
{%- assign articles = articles | push: article_brief %} {%- assign articles = articles | push: article_brief %}

View file

@ -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" %}
Массив содержит *фиксированное количество* элементов. Код выглядит немного сложнее. Массив содержит *фиксированное количество* элементов. Код выглядит немного сложнее.

View file

@ -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 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" %}
Код будет выглядеть проще, если предварительно *транспонировать* массив массивов, но если этого Код будет выглядеть проще, если предварительно *транспонировать* массив массивов, но если этого
нельзя сделать, тогда во внешнем цикле обходим колонки массива до тех пор, пока они ещё есть. нельзя сделать, тогда во внешнем цикле обходим колонки массива до тех пор, пока они ещё есть.

View file

@ -10,8 +10,8 @@ date: 2021.09.20
--- ---
Рассмотрим задачу, в которой нужно получить все возможные комбинации элементов последовательности, Рассмотрим задачу, в которой нужно получить все возможные комбинации элементов последовательности,
где количество элементов в комбинации не превышает заданного максимума, и напишем метод на Java где количество элементов в комбинации не превышает заданного максимума, и напишем метод для решения
с соответствующим отбором по минимальному и максимальному количеству элементов. на Java с соответствующим отбором по минимальному и максимальному количеству элементов.
*[Задача о сервировке стола](#table-setting-problem) [Метод для решения на Java](#combinations-of-length)* *[Задача о сервировке стола](#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`}, нарисуем все возможные Для наглядности возьмём последовательность из трёх элементов {`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&nbsp;=&nbsp;4</code>}, из которых известно, что На ужин приглашено четверо гостей {<code>n&nbsp;=&nbsp;4</code>}, из которых известно, что
приедут не более двух человек {<code>k&nbsp;=&nbsp;2</code>}, причём порядок их появления приедут не более двух человек {<code>k&nbsp;=&nbsp;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;&nbsp;max=size</code>} и получаем все возможные комбинации. этот метод без отбора {<code>min=0;&nbsp;max=size</code>} и получаем все возможные комбинации.
Для примера возьмём две последовательности из трёх элементов: цифр {`123`} и букв {`XYZ`}. Для примера возьмём две последовательности из трёх элементов: цифр {`123`} и букв {`XYZ`}.
### Описание метода {#method-description} {% include heading.html text="Описание метода" hash="method-description" type="3" %}
Подготавливаем два списка комбинаций: результирующий список и текущий список. В текущем списке Подготавливаем два списка комбинаций: результирующий список и текущий список. В текущем списке
количество элементов во всех комбинациях будет одинаковым. Максимальное количество элементов количество элементов во всех комбинациях будет одинаковым. Максимальное количество элементов

View file

@ -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 элемента. Время вычислений

View file

@ -25,8 +25,8 @@ title_translated: Code with comments
{%- assign articles = articles | push: "Комбинации элементов последовательности" %} {%- assign articles = articles | push: "Комбинации элементов последовательности" %}
{%- capture article_brief %} {%- capture article_brief %}
Рассмотрим задачу, в которой нужно получить все возможные комбинации элементов последовательности, Рассмотрим задачу, в которой нужно получить все возможные комбинации элементов последовательности,
где количество элементов в комбинации не превышает заданного максимума, и напишем метод на Java где количество элементов в комбинации не превышает заданного максимума, и напишем метод для решения
с соответствующим отбором по минимальному и максимальному количеству элементов. на Java с соответствующим отбором по минимальному и максимальному количеству элементов.
*Размещением* называется упорядоченный набор {`k`} различных элементов из множества {`n`} различных *Размещением* называется упорядоченный набор {`k`} различных элементов из множества {`n`} различных
элементов, где {<code>k&nbsp;&le;&nbsp;n</code>}. Если {<code>k&nbsp;=&nbsp;n</code>}, то такой элементов, где {<code>k&nbsp;&le;&nbsp;n</code>}. Если {<code>k&nbsp;=&nbsp;n</code>}, то такой
@ -38,7 +38,7 @@ title_translated: Code with comments
{%- capture article_brief %} {%- capture article_brief %}
В двухмерном массиве данные хранятся построчно. Рассмотрим алгоритм получения *декартова В двухмерном массиве данные хранятся построчно. Рассмотрим алгоритм получения *декартова
произведения* по столбцам с использованием трёх вложенных циклов. Количество строк и произведения* по столбцам с использованием трёх вложенных циклов. Количество строк и
колонок таблицы может быть произвольным. Последовательно перемножаем колонки и накапливаем колонок может быть произвольным. Последовательно перемножаем колонки таблицы и накапливаем
результат. Значения необязательно должны быть заполнены нулевые элементы отбрасываем. результат. Значения необязательно должны быть заполнены нулевые элементы отбрасываем.
{%- endcapture %} {%- endcapture %}
{%- assign articles = articles | push: article_brief %} {%- assign articles = articles | push: article_brief %}

View file

@ -1,5 +1,5 @@
#!/bin/bash #!/bin/bash
echo "Подготовка архива для последующего развёртывания." echo "Создание архива для последующего развёртывания."
cd _site || exit cd _site || exit
rm -rf ../pomodoro2.zip rm -rf ../pomodoro2.zip
7z a ../pomodoro2.zip ./* 7z a ../pomodoro2.zip . | grep -E '\S'

View file

@ -1,4 +1,4 @@
#!/bin/bash #!/bin/bash
echo "Локальное развёртывание для проверки корректности сборки." 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" echo "Адрес сервера: http://localhost:4000"