簡體   English   中英

如何在 Ruby 中打亂數組/哈希?

[英]How can I shuffle an array/hash in Ruby?

出於學習目的,這叫什么? 正在創建的 object 是數組還是 hash?

stack_of_cards = []

這就是我填充它的方式:

stack_of_cards << Card.new("A", "Spades", 1)
stack_of_cards << Card.new("2", "Spades", 2)
stack_of_cards << Card.new("3", "Spades", 3)
...

這是我的卡 class:

class Card

  attr_accessor :number, :suit, :value

  def initialize(number, suit, value)
    @number = number
    @suit = suit
    @value = value
  end

  def to_s
    "#{@number} of #{@suit}"
  end
end

我想打亂這個數組/哈希中的元素(這叫什么?:S)

有什么建議么?

stack_of_cards.shuffle

它是一個數組,有關更多信息,請參見http://www.ruby-doc.org/core-1.8.7/classes/Array.html

我已經寫了函數形式,它返回一個新的數組,它是新的一個被洗牌的。 您可以改為使用:

stack_of_cards.shuffle!

...原地打亂數組。

如果你想洗牌一個散列,你可以使用這樣的東西:

class Hash
  def shuffle
    Hash[self.to_a.sample(self.length)]
  end

  def shuffle!
    self.replace(self.shuffle)
  end
end

我已經發布了這個答案,因為如果我搜索“ruby shuffle hash”,我總是會發現這個問題。

如果您想發瘋並編寫自己的就地洗牌方法,您可以這樣做。

 def shuffle_me(array)
   (array.size-1).downto(1) do |i|
     j = rand(i+1)
     array[i], array[j] = array[j], array[i]
   end

   array
 end 

對於數組:

array.shuffle
[1, 3, 2].shuffle
#=> [3, 1, 2]

對於哈希:

Hash[*hash.to_a.shuffle.flatten]
Hash[*{a: 1, b: 2, c: 3}.to_a.shuffle.flatten(1)]
#=> {:b=>2, :c=>3, :a=>1}
#=> {:c=>3, :a=>1, :b=>2}
#=> {:a=>1, :b=>2, :c=>3}
# Also works for hashes containing arrays
Hash[*{a: [1, 2], b: [2, 3], c: [3, 4]}.to_a.shuffle.flatten(1)]
#=> {:b=>2, :c=>3, :a=>1}
#=> {:c=>[3, 4], :a=>[1, 2], :b=>[2, 3]}

除了使用 shuffle 方法,您還可以使用 sort 方法:

array.sort {|a, b| rand <=> rand }

如果您使用的是未實現shuffle的舊版 Ruby,這可能很有用。 shuffle! ,你可以使用sort! 在現有陣列上工作。

老問題,但也許對其他人有幫助。 我用它來創建一個紙牌游戲,這就是@davissp14 寫的,它被稱為“Fisher-Yates 算法”

module FisherYates

  def self.shuffle(numbers)
    n = numbers.length
    while n > 0 
      x = rand(n-=1)
      numbers[x], numbers[n] = numbers[n], numbers[x]
    end
    return numbers
  end

end 

現在您可以將其用作:

numbers_array = [1,2,3,4,5,6,7,8,9]
asnwer = FisherYates.shuffle(numbers_array)
return answer.inspect

https://dev.to/linuxander/fisher-yates-shuffle-with-ruby-1p7h

如果您想對哈希進行混洗,但又不想重載 Hash 類,則可以使用 sort 函數,然后使用 to_h 函數(Ruby 2.1+)將其轉換回哈希:

a = {"a" => 1, "b" => 2, "c" => 3}
puts a.inspect
a = a.sort {|a, b| rand <=> rand }.to_h
puts a.inspect

對於數組:

array.shuffle

對於哈希:

hash.sort_by{ rand() }

另一種 hash 洗牌是..

hash.to_a.shuffle.to_h

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM