Published
Edited
Apr 9, 2021
Insert cell
Insert cell
Insert cell
A = [1,3,5,2,4,6]
Insert cell
bigA = non_sequential();
Insert cell
B = [4,6,8,5,7,9]
Insert cell
bigB = non_sequential(50, -75);
Insert cell
Insert cell
Insert cell
in_at_least_one(A,B).sort(numeric_compare)
Insert cell
in_at_least_one(bigA,bigB).sort(numeric_compare)
Insert cell
in_both(A,B).sort(numeric_compare)
Insert cell
in_both(bigA,bigB).sort(numeric_compare)
Insert cell
Insert cell
in_at_least_one_v2(A,B)
Insert cell
in_at_least_one_v2(bigA,bigB)
Insert cell
in_both_v2(A,B)
Insert cell
in_both_v2(bigA,bigB)
Insert cell
Insert cell
in_at_least_one = (a,b) => {
let res, other;

// start result as copy of largest array, to reduce number of checks
if (a.length > b.length) {
res = a.concat([]);
other = b;
}
else {
res = b.concat([]);
other = a;
}

// examine each value in other, and add to result if not already there
other.forEach((v) => {if (!res.includes(v)) res.push(v)} );
return res;
}
Insert cell
in_both = (a,b) => {
let res = []; // start with empty result
let peek, other;

// use largest array for comparisons, to avoid missing elements
if (a.length > b.length) {
peek = a;
other = b;
}
else {
peek = b;
other = a;
}

// examine each value in peek, and add to result if also found in other
peek.forEach((v) => {if (other.includes(v)) res.push(v)} )
return res;
}
Insert cell
in_at_least_one_v2 = (a,b) => {
let res = []; // start with empty result and sorted copies of input
let c = a.concat([]).sort(numeric_compare);
let d = b.concat([]).sort(numeric_compare);

// pull smallest values off bottom of stack, keeping one copy of each
while (c.length > 0 && d.length > 0) {
if (c[0] < d[0]) { res.push(c.shift()); }
else if (d[0] < c[0]) { res.push(d.shift()); }
else if (c[0] == d[0]) { res.push(c.shift()); d.shift(); }
}

// add any leftovers to the result
if (c.length > 0) { res = res.concat(c); }
if (d.length > 0) { res = res.concat(d); }

return res;
}
Insert cell
in_both_v2 = (a,b) => {
let res = []; // start with empty result and sorted copies of input
let c = a.concat([]).sort(numeric_compare);
let d = b.concat([]).sort(numeric_compare);

// pull smallest values off bottom of the stack, discarding unless equal
while (c.length > 0 && d.length > 0) {
if (c[0] < d[0]) { c.shift(); }
else if (d[0] < c[0]) { d.shift(); }
else if (c[0] == d[0]) { res.push(c.shift()); d.shift(); }
}

return res;
}
Insert cell
non_sequential = (n=50, s=1, i=5) => {
let arr = [], v = s;
while(n--) { arr.push(v); v += (1 + Math.floor(Math.random()*i))}
return arr;
}
Insert cell
numeric_compare = (a, b) => a - b
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