Skip to content

Instantly share code, notes, and snippets.

@geekygrappler
Created September 29, 2019 19:35
Show Gist options
  • Save geekygrappler/2e69433650e21bcc6037e3df56ed2638 to your computer and use it in GitHub Desktop.
Save geekygrappler/2e69433650e21bcc6037e3df56ed2638 to your computer and use it in GitHub Desktop.

After Review

The Problem

I realised the issue with the 4x4 grid is that it will miss bacteria that should die from overcrowding. For example:

. x x p
. x y x
. x x x
. . . .

In this example the middle bacteria, y, will die because of overcrowding. However when we take for example the top right bacteria, p, and create a 4x4 grid around it.

. . . .
. . . .
x p . .
y x . .

You can see here that y will survive in this iteration because it only has 3 neighbours. This error is introduced because the grid cut off living bacteria and didn't account for them.

So I rethought how to do it and simplified it to:

  • Check every cell with bacteria
  • Check every cell adjacent to a cell with bacteria.
  • Check each of these cells only once with a 3x3 grid around them.

It is important to only check the central cell, as the bacteria in each cell only lives or dies based on the 8 cells around it. This removes the error of checking an edge cell on the grid (which is what I was doing before), when we don't know the state of all 8 cells around it.

x x x
x y x
x x x

So we only check y in this grid, none of the edge cells as this grid doesn't show us what's beyond the grid. For the above example, the following cells will be checked.

. . . . .
. x x x .
. x x x .
. x x x .
. . . . .

So we build 25, 3x3 grids around each point above and work out for each individual cell.

Code

The code is more. Unfortunately the tests didn't work because I couldn't get the typing to work for a unique array of arrays function:

function dedupCoordinates(coordinates: number [][]) : number [][] {
  return coordinates.reduce((unique: number [], c: number []) => {
    return unique.filter(u => u[0] === c[0] && u[1] === c[1]).length ? unique : [...unique, c];
  }, []);
}

This gives unique array paris [[1,2], [1,2], [1,3]] => [[1,2], [1,3]]. I found another way to do it, which I like even more:

function dedupCoordinates(coordinates: number [][]) : number [][] {
  let set = new Set(ar.map(JSON.stringify));
  return returnArray.from(set).map(JSON.parse);
}

Both of these broke the typescript compiler which meant I couldn't run the tests with ts-jest. It's a problem I've run into before with Typescript. If you try to do something quite complex, e.g. reduce the types are not simple and the hints from the compiler are also difficult for me to understand.

I ran the the programme manually with a few more test cases 🙄, and I hope this time the solution actually works.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment