From b1dd9c1db32faf425c4f24fa5e1f0493d5fd8d49 Mon Sep 17 00:00:00 2001 From: Tissevert Date: Wed, 17 Aug 2022 08:17:44 +0200 Subject: [PATCH] Plug the constellation generator into the toolbox --- index.html | 1 + js/Constellation.js | 65 +++++++++++++++++++++++++++++++++++++++++++++ js/Toolbox.js | 7 +++++ 3 files changed, 73 insertions(+) create mode 100644 js/Constellation.js diff --git a/index.html b/index.html index 0b56005..b5a22f1 100644 --- a/index.html +++ b/index.html @@ -25,6 +25,7 @@ Color +
diff --git a/js/Constellation.js b/js/Constellation.js new file mode 100644 index 0000000..930154d --- /dev/null +++ b/js/Constellation.js @@ -0,0 +1,65 @@ +import generate from Grid.Util; + +return { + random: random +}; + +function random(size) { + var indices = Array.from({length: size}).map(function(x, i) {return i;}); + var previousColumn; + var columns = [] + while(columns.length < 8) { + previousColumn = pickNextColumn(indices, previousColumn) + columns.push(previousColumn); + } + return generate(size, size, function(cell) { + return columns[cell.row] == cell.column; + }); +} + +function pickNextColumn(columnsLeft, previousColumn) { + var parts = contiguousParts(columnsLeft); + if(parts.length == 1 && columnsLeft.length == 4) { + var candidateColumns = [null, columnsLeft[1], columnsLeft[2], null]; + } else if(parts.length == 2 && columnsLeft.length < 5 + && Math.min(parts[0].length, parts[1].length) < 2) { + candidateColumns = parts[0].length == 1 ? [null].concat(parts[1]) : parts[0]; + } else { + var candidateColumns = columnsLeft; + } + candidateColumns = candidateColumns.map(maskAround(previousColumn)); + return columnsLeft.splice(pickIndex(candidateColumns), 1)[0]; +} + +function maskAround(c0) { + return function(c1) { + return Math.abs(c1 - c0) < 2 ? null : c1; + }; +} + +function pickIndex(t) { + var o = {}; + var definedCount = 0; + for(var i = 0; i < t.length; i++) { + if(t[i] != undefined) { + o[definedCount] = i; + definedCount++; + } + } + return o[Math.floor(definedCount * Math.random())]; +} + +function contiguousParts(t) { + var parts = []; + var current = []; + for(var i = 0; i < t.length; i++) { + if(current.length < 1 || t[i] - current[current.length-1] == 1) { + current.push(t[i]); + } else { + parts.push(current); + current = [t[i]]; + } + } + parts.push(current); + return parts; +} diff --git a/js/Toolbox.js b/js/Toolbox.js index e24922a..08bdde7 100644 --- a/js/Toolbox.js +++ b/js/Toolbox.js @@ -1,4 +1,5 @@ import * as Dom from UnitJS.Dom; +import Constellation; var toolbox; var tool; @@ -21,6 +22,12 @@ function init(size, elementId) { colors.className = color(); }); tool = toolbox.querySelector('#tool'); + toolbox.querySelector('#scatter').addEventListener('click', function() { + var constellation = Constellation.random(size); + for(var i = 0; i < size; i++) { + console.log(constellation[i].map(function(x) {return x ? '*' : ' ';}).join('|')); + } + }); } function get() {