如何在 Ruby 中打乱数组/散列?

发布于 2024-10-18 10:53:43 字数 586 浏览 2 评论 0原文

为了学习目的,这叫什么?正在创建的对象是数组还是哈希?

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)
...

这是我的 Card 类:

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)

有什么建议吗?

For learning purposes, what is this called? Is the object being created an array or a hash?

stack_of_cards = []

This is how I'm filling it:

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

Here is my Card 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

I'd like to shuffle the elements in this array/hash (what is this called? :S)

Any suggestions?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

空心↖ 2024-10-25 10:53:43
stack_of_cards.shuffle

它是一个数组,请参见 http://www.ruby-doc.org/core- 1.8.7/classes/Array.html 了解更多信息。

我编写了功能形式,它返回一个新的数组,并且它是经过洗牌的新数组。您可以改为使用:

stack_of_cards.shuffle!

...将数组就地打乱。

stack_of_cards.shuffle

It is an Array, see http://www.ruby-doc.org/core-1.8.7/classes/Array.html for more information.

I've written the functional form, which returns a new Array, and it's the new one that's shuffled. You can instead use:

stack_of_cards.shuffle!

...to shuffle the array in-place.

我的黑色迷你裙 2024-10-25 10:53:43

如果你想洗牌哈希,你可以使用这样的东西:

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

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

我已经发布了这个答案,因为如果我搜索“ruby shuffle hash”,我总是会找到这个问题。

If you want to shuffle a hash you can use something like this:

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

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

I've posted this answer since I always find this question if I search for "ruby shuffle hash".

仅此而已 2024-10-25 10:53:43

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

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

如果您使用的是未实现 shuffle 的旧版本 Ruby,这可能很有用。与 shuffle! 一样,您可以使用 sort! 来处理现有数组。

In addition to using the shuffle method, you can use the sort method:

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

This may be of use if you are using an older version of Ruby where shuffle is not implemented. As with shuffle!, you can use sort! to work on the existing array.

宁愿没拥抱 2024-10-25 10:53:43

如果您想疯狂地编写自己的就地洗牌方法,您可以这样做。

 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 

If you wanted to get crazy and write your own in-place shuffle method, you could do something like this.

 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 
佼人 2024-10-25 10:53:43

对于数组:

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]}

For arrays:

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

For hashes:

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]}
懒的傷心 2024-10-25 10:53:43

老问题,但也许对其他人有帮助。我用它创建了一个纸牌游戏,这就是 @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

Old question, but maybe help for someone else. I used it to create a card game, that's what @davissp14 wrote, it's called "Fisher-Yates algorithm"

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 

Now you can use it as:

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

妥活 2024-10-25 10:53:43

如果你想打乱哈希值,但又不想重载 Hash 类,可以使用排序函数,然后使用 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

If you want to shuffle a hash, but don't want to overload the Hash class, you can use the sort function and then convert it back to a hash with the to_h function (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
送君千里 2024-10-25 10:53:43

对于数组:

array.shuffle

对于哈希:

hash.sort_by{ rand() }

For an array:

array.shuffle

For a hash:

hash.sort_by{ rand() }

戈亓 2024-10-25 10:53:43

另一种哈希洗牌是..

hash.to_a.shuffle.to_h

An alternative hash shuffle is ..

hash.to_a.shuffle.to_h
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文