Форум программистов, компьютерный форум, киберфорум
JavaScript
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
0 / 0 / 0
Регистрация: 20.02.2020
Сообщений: 113

Функция с диапазоном

27.02.2024, 20:29. Показов 357. Ответов 0
Метки js (Все метки)

Студворк — интернет-сервис помощи студентам
Добрый день. Помогите, пожалуйста, сделать функцию чтобы когда задается матица, то чтобы была надпись на кнопках: задаю вручную, рандомные числа
если выбирается вариант рандомные числа, то чтобы потом пользователь мог выбрать диапазон
то есть, от 3 до 10, в итоге в матице будут числа только с диапазона от 3 до 10 включительно.
У меня функция просто рандомной генерации чисел.
И помогите, добавить функцию определение того, является ли граф непрерывным или нет.
И чтобы каждый последующий шаг окрашивания ребер графа, чтобы сопровождался нажатием кнопки, например Enter.
HTML5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
<!DOCTYPE html>
<html>
<head>
    <title>Vizualizácia algoritmu</title>
        <style>
        /* Убрать внешние границы таблицы */
        #adjacencyMatrixTable {
          border-collapse: collapse; /* Слияние границ ячеек */
          border: none; /* Удалить внешние границы таблицы */
        }
 
        /* Границы для всех заголовков */
        #adjacencyMatrixTable th {
          border: 1px solid #000;
          padding: 5px; /* Внутренний отступ для содержимого ячеек */
        }
 
        /* Границы для всех ячеек */
        #adjacencyMatrixTable td {
          border: 1px solid #000;
          padding: 5px; /* Внутренний отступ для содержимого ячеек */
        }
 
        /* Границы для первой строки (шапки таблицы) */
        #adjacencyMatrixTable tr:first-child th {
          background-color: #ccc; /* Цвет фона для шапки таблицы */
        }
 
        /* Границы для первого столбца */
        #adjacencyMatrixTable td:first-of-type {
          background-color: #ccc; /* Цвет фона для первого столбца */
          font-weight: bold;
        }
    </style>
</head>
<body>
    <h2>Počet vrcholov:</h2>
    <br>
    <label for="numVertices">Num Verticles:</label>
    <input type="number" id="numVertices" min="2" value="5">
 
    <br>
    <!-- Додайте ці елементи у ваш HTML-код -->
    <label for="minWeight">Min Weight:</label>
    <input type="number" id="minWeight" value="1">
    
    <br>
    <label for="maxWeight">Max Weight:</label>
    <input type="number" id="maxWeight" value="10">
 
    <br>
 
    <br>
   <label for="inputChoice">Choose Input Type:</label>
   <select id="inputChoice">
   <option value="manual">Manual Input</option>
   <option value="random">Random Numbers</option>
   </select>
 
  <div id="randomInputFields" style="display: none;">
  <label for="minWeight">Min Weight:</label>
  <input type="number" id="minWeight" value="1">
  
  <br>
  <label for="maxWeight">Max Weight:</label>
  <input type="number" id="maxWeight" value="10">
  </div>
    <button onclick="generateMatrix()">Vytvorte maticu</button>
    
    <h2>Matica susedstva:</h2>
    <textarea id="adjacencyMatrix" rows="10" cols="30" hidden></textarea>
    <div>
        <table id="adjacencyMatrixTable">
            <thead>
                <tr>
                    <th></th> <!-- Пустая ячейка в верхнем левом углу -->
                    <!-- Додайте заголовки для вершин тут -->
                </tr>
            </thead>
            <tbody id="matrixTable">
                <!-- Заповніть таблицю змістом матриці тут -->
            </tbody>
        </table>
    </div>
 
    <hr/>
 
    <h2>Vyberte algoritmus:</h2>
    
    <select id="algorithm" onchange="changeAlgorithm()">
        <option value="kruskal">Kruskal</option>
    </select>
 
    <hr/>
 
    <br>
 
    <div id="selectNodes">
        <h2>Вvyberte počiatočné a koncové vrcholy:</h2>
        <label for="startNode">Počiatočný vrchol:</label>
        <select id="startNode"></select>
        <label for="endNode">Konečný vrchol:</label>
        <select id="endNode"></select>
        <hr/>    
    </div>
    
    <br>
    <button onclick="visualizeAlgorithm()">Vizualízujte algoritmus</button>
    <br>
    
    <div style="margin: auto; text-align: center; vertical-align: middle;">
        <canvas id="canvas" width="600" height="600"></canvas>    
    </div>
    
    
    <div id="resultAlg">
            <hr/>
            <h2 id="routeLengthH">Dĺžka trasy:</h2>
            <p id="routeLength">-</p>
 
            <h2 id="visitedVerticesH">Zoznam vylezených vrcholov:</h2>
            <p id="visitedVertices">-</p>        
            <hr/>
    </div>
 
    <script src="visualization.js"></script>
</body>
</html>
JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
const startNodeSelect = document.getElementById("startNode");
const endNodeSelect = document.getElementById("endNode");
const numVerticesInput = document.getElementById("numVertices");
const adjacencyMatrixTextArea = document.getElementById("adjacencyMatrix");
 
let graph = [];
let vertexPositions = [];
let numVertices = 0;
 
let route = []; // Объявляем переменную route
let algorithmType ="prim";
 
 
 
function changeAlgorithm() {
    console.log("changeAlgorithm");
    var select = document.getElementById('algorithm');
    document.getElementById('resultAlg').style.display = "none";
    visualizeGraph();
    // Отримуємо вибране значення в select
    algorithmType = select.value;
 
    if(algorithmType === "prim")
      document.getElementById("selectNodes").style.display = "block";
    else
      document.getElementById("selectNodes").style.display = "none";
}
 
function isGraphContinuous(graph) {
  for (let i = 0; i < graph.length; i++) {
    for (let j = 0; j < graph[i].length; j++) {
      if (i !== j && graph[i][j] <= 0) {
        // Если вес ребра между вершинами i и j не положителен, граф не является непрерывным
        return false;
      }
    }
  }
  return true;
}
 
function generateMatrix() {
  document.getElementById('resultAlg').style.display = "none";
  
  const choice = prompt("Vyberte spôsob vyplnenia matice:\n1. Doplňte náhodnými číslami\n2. Vyplňte ručne");
 
  if (choice === "1") {
    // Случайная генерация
    generateRandomMatrix();
  } else if (choice === "2") {
    // Ручной ввод
    numVertices = parseInt(numVerticesInput.value);
    if (numVertices < 2) {
      alert("Number of vertices must be at least 2.");
      return;
    }
 
    graph = [];
    graph2 = [];
 
    const continuous = isGraphContinuous(graph);
 
    if (continuous) {
      console.log("Граф является непрерывным.");
    } else {
      console.log("Граф не является непрерывным.");
    }
    
    // Определяем тип ввода: manual или random
    const inputChoice = document.getElementById("inputChoice").value;
 
    for (let i = 0; i < numVertices; i++) {
      const row = [];
      for (let j = 0; j < numVertices; j++) {
        if (i < j) {
          let weight;
 
          if (inputChoice === "manual") {
            // Если выбран ввод вручную, запрашиваем у пользователя вес
            do {
              weight = prompt(`Zadajte váhu pre hranu medzi vrcholom ${i} a vrcholom ${j}:`);
              if (weight === null) {
                // Пользователь нажал Cancel
                return;
              }
              weight = parseInt(weight);
              if (isNaN(weight) || weight < 0) {
                alert("Neplatný vstup. Prosím vložte platné nezáporné číslo.");
              }
            } while (isNaN(weight) || weight < 0);
          } else if (inputChoice === "random") {
            // Если выбран ввод случайных чисел, генерируем случайный вес в указанном диапазоне
            const minWeight = parseInt(document.getElementById("minWeight").value);
            const maxWeight = parseInt(document.getElementById("maxWeight").value);
            weight = Math.floor(Math.random() * (maxWeight - minWeight + 1)) + minWeight;
          }
 
          row.push(weight);
        } else {
          row.push(graph[j][i]);
        }
      }
      graph2.push(row);
    }
 
  graph = graph2;
  }
 
// Проходим по верхнему треугольнику матрицы (без диагонали)
  for (let i = 0; i < numVertices; i++) {
    for (let j = i + 1; j < numVertices; j++) {
      // Заполняем элементы симметрично относительно главной диагонали
      graph[j][i] = graph[i][j];
    }
  }
 
 
  updateMatrixTextArea(graph);
  updateMatrixTable(graph);
  updateTableHeaders(numVertices);
  updateNodeSelectOptions(numVertices);
  visualizeGraph();
}
 
 
 
 
 
 
function generateRandomMatrix() {
  numVertices = parseInt(numVerticesInput.value);
  if (numVertices < 2) {
    alert("Počet vrcholov musí byť aspoň 2.");
    return;
  }
 
   const minWeight = parseInt(document.getElementById("minWeight").value);
  const maxWeight = parseInt(document.getElementById("maxWeight").value);
 
  if (isNaN(minWeight) || isNaN(maxWeight) || minWeight < 0 || maxWeight < minWeight) {
    alert("Neplatný vstup pre váhy. Zadajte nezáporné čísla a uistite sa, že maxWeight je väčšia alebo rovná minWeight.");
    return;
  }
 
  graph = generateRandomAdjacencyMatrix(numVertices, minWeight, maxWeight);
  updateMatrixTextArea(graph);
  updateMatrixTable(graph);
  updateTableHeaders(numVertices);
  updateNodeSelectOptions(numVertices);
  visualizeGraph();
}
 
function updateMatrixTextArea(matrix) {
  const matrixText = matrix.map(row => row.join(" ")).join("\n");
  adjacencyMatrixTextArea.value = matrixText;
}
 
function updateNodeSelectOptions(numVertices) {
  startNodeSelect.innerHTML = "";
  endNodeSelect.innerHTML = "";
  for (let i = 0; i < numVertices; i++) {
    const option = document.createElement("option");
    option.value = i;
    option.text = i.toString();
    startNodeSelect.appendChild(option);
    endNodeSelect.appendChild(option.cloneNode(true));
  }
  startNodeSelect.selectedIndex = 0;
  endNodeSelect.selectedIndex = 1;
}
 
function parseAdjacencyMatrix(matrixText) {
  const lines = matrixText.trim().split('\n');
  const matrix = [];
  for (let line of lines) {
    const row = line.trim().split(' ').map(Number);
    matrix.push(row);
  }
  return matrix;
}
 
function generateRandomAdjacencyMatrix(numVertices, minWeight, maxWeight) {
  const matrix = [];
  for (let i = 0; i < numVertices; i++) {
    const row = [];
    for (let j = 0; j < numVertices; j++) {
      if (i === j) {
        row.push(0);
      } else if (j > i) {
        // Генеруємо випадкові ваги в заданому діапазоні
        row.push(Math.floor(Math.random() * (maxWeight - minWeight + 1)) + minWeight);
      } else {
        // Використовуємо значення з симетричної частини матриці
        row.push(matrix[j][i]);
      }
    }
    matrix.push(row);
  }
  return matrix;
}
 
function updateMatrixTable(matrix) {
  const matrixTable = document.getElementById("matrixTable");
  matrixTable.innerHTML = ""; // Очищаем существующее содержимое таблицы
 
  for (let i = 0; i < matrix.length; i++) {
    const row = document.createElement("tr");
    const vertexHeader = document.createElement("td");
    vertexHeader.textContent = i;
    row.appendChild(vertexHeader);
 
    for (let j = 0; j < matrix[i].length; j++) {
      const cell = document.createElement("td");
      cell.textContent = matrix[i][j];
      row.appendChild(cell);
    }
 
    matrixTable.appendChild(row);
  }
}
 
function updateTableHeaders(numVertices) {
  const table = document.querySelector("table");
  const thead = table.querySelector("thead tr");
  thead.innerHTML = ""; // Очищаем существующие заголовки
 
  const emptyTh = document.createElement("th");
  thead.appendChild(emptyTh); // Пустая ячейка в верхнем левом углу
 
  for (let i = 0; i < numVertices; i++) {
    const th = document.createElement("th");
    th.textContent = i;
    thead.appendChild(th);
  }
}
 
function drawGraph() {
  const numVertices = graph.length;
  const vertexRadius = 20;
  const circleRadius = vertexRadius * numVertices * 1.5;
  const textOffset = 15;
 
  canvas.width = circleRadius * 2 + 50;
  canvas.height = circleRadius * 2 + 50;
  const centerX = canvas.width / 2;
  const centerY = canvas.height / 2;
 
  vertexPositions = [];
  for (let i = 0; i < numVertices; i++) {
    const angle = (i / numVertices) * 2 * Math.PI;
    const x = centerX + circleRadius * Math.cos(angle);
    const y = centerY + circleRadius * Math.sin(angle);
 
    for (let j = 0; j < i; j++) {
      while (circlesIntersect(x, y, vertexRadius, vertexPositions[j].x, vertexPositions[j].y, vertexRadius)) {
        x += textOffset;
      }
    }
 
    vertexPositions.push({ x, y });
  }
 
  ctx.clearRect(0, 0, canvas.width, canvas.height);
 
  for (let i = 0; i < numVertices; i++) {
    const x = vertexPositions[i].x;
    const y = vertexPositions[i].y;
 
    // Измените цвет вершины на светло-синий
    ctx.beginPath();
    ctx.arc(x, y, vertexRadius, 0, 2 * Math.PI);
    ctx.fillStyle = "lightblue"; // Измените цвет здесь
    ctx.fill();
    ctx.strokeStyle = "black";
    ctx.stroke();
 
    ctx.textAlign = "center";
    ctx.textBaseline = "middle";
    ctx.font = "bold 16px Arial";
    ctx.fillStyle = "black";
    ctx.fillText(i.toString(), x, y);
  }
 
  ctx.strokeStyle = "gray";
  ctx.lineWidth = 1;
  for (let i = 0; i < numVertices; i++) {
    for (let j = i + 1; j < numVertices; j++) {
      if (graph[i][j] !== 0) {
        const x1 = vertexPositions[i].x;
        const y1 = vertexPositions[i].y;
        const x2 = vertexPositions[j].x;
        const y2 = vertexPositions[j].y;
 
        const dx = x2 - x1;
        const dy = y2 - y1;
        const distance = Math.sqrt(dx * dx + dy * dy);
        const ratio = vertexRadius / distance;
 
        const newX1 = x1 + dx * ratio;
        const newY1 = y1 + dy * ratio;
        const newX2 = x2 - dx * ratio;
        const newY2 = y2 - dy * ratio;
 
        ctx.beginPath();
        ctx.moveTo(newX1, newY1);
        ctx.lineTo(newX2, newY2);
 
        ctx.strokeStyle = "lightgray";
 
        // Рассчитываем координаты для текста веса ребра
        const textX = (newX1 + newX2) / 2;
        const textY = (newY1 + newY2) / 2;
 
        // Перемещаем текст на некоторое расстояние от линии ребра
        const textOffsetX = (dx / distance) * 10;
        const textOffsetY = (dy / distance) * 10;
 
        ctx.textAlign = "center";
        ctx.textBaseline = "middle";
        const textColor = "black"; // Используем цвет ребра для текста
        ctx.font = "bold 16px Arial";
        ctx.fillStyle = textColor;
        ctx.fillText(graph[i][j].toString(), textX + textOffsetX, textY + textOffsetY);
 
        ctx.stroke();
      }
    }
  }
}
 
 
function circlesIntersect(x1, y1, r1, x2, y2, r2) {
  const dx = x2 - x1;
  const dy = y2 - y1;
  const distance = Math.sqrt(dx * dx + dy * dy);
  return distance < r1 + r2;
}
 
function visualizeGraph() {
  const matrixText = adjacencyMatrixTextArea.value;
  graph = parseAdjacencyMatrix(matrixText);
  drawGraph();
}
 
/*Algorithm start button click*/
 
function visualizeAlgorithm() {
  document.getElementById('resultAlg').style.display = "block";
  if (algorithmType === "prim") {
    visualizeRoute();
  } else if (algorithmType === "kruskal") {
    visualizeKruskal();
  }
}
 
 
/*Prima alhorithm*/
 
function visualizeRoute() {
  document.getElementById("visitedVertices").textContent = "";
  const start = parseInt(startNodeSelect.value);
  const end = parseInt(endNodeSelect.value);
 
  if (start === end) {
    return;
  }
 
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  drawGraph();
 
  const parent = prim(graph, start);
  const route = findOptimalRoute(start, end, parent);
 
  drawRouteWithAnimation(route, vertexPositions);
}
 
function prim(graph, startVertex) {
  const parent = new Array(numVertices).fill(-1);
  const key = new Array(numVertices).fill(Infinity);
  const inMST = new Array(numVertices).fill(false);
 
  key[startVertex] = 0;
 
  for (let count = 0; count < numVertices - 1; count++) {
    const u = minKey(key, inMST);
 
    inMST[u] = true;
 
    for (let v = 0; v < numVertices; v++) {
      if (graph[u][v] && !inMST[v] && graph[u][v] < key[v]) {
        parent[v] = u;
        key[v] = graph[u][v];
      }
    }
  }
 
  return parent;
}
 
function minKey(key, mstSet) {
  let min = Number.POSITIVE_INFINITY;
  let minIndex = -1;
 
  for (let v = 0; v < key.length; v++) {
    if (!mstSet[v] && key[v] < min) {
      min = key[v];
      minIndex = v;
    }
  }
 
  return minIndex;
}
 
function findOptimalRoute(start, end, parent) {
  let current = end;
  const route = [];
 
  while (current !== start) {
    route.unshift(current);
    current = parent[current];
  }
  route.unshift(start);
 
  return route;
}
 
function drawRouteWithAnimation(route, vertexPositions) {
  ctx.strokeStyle = "red";
  ctx.lineWidth = 2;
  let currentIndex = 0;
 
  function animate() {
    if (currentIndex < route.length - 1) {
      const u = route[currentIndex];
      const v = route[currentIndex + 1];
      const x1 = vertexPositions[u].x;
      const y1 = vertexPositions[u].y;
      const x2 = vertexPositions[v].x;
      const y2 = vertexPositions[v].y;
 
      // Рассчитываем координаты окружности вершины для начала и конца линии
      const dx1 = x2 - x1;
      const dy1 = y2 - y1;
      const distance1 = Math.sqrt(dx1 * dx1 + dy1 * dy1);
      const radius1 = 20; // Радиус кружков вершин
      const ratio1 = radius1 / distance1;
 
      const newX1 = x1 + dx1 * ratio1;
      const newY1 = y1 + dy1 * ratio1;
      const newX2 = x2 - dx1 * ratio1;
      const newY2 = y2 - dy1 * ratio1;
 
      ctx.beginPath();
      ctx.moveTo(newX1, newY1);
      ctx.lineTo(newX2, newY2);
      ctx.stroke();
 
      const routeLength = calculateRouteLength(route.slice(0,currentIndex+1));
      document.getElementById("routeLength").textContent = routeLength.toFixed(2);
      document.getElementById("visitedVertices").textContent = document.getElementById("visitedVertices").textContent + route[currentIndex]  + " ➝ ";
 
      currentIndex++;
 
      if (currentIndex < route.length - 1) {
        setTimeout(animate, 1000); // Настройте скорость анимации по желанию  
      }
      else
      {
        const routeLength = calculateRouteLength(route);
        document.getElementById("routeLength").textContent = routeLength.toFixed(2);
        document.getElementById("visitedVertices").textContent = document.getElementById("visitedVertices").textContent + route[currentIndex];
      }
    }
  }
 
  animate();
}
 
function calculateRouteLength(route) {
  let length = 0;
  for (let i = 0; i < route.length - 1; i++) {
    const u = route[i];
    const v = route[i + 1];
    length += graph[u][v];
  }
  return length;
}
 
 
 
/*Kruskal algorithm*/
 
function visualizeKruskal() {
  document.getElementById("visitedVertices").textContent = "";
  const matrixText = adjacencyMatrixTextArea.value;
  graph = parseAdjacencyMatrix(matrixText);
  drawGraph();
  const edges = kruskal(graph);
  drawKruskal(edges);
}
 
function kruskal(graph) {
  const numVertices = graph.length;
 
  // Створення масиву ребер для впорядкування
  const edges = [];
  for (let i = 0; i < numVertices; i++) {
    for (let j = i + 1; j < numVertices; j++) {
      if (graph[i][j] !== 0) {
        edges.push({ u: i, v: j, weight: graph[i][j] });
      }
    }
  }
 
  // Сортування ребер за зростанням ваги
  edges.sort((a, b) => a.weight - b.weight);
 
  const parent = Array(numVertices).fill(-1);
  const result = [];
 
  function find(v) {
    if (parent[v] === -1) {
      return v;
    }
    return find(parent[v]);
  }
 
  function union(x, y) {
    const xRoot = find(x);
    const yRoot = find(y);
    parent[xRoot] = yRoot;
  }
 
  for (let i = 0; i < edges.length; i++) {
    const { u, v, weight } = edges[i];
    const x = find(u);
    const y = find(v);
 
    if (x !== y) {
      result.push(edges[i]);
      union(x, y);
    }
  }
 
  return result;
}
 
function drawKruskal(edges) {
  const animationSpeed = 1000; // Швидкість анімації в мілісекундах
  let currentEdgeIndex = 0;
  const vertexRadius = 20;
  let totalRouteLength = 0;
 
  function drawNextEdge() {
    if (currentEdgeIndex < edges.length) {
      const { u, v, weight } = edges[currentEdgeIndex];
 
      const x1 = vertexPositions[u].x;
      const y1 = vertexPositions[u].y;
      const x2 = vertexPositions[v].x;
      const y2 = vertexPositions[v].y;
 
      const dx = x2 - x1;
      const dy = y2 - y1;
      const distance = Math.sqrt(dx * dx + dy * dy);
      const ratio = vertexRadius / distance;
 
      const startX = x1 + dx * ratio;
      const startY = y1 + dy * ratio;
      const endX = x2 - dx * ratio;
      const endY = y2 - dy * ratio;
 
      ctx.beginPath();
      ctx.moveTo(startX, startY);
      ctx.lineTo(endX, endY);
      ctx.strokeStyle = "green"; // Зелений колір для ребра у маршруті
      ctx.lineWidth = 2;
      ctx.stroke();
 
      totalRouteLength += weight;
      
      updateResult(u,v,totalRouteLength,currentEdgeIndex === (edges.length-1));
 
      currentEdgeIndex++;
 
      document.addEventListener("keydown", function(event) {
        if (event.key === "Enter") {
          drawNextEdge();
        }
      });
      
      // Викликаємо наступний кадр анімації
      setTimeout(drawNextEdge, animationSpeed);
    }
  }
 
  // Запускаємо анімацію
  drawNextEdge();
}
 
function updateResult(u,v, length,flag){
// Оновіть відображення довжини маршруту
    document.getElementById("routeLength").textContent = length;
    // Додайте вершини до списку
    document.getElementById("visitedVertices").textContent = document.getElementById("visitedVertices").textContent + u;
    document.getElementById("visitedVertices").textContent = document.getElementById("visitedVertices").textContent + " ➝ ";
    document.getElementById("visitedVertices").textContent = document.getElementById("visitedVertices").textContent + v ;
    if(!flag)
      document.getElementById("visitedVertices").textContent = document.getElementById("visitedVertices").textContent + "; ";
}
 
 
 
document.addEventListener("DOMContentLoaded", function() {
  changeAlgorithm();
  // Автоматично викликаємо генерацію випадкового графа та візуалізацію при завантаженні сторінки
generateRandomMatrix();
});
0
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
27.02.2024, 20:29
Ответы с готовыми решениями:

Процедура или функция, которая работает с диапазоном..
Помогите, пожалуйста! Данные берутся с листа с фиксированным набором столбцов и постоянно растущим числом строк. Нужна процедура или...

Есть ли в VBA функция, позволяющая определить пересечение одного диапазона дат с другим диапазоном дат?
Привет Все! Задача такова: имеем 1 диапазон даты, например, 01.10.10-30.10.10 имеем 2 диапазон даты, например, 15.09.10-15.10.10 ...

какая разница межлду "областю объясления", "диапазоном доступа" и "потенциальным диапазоном доступа"?
какая разница межлду &quot;областю объясления&quot;, &quot;диапазоном доступа&quot; и &quot;потенциальным диапазоном доступа&quot;?

0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
27.02.2024, 20:29
Помогаю со студенческими работами здесь

Матрица с диапазоном
помогите пожалуйста составить такую програику: &quot;Все елементы заданной матрици, которые лежат в указаном диапазоне переместить в начало...

запрос с диапазоном
надо выбрать товары в диапазоне цен от 10000 до 100.000 и рандомно четыре штуки!!! в таблице catalog за цену отвечает поле cost как это в...

Задача с диапазоном
Дано: функция h(x)=sin2*x*y+y^x/e^x значение y=3,1 диапазон 1,2&lt;=x&lt;=2,8 число повторов n=3 Надо написать программу в Pascal...

Проблема с диапазоном
Всем привет. Почему при на консоль выводится System.Int32 вместо 7 и 54, соответственно? При указании диапазона, код в квадратных...

фильтр с диапазоном
подскажите пожалуйста!!!как создать фильтр с диапазоном!!!!!!!!!то есть вводятся 2 числа(например год),и в таблице должны остатся нужные


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
1
Ответ Создать тему
Новые блоги и статьи
Воспроизведение звукового файла с помощью SDL3_mixer при касании экрана Android
8Observer8 26.01.2026
Содержание блога SDL3_mixer - это библиотека я для воспроизведения аудио. В отличие от инструкции по добавлению текста код по проигрыванию звука уже содержится в шаблоне примера. Нужно только. . .
Установка Android SDK, NDK, JDK, CMake и т.д.
8Observer8 25.01.2026
Содержание блога Перейдите по ссылке: https:/ / developer. android. com/ studio и в самом низу страницы кликните по архиву "commandlinetools-win-xxxxxx_latest. zip" Извлеките архив и вы увидите. . .
Вывод текста со шрифтом TTF на Android с помощью библиотеки SDL3_ttf
8Observer8 25.01.2026
Содержание блога Если у вас не установлены Android SDK, NDK, JDK, и т. д. то сделайте это по следующей инструкции: Установка Android SDK, NDK, JDK, CMake и т. д. Сборка примера Скачайте. . .
Использование SDL3-callbacks вместо функции main() на Android, Desktop и WebAssembly
8Observer8 24.01.2026
Содержание блога Если вы откроете примеры для начинающих на официальном репозитории SDL3 в папке: examples, то вы увидите, что все примеры используют следующие четыре обязательные функции, а. . .
моя боль
iceja 24.01.2026
Выложила интерполяцию кубическими сплайнами www. iceja. net REST сервисы временно не работают, только через Web. Написала за 56 рабочих часов этот сайт с нуля. При помощи perplexity. ai PRO , при. . .
Модель сукцессии микоризы
anaschu 24.01.2026
Решили писать научную статью с неким РОманом
http://iceja.net/ математические сервисы
iceja 20.01.2026
Обновила свой сайт http:/ / iceja. net/ , приделала Fast Fourier Transform экстраполяцию сигналов. Однако предсказывает далеко не каждый сигнал (см ограничения http:/ / iceja. net/ fourier/ docs ). Также. . .
http://iceja.net/ сервер решения полиномов
iceja 18.01.2026
Выкатила http:/ / iceja. net/ сервер решения полиномов (находит действительные корни полиномов методом Штурма). На сайте документация по API, но скажу прямо VPS слабенький и 200 000 полиномов. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru