Last active
February 27, 2017 01:48
-
-
Save manhdaovan/fad64e614ae4e091c0ffaff45aba9016 to your computer and use it in GitHub Desktop.
Compare Vietnamese string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def string_2array(s) | |
s.split('') | |
end | |
# return 1 if s2 > s1 | |
# return 0 if s2 == s1 | |
# return -1 if s2 < s1 | |
def my_compare(s1, s2) | |
downcase_letters = ' aàáảãạăằắẳẵặâầấẩẫậbcdđeèéẻẽẹêềếểễệfghiìíỉĩịjklmnoòóỏõọôồốổỗộơờớởỡợpqrstuùúủũụưừứửữựvwxyỳýỷỹỵz'.freeze | |
upcase_letters = 'AÀÁẢÃẠĂẰẮẲẴẶÂẦẤẨẪẬBCDĐEÈÉẺẼẸÊỀẾỂỄỆFGHIÌÍỈĨỊJKLMNOÒÓỎÕỌÔỒỐỔỖỘƠỜỚỞỠỢPQRSTUÙÚỦŨỤƯỪỨỬỮỰVWXYỲÝỶỸỴZ'.freeze | |
hash_chars = {} | |
string_2array(downcase_letters + upcase_letters).each_with_index do |char, index| | |
hash_chars[char] = index | |
end | |
longer_string, shorter_string, keep_order = s1.length >= s2.length ? [s1, s2, true] : [s2, s1, false] | |
string_2array(longer_string).each_with_index do |char, index| | |
if shorter_string[index].nil? | |
return keep_order ? -1 : 1 | |
elsif hash_chars[char] > hash_chars[shorter_string[index]] | |
return keep_order ? -1 : 1 | |
elsif hash_chars[char] < hash_chars[shorter_string[index]] | |
return keep_order ? 1 : -1 | |
end | |
end | |
0 | |
end | |
puts my_compare('Lê Công Vinh', 'Nguyễn Công Phượng') # 1 | |
puts my_compare('Nguyễn Công Phượng', 'Lê Công Vinh') # -1 | |
puts my_compare('Lê Công Vinh', 'Lê Công Vinh') # 0 | |
puts my_compare('', 'Lê Công Vinh') # 1 | |
puts my_compare('Lê Công Vinh', '') # -1 | |
puts my_compare('', '') # 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment