(Follow-up) Project Euler #11 Largest Product in a Grid | Cache-optimized + sliding window (C++14) ...

SOQL: Aggregate, Grouping By and WHERE Clauses not working

How did people program for Consoles with multiple CPUs?

Is it my responsibility to learn a new technology in my own time my employer wants to implement?

What exact does MIB represent in SNMP? How is it different from OID?

FBX seems to be empty when imported into Blender

Is there a way to save my career from absolute disaster?

If the heap is initialized for security, then why is the stack uninitialized?

Really confused on what inner tube would fit my BF’s new bike?

Elegant way to replace substring in a regex with optional groups in Python?

How to count occurrences of text in a file?

Why is there a PLL in CPU?

Received an invoice from my ex-employer billing me for training

Return the Closest Prime Number

How do we know the LHC results are robust?

If a black hole is created from light, can this black hole then move at speed of light?

Inappropriate reference requests from Journal reviewers

What is the purpose of the Evocation wizard's Potent Cantrip feature?

On model categories where every object is bifibrant

What can we do to stop prior company from asking us questions?

Disadvantage of gaining multiple levels at once in a short milestone-XP game

What does "Its cash flow is deeply negative" mean?

Is HostGator storing my password in plaintext?

WOW air has ceased operation, can I get my tickets refunded?

Why don't programming languages automatically manage the synchronous/asynchronous problem?



(Follow-up) Project Euler #11 Largest Product in a Grid | Cache-optimized + sliding window (C++14)



The Next CEO of Stack OverflowProject Euler #11 Largest Product in a Grid | Cache-optimized + sliding window (C++14)Project Euler Problem 11: Largest product in a gridProject Euler 11 - Largest Product in a gridProject Euler - Largest Product In A GridProject Euler #11 Largest product in a gridProject Euler #11 - Largest product in a gridTabulate schedule/calendar for database importProject Euler #11 - Largest product in a grid C++C++ Parsing with chain of responsibilityFast and flexible Sudoku Solver in C++Project Euler #11 Largest Product in a Grid | Cache-optimized + sliding window (C++14)












2












$begingroup$


Original code review: Project Euler #11 Largest Product in a Grid | Cache-optimized + sliding window (C++14)





Source: HackerRank & ProjectEuler.net



Problem: Largest Product in a Grid

In the 20×20 grid below, four numbers along a diagonal line have been marked in red.



08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08
49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00
81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65
52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91
22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80
24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50
32 98 81 28 64 23 67 10(26)38 40 67 59 54 70 66 18 38 64 70
67 26 20 68 02 62 12 20 95(63)94 39 63 08 40 91 66 49 94 21
24 55 58 05 66 73 99 26 97 17(78)78 96 83 14 88 34 89 63 72
21 36 23 09 75 00 76 44 20 45 35(14)00 61 33 97 34 31 33 95
78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92
16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57
86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58
19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40
04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66
88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69
04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36
20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16
20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54
01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48


The product of these numbers is 26 × 63 × 78 × 14 = 1788696.



What is the greatest product of four adjacent numbers in the same direction (up, down, left, right, or diagonally) in the 20×20 grid?



Input

Input consists of 20 lines each containing 20 integers.



Output

Print the required answer.



Limits

0 ≤ each integer in the grid ≤ 100



Sample

Input



89 90 95 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08  
49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00
81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65
52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91
22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80
24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50
32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70
67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21
24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72
21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95
78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92
16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57
86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58
19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40
04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66
88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69
04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36
20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16
20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54
01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48


Output



73812150


My updated solution (C++14)



#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>

// 2D grid represented by 1D vector for cache optimization
auto getGrid(int rows, int columns) {
auto values = rows * columns;
std::vector<int> grid(values);
std::copy_n(std::istream_iterator<int>(std::cin), values, grid.begin());

if (std::cin.fail()) {
throw std::runtime_error(
"The input is invalid! Check the rows and columns in your input and that all numbers in the grid are integers between 0 and 100.");
}
return grid;
}

class LargestProductInAGrid {
public:
LargestProductInAGrid(std::vector<int> &grid, int rows, int columns, int nAdjacents) : grid_(grid), rows_(rows),
columns_(columns),
nAdjacents_(nAdjacents) {}

template<typename T>
auto largestProductInAGrid() {
T largestProduct = 0;

for (auto row = 0; row < rows_; row++) {
largestProduct = std::max(largestProduct,
largestProductInASeries<T>(SeriesType::HORIZONTAL, row * columns_));
}

for (auto column = 0; column < columns_; column++) {
largestProduct = std::max(largestProduct, largestProductInASeries<T>(SeriesType::VERTICAL, column));
largestProduct = std::max(largestProduct, largestProductInASeries<T>(SeriesType::DIAGONAL_RIGHT, column));
largestProduct = std::max(largestProduct, largestProductInASeries<T>(SeriesType::DIAGONAL_LEFT, column));
}

return largestProduct;
}

private:
enum SeriesType {
HORIZONTAL, VERTICAL, DIAGONAL_RIGHT, DIAGONAL_LEFT
};

template<typename T>
T largestProductInASeries(SeriesType type, int startingIndex) {
int low = startingIndex, current = low;

T currentProduct = initializeProductInASeries<T>(type, current);
if (current < 0) return 0;
T highestProduct = currentProduct;

while (current >= 0) {
if (currentProduct == 0) {
while (grid_[low] != 0) low = nextIndex(type, low);
low = nextIndex(type, low);
current = low;
currentProduct = initializeProductInASeries<T>(type, current);
} else {
currentProduct /= grid_[low];
currentProduct *= grid_[current];

low = nextIndex(type, low);
current = nextIndex(type, current);
}

highestProduct = std::max(highestProduct, currentProduct);
}

return highestProduct;
}

template<typename T>
T initializeProductInASeries(SeriesType type, int &index) {
T product = 1;
for (int i = 0; i < nAdjacents_ && product > 0; i++) {
product *= grid_[index];
index = nextIndex(type, index);
if (index < 0) return 0;
}
return product;
}

int nextIndex(SeriesType type, int currentIndex) {

auto canAdvanceRight = bool((currentIndex + 1) % columns_);
if (type == SeriesType::HORIZONTAL && canAdvanceRight) {
return currentIndex + 1;
}

auto canAdvanceDown = currentIndex / columns_ + 1 < rows_;
if (type == SeriesType::VERTICAL && canAdvanceDown) {
return currentIndex + columns_;
}

if (type == SeriesType::DIAGONAL_RIGHT && canAdvanceRight && canAdvanceDown) {
return currentIndex + columns_ + 1;
}

auto canAdvanceLeft = bool(currentIndex % columns_);
if (type == SeriesType::DIAGONAL_LEFT && canAdvanceLeft && canAdvanceDown) {
return currentIndex + columns_ - 1;
}

return -1;
}

std::vector<int> grid_;
int rows_;
int columns_;
int nAdjacents_;
};

int main() {
const int rows = 20, columns = 20, nAdjacents = 4;
auto grid = getGrid(rows, columns);
LargestProductInAGrid solution(grid, rows, columns, nAdjacents);
std::cout << solution.largestProductInAGrid<int>() << std::endl;
}


Analysis

Time complexity: $O(r * c)$

Space complexity: $O(1)$, not counting initial data



Comments

Changes:




  1. Combined the logic of rows, columns, and diagonals into a single method.

  2. Templated the methods so that it can handle adjacent numbers <4 efficiently with int and between 5 and 9 numbers with unsigned long long.

  3. getGrid now throws an exception when the input is invalid.










share|improve this question









New contributor




Eric is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$

















    2












    $begingroup$


    Original code review: Project Euler #11 Largest Product in a Grid | Cache-optimized + sliding window (C++14)





    Source: HackerRank & ProjectEuler.net



    Problem: Largest Product in a Grid

    In the 20×20 grid below, four numbers along a diagonal line have been marked in red.



    08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08
    49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00
    81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65
    52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91
    22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80
    24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50
    32 98 81 28 64 23 67 10(26)38 40 67 59 54 70 66 18 38 64 70
    67 26 20 68 02 62 12 20 95(63)94 39 63 08 40 91 66 49 94 21
    24 55 58 05 66 73 99 26 97 17(78)78 96 83 14 88 34 89 63 72
    21 36 23 09 75 00 76 44 20 45 35(14)00 61 33 97 34 31 33 95
    78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92
    16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57
    86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58
    19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40
    04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66
    88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69
    04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36
    20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16
    20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54
    01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48


    The product of these numbers is 26 × 63 × 78 × 14 = 1788696.



    What is the greatest product of four adjacent numbers in the same direction (up, down, left, right, or diagonally) in the 20×20 grid?



    Input

    Input consists of 20 lines each containing 20 integers.



    Output

    Print the required answer.



    Limits

    0 ≤ each integer in the grid ≤ 100



    Sample

    Input



    89 90 95 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08  
    49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00
    81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65
    52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91
    22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80
    24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50
    32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70
    67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21
    24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72
    21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95
    78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92
    16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57
    86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58
    19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40
    04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66
    88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69
    04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36
    20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16
    20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54
    01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48


    Output



    73812150


    My updated solution (C++14)



    #include <iostream>
    #include <vector>
    #include <algorithm>
    #include <iterator>

    // 2D grid represented by 1D vector for cache optimization
    auto getGrid(int rows, int columns) {
    auto values = rows * columns;
    std::vector<int> grid(values);
    std::copy_n(std::istream_iterator<int>(std::cin), values, grid.begin());

    if (std::cin.fail()) {
    throw std::runtime_error(
    "The input is invalid! Check the rows and columns in your input and that all numbers in the grid are integers between 0 and 100.");
    }
    return grid;
    }

    class LargestProductInAGrid {
    public:
    LargestProductInAGrid(std::vector<int> &grid, int rows, int columns, int nAdjacents) : grid_(grid), rows_(rows),
    columns_(columns),
    nAdjacents_(nAdjacents) {}

    template<typename T>
    auto largestProductInAGrid() {
    T largestProduct = 0;

    for (auto row = 0; row < rows_; row++) {
    largestProduct = std::max(largestProduct,
    largestProductInASeries<T>(SeriesType::HORIZONTAL, row * columns_));
    }

    for (auto column = 0; column < columns_; column++) {
    largestProduct = std::max(largestProduct, largestProductInASeries<T>(SeriesType::VERTICAL, column));
    largestProduct = std::max(largestProduct, largestProductInASeries<T>(SeriesType::DIAGONAL_RIGHT, column));
    largestProduct = std::max(largestProduct, largestProductInASeries<T>(SeriesType::DIAGONAL_LEFT, column));
    }

    return largestProduct;
    }

    private:
    enum SeriesType {
    HORIZONTAL, VERTICAL, DIAGONAL_RIGHT, DIAGONAL_LEFT
    };

    template<typename T>
    T largestProductInASeries(SeriesType type, int startingIndex) {
    int low = startingIndex, current = low;

    T currentProduct = initializeProductInASeries<T>(type, current);
    if (current < 0) return 0;
    T highestProduct = currentProduct;

    while (current >= 0) {
    if (currentProduct == 0) {
    while (grid_[low] != 0) low = nextIndex(type, low);
    low = nextIndex(type, low);
    current = low;
    currentProduct = initializeProductInASeries<T>(type, current);
    } else {
    currentProduct /= grid_[low];
    currentProduct *= grid_[current];

    low = nextIndex(type, low);
    current = nextIndex(type, current);
    }

    highestProduct = std::max(highestProduct, currentProduct);
    }

    return highestProduct;
    }

    template<typename T>
    T initializeProductInASeries(SeriesType type, int &index) {
    T product = 1;
    for (int i = 0; i < nAdjacents_ && product > 0; i++) {
    product *= grid_[index];
    index = nextIndex(type, index);
    if (index < 0) return 0;
    }
    return product;
    }

    int nextIndex(SeriesType type, int currentIndex) {

    auto canAdvanceRight = bool((currentIndex + 1) % columns_);
    if (type == SeriesType::HORIZONTAL && canAdvanceRight) {
    return currentIndex + 1;
    }

    auto canAdvanceDown = currentIndex / columns_ + 1 < rows_;
    if (type == SeriesType::VERTICAL && canAdvanceDown) {
    return currentIndex + columns_;
    }

    if (type == SeriesType::DIAGONAL_RIGHT && canAdvanceRight && canAdvanceDown) {
    return currentIndex + columns_ + 1;
    }

    auto canAdvanceLeft = bool(currentIndex % columns_);
    if (type == SeriesType::DIAGONAL_LEFT && canAdvanceLeft && canAdvanceDown) {
    return currentIndex + columns_ - 1;
    }

    return -1;
    }

    std::vector<int> grid_;
    int rows_;
    int columns_;
    int nAdjacents_;
    };

    int main() {
    const int rows = 20, columns = 20, nAdjacents = 4;
    auto grid = getGrid(rows, columns);
    LargestProductInAGrid solution(grid, rows, columns, nAdjacents);
    std::cout << solution.largestProductInAGrid<int>() << std::endl;
    }


    Analysis

    Time complexity: $O(r * c)$

    Space complexity: $O(1)$, not counting initial data



    Comments

    Changes:




    1. Combined the logic of rows, columns, and diagonals into a single method.

    2. Templated the methods so that it can handle adjacent numbers <4 efficiently with int and between 5 and 9 numbers with unsigned long long.

    3. getGrid now throws an exception when the input is invalid.










    share|improve this question









    New contributor




    Eric is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.







    $endgroup$















      2












      2








      2





      $begingroup$


      Original code review: Project Euler #11 Largest Product in a Grid | Cache-optimized + sliding window (C++14)





      Source: HackerRank & ProjectEuler.net



      Problem: Largest Product in a Grid

      In the 20×20 grid below, four numbers along a diagonal line have been marked in red.



      08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08
      49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00
      81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65
      52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91
      22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80
      24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50
      32 98 81 28 64 23 67 10(26)38 40 67 59 54 70 66 18 38 64 70
      67 26 20 68 02 62 12 20 95(63)94 39 63 08 40 91 66 49 94 21
      24 55 58 05 66 73 99 26 97 17(78)78 96 83 14 88 34 89 63 72
      21 36 23 09 75 00 76 44 20 45 35(14)00 61 33 97 34 31 33 95
      78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92
      16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57
      86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58
      19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40
      04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66
      88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69
      04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36
      20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16
      20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54
      01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48


      The product of these numbers is 26 × 63 × 78 × 14 = 1788696.



      What is the greatest product of four adjacent numbers in the same direction (up, down, left, right, or diagonally) in the 20×20 grid?



      Input

      Input consists of 20 lines each containing 20 integers.



      Output

      Print the required answer.



      Limits

      0 ≤ each integer in the grid ≤ 100



      Sample

      Input



      89 90 95 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08  
      49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00
      81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65
      52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91
      22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80
      24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50
      32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70
      67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21
      24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72
      21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95
      78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92
      16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57
      86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58
      19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40
      04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66
      88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69
      04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36
      20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16
      20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54
      01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48


      Output



      73812150


      My updated solution (C++14)



      #include <iostream>
      #include <vector>
      #include <algorithm>
      #include <iterator>

      // 2D grid represented by 1D vector for cache optimization
      auto getGrid(int rows, int columns) {
      auto values = rows * columns;
      std::vector<int> grid(values);
      std::copy_n(std::istream_iterator<int>(std::cin), values, grid.begin());

      if (std::cin.fail()) {
      throw std::runtime_error(
      "The input is invalid! Check the rows and columns in your input and that all numbers in the grid are integers between 0 and 100.");
      }
      return grid;
      }

      class LargestProductInAGrid {
      public:
      LargestProductInAGrid(std::vector<int> &grid, int rows, int columns, int nAdjacents) : grid_(grid), rows_(rows),
      columns_(columns),
      nAdjacents_(nAdjacents) {}

      template<typename T>
      auto largestProductInAGrid() {
      T largestProduct = 0;

      for (auto row = 0; row < rows_; row++) {
      largestProduct = std::max(largestProduct,
      largestProductInASeries<T>(SeriesType::HORIZONTAL, row * columns_));
      }

      for (auto column = 0; column < columns_; column++) {
      largestProduct = std::max(largestProduct, largestProductInASeries<T>(SeriesType::VERTICAL, column));
      largestProduct = std::max(largestProduct, largestProductInASeries<T>(SeriesType::DIAGONAL_RIGHT, column));
      largestProduct = std::max(largestProduct, largestProductInASeries<T>(SeriesType::DIAGONAL_LEFT, column));
      }

      return largestProduct;
      }

      private:
      enum SeriesType {
      HORIZONTAL, VERTICAL, DIAGONAL_RIGHT, DIAGONAL_LEFT
      };

      template<typename T>
      T largestProductInASeries(SeriesType type, int startingIndex) {
      int low = startingIndex, current = low;

      T currentProduct = initializeProductInASeries<T>(type, current);
      if (current < 0) return 0;
      T highestProduct = currentProduct;

      while (current >= 0) {
      if (currentProduct == 0) {
      while (grid_[low] != 0) low = nextIndex(type, low);
      low = nextIndex(type, low);
      current = low;
      currentProduct = initializeProductInASeries<T>(type, current);
      } else {
      currentProduct /= grid_[low];
      currentProduct *= grid_[current];

      low = nextIndex(type, low);
      current = nextIndex(type, current);
      }

      highestProduct = std::max(highestProduct, currentProduct);
      }

      return highestProduct;
      }

      template<typename T>
      T initializeProductInASeries(SeriesType type, int &index) {
      T product = 1;
      for (int i = 0; i < nAdjacents_ && product > 0; i++) {
      product *= grid_[index];
      index = nextIndex(type, index);
      if (index < 0) return 0;
      }
      return product;
      }

      int nextIndex(SeriesType type, int currentIndex) {

      auto canAdvanceRight = bool((currentIndex + 1) % columns_);
      if (type == SeriesType::HORIZONTAL && canAdvanceRight) {
      return currentIndex + 1;
      }

      auto canAdvanceDown = currentIndex / columns_ + 1 < rows_;
      if (type == SeriesType::VERTICAL && canAdvanceDown) {
      return currentIndex + columns_;
      }

      if (type == SeriesType::DIAGONAL_RIGHT && canAdvanceRight && canAdvanceDown) {
      return currentIndex + columns_ + 1;
      }

      auto canAdvanceLeft = bool(currentIndex % columns_);
      if (type == SeriesType::DIAGONAL_LEFT && canAdvanceLeft && canAdvanceDown) {
      return currentIndex + columns_ - 1;
      }

      return -1;
      }

      std::vector<int> grid_;
      int rows_;
      int columns_;
      int nAdjacents_;
      };

      int main() {
      const int rows = 20, columns = 20, nAdjacents = 4;
      auto grid = getGrid(rows, columns);
      LargestProductInAGrid solution(grid, rows, columns, nAdjacents);
      std::cout << solution.largestProductInAGrid<int>() << std::endl;
      }


      Analysis

      Time complexity: $O(r * c)$

      Space complexity: $O(1)$, not counting initial data



      Comments

      Changes:




      1. Combined the logic of rows, columns, and diagonals into a single method.

      2. Templated the methods so that it can handle adjacent numbers <4 efficiently with int and between 5 and 9 numbers with unsigned long long.

      3. getGrid now throws an exception when the input is invalid.










      share|improve this question









      New contributor




      Eric is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.







      $endgroup$




      Original code review: Project Euler #11 Largest Product in a Grid | Cache-optimized + sliding window (C++14)





      Source: HackerRank & ProjectEuler.net



      Problem: Largest Product in a Grid

      In the 20×20 grid below, four numbers along a diagonal line have been marked in red.



      08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08
      49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00
      81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65
      52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91
      22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80
      24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50
      32 98 81 28 64 23 67 10(26)38 40 67 59 54 70 66 18 38 64 70
      67 26 20 68 02 62 12 20 95(63)94 39 63 08 40 91 66 49 94 21
      24 55 58 05 66 73 99 26 97 17(78)78 96 83 14 88 34 89 63 72
      21 36 23 09 75 00 76 44 20 45 35(14)00 61 33 97 34 31 33 95
      78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92
      16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57
      86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58
      19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40
      04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66
      88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69
      04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36
      20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16
      20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54
      01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48


      The product of these numbers is 26 × 63 × 78 × 14 = 1788696.



      What is the greatest product of four adjacent numbers in the same direction (up, down, left, right, or diagonally) in the 20×20 grid?



      Input

      Input consists of 20 lines each containing 20 integers.



      Output

      Print the required answer.



      Limits

      0 ≤ each integer in the grid ≤ 100



      Sample

      Input



      89 90 95 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08  
      49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00
      81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65
      52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91
      22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80
      24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50
      32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70
      67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21
      24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72
      21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95
      78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92
      16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57
      86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58
      19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40
      04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66
      88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69
      04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36
      20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16
      20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54
      01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48


      Output



      73812150


      My updated solution (C++14)



      #include <iostream>
      #include <vector>
      #include <algorithm>
      #include <iterator>

      // 2D grid represented by 1D vector for cache optimization
      auto getGrid(int rows, int columns) {
      auto values = rows * columns;
      std::vector<int> grid(values);
      std::copy_n(std::istream_iterator<int>(std::cin), values, grid.begin());

      if (std::cin.fail()) {
      throw std::runtime_error(
      "The input is invalid! Check the rows and columns in your input and that all numbers in the grid are integers between 0 and 100.");
      }
      return grid;
      }

      class LargestProductInAGrid {
      public:
      LargestProductInAGrid(std::vector<int> &grid, int rows, int columns, int nAdjacents) : grid_(grid), rows_(rows),
      columns_(columns),
      nAdjacents_(nAdjacents) {}

      template<typename T>
      auto largestProductInAGrid() {
      T largestProduct = 0;

      for (auto row = 0; row < rows_; row++) {
      largestProduct = std::max(largestProduct,
      largestProductInASeries<T>(SeriesType::HORIZONTAL, row * columns_));
      }

      for (auto column = 0; column < columns_; column++) {
      largestProduct = std::max(largestProduct, largestProductInASeries<T>(SeriesType::VERTICAL, column));
      largestProduct = std::max(largestProduct, largestProductInASeries<T>(SeriesType::DIAGONAL_RIGHT, column));
      largestProduct = std::max(largestProduct, largestProductInASeries<T>(SeriesType::DIAGONAL_LEFT, column));
      }

      return largestProduct;
      }

      private:
      enum SeriesType {
      HORIZONTAL, VERTICAL, DIAGONAL_RIGHT, DIAGONAL_LEFT
      };

      template<typename T>
      T largestProductInASeries(SeriesType type, int startingIndex) {
      int low = startingIndex, current = low;

      T currentProduct = initializeProductInASeries<T>(type, current);
      if (current < 0) return 0;
      T highestProduct = currentProduct;

      while (current >= 0) {
      if (currentProduct == 0) {
      while (grid_[low] != 0) low = nextIndex(type, low);
      low = nextIndex(type, low);
      current = low;
      currentProduct = initializeProductInASeries<T>(type, current);
      } else {
      currentProduct /= grid_[low];
      currentProduct *= grid_[current];

      low = nextIndex(type, low);
      current = nextIndex(type, current);
      }

      highestProduct = std::max(highestProduct, currentProduct);
      }

      return highestProduct;
      }

      template<typename T>
      T initializeProductInASeries(SeriesType type, int &index) {
      T product = 1;
      for (int i = 0; i < nAdjacents_ && product > 0; i++) {
      product *= grid_[index];
      index = nextIndex(type, index);
      if (index < 0) return 0;
      }
      return product;
      }

      int nextIndex(SeriesType type, int currentIndex) {

      auto canAdvanceRight = bool((currentIndex + 1) % columns_);
      if (type == SeriesType::HORIZONTAL && canAdvanceRight) {
      return currentIndex + 1;
      }

      auto canAdvanceDown = currentIndex / columns_ + 1 < rows_;
      if (type == SeriesType::VERTICAL && canAdvanceDown) {
      return currentIndex + columns_;
      }

      if (type == SeriesType::DIAGONAL_RIGHT && canAdvanceRight && canAdvanceDown) {
      return currentIndex + columns_ + 1;
      }

      auto canAdvanceLeft = bool(currentIndex % columns_);
      if (type == SeriesType::DIAGONAL_LEFT && canAdvanceLeft && canAdvanceDown) {
      return currentIndex + columns_ - 1;
      }

      return -1;
      }

      std::vector<int> grid_;
      int rows_;
      int columns_;
      int nAdjacents_;
      };

      int main() {
      const int rows = 20, columns = 20, nAdjacents = 4;
      auto grid = getGrid(rows, columns);
      LargestProductInAGrid solution(grid, rows, columns, nAdjacents);
      std::cout << solution.largestProductInAGrid<int>() << std::endl;
      }


      Analysis

      Time complexity: $O(r * c)$

      Space complexity: $O(1)$, not counting initial data



      Comments

      Changes:




      1. Combined the logic of rows, columns, and diagonals into a single method.

      2. Templated the methods so that it can handle adjacent numbers <4 efficiently with int and between 5 and 9 numbers with unsigned long long.

      3. getGrid now throws an exception when the input is invalid.







      c++ performance object-oriented programming-challenge c++14






      share|improve this question









      New contributor




      Eric is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.











      share|improve this question









      New contributor




      Eric is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      share|improve this question




      share|improve this question








      edited yesterday







      Eric













      New contributor




      Eric is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      asked yesterday









      EricEric

      1736




      1736




      New contributor




      Eric is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.





      New contributor





      Eric is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






      Eric is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






















          1 Answer
          1






          active

          oldest

          votes


















          5












          $begingroup$

          I'd separate the concerns of storage (Grid) and the search (longestProduct), like this:



          class Grid
          {
          std::vector<int> grid;
          int rows;
          int columns;

          public:
          Grid(int rows, int columns)
          : grid(rows * columns),
          rows(rows), columns(columns)
          {
          }

          void read(std::istream& in);
          long largestProduct(unsigned nAdjacents) const;
          }


          See how we can now re-use one grid and find its largest 3-product, 4-product, etc. without needed to re-instantiate.



          To calculate a n-product, we just need to know the starting point, stride, and length:



          private:
          long product(int x, int y, int step, unsigned n) const
          {
          long product = 1;
          for (auto *p = grid.data() + columns * x + y; n-- > 0; p += step) {
          product *= *p;
          }
          return product;
          }


          We can create a "high water mark" type to save typing all those std::max() invocations:



          // a simple value that can only be ovewritten by greater values
          template<typename T>
          struct MaxValue
          {
          T value;

          MaxValue(T value = T{})
          : value(value)
          {}

          operator T() const
          {
          return value;
          }

          MaxValue& operator=(T other)
          {
          if (value < other)
          value = other;
          return *this;
          }
          };


          Then our largestProduct search becomes much simpler (C++17, for my convenience):



          long largestProduct(unsigned nAdjacents) const
          {
          static const std::initializer_list<std::pair<int,int>> directions
          = {{0,1}, {1,1}, {1,0}, {1,-1}};

          MaxValue<long> largestProduct = 0;
          for (auto const [dy, dx]: directions) {
          // determine range to search
          auto const row_0 = 0u;
          auto const row_n = dy > 0 ? rows - nAdjacents : rows;
          auto const col_0 = dx < 0 ? nAdjacents : 0;
          auto const col_n = dx > 0 ? columns - nAdjacents : columns;
          auto const step = dy * columns + dx;
          // do the search
          for (auto r = row_0; r < row_n; ++r) {
          for (auto c = col_0; c < col_n; ++c) {
          largestProduct = product(r, c, step, nAdjacents);
          }
          }
          }
          return largestProduct;
          }




          Full code



          #include <algorithm>
          #include <initializer_list>
          #include <iterator>
          #include <istream>
          #include <vector>

          // a simple value that can only be ovewritten by greater values
          template<typename T>
          struct MaxValue
          {
          T value;

          MaxValue(T value = T{})
          : value(value)
          {}

          operator T() const
          {
          return value;
          }

          MaxValue& operator=(T other)
          {
          if (value < other)
          value = other;
          return *this;
          }
          };


          class Grid
          {
          std::vector<int> grid;
          int rows;
          int columns;

          public:
          Grid(int rows, int columns)
          : grid(rows * columns),
          rows(rows), columns(columns)
          {
          }

          void read(std::istream& in)
          {
          // temporarily set in to throw on error
          auto saved_exceptions = in.exceptions();
          in.exceptions(std::ios_base::failbit | std::ios_base::badbit);

          auto values = rows * columns;
          std::copy_n(std::istream_iterator<int>(in), values, grid.begin());

          // restore exception state
          in.exceptions(saved_exceptions);
          }

          long largestProduct(unsigned nAdjacents) const
          {
          static const std::initializer_list<std::pair<int,int>> directions
          = {{0,1}, {1,1}, {1,0}, {1,-1}};

          MaxValue<long> largestProduct = 0;
          for (auto const [dy, dx]: directions) {
          // determine range to search
          auto const row_0 = 0u;
          auto const row_n = dy > 0 ? rows - nAdjacents : rows;
          auto const col_0 = dx < 0 ? nAdjacents : 0;
          auto const col_n = dx > 0 ? columns - nAdjacents : columns;
          auto const step = dy * columns + dx;
          // do the search
          for (auto r = row_0; r < row_n; ++r) {
          for (auto c = col_0; c < col_n; ++c) {
          largestProduct = product(r, c, step, nAdjacents);
          }
          }
          }
          return largestProduct;
          }

          private:
          long product(int x, int y, int step, unsigned n) const
          {
          long product = 1;
          for (auto *p = grid.data() + columns * x + y; n-- > 0; p += step) {
          product *= *p;
          }
          return product;
          }
          };



          #include <iostream>
          #include <sstream>

          int main()
          {
          std::istringstream in(R"(
          89 90 95 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08
          49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00
          81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65
          52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91
          22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80
          24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50
          32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70
          67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21
          24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72
          21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95
          78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92
          16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57
          86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58
          19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40
          04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66
          88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69
          04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36
          20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16
          20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54
          01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48
          )");
          Grid grid{20, 20};
          grid.read(in);

          std::cout << grid.largestProduct(4) << std::endl;
          }




          From here, we might investigate ideas like the rolling product; that might provide less benefit than you expect, given how much more expensive division is compared to multiplication.






          share|improve this answer









          $endgroup$













          • $begingroup$
            I don't agree with the design to tightly couple the reading of the data and the function largestProduct. What if the data comes from a database, a web response, a file, a POST request, etc.? Technically we could transform into a string then pass it an an istream, but we could do better. In fact, largeProduct is a pure function, and it doesn't need to instantiate an object. I implemented in a class because I didn't want to pass 6 parameters to helper functions.
            $endgroup$
            – Eric
            7 hours ago






          • 1




            $begingroup$
            I think the best design would be to have a Grid struct that can be constructed by the different classes that would implement different ways to get the data, and then pass that Grid struct + nAdjacents to a pure function largestProduct as parameters.
            $endgroup$
            – Eric
            7 hours ago










          • $begingroup$
            The class LargestProductInAGrid is like a closure, and all you have to do is add a setter to be able to change the grid or number of adjacent products.
            $endgroup$
            – Eric
            7 hours ago








          • 1




            $begingroup$
            "a Grid struct that can be constructed by the different classes..." - Indeed, I agree with that. I was just being lazy when I made read() a member.
            $endgroup$
            – Toby Speight
            6 hours ago












          Your Answer





          StackExchange.ifUsing("editor", function () {
          return StackExchange.using("mathjaxEditing", function () {
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
          });
          });
          }, "mathjax-editing");

          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "196"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });






          Eric is a new contributor. Be nice, and check out our Code of Conduct.










          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f216426%2ffollow-up-project-euler-11-largest-product-in-a-grid-cache-optimized-slid%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          5












          $begingroup$

          I'd separate the concerns of storage (Grid) and the search (longestProduct), like this:



          class Grid
          {
          std::vector<int> grid;
          int rows;
          int columns;

          public:
          Grid(int rows, int columns)
          : grid(rows * columns),
          rows(rows), columns(columns)
          {
          }

          void read(std::istream& in);
          long largestProduct(unsigned nAdjacents) const;
          }


          See how we can now re-use one grid and find its largest 3-product, 4-product, etc. without needed to re-instantiate.



          To calculate a n-product, we just need to know the starting point, stride, and length:



          private:
          long product(int x, int y, int step, unsigned n) const
          {
          long product = 1;
          for (auto *p = grid.data() + columns * x + y; n-- > 0; p += step) {
          product *= *p;
          }
          return product;
          }


          We can create a "high water mark" type to save typing all those std::max() invocations:



          // a simple value that can only be ovewritten by greater values
          template<typename T>
          struct MaxValue
          {
          T value;

          MaxValue(T value = T{})
          : value(value)
          {}

          operator T() const
          {
          return value;
          }

          MaxValue& operator=(T other)
          {
          if (value < other)
          value = other;
          return *this;
          }
          };


          Then our largestProduct search becomes much simpler (C++17, for my convenience):



          long largestProduct(unsigned nAdjacents) const
          {
          static const std::initializer_list<std::pair<int,int>> directions
          = {{0,1}, {1,1}, {1,0}, {1,-1}};

          MaxValue<long> largestProduct = 0;
          for (auto const [dy, dx]: directions) {
          // determine range to search
          auto const row_0 = 0u;
          auto const row_n = dy > 0 ? rows - nAdjacents : rows;
          auto const col_0 = dx < 0 ? nAdjacents : 0;
          auto const col_n = dx > 0 ? columns - nAdjacents : columns;
          auto const step = dy * columns + dx;
          // do the search
          for (auto r = row_0; r < row_n; ++r) {
          for (auto c = col_0; c < col_n; ++c) {
          largestProduct = product(r, c, step, nAdjacents);
          }
          }
          }
          return largestProduct;
          }




          Full code



          #include <algorithm>
          #include <initializer_list>
          #include <iterator>
          #include <istream>
          #include <vector>

          // a simple value that can only be ovewritten by greater values
          template<typename T>
          struct MaxValue
          {
          T value;

          MaxValue(T value = T{})
          : value(value)
          {}

          operator T() const
          {
          return value;
          }

          MaxValue& operator=(T other)
          {
          if (value < other)
          value = other;
          return *this;
          }
          };


          class Grid
          {
          std::vector<int> grid;
          int rows;
          int columns;

          public:
          Grid(int rows, int columns)
          : grid(rows * columns),
          rows(rows), columns(columns)
          {
          }

          void read(std::istream& in)
          {
          // temporarily set in to throw on error
          auto saved_exceptions = in.exceptions();
          in.exceptions(std::ios_base::failbit | std::ios_base::badbit);

          auto values = rows * columns;
          std::copy_n(std::istream_iterator<int>(in), values, grid.begin());

          // restore exception state
          in.exceptions(saved_exceptions);
          }

          long largestProduct(unsigned nAdjacents) const
          {
          static const std::initializer_list<std::pair<int,int>> directions
          = {{0,1}, {1,1}, {1,0}, {1,-1}};

          MaxValue<long> largestProduct = 0;
          for (auto const [dy, dx]: directions) {
          // determine range to search
          auto const row_0 = 0u;
          auto const row_n = dy > 0 ? rows - nAdjacents : rows;
          auto const col_0 = dx < 0 ? nAdjacents : 0;
          auto const col_n = dx > 0 ? columns - nAdjacents : columns;
          auto const step = dy * columns + dx;
          // do the search
          for (auto r = row_0; r < row_n; ++r) {
          for (auto c = col_0; c < col_n; ++c) {
          largestProduct = product(r, c, step, nAdjacents);
          }
          }
          }
          return largestProduct;
          }

          private:
          long product(int x, int y, int step, unsigned n) const
          {
          long product = 1;
          for (auto *p = grid.data() + columns * x + y; n-- > 0; p += step) {
          product *= *p;
          }
          return product;
          }
          };



          #include <iostream>
          #include <sstream>

          int main()
          {
          std::istringstream in(R"(
          89 90 95 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08
          49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00
          81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65
          52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91
          22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80
          24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50
          32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70
          67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21
          24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72
          21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95
          78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92
          16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57
          86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58
          19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40
          04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66
          88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69
          04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36
          20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16
          20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54
          01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48
          )");
          Grid grid{20, 20};
          grid.read(in);

          std::cout << grid.largestProduct(4) << std::endl;
          }




          From here, we might investigate ideas like the rolling product; that might provide less benefit than you expect, given how much more expensive division is compared to multiplication.






          share|improve this answer









          $endgroup$













          • $begingroup$
            I don't agree with the design to tightly couple the reading of the data and the function largestProduct. What if the data comes from a database, a web response, a file, a POST request, etc.? Technically we could transform into a string then pass it an an istream, but we could do better. In fact, largeProduct is a pure function, and it doesn't need to instantiate an object. I implemented in a class because I didn't want to pass 6 parameters to helper functions.
            $endgroup$
            – Eric
            7 hours ago






          • 1




            $begingroup$
            I think the best design would be to have a Grid struct that can be constructed by the different classes that would implement different ways to get the data, and then pass that Grid struct + nAdjacents to a pure function largestProduct as parameters.
            $endgroup$
            – Eric
            7 hours ago










          • $begingroup$
            The class LargestProductInAGrid is like a closure, and all you have to do is add a setter to be able to change the grid or number of adjacent products.
            $endgroup$
            – Eric
            7 hours ago








          • 1




            $begingroup$
            "a Grid struct that can be constructed by the different classes..." - Indeed, I agree with that. I was just being lazy when I made read() a member.
            $endgroup$
            – Toby Speight
            6 hours ago
















          5












          $begingroup$

          I'd separate the concerns of storage (Grid) and the search (longestProduct), like this:



          class Grid
          {
          std::vector<int> grid;
          int rows;
          int columns;

          public:
          Grid(int rows, int columns)
          : grid(rows * columns),
          rows(rows), columns(columns)
          {
          }

          void read(std::istream& in);
          long largestProduct(unsigned nAdjacents) const;
          }


          See how we can now re-use one grid and find its largest 3-product, 4-product, etc. without needed to re-instantiate.



          To calculate a n-product, we just need to know the starting point, stride, and length:



          private:
          long product(int x, int y, int step, unsigned n) const
          {
          long product = 1;
          for (auto *p = grid.data() + columns * x + y; n-- > 0; p += step) {
          product *= *p;
          }
          return product;
          }


          We can create a "high water mark" type to save typing all those std::max() invocations:



          // a simple value that can only be ovewritten by greater values
          template<typename T>
          struct MaxValue
          {
          T value;

          MaxValue(T value = T{})
          : value(value)
          {}

          operator T() const
          {
          return value;
          }

          MaxValue& operator=(T other)
          {
          if (value < other)
          value = other;
          return *this;
          }
          };


          Then our largestProduct search becomes much simpler (C++17, for my convenience):



          long largestProduct(unsigned nAdjacents) const
          {
          static const std::initializer_list<std::pair<int,int>> directions
          = {{0,1}, {1,1}, {1,0}, {1,-1}};

          MaxValue<long> largestProduct = 0;
          for (auto const [dy, dx]: directions) {
          // determine range to search
          auto const row_0 = 0u;
          auto const row_n = dy > 0 ? rows - nAdjacents : rows;
          auto const col_0 = dx < 0 ? nAdjacents : 0;
          auto const col_n = dx > 0 ? columns - nAdjacents : columns;
          auto const step = dy * columns + dx;
          // do the search
          for (auto r = row_0; r < row_n; ++r) {
          for (auto c = col_0; c < col_n; ++c) {
          largestProduct = product(r, c, step, nAdjacents);
          }
          }
          }
          return largestProduct;
          }




          Full code



          #include <algorithm>
          #include <initializer_list>
          #include <iterator>
          #include <istream>
          #include <vector>

          // a simple value that can only be ovewritten by greater values
          template<typename T>
          struct MaxValue
          {
          T value;

          MaxValue(T value = T{})
          : value(value)
          {}

          operator T() const
          {
          return value;
          }

          MaxValue& operator=(T other)
          {
          if (value < other)
          value = other;
          return *this;
          }
          };


          class Grid
          {
          std::vector<int> grid;
          int rows;
          int columns;

          public:
          Grid(int rows, int columns)
          : grid(rows * columns),
          rows(rows), columns(columns)
          {
          }

          void read(std::istream& in)
          {
          // temporarily set in to throw on error
          auto saved_exceptions = in.exceptions();
          in.exceptions(std::ios_base::failbit | std::ios_base::badbit);

          auto values = rows * columns;
          std::copy_n(std::istream_iterator<int>(in), values, grid.begin());

          // restore exception state
          in.exceptions(saved_exceptions);
          }

          long largestProduct(unsigned nAdjacents) const
          {
          static const std::initializer_list<std::pair<int,int>> directions
          = {{0,1}, {1,1}, {1,0}, {1,-1}};

          MaxValue<long> largestProduct = 0;
          for (auto const [dy, dx]: directions) {
          // determine range to search
          auto const row_0 = 0u;
          auto const row_n = dy > 0 ? rows - nAdjacents : rows;
          auto const col_0 = dx < 0 ? nAdjacents : 0;
          auto const col_n = dx > 0 ? columns - nAdjacents : columns;
          auto const step = dy * columns + dx;
          // do the search
          for (auto r = row_0; r < row_n; ++r) {
          for (auto c = col_0; c < col_n; ++c) {
          largestProduct = product(r, c, step, nAdjacents);
          }
          }
          }
          return largestProduct;
          }

          private:
          long product(int x, int y, int step, unsigned n) const
          {
          long product = 1;
          for (auto *p = grid.data() + columns * x + y; n-- > 0; p += step) {
          product *= *p;
          }
          return product;
          }
          };



          #include <iostream>
          #include <sstream>

          int main()
          {
          std::istringstream in(R"(
          89 90 95 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08
          49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00
          81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65
          52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91
          22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80
          24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50
          32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70
          67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21
          24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72
          21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95
          78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92
          16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57
          86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58
          19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40
          04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66
          88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69
          04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36
          20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16
          20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54
          01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48
          )");
          Grid grid{20, 20};
          grid.read(in);

          std::cout << grid.largestProduct(4) << std::endl;
          }




          From here, we might investigate ideas like the rolling product; that might provide less benefit than you expect, given how much more expensive division is compared to multiplication.






          share|improve this answer









          $endgroup$













          • $begingroup$
            I don't agree with the design to tightly couple the reading of the data and the function largestProduct. What if the data comes from a database, a web response, a file, a POST request, etc.? Technically we could transform into a string then pass it an an istream, but we could do better. In fact, largeProduct is a pure function, and it doesn't need to instantiate an object. I implemented in a class because I didn't want to pass 6 parameters to helper functions.
            $endgroup$
            – Eric
            7 hours ago






          • 1




            $begingroup$
            I think the best design would be to have a Grid struct that can be constructed by the different classes that would implement different ways to get the data, and then pass that Grid struct + nAdjacents to a pure function largestProduct as parameters.
            $endgroup$
            – Eric
            7 hours ago










          • $begingroup$
            The class LargestProductInAGrid is like a closure, and all you have to do is add a setter to be able to change the grid or number of adjacent products.
            $endgroup$
            – Eric
            7 hours ago








          • 1




            $begingroup$
            "a Grid struct that can be constructed by the different classes..." - Indeed, I agree with that. I was just being lazy when I made read() a member.
            $endgroup$
            – Toby Speight
            6 hours ago














          5












          5








          5





          $begingroup$

          I'd separate the concerns of storage (Grid) and the search (longestProduct), like this:



          class Grid
          {
          std::vector<int> grid;
          int rows;
          int columns;

          public:
          Grid(int rows, int columns)
          : grid(rows * columns),
          rows(rows), columns(columns)
          {
          }

          void read(std::istream& in);
          long largestProduct(unsigned nAdjacents) const;
          }


          See how we can now re-use one grid and find its largest 3-product, 4-product, etc. without needed to re-instantiate.



          To calculate a n-product, we just need to know the starting point, stride, and length:



          private:
          long product(int x, int y, int step, unsigned n) const
          {
          long product = 1;
          for (auto *p = grid.data() + columns * x + y; n-- > 0; p += step) {
          product *= *p;
          }
          return product;
          }


          We can create a "high water mark" type to save typing all those std::max() invocations:



          // a simple value that can only be ovewritten by greater values
          template<typename T>
          struct MaxValue
          {
          T value;

          MaxValue(T value = T{})
          : value(value)
          {}

          operator T() const
          {
          return value;
          }

          MaxValue& operator=(T other)
          {
          if (value < other)
          value = other;
          return *this;
          }
          };


          Then our largestProduct search becomes much simpler (C++17, for my convenience):



          long largestProduct(unsigned nAdjacents) const
          {
          static const std::initializer_list<std::pair<int,int>> directions
          = {{0,1}, {1,1}, {1,0}, {1,-1}};

          MaxValue<long> largestProduct = 0;
          for (auto const [dy, dx]: directions) {
          // determine range to search
          auto const row_0 = 0u;
          auto const row_n = dy > 0 ? rows - nAdjacents : rows;
          auto const col_0 = dx < 0 ? nAdjacents : 0;
          auto const col_n = dx > 0 ? columns - nAdjacents : columns;
          auto const step = dy * columns + dx;
          // do the search
          for (auto r = row_0; r < row_n; ++r) {
          for (auto c = col_0; c < col_n; ++c) {
          largestProduct = product(r, c, step, nAdjacents);
          }
          }
          }
          return largestProduct;
          }




          Full code



          #include <algorithm>
          #include <initializer_list>
          #include <iterator>
          #include <istream>
          #include <vector>

          // a simple value that can only be ovewritten by greater values
          template<typename T>
          struct MaxValue
          {
          T value;

          MaxValue(T value = T{})
          : value(value)
          {}

          operator T() const
          {
          return value;
          }

          MaxValue& operator=(T other)
          {
          if (value < other)
          value = other;
          return *this;
          }
          };


          class Grid
          {
          std::vector<int> grid;
          int rows;
          int columns;

          public:
          Grid(int rows, int columns)
          : grid(rows * columns),
          rows(rows), columns(columns)
          {
          }

          void read(std::istream& in)
          {
          // temporarily set in to throw on error
          auto saved_exceptions = in.exceptions();
          in.exceptions(std::ios_base::failbit | std::ios_base::badbit);

          auto values = rows * columns;
          std::copy_n(std::istream_iterator<int>(in), values, grid.begin());

          // restore exception state
          in.exceptions(saved_exceptions);
          }

          long largestProduct(unsigned nAdjacents) const
          {
          static const std::initializer_list<std::pair<int,int>> directions
          = {{0,1}, {1,1}, {1,0}, {1,-1}};

          MaxValue<long> largestProduct = 0;
          for (auto const [dy, dx]: directions) {
          // determine range to search
          auto const row_0 = 0u;
          auto const row_n = dy > 0 ? rows - nAdjacents : rows;
          auto const col_0 = dx < 0 ? nAdjacents : 0;
          auto const col_n = dx > 0 ? columns - nAdjacents : columns;
          auto const step = dy * columns + dx;
          // do the search
          for (auto r = row_0; r < row_n; ++r) {
          for (auto c = col_0; c < col_n; ++c) {
          largestProduct = product(r, c, step, nAdjacents);
          }
          }
          }
          return largestProduct;
          }

          private:
          long product(int x, int y, int step, unsigned n) const
          {
          long product = 1;
          for (auto *p = grid.data() + columns * x + y; n-- > 0; p += step) {
          product *= *p;
          }
          return product;
          }
          };



          #include <iostream>
          #include <sstream>

          int main()
          {
          std::istringstream in(R"(
          89 90 95 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08
          49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00
          81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65
          52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91
          22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80
          24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50
          32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70
          67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21
          24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72
          21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95
          78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92
          16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57
          86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58
          19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40
          04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66
          88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69
          04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36
          20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16
          20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54
          01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48
          )");
          Grid grid{20, 20};
          grid.read(in);

          std::cout << grid.largestProduct(4) << std::endl;
          }




          From here, we might investigate ideas like the rolling product; that might provide less benefit than you expect, given how much more expensive division is compared to multiplication.






          share|improve this answer









          $endgroup$



          I'd separate the concerns of storage (Grid) and the search (longestProduct), like this:



          class Grid
          {
          std::vector<int> grid;
          int rows;
          int columns;

          public:
          Grid(int rows, int columns)
          : grid(rows * columns),
          rows(rows), columns(columns)
          {
          }

          void read(std::istream& in);
          long largestProduct(unsigned nAdjacents) const;
          }


          See how we can now re-use one grid and find its largest 3-product, 4-product, etc. without needed to re-instantiate.



          To calculate a n-product, we just need to know the starting point, stride, and length:



          private:
          long product(int x, int y, int step, unsigned n) const
          {
          long product = 1;
          for (auto *p = grid.data() + columns * x + y; n-- > 0; p += step) {
          product *= *p;
          }
          return product;
          }


          We can create a "high water mark" type to save typing all those std::max() invocations:



          // a simple value that can only be ovewritten by greater values
          template<typename T>
          struct MaxValue
          {
          T value;

          MaxValue(T value = T{})
          : value(value)
          {}

          operator T() const
          {
          return value;
          }

          MaxValue& operator=(T other)
          {
          if (value < other)
          value = other;
          return *this;
          }
          };


          Then our largestProduct search becomes much simpler (C++17, for my convenience):



          long largestProduct(unsigned nAdjacents) const
          {
          static const std::initializer_list<std::pair<int,int>> directions
          = {{0,1}, {1,1}, {1,0}, {1,-1}};

          MaxValue<long> largestProduct = 0;
          for (auto const [dy, dx]: directions) {
          // determine range to search
          auto const row_0 = 0u;
          auto const row_n = dy > 0 ? rows - nAdjacents : rows;
          auto const col_0 = dx < 0 ? nAdjacents : 0;
          auto const col_n = dx > 0 ? columns - nAdjacents : columns;
          auto const step = dy * columns + dx;
          // do the search
          for (auto r = row_0; r < row_n; ++r) {
          for (auto c = col_0; c < col_n; ++c) {
          largestProduct = product(r, c, step, nAdjacents);
          }
          }
          }
          return largestProduct;
          }




          Full code



          #include <algorithm>
          #include <initializer_list>
          #include <iterator>
          #include <istream>
          #include <vector>

          // a simple value that can only be ovewritten by greater values
          template<typename T>
          struct MaxValue
          {
          T value;

          MaxValue(T value = T{})
          : value(value)
          {}

          operator T() const
          {
          return value;
          }

          MaxValue& operator=(T other)
          {
          if (value < other)
          value = other;
          return *this;
          }
          };


          class Grid
          {
          std::vector<int> grid;
          int rows;
          int columns;

          public:
          Grid(int rows, int columns)
          : grid(rows * columns),
          rows(rows), columns(columns)
          {
          }

          void read(std::istream& in)
          {
          // temporarily set in to throw on error
          auto saved_exceptions = in.exceptions();
          in.exceptions(std::ios_base::failbit | std::ios_base::badbit);

          auto values = rows * columns;
          std::copy_n(std::istream_iterator<int>(in), values, grid.begin());

          // restore exception state
          in.exceptions(saved_exceptions);
          }

          long largestProduct(unsigned nAdjacents) const
          {
          static const std::initializer_list<std::pair<int,int>> directions
          = {{0,1}, {1,1}, {1,0}, {1,-1}};

          MaxValue<long> largestProduct = 0;
          for (auto const [dy, dx]: directions) {
          // determine range to search
          auto const row_0 = 0u;
          auto const row_n = dy > 0 ? rows - nAdjacents : rows;
          auto const col_0 = dx < 0 ? nAdjacents : 0;
          auto const col_n = dx > 0 ? columns - nAdjacents : columns;
          auto const step = dy * columns + dx;
          // do the search
          for (auto r = row_0; r < row_n; ++r) {
          for (auto c = col_0; c < col_n; ++c) {
          largestProduct = product(r, c, step, nAdjacents);
          }
          }
          }
          return largestProduct;
          }

          private:
          long product(int x, int y, int step, unsigned n) const
          {
          long product = 1;
          for (auto *p = grid.data() + columns * x + y; n-- > 0; p += step) {
          product *= *p;
          }
          return product;
          }
          };



          #include <iostream>
          #include <sstream>

          int main()
          {
          std::istringstream in(R"(
          89 90 95 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08
          49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00
          81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65
          52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91
          22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80
          24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50
          32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70
          67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21
          24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72
          21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95
          78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92
          16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57
          86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58
          19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40
          04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66
          88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69
          04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36
          20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16
          20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54
          01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48
          )");
          Grid grid{20, 20};
          grid.read(in);

          std::cout << grid.largestProduct(4) << std::endl;
          }




          From here, we might investigate ideas like the rolling product; that might provide less benefit than you expect, given how much more expensive division is compared to multiplication.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered yesterday









          Toby SpeightToby Speight

          26.8k742118




          26.8k742118












          • $begingroup$
            I don't agree with the design to tightly couple the reading of the data and the function largestProduct. What if the data comes from a database, a web response, a file, a POST request, etc.? Technically we could transform into a string then pass it an an istream, but we could do better. In fact, largeProduct is a pure function, and it doesn't need to instantiate an object. I implemented in a class because I didn't want to pass 6 parameters to helper functions.
            $endgroup$
            – Eric
            7 hours ago






          • 1




            $begingroup$
            I think the best design would be to have a Grid struct that can be constructed by the different classes that would implement different ways to get the data, and then pass that Grid struct + nAdjacents to a pure function largestProduct as parameters.
            $endgroup$
            – Eric
            7 hours ago










          • $begingroup$
            The class LargestProductInAGrid is like a closure, and all you have to do is add a setter to be able to change the grid or number of adjacent products.
            $endgroup$
            – Eric
            7 hours ago








          • 1




            $begingroup$
            "a Grid struct that can be constructed by the different classes..." - Indeed, I agree with that. I was just being lazy when I made read() a member.
            $endgroup$
            – Toby Speight
            6 hours ago


















          • $begingroup$
            I don't agree with the design to tightly couple the reading of the data and the function largestProduct. What if the data comes from a database, a web response, a file, a POST request, etc.? Technically we could transform into a string then pass it an an istream, but we could do better. In fact, largeProduct is a pure function, and it doesn't need to instantiate an object. I implemented in a class because I didn't want to pass 6 parameters to helper functions.
            $endgroup$
            – Eric
            7 hours ago






          • 1




            $begingroup$
            I think the best design would be to have a Grid struct that can be constructed by the different classes that would implement different ways to get the data, and then pass that Grid struct + nAdjacents to a pure function largestProduct as parameters.
            $endgroup$
            – Eric
            7 hours ago










          • $begingroup$
            The class LargestProductInAGrid is like a closure, and all you have to do is add a setter to be able to change the grid or number of adjacent products.
            $endgroup$
            – Eric
            7 hours ago








          • 1




            $begingroup$
            "a Grid struct that can be constructed by the different classes..." - Indeed, I agree with that. I was just being lazy when I made read() a member.
            $endgroup$
            – Toby Speight
            6 hours ago
















          $begingroup$
          I don't agree with the design to tightly couple the reading of the data and the function largestProduct. What if the data comes from a database, a web response, a file, a POST request, etc.? Technically we could transform into a string then pass it an an istream, but we could do better. In fact, largeProduct is a pure function, and it doesn't need to instantiate an object. I implemented in a class because I didn't want to pass 6 parameters to helper functions.
          $endgroup$
          – Eric
          7 hours ago




          $begingroup$
          I don't agree with the design to tightly couple the reading of the data and the function largestProduct. What if the data comes from a database, a web response, a file, a POST request, etc.? Technically we could transform into a string then pass it an an istream, but we could do better. In fact, largeProduct is a pure function, and it doesn't need to instantiate an object. I implemented in a class because I didn't want to pass 6 parameters to helper functions.
          $endgroup$
          – Eric
          7 hours ago




          1




          1




          $begingroup$
          I think the best design would be to have a Grid struct that can be constructed by the different classes that would implement different ways to get the data, and then pass that Grid struct + nAdjacents to a pure function largestProduct as parameters.
          $endgroup$
          – Eric
          7 hours ago




          $begingroup$
          I think the best design would be to have a Grid struct that can be constructed by the different classes that would implement different ways to get the data, and then pass that Grid struct + nAdjacents to a pure function largestProduct as parameters.
          $endgroup$
          – Eric
          7 hours ago












          $begingroup$
          The class LargestProductInAGrid is like a closure, and all you have to do is add a setter to be able to change the grid or number of adjacent products.
          $endgroup$
          – Eric
          7 hours ago






          $begingroup$
          The class LargestProductInAGrid is like a closure, and all you have to do is add a setter to be able to change the grid or number of adjacent products.
          $endgroup$
          – Eric
          7 hours ago






          1




          1




          $begingroup$
          "a Grid struct that can be constructed by the different classes..." - Indeed, I agree with that. I was just being lazy when I made read() a member.
          $endgroup$
          – Toby Speight
          6 hours ago




          $begingroup$
          "a Grid struct that can be constructed by the different classes..." - Indeed, I agree with that. I was just being lazy when I made read() a member.
          $endgroup$
          – Toby Speight
          6 hours ago










          Eric is a new contributor. Be nice, and check out our Code of Conduct.










          draft saved

          draft discarded


















          Eric is a new contributor. Be nice, and check out our Code of Conduct.













          Eric is a new contributor. Be nice, and check out our Code of Conduct.












          Eric is a new contributor. Be nice, and check out our Code of Conduct.
















          Thanks for contributing an answer to Code Review Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          Use MathJax to format equations. MathJax reference.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f216426%2ffollow-up-project-euler-11-largest-product-in-a-grid-cache-optimized-slid%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Fairchild Swearingen Metro Inhaltsverzeichnis Geschichte | Innenausstattung | Nutzung | Zwischenfälle...

          Pilgersdorf Inhaltsverzeichnis Geografie | Geschichte | Bevölkerungsentwicklung | Politik | Kultur...

          Marineschifffahrtleitung Inhaltsverzeichnis Geschichte | Heutige Organisation der NATO | Nationale und...