EDITED to sort the input stream using a bubble sort (the macro \bubblesort
can be used independently of the \compactthis
macro, if desired).
A \listterminator
must be set to ANY numerical value known not to be in the list (e.g., suitably large, negative, zero, etc.), currently set at 9999
. As shown (both in code and demonstrated in the MWE), the macro \adjtie
can be set to --
if 1--2
is preferred to 1, 2
for adjacent limiting entries.
No packages required.
\documentclass{article}
%
% THIS CODE CAN \bubblesort A NUMBERED LIST AND THEN \compactthis LIST IN THE MANNER
% OF 1-3, 7, 11-13
%
\def\listterminator{9999}% SET TO *ANY* VALUE KNOWN NOT TO BE IN LIST (POSITIVE OR NEGATIVE)
\def\adjtie{, }
%\def\adjtie{--}% OPTIONAL IF 1--2 preferred over 1, 2
\newcommand\compactthis[1]{%
\bubblesort{#1}%
\expandafter\begincompaction\sortedlist,\listterminator,\relax%
}
\def\begincompaction#1,#2\relax{%
\def\startlist{#1}%
\def\currentendlist{#1}%
\findendlist#2\relax%
}
\def\findendlist#1,#2\relax{%
\ifnum\numexpr\currentendlist+1\relax=#1\relax%
\def\currentendlist{#1}%
\findendlist#2\relax%
\else%
\ifnum\startlist=\currentendlist\relax%
\ignorespaces\startlist\unskip%
\else%
\ifnum\numexpr\startlist+1\relax=\currentendlist\relax%
\ignorespaces\startlist\unskip\adjtie\ignorespaces\currentendlist\unskip%
\else%
\ignorespaces\startlist\unskip--\ignorespaces\currentendlist\unskip%
\fi%
\fi%
\ifnum#1=\listterminator\else,\ \begincompaction#1,#2\relax\fi%
\fi%
}
\newcommand\bubblesort[1]{\def\sortedlist{}\sortlist#1,\listterminator,\relax}
\def\sortlist#1,#2,#3\relax{%
\ifnum#2=\listterminator\relax%
\edef\sortedlist{\sortedlist#1}%
\else
\ifnum#1<#2\relax%
\edef\sortedlist{\sortedlist#1,}%
\sortlist#2,#3\relax%
\else%
\let\tmp\sortedlist%
\def\sortedlist{}%
\expandafter\sortlist\tmp#2,#1,#3\relax%
\fi%
\fi%
}
\begin{document}
Bubble Sort Demonstration:
\bubblesort{1,2,11, 7, 4, 3}\sortedlist\par
\compactthis{1,2,3,4,5,7,8,9, 11}\par
\compactthis{1,2, 12 ,13 ,18, 20} (single member)\par
\compactthis{1,2, 12,13,18, 19, 20} (range at end)\par
\def\adjtie{--}\compactthis{1,2, 12,13,18, 19, 20} (\verb|\adjtie| set to {--})\par
\compactthis{1,2,11, 7, 4, 3, 12, 14, 13} (unsorted input)
\end{document}
