首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何对数组中除特殊字符以外的所有内容进行排序- Ruby

如何对数组中除特殊字符以外的所有内容进行排序- Ruby
EN

Stack Overflow用户
提问于 2021-04-26 13:21:57
回答 2查看 90关注 0票数 2

我尝试按字母顺序对一组字母进行排序,但将特殊字符保留在相同的位置,即拼音。

例如,

word = ["f", "a", "s", "t", "-", "c", "a", "r", "s"]

我如何才能按字母顺序对整个内容进行排序,同时又能保持"-“的位置。如果我按照现在的方式进行排序,那么"-“将会移到我不想要的前面。我已经尝试了15种不同的方法,但我都想不出来。你能帮上忙吗?

EN

回答 2

Stack Overflow用户

发布于 2021-04-26 13:40:46

一些非常冗长的方式来做这件事,来解释你需要实现的逻辑。有一些“更干净”的方法可以做到这一点,但我觉得这能让你更好地理解。

在数组中添加额外的特殊字符,以获得更好的测试覆盖率:

代码语言:javascript
运行
复制
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,因为稍后需要保留索引。

代码语言:javascript
运行
复制
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
票数 1
EN

Stack Overflow用户

发布于 2021-04-26 14:10:24

当我发布的时候,我有了一个闪电(当它发生的时候,我喜欢它)。这真的不是一个很好的解决方案,但它确实起作用了!

代码语言:javascript
运行
复制
    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'
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67261215

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档