Visualization in LaTeX of hamming distance
You can construct a macro that iterates over input, reading one token at a time. Then you compare the token to 0
or 1
and decide what to do. The commands \zero
and \one
are responsible for the actual typesetting.
\documentclass{article}
\usepackage{calc}
\usepackage{xcolor}
\newcommand{\zero}{\fbox{\textcolor{red}{0}}}
\newcommand{\onea}{\fbox{\rule{0pt}{1em}\textcolor{blue}{1}}}
\newcommand{\oneb}{\fbox{\rule[\heightof{1}-1em]{0pt}{\heightof{1}}\textcolor{blue}{1}}}
\newcommand{\process}[1]{%
\begingroup
\def\next##1{%
\ifx##1\relax
\let\next=\relax
\else
\if0##1%
\zero
\else\if1##1%
\one
\else
unknown
\fi\fi
\fi
\next}%
\next #1\relax
\endgroup}
\newcommand{\processa}{\let\one=\onea \process}
\newcommand{\processb}{\let\one=\oneb \process}
\begin{document}
Test: \processa{101010}
Test: \processb{101010}
\end{document}
Here is a solution using the listings package. Is this close to what you want?
\documentclass{article}
\usepackage{listings}
\usepackage{xcolor}
\lstdefinestyle{hama}{%
literate={1}{\raisebox{0.5ex}{\fbox{\textcolor{blue}{1}}}}{1}%
{0}{\fbox{\textcolor{red}{0}}}{1},%
basicstyle=\ttfamily,%
}
\lstdefinestyle{hamb}{%
literate={0}{\raisebox{0.5ex}{\fbox{\textcolor{blue}{0}}}}{1}%
{1}{\fbox{\textcolor{red}{1}}}{1},%
basicstyle=\ttfamily,%
}
\newcommand{\HAMA}[1]{%
\lstinline[style=hama]{#1}%
}
\newcommand{\HAMB}[1]{%
\lstinline[style=hamb]{#1}%
}
\begin{document}
\HAMA{00101101}
\HAMB{00100100}
\end{document}
This solution is adapted this question typesetting different characters with different colors in a DNA sequence, which also has several other methods which may be helpful.
there are three optional arguments: <position> <color 0> <color 1>
.
they are counted from the left, if you want to define the <color 1>
then you have to specify the two in front, too.
\documentclass{article}
\usepackage{xcolor}
\makeatletter
\def\0{\fbox{\textcolor{\process@colA}{0}}}
\def\1{\fbox{\process@rule\textcolor{\process@colB}{1}}}
\def\process@iv#1{%
\begingroup
\def\next##1{%
\ifx##1\relax
\let\next=\relax
\else
\ifx0##1\0\else\ifx1##1\1\else?\fi\fi
\fi
\next}%
\next #1\relax
\endgroup}
\def\process{\@ifnextchar[\process@i{\process@iii[b][red][blue]}}
\def\process@i[#1]{\@ifnextchar[{\process@ii[#1]}{\process@iii[#1][red][blue]}}
\def\process@ii[#1][#2]{\@ifnextchar[{\process@iii[#1][#2]}{\process@iii[#1][#2][blue]}}
\def\process@iii[#1][#2][#3]{%
\ifx#1b\def\process@rule{\rule{0pt}{3ex}}%
\else\def\process@rule{\rule[-1ex]{0pt}{2ex}}\fi%
\def\process@colA{#2}%
\def\process@colB{#3}%
\process@iv}
\makeatother
\parindent=0pt
\begin{document}
Test: \process{101010}\\
Test: \process[t]{101010}\\
Test: \process[b][yellow][cyan!80!blue]{101010}\\
Test: \process[t][magenta][gray]{101010}\\
Test \process{100200}
\end{document}