3
$\begingroup$

I'm trying to implement the solution to a math problem in Mathematica, but my code can't handle a particular boundary case. I think that I could implement a function that would do what I want it to, but it would be kind of ugly.

Here is the problem:

Here is the Math Problem (Mathematical Proofs, Chartrand, Polimeni, and Zhang)

letters = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l",
"m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"};

GetIndexInAlphabet[letter_String] := Position[letters, letter][[1, 1]];

GetIndexInAlphabet["a"] (* 1 *)

AofAlpha[letter_String] := Module[{startIndex, endIndex},
  startIndex = GetIndexInAlphabet[letter];
  endIndex = startIndex + 2;
  Take[letters, {startIndex, endIndex}]
];

AofAlpha["a"] (* {a, b, c} *)

AofAlpha["z"] (* {z, a, b} *)

Does anyone have a clean way to implement the wrapping behavior that the function should have?

$\endgroup$
2
$\begingroup$
x = Partition[letters, 3, 1, {1, 1}];

x[[1]]

{"a", "b", "c"}

x[[26]]

{"z", "a", "b"}

Generalization:

fun[letter_String, n_Integer] :=
 With[{cr = CharacterRange["a", "z"]},
  Partition[cr, n, 1, {1, 1}] [[ToCharacterCode[letter] - 96]] // Flatten] 

fun["y", 4]

{"y", "z", "a", "b"}

| improve this answer | |
$\endgroup$
  • $\begingroup$ Thank you! I see that Partition is the way to go here. Unfortunately, even Partition has kind of an ugly syntax having to define the {1,1} for the cyclic behavior, but sometimes that's the way it has to be. $\endgroup$ – Brady Hunt Sep 8 '14 at 16:01
4
$\begingroup$
S = First /@ Partition[CharacterRange["a", "z"], 3, 3, 1]
(* {"a", "d", "g", "j", "m", "p", "s", "v", "y"} *)

It's minimal because:

3*Length@S
(* 27 *)

and any $S$ with less cardinality will have at most $3*8= 24$ characters in it's union, so it won't cover the full letter set.

| improve this answer | |
$\endgroup$
  • $\begingroup$ Thank you as well @belisarius. I appreciate the added explanation of why it is minimal. Also, CharacterRange[] is very convenient for defining this set. $\endgroup$ – Brady Hunt Sep 8 '14 at 16:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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