нужно чтобы можно было добавлять конечные точки в каждой ветви, в которых будет…
- User
нужно чтобы можно было добавлять конечные точки в каждой ветви, в которых будет определено конечное косметическое средство как результат прохождения по всему дереву алгоритма - доработай программу:
ul, li {list-style: none; margin: 0; padding-left: 20px;} .node>.label {cursor: pointer; user-select: none; padding: 2px 4px; display: inline-block;} .selected>.label {background: #c2dbff;} .node>.label::before {content: "▶"; display: inline-block; width: 1em; color: #555;} .node.open>.label::before {content: "▼";} .node.leaf>.label::before {content: "•"; color: #999;} .node ul {display: none;} .node.open>ul {display: block;} Assistant
Вот доработанная версия программы с возможностью добавления конечных точек (результатов) в каждой ветви:
<!DOCTYPE html> <html lang="ru"> <head> <meta charset="UTF-8"> <title>Конструктор алгоритма косметического средства</title> <style> body {font-family: Arial, sans-serif; margin: 20px;} h2 {margin-top: 0;} #controls {margin-bottom: 14px;} #controls input {padding: 4px;} #controls button {padding: 6px 10px; margin-right: 4px;} ul, li {list-style: none; margin: 0; padding-left: 20px;} .node>.label {cursor: pointer; user-select: none; padding: 2px 4px; display: inline-block;} .selected>.label {background: #c2dbff;} .node>.label::before {content: "▶"; display: inline-block; width: 1em; color: #555;} .node.open>.label::before {content: "▼";} .node.leaf>.label::before {content: "•"; color: #999;} .node.result>.label::before {content: "★"; color: #4CAF50;} .node.result>.label {color: #2E7D32; font-weight: bold;} .node ul {display: none;} .node.open>ul {display: block;} .type-indicator { font-size: 0.8em; color: #666; margin-left: 5px; } .type-indicator.result { color: #4CAF50; font-weight: bold; } </style> </head> <body> <h2>Конструктор алгоритма определения косметического средства</h2> <div id="controls"> <input type="text" id="nodeText" placeholder="Текст узла"> <select id="nodeType" style="padding: 4px; margin-left: 5px;"> <option value="condition">Условие</option> <option value="result">Результат (косметическое средство)</option> </select> <button id="addRoot">Добавить корневой узел</button> <button id="addChild" disabled>Добавить дочерний узел</button> <button id="deleteNode" disabled>Удалить узел</button> <button id="toggleType" disabled>Изменить тип узла</button> <button id="saveTree">Сохранить JSON</button> <input type="file" id="loadFile" accept=".json" style="margin-left: 10px;"> </div> <div id="treeContainer"></div> <script> let treeData = []; let selectedNodeId = null; let idCounter = 0; function renderTree() { const container = document.getElementById('treeContainer'); container.innerHTML = ''; treeData.forEach(node => container.appendChild(createNodeElement(node))); } function createNodeElement(node) { const li = document.createElement('li'); li.className = 'node'; if (node.type === 'result') { li.className += ' result leaf'; } else if (node.children.length === 0) { li.className += ' leaf'; } li.dataset.id = node.id; const label = document.createElement('span'); label.className = 'label'; label.textContent = node.text; // Добавляем индикатор типа const typeIndicator = document.createElement('span'); typeIndicator.className = 'type-indicator'; if (node.type === 'result') { typeIndicator.className += ' result'; typeIndicator.textContent = '[РЕЗУЛЬТАТ]'; } label.appendChild(typeIndicator); li.appendChild(label); label.onclick = e => { e.stopPropagation(); // Выделение узла document.querySelectorAll('.selected').forEach(el => el.classList.remove('selected')); li.classList.add('selected'); selectedNodeId = node.id; // Управление кнопками document.getElementById('addChild').disabled = node.type === 'result'; document.getElementById('deleteNode').disabled = false; document.getElementById('toggleType').disabled = node.children.length > 0; // Разворачивание/сворачивание if (node.children.length && node.type !== 'result') { li.classList.toggle('open'); } }; label.ondblclick = e => { e.stopPropagation(); const newText = prompt('Изменить текст узла:', node.text); if (newText && newText.trim()) { node.text = newText.trim(); renderTree(); } }; if (node.children.length && node.type !== 'result') { const ul = document.createElement('ul'); node.children.forEach(child => ul.appendChild(createNodeElement(child))); li.appendChild(ul); li.classList.add('open'); } return li; } function findNode(arr, id) { for (const node of arr) { if (node.id === id) return node; const found = findNode(node.children, id); if (found) return found; } return null; } function deleteNode(arr, id) { for (let i = 0; i < arr.length; i++) { if (arr[i].id === id) { arr.splice(i, 1); return true; } if (deleteNode(arr[i].children, id)) return true; } return false; } document.getElementById('addRoot').onclick = () => { const text = document.getElementById('nodeText').value.trim(); const type = document.getElementById('nodeType').value; if (!text) return alert('Введите текст узла'); treeData.push({ id: ++idCounter, text: text, type: type, children: [] }); document.getElementById('nodeText').value = ''; renderTree(); }; document.getElementById('addChild').onclick = () => { const text = document.getElementById('nodeText').value.trim(); const type = document.getElementById('nodeType').value; if (!text) return alert('Введите текст узла'); if (!selectedNodeId) return; const parent = findNode(treeData, selectedNodeId); if (parent && parent.type !== 'result') { parent.children.push({ id: ++idCounter, text: text, type: type, children: [] }); document.getElementById('nodeText').value = ''; renderTree(); } }; document.getElementById('toggleType').onclick = () => { if (!selectedNodeId) return; const node = findNode(treeData, selectedNodeId); if (node && node.children.length === 0) { node.type = node.type === 'result' ? 'condition' : 'result'; renderTree(); // Обновляем состояние кнопок document.getElementById('addChild').disabled = node.type === 'result'; } }; document.getElementById('deleteNode').onclick = () => { if (!selectedNodeId) return; if (!confirm('Удалить выбранный узел и все его подветки?')) return; deleteNode(treeData, selectedNodeId); selectedNodeId = null; document.getElementById('addChild').disabled = true; document.getElementById('deleteNode').disabled = true; document.getElementById('toggleType').disabled = true; renderTree(); }; document.getElementById('saveTree').onclick = () => { const blob = new Blob([JSON.stringify(treeData, null, 2)], {type: 'application/json'}); const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = 'cosmetic_algorithm.json'; a.click(); }; document.getElementById('loadFile').onchange = e => { const file = e.target.files[0]; if (!file) return; const reader = new FileReader(); reader.onload = event => { try { treeData = JSON.parse(event.target.result); idCounter = Math.max(...getAllIds(treeData), 0); selectedNodeId = null; document.getElementById('addChild').disabled = true; document.getElementById('deleteNode').disabled = true; document.getElementById('toggleType').disabled = true; renderTree(); } catch (err) { alert('Ошибка чтения файла'); } }; reader.readAsText(file); }; function getAllIds(arr) { let ids = []; for (const node of arr) { ids.push(node.id); ids = ids.concat(getAllIds(node.children)); } return ids; } // Пример начального дерева с результатами treeData = [ { id: ++idCounter, text: "Тип кожи", type: "condition", children: [ { id: ++idCounter, text: "Жирная кожа", type: "condition", children: [ { id: ++idCounter, text: "С акне", type: "condition", children: [ { id: ++idCounter, text: "Салициловая кислота 2% + Ниацинамид", type: "result", children: [] } ] }, { id: ++idCounter, text: "Без акне", type: "condition", children: [ { id: ++idCounter, text: "Матирующий гель с цинком", type: "result", children: [] } ] } ] }, { id: ++idCounter, text: "Сухая кожа", type: "condition", children: [ { id: ++idCounter, text: "Питательный крем с церамидами", type: "result", children: [] } ] } ] } ]; renderTree(); </script> </body> </html>Основные изменения:
-
Добавлен тип узла - теперь каждый узел может быть либо "условием" (condition), либо "результатом" (result)
-
Выпадающий список для выбора типа - при создании нового узла можно выбрать его тип
-
Визуальное отличие результатов:
- Результаты отмечены звездочкой (★) вместо точки
- Текст результатов выделен зеленым цветом и жирным шрифтом
- Добавлен индикатор [РЕЗУЛЬТАТ]
-
Ограничения для результатов:
- К узлам-результатам нельзя добавить дочерние элементы
- Результаты всегда являются конечными точками
-
Кнопка "Изменить тип узла" - позволяет переключать тип узла между условием и результатом (только для узлов без детей)
-
Пример дерева - добавлен реалистичный пример алгоритма определения косметического средства с конечными результатами
Теперь вы можете строить полноценные алгоритмы, где каждая ветвь заканчивается конкретным косметическим средством как результатом прохождения по дереву решений.
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.