Добавление 1 к Integer.MAX_VALUE в al oop вызывает неожиданное поведение (не то, к которому оно относится к Integer.MIN_VALUE) - PullRequest
1 голос
/ 04 мая 2020

Я работал над вызовом HackerRank для «Манипуляции с массивом», и возникла неожиданная, интересная проблема. Я запускаю большое для l oop, где я добавляю суммы префиксов, и в тот момент, когда я передаю значение Integer.MAX_Value в сумме префикса (где сумма хранится как int), число сбрасывается вниз на несколько тысяч вместо того, чтобы зацикливаться на негативе, что является моим ожидаемым поведением.

Кто-нибудь знает, почему это может происходить? Нет проблем, если вы сохраните префиксную сумму как long.

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ArrayManipulation {
   public static long arrayManipulationPrefixSumLong(int n, int[][] queries) {
        long[] array = new long[n];
        for (int i = 0; i < queries.length; i++) {
            int lowIndex = queries[i][0] - 1;
            int highIndex = queries[i][1] - 1;
            int addend = queries[i][2];

            array[lowIndex] += addend;
            if (highIndex + 1 < n)
                array[highIndex + 1] -= addend;
        }

        long maxInt = 0;
        for (int i = 0; i < array.length; i++) {
            if (i != 0)
                array[i] = array[i - 1] + array[i];
            if (array[i] > maxInt)
                maxInt = array[i];
        }
        return maxInt;
    }

    public static int arrayManipulationPrefixSumInt(int n, int[][] queries) {
        int[] array = new int[n];
        for (int i = 0; i < queries.length; i++) {
            int lowIndex = queries[i][0] - 1;
            int highIndex = queries[i][1] - 1;
            int addend = queries[i][2];

            array[lowIndex] += addend;
            if (highIndex + 1 < n)
                array[highIndex + 1] -= addend;
        }

        int maxInt = 0;
        for (int i = 0; i < array.length; i++) {
            if (i != 0)
                array[i] = array[i - 1] + array[i];
            if (array[i] > maxInt)
                maxInt = array[i];
        }
        return maxInt;
    }

    public static void main(String[] args) {
        Scanner scanner = null;
        try {
            scanner = new Scanner(new File("input10ArrayManipulation_Subset85545.txt"));
//            scanner = new Scanner(new File("input10ArrayManipulation.txt"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        int n = scanner.nextInt();
//        System.out.println(n);
        int qn = scanner.nextInt();
//        System.out.println(qn);
        int[][] queries = new int[qn][3];
        for (int i = 0; i < qn; i++) {
            queries[i] = new int[]{scanner.nextInt(), scanner.nextInt(), scanner.nextInt()};
        }

        scanner.close();
        System.out.println(new String(new char[85]).replace("\0", "*"));
        System.out.println("Trying to find why exceeding Integer.MAX_VALUE in a loop causes unexpected behaviour.");
        System.out.println(new String(new char[60]).replace("\0", "-"));


        //Relevant part
        long arrayManipulationPrefixSumLong = arrayManipulationPrefixSumLong(n, queries);
        int arrayManipulationPrefixSumInt = arrayManipulationPrefixSumInt(n, queries);

        //Notice these two give different values
        System.out.println("The long version: " + arrayManipulationPrefixSumLong);
        System.out.println("The int version: " + arrayManipulationPrefixSumInt);

        // Adding past the max value in a loop doesn't result in a negative number,
        // to see this behaviour, increment the last line of input10ArrayManipulation_Subset85545 by 1.
        System.out.println(Integer.MAX_VALUE - arrayManipulationPrefixSumLong);
        //The below is my expected behaviour, where integer overflow occurs.
        System.out.println("Max integer is: " + Integer.MAX_VALUE + " | Max integer +1 is: " + (Integer.MAX_VALUE + 1));

        System.out.println(new String(new char[60]).replace("\0", "-"));
        System.out.println("Now testing with the other file that has 1 incremented on the last line, which makes it exceed the Integer.MAX_VALUE");
        try {
            scanner = new Scanner(new File("input10ArrayManipulation_Subset85545_increment1.txt"));
            n = scanner.nextInt();
//        System.out.println(n);
            qn = scanner.nextInt();
//        System.out.println(qn);
            queries = new int[qn][3];
            for (int i = 0; i < qn; i++) {
                queries[i] = new int[]{scanner.nextInt(), scanner.nextInt(), scanner.nextInt()};
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        arrayManipulationPrefixSumLong = arrayManipulationPrefixSumLong(n, queries);
        arrayManipulationPrefixSumInt = arrayManipulationPrefixSumInt(n, queries);

        //Notice these two give different values
        System.out.println("The long version: " + arrayManipulationPrefixSumLong);
        System.out.println("The int version: " + arrayManipulationPrefixSumInt);

        scanner.close();
    }
}

Текстовые файлы, использованные для тестирования этой программы, можно найти по адресу: https://drive.google.com/drive/folders/1ktlEixYsqeD2l4x12iD4gEVvM-1gVetK?usp=sharing

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...