-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlogic3.html
More file actions
811 lines (708 loc) · 33.1 KB
/
logic3.html
File metadata and controls
811 lines (708 loc) · 33.1 KB
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
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
<!DOCTYPE html>
<html lang="uk">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Симулятор Булевої Алгебри та Карт Карно</title>
<script>
window.MathJax = {
tex: {
inlineMath: [['$', '$'], ['\\(', '\\)']],
macros: {
// ВИПРАВЛЕНО: Видалено рекурсивний виклик vee
neg: ["\\overline{#1}", 1]
}
},
svg: { fontCache: 'global' }
};
</script>
<script type="text/javascript" id="MathJax-script" async
src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js">
</script>
<style>
:root {
--bg-color: #f4f7f6;
--card-bg: #ffffff;
--primary: #3498db;
--accent: #2c3e50;
--text: #333;
/* Palette for Groups - яскраві кольори для рамок */
--c-grp-0: #e74c3c; /* Red */
--c-grp-1: #3498db; /* Blue */
--c-grp-2: #2ecc71; /* Green */
--c-grp-3: #9b59b6; /* Purple */
--c-grp-4: #f39c12; /* Orange */
--c-grp-5: #1abc9c; /* Teal */
}
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background-color: var(--bg-color);
color: var(--text);
line-height: 1.6;
margin: 0;
padding: 20px;
}
.container { max-width: 1100px; margin: 0 auto; }
header { text-align: center; margin-bottom: 30px; }
h1 { color: var(--accent); margin-bottom: 5px; }
p.subtitle { color: #666; margin-top: 0; }
/* Tabs */
.tabs { display: flex; justify-content: center; margin-bottom: 20px; gap: 10px; }
.tab-btn {
padding: 12px 24px;
background: #ddd;
border: none;
border-radius: 25px;
cursor: pointer;
font-size: 1.1em;
font-weight: bold;
color: #555;
transition: all 0.3s;
}
.tab-btn.active {
background: var(--primary);
color: white;
box-shadow: 0 4px 10px rgba(52, 152, 219, 0.3);
}
.tab-content { display: none; animation: fadeIn 0.4s; }
.tab-content.active { display: block; }
@keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
/* Cards */
.logic-card {
background: var(--card-bg);
border-radius: 12px;
box-shadow: 0 4px 15px rgba(0,0,0,0.05);
margin-bottom: 30px;
padding: 25px;
border-left: 5px solid var(--accent);
}
.card-title { font-size: 1.4em; font-weight: bold; color: var(--accent); display: block; margin-bottom: 15px; border-bottom: 1px solid #eee; padding-bottom: 10px;}
/* Tables */
table { width: 100%; border-collapse: collapse; margin: 15px 0; background: white; }
th, td { border: 1px solid #ddd; padding: 10px; text-align: center; }
th { background-color: var(--accent); color: white; }
tr:nth-child(even) { background-color: #f9f9f9; }
/* Examples Box Style */
.example-box {
background: #fff;
border: 2px dashed var(--primary);
padding: 20px;
border-radius: 8px;
margin-top: 20px;
background-color: #fbfdff;
}
.example-box h4 { margin-top: 0; color: var(--primary); }
.example-step { margin-bottom: 8px; padding-left: 10px; border-left: 3px solid #ddd; }
/* K-Map Styles */
.controls-area {
display: flex;
flex-wrap: wrap;
gap: 15px;
justify-content: center;
background: #ecf0f1;
padding: 15px;
border-radius: 8px;
margin-bottom: 20px;
align-items: center;
}
.radio-group { display: flex; gap: 10px; align-items: center; background: white; padding: 5px 15px; border-radius: 20px; border: 1px solid #ddd; }
.radio-group label { cursor: pointer; font-weight: 600; font-size: 0.9em; }
.radio-group input { margin-right: 5px; }
.btn {
padding: 8px 20px;
border: none;
border-radius: 6px;
cursor: pointer;
font-weight: bold;
color: white;
background: var(--primary);
transition: background 0.2s;
}
.btn:hover { background: #2980b9; }
.btn-reset { background: #e74c3c; }
/* Grid Wrapper */
.kmap-container {
display: flex;
justify-content: center;
margin: 20px 0;
overflow-x: auto;
}
.kmap-grid {
display: grid;
gap: 4px;
position: relative;
user-select: none;
padding: 40px; /* Space for headers */
}
/* Grid Sizes */
.grid-3 { grid-template-columns: repeat(4, 70px); grid-template-rows: repeat(2, 70px); }
.grid-4 { grid-template-columns: repeat(4, 70px); grid-template-rows: repeat(4, 70px); }
.cell {
width: 70px;
height: 70px;
background: white;
border: 2px solid #bdc3c7;
border-radius: 8px;
display: flex;
align-items: center;
justify-content: center;
font-size: 1.6em;
font-weight: bold;
cursor: pointer;
position: relative;
z-index: 2;
}
.cell:hover { border-color: var(--primary); transform: scale(1.05); }
.cell.val-1 { color: var(--accent); }
.cell.val-0 { color: #bdc3c7; }
.header-label {
position: absolute;
font-weight: bold;
font-size: 0.9em;
color: var(--accent);
display: flex;
align-items: center;
justify-content: center;
}
/* ВИПРАВЛЕНО: Стилі оверлею */
.group-overlay {
position: absolute;
border-style: solid;
border-radius: 12px;
z-index: 5; /* Поверх клітинок, але події пропускаються */
pointer-events: none; /* Кліки проходять крізь рамку до клітинок */
background: transparent; /* Прибрано заливку */
box-shadow: 0 0 4px rgba(0,0,0,0.2);
transition: all 0.3s;
}
.result-box {
background: var(--accent);
color: white;
padding: 20px;
border-radius: 8px;
text-align: center;
font-size: 1.3em;
margin-top: 20px;
}
/* Legend for colors */
.group-legend {
display: flex;
gap: 10px;
justify-content: center;
margin-top: 10px;
flex-wrap: wrap;
}
.legend-item {
font-size: 0.8em;
padding: 2px 8px;
border-radius: 4px;
border: 2px solid;
background: white;
}
</style>
</head>
<body>
<div class="container">
<header>
<p class="subtitle">Мінімізація логічних функцій</p>
</header>
<div class="tabs">
<button class="tab-btn active" onclick="switchTab('laws')">📜 Закони логіки</button>
<button class="tab-btn" onclick="switchTab('kmap')">🧩 Карти Карно</button>
</div>
<div id="tab-laws" class="tab-content active">
<div class="logic-card">
<span class="card-title">Основні аксіоми та закони</span>
<p>
<strong>Позначення:</strong><br>
$\overline{A}$ — Заперечення (NOT)<br>
$\vee$ — Диз'юнкція (OR)<br>
$\cdot$ — Кон'юнкція (AND)
</p>
<p><em>Перейдіть на вкладку "Карти Карно" для симулятора.</em></p>
</div>
<details open>
<summary>Таблиця основних законів (Натисніть)</summary>
<table>
<thead>
<tr>
<th>Назва закону</th>
<th>Формула</th>
<th>Коментар</th>
</tr>
</thead>
<tbody>
<tr>
<td>Закони 0 і 1</td>
<td>$A \vee 0 = A$, $A \vee 1 = 1$<br>$A \cdot 1 = A$, $A \cdot 0 = 0$</td>
<td>Властивості констант</td>
</tr>
<tr>
<td>Ідемпотентність</td>
<td>$A \vee A = A$<br>$A \cdot A = A$</td>
<td>Повторення не змінює значення</td>
</tr>
<tr>
<td>Подвійне заперечення</td>
<td>$\overline{\overline{A}} = A$</td>
<td>Заперечення скасовує саме себе</td>
</tr>
<tr>
<td>Комутативний</td>
<td>$A \cdot B = B \cdot A$<br>$A \vee B = B \vee A$</td>
<td>Перестановка місць</td>
</tr>
<tr>
<td>Асоціативний</td>
<td>$(A \cdot B) \cdot C = A \cdot (B \cdot C)$<br>$(A \vee B) \vee C = A \vee (B \vee C)$</td>
<td>Групування дужками</td>
</tr>
<tr>
<td>Дистрибутивний</td>
<td>$A \cdot (B \vee C) = A \cdot B \vee A \cdot C$<br>$A \vee (B \cdot C) = (A \vee B) \cdot (A \vee C)$</td>
<td>Розкриття дужок</td>
</tr>
<tr>
<td>Де Моргана</td>
<td>$\overline{A \cdot B} = \overline{A} \vee \overline{B}$<br>$\overline{A \vee B} = \overline{A} \cdot \overline{B}$</td>
<td>"Розрізав риску — змінив знак"</td>
</tr>
<tr>
<td>Поглинання</td>
<td>$A \vee A \cdot B = A$<br>$A \cdot (A \vee B) = A$</td>
<td>Менший терм "поглинає" більший</td>
</tr>
<tr>
<td>Склеювання</td>
<td>$A \cdot B \vee A \cdot \overline{B} = A$<br>$(A \vee B) \cdot (A \vee \overline{B}) = A$</td>
<td>Основа методу Карт Карно</td>
</tr>
</tbody>
</table>
</details>
<div style="margin-top: 30px;">
<h3>💡 Приклади мінімізації</h3>
<p>Натисніть кнопку, щоб згенерувати випадковий приклад розв'язання.</p>
<button class="btn" onclick="showRandomExample()">🎲 Показати приклад</button>
<div id="example-container" class="example-box" style="display: none;">
</div>
</div>
</div>
<div id="tab-kmap" class="tab-content">
<div class="logic-card">
<details>
<summary>📘 Теорія Карт Карно (ДНФ vs КНФ)</summary>
<div class="dnf-cnf-info" style="margin-top: 10px;">
<p><strong>ДНФ (Диз'юнктивна Нормальна Форма):</strong></p>
<ul>
<li>Групуємо <strong>Одиниці (1)</strong>.</li>
<li>Записуємо <strong>суму добутків</strong> (OR для AND-термів).</li>
<li>Якщо змінна $A=1 \to A$, якщо $A=0 \to \overline{A}$.</li>
</ul>
<hr style="border-color: #ffeeba;">
<p><strong>КНФ (Кон'юнктивна Нормальна Форма):</strong></p>
<ul>
<li>Групуємо <strong>Нулі (0)</strong>.</li>
<li>Записуємо <strong>добуток сум</strong> (AND для OR-термів).</li>
<li>Логіка інверсна: Якщо змінна $A=1 \to \overline{A}$, якщо $A=0 \to A$.</li>
</ul>
</div>
</details>
</div>
<div class="logic-card" style="border-left-color: var(--primary);">
<span class="card-title">Інтерактивна Карта</span>
<div class="controls-area">
<div class="radio-group">
<span>Змінні:</span>
<label><input type="radio" name="vars" value="3" checked onchange="initKMap()"> 3 змінні</label>
<label><input type="radio" name="vars" value="4" onchange="initKMap()"> 4 змінні</label>
</div>
<div class="radio-group">
<span>Режим:</span>
<label><input type="radio" name="mode" value="dnf" checked onchange="solveKMap()"> ДНФ (1)</label>
<label><input type="radio" name="mode" value="cnf" onchange="solveKMap()"> КНФ (0)</label>
</div>
<button class="btn" onclick="randomizeKMap()">🎲 Випадково</button>
<button class="btn btn-reset" onclick="resetKMap()">🗑️ Очистити</button>
</div>
<div id="mode-hint" style="text-align: center; color: #666; margin-bottom: 10px; font-style: italic;">
Групуємо одиниці для ДНФ
</div>
<div class="kmap-container">
<div id="kmap-grid-wrapper" style="position: relative;">
<div id="headers-container"></div>
<div id="grid" class="kmap-grid grid-3"></div>
</div>
</div>
<div id="group-legend" class="group-legend"></div>
<div class="result-box">
<span>Результат:</span>
<div id="formula-display" style="font-size: 1.5em; font-weight: bold; margin-top: 10px;">$F = 0$</div>
</div>
</div>
</div>
</div>
<script>
function switchTab(tab) {
document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active'));
document.querySelectorAll('.tab-btn').forEach(el => el.classList.remove('active'));
document.getElementById('tab-' + tab).classList.add('active');
event.target.classList.add('active');
}
// --- БАЗА ПРИКЛАДІВ (НОВЕ) ---
const logicExamples = [
{
title: "Закон склеювання",
task: "$F = A \\cdot B \\vee A \\cdot \\overline{B}$",
steps: [
"Помічаємо спільний множник $A$.",
"Виносимо $A$ за дужки (дистрибутивний закон): $$A \\cdot (B \\vee \\overline{B})$$",
"Застосовуємо закон виключеного третього ($B \\vee \\overline{B} = 1$): $$A \\cdot 1$$",
"Враховуємо властивість одиниці ($X \\cdot 1 = X$)."
],
result: "$A$"
},
{
title: "Закон поглинання",
task: "$F = A \\vee A \\cdot B$",
steps: [
"Виносимо $A$ за дужки (уявляємо $A$ як $A \\cdot 1$): $$A \\cdot (1 \\vee B)$$",
"За властивістю одиниці ($1 \\vee X = 1$): $$A \\cdot 1$$",
"Отримуємо результат."
],
result: "$A$"
},
{
title: "Правило де Моргана",
task: "Спростити заперечення: $\\overline{A \\cdot B \\vee C}$",
steps: [
"Застосовуємо правило де Моргана до диз'юнкції (розриваємо верхню риску, $\\vee$ міняємо на $\\cdot$): $$\\overline{A \\cdot B} \\cdot \\overline{C}$$",
"Застосовуємо де Моргана до першої частини ($\\overline{A \\cdot B}$): $$(\\overline{A} \\vee \\overline{B}) \\cdot \\overline{C}$$",
"Розкриваємо дужки:"
],
result: "$\\overline{A}\\overline{C} \\vee \\overline{B}\\overline{C}$"
},
{
title: "Спрощення виразу",
task: "$F = (A \\vee B) \\cdot (A \\vee C)$",
steps: [
"Розкриваємо дужки: $$A\\cdot A \\vee A\\cdot C \\vee B\\cdot A \\vee B\\cdot C$$",
"Спрощуємо $A\\cdot A = A$: $$A \\vee A\\cdot C \\vee A\\cdot B \\vee B\\cdot C$$",
"Виносимо $A$ з перших трьох доданків: $$A \\cdot (1 \\vee C \\vee B) \\vee B\\cdot C$$",
"Дужка $(1 \\vee ...)$ дорівнює 1."
],
result: "$A \\vee B \\cdot C$"
},
{
title: "Подвійне склеювання",
task: "$F = A B \\vee \\overline{A} B \\vee A \\overline{B}$",
steps: [
"Згрупуємо перший і другий терми ($AB \\vee \\overline{A}B$): виносимо $B$, в дужках $1$, лишається $B$.",
"Але третій терм $A\\overline{B}$ залишився без пари. Використаємо трюк: $A \\vee A = A$. Продублюємо перший терм $AB$: $$A B \\vee \\overline{A} B \\vee A B \\vee A \\overline{B}$$",
"Групуємо 1-й з 2-м: $B(A \\vee \\overline{A}) = B$",
"Групуємо 3-й з 4-м: $A(B \\vee \\overline{B}) = A$"
],
result: "$A \\vee B$"
}
];
function showRandomExample() {
const container = document.getElementById('example-container');
const randomIndex = Math.floor(Math.random() * logicExamples.length);
const example = logicExamples[randomIndex];
let html = `<h4>${example.title}</h4>`;
html += `<p><strong>Завдання:</strong> ${example.task}</p>`;
html += `<div><strong>Розв'язання:</strong></div>`;
example.steps.forEach(step => {
html += `<div class="example-step">${step}</div>`;
});
html += `<div style="margin-top:10px; padding-top:10px; border-top:1px solid #eee;"><strong>Відповідь:</strong> ${example.result}</div>`;
container.innerHTML = html;
container.style.display = 'block';
// Re-render MathJax for the new content
MathJax.typesetPromise([container]);
}
// --- K-MAP ENGINE ---
let numVars = 3;
let gridState = [];
let grayCodes3 = [0, 1, 3, 2]; // 00, 01, 11, 10
let grayCodes4 = [0, 1, 3, 2];
function initKMap() {
const r = document.querySelector('input[name="vars"]:checked');
numVars = parseInt(r.value);
const size = numVars === 3 ? 8 : 16;
gridState = new Array(size).fill(0);
renderGridStructure();
resetKMap();
}
function renderGridStructure() {
const grid = document.getElementById('grid');
const headers = document.getElementById('headers-container');
grid.innerHTML = '';
headers.innerHTML = '';
grid.className = numVars === 3 ? 'kmap-grid grid-3' : 'kmap-grid grid-4';
const colLabels = ['00', '01', '11', '10'];
const rowLabels = numVars === 3 ? ['0', '1'] : ['00', '01', '11', '10'];
// Corner Label
const corner = document.createElement('div');
corner.className = 'header-label';
corner.style.top = '0'; corner.style.left = '0';
corner.style.width = '40px'; corner.style.height = '40px';
corner.innerHTML = numVars === 3 ? '$A \\setminus BC$' : '$AB \\setminus CD$';
headers.appendChild(corner);
// Column Headers
colLabels.forEach((lbl, i) => {
const el = document.createElement('div');
el.className = 'header-label';
el.style.top = '0';
el.style.left = (40 + i*74) + 'px';
el.style.width = '70px'; el.style.height = '40px';
el.innerText = lbl;
headers.appendChild(el);
});
// Row Headers
rowLabels.forEach((lbl, i) => {
const el = document.createElement('div');
el.className = 'header-label';
el.style.left = '0';
el.style.top = (40 + i*74) + 'px';
el.style.width = '40px'; el.style.height = '70px';
el.innerText = lbl;
headers.appendChild(el);
});
const rows = numVars === 3 ? 2 : 4;
for(let r=0; r<rows; r++) {
for(let c=0; c<4; c++) {
let rowBits = numVars === 3 ? r : grayCodes4[r];
let colBits = grayCodes3[c];
let logicalIdx = (rowBits << 2) | colBits;
const cell = document.createElement('div');
cell.className = 'cell val-0';
cell.id = `cell-${logicalIdx}`;
// Store visual coordinates for simpler drawing later
cell.dataset.vr = r; // visual row
cell.dataset.vc = c; // visual col
cell.onclick = () => toggleCell(logicalIdx);
cell.innerText = '0';
grid.appendChild(cell);
}
}
MathJax.typesetPromise([headers]);
}
function toggleCell(idx) {
gridState[idx] = gridState[idx] === 0 ? 1 : 0;
updateCellUI(idx);
solveKMap();
}
function updateCellUI(idx) {
const cell = document.getElementById(`cell-${idx}`);
cell.innerText = gridState[idx];
if(gridState[idx] === 1) {
cell.classList.remove('val-0');
cell.classList.add('val-1');
} else {
cell.classList.remove('val-1');
cell.classList.add('val-0');
}
}
function randomizeKMap() {
for(let i=0; i<gridState.length; i++) gridState[i] = Math.random() > 0.5 ? 1 : 0;
gridState.forEach((_, i) => updateCellUI(i));
solveKMap();
}
function resetKMap() {
gridState.fill(0);
gridState.forEach((_, i) => updateCellUI(i));
solveKMap();
}
// --- SOLVER ALGORITHM ---
function solveKMap() {
clearOverlays();
const mode = document.querySelector('input[name="mode"]:checked').value;
const targetVal = mode === 'dnf' ? 1 : 0;
document.getElementById('mode-hint').innerText =
mode === 'dnf' ? "Групуємо одиниці (ДНФ)" : "Групуємо нулі (КНФ)";
// Check empty/full
let hasTarget = gridState.some(v => v === targetVal);
if(!hasTarget) {
document.getElementById('formula-display').innerText = mode === 'dnf' ? "$F = 0$" : "$F = 1$";
MathJax.typesetPromise();
return;
}
let allTarget = gridState.every(v => v === targetVal);
if(allTarget) {
document.getElementById('formula-display').innerText = mode === 'dnf' ? "$F = 1$" : "$F = 0$";
MathJax.typesetPromise();
return;
}
let covered = new Set();
let groups = [];
const sizes = numVars === 3 ? [8, 4, 2, 1] : [16, 8, 4, 2, 1];
// Colors
const colors = [
'var(--c-grp-0)', 'var(--c-grp-1)', 'var(--c-grp-2)',
'var(--c-grp-3)', 'var(--c-grp-4)', 'var(--c-grp-5)'
];
let colorIdx = 0;
// Helper to map Logic Index back to visual presence
function checkRect(r, c, h, w) {
let indices = [];
const maxR = numVars === 3 ? 2 : 4;
const maxC = 4;
for(let i=0; i<h; i++) {
for(let j=0; j<w; j++) {
let curR = (r + i) % maxR;
let curC = (c + j) % maxC;
let rowBits = numVars === 3 ? curR : grayCodes4[curR];
let colBits = grayCodes3[curC];
let idx = (rowBits << 2) | colBits;
if(gridState[idx] !== targetVal) return null;
indices.push(idx);
}
}
return indices;
}
function getDims(size) {
let dims = [];
if(size === 16) dims.push([4,4]);
if(size === 8) { dims.push([2,4], [4,2]); }
if(size === 4) { dims.push([1,4], [4,1], [2,2]); }
if(size === 2) { dims.push([1,2], [2,1]); }
if(size === 1) { dims.push([1,1]); }
if(numVars === 3) return dims.filter(d => d[0] <= 2);
return dims;
}
for(let s of sizes) {
let dims = getDims(s);
for(let d of dims) {
let h = d[0], w = d[1];
const maxR = numVars === 3 ? 2 : 4;
for(let r=0; r<maxR; r++) {
for(let c=0; c<4; c++) {
let indices = checkRect(r, c, h, w);
if(indices) {
// Check if useful (covers at least one new cell)
let isUseful = false;
for(let idx of indices) {
if(!covered.has(idx)) isUseful = true;
}
if(isUseful) {
const term = getTerm(indices, mode);
const color = colors[colorIdx % colors.length];
groups.push({ indices: indices, term: term, color: color, id: colorIdx });
colorIdx++;
indices.forEach(idx => covered.add(idx));
}
}
}
}
}
}
drawGroups(groups);
updateLegend(groups);
let formula = groups.map(g => g.term).join(mode === 'dnf' ? " \\vee " : " \\cdot ");
document.getElementById('formula-display').innerText = `$F = ${formula}$`;
MathJax.typesetPromise();
}
function getTerm(indices, mode) {
let mask = numVars === 3 ? 7 : 15;
let val = indices[0];
let diff = 0;
indices.forEach(idx => diff |= (val ^ idx));
let literals = [];
const vars = numVars === 3 ? ['A','B','C'] : ['A','B','C','D'];
const totalBits = numVars;
for(let i=0; i<totalBits; i++) {
let bitPos = (totalBits - 1) - i;
if( !((diff >> bitPos) & 1) ) {
let bitVal = (val >> bitPos) & 1;
let name = vars[i];
if (mode === 'dnf') literals.push(bitVal === 1 ? name : `\\overline{${name}}`);
else literals.push(bitVal === 0 ? name : `\\overline{${name}}`);
}
}
if(literals.length === 0) return "1";
if(mode === 'dnf') return literals.join("\\cdot ");
else return `(${literals.join(" \\vee ")})`;
}
function clearOverlays() {
document.querySelectorAll('.group-overlay').forEach(e => e.remove());
document.getElementById('group-legend').innerHTML = '';
}
function updateLegend(groups) {
const lg = document.getElementById('group-legend');
groups.forEach(g => {
const sp = document.createElement('span');
sp.className = 'legend-item';
sp.style.borderColor = g.color;
sp.style.color = '#333';
sp.innerHTML = `$${g.term}$`;
lg.appendChild(sp);
});
MathJax.typesetPromise([lg]);
}
// --- ВИПРАВЛЕНА ФУНКЦІЯ МАЛЮВАННЯ ---
function drawGroups(groups) {
const container = document.getElementById('kmap-grid-wrapper');
const rows = numVars === 3 ? 2 : 4;
const cols = 4;
groups.forEach((g, gIndex) => {
// 1. Create a boolean mask for this group visually
let mask = Array(rows).fill().map(() => Array(cols).fill(false));
g.indices.forEach(idx => {
const el = document.getElementById(`cell-${idx}`);
const r = parseInt(el.dataset.vr);
const c = parseInt(el.dataset.vc);
mask[r][c] = true;
});
// 2. Find connected components (without wrapping) on this mask
// This separates a wrapped group (e.g., col 0 and col 3) into two visual boxes
let visited = Array(rows).fill().map(() => Array(cols).fill(false));
for(let r=0; r<rows; r++) {
for(let c=0; c<cols; c++) {
if(mask[r][c] && !visited[r][c]) {
// Start flood fill to find bounding box of this component
let minR = r, maxR = r, minC = c, maxC = c;
let queue = [[r,c]];
visited[r][c] = true;
while(queue.length > 0) {
let [cr, cc] = queue.shift();
minR = Math.min(minR, cr); maxR = Math.max(maxR, cr);
minC = Math.min(minC, cc); maxC = Math.max(maxC, cc);
// Neighbors (Up, Down, Left, Right) - NO WRAPPING here
const dirs = [[0,1], [0,-1], [1,0], [-1,0]];
for(let d of dirs) {
let nr = cr + d[0];
let nc = cc + d[1];
if(nr>=0 && nr<rows && nc>=0 && nc<cols && mask[nr][nc] && !visited[nr][nc]) {
visited[nr][nc] = true;
queue.push([nr,nc]);
}
}
}
// 3. Draw box for this component
const div = document.createElement('div');
div.className = 'group-overlay';
// Calculate geometry
// Cell is 70px, Gap is 4px. Header is 40px.
const top = 40 + minR * 74;
const left = 40 + minC * 74;
const width = (maxC - minC + 1) * 70 + (maxC - minC) * 4;
const height = (maxR - minR + 1) * 70 + (maxR - minR) * 4;
// Dynamic Padding/Inset to prevent exact overlap
const offset = (gIndex * 4);
div.style.top = (top + offset) + 'px';
div.style.left = (left + offset) + 'px';
div.style.width = (width - offset*2) + 'px';
div.style.height = (height - offset*2) + 'px';
div.style.borderColor = g.color;
div.style.borderWidth = '3px';
container.appendChild(div);
}
}
}
});
}
window.onload = initKMap;
</script>
</body>
</html>