I was going through some questions on HackerRank, that need to sort data a substring alphabetically "the shortest comes first"
for example
["cd","cc","cca", "ccb"]
the expected output should be
["cca","ccb","cc","cd"]
my output is shown as follows
["cc","cca","ccb","cd"]
using the following simple code
substring.sort! {|s1,s2| s1 <=> s2 }
my question is how can I make the sort to match the expected output.
I was thinking if I can make the string have the same size and append a large value at the end of the string then I can match the expected output but then I have to clean up the strings afterward.
I am not sure if it is possible in ruby to solve it without a hacky method.
please give me your suggestions.
EDIT
Sorry if it was not clear. basically, the algorithm they are using is checking the first letter from the first string and compare it with the second string. if they are the same it will move to the next letter of each string.. and so on... the trick is if they are no the same size it will always sort the shorter string as bigger than the longer if the last letter of the small string is the same as the second string. I will need to give more examples to clarify.
Example 1
["aac","aa","c","cd","da","a","bb","bd"]
Expected output is
["aac","aa","a","bb","bd","c","cd","da"]
Example 2
["d","ca","cb","cc","cca","ccb","ccc"]
Expected output is
["ca","cb","cca","ccb","ccc","cc","d"]
I hope that is more clearer.
question from:
https://stackoverflow.com/questions/65936813/ruby-alphabet-sorting