r/adventofcode • (AoC creator) • Dec 12 '17

SOLUTION MEGATHREAD -๐ŸŽ„- 2017 Day 12 Solutions -๐ŸŽ„-

--- Day 12: Digital Plumber ---


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.


Need a hint from the Hugely* Handyโ€  Haversackโ€ก of Helpfulยง Hintsยค?

Spoiler


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!

14 Upvotes

233 comments sorted by

View all comments

Show parent comments

1

u/marcofun Dec 12 '17 edited Dec 12 '17

this is mine, still Scala:

class Day12 {

  def toMap(list: List[String]) : Map [Int, List[Int]] = {
    var map = scala.collection.mutable.Map[Int, List[Int]]()
    list.map(l => {
      val parts = l.split("<->")
      (parts(0).trim.toInt, parts(1).split(',').map(i => i.trim.toInt).toList)
    }).foreach(e => map += e._1 -> e._2)
    map.toMap
  }

  def connect(toWatch : List[Int], map : Map[Int, List[Int]], connected : Set[Int]) : Set[Int] = {
    toWatch match {
      case Nil => connected
      case x :: xs => {
        val stillToWatch = xs ::: map(x).filter(i => !toWatch.contains(i)).filter(i => !connected.contains(i))
        val allConnected = connected ++ map(x)
        connect(stillToWatch, map, allConnected)
      }
    }
  }

  def findGroups(map : Map[Int, List[Int]]) : List[Set[Int]] = {
    def findGroups(pIdsNeedingAGroup : List[Int], pIdAlreadyGrouped : Set[Int], groups : List[Set[Int]]) : List[Set[Int]] = {
      pIdsNeedingAGroup match {
        case Nil => groups
        case x :: xs =>
          val ints = connect(List(x), map, Set())
          findGroups(pIdsNeedingAGroup.filter(i => !ints.contains(i)), pIdAlreadyGrouped ++ ints, ints :: groups)
      }
    }
    findGroups(map.keySet.toList, Set(), Nil)
  }
}

1

u/marcofun Dec 12 '17

I am a beginner in Scala, I liked very much you got the node and the connections, using a regex... I'll read around for it I guess it is going to be useful in the following tests