用于将数字分类到具有可变范围的区间的算法

时间:2018-02-16 20:04:19

标签: algorithm sorting

我需要将一组n个数字排序到具有一定范围的“bins”中。 这是我想要做的一个例子:

Array = [1, 5, 6, 4, 2, 10]
binA has a range from 1 to 3 -> 1,2 gets sorted in
binB has a range from 4 to 6 -> 4,5,6 gets sorted in
binC has a range from 7 to 10 -> 10 gets sorted in
binD has a range from 11 to 12 -> nothing gets sorted in

bin范围是我之前定义的,放入某些bin中的数字的顺序无关紧要。

1 个答案:

答案 0 :(得分:0)

如果您的垃圾箱总是大小相同(此处为3),您可以按功能(伪代码)添加垃圾箱:

bin = new Array (binA, binB, binC, binD) 

def bin (i: Int) : Int = bin((i+1)/3).add (i)

您可以为Bins创建一个新类(与上面的代码无关!):

case class Bin (val lo: Int, val hi: Int) {
  override def toString : String = s"from $lo to $hi ${lb} ${if (next == None) "-|" else "\n" + next.get.toString} "
  val lb =  collection.mutable.ListBuffer[Int] ()
  var next : Option[Bin] = None
  def add (i: Int) {
    if (i < hi)
        lb += i
    else {
        if (next == None) {
            val bin = Bin (hi+1, hi + 4)
            bin.add (i)
            next = Some (bin)
        }
        else next.map (bin => bin.add (i))
    }
  }
}

val sample = List (1, 5, 6, 4, 2, 10)
val binA = Bin (1, 3) 
sample.map (binA.add (_))
println (binA) 

结果:

from 1 to 3 ListBuffer(1, 2) 
from 4 to 7 ListBuffer(5, 6, 4) 
from 8 to 11 ListBuffer(10) -|   

对于不同的Bins大小,比如大百科全书中的字符(AB,CD,E,FH,...),当然,您需要一种不同的初始化方式,但每个bin都可以将值传递给下一个bin ,如果超出他的界限。