在红宝石使用哈希样的正确方法(correct way of using hash sort in r

2019-09-23 22:43发布

我是新来的Ruby和我试图写一个函数的Dijkstra但我的哈希排序似乎并没有在所有的工作

def distance(start_code, end_code, map)
#initialize hash for distance 
#distance are initialized to -1
dist_hash=Hash.new()
start_hash=Hash.new()
parent_hash=Hash.new()
close_list=Array.new()
find=-1
map.citylist.each do |e|
  dist_hash[e]=[+1.0/0.0]
end

start_hash[start_code]=0
parent_hash[start_code]=start_code

while (start_hash.empty?)==false


   #sort the hash
  start_hash.sort_by {|k,v| v}
  puts 'value'      
  puts start_hash.values()  
   #pop the first item in the hash
  h=start_hash.shift()
  curr_key=h[0]
  curr_val=h[1]
  curr_city=map.findcity(curr_key)
  close_list<<curr_city.code

   #for every one in adjacent list
  curr_city.get_adj_city().each do |e|


     #if it in the close list then igonore
    if close_list.include?(e)==false  
       #if it is not in the start_hash then add to start hash
      if start_hash.has_key?(e)==false
        dist=map.adj_dist(curr_city.code, e)
        dist=dist+curr_val
        start_hash[e]=dist
        parent_hash[e]=curr_city.code
       #if it is in the start_hash check if we have better distance
      else
        dist=map.adj_dist(curr_city.code, e)
        if (dist+curr_val)<start_hash[e]
          parent_hash[e]=curr_city.code
          start_hash[e]=dist
        end
      end
       #end pf checking single adj city
    end
     #end of check if include in close


  end
   #end of check whole list

  if curr_city.code==end_code
    find=0
    break
  end

end
#end of check node
#result
if find==0
  ptr=end_code
  puts ptr
  puts "final list"

  while ptr!=start_code
    ptr=parent_hash[ptr]
    puts ptr
  end
  return 0
else
  return -1
end

结束

当我试图调用d.distance(“积屑瘤”,“新浪”,图)

输出看起来像

value
0
value
1680
4651
value
10053
8047
4651
value
11094
15839
15839
8047
4651
10779
....

hash.sort_by后的权利,但没有排序的值被打印出来。 我是否正确使用方法?

Answer 1:

hash.sort_by后的权利,但没有排序的值被打印出来。 我是否正确使用方法?

No.当我不知道事情是如何工作的,我打开了IRB并尝试与它的几件事情:

hash = {a:1, b:2, c:4, d: 3}
=> {:a=>1, :b=>2, :c=>4, :d=>3}
hash.sort
=> [[:a, 1], [:b, 2], [:c, 4], [:d, 3]]
hash
=> {:a=>1, :b=>2, :c=>4, :d=>3}
hash.sort_by{|k,v| v }
=> [[:a, 1], [:b, 2], [:d, 3], [:c, 4]]
hash
=> {:a=>1, :b=>2, :c=>4, :d=>3}

sort_by不会改变的哈希值,它返回一个结果。 尝试:

散列= hash.sort_by {| K,V | V}#< -不使用此,它是一个数组,你会误导任何人读取这些代码。

sorted_tuples = hash.sort_by{|k,v| v }

或者类似的东西。



Answer 2:

Ruby 1.9的其实已经下令哈希值,所以如果你想继续在排序结果作为哈希工作,你可以简单地再次打开数组哈希:

h = {:a=>1, :c=>3, :b=>5, :d=>2}      # => {:a=>1, :c=>3, :b=>5, :d=>2}
h_sorted = Hash[h.sort_by{|k,v| v}]   # => {:a=>1, :d=>2, :c=>3, :b=>5}


Answer 3:

尝试这个

hash = {
  "fred" => 23,
  "joan" => 18,
  "pete" => 54
}

hash.values.sort    # => [18, 23, 54]
hash.sort_by { |name, age| age } # => [["joan", 18], ["fred", 23], ["pete", 54]]
hash.sort_by { |name, age| name } # => [["fred", 23], ["joan", 18], ["pete", 54]]


文章来源: correct way of using hash sort in ruby
标签: ruby hash