[texhax] scrambled text

Paul Isambert zappathustra at free.fr
Sat Aug 25 08:49:22 CEST 2012


Daniel Greenhoe <dgreenhoe at gmail.com> a écrit:
> 
> Is there any way using LaTeX to pseudo-randomly scramble a text string?
> 
> For example is there any package with a command called, say \scramble
> such that the syntax
>   \scramble{blue} would produce something like eblu or uebl?

If you're using PDFTeX, then try code 1 below; if you happen to use
LuaTeX, try the much simpler code 2.

Best,
Paul

% Code 1
\newcount\letters
\newcount\random
\newcount\scratch
\def\endofword{\endofword}

\def\scramble#1{%
  \letters=0
  \countletters#1\endofword
  \extractletters{#1}%
  }

\def\countletters#1{%
  \unless\ifx #1\endofword
    \advance\letters 1
    \expandafter\countletters
  \fi
  }

\def\extractletters#1{%
  \advance\letters-1
  \def\rest{}%
  \ifnum\letters>0
    \random=\pdfuniformdeviate\numexpr\letters+1\relax
    \scratch=0
    \getletter#1\endofword%
  \else
    #1%
  \fi
  }

\def\getletter#1{%
  \ifnum\scratch=\random
    #1%
    \expandafter\getrestofword
  \else
    \advance\scratch 1
    \edef\rest{\rest#1}%
    \expandafter\getletter
  \fi
  }

\def\getrestofword#1\endofword{%
  \expandafter\extractletters\expandafter{\rest#1}%
  }

\scramble{scramble}
% End of code 1

% Code 2
\bgroup
\catcode`\#=12 \catcode`\?=6
\gdef\scramble?1{%
  \directlua{%
    local str = string.explode("\luaescapestring{?1}", "")
    local out = ""
    while #str > 0 do
      out = out .. table.remove(str, math.random(#str))
    end
    tex.print(out)
    }%
  }
\egroup

\scramble{scramble}
% End of code 2



More information about the texhax mailing list