首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Ruby数组中选择“最不拥挤”数字

在Ruby数组中选择“最不拥挤”数字
EN

Stack Overflow用户
提问于 2014-03-20 14:48:55
回答 1查看 49关注 0票数 3

我有一种智力上的好奇心,我喜欢你的想法。不一定需要一个完整的解决方案,只是想让更多的人关注它。

Given:

  • 整数数组(可能存在重复)
  • 可供选择的“可接受”整数的范围。

问题:

根据r中“拥塞”在a中的位置来对整数进行加权。“拥挤”的整数是什么情况有两个因素:

  1. 它在a中出现了多少次?频率越高,就越拥挤。
  2. 它有几个近邻?邻居越近,就越拥挤。

1重量比#2重得多(多少?)不确定,我只是觉得应该是“很多”。

示例:

a = [1, 1, 2, 4, 6, 8, 8, 8, 8, 9, 10, 10]

r = (1..11)

解决方案理念:

下面是我想出的一个快速(而且肮脏,绝对)的解决方案;似乎就是这样做的:

代码语言:javascript
复制
$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

发行:

  • 这考虑到了近邻,但不是邻居--2点,3点,等等。我认为应该有某种滑动尺度(例如,“邻家”邻居数是邻居2点以外的2倍,等等)。
  • 我在餐巾纸上想出了这个“算法”,但我想知道是否有更聪明的方法来做到这一点?

感谢你的想法!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-03-20 18:52:35

看看这个:

代码语言:javascript
复制
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

最后看起来是这样:

代码语言:javascript
复制
# 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

基本上,这里的相关变化是,它获取我们感兴趣的整数,从数组的当前元素中减去它,然后得到该数字的正数。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22536602

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档