Code patternsDataCompare two strings

Compare two strings

Reads two lines and prints Y if they are the same and N if not.

Watch it run

The form “Two lines from the input” works on 17 cells; the named ones are “zero”, “letter”, “flag” and “scratch”. Press Play, drag the step slider forwards and back, or edit first line and second line:

The figure needs JavaScript. The program below is the result for the example values.

The first line is stored with two empty cells after every letter. Then the second line is read one letter at a time, and each letter is taken off the stored one: a flat loop.

If anything is left, the letters differed. A flag is set to 1, and the flag is carried along from letter to letter, as the running total is in the form A running total that travels along of walk an array of records.

A line that is longer than the other leaves letters with nothing to cancel them, so different lengths are caught by the same test.

The code

This is the program the figure ran. It is brainfuck as it stands: copy it, or open it in the playground, where you can change it:

>>>,----------[++++++++++>>>,----------]<<<[<<<]>>>>>,----------[++++++++++[-<<->>]<<[[-]>[-]+<]>[->>>+<<<]>>>>,----------]<<[[-]>[-]+[->>>+<<<]>>]>>+<[[-]>->>++++++[-<+++++++++++++>]<.[-]<]>[>>+++++++++++[-<++++++++>]<+.[-]<->]<<
Open in the playground230 characters

What it needs

Common mistakes
  • Storing the two strings one after the other. Then every comparison of two letters is a walk between them. Next to each other, it is one step.
  • Counting the differences instead of setting a flag: 256 differences would wrap to "equal" on 8-bit cells.

What it costs

A plain step is one command. An optimised step is one step of an interpreter that folds runs of the same command and flat loops. Choose the values and watch the two bars; What costs what explains how cost is counted:

The figure needs JavaScript. The table below has the measured steps.

Cost as a formula, and measured
Table 1. The cost as a function of the values.
FormPlain stepsOptimised steps
Two lines from the inputgrows with the letter codes19 + 12 per letter when the lines are equal
Table 2. Measured when this page was written.
FormValuesBitsCharactersPlain stepsOptimised steps
Two lines from the inputfirst line = "tea"; second line = "tea"82302,76155
Two lines from the inputfirst line = "tea"; second line = "ten"82303,29859
Two lines from the inputfirst line = "tea"; second line = "teapot"82306,08288

Where it is used

Sources

Every program on this page was run on many inputs, in plain and in optimised mode, and compared with JavaScript. The explanations are written for this page.