r/adventofcode • • Dec 04 '21

SOLUTION MEGATHREAD -🎄- 2021 Day 4 Solutions -🎄-

--- Day 4: Giant Squid ---


Post your code solution in this megathread.

Reminder: Top-level posts in Solution Megathreads are for code solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


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

EDIT: Global leaderboard gold cap reached at 00:11:13, megathread unlocked!

98 Upvotes

1.2k comments sorted by

View all comments

2

u/uNxe Dec 04 '21

Scala

Part1

import scala.annotation.tailrec

@tailrec def calc(drawn: Array[Int], data: Array[Array[Array[(Int, Int)]]], position: Int = 0): Int = {
  val result = data.
    filter(block => !block.filter(row => row.foldLeft(0)(_ + _._2) == 5).isEmpty || 
                    !block.transpose.filter(row => row.foldLeft(0)(_ + _._2) == 5).isEmpty)

  if(result.isEmpty){
    val moddata = data.map(block => {
      block.map(row => {
          row.map(value => {
            if(value._1 == drawn(position)) (value._1, 1) else value
          })
      })
    })
    calc(drawn, moddata, position + 1)
  }
  else {
    result.
      head.
      reduce(Array.concat(_, _)).
      foldLeft(0)( (acc, value) => if(value._2 == 0) acc + value._1 else acc ) * drawn(position - 1)
  }
}

val input = io.Source.fromInputStream(System.in).getLines
val drawn = input.next.split(",").map(_.toInt)
val data = input. 
  sliding(6, 6).
  map(_.drop(1).toArray).
  map(_.map(row => row.trim.split("\\D+").map(value => (value.toInt, 0)))).
  toArray

println(calc(drawn, data))

part2

import scala.annotation.tailrec

@tailrec def calc(drawn: Array[Int], data: Array[Array[Array[(Int, Int)]]], position: Int = 0): Int = {
  val uncompleteblocks = data.
    filter(block => block.filter(row => row.foldLeft(0)(_ + _._2) == 5).isEmpty && 
                    block.transpose.filter(row => row.foldLeft(0)(_ + _._2) == 5).isEmpty)

  if(uncompleteblocks.isEmpty && data.size == 1)
    data.
      head.
      reduce(Array.concat(_, _)).
      foldLeft(0)( (acc, value) => if(value._2 == 0) acc + value._1 else acc ) * drawn(position - 1)
  else {
    val moddata = uncompleteblocks.map(block => {
      block.map(row => {
          row.map(value => {
            if(value._1 == drawn(position)) (value._1, 1) else value
          })
      })
    })
    calc(drawn, moddata, position + 1)
  }
}

val input = io.Source.fromInputStream(System.in).getLines
val drawn = input.next.split(",").map(_.toInt)
val data = input. 
  sliding(6, 6).
  map(_.drop(1).toArray).
  map(_.map(row => row.trim.split("\\D+").map(value => (value.toInt, 0)))).
  toArray

println(calc(drawn, data))

1

u/daggerdragon Dec 05 '21

Your code is hard to read on old.reddit. Please edit it as per our posting guidelines in the wiki: How do I format code?