为什么在线程“ main”中得到一个“异常” java.lang.IndexOutOfBoundsException:索引0的长度为0超出范围”

问题描述 投票:0回答:1

我必须使用表示限制的列表中的数字进行回溯,例如:“ x1 + x2> = 1”。如果满足所有条件,则将该数组添加到另一个数组中,此外还有另一个列表,该列表代表我必须对所有变量“ x1 + x2 + x3 + x4”进行求和的结果,并通过该搜索来求和带有最小值。

好,我在回溯中应该做的是用限制满足的所有可能性制作一个二进制矩阵。我所做的是这个,但是我得到了错误:“线程异常”主“ java.lang.IndexOutOfBoundsException:索引2的长度为0超出范围”,我不知道我的问题在哪里。

import java.util.ArrayList;

public class Pra_hacer_pruebas {
    public static void main(String[] args) {
           Pra_hacer_pruebas a = new Pra_hacer_pruebas();
           ArrayList<Integer> conf1= new ArrayList<>(); // conf1 is the list that will contain one of the possibilities that may or may not be added to the binary matrix.
           ArrayList<ArrayList<Integer>>pos_v = new ArrayList<>();// pos_v is where the possibilities will be added, binary matrix
           int[][] restric = new int[2][2];// restric is the list with restrictions
           restric[0][0]=2;
           restric[0][1]=1;
           restric[1][0]=4;
           restric[1][1]=2;
           for(int t=0;t<4;t++){
               conf1.set(t, -1);
           }
           //System.out.println(conf.get(i));
           a.binario(conf1,restric,0,0,0,pos_v,0,4,-1);
    }

    public void binario(ArrayList<Integer> conf1, int[][] restric, int suma,int filas,int columnas,ArrayList<ArrayList<Integer>> pos_validas,int posicion, int cont,int bin){
        //filas = rows, suma= sum is to see if it meets the condition, columnas = columns, pos_validas = pos_v, posicion is to advance the rows of the matrix, cont: is the amount of different variables, bin is the binary variable
        Boolean booleano = false;  // booleano is the flag that if it is true it is because there was a null position (-1)
        for (int[] restric1 : restric) {
            suma=0;
            for (int co = 0; co < restric1.length; co++) {
                if ((conf1.get(restric1[co]) == 1) || (conf1.get(restric1[co]) == 0)) {
                    suma = suma + conf1.get(restric1[co]);
                } else {
                    booleano = true;
                }
            }
            if (booleano == false) {
                if (suma < 1){
                    break;
                }
            }
        }
        if (booleano == false) {
            pos_validas.set(posicion, conf1);
            posicion++;
        }
        for (int f = 0; f < cont; f++) {
            if (conf1.get(f) < 1) {
                bin++;
                conf1.set(f, bin);
binario(conf1,restric,suma,filas,columnas,pos_validas,posicion,cont,bin);
            }
            bin--;
        }
    }
}
java backtracking
1个回答
0
投票

您的Arraylist对象开始时是空对象。您根本无法在其上调用.set():那些UPDATE现有条目,它们不创建新条目。尝试add

© www.soinside.com 2019 - 2024. All rights reserved.