r/adventofcode • • Dec 02 '18

SOLUTION MEGATHREAD -🎄- 2018 Day 2 Solutions -🎄-

--- Day 2: Inventory Management System ---


Post your solution as a comment or, for longer solutions, consider linking to your repo (e.g. GitHub/gists/Pastebin/blag or whatever).

Note: The Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


Advent of Code: The Party Game!

Click here for rules

Card Prompt: Day 2

Transcript:

The best way to do Advent of Code is ___.


This thread will be unlocked when there are a significant number of people on the leaderboard with gold stars for today's puzzle.

edit: Leaderboard capped, thread unlocked!

51 Upvotes

407 comments sorted by

View all comments

1

u/Toromtomtom Dec 02 '18

My Scala solution tries to implement efficient functional programming using lazy streams and tail-recursive functions:

import scala.annotation.tailrec
import scala.collection.immutable.Stream.Empty

object Two {

  def input: Stream[String] = {
    val input = this.getClass.getResource("input").getFile
    val it = scala.io.Source.fromFile(input).getLines
    it.toStream
  }

  // 1

  def testInput: Stream[String] = Stream(
    "abcdef",
    "bababc",
    "abbcde",
    "abcccd",
    "aabcdd",
    "abcdee",
    "ababab"
  )

  def contains23(id: String): (Int, Int) = {
    val counts = id.groupBy(identity).values.toStream.map(_.length)
    (if (counts.contains(2)) 1 else 0, if (counts.contains(3)) 1 else 0)
  }

  def checkSum(ids: Stream[String]): Int = {
    val c23 = ids.map(contains23)
    val (c2, c3) = c23.foldLeft((0, 0)) { case ((s1, s2), (has1, has2)) => (s1 + has1, s2 + has2) }
    c2 * c3
  }

  // 2

  def testInput2: Stream[String] = Stream(
    "abcde",
    "fghij",
    "klmno",
    "pqrst",
    "fguij",
    "axcye",
    "wvxyz"
  )

  def withoutNth(s: String, n: Int): String =
      s.substring(0, n) ++ s.substring(n + 1)

  def findDup(ids: Stream[String]): Option[String] = {
    @tailrec def go(ids: Stream[String], seen: Set[String]): Option[String] = ids match {
      case Empty => None
      case h #:: t if seen.contains(h) => Some(h)
      case h #:: t => go(t, seen + h)
    }
    go(ids, Set.empty)
  }

  def oneCharDiffers(ids: Stream[String]): Option[String] = {
    @tailrec def go(idxs: Stream[Int]): Option[String] = idxs match {
      case idx #:: tail =>
        val idsWithoutIdx = ids.map(withoutNth(_, idx))
        findDup(idsWithoutIdx) match {
          case Some(dup) => Some(dup)
          case None => go(tail)
        }
      case Empty => None
    }
    go(ids.head.indices.toStream)
  }

  def main(args: Array[String]): Unit = {
    println(checkSum(testInput))
    println(checkSum(input))
    println(oneCharDiffers(testInput2))
    println(oneCharDiffers(input))
  }
}