问题描述
我正在做一个简单的彩票游戏.目前它从一个txt文件中取出序列号和彩票号码,并将它们放在一个二维数组中.
I i'm doing a simple lottery game. at the moment its taking serial number and lottery number from a txt file, and putting them in a 2 dimensional array.
现在我想检查一下序列号和彩票号码是否重复
now i want to make a check grade if there are any duplicates of the serial number and lottery number
example:
5153,177 = 1
54338,115 = 1
74522,171 = 3
我尝试过使用支票号码方法,它没有给出任何错误,但是当我这样做时
i've tried making a check number method, it do not give any errors, but when i do
puts sold.checkgrade
它不起作用
我怎样才能让它像我的例子一样?
How can i make it do like in my example?
class Lottery
attr_accessor :lotnumber
attr_accessor :serialnumber
def initialize(lotnumber, serialnumber)
@lotnumber = lotnumber
@serialnumber = serialnumber
end
def checknumber
ObjectSpace.each_object(Lottery).to_a.select do |other|
@lotnumber == other.lotnumber && @serialnumber == other.serialnumber
end.size
end
end
我的txt
29371,43
13797,6
8114,55
70657,106
32741,74
7272,103
37416,14
5153,177
54338,115
74522,171
74522,171
74522,171
推荐答案
Ruby 的 group_by
方法是一个很好的起点:
Ruby's group_by
method is a good place to start:
data = %w[
29371,43
13797,6
8114,55
70657,106
32741,74
7272,103
37416,14
5153,177
54338,115
74522,171
74522,171
74522,171
]
data.group_by{ |s| s }.map{ |k, v| [k, v.size] }
# => [["29371,43", 1],
# ["13797,6", 1],
# ["8114,55", 1],
# ["70657,106", 1],
# ["32741,74", 1],
# ["7272,103", 1],
# ["37416,14", 1],
# ["5153,177", 1],
# ["54338,115", 1],
# ["74522,171", 3]]
内在的魔法是,group_by
创建一个数组的散列:
The inner magic is, group_by
creates a hash of arrays:
data.group_by{ |s| s }
# => {"29371,43"=>["29371,43"],
# "13797,6"=>["13797,6"],
# "8114,55"=>["8114,55"],
# "70657,106"=>["70657,106"],
# "32741,74"=>["32741,74"],
# "7272,103"=>["7272,103"],
# "37416,14"=>["37416,14"],
# "5153,177"=>["5153,177"],
# "54338,115"=>["54338,115"],
# "74522,171"=>["74522,171", "74522,171", "74522,171"]}
如果你想要散列而不是数组数组:
If you want a hash instead of an array of arrays:
Hash[data.group_by{ |s| s }.map{ |k, v| [k, v.size] }]
# => {"29371,43"=>1,
# "13797,6"=>1,
# "8114,55"=>1,
# "70657,106"=>1,
# "32741,74"=>1,
# "7272,103"=>1,
# "37416,14"=>1,
# "5153,177"=>1,
# "54338,115"=>1,
# "74522,171"=>3}
这篇关于二维数组中的重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!