1
$\begingroup$

Say you have the following list of 12 elements

X={"x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x"}

And I want to turn it into the following sorted list:

{"x1", "x10", "x11", "x12", "x2", "x3", "x4", "x5", "x6", "x7", "x8", "x9"}

How do I achieve this? I've tried numerous methods such as using a "Print[]" within a For loop and StringReplace but I haven't figured it out. I'm new to mathematica. Thanks in advance for the help!

$\endgroup$
  • $\begingroup$ Hi,brother or sister.If I have help you to solve this problem,click the check that left in my answer. $\endgroup$ – yode Mar 16 '16 at 1:35
  • $\begingroup$ Welcome to Mathematica.SE! I suggest the following: 1) As you receive help, try to give it too, by answering questions in your area of expertise. 2) Take the tour! 3) When you see good questions and answers, vote them up by clicking the gray triangles, because the credibility of the system is based on the reputation gained by users sharing their knowledge. Also, please remember to accept the answer, if any, that solves your problem, by clicking the checkmark sign! $\endgroup$ – Michael E2 Mar 16 '16 at 1:51
  • $\begingroup$ Sort@Table["x" <> IntegerString[i], {i, 1, 12}] $\endgroup$ – user1066 Mar 16 '16 at 10:00
4
$\begingroup$

Basically, the problem is to join each element in the list with its index. The MapIndexed function is handy for this.

The function to apply for each element is a straightforward StringJoin:

f[x,y]=x<>ToString[y]

Overall, the solution is

Sort@MapIndexed[#1 <> ToString[First[#2]] &, X]

{"x1", "x10", "x11", "x12", "x2", "x3", "x4", "x5", "x6", "x7", "x8", "x9"}

|improve this answer|||||
$\endgroup$
3
$\begingroup$
X = {"x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x", "x"};
n = IntegerString@Range@Length@X;
Sort@MapThread[StringJoin, {X, n}]

{"x1", "x10", "x11", "x12", "x2", "x3", "x4", "x5", "x6", "x7", "x8", "x9"}

Actually,I can tell you another secret to this

Sort@Table[TemplateApply["x<*i*>"], {i, 12}]

{"x1", "x10", "x11", "x12", "x2", "x3", "x4", "x5", "x6", "x7", "x8", "x9"}

|improve this answer|||||
$\endgroup$
  • $\begingroup$ With[ {lst = Table["x", {12}]}, StringJoin[lst[[#]], IntegerString[#, 10, 2]] & /@ Range[Length@lst] ] will get you what you want if sorting is critical. $\endgroup$ – dwa Mar 16 '16 at 2:16
  • $\begingroup$ @dwa Thanks for your good suggestion~ $\endgroup$ – yode Mar 16 '16 at 2:21
2
$\begingroup$

Note you could just do:

Sort["x" <> ToString[#] & /@ Range[12]]

If you have list you can also use MapIndexed:

xs = ConstantArray["x", 12];
Sort@MapIndexed[#1 <> ToString[#2[[1]]] &, xs]
|improve this answer|||||
$\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.