Guest User

Untitled

a guest
Jul 18th, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.22 KB | None | 0 0
  1. stack_of_cards = []
  2.  
  3. stack_of_cards << Card.new("A", "Spades", 1)
  4. stack_of_cards << Card.new("2", "Spades", 2)
  5. stack_of_cards << Card.new("3", "Spades", 3)
  6. ...
  7.  
  8. class Card
  9.  
  10. attr_accessor :number, :suit, :value
  11.  
  12. def initialize(number, suit, value)
  13. @number = number
  14. @suit = suit
  15. @value = value
  16. end
  17.  
  18. def to_s
  19. "#{@number} of #{@suit}"
  20. end
  21. end
  22.  
  23. stack_of_cards.shuffle
  24.  
  25. stack_of_cards.shuffle!
  26.  
  27. class Hash
  28. def shuffle
  29. Hash[self.to_a.sample(self.length)]
  30. end
  31.  
  32. def shuffle!
  33. self.replace(self.shuffle)
  34. end
  35. end
  36.  
  37. array.sort {|a, b| rand <=> rand }
  38.  
  39. def shuffle_me(array)
  40. (array.size-1).downto(1) do |i|
  41. j = rand(i+1)
  42. array[i], array[j] = array[j], array[i]
  43. end
  44.  
  45. array
  46. end
  47.  
  48. array.shuffle
  49. [1, 3, 2].shuffle
  50. #=> [3, 1, 2]
  51.  
  52. Hash[*hash.to_a.shuffle.flatten]
  53. Hash[*{a: 1, b: 2, c: 3}.to_a.shuffle.flatten(1)]
  54. #=> {:b=>2, :c=>3, :a=>1}
  55. #=> {:c=>3, :a=>1, :b=>2}
  56. #=> {:a=>1, :b=>2, :c=>3}
  57. # Also works for hashes containing arrays
  58. Hash[*{a: [1, 2], b: [2, 3], c: [3, 4]}.to_a.shuffle.flatten(1)]
  59. #=> {:b=>2, :c=>3, :a=>1}
  60. #=> {:c=>[3, 4], :a=>[1, 2], :b=>[2, 3]}
  61.  
  62. a = {"a" => 1, "b" => 2, "c" => 3}
  63. puts a.inspect
  64. a = a.sort {|a, b| rand <=> rand }.to_h
  65. puts a.inspect
Add Comment
Please, Sign In to add comment