DEV Community

Discussion on: Daily Challenge #77 - Bird Mountain

Collapse
 
willsmart profile image
willsmart • Edited

A TypeScript version using reduces and maps to avoid too much mutation.
The main loop early exits if possible (if there are no hills left), otherwise it erodes the mountainscape by one hill. The starPattern array determines how this erosion happens, and it seems that the challenge uses up-down-left-right-dot.

const starPattern = [[0, 0], [-1, 0], [1, 0], [0, -1], [0, 1]];

const hillCount = (mountains: string[][]): number =>
  mountains.reduce((acc, row) => acc + row.reduce((acc, dot) => acc + Number(dot === "^"), 0), 0);

const peakHeight = (mountains: string[][]): number =>
  Array.from({
    length: mountains.length,
  }).findIndex(() => {
    if (hillCount(mountains) === 0) return true;
    mountains = mountains.map((row, rowIndex) =>
      row.map((_, colIndex) =>
        starPattern.reduce((acc, [x, y]) => acc && (mountains[rowIndex + y] || [])[colIndex + x] == "^", true)
          ? "^"
          : " "
      )
    );
    return false;
  });

Tested on Kata in its JS form.

Note that on there the mountains are defined using something like this:

const mountains = [
      "^^^^^^        ".split(''),
      " ^^^^^^^^     ".split(''),
      "  ^^^^^^^     ".split(''),
      "  ^^^^^       ".split(''),
      "  ^^^^^^^^^^^ ".split(''),
      "  ^^^^^^      ".split(''),
      "  ^^^^        ".split('')
    ]