Public
Edited
Dec 24, 2022
1 fork
1 star
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
chunkSize = 4
Insert cell
Insert cell
Insert cell
Insert cell
datastremBufferExample = "mjqjpqmgbljsphdztnvjfqwrcgsmlb"
Insert cell
Insert cell
startOfPacketMarker(chunkSize)(datastremBufferExample)
Insert cell
Insert cell
Insert cell
Insert cell
getFirstMarker = (e) => {
const {groups: {first}} = (/(?<first>\d+)$/.exec(e));
const {groups: {string}} = /^(?<string>[a-z]+):/.exec(e);
return {first: +first, string};
}
Insert cell
parseExampleText = (text) => R.pipe(
R.split("\n"),
R.map(getFirstMarker),
)(text)
Insert cell
tests = [
// "mjqjpqmgbljsphdztnvjfqwrcgsmlb",
"bvwbjplbgvbhsrlpgdmjqwftvncz",
"nppdvjthqldpwncqszvftbrmjlhg",
"nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg",
"zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw"
]
Insert cell
Insert cell
Insert cell
Insert cell
R.aperture(3, [1, 2, 3, 4, 5]); //=> [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
Insert cell
// for each of the strings, generate a list of chunks – ${chunkSize} consecutive characters
step1 = R.map(R.aperture(chunkSize))(tests)
Insert cell
// reduce each chunk to its unique characters
step2 = R.map(R.map(R.uniq))(step1)
Insert cell
// retrieve the number of unique characters in each chunk
step3 = R.map(R.map(R.prop("length")))(step2)
Insert cell
step4 = R.map( // for each list,
R.findIndex( // find first element in list
R.equals(chunkSize) // where length equals chunkSize
)
)
(step3)
Insert cell
// A marker can only occur after at least chunkSize characters.
// So, add chunkSize to each position.
step5 = R.map(R.add(chunkSize))(step4)
Insert cell
Insert cell
R.map(R.prop("first"))(part1Examples)
Insert cell
Insert cell
// Number → String → Number
// takes a chunkSize (Number)
// returns function that takes a data stream (String)
// returns postion of start-of-packet marker (Number) in data stream
startOfPacketMarker = R.curry(
(chunkSize, stream) =>
R.pipe(
R.aperture(chunkSize), // expand data into list of chunkSize chunks
R.findIndex( // find first element in list that…
R.pipe(
R.uniq, // reduce each chunk to its unique characters
R.prop("length"), // grab each chunk’s length
R.equals(chunkSize), // …equals chunkSize
)
),
R.add(chunkSize), // must process at least chunkSize characters before a marker can be found
)(stream)
)
Insert cell
R.map(startOfPacketMarker(chunkSize))(tests)
Insert cell
Insert cell
startOfPacketMarker(chunkSize)(input)
Insert cell
Insert cell
Insert cell
viewof part2Examples = Inputs.table(parseExampleText(part2ExamplesText), {width: {first: 36}, })
Insert cell
startOfPacketMarker(14)(input)
Insert cell
Insert cell
R = require("ramda")
Insert cell
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