我有一個混合元素陣列,例如整數和字串:
ary = [3, "foo", 2, 5, "bar", 1, "baz", 4]
我想應用一種排序,但只適用于特定元素。在上面的例子中,要排序的元素是整數(但它可以是任何東西)。然而,即使它們應該被排序,它們也必須停留在它們的“整數點”中。并且琴弦必須保持在它們的確切位置。
排序應該像這樣作業:
[3, "foo", 2, 5, "bar", 1, "baz", 4] # before
[1, "foo", 2, 3, "bar", 4, "baz", 5] # after
"foo"仍處于索引 1,"bar"處于索引 4,"baz"處于索引 6。
我可以將陣列劃分為整數和非整數以及它們的位置:
a, b = ary.each_with_index.partition { |e, i| e.is_a?(Integer) }
a #=> [[3, 0], [2, 2], [5, 3], [1, 5], [4, 7]]
b #=> [["foo", 1], ["bar", 4], ["baz", 6]]
對整數進行排序:
result = a.map(&:first).sort
#=>[1, 2, 3, 4, 5]
并在其原始位置重新插入非整數:
b.each { |e, i| result.insert(i, e) }
result
#=> [1, "foo", 2, 3, "bar", 4, "baz", 5]
但這似乎相當笨拙。我特別不喜歡一次一個字串地解構和重建陣列。有沒有更優雅或更直接的方法?
uj5u.com熱心網友回復:
可能的解決方案
ary = [3, "foo", 2, 5, "bar", 1, "baz", 4]
integers = ary.select(&->(el) { el.is_a?(Integer) }).sort
ary.map { |n| n.is_a?(Integer) ? integers.shift : n }
# => [1, "foo", 2, 3, "bar", 4, "baz", 5]
uj5u.com熱心網友回復:
我不精通Ruby。雖然我想試一試我能想到的。
我的評論中提到了這個想法。
- 獲取整數的索引
- 對索引的值進行排序
- 將排序后的值插入陣列
ary = [3, "foo", 2, 5, "bar", 1, "baz", 4]
=> [3, "foo", 2, 5, "bar", 1, "baz", 4]
indices = ary.map.with_index { |item,idx| idx if item.is_a?(Integer) }.compact
=> [0, 2, 3, 5, 7]
values = ary.values_at(*indices).sort
=> [1, 2, 3, 4, 5]
indices.zip(values).each { |idx, val| ary[idx]=val}
=> [[0, 1], [2, 2], [3, 3], [5, 4], [7, 5]]
ary
=> [1, "foo", 2, 3, "bar", 4, "baz", 5]
uj5u.com熱心網友回復:
我假設,如示例所示, ifarr = ary.dup和arris modifiedary不會發生突變。如果不是這種情況,則必須使用ary.
幫手:
def sort_object?(e)
e.class == Integer
end
sort_object?(3)
#=> true
sort_object?(-3e2)
#=> true
sort_object?("foo")
#=> false
ary = [3, "foo", 2, 5, "bar", 1, "baz", 4]
obj_to_idx = ary.zip((0..ary.size-1).to_a).to_h
#=> {3=>0, "foo"=>1, 2=>2, 5=>3, "bar"=>4, 1=>5, "baz"=>6, 4=>7}
to_sort = ary.select { |k| sort_object?(k) }
#=> [3, 2, 5, 1, 4]
sorted = to_sort.sort
#=> [1, 2, 3, 4, 5]
new_idx_to_orig_idx = to_sort.map { |n| obj_to_idx[n] }
.zip(sorted.map { |n| obj_to_idx[n] })
.to_h
#=> {0=>5, 2=>2, 3=>0, 5=>7, 7=>3}
new_idx_to_orig_idx.each_with_object(ary.dup) do |(new_idx,orig_idx),a|
a[new_idx] = ary[orig_idx]
end
#=> [1, "foo", 2, 3, "bar", 4, "baz", 5]
如果需要,其中一些陳述句當然可以鏈接起來。
uj5u.com熱心網友回復:
指定陣列索引的就地重新分配
你當然可以讓它更短,甚至可以跳過與 Hash 物件之間的轉換,但中間步驟是為了展示我的思維程序,使意圖更明確,除錯更容易一些。考慮以下:
ary = [3, "foo", 2, 5, "bar", 1, "baz", 4]
ints = ary.each_with_index.select { |elem, idx| [elem, idx] if elem.kind_of? Integer }.to_h
ordered_ints = ints.keys.sort.zip(ints.values).to_h
ints.keys.sort.zip(ints.values).each { |elem, idx| ary[idx] = elem }
ary
#=> [1, "foo", 2, 3, "bar", 4, "baz", 5]
這里的想法是我們:
- 使用#each_with_index僅選擇我們想要排序的型別的專案,以及它們在當前 Array 中的索引。如果你不喜歡#kind_of?你可以用#respond_to 替換它嗎?或任何其他對您有意義的選擇標準。
- 對選定的陣列值進行排序,然后將它們與我們要修改的索引位置一起#zip 。
- 為需要替換的每個索引重新分配已排序的元素。
使用這種方法,所有未選擇的元素都保留在ary陣列中的原始索引位置。我們只是用重新排序的專案修改特定陣列索引的值。
uj5u.com熱心網友回復:
我也會把我的帽子扔進這個戒指。
似乎其他答案依賴于唯一性的假設,所以我通過建立位置音譯采取了不同的路線Hash
(更新:比必要的更進一步)
def sort_only(ary, sort_klass: Integer)
raise ArgumentError unless sort_klass.is_a?(Class) && sort_klass.respond_to?(:<=>)
# Construct a Hash of [Object,Position] => Object
translator = ary
.each_with_index
.with_object({}) {|a,obj| obj[a] = a.first}
.tap do |t|
# select the keys where the value (original element) is a sort_klass
t.filter_map {|k,v| k if v.is_a?(sort_klass)}
.then do |h|
# sort them and then remap these keys to point at the sorted value
h.sort.each_with_index do |(k,_),idx|
t[h[idx]] = k
end
end
end
# loop through the original array with its position index and use
# the transliteration Hash to place them in the correct order
ary.map.with_index {|a,i| translator[[a,i]]}
end
示例:(作業示例)
sort_only([3, "foo", 2, 5, "bar", 1, "baz", 4])
#=> [1, "foo", 2, 3, "bar", 4, "baz", 5]
sort_only([3, 3, "foo", 2, 5, "bar", 1, "baz",12.0,5,Object, 4,"foo", 7, -1, "qux"])
#=> [-1, 1, "foo", 2, 3, "bar", 3, "baz", 12.0, 4, Object, 5, "foo", 5, 7, "qux"]
sort_only([3, "foo", 2, 5,"qux", "bar", 1, "baz", 4], sort_klass: String)
#=> [3, "bar", 2, 5, "baz", "foo", 1, "qux", 4]
作為參考,第二個示例產生以下音譯:
{[3, 0]=>-1, [3, 1]=>1, ["foo", 2]=>"foo", [2, 3]=>2, [5, 4]=>3,
["bar", 5]=>"bar", [1, 6]=>3, ["baz", 7]=>"baz", [12.0, 8]=>12.0,
[5, 9]=>4, [Object, 10]=>Object, [4, 11]=>5, ["foo", 12]=>"foo",
[7, 13]=>5, [-1, 14]=>7, ["qux", 15]=>"qux"}
uj5u.com熱心網友回復:
下面的代碼只是創建了兩個新陣列:numbers和others. numbers是Integer來自原始陣列的實體,稍后按降序排序。others看起來像原始陣列,但數字點替換為nil. 最后將排序的數字推nil到點
arr.inject([[], []]) do |acc, el|
el.is_a?(Integer) ? (acc[0]<<el; acc[1]<<nil) : acc[1]<<el; acc
end.tap do |titself|
numbers = titself[0].sort_by {|e| -e }
titself[1].each_with_index do |u, i|
titself[1][i] = numbers.pop unless u
end
end.last
uj5u.com熱心網友回復:
我將在這里用另一種方法來回答我自己的問題。該解決方案將大部分作業委托給 Ruby 的內置方法,并盡可能避免顯式塊/回圈。
從輸入陣列開始:
ary = [3, "foo", 2, 5, "bar", 1, "baz", 4]
您可以構建對的哈希position => element:
hash = ary.each_index.zip(ary).to_h
#=> {0=>3, 1=>"foo", 2=>2, 3=>5, 4=>"bar", 5=>1, 6=>"baz", 7=>4}
提取具有整數值的對:(或您想要排序的任何內容)
ints_hash = hash.select { |k, v| v.is_a?(Integer) }
#=> {0=>3, 2=>2, 3=>5, 5=>1, 7=>4}
對它們的值進行排序:(任何你想要的方式)
sorted_ints = ints_hash.values.sort
#=> [1, 2, 3, 4, 5]
為排序后的值建立一個新的映射:
sorted_ints_hash = ints_hash.keys.zip(sorted_ints).to_h
#=> {0=>1, 2=>2, 3=>3, 5=>4, 7=>5}
更新位置哈希:
hash.merge!(sorted_ints_hash)
#=> {0=>1, 1=>"foo", 2=>2, 3=>3, 4=>"bar", 5=>4, 6=>"baz", 7=>5}
瞧:
hash.values
#=> [1, "foo", 2, 3, "bar", 4, "baz", 5]
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/495320.html
上一篇:使用光纖時的意外結果
