生成概率树然后对结果进行排序的时间有效实现

Sia*_*ana 6 java algorithm probability execution-time

我有一些事件,他们每个人都有可能发生,如果他们这样做,他们就会有重量.我想用相应的权重创建事件概率的所有可能组合.最后,我需要按重量顺序排序.这就像生成一个概率树,但我只关心生成的叶子,而不是它们获取它们的节点.我不需要在创建最终结果期间查找特定条目,只需创建所有值并按重量对它们进行排序.

将会有大约5-15个事件,但由于n ^事件有2 ^ n的可能性,并且这是经常做的,我不希望它花费不必要的长时间.速度比使用的存储量重要得多.

我提出的解决方案有效,但速度很慢.想要更快的解决方案或一些改进的想法吗?

   class ProbWeight {
        double prob;
        double eventWeight;

        public ProbWeight(double aProb, double aeventWeight) {
            prob = aProb;
            eventWeight = aeventWeight;
        }

        public ProbWeight(ProbWeight aCellProb) {
            prob = aCellProb.getProb();
            eventWeight = aCellProb.geteventWeight();
        }

        public double getProb(){
            return prob;
        }
        public double geteventWeight(){
            return eventWeight;
        }       

        public void doesHappen(ProbWeight aProb) {
            prob*=aProb.getProb();
            eventWeight += aProb.geteventWeight();                             
        }

        public void doesNotHappen(ProbWeight aProb) {
            prob*=(1-aProb.getProb());                         
        }

    }

    //Data generation for testing
    List<ProbWeight> dataList = new ArrayList<ProbWeight>();
    for (int i =0; i<5; i++){
        ProbWeight prob = new ProbWeight(Math.random(), 10*Math.random(), i);
        dataList.add(prob);
    }

    //The list where the results will end up
    List<ProbWeight> resultingProbList = new ArrayList<ProbWeight>();
    // a temporaty list to avoid modifying a list while looping through it
    List<ProbWeight> tempList = new ArrayList<ProbWeight>();

    resultingProbList.add(dataList.remove(0));
    for (ProbWeight data : dataList){ //for each event
        //go through the already created event combinations and create two new for each
        for(ProbWeight listed: resultingProbList){ 
            ProbWeight firstPossibility = new ProbWeight(listed);
            ProbWeight secondPossibility = new ProbWeight(listed);
            firstPossibility.doesHappen(data);
            secondPossibility.doesNotHappen(data);
            tempList.add(firstPossibility);
            tempList.add(secondPossibility);
        }
        resultingProbList = new ArrayList<ProbWeight>(tempList);
    }
    // Then sort the list by weight using sort and a comparator
Run Code Online (Sandbox Code Playgroud)

avi*_*iad 4

50%是关于选择合适的数据结构,50%是关于算法。数据结构 - 我相信TreeBidiMap将为您带来魔力。您需要实现 2 个比较器 - 1 个用于权重,另一个用于概率。算法 - 微不足道。祝你好运!