Public
Edited
Dec 16, 2023
Fork of Simple D3
Insert cell
Insert cell
Insert cell
vis = {
const w = width;
const aspect = MAP.length / MAP[0].length;
const height = w * aspect;
const cellsz = height / MAP.length;
const svg = d3.create("svg")
.attr("viewBox", [0, 0, w, height])
.attr("width", w)
.attr("height", height)
.attr("style", "max-width: 100%; height: auto;");

let hs = []
MAP.forEach((row, ri) => row.forEach((v, ci) => {
if (v == '#') {
hs.push([ri, ci]);
}
}));
const SW = 3;
// let iterL = JSON.parse(solution[curiter]);
// return iterL;
let o_circles = svg
.selectAll(".o")
.data(JSON.parse(solution[curiter.value]))
.join("circle")
.attr('class', 'o')
.attr("cx", d => (d[1]+0.5) * cellsz)
.attr("cy", d=> (d[0]+0.5) * cellsz)
.attr("r", d => cellsz/2.0)
// .attr("fill", "#FFF")
.attr("fill", "#001b42")
// .attr('stroke-width', SW);
let h_circles = svg
.selectAll(".h")
.data(hs)
.join("circle")
.attr('class', 'h')
.attr("cx", d => (d[1]+0.5) * cellsz)
.attr("cy", d=> (d[0]+0.5) * cellsz)
.attr("r", d => cellsz/2.0)
.attr("fill", "#8a8471");
function update(data) {
o_circles
.data(JSON.parse(solution[curiter.value]))
.transition()
.duration(100)
.attr("cx", d => (d[1]+0.5) * cellsz)
.attr("cy", d=> (d[0]+0.5) * cellsz)
.ease(d3.easeLinear);
}

// update(iterL)
curiter.addEventListener('input', e => {
update(JSON.parse(solution[curiter.value]));
})
return svg.node();
}
Insert cell
Insert cell
solution = {
let os = []
MAP.forEach((row, ri) => row.forEach((v, ci) => {
if (v == 'O') {
os.push([ri, ci]);
}
}));

let dot = (a,b) => (a[0]*b[0]+a[1]*b[1]);

const DIRS = [
[-1,0],
[0,-1],
[1,0],
[0,1]
];

let iters = [JSON.stringify(os)];
for (let i = 0; i < NITERS; ++i) {
let diri = DIRS[i % 4];
// os.sort((a,b) => dot(b, diri) - dot(a, diri));
let ois = os.map((v,i) => i)
ois.sort((a,b) => dot(os[b], diri) - dot(os[a], diri));
for (let j of ois) {
let pos = os[j];
let ahead = [...os[j]];
let blocked = false;
while (!blocked) {
let an = [ahead[0]+diri[0], ahead[1]+diri[1]];
blocked = (an[0] < 0) ||
(an[1] < 0) || (an[0] >= MAP.length) ||
(an[1] >= MAP[0].length) || (MAP[an[0]][an[1]] == '#') || os.some(e => `${e}` == `${an}`);
if (!blocked) ahead = an;
}

os[j] = ahead;
}
let sd = JSON.stringify(os);
if (sd in iters) {
iters.push(sd);
break;
}
iters.push(sd);
}

return iters
}
Insert cell
function score(os) {
let total = 0;
for (let o of os) {
total += MAP.length - o[0];
}
return total
}
Insert cell
Insert cell
NITERS=10
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more