Prev: boolean variable with contours
Next: problems
From: David Bailey on 3 Jul 2010 08:19 On 02/07/10 07:54, S. B. Gray wrote: > I have strings like foo="623 715". foo will always be 3 digits, space, 3 > digits. I need to put each set of digits in numerical order and then put > the two triples in order. This would give 157 236. There must be a > simple way to do this, but I see nothing under string sorting. > This splits out the two 3-digit codes, splits these into individual characters using Characters[], and sorts the result before reassembling each string. Then I compare the numerical value of the two expressions, and return the appropriate ordering: In[3]:= foo = "623 715" Out[3]= "623 715" In[4]:= str1 = StringTake[foo, 3]; In[5]:= str2 = StringDrop[foo, 4]; In[9]:= str1 = StringJoin @@ Sort(a)Characters[str1] Out[9]= "236" In[10]:= str2 = StringJoin @@ Sort(a)Characters[str2] Out[10]= "157" In[11]:= If[ToExpression[str1] < ToExpression[str2], str1 <> " " <> str2, str2 <> " " <> str1] Out[11]= "157 236" Of course, you may want to join this code together into a single function, but it is nice to see the separate steps before creating a black box! David Bailey http://www.dbaileyconsultancy.co.uk
From: Bob Hanlon on 3 Jul 2010 08:20 mySort[str_String] := StringJoin @@ Insert[ Flatten[ Sort[ Sort /@ Characters /@ StringSplit[str]]], " ", 4] data = Table[ToString[ RandomInteger[{100, 999}]] <> " " <> ToString[RandomInteger[{100, 999}]], {5}] {299 945,918 889,275 396,938 962,947 461} mySort /@ data {299 459,189 889,257 369,269 389,146 479} Bob Hanlon ---- "S. B. Gray" <stevebg(a)ROADRUNNER.COM> wrote: ============= I have strings like foo="623 715". foo will always be 3 digits, space, 3 digits. I need to put each set of digits in numerical order and then put the two triples in order. This would give 157 236. There must be a simple way to do this, but I see nothing under string sorting. Steve Gray
From: Christoph Lhotka on 5 Jul 2010 06:00 hello, your code has the drawback to remove the 0, e.g. it will give "545 350" -> "35 455" I took care of that in my code, if you are interested... sortfoo = (StringJoin @@ # & /@ (Sort /@ IntegerDigits /@ ToExpression /@ StringSplit[#, " "] /. n_Integer :> ToString[n]) // Sort) /. {x_String, y_String} :> x <> " " <> y &; best regards, christoph On 03/07/2010 14:18, Dimitris Emmanoulopoulos wrote: > orderingstring[x_] := > StringReplace[ > StringTake[ > ToString[ > Sort[Map[FromDigits, > ToExpression[ > Map[Sort, > StringCases[StringSplit[x], DigitCharacter]]]]]], {2, -2}], > "," -> ""]
From: Murta on 5 Jul 2010 06:01
Well... there is my contribution.. str="623 715 812"; FromDigits/@Sort/@IntegerDigits/@ToExpression(a)StringSplit[str]//Sort {128,157,236} Another option to read de string is use that.. str="623 715 812"; FromDigits/@Sort/@IntegerDigits/@ImportString[str,"Table"][[1]]//Sort {128,157,236} Rodrigo Murta |