我尝试按字母顺序对一组字母进行排序,但将特殊字符保留在相同的位置,即拼音。
例如,
word = ["f", "a", "s", "t", "-", "c", "a", "r", "s"]
我如何才能按字母顺序对整个内容进行排序,同时又能保持"-“的位置。如果我按照现在的方式进行排序,那么"-“将会移到我不想要的前面。我已经尝试了15种不同的方法,但我都想不出来。你能帮上忙吗?
发布于 2021-04-26 13:40:46
一些非常冗长的方式来做这件事,来解释你需要实现的逻辑。有一些“更干净”的方法可以做到这一点,但我觉得这能让你更好地理解。
在数组中添加额外的特殊字符,以获得更好的测试覆盖率:
let(:input) { ["f", "a", "s", "t", "-", "c", "a", "r", "s", "/"] }
let(:desired_output) { ["a", "a", "c", "f", "-", "r", "s", "s", "t", "/"] }
it "takes the input and gives the desired output" do
expect(sort_alphanumeric_characters(input)).to eq(desired_output)
end
在数组上调用.map
和.select
以枚举值,然后调用.with_index
,因为稍后需要保留索引。
def sort_alphanumeric_characters(word_as_array)
# assuming you mean non-alphanumeric
# collect those indicies which are 'special' characters
# the regex matches the string with anything outside of the alphanumeric range. Note the '^'
special_character_indicies = word_as_array.map.with_index { |val, indx| indx if val =~ /[^a-zA-Z0-9]/ }.compact
# collect all characters by index that were not yielded as 'special'
alphanumeric_array = word_as_array.select.with_index { |char, indx| char unless special_character_indicies.include? indx }
# sort the alphanumeric array
sorted_alphanumeric_array = alphanumeric_array.sort
# use Array#insert to place the 'special' by index
special_character_indicies.each do |special_indx|
special_char = word_as_array[special_indx]
sorted_alphanumeric_array.insert(special_indx, special_char)
end
# return desired output
sorted_alphanumeric_array
end
发布于 2021-04-26 14:10:24
当我发布的时候,我有了一个闪电(当它发生的时候,我喜欢它)。这真的不是一个很好的解决方案,但它确实起作用了!
def scramble_words(str)
idx = 0
chars = str.delete("^a-z").chars
first_ele = chars.shift
last_ele = chars.pop
str.chars.each_with_index {|c, i| idx = i if c =~ /[^a-z" "]/ }
(first_ele + chars.sort.join + last_ele).insert(idx, str[idx])
end
p scramble_words('card-carrying') == 'caac-dinrrryg'
p scramble_words("shan't") == "sahn't"
p scramble_words('-dcba') == '-dbca'
https://stackoverflow.com/questions/67261215
复制相似问题