使用markov链时获取ArrayIndexOutOfBoundsException

时间:2011-05-30 14:59:05

标签: java arrays algorithm markov-chains

我有一个数组来存储一组用于绘制一条线的坐标。所以这里有一些示例坐标

double[][] plotMatrix = {{10,20},{55,80},
                         {120,40},{225,30},
                         {327.5,100},
                         {427.5,30},
                         {529,60}};

下一步是创建一个二维的马尔可夫矩阵。

enter image description here

首先,我计算左列中的点后跟顶部列中的点的时间。因为我想要一条线,每个点后跟另一个单点。这意味着如果我们输入{10,20},{55,80}作为下一个点的可行性是100%。

我不是很确定这一切所以请纠正我!

所以这是我的矩阵

double[][] markovMatrix = { {0.0,1.0,0.0,0.0,0.0,0.0,0.0},
                                    {0.0,0.0,1.0,0.0,0.0,0.0,0.0},
                                    {0.0,0.0,0.0,1.0,0.0,0.0,0.0},
                                    {0.0,0.0,0.0,0.0,1.0,0.0,0.0},
                                    {0.0,0.0,0.0,0.0,0.0,1.0,0.0},
                                    {0.0,0.0,0.0,0.0,0.0,0.0,1.0},
                                    {0.0,0.0,0.0,0.0,0.0,0.0,0.0}};

我的算法:

    int seed = 0;
    int output = 0;

    for(int i = 0; i < 40;i++){
        double choice = r.nextDouble();

        double currentSum = 0.0;

        for(;output < markovMatrix.length;output++){

            currentSum += markovMatrix[seed][output];

            if(choice <= currentSum){
                break;
            }
        }

        System.out.println(output);
        polygon.lineTo(plotMatrix[output][0], plotMatrix[output][1]);

        seed = output;

        output = 0;
    }

我的问题是,当我尝试访问plotMatrix和markovMatrix时,我得到ArrayOutOfBoundsException:7。但是,在每个循环结束时输出设置为0。任何想法如何解决这个问题?

2 个答案:

答案 0 :(得分:3)

我不太确定它的答案是否正确,

但是(;输出&lt; markovMatrix.length;输出++)将从0步进到7,而在markovMatrix中只有0到6个条目。

使用for(; output&lt; markovMatrix.length-1; output ++)通过从1步进到6来修复ArrayIndexOutOfBoundsException。

但是我怀疑你真的想从0步到6步。这就是你的问题。

答案 1 :(得分:1)

何时完成内循环输出= 7循环,这是数组的长度。 您应该跳过最后一次迭代,因为您的数组索引是从0到6。