Путь минимальной суммы пирамиды 2D ArrayList IndexOutOfBounds - PullRequest
0 голосов
/ 04 июня 2018

Я пытаюсь вычислить минимальную сумму восходящего пути пирамиды.Я читаю входные данные из текстового файла.

Пример моего текстового файла:

5
6
6 5
3 5 8
3 9 2 1
4 7 9 2 7

Первая строка сообщает программе о размере пирамиды, а остальные собирают пирамиду.(В этом примере размер равен 5).

Это мой основной метод:

public static void main(String[] args) throws FileNotFoundException {

    if(args.length > 0) {   
        File file1 = new File(args[0]);
        Scanner scanner1 = new Scanner(file1); // The Scanner that is going to read file1.
        int pyramidSize = scanner1.nextInt();
        scanner1.next();
        System.out.println("Pyramid Size = " + pyramidSize);
        ArrayList<ArrayList <Integer>> solution1List = new ArrayList<ArrayList <Integer>>(pyramidSize);
        // Reads all integers to an array list.

        while(scanner1.hasNext()) {
            int row = 1;

            if(scanner1.hasNextInt()) {    
                int temporaryForSolution1Integer = scanner1.nextInt();
                solution1List.get(row).add(temporaryForSolution1Integer);
            }
            else {
                scanner1.next();
                row++;
            }


            scanner1.close(); // Closed the scanner in order to prevent resource leak.
        }

         System.out.println("The minimum sum path is = " + minimumSumPath(solution1List));

Это метод, который я использую для расчета минимального пути:

public static int minimumSumPath(ArrayList<ArrayList<Integer>> triangle) {

    if (triangle.size() == 0)
        return 0;
    int size = triangle.size();
    int min = Integer.MAX_VALUE;

    int[] sum = new int[size];
    sum[0] = triangle.get(0).get(0);
    for(int current = 1; current <= size - 1; current++){
        int next_size = triangle.get(current).size();
        // it has to start with the end of the array
        // because the further one need the clean sum 
        // value than the newer one.
        for(int next = next_size - 1; next >= 0; next--) {
            if (next == 0) {
                sum[0] = sum[0] + triangle.get(current).get(next);
            } else if (next == (next_size - 1)) { // Reaches to the rightmost element of that iteration
                sum[next] = sum[next-1] + triangle.get(current).get(next);
            } else { // Provides sum[next] to be the minimal sum that can come there
                sum[next] = Math.min(sum[next-1], sum[next]) + triangle.get(current).get(next);
            }
        }
    }

    for(int i = 0; i < size; i++){
        if(sum[i] < min){
           min = sum[i];
        }
    }
    return min;
}

В настоящее время я сталкиваюсь с ошибкой вроде:

PS C:\Users\berku\Desktop\BERKSOL> javac .\berkSol.java
PS C:\Users\berku\Desktop\BERKSOL> java berkSol input1.txt input2.txt
Pyramid Size = 5
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 0
    at java.util.ArrayList.rangeCheck(Unknown Source)
    at java.util.ArrayList.get(Unknown Source)
    at berkSol.main(berkSol.java:23)

Я думаю, что мой метод расчета верен.

Если кто-то может помочь мне с этой ошибкой, я будуочень рад ему / ей.

1 Ответ

0 голосов
/ 04 июня 2018

solution1List.get(row).add(temporaryForSolution1Integer); в этом индексе нет элемента.

Вы создаете двухмерный список как ArrayList<ArrayList <Integer>> solution1List = new ArrayList<ArrayList <Integer>>(pyramidSize);, но никогда не добавляете к нему фактические List элементы.

РаньшеВы можете сделать solution1List.get(0); Вы должны сделать solution1List.add(new ArrayList<Integer>());


Обратите внимание, что Lists, а также Arrays основаны на 0.это означает, что первый элемент фактически доступен с 0, а не с 1

...