Public
Edited
Dec 22, 2022
1 fork
1 star
Insert cell
Insert cell
list = (data) => {
const list = data
.trim()
.split("\n")
.map((n) => ({ prev: null, n: +n, next: null }));
let prev = list[list.length - 1];
for (const p of list) {
prev.next = p;
p.prev = prev;
prev = p;
}
return list;
}
Insert cell
function mix(list, len = list.length) {
// yield [...print(list)];
let zero = list[0];
for (let i = 0; i < len; i++) {
const p = list[i];
if (p.n === 0) {
zero = p;
continue;
}
const dir = p.n > 0 ? "next" : "prev";
const hops = p.n > 0 ? p.n : -p.n + 1;
let after = p;
for (let i = 0; i < hops; i++) after = after[dir];
// yield { n: p.n, l: after.n, r: after.next.n };
// extract
const { prev, next } = p;
prev.next = next;
next.prev = prev;
// insert
p.next = after.next;
p.prev = after;
p.next.prev = p.prev.next = p;
// yield [...print(list)];
}
return zero;
}
Insert cell
function* print(n) {
while (n.n !== 0) n = n.next;
const zero = n;
do {
yield n.n;
n = n.next;
} while (n !== zero);
}
Insert cell
mix(list(sample), 1)
Insert cell
part1ref(data, 1)
Insert cell
function* coordinates(p) {
for (let t = 0; t < 3; t++) {
for (let i = 0; i < 1000; i++) p = p.next;
yield p.n;
}
}
Insert cell
part1 = d3.sum(coordinates(mix(list(data)))) // -10214, 10214 (too low)
Insert cell
Insert cell
Insert cell
part1ref = async (input, len = 5000) => {
let numbers = input
.trim()
.split("\n")
.map((num) => parseInt(num));

const first = { index: 0, value: numbers[0], next: null, previous: null };
let current = first;
for (let i = 1; i < numbers.length; i++) {
let node = { index: i, value: numbers[i], next: null, previous: current };
current.next = node;
current = node;
}
current.next = first;
first.previous = current;
current = current.next;

let head;
for (let i = 0; i < len; i++) {
let node = current;
while (node.index != i) node = node.next;

if (node.value > 0) {
for (let move = 0; move < node.value; move++) {
let index = node.index,
value = node.value;
node.index = node.next.index;
node.value = node.next.value;
node.next.index = index;
node.next.value = value;
node = node.next;
}
} else if (node.value < 0) {
for (let move = 0; move < Math.abs(node.value); move++) {
let index = node.index,
value = node.value;
node.index = node.previous.index;
node.value = node.previous.value;
node.previous.index = index;
node.previous.value = value;
node = node.previous;
}
}
head = node;
}
return head;

let sum = [];
while (current.value != 0) current = current.next;
return current;
for (let grove = 0; grove < 3; grove++) {
for (let i = 0; i < 1000; i++) current = current.next;
sum.push(current.value);
}

return sum;
}
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