我试图按字母顺序对字母数组进行排序,但在ruby中,将特殊字符保持在同一位置。
例如,
word = ["f", "a", "s", "t", "-", "c", "a", "r", "s"]
我怎么能把整件事按字母顺序排序,但保留"-"如果我对它现在的状况进行排序-"我不想去前线。我试过十五种不同的方法,但我想不通。你能帮忙吗?
一些非常详细的方法,解释您需要实现的逻辑。有一些"更清洁"的方法可以实现这一点,但我觉得这能让人更好地理解。
为阵列添加额外的特殊字符以获得更好的测试覆盖率:
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
我一发帖就有了闪电(喜欢这种情况(。这真的不是一个很好的解决方案,但它确实奏效了!!
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'