5
$\begingroup$

When sorting a list of Japanese strings rendered in either hiragana or katakana, one convention is to sort them in gojūon order. This is the convention imposed by AlphabeticSort, as shown by the snippet AlphabeticSort[RandomSample[Alphabet[Language -> "Hiragana"]], Language -> "Hiragana"] (and similarly for Language -> "Katakana").

Is it possible to modify AlphabeticSort so that strings are sorted in iroha order instead? Alternatively, what else can be used so that one can sort strings in iroha order?

$\endgroup$
4
$\begingroup$

To sort words lexicographically according to some alphabet, one can use SortBy where the key used for a given word is a list of the ranks of its letters in the given alphabet. Lookup deals with unknown letters; I've supplied the default argument 0 which means unknown letters are before everything else in the alphabet. I also PadRight to a given length because Mathematica sorts {5} before {1, 2, 3}.

ClearAll[SortByAlphabet];
SortByAlphabet[words : {___String}, alphabet : {___String}] :=
  With[{
    letterranks = Association[Table[alphabet[[i]] -> i,
                                    {i, Length[alphabet]}]],
    length = Max[StringLength /@ words]},
   SortBy[words, 
    PadRight[
      Lookup[letterranks, Characters[ToLowerCase[#]], 0], 
      length] &]];

then use for instance as

SortByAlphabet[{"hello", "world", "this", "code", "is",
  "in", "mathematica", "or", "perhaps", "i", "should",
  "call", "that", "the", "wolfram", "language"}, 
  Join[CharacterRange["n", "z"], CharacterRange["a", "m"]]]

Result:

{"or", "perhaps", "should", "that", "the", "this",
"world", "wolfram", "code", "call", "hello", "i",
"in", "is", "language", "mathematica"}
$\endgroup$

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.