我有一种求知欲,我会喜欢你的想法。不一定需要一个完整的解决方案;只是想更多地关注它。
假设:
问题:
根据"拥挤情况"对r
中的整数进行加权。他们在a
。有两个因素:"拥挤"整数是:
a
出现了多少次?越频繁,越拥挤。示例:
a = [1, 1, 2, 4, 6, 8, 8, 8, 8, 9, 10, 10]
r = (1..11)
解决方案想法:
这是我想出的一个快速(而且很脏,绝对)的解决方案;似乎做了这个工作:
$a = [1, 1, 2, 4, 6, 8, 8, 8, 8, 9, 10, 10]
$r = (1..11)
def how_congested?(integer)
((10 * $a.count(integer) + 2.5 * number_of_neighbors(integer))/100)
end
def number_of_neighbors(integer)
count = 0
hash = Hash[$a.uniq.map.with_index.to_a]
index = hash[integer]
count += 1 unless hash[integer + 1].nil?
count += 1 unless hash[integer - 1].nil?
count
end
$r.each do |i|
puts "Congestion of ##{ i }: #{ how_congested?(i) }"
end
# Congestion of #1: 0.225
# Congestion of #2: 0.125
# Congestion of #3: 0.05
# Congestion of #4: 0.1
# Congestion of #5: 0.05
# Congestion of #6: 0.1
# Congestion of #7: 0.05
# Congestion of #8: 0.425
# Congestion of #9: 0.15
# Congestion of #10: 0.225
# Congestion of #11: 0.025
问题:
欣赏你的想法!
答案 0 :(得分:1)
检查出来:
class Congestion
attr_accessor :array, :range
def initialize(array, range)
@array = array
@range = range
end
def how_congested?(integer)
((10 * self.array.count(integer) + 2.5 * weight_of_neighbors(integer)) / 100)
end
def weight_of_neighbors(integer)
weight = 0
@array.uniq.each do |elem|
weight += case (elem - integer).abs
when 1 then 3
when 2 then 2
when 3 then 1.5
when 4 then 1.25
when 5 then 1
else 0
end
end
weight
end
def calculate
self.range.each do |i|
congestion = how_congested?(i)
puts "Congestion of #{i}: #{congestion}"
end
end
end
a = [1, 1, 2, 4, 6, 8, 8, 8, 8, 9, 10, 10]
r = (1..11)
c = Congestion.new(a, r)
c.calculate
最终看起来像这样:
# Congestion of 1: 0.3375
# Congestion of 2: 0.25625
# Congestion of 3: 0.2625
# Congestion of 4: 0.29375
# Congestion of 5: 0.3125
# Congestion of 6: 0.325
# Congestion of 7: 0.3
# Congestion of 8: 0.60625
# Congestion of 9: 0.3125
# Congestion of 10: 0.35625
# Congestion of 11: 0.1875
基本上,这里的相关变化是它需要我们感兴趣的整数,从数组的当前元素中减去它,然后得到该数字的正版本。