Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
82 views
in Technique[技术] by (71.8m points)

Ruby Alphabet sorting

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There should be no need for a hacky method, sort is flexible enough.

Your code currently compares s1 to s2 using default Ruby's comparison (<=>). I believe you should compare lengths of s1 and s2 first, returning alphabetical comparison when the lengths are equal.

Another approach is to group the input array by size, then sort each chunk independently, then flatten the array. Something along the lines of:

input_array.group_by(&:size).sort.map(&:last).map(&:sort).flatten

which seems to work like this:

irb(main):025:0> ["defg", "c", "cd", "cc", "cca", "ccb"].group_by(&:size).sort.map(&:last).map(&:sort).flatten
=> ["c", "cc", "cd", "cca", "ccb", "defg"]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...