コード例 #1
0
ファイル: WaveletTree.cpp プロジェクト: iborko/fmindex
char WaveletTree::calc_pivot(const std::string& alph, const CharIntMap& counts) {

    UIntVector scores;
    scores.resize(alph.size(), 0);

    for (std::size_t i = 0; i < alph.size(); i++) {

        // calc the number of 0s and 1s
        UInt sum_before = 0;
        UInt sum_after = 0;
        for (std::size_t j = 0; j < i; j++) {
            // operator[] can't be used in const map, so I had to use
            // find to get iterator
            CharIntMap::const_iterator elem = counts.find(alph[j]);
            if (elem == counts.end())
                throw std::runtime_error("counts has missing key");
            sum_before += elem->second;
        }
        for (std::size_t j = i; j < alph.size(); j++) {
            CharIntMap::const_iterator elem = counts.find(alph[j]);
            if (elem == counts.end())
                throw std::runtime_error("counts has missing key");
            sum_after += elem->second;
        }

        // diff between numbers of 0s and 1s
        scores[i] = abs(sum_before - sum_after);
        
        // if current score is worse than prev, than prev is the best,
        // continuing will only give worse scores
        if (i > 0 && scores[i] > scores[i-1])
            return alph[i-1];
    }

    return alph[alph.size() - 1];
}