Arithmetic Coding PlaygroundAC Playground

Arithmetic coding turns text into a compact stream of bits, guided by a model that predicts each next character. Your job is to write that model. The playground does the rest: it encodes the text, decodes it again to make sure nothing was lost, and shows you where your model predicted well and where it struggled.

A character your model gives probability p costs about −log₂ p bits, so confident, correct guesses are cheap and surprises are expensive.

Model

A model needs an alphabet, a context size, and a frequencies function that returns a weight for every character that could come next. The reference at the bottom of the page explains each part.

JavaScript

Text

This is the text your model will compress. It can only contain characters from the model's alphabet.

Results

Cost of each character

Each character is shaded by how many bits it took to encode; darker means more expensive. Hover over a character to see its probability, or click it to see everything the model predicted at that point.

What the model predicted


Compressed output

The encoded bytes, shown in hexadecimal.

Compare with the examples

Run your model and each example on the current text to see which one compresses it best.

Reference
const alphabet
The characters your text can contain, written as a string such as "abc " or as an array. A special end-of-text symbol, EOF, is added automatically, so leave it out.
const contextSize
How many of the most recent characters are passed to frequencies. Use 0 to pass nothing, or null to pass all of the text read so far. If you leave it out, all of the text is passed.
function frequencies(context)
Called once for every character. Return how likely each possible next character is, as whole-number weights. You can return an object such as { a: 3, " ": 9, [EOF]: 1 }, where any character you leave out gets a weight of 0, or an array with one weight per alphabet character followed by one for EOF. The weights must add up to at least 1 and at most 2³⁰ (about a billion), and the character that actually comes next must have a weight above 0.
function observe(symbol, context) Optional
Called after each character, with the same context that frequencies just received. Use it to update counts or anything else your model learns as it reads.
function reset() Optional
Called before encoding starts and again before decoding starts, so your model begins from the same state both times.

Decoding only works if your model makes exactly the same predictions both times. Avoid randomness, the current time, and any state that reset doesn't restore. If your code runs for more than four seconds, it is stopped so that the page stays responsive.