1
$\begingroup$

What is the correct idiom for mapping the $0$ value in a modulo $n$ expression back to $n$.

For example if I want to be sure that any integer value maps back to the index for a character in the alphabet, I might use something like

letterIndex[l_]  = First@FirstPosition[ToUpperCase /@ Alphabet[], l];
letterIndex[l_, rot_] := Mod[letterIndex[l] + rot, 26] /. 0 -> 26;

But this look stupid to me and I feel like I'm missing something idiomatic to Mathematica (or to modular equivalences — which have always frustrated me — in general).

$\endgroup$
4
  • 2
    $\begingroup$ You mean Mod[{1, 2, 3, 4, 5, 6, 7}, 3, 1]? $\endgroup$
    – Kuba
    Apr 17, 2015 at 19:49
  • $\begingroup$ @Kuba: I don't get it? $\endgroup$
    – orome
    Apr 17, 2015 at 20:48
  • 1
    $\begingroup$ I mean Mod[x, 26]/.(0->26) can be done with Mod[x, 26, 1]. $\endgroup$
    – Kuba
    Apr 17, 2015 at 21:02
  • $\begingroup$ @Kuba: Duh! I should have looked a bit more closely at the doc! $\endgroup$
    – orome
    Apr 18, 2015 at 12:29

1 Answer 1

2
$\begingroup$

In addition to what I've said in comments, you can write your function in shorter form:

letterIndex2[l_, rot_: 0] := Mod[First@ToCharacterCode[l] - 64 + rot, 26, 1]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.