我有一個如下所示的陣列
[["GJ","MP"],["HR","MH"],["MP","KL"],["KL","HR"]]
我想要如下結果
"GJ, MP, KL, HR, MH"
["GJ","MP"]
添加的陣列的第一個元素在answer_string = "GJ, MP"
Now FindMP中,這是該陣列的最后一個元素,在另一個位置應該是第一個元素["MP","KL"]
,這樣我必須添加KL到answer_string = "GJ, MP, KL"
這就是我想要的輸出
uj5u.com熱心網友回復:
鑒于
ary = [["GJ","MP"],["HR","MH"],["MP","KL"],["KL","HR"]]
(每個元素實際上是您需要遍歷的簡單圖形中的一條邊)您的任務可以用一種非常直接的方式解決:
acc = ary.first.dup
ary.size.times do
# Find an edge whose "from" value is equal to the latest "to" one
next_edge = ary.find { |a, _| a == acc.last }
acc << next_edge.last if next_edge
end
acc
#=> ["GJ", "MP", "KL", "HR", "MH"]
這里的壞處是它的二次時間(你在每次迭代中搜索整個陣列)如果初始陣列足夠大,它會嚴重打擊你。使用一些具有更快查找速度的輔助資料結構(例如哈希)會更快。… 喜歡
head, *tail = ary
edges = tail.to_h
tail.reduce(head.dup) { |acc, (k, v)| acc << edges[acc.last] }
#=> ["GJ", "MP", "KL", "HR", "MH"]
(我沒有將結果陣列連接成一個字串,但這有點簡單)
uj5u.com熱心網友回復:
d = [["GJ","MP"],["HR","MH"],["MP","KL"],["KL","HR"]]
o = [] # List for output
c = d[0][0] # Save the current first object
loop do # Keep looping through until there are no matching pairs
o.push(c) # Push the current first object to the output
n = d.index { |a| a[0] == c } # Get the index of the first matched pair of the current `c`
break if n == nil # If there are no found index, we've essentially gotten to the end of the graph
c = d[n][1] # Update the current first object
end
puts o.join(',') # Join the results
隨著問題發生巨大變化而更新。本質上,您是在瀏覽圖表。
uj5u.com熱心網友回復:
我arr.size.times用來回圈
def check arr
new_arr = arr.first #new_arr = ["GJ","MP"]
arr.delete_at(0) # remove the first of arr. arr = [["HR","MH"],["MP","KL"],["KL","HR"]]
arr.size.times do
find = arr.find {|e| e.first == new_arr.last}
new_arr << find.last if find
end
new_arr.join(',')
end
array = [["GJ","MP"],["HR","MH"],["MP","KL"],["KL","HR"]]
p check(array)
#=> "GJ,MP,KL,HR,MH"
uj5u.com熱心網友回復:
假設:
a是一個Array還是一個Hasha是原始帖子中提供的表格- 對于每個元素
b都是ab[0]唯一的
我要做的第一件事是,如果a是Array,則轉換a為Hash以便更快地查找(這在技術上不是必需的,但它簡化了實作并應該提高性能)
a = [["GJ","MP"],["HR","MH"],["MP","KL"],["KL","HR"]]
a.to_h
#=> {"GJ"=>"MP", "HR"=>"MH", "MP"=>"KL", "KL"=>"HR"}
更新 如果路徑總是從鏈的頭到尾并且元素總是完整的鏈,那么借鑒@KonstantinStrukov的 靈感:(如果你更喜歡這個選項,那么請給他信用??)
a.to_h.then {|edges| edges.reduce { |acc,_| acc << edges[acc.last] }}.join(",")
#=> "GJ,MP,KL,HR,MH"
警告:如果原始結果中存在斷開連接的元素,則此結果將包含nil(表示為尾隨逗號)。這可以通過添加來解決,Array#compact但它也會導致對每個斷開連接的元素進行不必要的遍歷。
ORIGINAL
我們可以使用遞回方法來查找從給定鍵到路徑末尾的路徑。默認鍵是a[0][0]
def navigate(h,from:h.keys.first)
return unless h.key?(from)
[from, *navigate(h,from:h[from]) || h[from]].join(",")
end
解釋:
navigation(h,from:h.keys.first)- 要遍歷的哈希和遍歷的起點return unless h.key?(key)如果Hash不包含from密鑰回傳nil(鏈的末端)[from, *navigate(h,from:h[from]) || h[from]].join(",")- 構建一個Array鍵from和查找該鍵值的遞回結果(from如果遞回回傳)nil然后附加最后一個值。然后簡單地將 the 轉換Array為 aString用逗號連接元素。
用法:
a = [["GJ","MP"],["HR","MH"],["MP","KL"],["KL","HR"]].to_h
navigate(a)
#=> "GJ,MP,KL,HR,MH"
navigate(a,from: "KL")
#=> "KL,HR,MH"
navigate(a,from: "X")
#=> nil
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/535327.html
上一篇:如何根據鍵迭代物件并洗掉其余專案
下一篇:我需要列印一個二維字符陣列
