• Definitely a bit of a jump between yesterday and today's. Wasted a fair bit of time trying to recursively calculate the aggregated directory sizes after building the file system.

    Once I calculated the dir sizes as I went along building the file system, it was much easier.

    Solution >
    let fs = {}
    let dirHistory = []
    let currentDir = fs
    
    arr.forEach(i => {
      if (i === '$ cd ..') {
        currentDir = dirHistory.pop()
      } else if (/\$ cd [a-z]+/.test(i)) {
        dirHistory.push(currentDir)
        let dirName = i.match(/[a-z]+/g)[1]
        currentDir = currentDir[dirName]
      } else if (/dir [a-z]+/.test(i)) {
        let dirName = i.match(/[a-z]+/g)[1]
        currentDir[dirName] = { size: 0 }
      } else if (/[0-9]+/.test(i)) {
        let size = Number(i.match(/[0-9]+ /)[0].trim())
        currentDir.size += size
        dirHistory.forEach(histItem => {
          histItem.size += size
        })
      }
    })
    
    
    let sizeArr = []
    let getSizes = obj => {
      sizeArr.push(obj.size)
      if (Object.values(obj).length < 2) {
        return
      }
      return Object.values(obj).filter(i => !Number.isInteger(i)).forEach(getSizes)
    }
    
    getSizes(fs)
    sizeArr.filter(i => i <= 100000).reduce((a, i) => a + i, 0)
    
  • Looks like markdown code tags aren't supported, but html pre tag is.

    <details>
    <summary>Spoiler</summary>
    <pre>
    Code here
    </pre>
    </details>

About

Avatar for frankenbike @frankenbike started