mardi 29 septembre 2020

Program output varies for unknown reason [duplicate]

Disclaimer: I know the code is wrong and horrible, but that isn't the point.
I was trying to solve Project Euler Problem 11, and i came up with this code

template<size_t N>
long long GridGP(long long (&grid)[N]) //Stands for Grid Greatest Product;
{
    long long gridSize = sizeof(grid) / sizeof(*grid);
    long long digitProd = 1; //Digit Product
    long long potDigProd = 1; //Potential Digit Product
    for (long long numLocation = 0; numLocation <= gridSize - 31; numLocation++) //-31 so that it doesn't continue onto the last 3 rows
    {
        potDigProd = 1;
        if (numLocation - 3 >= ((numLocation / 10) * 10)) //Left Diagonal
        {
            for (long long i = 0; i <= 4; i++) //Times 4 not 3, so that it includes the first number in the series of 4 adjacent numbers
            {
                potDigProd *= grid[numLocation - ((i * 10) - i)];
            }
            if (potDigProd > digitProd) digitProd = potDigProd;
            potDigProd = 1;
        }
        if (numLocation - 3 < ((numLocation / 10) * 10) + 7) //Right Diagonal
        {
            for (long long i = 0; i <= 4; i++)
            {
                potDigProd *= grid[numLocation + ((i * 10) + i)];
            }
            if (potDigProd > digitProd) digitProd = potDigProd;
            potDigProd = 1;
        }
        for (long long i = 0; i <= 4; i++) //Down, doesn't requre an if statement to check if it's beyond the last 4th row because the for loop doesn't go beyond the last 4th row
        {
            potDigProd *= grid[numLocation + (i * 10)];
        }
        if (potDigProd > digitProd) digitProd = potDigProd;
        potDigProd = 1;
        if (numLocation >= 40) //Up
        {
            for (long long i = 0; i <= 4; i++)
            {
                potDigProd *= grid[numLocation - (i * 10)];
            }
            if (potDigProd > digitProd) digitProd = potDigProd;
            potDigProd = 1;
        }
    }
    return digitProd;
}

The main method just has the grid from problem 11 as an int array grid20x20 and then cout << GridGP(grid20x20);

Can someone explain why?
Note: It is possible that you'll have it give the same answer everytime, if that happens rebuild the project and you should start getting a different answer each time. very weird.
I also use the Visual Studio C++ Compiler

The post i was linked to does not answer my question




Aucun commentaire:

Enregistrer un commentaire