-
Notifications
You must be signed in to change notification settings - Fork 11
/
creator.js
433 lines (306 loc) · 9.74 KB
/
creator.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
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
import {Puzzle} from '../src/puzzle.js';
import {PuzzleCell} from '../src/puzzle-cell.js';
import {Solver} from '../src/solver.js';
import {Utility} from '../src/utility.js';
export {Creator};
/**
* @class
* @type {Creator}
* @this Creator
*
* creates nonogram puzzles
*
* @property {Puzzle} puzzle
* @property {array} log
* @property {number} creationTime
* @property {number} solvingTime
*/
const Creator = class
{
// ###################################################################################### public methods
/**
* populates the puzzles rows and columns with random, solvable values
*
* @param {number} width
* @param {number} height
* @param {number|null} density - a floating point number between 0 and 1 (optional) that controls the percentage of filled cell likelihood.
* If not supplied a random value between 0.2 and 0.8 will be generated.
* Note that this does not make a puzzle grid filled in by the percentage,
* rather it's a 'suggestion' that is run through randomization on a cell-by-cell basis.
* @returns {Puzzle|Puzzle|class}
*/
createRandom( width, height, density )
{
const start = new Date().getTime();
let puzzleValid = false,
densityValid = typeof density === 'number' && density >= 0 && density <= 1,
cellsFilled, chanceOfCellFill, solutionGrid, rowArray, cellValue, solver, i, elapsed
;
this.puzzle = new Puzzle( width, height );
this._reset();
while (puzzleValid === false) {
chanceOfCellFill = densityValid ? density : Utility.getRandomIntBetween( 200, 800 ) / 1000;
solutionGrid = [];
rowArray = [];
cellsFilled = 0;
this._log( 'Creating random ' +
this.puzzle.width + 'x' + this.puzzle.height +
' puzzle with density of ' + chanceOfCellFill + '...'
);
// create puzzle grid randomly using density as a factor
for (i = 0; i < this.puzzle.totalCells; i++) {
cellValue = Math.random() < chanceOfCellFill ? 1 : 0;
cellsFilled += cellValue;
if (i % this.puzzle.width === 0 && i > 0) {
solutionGrid.push( rowArray );
rowArray = [];
}
rowArray.push( cellValue );
}
// ensure that at least one cell is filled, and that not all of them are
if (cellsFilled === 0) {
this._log( 'Generated puzzle has no cells filled. Trying again...' );
continue;
} else if (cellsFilled === this.puzzle.totalCells) {
this._log( 'Generated puzzle has all cells filled. Trying again...' );
continue;
}
// populate the solution grid
solutionGrid.push( rowArray );
// populate the grid
this.puzzle = Creator._populatePuzzleFromGrid( this.puzzle, solutionGrid );
// ensure that puzzle is solvable
solver = new Solver( this.puzzle );
if (solver.solve()) {
puzzleValid = true;
elapsed = (new Date().getTime() - start) / 1000;
this._log( 'Puzzle is solvable - solved in ' + solver.elapsedTime + ' seconds' );
this._logLine();
this._log( 'Puzzle generated in ' + elapsed + ' seconds.' );
this.creationTime = elapsed;
this.solvingTime = solver.elapsedTime;
} else {
this._log( 'Puzzle cannot be solved. Trying again...' );
}
this._logLine();
}
this.puzzle.creator = this;
return this.puzzle;
}
/**
* - create a puzzle using a grid
*
* @param {array} grid - a multi-dimensional array representing rows and columns.
* for example a 2x2 grid could be represented by [[0,1],[0,0]]
* @throws - error if grid is invalid
*/
createFromGrid( grid )
{
const start = new Date();
let width = 0,
height = 0,
puzzle, solver, elapsed
;
this._reset();
this._log( 'creating puzzle from grid array.' );
// make sure grid is valid and get width & height
if (!(grid instanceof Array)) {
throw 'grid is not an array';
}
grid.forEach( ( row, rowKey ) =>
{
if (!(row instanceof Array)) {
throw 'grid is not a multi-dimensional array';
}
if (width === 0) {
width = row.length;
} else if (row.length !== width) {
throw 'row ' + rowKey + ' has an invalid length (' + row.length + ') - expecting ' + width;
}
height++;
} );
this._log( 'grid is valid' );
this._log( 'populating ' + width + 'x' + height + ' puzzle' );
puzzle = new Puzzle( width, height );
this.puzzle = Creator._populatePuzzleFromGrid( puzzle, grid );
this.puzzle.creator = this;
// ensure that puzzle is solvable
solver = new Solver( this.puzzle );
if (solver.solve()) {
this._log( 'Puzzle is solvable.' );
this._logLine();
} else {
this._log( 'Puzzle cannot be solved.' );
this._logLine();
return false;
}
elapsed = (new Date().getTime() - start) / 1000;
this._log( 'Puzzle built and solved in ' + elapsed + ' seconds.' );
this._logLine();
return this.puzzle;
}
/**
* - create a puzzle from a hint object
*
* @param {object} hints - structured as follows:
* {
* row: [[3], [5], [5], [2, 3], [1, 5], [2, 1, 1], [2, 5], [1, 3]],
* column: [[1, 3], [4], [], [2, 3], [5, 2], [5, 2], [5, 2], [2, 3]]
* }
* @param {array} hints.row
* @param {array} hints.column
* @throws - error if hints object is structured incorrectly
*/
createFromHints( hints )
{
const start = new Date();
let width, height, puzzle, solver, elapsed;
this._reset();
this._log( 'creating puzzle from hints' );
// make sure row & column properties exist
if (typeof hints !== 'object' || !hints.row || !hints.column) {
throw 'parameter passed to createFromHints() must be an object containing "row" and "column" properties';
} else if (!(hints.row instanceof Array) || !(hints.column instanceof Array)) {
throw 'hints.row or hints.column must be an array.';
}
this._log( 'found row and column hints' );
width = hints.column.length;
height = hints.row.length;
puzzle = new Puzzle( width, height );
puzzle.rowHints = hints.row;
puzzle.columnHints = hints.column;
puzzle.creator = this;
this._log( 'populating ' + width + 'x' + height + ' puzzle' );
// populate cells array
puzzle.grid.forEach( ( row, rowKey ) =>
{
row.forEach( ( column, columnKey ) =>
{
puzzle.cells.push( new PuzzleCell( {
index: (rowKey * puzzle.width) + columnKey,
column: columnKey,
row: rowKey
} ) );
} );
} );
this.puzzle = puzzle;
// ensure that puzzle is solvable
solver = new Solver( this.puzzle );
if (solver.solve()) {
this._log( 'Puzzle is solvable.' );
this._logLine();
} else {
this._log( 'Puzzle cannot be solved.' );
this._logLine();
return false;
}
// set solution on puzzle cells
solver.puzzle.cells.forEach( ( solvedCell, cellIndex ) =>
{
const puzzleCell = this.puzzle.getCellByIndex( cellIndex );
puzzleCell.aiSolution = solvedCell.aiSolution;
puzzleCell.solution = solvedCell.aiSolution;
} );
elapsed = (new Date().getTime() - start) / 1000;
this._log( 'Puzzle built and solved in ' + elapsed + ' seconds.' );
this._logLine();
return this.puzzle;
}
// ###################################################################################### private methods
/**
*
* @param {Puzzle} puzzle
* @param {array} grid - a multidimensional array
* @returns {Puzzle} puzzle
* @private
*/
static _populatePuzzleFromGrid( puzzle, grid )
{
let columnHints, rowKey, row, columnKey, column, cell, currentVal, lastVal, rowHints, hintKey, hint;
puzzle.reset();
puzzle.grid = grid;
for (rowKey = 0; rowKey < puzzle.grid.length; rowKey++) {
row = puzzle.grid[rowKey];
rowHints = [];
puzzle.rowHints[rowKey] = [];
for (columnKey = 0; columnKey < row.length; columnKey++) {
column = row[columnKey];
currentVal = column;
lastVal = columnKey > 0 ? puzzle.grid[rowKey][columnKey - 1] : 0;
// populate cells
puzzle.cells.push( new PuzzleCell( {
index: (rowKey * puzzle.width) + columnKey,
column: columnKey,
row: rowKey,
solution: column
} ) );
// populate row hints
if (currentVal === 1 && lastVal === 0) {
rowHints.push( 1 );
} else if (currentVal === 0 && lastVal === 1) {
rowHints.push( 0 );
} else if (currentVal === 1 && lastVal === 1) {
rowHints[rowHints.length - 1]++;
}
}
// clean up row hints
for (hintKey = 0; hintKey < rowHints.length; hintKey++) {
hint = rowHints[hintKey];
if (hint > 0) {
puzzle.rowHints[rowKey].push( hint );
}
}
}
// populate column hints
for (columnKey = 0; columnKey < puzzle.width; columnKey++) {
puzzle.columnHints[columnKey] = [];
columnHints = [];
for (cell = columnKey; cell < puzzle.totalCells; cell += puzzle.width) {
row = Math.floor( cell / puzzle.width );
currentVal = puzzle.grid[row][columnKey];
lastVal = row > 0 ? puzzle.grid[row - 1][columnKey] : 0;
if (currentVal === 1 && lastVal === 0) {
columnHints.push( 1 );
} else if (currentVal === 0 && lastVal === 1) {
columnHints.push( 0 );
} else if (currentVal === 1 && lastVal === 1) {
columnHints[columnHints.length - 1]++;
}
}
// clean up column hints
for (hintKey = 0; hintKey < columnHints.length; hintKey++) {
hint = columnHints[hintKey];
if (hint > 0) {
puzzle.columnHints[columnKey].push( hint );
}
}
}
return puzzle;
}
/**
*
* @param msg
* @private
*/
_log( msg )
{
this.log.push( msg );
}
/**
*
* @private
*/
_logLine()
{
this.log.push( '-----------------------------------' );
}
/**
* @private
*/
_reset()
{
this.log = [];
this.creationTime = 0;
this.solvingTime = 0;
}
};