JavaScript实现生成数独
Xplorist Lv6

JavaScript实现生成数独

reference-site-list

steps

  • x

code

  • html

sudoku.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>sudoku</title>
<link rel="stylesheet" type="text/css" href="./sudoku.css">
</head>
<body>
<div id="app">
<div class="row" v-for="(row, rowIndex) in rows">
<div class="col" v-for="(col, colIndex) in row"
v-bind:style="{borderTop: rowIndex === 0 ? '2px black solid' : '0px',
borderLeft: colIndex ===0 ? '2px black solid' : '0px',
borderRight: (colIndex + 1) % 3 === 0 ? '2px black solid' : '1px gainsboro solid',
borderBottom: (rowIndex + 1) % 3 === 0 ? '2px black solid' : '1px gainsboro solid',
color: col === 0 ? 'red' : 'black'}">
{{ col }}
</div>
</div>
</div>
</body>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14"></script>
<script type="text/javascript" src="./sudoku.js"></script>
</html>
  • css

sudoku.css

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
#app {
/*border: 1px gainsboro solid;*/
width: 100%;
height: 98vh;
display: flex;
flex-direction: column;
}

div {
/*border: 1px gainsboro solid;*/
}

.row {
display: flex;
flex-direction: row;
height: 11vh;
}

.col {
width: 12%;
border-right: 1px gainsboro solid;
border-bottom: 1px gainsboro solid;
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
font-size:2.5em;
}
  • JavaScript

sudoku.js

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
var app = new Vue({
el: '#app',
data: {
rows: [],
cols: [],
zones: [],
},
methods: {
init: function () {
this.initEmptyArr(this.rows);
this.initEmptyArr(this.cols);
this.initEmptyArr(this.zones);
this.rows[0] = this.getRandomRow();
for (var i = 0; i < this.rows.length; i++) {
for (var j = 0; j < this.rows[i].length; j++) {
var num = this.rows[i][j];
var zoneName = this.getZoneName(i, j);
var zoneOrder = this.getZoneOrder(i, j);
if (i === 0) {
this.cols[j][i] = num;
this.zones[zoneName][zoneOrder] = num;
} else {
/*
if (newNum === 0) {
this.lineReset(i);
i--;
break;
} else {
this.rows[i][j] = newNum;
this.cols[j][i] = newNum;
this.zones[zoneName][zoneOrder] = newNum;
}
*/
this.generateSpecial(i, j, zoneName);
num = this.rows[i][j];
if (num === 0) {
var newNum = this.getRandomInPossible(i, j, zoneName);
this.rows[i][j] = newNum;
this.cols[j][i] = newNum;
this.zones[zoneName][zoneOrder] = newNum;
}
}
}
window.console.log("i = " + i + " : " + this.rows[i]);
}
},
// 整行数据重置
lineReset: function (row) {
for (var i = 0; i < this.rows[row].length; i++) {
this.rows[row][i] = 0;
this.cols[i][row] = 0;
var zoneName = this.getZoneName(row, i);
var zoneOrder = this.getZoneOrder(row, i);
this.zones[zoneName][zoneOrder] = 0;
}
},
initEmptyArr: function (arr) {
for (var i = 0; i < 9; i++) {
var row = [];
for (var j = 0; j < 9; j++) {
row.push(0);
}
arr.push(row);
}
},
// 获取宫序号
getZoneOrder: function (row, col) {
return row % 3 * 3 + col % 3;
},
// 获取宫名
getZoneName: function (row, col) {
return Math.floor(row / 3) * 3 + Math.floor(col / 3);
},
// 当在中宫列的第2行进行生成关键的三个数的组合
generateSpecial: function (row, col, zone) {
if (row % 3 === 1 && Math.floor(col / 3) === 1) {
var rowSet = [];
var zoneSet = [];
var rightSet = []; // 上一行最右边的3个数的集合
for (var i = 0; i < 3; i++) {
rowSet.push(this.rows[row][i]);
zoneSet.push(this.zones[zone][i]);
rightSet.push(this.rows[row - 1][i + 6]);
}
var sameSet = [];
for (var i = 0; i < rowSet.length; i++) {
if (rightSet.includes(rowSet[i])) {
sameSet.push(rowSet[i]);
}
}

var sameNum = sameSet.length;
if (sameNum === 0) {
// 上右3中的数,进行随机排列
// var result = this.getRandomArr(rightSet);
var align = this.getRandomLegalAlign(rightSet);
this.rows[row][col] = align[0];
this.rows[row][col + 1] = align[1];
this.rows[row][col + 2] = align[2];
} else if (sameNum === 1) {
// 上右3中不同的两个数,再从上左3中随机出一个数,组成排列,从有效排列中随机出一个排列

} else if (sameNum === 2) {
// 上右3中不同的一个数,在从上左3中随机出两个数,组成排列,从有效排列中随机出一个排列

}
}
},
// 从有效的排列中随机选一个
getRandomLegalAlign: function (arr) {
var aligns = this.findLegalArr(arr);
var random = this.getRandomNum(0, aligns.length - 1);
return aligns[random];
},
// 找出有效的排列
findLegalArr: function (arr) {
var result = [];
var aligns = this.listAlign(arr);
for (var i = 0; i < aligns.length; i++) {
var align = aligns[i];
if (this.checkCenter(align)) {
result.push(align);
}
}
return result;
},
// 列举出3个数字所有的排列
listAlign: function (arr) {
var trees = [];
for (var i = 0; i < arr.length; i++) {
var num = arr[i];
var tree = {
val: num,
parent: null,
children: []
};
this.generateTree(arr, num, tree);
trees.push(tree);
}
var result = [];
// 树转数组
for (var i = 0; i < trees.length; i++) {
var tree = trees[i];
var temp = [];
this.recurseTree(tree, temp, result);
}
return result;
},
// 遍历树
recurseTree: function (node, arr, result) {
var temp = arr.slice();
temp.push(node.val);
var children = node.children;
if (children.length === 0) {
result.push(temp);
} else {
for (var i = 0; i < children.length; i++) {
var child = children[i];
this.recurseTree(child, temp, result);
}
}
},
// 生成以该数字开头的树
generateTree: function (arr, num, tree) {
var temp = arr.slice();
// 移除数组中该该数字,获得该节点的子节点数
for (var i = 0; i < temp.length; i++) {
if (temp[i] === num) {
temp.splice(i, 1);
i--;
}
}
for (var i = 0; i < temp.length; i++) {
var item = {
val: temp[i],
parent: num,
children: []
};
tree.children.push(item);
this.generateTree(temp, temp[i], item);
}
},
// 检查中宫列的中行3个数字是否合规
checkCenter: function (arr) {
if (this.cols[3].includes(arr[0]) || this.cols[4].includes(arr[1]) || this.cols[5].includes(arr[2])) {
return false;
}
return true;
},
// 根据坐标获取可能集合中的一个随机值
getRandomInPossible: function (row, col, zone) {
var possible = this.getPossible(row, col, zone);
if (possible.length === 0) {
return 0;
}
return this.getRandomOne(possible);
},
// 根据坐标获取可能集合
getPossible: function (row, col, zone) {
var rowTemp = this.pushToArr(this.rows[row]);
var colTemp = this.pushToArr(this.cols[col]);
var zoneTemp = this.pushToArr(this.zones[zone]);

var rowArr = this.getNotZeroSet(rowTemp);
var colArr = this.getNotZeroSet(colTemp);
var zoneArr = this.getNotZeroSet(zoneTemp);
var subAll = [];
subAll = this.addToSubSet(rowArr, subAll);
subAll = this.addToSubSet(colArr, subAll);
subAll = this.addToSubSet(zoneArr, subAll);
var total = this.getTotalSet();
var result = [];
for (var i = 0; i < total.length; i++) {
var item = total[i];
if (!subAll.includes(item)) {
result.push(item);
}
}
if (result.length === 0) {
window.console.log( 'row: ' + row + ' col: ' + col + ' zon: ' + zone
+ '\nrowTemp: ' + rowTemp + '\ncolTemp: ' + colTemp + '\nzoneTemp: ' + zoneTemp
+ '\nsubAll : ' + subAll);
}
return result;
},
// 将一个数组中的所有元素添加到另外一个数组中
pushToArr: function (arr) {
var result = [];
for (var i = 0; i < arr.length; i++) {
result.push(arr[i]);
}
return result;
},
// 将集合去重添加到目标集合中
addToSubSet: function (arr, subAll) {
for (var i = 0; i < arr.length; i++) {
var item = arr[i];
if (!subAll.includes(item)) {
subAll.push(item);
}
}
return subAll;
},
// 获取非0集合
getNotZeroSet: function (arr) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] === 0) {
arr.splice(i, 1);
i--;
}
}
return arr;
},
// 获取全集
getTotalSet: function () {
var total = [];
for (var i = 0; i < 9; i++) {
total.push(i + 1);
}
return total;
},
// 获取1-9的随机不重复数组
getRandomRow: function () {
var row = [];
var temp = [];
for (var i = 0; i < 9; i++) {
temp.push(i + 1);
}
for (var i = 0; i < 9; i++) {
var random = this.getRandomNum(0, temp.length - 1);
row.push(temp[random]);
temp.splice(random, 1);
}
return row;
},
// 将数组变成随机数组
getRandomArr: function (arr) {
var result = [];
var temp = arr.slice();
while (temp.length > 0) {
var random = this.getRandomNum(0, temp.length - 1);
result.push(temp[random]);
temp.splice(random, 1);
}
return result;
},
// 从数组中随机取出一个数
getRandomOne: function (arr) {
var random = this.getRandomNum(0, arr.length - 1);
return arr[random];
},
// 获取[min, max]之间的一个随机数
getRandomNum: function (min, max) {
min = Math.floor(min);
max = Math.ceil(max);
return Math.floor(Math.random() * (max + 1 - min)) + min;
},
},
created: function () {
this.init();
}
});
 评论
// variables $gt-color-main := #6190e8 $gt-color-sub := #a1a1a1 $gt-color-loader := #999999 $gt-color-error := #ff3860 $gt-color-hr := #e9e9e9 $gt-color-comment-txt := #333333 $gt-color-link-active := #333333 $gt-color-btn := #ffffff $gt-size-base := 16px // default font-size $gt-size-border-radius := 5px $gt-breakpoint-mobile := 479px $gt-mask-z-index := 9999 // functions & mixins clearfix() { &:before &:after { display table clear both content "" } } em($px, $base-size = $gt-size-base) { u = unit($px) if (u is 'px') { unit($px / $base-size, 'em') } else { unit($px, u) } } mobile() { @media (max-width $gt-breakpoint-mobile) { {block} } } // variables - calculated $gt-size-loader-dot := em(6px) $gt-size-loader := em(28px) $gt-size-avatar := em(50px) $gt-size-avatar-mobi := em(32px) // styles // Put everything under container to avoid style conflicts .comments-container { .gt-container { box-sizing border-box * { box-sizing border-box } font-size $gt-size-base // common a { color $gt-color-main &:hover { color lighten($gt-color-main, 20%) border-color lighten($gt-color-main, 20%) } &.is--active { color $gt-color-link-active cursor default !important &:hover { color $gt-color-link-active } } } .hide { display none !important } // icons .gt-svg { display inline-block width em(16px) height em(16px) vertical-align sub svg { width 100% height 100% fill $gt-color-main } } .gt-ico { display inline-block &-text { margin-left em(5px) } &-github { width 100% height 100% .gt-svg { width 100% height 100% } svg { fill inherit } } } // loader .gt-spinner { position relative &::before { position absolute top 3px box-sizing border-box width em(12px) height em(12px) margin-top em(-3px) margin-left em(-6px) border 1px solid $gt-color-btn border-top-color $gt-color-main border-radius 50% animation gt-kf-rotate 0.6s linear infinite content '' } } .gt-loader { position relative display inline-block width $gt-size-loader height $gt-size-loader font-style normal // font-size: $gt-size-loader line-height $gt-size-loader border 1px solid $gt-color-loader border-radius 50% animation ease gt-kf-rotate 1.5s infinite &:before { position absolute top 0 left 50% display block width $gt-size-loader-dot height $gt-size-loader-dot margin-top -($gt-size-loader-dot / 2) margin-left -($gt-size-loader-dot / 2) background-color $gt-color-loader border-radius 50% content '' } } // avatar .gt-avatar { display inline-block width $gt-size-avatar height $gt-size-avatar +mobile() { width $gt-size-avatar-mobi height $gt-size-avatar-mobi } img { width 100% height auto border-radius 3px } &-github { width $gt-size-avatar - em(2px) height $gt-size-avatar - em(2px) cursor pointer +mobile() { width $gt-size-avatar-mobi - em(2px) height $gt-size-avatar-mobi - em(2px) } } } // button .gt-btn { display inline-block padding em(12px) em(20px) color $gt-color-btn font-size em(12px) line-height 1 white-space nowrap text-decoration none background-color $gt-color-main border 1px solid $gt-color-main border-radius $gt-size-border-radius outline none cursor pointer &-text { font-weight 400 } &-loading { position relative display inline-block width em(12px) height em(16px) margin-left em(8px) vertical-align top } &.is--disable { cursor not-allowed opacity 0.5 } &-login { margin-right 0 } &-preview { color $gt-color-main background-color var(--background-color) &:hover { background-color var(--second-background-color) } } &-public { &:hover { background-color lighten($gt-color-main, 20%) border-color lighten($gt-color-main, 20%) } } } } &-loadmore // loadmore /* error */ .gt-error { margin em(10px) color $gt-color-error text-align center } // initing .gt-initing { padding em(20px) 0 text-align center &-text { margin em(10px) auto font-size 92% } } // no int .gt-no-init { padding em(20px) 0 text-align center } // link .gt-link { border-bottom 1px dotted $gt-color-main &-counts &-project { text-decoration none } } // meta .gt-meta { position relative z-index 10 margin em(20px) 0 padding em(16px) 0 font-size em(16px) border-bottom 1px solid $gt-color-hr clearfix() } .gt-counts { margin 0 em(10px) 0 0 color var(--default-text-color) } .gt-user { float right margin 0 font-size 92% &-pic { width 16px height 16px margin-right em(8px) vertical-align top } &-inner { display inline-block cursor pointer .gt-user-name { color var(--default-text-color) } } .gt-ico { margin 0 0 0 em(5px) svg { fill var(--default-text-color) } } .is--poping { .gt-ico { svg { fill $gt-color-main } } } } .gt-version { margin-left em(6px) color $gt-color-sub } .gt-copyright { margin 0 em(15px) em(8px) padding-top em(8px) border-top 1px solid var(--border-color) } // popup .gt-popup { position absolute top em(38px) right 0 display inline-block padding em(10px) 0 font-size em(14px) letter-spacing 0.5px background var(--background-color) border 1px solid var(--border-color) .gt-action { position relative display block margin em(8px) 0 padding 0 em(18px) text-decoration none cursor pointer &.is--active { &:before { position absolute top em(7px) left em(8px) width em(4px) height em(4px) background $gt-color-main content '' } } } } // header .gt-header { position relative display flex &-comment { flex 1 margin-left em(20px) +mobile() { margin-left em(14px) } } &-textarea { display block box-sizing border-box width 100% min-height em(82px) max-height em(240px) padding em(12px) color var(--default-text-color) font-size em(14px) word-wrap break-word background-color var(--fourth-text-color) border 1px solid var(--border-color) border-radius $gt-size-border-radius outline none transition all 0.25s ease resize vertical &:hover { background-color var(--background-color) } } &-preview { padding em(12px) background-color var(--background-color) border 1px solid var(--border-color) border-radius $gt-size-border-radius } &-controls { position relative margin em(12px) 0 0 clearfix() +mobile() { margin 0 } &-tip { color $gt-color-main font-size em(14px) text-decoration none vertical-align sub +mobile() { display none } } .gt-btn { float right margin-left em(20px) +mobile() { float none width 100% margin em(12px) 0 0 } } } } &:after { position fixed top 0 right 0 bottom 100% left 0 opacity 0 content '' } &.gt-input-focused { position relative &:after { position fixed top 0 right 0 bottom 0 left 0 z-index $gt-mask-z-index background #000 opacity 0.6 transition opacity 0.3s, bottom 0s content '' } .gt-header-comment { z-index $gt-mask-z-index + 1 } } // comments .gt-comments { padding-top em(20px) &-null { text-align center } &-controls { margin em(20px) 0 text-align center } } // comment .gt-comment { position relative display flex padding em(10px) 0 &-content { flex 1 margin-left em(20px) padding em(12px) em(16px) overflow auto background-color var(--second-background-color) transition all ease 0.25s +mobile() { margin-left em(14px) padding em(10px) em(12px) } } &-header { position relative margin-bottom em(8px) font-size em(14px) } &-block-1 { float right width em(32px) height em(22px) } &-block-2 { float right width em(64px) height em(22px) } &-username { color $gt-color-main font-weight 500 text-decoration none &:hover { text-decoration underline } } &-text { margin-left em(8px) color $gt-color-sub } &-date { margin-left em(8px) color $gt-color-sub } &-like &-edit &-reply { position absolute height em(22px) &:hover { cursor pointer } } &-like { top 0 right em(32px) } &-edit &-reply { top 0 right 0 } &-body { // color: $gt-color-comment-txt !important color var(--second-text-color) !important .email-hidden-toggle a { display inline-block height 12px padding 0 9px color #444d56 font-weight 600 font-size 12px line-height 6px text-decoration none vertical-align middle background #dfe2e5 border-radius 1px &:hover { background-color #c6cbd1 } } .email-hidden-reply { display none white-space pre-wrap .email-signature-reply { margin 15px 0 padding 0 15px color #586069 border-left 4px solid #dfe2e5 } } .email-hidden-reply.expanded { display block } } &-admin { .gt-comment-content { background-color var(--fourth-text-color) } } } @keyframes gt-kf-rotate { 0% { transform rotate(0) } 100% { transform rotate(360deg) } } }