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
|
<html>
<!--
Task 2 from
https://perlweeklychallenge.org/blog/perl-weekly-challenge-077/
Comments: https://andrewshitov.com/2020/09/08/lonely-x-the-weekly-challenge-77-task-2/
-->
<head>
<meta charset="UTF-8"/>
<title>Lonely X</title>
<style>
* {
text-align: center;
font-family: Arial, sans-serif;
}
#Shape table {
margin: auto;
/* border-collapse: collapse; */
}
/* #Shape table tr td input {
width: 50px;
height: 50px;
} */
#Shape table tr td {
border: 5px solid white;
}
#Shape table tr td.lonely {
border: 5px solid green;
}
</style>
</head>
<body>
<p>
<input type="text" name="width" id="MatrixWidth" size="3" value="3" />
×
<input type="text" name="height" id="MatrixHeight" size="3" value="3" />
<input type="submit" value="Set the shape" onclick="set_shape()" />
</p>
<div id="Shape"></div>
<p>Note: Lonely X is marked green.</p>
<script>
let w = 0;
let h = 0;
function set_shape() {
w = parseInt(document.getElementById('MatrixWidth').value);
h = parseInt(document.getElementById('MatrixHeight').value);
let table = '<table>';
for (let y = 0; y != h; y++) {
table += '<tr>';
for (let x = 0; x != w; x++) {
table += '<td><input type="checkbox" data-x="' + x + '" data-y="' + y + '" onclick="update_lonely()" /></td>';
}
table += '</tr>';
}
table += '</table>';
document.getElementById('Shape').innerHTML = table;
}
function update_lonely() {
let cells = document.getElementById('Shape').getElementsByTagName('input');
let neigbours = [[0, 1], [0, -1], [1, 0], [-1, 0], [1, 1], [-1, -1], [1, -1], [-1, 1]];
for (let i = 0; i != cells.length; i++) {
cells[i].parentNode.className = '';
if (!cells[i].checked) continue;
let x = parseInt(cells[i].getAttribute('data-x'));
let y = parseInt(cells[i].getAttribute('data-y'));
let is_ok = true;
for (let c = 0; c != neigbours.length; c++) {
if (!test_cell(x + neigbours[c][0], y + neigbours[c][1])) {
is_ok = false;
break;
}
}
if (is_ok) {
cells[i].parentNode.className = 'lonely';
}
}
}
function test_cell(x, y) {
if (x < 0 || y < 0 || x >= w || y >= h) {
return true;
}
else {
let cell = document.querySelector('#Shape tr td input[data-x="'+ x + '"][data-y="' + y + '"]');
return !cell.checked;
}
}
set_shape();
</script>
</body>
</html>
|