# (Follow-up) 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

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),

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_;
}

return currentIndex + columns_ + 1;
}

auto canAdvanceLeft = bool(currentIndex % columns_);
return currentIndex + columns_ - 1;
}

return -1;
}

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

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


Analysis
Time complexity: $$\O(r * c)\$$
Space complexity: $$\O(1)\$$, not counting initial data

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.

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)
{
}

}


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)
{
}

{
// temporarily set in to throw on error
auto saved_exceptions = in.exceptions();

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

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

{
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};

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.

• 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.
– Eric
Commented Mar 29, 2019 at 11:14
• 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.
– Eric
Commented Mar 29, 2019 at 11:19
• 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.
– Eric
Commented Mar 29, 2019 at 11:22
• "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. Commented Mar 29, 2019 at 12:16