Public
Edited
Dec 1, 2023
2 stars
Insert cell
Insert cell
Insert cell
width = 10
Insert cell
dirs = [ [0, 1], [1, 0] ]
Insert cell
function* grids(size = 2, taken = new Set()) {
for (const [dx, dy] of dirs) {
for (let x = 0; x < width - (size - 1) * dx; x++) {
point: for (let y = 0; y < width - (size - 1) * dy; y++) {
const grid = new d3.InternSet([], String);
for (let i = 0; i < size; i++) {
const p = [x + dx * i, y + dy * i];
if (taken.has(p)) continue point;
grid.add(p);
}
yield grid;
}
}
}
}
Insert cell
function* flat(iter) {
for (const i of iter) yield* i;
}
Insert cell
count = (iter) => {
const counts = new d3.InternMap([], String);
for (const c of iter) counts.set(c, (counts.get(c) ?? 0) + 1);
return counts;
}
Insert cell
Insert cell
plot = (grids, options = {}) => {
const data = count(flat(grids));
return Plot.plot({
marks: [
Plot.cell(data, {
x: ([d]) => d[0],
y: ([d]) => d[1],
fill: ([, count]) => count,
inset: -2
}),
Plot.text(data, {
x: ([d]) => d[0],
y: ([d]) => d[1],
text: ([, count]) => count,
fontSize: 14,
stroke: "white",
strokeOpacity: 0.5,
fill: "black"
})
],
aspectRatio: 1,
x: { tickFormat: (i) => "ABCDEFGHIJ"[i], axis: "top" },
y: { tickFormat: (i) => i + 1 },
...options
});
}
Insert cell
Insert cell
function* gridss(ships, occupied = new d3.InternSet([], String)) {
if (ships.length) {
const [ship, ...remaining] = ships;
for (const grid of grids(ship, occupied))
yield* gridss(remaining, grid.union(occupied));
} else {
yield occupied;
}
}
Insert cell
coords = (list) =>
new d3.InternSet(
list
.trim()
.split(/\s+/)
.map((s) => ["ABCDEFGHIJ".indexOf(s[0]), +s[1] - 1]),
String
)
Insert cell
plot(
gridss(
[3, 3],
coords(`
E5 E6 E7 E8 E4 E3
H4 H8
`)
),
{
color: { domain: [0, 2000] }
}
)
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