gpt4 book ai didi

arrays - ruby 字母数字排序未按预期工作

转载 作者:行者123 更新时间:2023-12-02 20:59:30 28 4
gpt4 key购买 nike

给定以下数组:

y = %w[A1 A2 B5 B12 A6 A8 B10 B3 B4 B8]
=> ["A1", "A2", "B5", "B12", "A6", "A8", "B10", "B3", "B4", "B8"]

预期的排序数组为:

=> ["A1", "A2", "A6", "A8", "B3", "B4", "B5", "B8", "B10", "B12"]

使用以下(普通)排序,我得到:

irb(main):2557:0> y.sort{|a,b| puts "%s <=> %s = %s\n" % [a, b, a <=> b]; a <=> b}
A1 <=> A8 = -1
A8 <=> B8 = -1
A2 <=> A8 = -1
B5 <=> A8 = 1
B4 <=> A8 = 1
B3 <=> A8 = 1
B10 <=> A8 = 1
B12 <=> A8 = 1
A6 <=> A8 = -1
A1 <=> A2 = -1
A2 <=> A6 = -1
B12 <=> B3 = -1
B3 <=> B8 = -1
B5 <=> B3 = 1
B4 <=> B3 = 1
B10 <=> B3 = -1 # this appears to be wrong, looks like 1 is being compared, not 10.
B12 <=> B10 = 1
B5 <=> B4 = 1
B4 <=> B8 = -1
B5 <=> B8 = -1
=> ["A1", "A2", "A6", "A8", "B10", "B12", "B3", "B4", "B5", "B8"]

...这显然不是我想要的。我知道我可以尝试先拆分 alpha,然后对数字进行排序,但似乎我不必这样做。

可能需要注意的是:我们现在只能使用 Ruby 1.8.7 :( 但即使 Ruby 2.0.0 也在做同样的事情。我在这里错过了什么?

建议?

最佳答案

您正在对字符串进行排序。字符串像字符串一样排序,而不是数字。如果你想对数字进行排序,那么你应该对数字进行排序,而不是对字符串进行排序。字符串 'B10' 按字典顺序比字符串 'B3' 小,这不是 Ruby 独有的东西,甚至不是编程独有的东西,这就是按字典顺序对片段进行排序的方式文本几乎无处不在,在编程、数据库、词典、词典、电话簿等中。

您应该将字符串拆分为数字和非数字部分,并将数字部分转换为数字。数组排序是按字典顺序排序的,因此最终排序会完全正确:

y.sort_by {|s| # use `sort_by` for a keyed sort, not `sort`
s.
split(/(\d+)/). # split numeric parts from non-numeric
map {|s| # the below parses numeric parts as decimals, ignores the rest
begin Integer(s, 10); rescue ArgumentError; s end }}
#=> ["A1", "A2", "A6", "A8", "B3", "B4", "B5", "B8", "B10", "B12"]

关于arrays - ruby 字母数字排序未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39023861/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com