Say I have an array of hash strings, e.g.
['a04a872ff4027233', '8cef496d2a92808c', etc.]
I would like an elegant way to determ开发者_C百科ine what is the shortest uniform-length substring I can use to differentiate between the alternatives.
E.g. if the shortest length substring is 3, then the options could be abbreviated to ['a04', '8ce', etc], and I could then just expand the abbreviation later.
I need a solution in Ruby.
(1...s.first.size).find {|i| !s.map {|j| j[0...i]}.uniq!}
Not very "elegant" per se, but this would work:
strings = ['a04a872ff4027233', '8cef496d2a92808c', .....]
count = 1
count += 1 while strings.map{ |item| item[0...count] }.uniq.length != strings.length
count
# => 3
strings.map{ |item| item[0...count] }
# => ['a04', '8ce', ...]
精彩评论