Browse Source

HW 04 done

Olga_Brekhuntsova 3 years ago
parent
commit
e9a12d3042

+ 3 - 0
hw-js-04-structures-evaluations-loops/.vscode/settings.json

@@ -0,0 +1,3 @@
+{
+  "liveServer.settings.port": 5501
+}

+ 31 - 0
hw-js-04-structures-evaluations-loops/index.html

@@ -0,0 +1,31 @@
+<!DOCTYPE html>
+<html lang="ru">
+<head>
+    <meta charset="UTF-8" />
+    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+    <title>nix-js-04-structures-evaluations-loops</title>
+</head>
+
+<body style="padding:30px; font-family:Anonymous Pro, monospace">
+    <h1>structures-evaluations-loops</h1>
+    <div id='root'></div>
+    <script src="/js/task-01.js" type="module"></script>
+    <script src="/js/task-02.js" type="module"></script>
+    <script src="/js/task-03.js" type="module"></script>
+ <script src="/js/task-04.js" type="module"></script>
+    <script src="/js/task-05.js" type="module"></script>
+     <script src="/js/task-06.js" type="module"></script>
+    <script src="/js/task-07.js" type="module"></script>
+    <script src="/js/task-08.js" type="module"></script>
+    <script src="/js/task-09.js" type="module"></script>
+    <script src="/js/task-10.js" type="module"></script>
+    <script src="/js/task-11.js" type="module"></script>
+<script src="/js/task-12.js" type="module"></script>
+    <script src="/js/task-13.js" type="module"></script>
+<script src="/js/task-14.js" type="module"></script>
+<script src="/js/task-15.js" type="module"></script>
+<script src="/js/task-16.js" type="module"></script>
+<script src="/js/task-17.js" type="module"></script>
+</body>
+
+</html>

+ 147 - 0
hw-js-04-structures-evaluations-loops/js/task-01.js

@@ -0,0 +1,147 @@
+// html tree
+
+// -------------УСЛОВИЕ-------------
+{/* <body>
+        <div>
+            <span>Enter a data please:</span>
+            <br/>
+            <input type='text' id='name'>
+            <input type='text' id='surname'>
+        </div>
+        <div>
+            <button id='ok'>OK</button>
+            <button id='cancel'>Cancel</button>
+        </div>
+        </body> */}
+    
+{/* Сделайте декларативную JSON-структуру для тэгов выше, в которой:
+- каждый тэг будет объектом
+- имя тэга будет полем tagName
+- вложенные тэги будут в поле subTags
+- текст в тэге будет в поле text
+- набор аттрибутов тэга будет в поле attrs.
+         */}
+{/* Например для обычной таблицы 2x2 это будет выглядеть следующим образом: */}
+{/* <table border='1'>
+    <tr>
+        <td>
+            1x1
+        </td>
+        <td>
+            1x2
+        </td>
+    </tr>
+    <tr>
+        <td>
+            2x1
+        </td>
+        <td>
+            2x2
+        </td>
+    </tr>
+        </table>
+var table = {
+    tagName: 'table',
+    attrs: {
+        border: "1",
+    },
+    subTags: [
+        {
+            tagName: 'tr',
+            subTags: [
+                {
+                    tagName: "td",
+                    text: "1x1",
+                },
+                {
+                    tagName: "td",
+                    text: "1x2",
+                },
+            ]
+        },
+        {
+            tagName: 'tr',
+            subTags: [
+                {
+                    tagName: "td",
+                    text: "2x1",
+                },
+                {
+                    tagName: "td",
+                    text: "2x2",
+                },
+            ]
+        }
+    ]
+} */}
+
+{/* Выведите значения текста во второй кнопке, используя . и [].
+Выведите значение атрибута id во втором input, используя . и []. */}
+
+// -------------РЕШЕНИЕ-------------
+const body = {
+    tagName: "body",
+    subTags: [
+        {
+            tagName: "div",
+            subTags:
+                [
+                    {
+                        tagName: "span",
+                        text: "Enter a data please:"
+                    },
+                    {
+                        tagName: "br"
+                    },
+                    {
+                        tagName: "input",
+                        attrs: {
+                            type: "text",
+                            id: "name"
+                        }
+                    },
+                      {
+                        tagName: "input",
+                        attrs: {
+                            type: "text",
+                            id: "surname"
+                                }
+                       }
+                   ]
+        },
+        {
+            tagName: "div",
+            subTags:
+                [
+                    {
+                        tagName: "button",
+                        text: "OK",
+                        attrs: {
+                            id: "ok"
+                        }
+                    },
+                    {
+                        tagName: "button",
+                        text: "Cancel",
+                        attrs: {
+                            id: "cancel"
+                        }
+                    }
+                ]
+        }
+    ]
+    }
+    
+const task01block = document.createElement('div');
+task01block.style = "border: 2px solid green; border-radius:5px; margin-bottom:10px; padding:10px";
+const task01title = document.createElement('h2');
+task01title.innerText = 'Task-01 html tree';
+const elem1 = document.createElement('p');
+const elem2 = document.createElement('p');
+root.appendChild(task01block); 
+task01block.appendChild(task01title); 
+
+elem1.innerText=body.subTags[1].subTags[1].text;
+task01block.appendChild(elem1);
+elem2.innerText = body.subTags[0].subTags[3].attrs.id;
+task01block.appendChild(elem2);

+ 94 - 0
hw-js-04-structures-evaluations-loops/js/task-02.js

@@ -0,0 +1,94 @@
+// declarative fields
+
+// -------------УСЛОВИЕ-------------
+// Как известно, элемент массива и объекта может быть любого типа данных JS, т.е.в коде может быть любое выражение,
+// которое вычисляется в то или иное значение типа данных.
+// А значит, мы можем применять функции для ввода данных типа confirm или prompt:
+// var text = "Enter a number";
+// var arr3 = [+prompt(text), +prompt(text), +prompt(text)]; //вводим числа.
+// Организуйте таким способом заполнение полей в объектах:
+var notebook = {
+    brand: "HP",
+    type:  "440 G4",
+    model: "Y7Z75EA",
+    ram: 4,
+    size: "14",
+    weight: 1.8,
+    resolution: {
+        width: 1920,
+        height: 1080,
+    },
+};
+
+var phone = {
+    brand: "meizu",
+    model: "m2",
+    ram: 2,
+    color: "black",
+};
+
+var person = {
+    name: "Donald",
+    surname: "Trump",
+    married: true,
+}
+// Например:
+// var person = {
+//     name: prompt("Enter a name"),
+//     surname: prompt("Enter a surname"),
+// }
+// Используйте приведение к числу, prompt и confirm в зависимости от типов данных.
+
+// -------------РЕШЕНИЕ-------------
+
+const task02block = document.createElement('div');
+task02block.style = "border: 2px solid green; border-radius:5px; margin-bottom:10px; padding:10px";
+const task02title = document.createElement('h2');
+task02title.innerText = 'Task-02 Declarative fields';
+const inputBtn = document.createElement('button');
+inputBtn.innerText = 'Start input data';
+inputBtn.style = 'margin-bottom:10px';
+root.appendChild(task02block); 
+task02block.appendChild(task02title); 
+task02block.appendChild(inputBtn); 
+
+inputBtn.onclick = () => {
+const good1 = document.createElement('div');
+const good2 = document.createElement('div');
+const good3 = document.createElement('div');
+    let notebookNew = {
+        brand: prompt("Notebook: enter a brand"),
+        type: prompt("Notebook: enter a type"),
+        model: prompt("Notebook: enter a model"),
+        ram: +prompt("Notebook: enter ram number"),
+        size: prompt("Notebook: enter a size"),
+        weight: +prompt("Notebook: enter a weight"),
+        resolution: {
+            width: +prompt("Notebook: enter width"),
+            height: +prompt("Notebook: enter height"),
+        },
+        
+    };
+    good1.innerText = "Notebook:"+JSON.stringify(notebookNew);
+    task02block.appendChild(good1); 
+    console.log(notebookNew);
+    
+    var phoneNew = {
+        brand: prompt("Phone: enter a brand"),
+        model: prompt("Phone: enter a model"),
+        ram: +prompt("Phone: enter ram"),
+        color: prompt("Phone: enter a color"),
+    };
+    good2.innerText = "Phone:"+JSON.stringify(phoneNew);
+    task02block.appendChild(good2); 
+    console.log(phoneNew);
+
+    var personNew = {
+        name: prompt("Person: enter a name"),
+        surname: prompt("Person: enter a surname"),
+        married: confirm("Person: es married?"),
+    }
+    good3.innerText = "Person:"+JSON.stringify(personNew);
+    task02block.appendChild(good3); 
+    console.log(personNew);
+}

+ 65 - 0
hw-js-04-structures-evaluations-loops/js/task-03.js

@@ -0,0 +1,65 @@
+// object links
+
+// -------------УСЛОВИЕ-------------
+// Добавьте персоне гаджеты, используя новые поля smartphone и laptop в объекте персоны
+// Добавьте владельца в гаджеты, используя новое поле owner в объектах телефона и ноутбука.
+// обратите внимание на цикличность ссылок в объектах, если вы все сделали правильно, то
+// person.smartphone.owner.laptop.owner.smartphone == person.smartphone
+
+// -------------РЕШЕНИЕ-------------
+
+const task03block = document.createElement('div');
+task03block.style = "border: 2px solid green; border-radius:5px; margin-bottom:10px; padding:10px";
+const task03title = document.createElement('h2');
+task03title.innerText = 'Task-03 Object links';
+const checkBtn = document.createElement('button');
+checkBtn.innerText = 'Check the circle link';
+checkBtn.style = 'margin-bottom:10px';
+root.appendChild(task03block); 
+task03block.appendChild(task03title); 
+task03block.appendChild(checkBtn); 
+
+checkBtn.onclick = () => {
+const good1 = document.createElement('div');
+const good2 = document.createElement('div');
+const good3 = document.createElement('div');
+    var notebook = {
+        brand: "HP",
+        type: "440 G4",
+        model: "Y7Z75EA",
+        ram: 4,
+        size: "14",
+        weight: 1.8,
+        resolution: {
+            width: 1920,
+            height: 1080,
+        },
+    };
+  good1.innerText = "Notebook:"+JSON.stringify(notebook);
+    task03block.appendChild(good1); 
+
+    var phone = {
+        brand: "meizu",
+        model: "m2",
+        ram: 2,
+        color: "black",
+    };
+    good2.innerText = "Phone:"+JSON.stringify(phone);
+    task03block.appendChild(good2); 
+ 
+    var person = {
+        name: "Donald",
+        surname: "Trump",
+        married: true,
+    }
+    good3.innerText = "Person:"+JSON.stringify(person);
+    task03block.appendChild(good3); 
+ 
+    notebook.owner = person;
+    phone.owner = person;
+    person.smartphone = phone;
+    person.laptop = notebook;
+    const circleLink = document.createElement('p');
+    circleLink.innerHTML = `Check result: Expression <b>"person.smartphone.owner.laptop.owner.smartphone == person.smartphone"</b> returns <b>${person.smartphone.owner.laptop.owner.smartphone == person.smartphone}</b>`;
+    task03block.appendChild(circleLink);
+}

+ 39 - 0
hw-js-04-structures-evaluations-loops/js/task-04.js

@@ -0,0 +1,39 @@
+// imperative array fill 3
+// Создайте пустой массив и добавьте в него три элемента, введенные пользователем(prompt),
+// используя императивный подход(несколько операторов подряд)
+const task04block = document.createElement('div');
+task04block.style = "border: 2px solid green; border-radius:5px; margin-bottom:10px; padding:10px";
+const task04title = document.createElement('h2');
+task04title.innerText = 'Task-04  Imperative array fill 3';
+const inputPushBtn = document.createElement('button');
+inputPushBtn.innerText = 'Start array input by push';
+inputPushBtn.style = 'margin-bottom:10px';
+const inputDestrBtn = document.createElement('button');
+inputDestrBtn.innerText = 'Start array input using destruction';
+inputDestrBtn.style = 'margin-bottom:10px; margin-left:10px';
+root.appendChild(task04block); 
+task04block.appendChild(task04title); 
+task04block.appendChild(inputPushBtn); 
+task04block.appendChild(inputDestrBtn); 
+inputPushBtn.onclick = () => {
+let array = [];
+array.push(prompt('Ведите 1й элемент массива'), prompt('Ведите 2й элемент массива'), prompt('Ведите 3й элемент массива'));
+    const pushedArray = document.createElement('p');
+    const pushedArrayTitle = document.createElement('h3');
+    pushedArrayTitle.innerText = "Array by .push()";
+    pushedArray.innerText = `Array=[${array}]`;
+task04block.appendChild(pushedArrayTitle);
+    task04block.appendChild(pushedArray);
+    console.log(array);
+ }
+inputDestrBtn.onclick = () => {
+let array = [];
+array=[...array, prompt('Ведите 1й элемент массива'), prompt('Ведите 2й элемент массива'), prompt('Ведите 3й элемент массива')]
+    const destrArray = document.createElement('p');
+    const destrArrayTitle = document.createElement('h3');
+    destrArrayTitle.innerText = "Array by destruction";
+    destrArray.innerText =  `Array=[${array}]`;
+task04block.appendChild(destrArrayTitle);
+    task04block.appendChild(destrArray);
+    console.log(array);
+}

+ 16 - 0
hw-js-04-structures-evaluations-loops/js/task-05.js

@@ -0,0 +1,16 @@
+// while confirm
+// Сделайте цикл с confirm, который продолжается по Отмена и заканчивается по ОК.
+
+const task05block = document.createElement('div');
+task05block.style = "border: 2px solid green; border-radius:5px; margin-bottom:10px; padding:10px";
+const task05title = document.createElement('h2');
+task05title.innerText = 'Task-05 While confirm';
+const confirmBtn = document.createElement('button');
+confirmBtn.innerText = 'Start input data';
+confirmBtn.style = 'margin-bottom:10px';
+root.appendChild(task05block); 
+task05block.appendChild(task05title); 
+task05block.appendChild(confirmBtn); 
+confirmBtn.onclick = () => { 
+    while (!confirm('Жмакай. Остановить цикл: ОК'));
+}

+ 28 - 0
hw-js-04-structures-evaluations-loops/js/task-06.js

@@ -0,0 +1,28 @@
+// array fill
+// Создайте пустой массив и добавляйте в него элементы, пока пользователь не нажмет Отмена в очередном prompt.
+// Используйте push для удобства: push
+
+const task06block = document.createElement('div');
+task06block.style = "border: 2px solid green; border-radius:5px; margin-bottom:10px; padding:10px";
+const task06title = document.createElement('h2');
+task06title.innerText = 'Task-06  Array fill';
+const arrayFillBtn = document.createElement('button');
+arrayFillBtn.innerText = 'Fill array';
+arrayFillBtn.style = 'margin-bottom:10px';
+
+root.appendChild(task06block); 
+task06block.appendChild(task06title); 
+task06block.appendChild(arrayFillBtn); 
+ 
+arrayFillBtn.onclick = () => {
+    let array = [];
+    let elem = prompt('Ведите элемент массива'); 
+    while (elem)
+    {array.push(elem)
+elem = prompt('Ведите элемент массива') };
+    
+    const pushedArray = document.createElement('p');
+    pushedArray.innerText = `Array=[${array}]`;
+    task06block.appendChild(pushedArray);
+    console.log(array);
+ }

+ 29 - 0
hw-js-04-structures-evaluations-loops/js/task-07.js

@@ -0,0 +1,29 @@
+// array fill nopush
+// Сделайте предыдущее задание, не используя push, а обращаясь к элементам по индексу.
+const task07block = document.createElement('div');
+task07block.style = "border: 2px solid green; border-radius:5px; margin-bottom:10px; padding:10px";
+const task07title = document.createElement('h2');
+task07title.innerText = 'Task-07  Array fill nopush';
+const arrayFillBtn = document.createElement('button');
+arrayFillBtn.innerText = 'Fill array';
+arrayFillBtn.style = 'margin-bottom:10px';
+
+root.appendChild(task07block); 
+task07block.appendChild(task07title); 
+task07block.appendChild(arrayFillBtn); 
+ 
+arrayFillBtn.onclick = () => {
+    let array = [];
+    let i=0;
+    let elem = prompt('Ведите элемент массива'); 
+    while (elem)
+    {
+        array[i] = elem;
+        elem = prompt('Ведите элемент массива')
+    i++};
+    
+    const pushedArray = document.createElement('p');
+    pushedArray.innerText = `Array=[${array}]`;
+    task07block.appendChild(pushedArray);
+    console.log(array);
+ }

+ 27 - 0
hw-js-04-structures-evaluations-loops/js/task-08.js

@@ -0,0 +1,27 @@
+// infinite probability
+// Создайте бесконечный цикл, который прерывается с помощью конструкции break, когда Math.random() > 0.9.
+// Код должен подсчитывать количество итераций и вывести это число с помощью alert.
+
+const task08block = document.createElement('div');
+task08block.style = "border: 2px solid green; border-radius:5px; margin-bottom:10px; padding:10px";
+const task08title = document.createElement('h2');
+task08title.innerText = 'Task-08 Infinite probability';
+const runNumbersBtn = document.createElement('button');
+runNumbersBtn.innerText = 'Run Math.random()';
+runNumbersBtn.style = 'margin-bottom:10px';
+root.appendChild(task08block); 
+task08block.appendChild(task08title); 
+task08block.appendChild(runNumbersBtn); 
+runNumbersBtn.onclick = () => { 
+    let i = 0;
+    let number;
+    while (number = Math.random()) {
+        console.log(number);
+          i++;
+         if (number > 0.9) {
+      break;
+    }
+          }
+    
+    alert(`Math.random() ran ${i} times`)
+}

+ 18 - 0
hw-js-04-structures-evaluations-loops/js/task-09.js

@@ -0,0 +1,18 @@
+// empty loop
+// Сделайте цикл с prompt, который прерывается по нажатию OK и продолжается по нажатию "Отмена" c пустым телом цикла.
+
+
+const task09block = document.createElement('div');
+task09block.style = "border: 2px solid green; border-radius:5px; margin-bottom:10px; padding:10px";
+const task09title = document.createElement('h2');
+task09title.innerText = 'Task-09 Empty loop';
+const runLoopBtn = document.createElement('button');
+runLoopBtn.innerText = 'Run empty loop';
+runLoopBtn.style = 'margin-bottom:10px';
+root.appendChild(task09block); 
+task09block.appendChild(task09title); 
+task09block.appendChild(runLoopBtn); 
+runLoopBtn.onclick = () => { 
+      while (prompt('')===null) {
+   }
+ }

+ 29 - 0
hw-js-04-structures-evaluations-loops/js/task-10.js

@@ -0,0 +1,29 @@
+// progression sum
+// Подсчитать сумму арифметической прогрессии от 1 до N c шагом 3 (1,4,7....) используя цикл for.
+
+
+const task10block = document.createElement('div');
+task10block.style = "border: 2px solid green; border-radius:5px; margin-bottom:10px; padding:10px";
+const task10title = document.createElement('h2');
+task10title.innerText = 'Task-10 Progression sum';
+const countProgBtn = document.createElement('button');
+countProgBtn.innerText = 'Count progression sum';
+countProgBtn.style = 'margin-bottom:10px';
+root.appendChild(task10block); 
+task10block.appendChild(task10title); 
+task10block.appendChild(countProgBtn); 
+countProgBtn.onclick = () => { 
+    let sum = null;
+    const j = 3;
+    let elem = 1;
+    const n = +prompt('Введите N - кол-во членов арифметической прогрессии');
+    
+    if (n) {
+        for (let i = 1; i <= n; i++) { sum = elem + sum; elem = elem + j; }
+const sumResult = document.createElement('p');
+    sumResult.innerHTML = `Сумма арифметической прогрессии от 1 до ${n} c шагом 3 равна <b> ${sum}</b>`;
+    task10block.appendChild(sumResult);    }
+    else {alert("Некорректный ввод") }
+    
+}
+     

+ 25 - 0
hw-js-04-structures-evaluations-loops/js/task-11.js

@@ -0,0 +1,25 @@
+// chess one line
+// Сформировать строку " # # # # # " с помощью цикла for.
+// Длина строки может быть четной и нечетной, и указывается в одном месте в коде.
+
+const task11block = document.createElement('div');
+task11block.style = "border: 2px solid green; border-radius:5px; margin-bottom:10px; padding:10px";
+const task11title = document.createElement('h2');
+task11title.innerText = 'Task-11 Chess one line';
+const chessLineBtn = document.createElement('button');
+chessLineBtn.innerText = 'Form chess line';
+chessLineBtn.style = 'margin-bottom:11px';
+root.appendChild(task11block); 
+task11block.appendChild(task11title); 
+task11block.appendChild(chessLineBtn); 
+chessLineBtn.onclick = () => { 
+    let resultLine = "  ";
+    const n = +prompt('Введите кол-во ячеек в строке шахматного поля');
+        if (n) {
+        for (let i = 1; i <= n; i++) { resultLine = resultLine+(i%2?"  ":"#"); }
+const lineResult = document.createElement('p');
+    lineResult.innerHTML = `Строка шахматного поля из ${n} ячеек: <b> "${resultLine}"</b>`;
+    task11block.appendChild( lineResult);    }
+    else {alert("Некорректный ввод") }
+    
+}

+ 43 - 0
hw-js-04-structures-evaluations-loops/js/task-12.js

@@ -0,0 +1,43 @@
+// numbers
+// Сформировать строку c помощью вложенных циклов.Для перевода строки используйте \n.
+// 0123456789
+// 0123456789
+// 0123456789
+// 0123456789
+// 0123456789
+// 0123456789
+// 0123456789
+// 0123456789
+// 0123456789
+// 0123456789
+
+const task12block = document.createElement('div');
+task12block.style = "border: 2px solid green; border-radius:5px; margin-bottom:10px; padding:10px";
+const task12title = document.createElement('h2');
+task12title.innerText = 'Task-12 Numbers';
+const numberStringBtn = document.createElement('button');
+numberStringBtn.innerText = 'Form number lines';
+numberStringBtn.style = 'margin-bottom:12px';
+root.appendChild(task12block); 
+task12block.appendChild(task12title); 
+task12block.appendChild(numberStringBtn); 
+numberStringBtn.onclick = () => { 
+    let resultLine = "";
+    const n = +prompt('Введите желаемое количество строк');
+    const m = +prompt('Введите желаемое количество элементов в строке');
+  
+        if (n&&m) {
+            for (let j = 0; j < n; j++) {            
+                for (let i=0; i<m; i++) {
+                        resultLine = resultLine + (((i === 0) || (((i + 1) % m)||(j===(n-1)))) ? (i + " ") : (i + "\n"));
+                               }      
+                               }
+            console.log(resultLine);
+          
+    const lineResult = document.createElement('p');
+    lineResult.innerHTML = `Таблица чисел от 0 до ${m-1} из ${n} строк:<br/> <b> ${resultLine.split('\n').join("<br>")}</b>`;
+   task12block.appendChild(lineResult);
+                 }
+    else {alert("Некорректный ввод") }
+    
+}

+ 44 - 0
hw-js-04-structures-evaluations-loops/js/task-13.js

@@ -0,0 +1,44 @@
+// chess
+// Сформируйте строку с шахматной доской из вложенных циклов.Для перевода строки используйте \n.
+// Код должен поддерживать легкое изменение размеров доски.
+// .#.#.#.#.#.#
+// #.#.#.#.#.#.
+// .#.#.#.#.#.#
+// #.#.#.#.#.#.
+// .#.#.#.#.#.#
+// #.#.#.#.#.#.
+// .#.#.#.#.#.#
+// #.#.#.#.#.#.
+// .#.#.#.#.#.#
+// #.#.#.#.#.#.
+const task13block = document.createElement('div');
+task13block.style = "border: 2px solid green; border-radius:5px; margin-bottom:10px; padding:10px";
+const task13title = document.createElement('h2');
+task13title.innerText = 'Task-13 Chess';
+const chessFieldBtn = document.createElement('button');
+chessFieldBtn.innerText = 'Form chess field';
+chessFieldBtn.style = 'margin-bottom:13px';
+root.appendChild(task13block); 
+task13block.appendChild(task13title); 
+task13block.appendChild(chessFieldBtn); 
+chessFieldBtn.onclick = () => { 
+ let resultLine = "";
+    const n = +prompt('Введите желаемое количество строк');
+    const m = +prompt('Введите желаемое количество элементов в строке');
+  
+        if (n&&m) {
+            for (let j = 0; j < n; j++) {            
+                for (let i = 0; i < m; i++) {
+                  
+                    resultLine = resultLine + (((i === 0) || (((i + 1) % m) || (j === (n - 1)))) ? (j%2?(i%2?".":"#"):(i%2?"#":".")) : ((j%2?(i%2?".":"#"):(i%2?"#":".")) + "\n"));
+                               }      
+                               }
+            console.log(resultLine);
+          
+    const lineResult = document.createElement('p');
+    lineResult.innerHTML = `Шахматное поле ${n}Х${m}:<br/> <b> ${resultLine.split('\n').join("<br>")}</b>`;
+   task13block.appendChild(lineResult);
+                 }
+    else {alert("Некорректный ввод") }
+   
+    }

+ 45 - 0
hw-js-04-structures-evaluations-loops/js/task-14.js

@@ -0,0 +1,45 @@
+// cubes
+// Сформируйте массив из N элементов, содержащий в себе кубы индексов, т.е:
+// [0,1,8,27,64...]
+
+const task14block = document.createElement('div');
+task14block.style = "border: 2px solid green; border-radius:5px; margin-bottom:10px; padding:10px";
+const task14title = document.createElement('h2');
+task14title.innerText = 'Task-14 Cubes';
+const arrayDegreeBtn = document.createElement('button');
+arrayDegreeBtn.innerText = 'Form index-degree array with Math.pow()';
+arrayDegreeBtn.style = 'margin-bottom:14px';
+const arrayDegreeLoopBtn = document.createElement('button');
+arrayDegreeLoopBtn.innerText = 'Form index-degree array with loops';
+arrayDegreeLoopBtn.style = 'margin-bottom:14px; margin-left:10px';
+root.appendChild(task14block); 
+task14block.appendChild(task14title); 
+task14block.appendChild(arrayDegreeBtn); 
+task14block.appendChild(arrayDegreeLoopBtn); 
+arrayDegreeBtn.onclick = () => { 
+    let cubeArray = [];
+    const n = +prompt('Введите кол-во элементов массива');
+    const d = +prompt('Введите степень, в которую нужно возводить индекс');
+        if (n&&d) {
+            for (let i = 0; i < n; i++) { cubeArray[i] = Math.pow(i,d); }
+            console.log(cubeArray)
+const arrayResult = document.createElement('p');
+    arrayResult.innerHTML = `Массив из ${n} элементов, у которого каждый элемент равен индексу, возведенному в степень ${d}: <b> [${cubeArray}]</b>`;
+    task14block.appendChild( arrayResult);    }
+    else {alert("Некорректный ввод") }    
+}
+arrayDegreeLoopBtn.onclick = () => { 
+    let cubeArray = [];
+    const n = +prompt('Введите кол-во элементов массива');
+    const d = +prompt('Введите степень, в которую нужно возводить индекс');
+       if (n&&d) {
+           for (let i = 0; i < n; i++) {
+               cubeArray[i] = 1;
+             for (let j = 1; j <= d; j++) { cubeArray[i]*=i }
+                  }
+            console.log(cubeArray)
+const arrayResult = document.createElement('p');
+    arrayResult.innerHTML = `Массив из ${n} элементов, у которого каждый элемент равен индексу, возведенному в степень ${d}: <b> [${cubeArray}]</b>`;
+    task14block.appendChild( arrayResult);    }
+    else {alert("Некорректный ввод") }    
+}

+ 38 - 0
hw-js-04-structures-evaluations-loops/js/task-15.js

@@ -0,0 +1,38 @@
+// multiply table
+// C помощью вложенного цикла сформируйте массив массивов "таблица умножения".
+// Для инициализации вложенных массивов используйте
+// arr[i] = [] //в i-тый элемент массива заносится новый пустой массив
+// arr[5][6] должен быть равен, соответственно, 30, arr[7][2] == 14 и так далее.
+
+// matrix to html table
+// Сделайте вложенный цикл, который формирует HTML - таблицу в переменной строкового типа из любого двумерного массива.
+// Т.е.если в нём использовать результат работы предыдущего задания, то получится таблица умножения в HTML(Таблица Пифагора)
+
+const task15block = document.createElement('div');
+task15block.style = "border: 2px solid green; border-radius:5px; margin-bottom:10px; padding:10px";
+const task15title = document.createElement('h2');
+task15title.innerText = 'Task-15 Multiply table + matrix to html table';
+const formArrayBtn = document.createElement('button');
+formArrayBtn.innerText = 'Form multiply array';
+formArrayBtn.style = 'margin-bottom:15px';
+root.appendChild(task15block); 
+task15block.appendChild(task15title); 
+task15block.appendChild(formArrayBtn); 
+formArrayBtn.onclick = () => { 
+    let str="";
+const array = [];
+for (let i = 0; i <10; i++) {
+    array[i] = [];
+    str += "<tr>";
+    for (let j = 0; j < 10; j++) {
+        array[i][j] = (i + 1) * (j + 1);
+        str += "<td style='width:40px'>" + array[i][j] + "</td>";
+    }
+    str+="</tr>"
+    }
+    const arrayOutput = document.createElement('div');
+    arrayOutput.innerHTML = `<h3>Таблица Пифагора:</h3> <table><b> ${str}</b></table>`;
+    task15block.appendChild( arrayOutput);  
+    console.log(array);
+ }
+

+ 42 - 0
hw-js-04-structures-evaluations-loops/js/task-16.js

@@ -0,0 +1,42 @@
+// Задание на синий пояс: Треугольник
+// Сформировать следующую строку - треугольник:
+// .....#.....
+// ....###....
+// ...#####...
+// ..#######..
+// .#########.
+// ###########
+
+const task16block = document.createElement('div');
+task16block.style = "border: 2px solid green; border-radius:5px; margin-bottom:10px; padding:10px";
+const task16title = document.createElement('h2');
+task16title.innerText = 'Task-16 Triangle blue belt';
+const task16comment = document.createElement('p');
+task16comment.innerText = 'Возможно построение треугольника на любое кол-во строк';
+const makeTrianBtn = document.createElement('button');
+makeTrianBtn.innerText = 'Draw triangle';
+makeTrianBtn.style = 'margin-bottom:16px';
+root.appendChild(task16block); 
+task16block.appendChild(task16title); 
+task16block.appendChild(task16comment); 
+task16block.appendChild(makeTrianBtn); 
+makeTrianBtn.onclick = () => { 
+ let resultLine = "";
+    const n = +prompt('Введите желаемое количество строк');
+    // const m = +prompt('Введите желаемое нечетное количество элементов в строке');
+  
+        if (n) {
+            for (let j = 1; j <= n; j++) {            
+                for (let i = 1; i <= 2*n-1; i++) {
+                    resultLine = resultLine + (((i >= n - (j - 1)) && (i <= n + (j - 1)) )? "#" : ".")+((i===(2*n-1))?"\n":"");
+                                                  }      
+                               }
+            console.log(resultLine);
+          
+    const lineResult = document.createElement('p');
+    lineResult.innerHTML = `Треугольник с ${n} строками:<br/> <b> ${resultLine.split('\n').join("<br>")}</b>`;
+   task16block.appendChild(lineResult);
+                 }
+    else {alert("Некорректный ввод") }
+   
+    }

+ 170 - 0
hw-js-04-structures-evaluations-loops/js/task-17.js

@@ -0,0 +1,170 @@
+// Задание на черный пояс: Электронная гадалка
+
+// Пользователь вводит 0 или 1. Гадалка пытается угадать, что введет пользователь (естественно перед его вводом),
+//     но не показывает пользователю, чтобы пользователь не выбрал противоположный вариант,
+//         а выводит предполагаемый вариант в консоль, скрытую от пользователя.
+// Как это работает?
+//     Гадалка хранит историю ввода(4 последних числа) пользователя в массиве history.
+// Каждое следующее число добавляется с помощью push в конец массива, при этом первое число из массива(самое старое)
+// удаляется с помощью shift.
+// Гадалка запоминает, что пользователь ввёл в предыдущий раз после такой истории.То есть, если пользователь
+// вводил 0, 1, 0, 1, 0, то логично предположить, что с историей 0, 1, 0, 1 следующим вариантом будет 0.
+// Для хранения используется 4х мерный массив, индексами которого является история:
+// predictArray[history[0]][history[1]][history[2]][history[3]] равно тому, что пользователь ввёл после истории в предыдущий раз.
+// Алгоритм:
+// Изначально predictArray содержит, например, -1, или иные значения, которые отличаются от пользовательского ввода.
+// История пусть состоит из единиц: history = [1, 1, 1, 1];, Т.е.считается что пользователь нажимал 1 четыре ряда подряд.
+// Пока мы не можем предсказать, так как в массиве еще не сохранилось то, что вводил пользователь, мы используем Math.random
+// в качестве предсказания, и записываем ввод пользователя в массив predictArray, добавляя новые значения в history,
+//     и сдвигая его.Т.е.если пользователь ввел 0, то:
+// predictArray[1][1][1][1] = 0; //1,1,1,1 - история, 0 - новое значение
+// history = [1, 1, 1, 0]        //удаляем старую единицу из истории и добавляем введенный только что 0
+// Для предсказания следующего достаем значение массива predictArray[1, 1, 1, 0], а после ввода опять записываем туда то,
+// что ввёл пользователь(пусть 1):
+// predictArray[1][1][1][0] = 1; //1,1,1,0 - история, 1 - новое значение
+// history = [1, 1, 0, 1]        //удаляем старую единицу из истории и добавляем введенный только что 1
+// Таким образом в predictArray накапливаются знания о том, что вводит пользователь после определенной истории чисел.
+
+const task17block = document.createElement('div');
+task17block.style = "border: 2px solid green; border-radius:5px; margin-bottom:10px; padding:10px";
+const task17title = document.createElement('h2');
+task17title.innerText = 'Task-17 Digital Vanga';
+const task17comment = document.createElement('p');
+task17comment.innerText = 'Возможно сохранение истории в n-мерный массив';
+const playVangaBtn = document.createElement('button');
+playVangaBtn.innerText = 'Play';
+playVangaBtn.style = 'margin-bottom:17px';
+root.appendChild(task17block); 
+task17block.appendChild(task17title); 
+task17block.appendChild(task17comment); 
+task17block.appendChild(playVangaBtn); 
+playVangaBtn.onclick = () => { 
+    let history = [];
+    let predictArray = [-1, -1];
+    let VangaNumber = null;
+    let step = null;
+    let userNumber = null;
+    const historyDeep=+prompt('Введите кол-во элементов, записываемых в историю')
+    // const historyDeep = 4;
+
+// Формирование начального многомерного массива predictArray произвольной глубины вложенности
+    function predictArrayFirstFilling(predictArray, historyDeep) {
+        let prePredictArray = [];
+        if (historyDeep ===0) {
+    return predictArray;
+  } else {
+            
+            prePredictArray = JSON.parse(JSON.stringify(predictArray));
+            //Деструктуризация и слайс не дали глубокого копирования, потому использовала JSON.parse(JSON.stringify)
+            // prePredictArray = [...predictArray];
+            //  prePredictArray = predictArray.slice(0);
+            for (let j = 0; j < 2; j++) {
+                // predictArray[j] = prePredictArray.slice(0);
+                // predictArray[j] = [...prePredictArray];
+                predictArray[j] = JSON.parse(JSON.stringify(prePredictArray));
+      }
+    return predictArrayFirstFilling (predictArray, historyDeep - 1);
+  }
+    }
+    predictArrayFirstFilling(predictArray, historyDeep-1);
+  
+// для постоянной глубины истории =4
+    // for (let i = 0; i < 2; i++) { 
+    //       predictArray[i] = [];
+    //     for (let j = 0; j < 2; j++) { 
+    //           predictArray[i][j] = [];
+    //         for (let k = 0; k < 2; k++) {
+    //               predictArray[i][j][k] = [];
+    //             for (let l = 0; l < 2; l++) {
+    //                 predictArray[i][j][k][l] = -1;
+    //             }
+    //              }
+    //       }
+    // }
+
+// Формирование 1-го массива history
+    for (step = 0; step < historyDeep; step++) {
+        VangaNumber = (Math.random() > 0.5) ? 1 : 0;
+        console.log(`Гадалка задумала: ${VangaNumber}`);
+        userNumber = prompt('Введите одно из чисел: 0 или 1');
+      
+        if (!(userNumber === null)) {
+            if (!(userNumber === "")) {
+                if (userNumber == 1 || userNumber == 0) {
+                    history[step] = userNumber;
+                    VangaNumber == userNumber ? alert(`Гадалка угадала, что ты загадал ${userNumber} `) : alert('Гадалка не угадала твое число')
+                }
+                else {
+                    alert("Ошибка ввода. Нужно ввести число 0 или 1");
+                    step--;
+                }
+            }
+            else {
+                alert("Ошибка ввода. Нужно ввести число 0 или 1");
+                step--;
+            }
+        }
+        else break;
+    }
+    console.log(`history=[${ history }]`);
+    // Формирование 2-го и более массивов history и внесение статистики в predictArray
+    while (!(userNumber === null)) {
+        //Проверка наличия записи в predictArray
+        let predictArrayElement = predictArray;
+        let prePredictArrayElement = [];
+        for (let i = 0; i < historyDeep; i++) {
+            prePredictArrayElement = predictArrayElement;
+            if (i < historyDeep - 1) {
+                predictArrayElement = [...prePredictArrayElement[history[i]]];
+            }
+            else {
+                predictArrayElement = predictArrayElement[history[i]];
+            }
+        }
+        //Выбор гадалки
+        if (predictArrayElement == 0 || predictArrayElement == 1) {
+            VangaNumber = predictArrayElement;
+            console.log(`Гадалка задумала: ${VangaNumber}`);
+        }
+        else {
+            VangaNumber = (Math.random() > 0.5) ? 1 : 0;
+            console.log(`Гадалка задумала: ${VangaNumber}`);
+        };
+    
+        userNumber = prompt('Введите одно из чисел: 0 или 1') 
+            if (!(userNumber === null)) {
+                if (!(userNumber === "")) {
+                    if (userNumber == 1 || userNumber == 0) {
+                        VangaNumber == userNumber ? alert(`Гадалка угадала, что ты загадал ${userNumber} `) : alert('Гадалка не угадала твое число');
+                
+                        //Перезапись нужного элемента массива predictArray
+                        let predictArrayElement = 'predictArray';
+                        for (let i = 0; i < historyDeep; i++) { 
+                            predictArrayElement +=`[${[history[i]]}]`;
+                        }
+                        predictArrayElement += `=${userNumber}`;
+                        eval(predictArrayElement);                    
+                    
+    history.push(userNumber);
+    history.splice(0, 1);
+    console.log(`history=[${history}]`);
+                    }
+                    else {
+                        alert("Ошибка ввода. Нужно ввести число 0 или 1");
+                        step--;
+                    }
+                }
+                else {
+                    alert("Ошибка ввода. Нужно ввести число 0 или 1");
+                    step--;
+                }
+            }
+            else break;
+                }
+    console.log(`predictArray=`);
+    console.log(predictArray);
+  
+    }
+
+
+

+ 7 - 0
hw-js-04-structures-evaluations-loops/readme.md

@@ -0,0 +1,7 @@
+Каждая задача в отдельном скрипте, чтобы удобнее было проверять.
+Выполнены все задачи на все пояса, и даже больше:
+
+1. треугольник можно строить на любое кол=-во строк
+2. гадалке можно устанавливать кол-во элементов, которые вносятся в историю, и соответственно, глубину многомерного массива статистики predictArray
+
+Хостинг http://hw_js_04.olgapistryak.fe.a-level.com.ua/