ひょうじゅんベースラインアルゴリズム

1558 ワード

class MedLvBo {
    private val data = IntArray(254)
    private var index = 0
    fun init(v:Int):Int{
        data[index++] = v
        if(index == 254)index=0
        return data[index]-initAvg(initMid(v))
    }


    private var avgI = 0
    private val dI=IntArray(256)
    private var sum = 0
    private fun initAvg(v:Int):Int{
        sum-=dI[avgI]
        sum+=v
        dI[avgI++]=v
        if(avgI==256)avgI=0
        return sum shr 8
    }

    private var mPos: Int = 125
    private var i = 0
    private val d = IntArray(251)
    private val f = BooleanArray(251) {
        it < mPos
    }
    private var mV = 0
    private fun initMid(a: Int): Int {
        d[i] = a
        if (f[i]) {
            if (a < mV) {
                f[i] = false
                f[mPos] = true
                mPos = i
                g(a)
            }
        } else if (a > mV) {
            f[i] = true
            mV = a
            mPos = i
            d.forEachIndexed { i, v ->
                if (f[i] && v < mV) {
                    mPos = i
                    mV = v
                }
            }
            f[mPos] = false
        } else if (i == mPos && mV != a) {
            g(a)
        }

        if (++i == 521) {
            i = 0
        }
        return mV
    }
    private fun g(a: Int) {
        mV = a
        d.forEachIndexed { i, v ->
            if (f[i].not() && v > mV) {
                mPos = i
                mV = v
            }
        }
    }
}