HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Code for finding the "longest" empty space in a grid

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thespacegridemptyforfindingcodelongest

Problem

I have written some code to find the longest line of empty space in a grid and I'd like to know if it can be simplified or shortened at all.

Here is an example of the input and output of the program:

Input

Output

As you can see, the program found the longest line to be near the top in the middle. The program is only looking for a 1 block wide line, which is by design. It also supports looking for the longest horizontal line too, which is not shown above.

Code

function findLongestLineInRow(grid, position, direction) {
let current = 0,
start = 0,
maximum = 0,
offset = 0;

const length = direction === 'vertical' ? grid.length : grid[0].length;

for (let i = 0; i maximum) {
maximum = current;
offset = start;
}

current = 0;
start = i + 1;
} else {
current++;
}
}

return {
x: direction === 'vertical' ? position : offset,
y: direction === 'vertical' ? offset : position,
length: maximum,
direction
};
}

function findLongestLineInRowRange(start, end, direction) {
let longest = { x: 0, y: 0, length: 0 };

for (let i = start; i longest.length) {
longest = line;
}
}

return longest;
}

function findLongestLineInGrid(grid) {
const horizontal = findLongestLineInRange(0, grid.length, 'horizontal'),
vertical = findLongestLineInRange(0, grid[0].length, 'vertical');

const { x, y, length, direction } = horizontal.length >= vertical.length ? horizontal : vertical;

return {
x, y,
width: direction === 'vertical' ? 1 : length,
height: direction === 'vertical' ? length : 1,
};
}


And here's an example of it running in the browser:



`function findLongestLineInRow(grid, position, direction) {
let current = 0,
start = 0,
maximum = 0,
offset = 0;

const length = direction === 'vertical' ? grid.length : grid[0].length;

for (let i = 0; i maximum) {
maximum = current;
o

Solution

Looks pretty good. I'd probably prefer a const VERTICAL = 'vertical' to the repeated 'vertical' string.

However, you could also add a function to transpose the grid, so columns become rows. I.e. instead of having each of your functions switch between vertical/horizontal all the time, simply transpose the input and output instead.

Context

StackExchange Code Review Q#154346, answer score: 3

Revisions (0)

No revisions yet.