summaryrefslogtreecommitdiffstats
path: root/day11/day11-2.js
blob: 5d72f0ffdd08f04bc14a45eb66d620cd2d3c4e15 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
const data = require('./data')
const rows = data.split(/\n/g).filter(r => r)
const rowsLn = rows[0].length
const string = rows.join('')

const checkSeat = (i, s) => {
  const lookup = (index, posCheck, next) => {
    const nextIndex = next(index)
    return posCheck(index)
      ? (s[nextIndex] !== '.' ? s[nextIndex] : lookup(nextIndex, posCheck, next))
      : '.'
  }

  const around = [
    lookup(i, i => (i >= rowsLn), i => (i-rowsLn)),                                   // Top
    lookup(i, i => (i >= rowsLn && (i+1)%rowsLn !== 0), i => (i+1-rowsLn)),           // T-R
    lookup(i, i => ((i+1)%rowsLn !== 0), i => (i+1)),                                 // Rigth
    lookup(i, i => (i < s.length - rowsLn && (i+1)%rowsLn !== 0), i => (i+1+rowsLn)), // B-R
    lookup(i, i => (i < s.length - rowsLn), i => (i+rowsLn)),                         // Bottom
    lookup(i, i => (i%rowsLn !== 0 && i < s.length -rowsLn), i => (i-1+rowsLn)),      // B-L
    lookup(i, i => (i%rowsLn !== 0), i => (i-1)),                                     // Left
    lookup(i, i => (i > rowsLn && i%rowsLn > 0), i => (i-1-rowsLn)),                  // T-L
  ]

  const taken = around.filter(s => s === '#').length
  const free = around.filter(s => s === 'L').length

  return [taken, free]
}

const round = (str) => {
  const newArray = []
  str.split('').forEach((s, i) => {
    const [taken, free] = checkSeat(i, str)
    if (s === 'L' && taken === 0) {
      newArray[i] = '#'
    } else if (s === '#' && taken >= 5) {
      newArray[i] = 'L'
    } else {
      newArray[i] = str[i]
    }
  })

  const newString = newArray.join('')
  return newString === str
    ? newString.split('').filter(s => s === '#').length
    : round(newString)
}

console.log(round(string))