r/adventofcode • • Dec 05 '18

SOLUTION MEGATHREAD -🎄- 2018 Day 5 Solutions -🎄-

--- Day 5: Alchemical Reduction ---


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

Please prefix your card submission with something like [Card] to make scanning the megathread easier. THANK YOU!

Card prompt: Day 5

Transcript:

On the fifth day of AoC / My true love sent to me / Five golden ___


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 at 0:10:20!

31 Upvotes

515 comments sorted by

5

u/ephemient Dec 05 '18 edited Apr 24 '24

This space intentionally left blank.

2

u/daggerdragon Dec 05 '18

[CARD]

On the fifth day of AoC / My true love sent to me / Five golden HDMI cables

I see your true love is a fan of Monster-branded cables. >_>

→ More replies (1)

3

u/usbpc102 Dec 05 '18

First time on the global leaderboard to me (97/113) and that with this super hacky Kotlin solution:

package advent2018

import xyz.usbpc.aoc.Day
import xyz.usbpc.aoc.inputgetter.AdventOfCode

class Day05(override val adventOfCode: AdventOfCode) : Day {
    override val day: Int = 5
    private val input = adventOfCode.getInput(2018, day)

    override fun part1(): String {
        val regexList = mutableListOf<Regex>()

        var string = input

        for (c in 'a'..'z') {
            regexList.add(Regex("$c${c.toUpperCase()}"))
            regexList.add(Regex("${c.toUpperCase()}$c"))
        }

       var prev = ""

        while (prev != string) {
            prev = string
            for (r in regexList) {
                string = r.replaceFirst(string, "")
            }
        }

        return "" + string.length
    }

    override fun part2(): String {
        val regexList = mutableListOf<Regex>()


        for (c in 'a'..'z') {
            regexList.add(Regex("$c${c.toUpperCase()}"))
            regexList.add(Regex("${c.toUpperCase()}$c"))
        }

        val resluts = mutableListOf<String>()
        for (c in 'a'..'z') {
            var string = input.replace("$c", "").replace("${c.toUpperCase()}", "")
            var prev = ""

            while (prev != string) {
                prev = string
                for (r in regexList) {
                    string = r.replaceFirst(string, "")
                }
            }

            resluts.add(string)
        }

        return "" + resluts.minBy { it.length }!!.length
    }
}

As always the whole code can be found on github. Cleaning it up now.

4

u/daggerdragon Dec 05 '18

First time on the global leaderboard to me (97/113)

Welcome to the exalted halls of Valhalla the leaderboard! :D

3

u/nutrecht Dec 05 '18

resluts.add(string)

Dirty indeed! ;)

→ More replies (1)
→ More replies (3)

3

u/PendragonDaGreat Dec 05 '18

[card]On the fifth day of AoC / My true love sent to me / Five golden keycaps

Powershell 5.1

I have great shame, and also fail any code golf.

Part 1:

[string]$data = Get-Content $inputPath

$timer = New-Object System.Diagnostics.Stopwatch
$timer.Start()
do {
    $lastLength = $data.Length
    $data = $data.Replace('aA','').Replace('Aa','').Replace('bB','').Replace('Bb','').Replace('cC','').Replace('Cc','').Replace('dD','').Replace('Dd','').Replace('eE','').Replace('Ee','').Replace('fF','').Replace('Ff','').Replace('gG','').Replace('Gg','').Replace('hH','').Replace('Hh','').Replace('iI','').Replace('Ii','').Replace('jJ','').Replace('Jj','').Replace('kK','').Replace('Kk','').Replace('lL','').Replace('Ll','').Replace('mM','').Replace('Mm','').Replace('nN','').Replace('Nn','').Replace('oO','').Replace('Oo','').Replace('pP','').Replace('Pp','').Replace('qQ','').Replace('Qq','').Replace('rR','').Replace('Rr','').Replace('sS','').Replace('Ss','').Replace('tT','').Replace('Tt','').Replace('uU','').Replace('Uu','').Replace('vV','').Replace('Vv','').Replace('wW','').Replace('Ww','').Replace('xX','').Replace('Xx','').Replace('yY','').Replace('Yy','').Replace('zZ','').Replace('Zz','')
} while ($data.Length -lt $lastLength)

Write-Host $data.Length
$timer.Stop()
Write-Host $timer.Elapsed

Average runtime 0.18 seconds

Part 2:

[string]$data = Get-Content $inputPath

$timer = New-Object System.Diagnostics.Stopwatch
$timer.Start()

$bestSoFar = $data.Length
$bestLetterSoFar = $null
$alphabet = @()  
 
for ([byte]$c = [char]'A'; $c -le [char]'Z'; $c++)  
{  
    $alphabet += [char]$c  
}

Write-Host $alphabet

foreach($let in $alphabet) {
    [string]$let = $let
    $tempData = $data.Replace($let,'').Replace($let.ToLower(), '')
    do {
        $lastLength = $tempData.Length
        $tempdata = $tempdata.Replace('aA','').Replace('Aa','').Replace('bB','').Replace('Bb','').Replace('cC','').Replace('Cc','').Replace('dD','').Replace('Dd','').Replace('eE','').Replace('Ee','').Replace('fF','').Replace('Ff','').Replace('gG','').Replace('Gg','').Replace('hH','').Replace('Hh','').Replace('iI','').Replace('Ii','').Replace('jJ','').Replace('Jj','').Replace('kK','').Replace('Kk','').Replace('lL','').Replace('Ll','').Replace('mM','').Replace('Mm','').Replace('nN','').Replace('Nn','').Replace('oO','').Replace('Oo','').Replace('pP','').Replace('Pp','').Replace('qQ','').Replace('Qq','').Replace('rR','').Replace('Rr','').Replace('sS','').Replace('Ss','').Replace('tT','').Replace('Tt','').Replace('uU','').Replace('Uu','').Replace('vV','').Replace('Vv','').Replace('wW','').Replace('Ww','').Replace('xX','').Replace('Xx','').Replace('yY','').Replace('Yy','').Replace('zZ','').Replace('Zz','')
    } while ($tempdata.Length -lt $lastLength)
    Write-Host $let
    Write-Host $tempData.length

    if($tempData.length -lt $bestSoFar) {
        $bestSoFar = $tempData.length
        $bestLettersofar = $let
    }

}


write-host $bestLetterSoFar
Write-Host $bestSoFar
$timer.Stop()
Write-Host $timer.Elapsed

Average runtime 4.75 seconds

3

u/Nathan340 Dec 05 '18

Between you, me, and /u/ka-splam this is the fastest!

My first solution was with a giant regex like aA|Aa|bB|bB...zZ|Zz

As ka-splam said, even though we eliminate a loop, this is actually super slow. Around 3 minutes on my machine.

His method of a loop to replace each letter type takes ~15 seconds.

But you have us beat with this giant replace line at 4 seconds.

Interestingly a middle ground between yours and his which does your style chain replace on each letter splits the difference in time, comes out at 8 seconds. Something like this as the loop:

0..25 | % {
	$l = [char](97+$_)
	$u = [char](65+$_)
	$repl = $repl.Replace("$l$u", "").Replace("$u$l", "")
}

(I did try to programmatically generate that replace block as a string and then use invoke-expression on it to get the speed benefits of its execution with less typing, but that failed spectacularly)

→ More replies (9)

55

u/glguy Dec 05 '18 edited Dec 06 '18

Haskell - single pass with foldr. Using foldr you work with a completely reduced tail and just adding things on to the front of that one at a time reducing as needed.

https://github.com/glguy/advent2018/blob/master/execs/Day05.hs#L27-L31

part1 :: String -> Int
part1 = length . foldr step ""
  where
    step x (y:ys) | x /= y && toUpper x == toUpper y = ys
    step x ys                                        = x : ys

7

u/Auburus Dec 05 '18

That is actually pretty smart!

I felt like today's challenge was really suited for Haskell, but the bruteforce algorithm I implemented (react until nothing changes) is not as elegant.

Well, thanks for keep posting your solutions, I always like to learn more haskell!

→ More replies (1)

5

u/greenkiweez Dec 05 '18

this is poetry

3

u/raevnos Dec 05 '18

I'm so used to left folds I never remember that right folds exist.

→ More replies (16)
→ More replies (7)

26

u/eltrufas Dec 05 '18

Missed the leaderboards because I was forgetting to trim my iinput for whitespace. Lesson learned I guess!

import sys

line = [line for line in sys.stdin][0].strip()


def are_opp(a, b):
    return (a.lower() == b.lower() and
            ((a.isupper() and b.islower()) or
             (a.islower() and b.isupper())))


def react(line):
    buf = []
    for c in line:
        if buf and are_opp(c, buf[-1]):
            buf.pop()
        else:
            buf.append(c)
    return len(buf)


agents = set([c.lower() for c in line])

# part 1
print(react(line))

# part 2
print(min([react(line.replace(a, '').replace(a.upper(), ''))
           for a in agents]))

9

u/0rac1e Dec 05 '18

Same here. That pesky carriage return threw me off.

→ More replies (2)
→ More replies (8)

24

u/Smylers Dec 05 '18

Oooh, another challenge where using Vim seems easier than writing a program! For part 1, anyway — load your input file, then make searching case-insensitive:

:set ic⟨Enter⟩

and remove pairs of letters of opposite case with:

:s/\v(\l\u|\u\l)&(.)\2//g⟨Enter⟩

That substitution will then need repeating for newly created pairs. Do it again with @:, and watch as the line gets shorter on each press.

If you've had enough, you can make it loop till their are no more pairs with:

qaqqag&:redr⟨Enter⟩
@aq@a

Then the answer is the number of columns, which is displayed with g⟨Ctrl+G⟩.

(I have a plan for Part 2, but now need to get the children breakfast. I'll try to put it in a reply to this comment later.)

6

u/Smylers Dec 05 '18 edited Dec 06 '18

Part 2 in Vim wasn't easier than in a programming language ...

:set ic⟨Enter⟩
:s/\v(.)\1&(\l\u|\u\l)//g⟨Enter⟩
qaqqa:&&⟨Enter⟩@aq@a
yy26p⟨Ctrl+V⟩GI⟨Ctrl+V⟩⟨Ctrl+V⟩96 ⟨Esc⟩gveg⟨Ctrl+A⟩
qbce⟨Ctrl+R⟩-⟨Esc⟩x:s!⟨Ctrl+R⟩-!!g⟨Enter⟩
0Pq:+,$norm@b⟨Enter⟩
{qc$BC⟨Ctrl+R⟩=len(@-)⟨Enter⟩⟨Esc⟩q⟨Enter⟩
:s/<Up>⟨Enter⟩
:,$norm:redr|norm@a⟨Ctrl+V⟩⟨Enter⟩@c⟨Enter⟩
:2,sor n⟨Enter⟩

Update: Watch Vim running this.

The first 3 lines solve Part 1, pretty much as above, saving the method to macro @a.

Then it makes 26 copies of the reacted polymer, and inserts the alphabet down the left. (How?). On each line, it removes that letter from the polymer (and re-inserts it at the left, so we can see which line is which). (Why does the substitution use s!!! rather than the typical s///?)

Now we've copied the original reacted polymer, replace it with its length, saving the method to macro @c. And run both @a and @c on the other 26 lines (Why is a :norm nested within another :norm there?) — the line which gets the most units removed takes a little longer than the others.

Sort the alphabetical lines by the lengths. The answer to Part 1 is the unlabelled number on the top row (in orange in the video), and the answer to Part 2 is the number on the next line (in yellow, labelled with the letter of the problematic unit types).

That actually ended up being shorter, more readable, less awkward, and faster to run than I expected (but has been edited from the original, which was clunkier in several ways).

→ More replies (1)

18

u/dark_terrax Dec 05 '18

My initial implementation for part 1 ran fairly slowly (~10 seconds), so I assumed my part 2 was going to be horrible, but ended finishing in almost no extra time. I eventually realized that I had used my reduced result from part 1 as the basis for part 2, which is actually a really great optimization.

5

u/phira Dec 05 '18

Accidental genius :) nice!

15

u/jonathan_paulson Dec 05 '18 edited Dec 05 '18

Rank 36/9. Disappointing part 1, including a wrong answer and deciding to type out the alphabet by hand. Video of me solving at: https://www.youtube.com/watch?v=VBhrueOccZ0

Code (for part 2):

 s = open('5.in').read().strip()

 alpha = 'abcdefghijklmnopqrstuvwxyz'
 M = {}
 for c in alpha:
     M[c.lower()] = c.upper()
     M[c.upper()] = c.lower()

 ans = 1e5
 for rem in alpha:
     s2 = [c for c in s if c!=rem.lower() and c!=rem.upper()]
     stack = []
     for c in s2:
         if stack and c == M[stack[-1]]:
             stack.pop()
         else:
             stack.append(c)
     ans = min(ans, len(stack))
 print ans

7

u/[deleted] Dec 05 '18

str.swapcase would also save you a ton of time.

→ More replies (4)

13

u/vash3r Dec 05 '18

the key to typing out the alphabet by hand is that you didn't need to iterate through the letters in alphabetical order :)

11

u/[deleted] Dec 05 '18 edited Dec 05 '18
from string import ascii_uppercase

is a good one to keep in your back pocket too

5

u/[deleted] Dec 05 '18

This. Also, even if you need to for $REASONS: alphabet = "qwerty....cvbnm".sort()

→ More replies (2)
→ More replies (1)
→ More replies (4)

13

u/apazzolini Dec 05 '18 edited Dec 05 '18

Absolute value between the two ASCII character codes == 32 is another way to do the letter comparison. Runs in <40ms for part 2.

JavaScript

import { minBy } from 'lodash'

const peek = stack => stack[stack.length - 1]

const factorPolymer = input => {
    const stack = []

    input.split('').forEach(char => {
        // XOR of A and a, B and b, etc is 32
        if (!stack.length || (peek(stack).charCodeAt() ^ char.charCodeAt()) !== 32) {
            stack.push(char)
        } else {
            stack.pop()
        }
    })

    return stack.join('')
}

export const solvePart1 = input => {
    return factorPolymer(input).length
}

export const solvePart2 = input => {
    input = factorPolymer(input) // A first factorization pass speeds up the following passes

    const polymers = Array(26) // Indexes 0-26 represent 65-91 ASCII codes
        .fill()
        .map((e, i) => {
            const re = new RegExp(String.fromCharCode(i + 65), 'gi')
            const strippedInput = input.replace(re, '')
            return factorPolymer(strippedInput)
        })

    return minBy(polymers, 'length').length
}

Edit: Updated to use a stack instead of string concatenation and the fact that ASCII is laid out in a way that XOR of A and a is 32.

→ More replies (2)

12

u/pixiethecat Dec 05 '18 edited Dec 05 '18

Python 3

Fun!

line = open("day5input.txt").read().splitlines()[0]

oldline = None
while oldline != line:
    oldline = line
    for i in range(0,26):
        line = line.replace(chr(ord("a") + i) + chr(ord("A") + i),"")
        line = line.replace(chr(ord("A") + i) + chr(ord("a") + i),"")

print("Part1:")
print(len(line))

original = line
best = len(line)
for j in range(0,26):
    line = original
    line = line.replace(chr(ord("a") + j),"")
    line = line.replace(chr(ord("A") + j),"")
    oldline = None
    while oldline != line:
        oldline = line
        for i in range(0,26):
            line = line.replace(chr(ord("a") + i) + chr(ord("A") + i),"")
            line = line.replace(chr(ord("A") + i) + chr(ord("a") + i),"")

    best = len(line) if len(line) < best else best
print("Part2:")
print(best)

17

u/andreyrmg Dec 05 '18 edited Dec 05 '18
from string import *


def collapse(s):
    p = ['.']
    for u in s:
        v = p[-1]
        if v != u and v.lower() == u.lower():
            p.pop()
        else:
            p.append(u)
    return len(p) - 1


s = open('5.txt').read().strip()
print(collapse(s))
print(min(collapse(c for c in s if c.lower() != x) for x in ascii_lowercase))
→ More replies (4)

5

u/EquationTAKEN Dec 05 '18

Nice one!

Remember, the range function implies starting at 0 by default, so range(26) are the same numbers as range(0, 26).

→ More replies (1)

3

u/rdd33 Dec 05 '18

Instead of chr(ord("a") + j) etc you could loop string.ascii_lowercase or ascii_uppercase.

→ More replies (1)

3

u/llimllib Dec 05 '18

I think a regex solution is slower, but satisfying:

import re
import string

lower = string.ascii_lowercase
upper = string.ascii_uppercase
s = open("input.txt").read().strip()
pat = "|".join(
    a + b for a, b in list(zip(lower, upper)) + list(zip(upper, lower)))
ss = re.sub(pat, "", s)
while s != ss:
    s = ss
    ss = re.sub(pat, "", s)
print(len(s), s)

(for part 1, just iterate for part 2)

3

u/RainVector Dec 05 '18

This is the most efficient way to solve this problem. Great!

→ More replies (1)

3

u/safety_monkey Dec 05 '18 edited Dec 05 '18

This is a great solution, but I'm perplexed. I have something very similar and it runs in ~2.4 seconds, whereas yours consistently runs in ~1.1 seconds. I'd love it if someone could point out which specific technique is faster here.

from string import ascii_lowercase
import re

def parse_input(filename):
  """Convenience method to parse a file and return a list as input"""
  with open(filename, 'r') as input_file:
    return input_file.readline()

def part1(input_string):
  old_input = None
  while old_input != input_string:
    old_input = input_string
    for char in ascii_lowercase:
      input_string = input_string.replace(char.lower() + char.upper(), '')
      input_string = input_string.replace(char.upper() + char.lower(), '')
  return len(input_string)

def part2(input_string):
  test_input = ""
  shortest_value = len(input_string)
  for char in ascii_lowercase:
    test_input = input_string.replace(char, '').replace(char.upper(), '')
    length = part1(test_input)
    shortest_value = length if length < shortest_value else shortest_value
  return shortest_value

if __name__ == "__main__":
  INPUT = 'inputs/day05.txt'
  TEST_INPUT = 'dabAcCaCBAcCcaDA'

  assert part1(TEST_INPUT) == 10
  print(f"Part 1: {str(part1(parse_input(INPUT)))}")

  assert part2(TEST_INPUT) == 4
  print(f"Part 2: {part2(parse_input(INPUT))}")
→ More replies (4)
→ More replies (1)

11

u/_jonah Dec 05 '18 edited Dec 05 '18

J, both parts

p1 =. [: # ,`(}.@])@.(32 -: |@(- {.)&(3&u:)/)/

p2 =. [: <./ (a. {~ (,. 32 + ]) 65 + i.26) p1@-."1~ ]

Try it online!

3

u/Kaligule Dec 05 '18

J will never stop to amaze me.

10

u/Arknave Dec 05 '18 edited Dec 05 '18

First time I’ve done it live this year (moving east was a mistake for Advent of Code purposes). 6th / 4th. Used a stack and added the characters one at a time for a O(n) solution. Similar to checking if a parenthesis string is balanced.

def run(s):
    stk = []
    for c in s:
        popped = False
        if stk:
            bk = stk[-1]
            if (('A' <= bk <= 'Z' and 'a' <= c <= 'z') or ('A' <= c <= 'Z' and 'a' <= bk <= 'z')) and bk.lower() == c.lower():
                stk.pop()
                popped = True
        if not popped:
            stk.append(c)
    return len(stk)

def main():
    s = input().strip()
    ans = 1000000
    for k in range(26):
        up = chr(ord('A') + k)
        lo =  chr(ord('a') + k)
        t = str(s)
        t = t.replace(up, '')
        t = t.replace(lo, '')
        print(t)
        ans = min(ans, run(t))
    print(ans)

main()

Also watch me code it and cry on youtube here: https://youtu.be/GDx_rC5wXGc (should go live at 12:30 EST).

→ More replies (1)

7

u/p_tseng Dec 05 '18 edited Dec 05 '18

Ruby, reporting in.

Leaderboard code was not nearly this clean, I copy/pasted the react code, and started out with actually just running it 100 times. That was good enough for part 1, but for part 2 I actually needed to make it run to completion. So I ate a minute penalty on part 2 for making a really far-off guess. This code is slightly less repetitive than what I submitted (I made react into a function) and uses the fact that gsub returns nil if no modifications were made.

def react(str)
  loop {
    break str if (?a..?z).all? { |x|
      [
        str.gsub!(x + x.upcase, ''),
        str.gsub!(x.upcase + x, ''),
      ].none?
    }
  }
end

input = (ARGV.empty? ? DATA : ARGF).read.chomp.freeze

puts (part1 = react(input.dup).freeze).size
puts (?a..?z).map { |tried_letter|
  react(part1.tr(tried_letter + tried_letter.upcase, '')).size
}.min

__END__
my input goes here

It ran on my input in about 1 second so I did not need to do anything more clever.

Edit: Yeah okay, after reading others' solutions, I get it, a less wasteful way to do it would be to add letters left-to-right and therefore I know I only need to delete from the right end of the string. Let this be a lesson on there being a huge difference between what I write if I want to go as fast as possible versus what I might write if I actually have time to think about it.

→ More replies (6)

7

u/cheetahkk Dec 05 '18

Python - using functools.reduce. Fun!

from functools import reduce

def trigger(x, y):
    return False if not x else abs(ord(x[-1]) - ord(y)) == 32

def react(polymer):
    return reduce((lambda x, y: x[:-1] if trigger(x, y) else x+y), polymer)

polymer = open('input.txt').read()
print(len(react(polymer)))
print(min([len(react(polymer.replace(chr(i), '').replace(chr(i-32), ''))) for i in range(ord('a'), ord('z') + 1)]))
→ More replies (3)

6

u/jayfoad Dec 05 '18 edited Dec 05 '18

APL #47/29

Using regular expressions, the solution for part 1 boils down to 'Aa|Bb|...|aA|bB|...'⎕R''⍣≡, i.e. keep replacing 'Aa' etc with '' until we reach a fixed point. An alternative solution using Find (⍷) instead runs a bit faster, but part 2 still takes a few seconds.

3

u/jayfoad Dec 05 '18

Updated alternative solution still uses the "fixed point operator" ⍣≡ but now does arithmetic on ASCII codepoints instead of string operations. Combined time for both parts is now about 0.02 seconds.

→ More replies (8)

6

u/ChrisVittal Dec 05 '18

[Card] Staaaaars

Rust, first Rust I'm proud of. Never copy my input data.

static INPUT: &str = "data/day05";

fn react<'a>(input: impl Iterator<Item = &'a u8>) -> usize {
    let mut v = Vec::new();
    for &c in input {
        match v.last() {
            None => v.push(c),
            Some(&d) => if d.to_ascii_lowercase() == c.to_ascii_lowercase() && d != c {
                v.pop();
            } else {
                v.push(c);
            }
        }
    }
    v.len()
}

fn main() {
    let input: Vec<u8> = aoc::file::first_line(INPUT).into();
    println!("  1: {}", react(input.iter()));
    let mut min = std::usize::MAX;
    for i in 0u8..=26 {
        let v = input.iter().filter(|&&c| c != b'a'+i && c != b'A'+i);
        min = usize::min(react(v), min);
    }
    println!("  2: {}", min);
}

3

u/lazyear Dec 05 '18

I quite like this one. I was looping through the string slices and being forced to re-allocate every split. This is significantly faster and more efficient.

→ More replies (2)

5

u/Philboyd_Studge Dec 05 '18

[Card] FIVE GOLDEN STARS OK ONLY 2

Java - easy one. You can test for lowercase/uppercase being the same letter using XOR 32.

package Advent2018;

import util.AdventOfCode;

import java.util.List;

public class Day5 extends AdventOfCode {

    public Day5(List<String> input) {
        super(input);
    }

    private int remove(StringBuilder in) {
        boolean removed = true;

        while (removed) {
            for (int i = 0; i < in.length() - 1; i++) {
                if ( (in.charAt(i) ^ in.charAt(i + 1)) == 32) {
                    in.delete(i, i + 2);
                    removed = true;
                    break;
                }
                removed = false;
            }
        }
        return in.length();
    }

    @Override
    public Object part1() {
        StringBuilder chain = new StringBuilder(input.get(0));
        return remove(chain);
    }

    @Override
    public Object part2() {
        int min = Integer.MAX_VALUE;

        String[] patterns = new String[26];
        for (int i = 0; i < 26; i++) {
            patterns[i] = "[" + (Character.toString((char)(i + 'a'))) +
                    (Character.toString((char)(i + 'A'))) + "]";
            //System.out.println(patterns[i]);
        }

        for (int i = 0; i < 26; i++) {
            String chain = input.get(0);
            chain = chain.replaceAll(patterns[i], "");
            int result = remove(new StringBuilder(chain));
            System.out.println(result);
            if (result < min) min = result;
        }
        return min;
    }

    @Override
    public void parse() {

    }

}

5

u/TheVarmari Dec 05 '18

You can test for lowercase/uppercase being the same letter using XOR 32.

Huh, that's a neat way to check for that. Should've probably thought of it. Good to know for future challenges... Good job!

→ More replies (1)
→ More replies (3)

5

u/donatasp Dec 05 '18

Since there is no Common Lisp yet

(defun destroy? (a b)
  (and a b (char/= a b) (char-equal a b)))

(defun reduce-polymer (polymer)
  (let ((stack (list (elt polymer 0))))
    (loop :for u :across (subseq polymer 1)
          :do
             (push u stack)
             (if (destroy? (car stack) (cadr stack))
                 (progn
                   (pop stack)
                   (pop stack))))
    stack))

(length (reduce-polymer *polymer*)) ;; => 11476

(defun reduce-polymer2 (polymer1 unit-to-skip)
  (let ((polymer (remove-if (lambda (c) (char-equal c unit-to-skip)) polymer1)))
    (reduce-polymer polymer)))

(loop :for i :from (char-code #\a) :to (char-code #\z)
      :minimizing (length (reduce-polymer2 *polymer* (code-char i)))) ;; => 5446

3

u/Average-consumer Dec 05 '18

Very similar to what I did in Clojure

→ More replies (8)

5

u/schod Dec 05 '18

BASH Time :)

No sed, no grep, just pure bash!

Puzzle #1 (6 seconds)

#!/bin/bash

in_file=input

polymer=$(cat $in_file)

# 1000 iteration is enough :)
for i in {1..1000}; do
    for x in {a..z}; do
        polymer=${polymer//$x${x^^}}
        polymer=${polymer//${x^^}$x}
    done
done

echo ${#polymer}

Puzzle #2 (330 seconds)

#!/bin/bash

in_file=input
polymer=$(cat $in_file)
min_size=${#polymer}

for ch in  {a..z}; do
    test_polymer=${polymer//$ch}
    test_polymer=${test_polymer//${ch^^}}

    # 2000 iteration is enough :)
    for i in {1..2000}; do
        for x in {a..z}; do
            test_polymer=${test_polymer//$x${x^^}}
            test_polymer=${test_polymer//${x^^}$x}
        done
    done

    if [ ${#test_polymer} -lt $min_size ]; then
        min_size=${#test_polymer}
    fi
done

echo $min_size

8

u/edgargonzalesII Dec 05 '18

Java 8

Felt really proud of the part 1 using a stack. Leetcode came in useful for once.

private int util1(String in) {
    char[] arr = in.toCharArray();
    Stack<Character> inStack = new Stack<>();
    Stack<Character> q = new Stack<>();

    for(char c : arr)
        inStack.push(c);

    for(char c : inStack) {
        if(q.isEmpty())
            q.push(c);
        else {
            char last = q.peek();

            if(Math.abs(last-c) == 32) {
                q.pop();
            } else {
                q.push(c);
            }
        }
    }

    return q.size();
}

// Less interesting part 2
public void runPart2() {
    String in = this.getInputLines()[0];
    int min = Integer.MAX_VALUE;

    for(int i=0; i<26; i++) {
       String temp = in.replaceAll("[" + (char) (i + 'a') + (char) (i + 'A') + "]", "");

       min = Math.min(min, util1(temp));
    }

    System.out.println(min);
}

3

u/___alt Dec 05 '18

Note that the preferred abstraction for stacks in Java is Deque, Stack being an outdated one that builds upon the outdated Vector.

→ More replies (2)
→ More replies (10)

4

u/VikeStep Dec 05 '18 edited Dec 05 '18

F#

Repo

Got a really nice, concise solution with F#, gotta love pattern matching on lists. I also take advantage of the fact that we can take the output from part 1 and feed it into part 2. This reduced the time to run from 52ms to 17ms for me.

let remainingPolymer =
    let processUnit polymer ch =
        match polymer with
        | x :: xs when abs (ch - x) = 32 -> xs
        | xs -> ch :: xs
    Seq.fold processUnit []
let filterChars str ch = Seq.filter (fun c -> c <> ch && (c - 32) <> ch) str
let solvePart1 = Seq.map int >> remainingPolymer >> Seq.length
let solvePart2 str =
    let reducedStr = str |> Seq.map int |> remainingPolymer
    Seq.init 26 ((+)65 >> filterChars reducedStr >> remainingPolymer >> Seq.length) |> Seq.min
let solver = {parse = parseFirstLine asString; part1 = solvePart1; part2 = solvePart2}

Part 1: 2.93ms
Part 2: 17.34ms

3

u/will_bui Dec 05 '18 edited Dec 05 '18

K:

uniq:{x@&0={+/x in y}':[x]}
f:{#{._[;(!#x)!x]@,/uniq 0 -1+/:&(=':["i"$_:x])&~=':[90<i:"i"$x]}/x}
(f x),&/f':{x@&~x in y,.q.upper y}[x]'?_x:*0:`p5

Drop indexes where case differs with previous and the lowercased int value equals with previous until output converges.

Optimised by removing all pairs each time around instead of one at a time. (2 sec runtime)

→ More replies (1)

3

u/tehjimmeh Dec 05 '18 edited Dec 06 '18

Using the left side of the string as an in-place stack:

C++

int main(int argc, char* argv[]) {
    std::ifstream ifs(argv[1]); std::string orig; ifs >> orig;
    orig = "1" + orig;

    auto eval = [](auto&& l) {
        auto res = l.size()-1;
        for (auto it1 = l.begin()+1, it2 = it1 + 1; it2 != l.end();)
            if ((*it1) != (*it2) && (toupper(*it1) == toupper(*it2)))
                it2++, it1--, res -= 2;
            else 
                std::swap(*(++it1), *(it2++));
        return res;
    };

    size_t part1 = eval(std::string(orig));
    size_t part2 = SIZE_MAX;
    for (char l = 'a'; l <= 'z'; l++) {
        auto line = orig;
        for (char& c : std::array{ l, (char)toupper(l) })
            line.erase(std::remove(line.begin(), line.end(), c), line.end());
        part2 = std::min(part2, eval(line));
    }

    std::cout << "1: " << part1 << "\n" << "2: " << part2 << "\n";
}

3

u/binajohny Dec 05 '18

My Kotlin solution (GitHub)

private fun react(string: String, vararg skip: Char): Int {
    val stack = Stack<Char>()

    string.forEach {
        if (it in skip) {
            // no-op
        } else if (stack.empty().not() && abs(stack.peek() - it) == 'a' - 'A') {
            stack.pop()
        } else {
            stack.push(it)
        }
    }

    return stack.size
}


fun part1(input: String): Int {
    return react(input)
}

fun part2(input: String): Int {
    return ('a'..'z').map { react(input, it, it.toUpperCase()) }.min() ?: -1
}

3

u/mvmaasakkers Dec 05 '18

Go / Golang

I imagine this could be done way more efficiently but this was what I came up with. If anyone has some pointers let me know!

Also in gist

package main

import (
	"bufio"
	"flag"
	"fmt"
	"log"
	"os"
	"strings"
	"unicode"
)

func readInput(filename string) string {
	fileHandle, _ := os.Open(filename)
	defer func() {
		if err := fileHandle.Close(); err != nil {
			log.Fatal(err)
		}
	}()
	fileScanner := bufio.NewScanner(fileHandle)

	input := ""
	for fileScanner.Scan() {
		line := fileScanner.Text()
		if len(line) > 0 {
			input = line
		}
	}

	return strings.TrimSpace(input)
}

var file = flag.String("file", "./p1.txt", "file used for input")

func main() {
	flag.Parse()

	input := readInput(*file)

	fmt.Println("Part 1:", part1(input))
	fmt.Println("Part 2:", part2(input))
}

func part1(input string) (int) {
	return len(produce(input))
}

func produce(line string) string {
	for {
		changes := false
		for k, g := range line {
			if k > 0 {
				if unicode.IsLower(g) && unicode.IsUpper(rune(line[k-1])) || unicode.IsLower(rune(line[k-1])) && unicode.IsUpper(g) {
					if strings.ToLower(string(g)) == strings.ToLower(string(line[k-1])) {
						line = line[:k-1] + line[k+1:]
						changes = true
					}
				}
			}
			if changes {
				break
			}
		}
		if !changes {
			break
		}
	}

	return line
}

var alphabet = "abcdefghijklmnopqrstuvwxyz"

func part2(input string) (outcome int) {
	outcome = len(input)
	for _, c := range alphabet {
		check := strings.Replace(strings.Replace(input, string(strings.ToUpper(string(c))), "", -1), string(c), "", -1)
		l := len(produce(check))
		if l < outcome {
			outcome = l
		}
	}

	return outcome
}

5

u/d-sky Dec 05 '18 edited Dec 05 '18

Another Go/Golang solution using go routines. Not really faster with this short input. But just for fun, why not? :) You can also use the result of the part 1 reaction as the starting point for the 26 reactions in part 2.

package main

import (
	"fmt"
	"io/ioutil"
)

func opposite(a, b byte) bool {
	return a == b+32 || a == b-32
}

func react(polymer []byte, remove byte) []byte {
	var result []byte
	for _, unit := range polymer {
		switch {
		case unit == remove || unit == remove-32:
			continue
		case len(result) != 0 && opposite(result[len(result)-1], unit):
			result = result[:len(result)-1]
		default:
			result = append(result, unit)
		}
	}
	return result
}

func main() {
	polymer, err := ioutil.ReadFile("input.txt")
	if err != nil {
		panic(err)
	}

	polymer = react(polymer, 0)
	fmt.Println(len(polymer))

	lengths := make(chan int)
	for unitType := 'a'; unitType <= 'z'; unitType++ {
		go func(unitType byte) { lengths <- len(react(polymer, unitType)) }(byte(unitType))
	}
	min := len(polymer)
	for unitType := 'a'; unitType <= 'z'; unitType++ {
		length := <-lengths
		if length < min {
			min = length
		}
	}
	fmt.Println(min)
}
→ More replies (4)

4

u/CHAOSFISCH Dec 05 '18 edited Dec 05 '18

My solution. Should be O(n) (part 1) and O(n*m) (part 2, m = size of alphabet)

package main

import (
	"bufio"
	"io"
	"log"
	"os"
	"strings"
	"unicode"
)

func main() {
	f, err := os.Open("input_5.txt")
	defer f.Close()
	if err != nil {
		log.Fatalf("could not open input: %v", err)
	}

	reacted := part51(f)
	log.Printf("Length of reaction is: %d\n", len(reacted))
	part52(reacted)
}

func part51(r io.Reader) []rune {
	br := bufio.NewReader(r)

	var result []rune
	for {
		if c, _, err := br.ReadRune(); err != nil {
			if err == io.EOF {
				break
			}
		} else {
			if len(result) == 0 {
				result = append(result, c)
				continue
			}

			last := result[len(result)-1]
			switch {
			case unicode.IsUpper(c) && unicode.IsLower(last) && unicode.ToLower(c) == last:
				fallthrough
			case unicode.IsLower(c) && unicode.IsUpper(last) && unicode.ToUpper(c) == last:
				result = result[:len(result)-1]
				break
			default:
				result = append(result, c)
				break
			}
		}
	}

	return result
}

func part52(reacted []rune) {
	alphabet := "abcdefghijklmnopqrstuvwxyz"
	reactedString := string(reacted)
	bestLength := len(reacted)
	for _, l := range alphabet {
		replaced := strings.Replace(strings.Replace(reactedString, string(l), "", -1), strings.ToUpper(string(l)), "", -1)
		result := part51(strings.NewReader(replaced))
		if bestLength > len(result) {
			bestLength = len(result)
		}
	}

	log.Printf("Best length is: %d\n", bestLength)
}
→ More replies (1)

3

u/ThezeeZ Dec 05 '18

My solution after I toyed with it a little (repo)

import (
	"regexp"
)

func Reduction(polymer string) string {
	for i := 0; i < len(polymer)-1; {
		if polymer[i] == polymer[i+1]+32 || polymer[i] == polymer[i+1]-32 {
			polymer = polymer[:i] + polymer[i+2:]
			i--
			if i < 0 {
				i = 0
			}
		} else {
			i++
		}
	}
	return polymer
}

func BestCollapse(polymer string) string {
	polymer = Reduction(polymer)
	shortest := polymer
	for i := 'A'; i <= 'Z'; i++ {
		remainingPolymer := regexp.MustCompile("(?i)" + string(i)).ReplaceAllString(polymer, "")

		collapsed := Reduction(remainingPolymer)
		if len(collapsed) < len(shortest) {
			shortest = collapsed
		}
	}
	return shortest
}
→ More replies (2)
→ More replies (3)

3

u/0rac1e Dec 05 '18 edited Dec 05 '18

Perl 6

As soon as I read the puzzle, I knew I would use that bit-wise trick to flip the case of an ASCII char.

sub solve($p is copy, :$t) {
    if $t { $p .= trans([$t.lc, $t.uc] => ['', '']) }
    my $c = 0;
    while $c ≤ $p.chars - 2 {
        if $p.substr($c, 1).ord == $p.substr($c + 1, 1).ord +^ 32 {
            $p = $p.substr(0, $c) ~ $p.substr($c + 2);
            $c = max(0, $c - 1);
            next;
        }
        $c++;
    }
    return $p.chars;
}

given 'input'.IO.slurp.trim -> $input {
    say solve($input);
    say $input.lc.comb.unique.map(-> $t { solve($input, :$t) }).min;
}

and just because...

Python

def solve(p, t=None):
    if t: p = p.translate(str.maketrans('', '', t.lower() + t.upper()))
    c = 0
    while c <= len(p) - 2:
        if ord(p[c]) == ord(p[c + 1]) ^ 32:
            p = p[:c] + p[c + 2:]
            c = max(0, c - 1)
            continue
        c += 1
    return len(p)

data = open('input').read().strip()

print(solve(data))
print(min(solve(data, t) for t in set(data.lower())))

3

u/[deleted] Dec 05 '18

Dlang:

import std.experimental.all;

auto react(int[] seq) {
    int[] stack;
    foreach(code; seq) {
        if (!stack.empty && ((stack.back() ^ code) == 0x20))
            stack.popBack();
        else
            stack ~= code;
    }
    return stack;
}

void main() {
    auto reduced = readText("day05-input.txt").filter!(std.ascii.isAlpha).map!(to!int).array.react;
    writeln("Result 5a: ", reduced.length);
    writeln("Result 5b: ", lowercase.map!(to!int)
            .map!(c1 => reduced.filter!(c2 => (c1 ^ c2) != 0x20 && (c1 ^ c2) != 0).array.react.length)
            .minElement);
}
→ More replies (2)

3

u/Smylers Dec 05 '18

A Perl one-liner for Part 1:

perl -wlnE '1 while s/(?i:(.)\1)(?<=[a-z][A-Z]|[A-Z][a-z])//g; say length' input

No stacks, no writing out the alphabet or making pairs of equivalent characters, just the POWER OF REGEX.†

In a reversal of usual, this is a translation of my Vim solution.‡ It turns out Vim's regexps are nicer than Perl's for this, Perl's equivalents being less succinct than Vim's \l, \u, and &.

Extending that to solve Part 2:

perl -MList::AllUtils=min -wnlE '$polymer = $_; say min map { $_ = $polymer =~ s/$_//igr; 1 while s/(?i:(.)\1)(?<=[a-z][A-Z]|[A-Z][a-z])//g; length } "a".."z"' input

That's possibly stretching the definition of ‘one-liner’, and is a bit bit awkward to read, so here it is rewritten as a program:

use v5.14; use warnings; use List::AllUtils qw<min>;

chomp (my $polymer = <>);
say min map {
    $_ = $polymer =~ s/$_//igr;
    1 while s/(?i:(.)\1)(?<=[a-z][A-Z]|[A-Z][a-z])//g;
    length
  } 'a' .. 'z';

The body of the map is basically the one-liner from Part 1. Since it transforms the polymer, $polymer stores the initial value. At the start of the map, it takes a fresh copy of the original and removes the current letter from it before processing

[Card] Five golden hours of sleep.

† OK, so probably Perl's regex engine uses stacks and has lists of letters and their cases inside it.

‡ Typically I work out the solution in Perl first, then try to convert that to Vim.

→ More replies (2)

3

u/donaldihunter Dec 05 '18

Perl 6

#!/usr/bin/env perl6
use v6;

my $str = '5a-input.txt'.IO.slurp.trim;

my @candidates = gather {
    for 'a' .. 'z' -> $c {
        my $work = $str.trans($c => '', $c.uc => '');
        my $length;
        repeat {
            $length = $work.chars;
            $work .= trans(('a'..'z' Z~ 'A'..'Z') => '', ('A'..'Z' Z~ 'a'..'z') => '');
        } while $work.chars < $length;
        take $work.chars;
    }
}

say @candidates.min;

3

u/alasano Dec 05 '18 edited Dec 06 '18

Finally a solution I'm happy with :P

Javascript

EDIT : Greatly optimized - Run time is 68 ms for Part 1 and 14 ms for Part 2 for a total of 82 ms for both parts. This is achieved by feeding the output of the first part as the input of the second part. Before it took ~1500 ms for both parts.

let input = require('./input5');

function polymerize(str) {
    let i = 0;
    while (str[i + 1] != undefined) {
        let a = str.charCodeAt(i);
        let b = str.charCodeAt(i + 1);
        if (a == b + 32 || a == b - 32) {
            str = str.substring(0, i) + str.substring(i + 2, str.length);
            i--;
        } else {
            i++;
        }
    }
    return str;
}

function optimize(str) {
    let upper = 65;
    let lower = 97;
    let result = 100000;
    for (let i = 0; i < 25; i++) {
        let pattern = `(${String.fromCharCode(upper + i)}|${String.fromCharCode(lower + i)})`;
        let re = new RegExp(pattern, "g");
        let attempt = str.replace(re, "");
        let polymerCount = polymerize(attempt).length;
        if (polymerCount < result) {
            result = polymerCount;
        }
    }
    return result;
}
let polymerized = polymerize(input);
console.log(`Part 1: ${polymerized.length}`);
console.log(`Part 2: ${optimize(polymerized)}`);

3

u/CheezyXenomorph Dec 05 '18

PHP 7.2

<?php

namespace Cheezykins\AdventOfCode\DayFive;

class Polymer
{
    /** @var string $chain */
    protected $chain;

    public function __construct(string $chain)
    {
        $this->chain = $chain;
    }

    public function optimize(): ?int
    {
        $letters = range('a', 'z');
        $minimal = null;

        foreach ($letters as $letter) {
            if (stripos($this->chain, $letter) === false) {
                continue;
            }
            $chain = self::reduce($this->chain, $letter);
            if ($minimal === null || strlen($chain) < $minimal) {
                $minimal = strlen($chain);
                $this->optimal = $chain;
            }
        }
        return $minimal;
    }

    public function activate(): int
    {
        return strlen(self::reduce($this->chain));
    }

    /**
     * @param string $chain
     * @param string|null $removeFirst
     * @return string
     */
    public static function reduce(string $chain, ?string $removeFirst = null): string
    {
        if ($removeFirst !== null) {
            $chain = str_ireplace($removeFirst, '', $chain);
        }

        $chainStack = str_split($chain);
        $outputStack = [];

        foreach ($chainStack as $chainItem) {
            if ($outputStack === []) {
                $outputStack[] = $chainItem;
                continue;
            }
            $last = ord(end($outputStack));
            if (abs($last - ord($chainItem)) === 32) {
                array_pop($outputStack);
            } else {
                array_push($outputStack, $chainItem);
            }
        }

        return implode('', $outputStack);
    }
}

Times running under phpunit:

Part 1: 14ms

Part 2: 79ms

https://i.imgur.com/dzSCVzT.png

3

u/Minijackson Dec 05 '18 edited Dec 05 '18

Rust - Going for the fastest code :p

The whole part 2 takes about 15 milliseconds, instead of the 71 milliseconds of my simpler, single-threaded implementation.

Using the awesome rayon library to handle parallelization.

Code inspired by /u/glguy and /u/aurele

fn are_opposites(left: char, right: char) -> bool {
    // A is 0x41, a is 0x61
    // B is 0x42, b is 0x62
    // etc.
    //
    // For units to pass the comparison, their "letter part" must be equal,
    // and their "case part" mut be different.
    //
    // Using the result of the bitwise XOR:
    //
    //        vvvv- same letter
    // 0b0010_0000
    //   ^^^^------ not the same case
    //
    // This is much faster than using the `to_lowercase` function, since Rust's
    // awesome UTF-8 support uses a big conversion table, *and* needs to support
    // multiple-characters lowercase.
    (left as u8) ^ (right as u8) == 0b0010_0000
}

/// Single threaded Polymer reduction
fn reduce_subpolymer(subpolymer: &str) -> String {
    subpolymer
        .chars()
        .fold(String::new(), |mut result, letter| {
            if let Some(end) = result.pop() {
                if are_opposites(end, letter) {
                    result
                } else {
                    result.push(end);
                    result.push(letter);
                    result
                }
            } else {
                result.push(letter);
                result
            }
        })
}

/// Combine 2 already reduced polymers
///
/// The only reduction that can happen is between the end of `left` and the
/// beginning of `right`. So as soon as there are no collisions in this space,
/// we can just concatenate both.
fn combine_subpolymer(left: &mut String, right: &str) {
    let mut i = 0;
    while i < right.len() {
        if let Some(left_end) = left.pop() {
            if !are_opposites(left_end, right.chars().nth(i).unwrap()) {
                // Put it back in!
                left.push(left_end);
                break;
            }
        } else {
            break;
        }

        i += 1;
    }

    if i < right.len() {
        left.push_str(&right[i..]);
    }
}

/// Multi-threaded implementation
///
/// What happens is rayon will split the input, and multiple smaller folds will
/// happen. We construct several strings from that, reduce them, and combine
/// them.
///
/// Graphically ('|' separate threads):
///
/// Init:
/// "dabAcCaCBAcCcaDA"
///
/// Thread separation:
///   'd' 'a' 'b' 'A' 'c' | 'C' 'a' 'C' 'B' 'A' 'c' | 'C' 'c' 'a' 'D' 'A'
///
/// Sub-string construction:
///   "dabAc"  |  "CaCBAc"  |  "CcaDA"
///
/// Reduction:
///   "dabAc"  |  "CaCBAc"  |  "aDA"
///
/// Combination:
///   "dabCBAc"  |  "aDA"
///   "dabCBAcaDA"
fn reduce_polymer(puzzle: String) -> usize {
    puzzle
        .par_chars()
        // Make sub-strings
        .fold(
            || String::new(),
            |mut s, c| {
                s.push(c);
                s
            },
        )
        // Reduce them
        .map(|subpolymer| reduce_subpolymer(&subpolymer))
        // Combine them
        .reduce(
            || String::new(),
            |mut acc, subpolymer| {
                combine_subpolymer(&mut acc, &subpolymer);
                acc
            },
        )
        .len()
}

fn part1() {
    let result = reduce_polymer(PUZZLE.trim().to_owned());
    println!("Size: {}", result);
}

fn part2() {
    let min = Arc::new(Mutex::new(std::usize::MAX));

    (b'a'..b'z')
        .into_par_iter()
        .for_each_with(min.clone(), |min, letter_code| {
            let lower_letter = letter_code as char;
            let upper_letter = lower_letter.to_uppercase().next().unwrap();

            let candidate = PUZZLE
                .trim()
                .par_chars()
                // Could be done while constructing the sub-strings in
                // `reduce_polymer` but I haven't found an elegant way of doing
                // this, whithout code duplication
                .filter(|&letter| letter != lower_letter && letter != upper_letter)
                .collect();

            let result = reduce_polymer(candidate);

            let mut min = min.lock().unwrap();
            if result < *min {
                *min = result;
            }
        });

    println!("Result: {}", *min.lock().unwrap());
}

3

u/aurele Dec 05 '18 edited Dec 05 '18

My newest version does not use rayon anymore but has been optimized further and runs in ~600µs for part2 (and under 1ms for both parts):

#[aoc(day5, part1)]
fn part1(input: &[u8]) -> usize {
    polymere(input[..input.len() - 1].iter().cloned()).len()
}

#[aoc(day5, part2)]
fn part2(input: &[u8]) -> usize {
    let reduced = polymere(input[..input.len() - 1].iter().cloned());
    (b'a'..=b'z')
        .map(|c| polymere(reduced.iter().cloned().filter(|&b| b | 32 != c)).len())
        .min()
        .unwrap()
}

fn polymere(input: impl Iterator<Item = u8>) -> Vec<u8> {
    let mut output: Vec<u8> = Vec::new();
    for c in input {
        if output.last().map(|&l| l ^ c == 32).unwrap_or(false) {
            output.pop();
        } else {
            output.push(c);
        }
    }
    output
}
→ More replies (2)

3

u/askalski Dec 05 '18

On the fifth day of AoC / My true love sent to me / Five golden Perls.

"Optimized" brute force regex solution in Perl can react two nested particles at a time! 40% faster than the alternative that reacts only one particle!

$ time ./day05-optimized.pl input.txt
Part 1: 10766
Part 2: 6538

real    0m0.138s
user    0m0.138s
sys     0m0.000s

$ time ./day05-unoptimized.pl input.txt
Part 1: 10766
Part 2: 6538

real    0m0.235s
user    0m0.235s
sys     0m0.000s

1

u/Unihedron Dec 05 '18 edited Dec 05 '18

Had two bugs... Fixed one, couldn't find the other one fast enough :p Ruby

[Card] Nsfw Image

(I was using $<.chars instead of $<.read, which was an enumerable and after it consumes for the first time it doesn't work a second time...)

g=' '
a=$<.read
a.chars{|x|g[-1].downcase==x.downcase && g[-1] != x ? (g[-1]='') : g<<x}
p g.strip.size

a=g.strip # This line is added afterwards because all initial reductions also apply regardless of which letter to take away, so part 1 can be used as a first pass
p a.downcase.chars.uniq.map{|x|g=' '
a.chars.reject{|y|y.downcase==x}.each{|x|g[-1].downcase==x.downcase && g[-1] != x ? (g[-1]='') : g<<x}
g.strip.size
}.min

1

u/daggerdragon Dec 05 '18

[Card] Image

Mark that NSFW. I'll re-approve the comment when you do.

→ More replies (1)

2

u/vash3r Dec 05 '18

Python 2 (Pypy), #4/14. Basically just did it with string replacement until no more pairs could react.

#part 1 - r is the input
r1 = r
l1 = len(r1)
l2 = l1+1
while l1!=l2:
	l2 = l1
	for c in "qwertyuiopasdfghjklzxcvbnm":
		r1 = r1.replace(c+c.upper(),"").replace(c.upper()+c,"")
	l1 = len(r1)
print l1

# part 2 - takes ~5 seconds with Pypy 2 on my machine
m = 100000000
for _c in "qwertyuiopasdfghjklzxcvbnm":
	r2 = r.replace(_c,"").replace(_c.upper(),"")
	l1 = len(r2)
	l2 = l1+1
	while l1!=l2:
		l2 = l1
		for c in "qwertyuiopasdfghjklzxcvbnm":
			r2 = r2.replace(c+c.upper(),"").replace(c.upper()+c,"")
		l1 = len(r2)
	if l1 < m:
		m = l1
print m

3

u/Ryryme Dec 05 '18

"qwertyuiopasdfghjklzxcvbnm" that's genius I love it

→ More replies (2)
→ More replies (4)

2

u/ValdasTheUnique Dec 05 '18

C#. Problem was very easy but I wasted a lot of time doing the check incorrectly so no leaderboard for me.

public static void Part1()
{
    var stack = new Stack<char>();
    foreach (var c in Input)
    {
        if (stack.Count == 0)
        {
            stack.Push(c);
        }
        else
        {
            var inStack = stack.Peek();
            var same = c != inStack && char.ToUpper(c) == char.ToUpper(inStack);
            if (same)
            {
                stack.Pop();
            }
            else
            {
                stack.Push(c);
            }
        }
    }

    Console.WriteLine(stack.Count);
}

public static void Part2()
{
    var min = int.MaxValue;
    for (var i = 'a'; i < 'z'; i++)
    {
        var s = Input.Replace(i.ToString(), "").Replace(char.ToUpper(i).ToString(), "");
        var stack = new Stack<char>();
        foreach (var c in s)
        {
            if (stack.Count == 0)
            {
                stack.Push(c);
            }
            else
            {
                var inStack = stack.Peek();
                var same = c != inStack && char.ToUpper(c) == char.ToUpper(inStack);
                if (same)
                {
                    stack.Pop();
                }
                else
                {
                    stack.Push(c);
                }
            }
        }

        if (stack.Count < min)
        {
            min = stack.Count;
        }
    }

    Console.WriteLine(min);
}
→ More replies (1)

2

u/[deleted] Dec 05 '18

Python 3 #49/#94

If I actually remembered to assign the str.replace() results the first few quick tries, I could've gotten a bit higher on part 2. This is my first time on the leaderboard though, so I'm very happy with that.

with open("p05.dat", "r") as f:
    original_data = f.read().rstrip()

alphabet = "abcdefghijklmnopqrstuvwxyz"
pairs = [c + c.upper() for c in alphabet]
pairs += [c.upper() + c for c in alphabet]
def react(s):
    for p in pairs:
        s = s.replace(p, "")
    return s

def full_react(s):
    ps = data
    s = data
    while True:
        s = react(ps)
        if s == ps:
            break
        ps = s
    return s

data = original_data
print(len(full_react(data)))

lens = []
for c in alphabet:
    data = original_data
    # remember to store your results!
    data = data.replace(c, "")
    data = data.replace(c.upper(), "")
    lens.append(len(full_react(data)))
print(min(lens))

2

u/wimglenn Dec 05 '18

I don't get it, the first time you replace a pair it can reveal new pairs that didn't get seen on the first pass - e.g. abaABA - why wasn't this a problem for you?

→ More replies (3)
→ More replies (4)

2

u/NeuroXc Dec 05 '18

Rust

Maybe not the most elegant solution, but it works.

use std::collections::VecDeque;

fn reduce_chain(mut chain: VecDeque<char>) -> VecDeque<char> {
    let mut result = VecDeque::new();
    loop {
        let input_len = chain.len();
        loop {
            if chain.is_empty() {
                break;
            }
            loop {
                if result.is_empty() {
                    if let Some(next) = chain.pop_front() {
                        result.push_back(next);
                    } else {
                        break;
                    }
                }
                if let Some(next) = chain.pop_front() {
                    let prev = *result.back().unwrap();
                    if prev != next && prev.to_ascii_lowercase() == next.to_ascii_lowercase() {
                        // Reaction occurs
                        result.pop_back();
                        continue;
                    } else {
                        result.push_back(next);
                    }
                }
                break;
            }
        }
        if input_len == result.len() {
            return result;
        }
        chain = result;
        result = VecDeque::new();
    }
}

#[aoc(day5, part1)]
pub fn day5_part1(input: &str) -> usize {
    reduce_chain(input.trim().chars().collect::<VecDeque<_>>()).len()
}

const ASCII_LOWER: [char; 26] = [
    'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
    't', 'u', 'v', 'w', 'x', 'y', 'z',
];

#[aoc(day5, part2)]
pub fn day5_part2(input: &str) -> usize {
    let original = reduce_chain(input.trim().chars().collect::<VecDeque<_>>());
    let mut results = [0usize; 26];
    for i in 0..26 {
        results[i] = reduce_chain(
            original
                .iter()
                .filter(|c| c.to_ascii_lowercase() != ASCII_LOWER[i])
                .cloned()
                .collect(),
        ).len();
    }
    *results.iter().min().unwrap()
}

#[test]
fn test_part1() {
    assert_eq!(day5_part1("dabAcCaCBAcCcaDA"), 10);
}

#[test]
fn test_part2() {
    assert_eq!(day5_part2("dabAcCaCBAcCcaDA"), 4);
}

Performance:

Day 5 - Part 1 : #####
        runner: 747.272µs

Day 5 - Part 2 : ####
        runner: 4.37843ms
→ More replies (3)

2

u/Fyver42 Dec 05 '18
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>

#define LENGTH  50000

int react(char *polymer)
{
    int reaction = 1;
    while (reaction) {
        reaction = 0;
        for (int i = 0; i < LENGTH - 1; i++)
            if (polymer[i] != ' ') {
                int j = i + 1;
                while (polymer[j] == ' ' && j < LENGTH)
                    j++;
                if (abs(polymer[i] - polymer[j]) == 'a' - 'A') {
                    polymer[i] = polymer[j] = ' ';
                    reaction = 1;
                }
            }
    }

    int count = 0;
    for (int i = 0; i < LENGTH; i++)
        if (polymer[i] != ' ')
                count ++;
    return count;
}

int main()
{
    char *polymer;
    char initpolymer[LENGTH + 1];

    FILE *fp = fopen("inputs/day05", "r");
    fgets(initpolymer, sizeof(initpolymer), fp);

    polymer = strndup((char *)initpolymer, LENGTH);
    printf("%d\n", react(polymer));
    free(polymer);

    int min = LENGTH;
    for (int c = 'a'; c <= 'z'; c++) {
        polymer = strndup((char *)initpolymer, LENGTH);
        for (int i = 0 ; i < LENGTH; i++)
            if (polymer[i] == c || polymer[i] == c - ('a' - 'A'))
                polymer[i] = ' ';
        int len = react(polymer);
        if (len < min)
            min = len;
        free(polymer);
    }

    printf("%d\n", min);

    return 0;
}

2

u/BafDyce Dec 05 '18

[Card] On the fifth day of AoC / My true love sent to me / Five golden mistakes

Code (in Rust): https://gitlab.com/BafDyce/adventofcode/blob/master/2018/rust/day05/src/part1.rs

At the beginning, I had to fight string/char-iterators a lot, and I had quite some inefficient code (I didnt know to_lowercase/to_uppercase returned an iterator, so I was confused why i cannot compare them, so i used .to_string() everywhere..)

The final code runs in 2 minutes, 10 seconds for both parts.

2

u/ka-splam Dec 05 '18
PowerShell #509 / #499

[card] My true love sent to me: 5 golden newlines.

A bit of a bad one, started off seeing what I needed to do, but hesitating on how. Then I had 10386 and it was wrong. I was around 6 minutes, borderline late on the scoreboard, but I couldn't see any problem with my code.

Spent another 6+ minutes bashing my face into that, before I realised I had read \r\n newlines at the end of the file and my polymer code was fine, the real answer was 10384. Gahhhhh

$p = (get-content .\data.txt -Raw).Trim()
$pprev = ''
$letters = [string[]][char[]](97..122)
while ($pprev -ne $p)
{
    $pprev = $p
    foreach ($l in $letters)
    {
        $p = $p -creplace ($l.tolower() + $l.toupper()), ''
        $p = $p -creplace ($l.toupper() + $l.tolower()), ''            
    }
}
$p.Length

Part 2:

No better; I made the reactor into a function, then instead of passing in (the polymer without A, the polymer without B), I passed in (the alphabet without A, the alphabet without B..). Again, kinda knew what I wanted, but just flubbed it in the implementation rush.

$p = (get-content .\data.txt -Raw).Trim()
$letters = [string[]][char[]](97..122)

function react-polymer ($p) {
    $pprev = ''

    while ($pprev -ne $p)
    {
        $pprev = $p
        foreach ($l in $letters)
        {
            $p = $p -creplace ($l.tolower() + $l.toupper()), ''
            $p = $p -creplace ($l.toupper() + $l.tolower()), ''
        }
    }
    return $p.Trim().Length
}

$r = foreach ($l in $letters) 
{
    $tmp = react-polymer ($p-replace$l)
    [pscustomobject]@{
        'leng'=[int]$tmp
        'letter'=$l
    }
}

$r | sort -Property leng -desc

This runs in about 18 seconds; I thought I could speed it up by making the regex a single long aA|Aa|bB|Bb.. because that would start the regex engine once, and remove the inner while(){} loop from PS, which is usually a good optimization. Push more things down lower into the .Net framework. But, to my surprise, it's dramatically slower. I can only guess that there's a lot of regex backtracking involved for every character doing a lookahead, then backtracking out.

If I'd been using PowerShell 6, I could have done 'a'..'z' for the alphabet and not had to go "97 to ... what's 97 + 26?"

3

u/hpzr24w Dec 05 '18

As I found out tonight, trying to bisect the answer by repeated guesses does not work.

Thanks Eric!!!!!

2

u/Smylers Dec 05 '18

...and not had to go "97 to ... what's 97 + 26?"

I've never used PowerShell, but can't it do arithmetic? As in, if you'd written 97+25,would that have worked?

→ More replies (1)

2

u/tk3369 Dec 05 '18 edited Dec 05 '18

Julia - simple loops. I'm sure it can be done more elegantly but going with it due to time pressure :-)

function annihilate(s)
    while true
        v = Char[]
        i = 1
        elim = false
        while i <= length(s)
            if i == length(s)
                push!(v, s[i])
            elseif abs(Int(s[i+1]) - Int(s[i])) != 32  
                # 32 is the distance between lower/uppercase letters
                push!(v, s[i])
            else
                i += 1      # skip next letter
                elim = true
            end
            i += 1
        end
        !elim && break   # break when there's nothing more to do
        s = v
    end
    join(Char.(s))
end

input = readlines("input5.txt")[1]

# part 1 - elapsed 0.15 seconds
input |> collect |> annihilate |> length

# part 2 - elapsed 2.27 seconds
Dict(c => replace(input, Regex("$c", "i") => "") |> collect |> annihilate |> length 
         for c in "abcdefghijklmnopqrstuvwxyz")
→ More replies (5)

2

u/scul86 Dec 05 '18 edited Dec 05 '18

Python 3

from utils.decorators import time_it

with open('input') as f:
    puzzle_input = f.readline().strip()


def part1(n):
    for i in range(len(n) - 1, 0, -1):
        a, b = n[i], n[i-1]
        if a != b and a.lower() == b.lower():
            if i == len(n)-1:
                n = ' ' + n[:i-1]
            else:
                n = n[:i-1] + n[i+1:]
    return len(n.strip())


@time_it
def part2(n):
    chars = set(n.lower())
    ret = min(part1(n.replace(char, '').replace(char.upper(), '')) for char in chars)
    return ret


test_one = 'dabAcCaCBAcCcaDA'

assert part1('bAaB') == 0
assert part1(test_one) == 10
print(f'Part 1: {part1(puzzle_input)}')

assert part2(test_one) == 4
print(f'Part 2: {part2(puzzle_input)}')

Edit: updated part1() function, found a failing test with prior code.

2

u/Frizkie Dec 05 '18 edited Dec 05 '18

Ruby

chars = File.read('data.txt').chomp.chars

Part 1

loop { (r = chars.find_index.with_index { |c, i| c == chars[i+1]&.swapcase }) ? (2.times { chars.delete_at(r) }) : (break) }
puts chars.count

Part 2

results = {}

def react(chars)
  loop { (r = chars.find_index.with_index { |c, i| c == chars[i+1]&.swapcase }) ? (2.times { chars.delete_at(r) }) : (break) }
  return chars.count
end

('a'..'z').each { |p| results[p] = react(chars.clone.delete_if { |c| c.downcase == p }) }
puts "result: #{results.values.min}"

This was a fun one. Cool to see that I was able to fit the loop in part 1 on a single line too. Also, don't bother trying the part 2 solution, it's horrifically slow (7 minutes). Luckily a was the character with the shortest resulting string for my input, and i saw mid-run that it was significantly smaller than other letters' results, so I tried it before it was finished and got it right before the script finished.

EDIT: Here's a bonus multi-threaded solution to part 2 (you'll need something other than MRI to run it, I used JRuby, because MRI doesn't schedule on multiple cores). It ran on 12 logical cores and finished after 70 seconds. Yikes.

chars = File.read('data.txt').chomp.chars
results = {}

def react(chars)
  loop { (r = chars.find_index.with_index { |c, i| c == chars[i+1]&.swapcase }) ? (2.times { chars.delete_at(r) }) : (break) }
  return chars.count
end

('a'..'z').map { |p| Thread.new { results[p] = react(chars.clone.delete_if { |c| c.downcase == p }) } }.each(&:join)
sleep(1) until results.count == 26
puts "result: #{results.values.min}"

2

u/nutrecht Dec 05 '18

Lot easier than yesterday. Day 5 in Kotlin

private val input = resourceString(2018, 5)

override fun part1() = react(input)

override fun part2() =
    input.map { it.toLowerCase() }.toSet()
            .map { c -> c to input.filter { it.toLowerCase() != c } }
            .map { it.first to react(it.second) }
            .minBy { it.second }!!.second

private fun react(inp: String) : Int {
    val poly = StringBuilder(inp)

    while(true) {
        var changes = false

        for(i in (0 until poly.length - 1)) {
            if(poly[i].toLowerCase() == poly[i + 1].toLowerCase() && poly[i] != poly[i + 1]) {
                poly.delete(i, i + 2)
                changes = true
                break
            }
        }

        if(!changes) {
            break
        }
    }

    return poly.length
}

2

u/tinyhurricanes Dec 05 '18

Modern Fortran 2018 (complete code)

Part 1 runs in 0.07 sec, part 2 in 2.3 sec.

program main
use syslog_mod
use fclap_mod
use file_tools_mod
use string_tools_mod
implicit none

!-- Counters
integer :: i, j, k

integer :: m

integer :: ix

!-- Input file unit
integer :: input_unit

!-- Number of lines in input file
integer :: num_lines

!-- Current length of polymer
integer :: len_polymer = 0

!-- Parameters
integer,parameter :: MAX_POLYMER_LEN = 60000
integer,parameter :: ASCII_CHAR_SHIFT_UPPERCASE = 64
integer,parameter :: ASCII_CHAR_SHIFT_LOWERCASE = 96
! A = 65, Z = 90, a = 97, z = 122
! a = 97 -> i = 1
! A = 65 -> i = 1

!-- Polymers
character(len=MAX_POLYMER_LEN) :: polymer
character(len=MAX_POLYMER_LEN) :: polymer_new
integer :: ipolymer(MAX_POLYMER_LEN)

!-- Main variables
integer,parameter :: NUM_UNITS = 26 ! (number of letters)
integer :: remove_upper_ix = 0      ! index of uppercase letter to try removing
integer :: remove_lower_ix = 0      ! index of lowercase letter to try removing

!-- Input file reading properties
integer,parameter            :: max_line_len = 600000
character(len=max_line_len)  :: line
character(len=:),allocatable :: input_file

!-- Initialize System Log
call init_syslog

!-- Process Command Line Arguments
call configure_fclap
call parse_command_line_arguments

!-- Get input file name from command line
input_file = get_value_for_arg('input_file')

!-- Start timer
call syslog % start_timer

LESION_LOOP: do m = 0, NUM_UNITS

    !-- Open file and read into memory
    open (                    & 
        newunit = input_unit, & 
        file    = input_file, &
        action  = 'read',     &
        status  = 'old',      &
        form    = 'formatted' &
    )
    read (input_unit,'(a)') line
    close (input_unit)

    if (len(trim(line)) <= max_line_len) then
        polymer = trim(adjustl(line))
        !write (syslog%unit,*) polymer
    else
        write(syslog%unit,*) 'Error: line exceeded maximum length'
        call bomb
    end if

    ! For non-first loops, try removing letter pairs (Aa,Bb,etc.) and replace with space
    if (m /= 0) then
        remove_lower_ix = m + ASCII_CHAR_SHIFT_LOWERCASE
        remove_upper_ix = m + ASCII_CHAR_SHIFT_UPPERCASE
        do i = 1, len(polymer)
            if (iachar(polymer(i:i)) == remove_lower_ix .or. &
                iachar(polymer(i:i)) == remove_upper_ix) then
                polymer(i:i) = ' '
            end if
        end do
    end if
    
    k = 0
    MAIN_LOOP: do
    
        ! Increment loop counter
        k = k + 1

        ! Reset length reduction counter
        j = 0

        len_polymer = len(adjustl(trim(polymer)))
        ipolymer(:) = 0
        polymer_new = ' '

        POLYMER_DIGITIZER: do i = 1, len_polymer

            ix = iachar(polymer(i:i))

            if (ix >= 65 .and. ix <= 90) then ! uppercase (+ve)
                ix = +(ix - ASCII_CHAR_SHIFT_UPPERCASE)
            else if (ix >= 97 .and. ix <= 122) then ! lowercase (-ve)
                ix = -(ix - ASCII_CHAR_SHIFT_LOWERCASE)
            else if (ix == 32) then !space
                ix = 0
            else
                print*,'Unknown character',ix,'(',polymer(i:i),') on iteration ',k
                error stop
            end if

            ipolymer(i) = ix
        end do POLYMER_DIGITIZER

        PAIR_ANNIHILATOR: do i = 1, len_polymer - 1

            if (ipolymer(i) == -ipolymer(i+1)) then

                ! Annihilate
                ipolymer(i:i)     = 0
                ipolymer(i+1:i+1) = 0

            end if

        end do PAIR_ANNIHILATOR

        REBUILD_POLYMER_STRING: do i = 1, len_polymer

            if (ipolymer(i) == 0) then
                j = j + 1
                cycle REBUILD_POLYMER_STRING
            end if

            if (ipolymer(i) > 0) then
                ix = ipolymer(i) + ASCII_CHAR_SHIFT_UPPERCASE
                polymer_new(i-j:i-j) = achar(ix)
            else
                ix = -ipolymer(i) + ASCII_CHAR_SHIFT_LOWERCASE
                polymer_new(i-j:i-j) = achar(ix)
            end if
            
        end do REBUILD_POLYMER_STRING
        
        if (j == 0) exit MAIN_LOOP ! done: didn't remove any this round

       !write (syslog%unit,*) ' iter = ', k, ' len = ', size(ipolymer)
       !write (syslog%unit,*) polymer_new

        polymer = adjustl(polymer_new)

    end do MAIN_LOOP

    ! Part 1
    if (m == 0) then
        write (syslog%unit,*) 'Part 1: ', len(adjustl(trim(polymer))) ! 11754
        write (syslog%unit,*) 'Part 2: '
        write (syslog%unit,*) ' # Letter  Length'
    ! Part 2
    else
        write (syslog%unit,'(i3,a5,i10)') &
            m,achar(m+ASCII_CHAR_SHIFT_LOWERCASE),len(adjustl(trim(polymer))) ! t=4098
    end if

end do LESION_LOOP

!-- End timer
call syslog % end_timer

call syslog%log(__FILE__,'Done.')

end program

2

u/donatasp Dec 05 '18

Amazing.

2

u/streetster_ Dec 05 '18 edited Dec 05 '18

Day 05 in Q/KDB+

fold:{ $[32=abs y-last x;-1_(),x;x,y] }
/ Part 1
count fold/[j:"j"$r:first read0 `:input/05.txt]
/ Part 2
min { count fold/[x] } each j except/:-32 0+/:"j"$distinct lower r
→ More replies (1)

2

u/meithan Dec 05 '18 edited Dec 07 '18

Python

I initially solved it in an incredibly stupid and slow way (that took ~6.5 minutes to process both parts). Then I reworked it in an effort to optimize it, and found an obvious solution that takes less than half a second. Key points:

  • Using a stack to build the "reduced" ("reacted") list of units letter by letter in a single pass of the original list: take the next letter from the original list; if it reacts with the top of the stack, pop the top of the stack (and don't add the letter); if it doesn't, add the letter to the stack.

  • Appending or removing an item to/from the end of a list in Python is O(1) (amortized), so it's an efficient stack

I also use the fact that the difference in the ASCII codes of a lowercase letter and its uppercase version is always 32, but a != b and a.lower() == b.lower(), as seen in another answer, is simpler and just as fast.

I also tried using a deque (from Python's collections module), but it's not any faster, proving that the Python list appends/pops are effectively very close to O(1), at least in this case.

Edit: I applied further optimizations as suggested by others, with the resulting of bringing runtime from ~500 ms to less than 100 ms!

  • Pre-computing the ASCII codes of the input letters and doing the reactions using the codes (avoiding further calls to ord(), lower(), etc.)

  • Using string replace() instead of a list comprehension to eliminate the given letter in Part 2. String replace() is surprisingly fast!

  • And the biggest optimization came from realizing you can reuse the shorter result of Part 1 as a starting point for Part 2.

Here's the (optimized) code. Solves both parts in under 100 ms on my computer. Very simple and fast.

from string import ascii_lowercase

units = open("day5.in").read().strip()

def reduce(units):
  new_units = []
  for c in [ord(x) for x in units]:
    if len(new_units) > 0 and abs(c - new_units[-1]) == 32:
      new_units.pop()
    else:
      new_units.append(c)
  return new_units

# Part 1

reduced_units = "".join([chr(x) for x in reduce(units)])
print("Part 1:", len(reduced_units))

# Part 2

min_len = None
for letter in ascii_lowercase:

  units1 = reduced_units.replace(letter, "").replace(letter.upper(), "")
  reduced = reduce(units1)

  if min_len is None or len(reduced) < min_len:
    min_len = len(reduced)

print("Part 2:", min_len)
→ More replies (11)

2

u/fotoetienne Dec 05 '18 edited Dec 05 '18

Kotlin solution here. Using a stack to get O(n) runtime.

fun react(polymer: CharArray, omit: Char? = null) = Stack<Char>().apply {
    for (char in polymer)
        if (isNotEmpty() && abs(char - peek()) == 'a' - 'A') pop() // Found a pair. React!
        else if (char.toUpperCase() != omit) push(char)            // Not a pair :(
}.size

println("Part 1 - Reacted size: ${react(polymer)}")

val minSize = ('A'..'Z').map { react(polymer, omit = it) }.min()
println("Part 2 - Reacted size with problem pair removed: $minSize")

Full solution on github

2

u/HiramAbiff Dec 05 '18

AWK

5.1

awk '{a="abcdefghijklmnopqrstuvwxyz";do{s=0;for(i=1;i<=26;++i){c=substr(a,i,1);C=toupper(c);s+=gsub(c C,"")+gsub(C c,"")}}while(s);print length}' input5.txt

5.2

awk '{a="abcdefghijklmnopqrstuvwxyz";o=length;for(j=1;j<=26;++j){p=$0 "";c=substr(a,j,1);gsub(c,"",p);gsub(toupper(c),"",p);do{s=0;for(i=1;i<=26;++i){c=substr(a,i,1);C=toupper(c);s+=gsub(c C,"",p)+gsub(C c,"",p)}}while(s);if(length(p)<o)o=length(p)}}END{print o}' input5.txt

2

u/blowjobtransistor Dec 05 '18

PostgreSQL

Wow, before doing it with regexp, this one was turning into a nightmare with window functions in SQL...

create table regexp as
select 'Aa|aA|Bb|bB|Cc|cC|Dd|dD|Ee|eE|Ff|fF|Gg|gG|Hh|hH|Ii|iI|Jj|jJ|Kk|kK|Ll|lL|Mm|mM|Nn|nN|Oo|oO|Pp|pP|Qq|qQ|Rr|rR|Ss|sS|Tt|tT|Uu|uU|Vv|vV|Ww|wW|Xx|xX|Yy|yY|Zz|zZ' as regexp;

create table polymer as
with recursive tmp(line, removed, iter) as (
select
    regexp_replace(line, regexp, '') as line,
    (regexp_matches(line, regexp))[1] as removed,
    0 as iter
from input, regexp
union all
select
    regexp_replace(line, regexp, '') as line,
    (regexp_matches(line, regexp))[1] as removed,
    iter + 1
from tmp, regexp
where removed notnull
)
select
line
from tmp
order by iter desc
limit 1;

create view part_2_solution as
with recursive tmp(letter, line, removed, iter) as (
with removals as (
    select chr(97 + offs) as letter
    from generate_series(0, 25) as offs
)
select
    letter,
    regexp_replace(line, '[' || letter || upper(letter) || ']', '', 'g') as line,
    letter as removed,
    0 as iter
from polymer, regexp, removals
union all
select
    letter,
    regexp_replace(line, regexp, '') as line,
    (regexp_matches(line, regexp))[1] as removed,
    iter + 1
from tmp, regexp
where removed notnull
)
select min(length(line)) as answer
from tmp;

select 1 as part, length(line) as answer from polymer
union all
select 2 as part, answer from part_2_solution;

2

u/ephemient Dec 05 '18 edited Apr 24 '24

This space intentionally left blank.

2

u/Vladob Dec 05 '18

No Perl 5 solution so far? One pretty straightforward here:

#!/usr/bin/env perl
use strict;
use warnings;

sub reduce
{
    my ($line,@ra) = @_;
    my $r = join( '|', @ra);
    1 while( $line =~ s/$r//g );
    return $line;
}

my $line = <>;
chomp $line;

my @react;
foreach my $x ( 'a' .. 'z' ) {
    push @react, ( lc($x).uc($x), uc($x).lc($x) );
}

my $r1 = reduce( $line, @react);
print( "Part 1: reduced polymer has ", length($r1), " units.\n");

my ($min_c,$min_l) = ( undef, length($line));
foreach my $x ( 'a' .. 'z' ) {
    my $ll = length( reduce( reduce( $line, lc($x), uc($x)), @react));
    if( $ll < $min_l ) {
        $min_l = $ll;
        $min_c = $x;
    }
}

print( "Part 2: removing unit $min_c, the polymer can be reduced to $min_l length.\n");

2

u/mschaap Dec 05 '18 edited Dec 05 '18

My Perl 6 solution:

#!/usr/bin/env perl6
use v6.c;

$*OUT.out-buffer = False;   # Autoflush

sub process(Str $polymer)
{
    constant @units = flat 'a'..'z', 'A'..'Z';
    constant %opposite = hash @units Z=> @units.rotate(26);

    my @c = $polymer.comb;
    loop (my $i = 0; $i+1 < @c; $i++)
    {
        next if $i < 0;
        if @c[$i+1] eq %opposite{@c[$i]} {
            @c.splice($i,2);
            $i -= 2;
        }
    }

    return @c.join;
}

sub polymer-without(Str $polymer, Str $c)
{
    return $polymer.subst(/:i $c/, '', :g);
}

#| Process polymer input
multi sub MAIN(Str $input is copy)
{
    my $output = process($input);
    say "$output.chars() units left after reacting.";

    my %removed = $input.lc.comb.sort.squish.map(-> $c { $c => process(polymer-without($output, $c)) });
    my $shortest = %removed.min(*.value.chars);
    say "$shortest.value().chars() units left after removing $shortest.key() and reacting.";
}

#| Process polymer input from a file
multi sub MAIN(Str $inputfile where *.IO.f)
{
    MAIN($inputfile.IO.slurp.chomp);
}

#| Process default polymer file (aoc5.input)
multi sub MAIN()
{
    MAIN(~$*PROGRAM.sibling('aoc5.input'));
}

This runs in 2 seconds.

My first attempt was regex-based. Cleaner code, perhaps, but part one took about 3 minutes, and I don't know yet how long part two would take... 😉 (Even with the optimization of taking the output of part 1 instead of the original input.) Edit: actually, not that bad, about 7½ minutes for both parts.

The process sub for that attempt:

sub process(Str $polymer is copy)
{
    constant @units = flat 'a'..'z', 'A'..'Z';
    constant @pairs = @units Z~ @units.rotate(26);

    while $polymer ~~ s:g/ ||@pairs // { }
    return $polymer;
}

The rest of the code is identical.

Edit: with the XOR trick, the process sub can be simplified to:

sub process(Str $polymer)
{
    my @c = $polymer.ords;
    loop (my $i = 0; $i+1 < @c; $i++)
    {
        next if $i < 0;
        if @c[$i] +^ @c[$i+1] == 0x20 {
            @c.splice($i,2);
            $i -= 2;
        }
    }
    return @c.chrs;
}

This runs slightly faster than my original version – about 1⅔ seconds for both parts.

→ More replies (1)

2

u/mstksg Dec 05 '18 edited Dec 05 '18

[Haskell] From my daily reflections post :)

One of the first higher-order functions you learn about in Haskill is foldr, which is like a "skeleton transformation" of a list.

That's because in Haskell, a (linked) list is one of two constructors: nil ([]) or cons (:). The list [1,2,3] is really 1:(2:(3:[])).

foldr f z is a function that takes a list replaces all :s with f, and []s with zs:

          [1,2,3] = 1  :  (2  :  (3  :  []))
foldr f z [1,2,3] = 1 `f` (2 `f` (3 `f` z ))

This leads to one of the most famous identities in Haskell: foldr (:) [] xs = xs. That's because if we go in and replace all (:)s with (:), and replace all []s with []... we get back the original list!

But something we can also do is give foldr a "custom cons". A custom cons that will go in place of the normal cons.

This problem is well-suited for such a custom cons: instead of normal (:), we'll write a custom cons that respects the rules of reaction: we can't have two "anti-letters" next to each other:

anti :: Char -> Char -> Bool
anti x y = toLower x == toLower y && x /= y

funkyCons :: Char -> String -> String
x `funkyCons` (y:xs)
    | anti x y  = xs
    | otherwise = x:y:xs
x `funkyCons` []     = [x]

So, foldr funkyCons [] will go through a list and replace all (:) (cons) with funkyCons, which will "bubble up" the reaction.

So, that's just the entire part 1!

day05a :: String -> Int
day05a = length . foldr funkyCons []

For part 2 we can just find the minimum length after trying out every character.

day05b :: String -> Int
day05b xs = minimum [ length $ foldr funkyCons [] (remove c xs)
                    | c <- ['a' .. 'z']
                    ]
  where
    remove c = filter ((/= c) . toLower)

(Note that in the actual input, there is a trailing newline, so in practice we have to strip it from the input.)

2

u/wzkx Dec 05 '18

J

Slow.... 5.6s, 132s

t=: a.i.LF-.~CR-.~fread '05.dat'
f=: 3 :'while.(z=.(1 i.~32=[:|}.-}:)y)<<:#y do.y=.(z{.y),y}.~z+2 end.#y'
echo f t
echo <./(3 :'f(t-.y)-.y+32')"0[65+i.26
exit 0

2

u/wzkx Dec 05 '18

OK, tacit way. But this is slower because some calculations are repeated both in condition and in transformation. About 5 minutes in total.

f=: #@((({.~,(}.~2&+))(1 i.~32=[:|}.-}:))^:((1 i.~32=[:|}.-}:)<<:&#)^:_)
echo f t=: a.i.LF-.~CR-.~fread'05.dat'
echo <./(f@(t&(-.-.32+])))"0[65+i.26

2

u/wzkx Dec 05 '18

And this is in J style and FAST!

q=: #~-.@(0&,+.,&0)@(]>[:}:0:,])@(32=[:|}.-}:)
echo #q^:_ t=: a.i.LF-.~CR-.~fread'05.dat'
echo <./((#@(q^:_))@(t&(-.-.32+])))"0[65+i.26

2

u/azatol Dec 05 '18

F#. I went through three different versions of the main reaction code. The third version is more than 10 times faster, because I realized you can completely process a local area of the string before moving on.

I was going to try to create a doubly linked list, but the I realized I could hold the already processed part of the string in reverse order, so I can continue to pop off characters as required.

I learned about: optimizing string processing, using ranges for characters.

https://gist.github.com/apeterson-BFI/bdb4d37bd1815c3e9ffe92da4917428a

2

u/vypxl Dec 05 '18

Awk is fun I must say.

awk '{b=f($0);print b;split("abcdefghijklmnopqrstuvwxyz",a,"");for(i in a){IGNORECASE=1;r=f(gensub(a[i],"","g"));if(r<b) b=r}print b}function f(x){IGNORECASE=0;p="aA|Aa|bB|Bb|cC|Cc|dD|Dd|eE|Ee|fF|Ff|gG|Gg|hH|Hh|iI|Ii|jJ|Jj|kK|Kk|lL|Ll|mM|Mm|nN|Nn|oO|Oo|pP|Pp|qQ|Qq|rR|Rr|sS|Ss|tT|Tt|uU|Uu|vV|Vv|wW|Ww|xX|Xx|yY|Yy|zZ|Zz";while(x~p)gsub(p,"",x);return length(x)}' < 5.in

Generated the Regex with Python because of my laziness though.

Here, a readable version:

{
    best=f($0)
    print "Solution for part 1:"
    print best

    split("abcdefghijklmnopqrstuvwxyz",a,"")
    for(i in a){
        IGNORECASE=1
        r=f(gensub(a[i],"","g"))
        if(r<best) best=r
    }
    print "Solution for part 2:"
    print best
}

function f(x){
    IGNORECASE=0
    p="aA|Aa|bB|Bb|cC|Cc|dD|Dd|eE|Ee|fF|Ff|gG|Gg|hH|Hh|iI|Ii|jJ|Jj|kK|Kk|lL|Ll|mM|Mm|nN|Nn|oO|Oo|pP|Pp|qQ|Qq|rR|Rr|sS|Ss|tT|Tt|uU|Uu|vV|Vv|wW|Ww|xX|Xx|yY|Yy|zZ|Zz"
    while(x~p) gsub(p,"",x)
    return length(x)
}

Card: On the fifth day of AoC / My true love sent to me / Five golden cryptic awk oneliners

2

u/etagawesome Dec 05 '18

In C.

My first solution was dumb and brute-forcey. I was running through the input once, writing it to a file, then repeating until the input and output files were the same length. After that and checking this thread I decided a stack made a billion times more sense.

This solves part 1 and part 2

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>

int main() {
  size_t stack_cap=100;
  char* stack = malloc(sizeof(char) * stack_cap);
  for(char a='a'; a<='z'+1; ++a){
    // "empty" the stack
    size_t stack_len=0;
    while(1){
      char c = (char)fgetc(stdin);
      if(c == EOF){
        break;
      }
      char d = stack[stack_len-1];
      if((toupper(d) == c && !isupper(d)) ||
        (tolower(d) == c && !islower(d))) {
        //pop d
        stack_len--;
      } else {
        if (tolower(c) != a) {
          stack[stack_len++] = c;
          if (stack_len >= stack_cap) {
            stack_cap *= 2;
            stack = realloc(stack, sizeof(char) * stack_cap);
          }
        }
      }
    }
    fseek(stdin, 0, 0);
    printf("%c\t%lu\n", a, stack_len -1);
  }
  free(stack);
}

2

u/j4_james Dec 05 '18

Befunge - Both solutions are technically Befunge-93, but part 2 requires a Befunge-98 interpreter to handle the full size input, since Befunge-93 just doesn't have enough memory otherwise.

Part 1

<v9:_|#`*84:~p99:<$
|>9g-:48*-\48*+*#^_
+#\<0<@._1#!

Part 2

~:48*`#v_55*06g00p1+>1-:6g:00v>
v*55p50<  @.-*84g00_^#!:p0`g<<$
>:05g-:"A"+\"a"+*#v_:1-\!    #^_
4:-g50g-*55g6:::::<0v+*84\-*8
5g\:6g64*-p\6g\-\6p^>*!2*1-\0

2

u/dpeckett Dec 05 '18 edited Dec 06 '18

Continuing with my quest to solve all this years challenges using nothing other than AWK:

function z() {
  do {
    n=f=l=0;
    for(i in a)
      if(l&&a[l]!=a[i]&&tolower(a[l])==tolower(a[i]))a[i]=a[l]=0;
      else l=i;
    for(i in a)if(!a[i]){f=1;delete a[i]}else n++
  } while(f)
  return n
}BEGIN{PROCINFO["sorted_in"]="@ind_num_asc"}{
  split($1,b,"");
  for(i in b)d[tolower(b[i])]++;
  for(c in d) {
    for(i in b)a[i]=tolower(b[i])!=c?b[i]:0;
    r[z()]=c;
  }
  for(i in r){print i;exit}
}

Runtime:

real 0m8.181s
user 0m8.160s
sys  0m0.015s

Notes:

I should start the second challenge from the inputs of the first as an optimisation step.

2

u/IcyHammer Dec 05 '18

C# solution where I was aiming to maximize performance. First part takes 4ms to complete.

byte[] values = File.ReadAllBytes("input.txt");
int length = values.Length;

List<sbyte> currentValues = new List<sbyte>(values.Length);

int countMinusOne = 0;
sbyte asciiDistance = 32;
int valuesIndex = 0;

while (valuesIndex < length)
{
if (currentValues.Count == 0)
    currentValues.Add(unchecked((sbyte)values[valuesIndex++]));

countMinusOne = currentValues.Count - 1;
if (Mathf.Abs(currentValues[countMinusOne] - values[valuesIndex]) == asciiDistance)
    currentValues.RemoveAt(countMinusOne);
else
    currentValues.Add(unchecked((sbyte)values[valuesIndex]));

valuesIndex++;
}

2

u/hpzr24w Dec 05 '18

C

Not sure if I've spotted a C version, so I figured I'd write one!

Header

// Advent of Code 2018
// Day 05 - Alchemical Reduction

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

React

int react(char * s) {
    char *r = s+1, *w = s;
    while (*r)
        if ((*r^*w)==('A'^'a')) w--, r++; else *++w=*r++;
    *++w='\0';
    return w-s;
}

Main and Part 1

int main()
{
#if 1
    #include "day_05.h"
#else
    char o[] = "dabAcCaCBAcCcaDA";
    char s[] = "dabAcCaCBAcCcaDA";
#endif
    
    int l = react(s);
    printf("Part 1: Length: %d\n",l);

Part 2

    int b = l;
    for (int i='a';i<='z';++i) {
        char *p=s,*q=o;
        while (*p)
            if (tolower(*p)==i) p++; else *q++=*p++;
        *q='\0';        
        int c = react(o);
        b = c<b ? c : b;
    }
    printf("Part 2: Best length: %d\n",b);
    return 0;
}
→ More replies (2)

2

u/thatikey Dec 06 '18

(Haskell) It's not quite as beautiful as glguy's solution, but I was pretty proud of mine:

module DayFive where

import Data.Char (toLower)
import qualified Data.Set as Set
import Data.Ord (comparing)
import Data.Foldable (maximumBy)

isReactive a b = a /= b && toLower a == toLower b

partOne s = length $ collapse s []

totalCollapseRadius :: Char -> String -> String -> Int -> Int
totalCollapseRadius _ [] _ total = total
totalCollapseRadius c (a:rest) fstack total
    | c == toLower a = 
        let
            filtered = dropWhile (== c) rest
            len = length $ takeWhile (uncurry isReactive) $ zip filtered fstack
        in
            totalCollapseRadius c (drop len filtered) (drop len fstack) (total + len)
    | otherwise = totalCollapseRadius c rest (a:fstack) total

collapse :: String -> String -> String
collapse [] fstack = fstack
collapse (a:rest) [] = collapse rest [a]
collapse (a:rest) (b:fstack)
    | isReactive a b = 
        let 
            len = length $ takeWhile (uncurry isReactive) $ zip rest fstack
        in
            collapse (drop len rest) (drop len fstack)
    | otherwise = collapse rest (a:b:fstack)

partTwo s = 
    let
        collapsedResult = collapse s []
        polymers = Set.fromList (map toLower collapsedResult)
        (c, _) = maximumBy (comparing snd) $ map (\a -> (a, totalCollapseRadius a collapsedResult [] 0)) $ Set.toList polymers
    in
        length $ collapse (filter ((/= c) . toLower) collapsedResult) []

2

u/that_lego_guy Dec 07 '18

Day 5, IN EXCEL!!?!

=IF(A4=A5,EXACT(A4,A5),"")

https://github.com/thatlegoguy/AoC2018

1

u/liuquinlin Dec 05 '18 edited Dec 05 '18

Python 3:

Went with an index based solution for Part 1 to avoid having to iterate over the string too many times (Part 2 runs in less than a second), probably not really necessary versus just doing string replaces.

# l is the input

def p1(l):
    i = 0
    while i < (len(l) - 1):
        j = i + 1
    if (l[i] != l[j] and l[i].upper() == l[j].upper()):
       l = l[:i] + l[i+2:]
       i = max(0, i-1) # wasted a lot of time here due to not checking the 0 case
   else:
       i += 1
   return len(l)

def p2(l):
    m = len(l)
    for r in string.ascii_lowercase:
        x = l.replace(r, "").replace(r.upper(), "")
        m = min(m, p1(x))
    return m

2

u/wimglenn Dec 05 '18

shouldn't m = min(m, p1(x)) be indented more?

→ More replies (1)

1

u/Cyphase Dec 05 '18 edited Dec 05 '18

EDIT: My heavily optimized version is in a child comment. It runs in ~1.75ms for my AoC 50K input.

This is my Python solution that took waay to long to write for how simple it is. :/

def part1(data):  # 0.429s, best out of three
    i = 0
    d = list(data)

    while i + 1 < len(d):
        if d[i].lower() == d[i + 1].lower():
            if d[i] != d[i + 1]:  # match
                d.pop(i)
                d.pop(i)
                i -= 1
                continue
        i += 1

    return len(d)


def part2(data):  # 6.923s, best out of three
    return min(
        part1(list(x for x in data if x.lower() != c))
        for c in "abcdefghijklmnopqrstuvwxyz"
    )

4

u/Cyphase Dec 05 '18 edited Dec 05 '18

Here's my heavily optimized version of essentially the same algorithm.

Benchmarks are of the function only, not the interpreter starting or the input being read.


Update 1:

Benchmarks (on PyPy2): ~1.75ms for my AoC 50K input, ~4.44ms for a randomly generated 50K input, ~97.6ms for a 1M input, and ~521ms for a 5M input (the 1M * 5). The 50K and 1M random inputs were created by /u/mebeim.

def part2(d):
    d = [ord(x) for x in d]
    r = [0] * len(d)
    r[0] = d[0]
    ri = 1
    for i in range(1, len(d)):
        if ri and (r[ri - 1] ^ d[i]) == 32:
            ri -= 1  # .pop()
        else:
            r[ri] = d[i]  # .append(d[i])
            ri += 1
    d = r[:ri]
    min = float("inf")
    for c in range(97, 122 + 1):
        r[0] = d[0]
        ri = 1
        for i in range(1, len(d)):
            di = d[i]
            if di == c or di == c - 32:
                continue
            if ri and (r[ri - 1] ^ di) == 32:
                ri -= 1  # .pop()
                continue
            r[ri] = d[i]  # .append(d[i])
            ri += 1
        if ri < min:
            min = ri
    return min

Original post

Benchmarks (on PyPy2): ~8.33ms for my 50K input, ~29.2ms for a randomly generated 50K input from /u/mebeim, and ~674ms for a 1M input, also from /u/mebeim.

def part2(d):
    r = [0] * len(d)
    r[0] = d[0]
    ri = 1
    for i in range(1, len(d)):
        if ri and abs(ord(r[ri - 1]) - ord(d[i])) == 32:
            ri -= 1  # .pop()
        else:
            r[ri] = d[i]  # .append(d[i])
            ri += 1
    d = r[:ri]
    min = float("inf")
    for c in "abcdefghijklmnopqrstuvwxyz":
        r[0] = d[0]
        ri = 1
        for i in range(1, len(d)):
            di = d[i]
            if di.lower() == c:
                continue
            if ri and abs(ord(r[ri - 1]) - ord(di)) == 32:
                ri -= 1  # .pop()
            else:
                r[ri] = d[i]  # .append(d[i])
                ri += 1
        if ri < min:
            min = ri
    return min

1

u/pythondevgb Dec 05 '18

Feel like my solution is a 'dumb' one. Went for the obvious way of simply removing the letters that reacted from a list, this is really slow but anyway, although this one didn't feel as difficult as the past 2. I still lost a bunch of time mainly with iterating over and deleting elements from a list. That confused me a bit with the indices.

(Join my private reddit/python leaderboard, only requirement is to not have made the overall leaderboard thus far, PM for the code.)

inputstr = open('day5_input.txt').read()
theinput = list(inputstr)
deletions = True
uniques = set(inputstr.lower())
def collapse(polymer):
    deletions = True
    while deletions:
        i=0
        deletions = 0
        while i<(len(polymer)-1):
            first, second = polymer[i:i+2]
            if (first != second) and (first.lower() == second.lower()):
                del polymer[i:i+2]
                deletions+=1
            else: 
                i+=1
    return len(polymer)
    
polymers = [[l for l in theinput if not l.lower() == filtered] for filtered in uniques]

#Part1
print(collapse(theinput))

#Part2
print(min(collapse(polymer) for polymer in polymers))

2

u/zingaat Dec 05 '18

I've found it much easier to traverse the lists from end to start (max index to min) when deleting elements. Makes the whole messy indices issue moot.

1

u/shuttup_meg Dec 05 '18 edited Dec 05 '18

Python2

Nothing particularly interesting about my approach, but I did successfully use the multiprocessing module to greatly speed up part 2 (from about 12 seconds down to about a second on my 12 core XEON machine)

from string import ascii_lowercase, ascii_uppercase
from multiprocessing import Pool, freeze_support

NUM_CORES = 16
PATTERNS = [''.join([a,A]) for a,A in zip(ascii_lowercase, ascii_uppercase)] +  \
           [''.join([A,a]) for A,a in zip(ascii_uppercase, ascii_lowercase)]

def react(inp):
    while True:
        orig_inp_outer = inp
        for pattern in PATTERNS:
            orig_inp = inp
            while True:
                inp = inp.replace(pattern,"")
                if orig_inp == inp:
                    break
                else:
                    orig_inp = inp

        if orig_inp_outer == inp:
            break
        else:
            orig_inp_outer = inp
    return inp

def reactor(arg):
    p, inp = arg
    return len(react(inp.translate(None,p)))

def run():
    inp = open("input_5.txt").read()

    # Part 1
    print len(react(inp))

    # Part 2
    p2 = [(''.join([a,b]),inp) for a,b in zip(ascii_lowercase, ascii_uppercase)]
    results = Pool(NUM_CORES).map(reactor,p2)
    minimum = min(results)
    print minimum

if __name__ == '__main__':
    freeze_support()
    run()

2

u/c17r Dec 05 '18

You can also speed it up by re-using the result from part1 in part2.

1

u/CrazyPieGuy Dec 05 '18 edited Dec 05 '18

My Python 3 version. Takes 0.8 seconds.

I originally checked each set of adjacent units, and on a match, I would remove them by adding a string up to the pair to a string after the pair, but I ran into memory errors in puzzle 2. string.replace() as well as realizing I didn't have to start from scratch each letter solved that though.

I don't program in a professional capacity and don't interact with any other programmers, so I would love some feedback on how to clean up my solution if anyone has the time.

import string

f = open("R:\Python\Advent_Of_Code\Day_5\input.txt", "r")
for line in f:
    polymer = line

#Puzzle 1
last_len = 0
while len(polymer) != last_len:
    last_len = len(polymer)
    for j in range(len(string.ascii_lowercase)):
        polymer = polymer.replace(str(string.ascii_lowercase[j] + string.ascii_uppercase[j]), "")
        polymer = polymer.replace(str(string.ascii_uppercase[j] + string.ascii_lowercase[j]), "")
print(f"The original polymer was cleaned to a length of {len(polymer)} units.")

#Puzzle 2
unstablest_letter = ""
shortest_polymer = len(polymer)

for i in range(len(string.ascii_lowercase)):
    this_polymer = polymer

    #Removes chosen letter
    this_polymer = this_polymer.replace(string.ascii_lowercase[i], "")
    this_polymer = this_polymer.replace(string.ascii_uppercase[i], "")

    #Removes unstable pairs
    last_len = 0
    while len(this_polymer) != last_len:
        last_len = len(this_polymer)
        for j in range(len(string.ascii_lowercase)):
            this_polymer = this_polymer.replace(str(string.ascii_lowercase[j] + string.ascii_uppercase[j]), "")
            this_polymer = this_polymer.replace(str(string.ascii_uppercase[j] + string.ascii_lowercase[j]), "")

    if len(this_polymer) < shortest_polymer:
        shortest_polymer = len(this_polymer)
        unstablest_letter = string.ascii_uppercase[i]

print(f'The most unstable letter is {unstablest_letter}. Without it the polymer was reduced to {shortest_polymer} units.')

2

u/c17r Dec 05 '18

Your technique is like mine. I refer to it as solving this problem with a sledgehammer :) Here's mine for comparison:

from string import ascii_lowercase, ascii_uppercase

raw = contents(2018, 5, 1)[0]

def reduce(data):
    orig = None
    while orig != data:
        orig = data
        for one, two in zip(ascii_lowercase, ascii_uppercase):
            data = data.replace(one + two, '').replace(two + one, '')
    return data

print(len(raw))
part1 = reduce(raw)
print(len(part1))

low = None
for one, two in zip(ascii_lowercase, ascii_uppercase):
    attempt = part1.replace(one, '').replace(two, '')
    pass2 = reduce(attempt)
    if low is None or len(pass2) < low:
        low = len(pass2)
print(low)
→ More replies (1)

1

u/red_shifter Dec 05 '18

When working on a solution (Python 3) for part 1, I encountered a puzzling behavior of a recursive function. It gives the expected output, but the "print tests" I put inside the function to check if it is working properly are mystifying to me. Here is the code:

poly_input = 'dabAcCaCBAcCcaDA'

def check_poly(string):
    poly_output = string
    for i in range(len(string)-1):
        unit1 = string[i]
        unit2 = string[i+1]
        if unit1.lower() == unit2.lower():
            if (unit1.islower() and unit2.isupper()) or (unit1.isupper() and unit2.islower()):
                print('{}{}'.format(unit1, unit2))
                poly_output = string[:i]+string[i+2:]
                poly_output = check_poly(poly_output)
    print('RETURN')
    return poly_output

print(check_poly(poly_input))

It should print all the annihilating pairs it finds, print "RETURN" when it reaches the end of a function run and finally print the output polymer sequence. Here are the messages it produces:

cC
Aa
cC
RETURN
Cc
RETURN
RETURN
cC
Aa
RETURN
RETURN
Cc
Aa
RETURN
RETURN
RETURN
cC
cC
Aa
RETURN
RETURN
RETURN
Cc
cC
Aa
RETURN
RETURN
RETURN
RETURN
dabCBAcaDA

The first four lines are expected, but I cannot figure out what all the remaining pairs and "RETURNS" are doing there. I guess it has to be related to how recursion works in Python somehow.

2

u/c17r Dec 05 '18
    if unit1.lower() == unit2.lower():
        if (unit1.islower() and unit2.isupper()) or (unit1.isupper() and unit2.islower()):

could be simplified to if unit1.lower() == unit2.lower() and unit1 != unit2:

And your recursion is off because the actual loop of check_poly() is using string but updating poly_output, so even if the recursion has changed things, the parent loop doesn't know about so it continues down the original string still making/checking changes that it doesn't need to, hence the extra output.

I think you meant to do:

poly_input = 'dabAcCaCBAcCcaDA'

def check_poly(string):
    print('>', string)
    for i in range(len(string)-1):
        unit1, unit2 = string[i], string[i+1]
        if unit1.lower() == unit2.lower() and unit1 != unit2:
            return check_poly(string[:i]+string[i+2:])
    return string

print(check_poly(poly_input))

which gives an output of:

> dabAcCaCBAcCcaDA
> dabAaCBAcCcaDA
> dabCBAcCcaDA
> dabCBAcaDA
dabCBAcaDA
→ More replies (2)

1

u/gerikson Dec 05 '18

On the fifth day of AoC / My true love sent to me / Five golden puzzles, pearls without price.

This is a problem made for Perl! Total runtime ~1.6s on my low-end VPS.

https://github.com/gustafe/aoc2018/blob/master/d05-Alchemical-Reduction.pl

1

u/drakmaniso Dec 05 '18

Go (golang)

Part 1 and 2:

package main

import (
	"fmt"
	"log"
	"os"
)

func main() {
	input := read()
	fmt.Printf("Answer for part1: %d\n", len(part1(input)))
	u, l := part2(input)
	fmt.Printf("Answer for part2: unit %c -> length %d\n", u, l)
}

func part1(input []byte) []byte {
	in := append(make([]byte, 0, len(input)), input...)
	out := make([]byte, 0, len(input))

	for {
		i := 0
		for i < len(in) {
			if i < len(in)-1 && in[i] == opposite(in[i+1]) {
				i += 2
				continue
			}
			out = append(out, in[i])
			i++
		}
		if len(in) == len(out) {
			break
		}
		in, out = out, in[:0]
	}

	return out
}

func part2(input []byte) (unit byte, length int) {
	length = len(input)
	for u := byte('a'); u <= 'z'; u++ {
		in := strip(input, u)
		l := len(part1(in))
		if l < length {
			length = l
			unit = u
		}
	}
	return unit, length
}

func opposite(r byte) byte {
	if r < 'a' {
		return r + 'a' - 'A'
	}
	return r - 'a' + 'A'
}

func strip(input []byte, b byte) []byte {
	out := make([]byte, 0, len(input))
	for i := range input {
		if input[i] == b || input[i] == opposite(b) {
			continue
		}
		out = append(out, input[i])
	}
	return out
}

func read() (input []byte) {
	f, err := os.Open("input.txt")
	if err != nil {
		log.Fatalf("ERROR: open input: %v", err)
	}
	defer f.Close()
	n, err := fmt.Fscanf(f, "%s", &input)
	if n != 1 || err != nil {
		log.Printf("ERROR: scan input: %v", err)
	}
	return input
}

1

u/radarvan07 Dec 05 '18

Rust here. I was going to use a stack, but it turns out that the Vec that I read the input into has just enough free space to store it! No further allocations needed.

fn reduce(mut data: Vec<u8>) -> usize {
    let mut dptr = 0;
    for iptr in 0..data.len() {
        if dptr > 0 && (data[iptr].eq_ignore_ascii_case(&data[dptr - 1])) && data[iptr] != data[dptr - 1] {
            dptr -= 1;
        } else {
            data[dptr] = data[iptr];
            dptr += 1;
        }
    }

    dptr
 }

1

u/toastedstapler Dec 05 '18 edited Dec 05 '18

Python

runs a lot faster than my initial first version that called .replace 52 times per loop until no changes were made

went from 6.5s for part 2 down to just 0.142!

#!/usr/local/bin/python3

from string import ascii_lowercase, ascii_uppercase
import time
from functools import reduce

input_filename = "input/input_day5.txt"

def reduce_polarities(polymer):
    return reduce(lambda a, b: a[:-1] if a[-1] != b and a[-1].upper() == b.upper() else a + b, "#" + polymer)[1:]

def get_polymer():
    with open(input_filename) as f:
        contents = f.read().strip()
        return contents

def part1(polymer):
    return reduce_polarities(polymer)

def part2(polymer):
    shortest = len(polymer)
    for a1, a2 in zip(ascii_lowercase, ascii_uppercase):
        modified_polymer = polymer.replace(a1, '').replace(a2, '')
        modified_shortened = reduce_polarities(modified_polymer)
        if len(modified_shortened) < shortest:
            shortest = len(modified_shortened)
    return shortest

def main():
    start_setup = time.time()
    polymer = get_polymer()
    end_setup = time.time()

    start_part1 = time.time()
    reduced = part1(polymer)
    res_part1 = len(reduced)
    end_part1 = time.time()

    start_part2= time.time()
    res_part2 = part2(reduced)
    end_part2 = time.time()

    print(f"part 1: {res_part1}")
    print(f"part 2: {res_part2}")
    print(f"setup took {end_setup - start_setup} seconds")
    print(f"part 1 took {end_part1 - start_part1} seconds")
    print(f"part 2 took {end_part2 - start_part2} seconds")
    print(f"overall took {end_part2 - start_setup} seconds")

if __name__ == '__main__':
    main()

1

u/snurre Dec 05 '18

Kotlin:

class Day05 {
    private val data = File(this.javaClass.getResource("05.txt").path).readText().trim()
    private val units = ('a'..'z').let {
        val s = hashSetOf<String>()
        it.forEach { c ->
            s.add("$c${c.toUpperCase()}")
            s.add("${c.toUpperCase()}$c")
        }
        s
    }

    private fun react(s: String): String {
        val sb = StringBuilder()
        var i = -1
        while (++i < s.length - 1) {
            if (s.substring(i, i + 2) in units) i++ else sb.append(s[i])
            if (i == s.length - 2) sb.append(s[i] + 1)
        }
        return sb.toString()
    }

    private fun solve(s: String): String {
        var polymer = s
        while (polymer != { val p = react(polymer); polymer = p;p }()) {}
        return polymer
    }

    @Test
    fun part1() {
        println(solve(data).length)
    }

    @Test
    fun part2() {
        var shortest = data.length
        for (c in 'a'..'z') {
            val polymer = solve(data.replace(c.toString(), "", true))
            if (polymer.length < shortest) shortest = polymer.length
        }
        println(shortest)
    }
}

1

u/[deleted] Dec 05 '18

Go/Golang

The rest of my solutions: https://github.com/tardisman5197/aoc2018

If anyone has any suggestions for ways I can improve it is much appreciated.

Part 1

// part1 finds the length of the polymer after reactions have taken place
func part1(input string) int {
    output, _ := react(input, 0)
    return len(output)
}

Part 2

// part2 finds the shortest length of the polymer, after certain
// units have been removed
func part2(input string) int {
    lowestLength := math.MaxInt64
    for i := 0; i < 26; i++ {
        if strings.Contains(input, string(i+65)) || strings.Contains(input, string(i+95)) {
	    // Remove uppercase
	    currentString := strings.Replace(input, string(i+65), "", -1)
	    // Remove lowercase
	    currentString = strings.Replace(currentString, string(i+97), "", -1)
            
            // Carry out reaction
	    currentString, _ = react(currentString, 0)

            if len(currentString) < lowestLength {
	        lowestLength = len(currentString)
	    }
	}
    }
    return lowestLength
}

Other Stuff

// react simulates the reaction of a polymer and returns the stable polymer
func react(input string, currentIndex int) (string, int) {
    if math.Abs(float64(int(input[currentIndex])-int(input[currentIndex+1]))) == 32 {
        input = input[:currentIndex] + input[currentIndex+2:]

	if currentIndex != 0 {
            currentIndex--
	}
    } else {
	currentIndex++
    }

    if currentIndex >= len(input)-1 {
	return input, currentIndex
    }

    return react(input, currentIndex)
}

1

u/BalbinHS Dec 05 '18 edited Dec 05 '18

Elixir:

def part1(input) do
  input
  |> String.trim()
  |> String.graphemes()
  |> fully_react()
end

def fully_react(string_graphemes) do
  {length, _} =
    Enum.reduce(string_graphemes, {0, []}, fn
      letter, {length, [last_seen | rest]} ->
        cond do
          letter != last_seen and String.downcase(letter) == String.downcase(last_seen) ->
            {length - 1, rest}

          true ->
            {length + 1, [letter | [last_seen | rest]]}
        end

      letter, {length, []} ->
        {length + 1, [letter]}
    end)

  length
end

def part2(input) do
  input = String.trim(input)
  input_graphemes = String.graphemes(input)
  # to_check = MapSet.new(input_graphemes)
  to_check = for l <- ?a..?z, do: <<l::utf8>>

  Enum.reduce(to_check, :infinity, fn letter, acc ->
    input_graphemes
    |> Enum.filter(fn l -> String.downcase(l) != letter end)
    |> fully_react()
    |> min(acc)
  end)
end

1

u/rolandtritsch Dec 05 '18

ETA (Haskell on the JVM)

https://github.com/rolandtritsch/haskell-aoc-2018

General:

type Type = Char
data Polarity = Plus | Minus deriving (Show, Eq)
data Unit = Unit Type Polarity deriving (Show, Eq)

type Polymer = [Unit]

-- | read the input file
input :: String
input = head $ inputRaw "input/Day05input.txt" where

-- | read the input file
buildPolymer :: String -> Polymer
buildPolymer line = map buildPolymer' line where
  buildPolymer' c = Unit (toLower c) (p (isLower c)) where
    p True = Minus
    p False = Plus

-- | can these two Units react?
canReact :: Unit -> Unit -> Bool
canReact (Unit t p) (Unit t' p') = t == t' && p /= p'

-- | take a Polymer, find the first 2 Units that can react, react and
-- return the resulting Polymer.
react :: Polymer -> Polymer
react (u:[]) = [u]
react (u:u':[])
  | canReact u u' = []
  | otherwise = [u] ++ [u']
react (u:rest@(u':rest'))
  | canReact u u' = react rest'
  | otherwise = [u] ++ react rest
react p = error ("Unexpected pattern match: " ++ show p)

-- | react until there is nothing to react on.
reaction :: Polymer -> Polymer
reaction p
  | p == nextP = p
  | otherwise = reaction nextP
  where
    nextP = react p

Part1:

-- | solve the puzzle
solve :: String -> Int
solve p = (length . reaction) (buildPolymer p)

Part2:

-- | solve the puzzle
solve :: String -> Int
solve p = snd $ minimumBy (comparing snd) allReactions where
  allReactions = [(t, reactionLength t) | t <- ['a'..'z']] where
    reactionLength t = (length . reaction) (filter (\(Unit t' _) -> t /= t') p') where
      p' = buildPolymer p

1

u/__Abigail__ Dec 05 '18

Perl

Really easy exercise when using Perl and its string manipulation.

#!/opt/perl/bin/perl

use 5.026;

use strict;
use warnings;
no  warnings 'syntax';

use experimental 'signatures';

my $input = "input";
open my $fh, "<", $input or die "Failed to open $input: $!";
my $text = <$fh>;
$text =~ s/\n+//g;

#
# Repeatedly remove 'Aa' / 'aA' units.
#
sub react ($text) {
    state $pat = join "|" => map {"$_\u$_|\u$_$_"} 'a' .. 'z';
    1 while $text =~ s/$pat//g;
    $text;
}

say "Part 1: ", length react $text;

my $shortest = length $text;
#
# Foreach letter, remove it (either case), and perform the reaction.
# Remember the shortest result.
#
foreach my $unit ('a' .. 'z') {
    my $cleaned = $text =~ s/$unit//gir;
    my $length  = length react $cleaned;
    if ($length < $shortest) {
        $shortest = $length;
    }
}

say "Part 2: ", $shortest;

__END__

1

u/wzkx Dec 05 '18 edited Dec 05 '18

Rust, SweetRust =>

use std::io::prelude::*; // read_to_string

fn reduce( w: &Vec<u8> ) -> usize:
  let mut v = w.clone();
  let (mut i, mut n) = (0, v.len());
  loop:
    while i < n-1:
      if v[i]==v[i+1]+32 || v[i]+32==v[i+1]:
        v.remove(i+1);
        v.remove(i);
        n -= 2;
        if i>0 { i -= 1; }
        break;
      i += 1;
    if i == n-1:
      break;
  return n;

fn main():
  // read input into s
  let mut s = String::new();
  std::fs::File::open( "05.dat" ).unwrap().read_to_string( &mut s ).unwrap();
  // part 1
  let v: Vec<u8> = s.trim().chars().map( |c| c as u8 ).collect();
  let n = reduce( &v );
  println!( "{}", n );
  // part 2
  let mut m = v.len(); // minimal length
  for c in 'A' as u8 ..= 'Z' as u8:
    let mut u = v.clone();
    u.retain( |&x| x!=c && x!=c+32 );
    let n = reduce( &u );
    if n < m:
      m = n;
  println!( "{}", m );

P.S. Oh, changing reduce to go right to left will increase the speed - 0.64s to 0.15s.

my aoc2018

1

u/knotdjb Dec 05 '18 edited Dec 05 '18

Golang:

package main

import (
	"fmt"
	"io/ioutil"
	"os"
)

func react(p []byte, skip byte) []byte {
	newp := []byte{'.'}
	for _, v := range p {
		if (v | ' ') == (skip | ' ') {
			continue
		}

		if newp[len(newp)-1] == (v ^ ' ') {
			newp = newp[:len(newp)-1]
			continue
		}

		newp = append(newp, v)
	}

	return newp[1:]
}

func main() {
	f, err := os.Open("input.txt")
	if err != nil {
		panic("Unable to open input.txt")
	}

	p, err := ioutil.ReadAll(f)
	if err != nil {
		panic(fmt.Errorf("ReadAll: %v", err))
	}

	// trim '\n'
	p = p[:len(p)-1]

	// part 1
	fmt.Println(len(react(p, '#')))

	// part 2
	Σ := map[byte]struct{}{}
	for _, c := range p {
		// lowercase c
		c = c | ' '
		Σ[c] = struct{}{}
	}

	best := len(p)
	for k, _ := range Σ {
		newp := react(p, k)
		if len(newp) < best {
			best = len(newp)
		}
	}

	fmt.Println(best)
}

1

u/tobiasvl Dec 05 '18 edited Dec 05 '18

[Card] strings

(you know, since it rhymes with "rings"…)

Python 2:

from string import ascii_lowercase as lower, ascii_uppercase as upper

with open('input.txt') as f:
    polymer = f.read().strip('\n')

def react(polymer):
    result = ''
    for c in polymer:
        c2 = result[-1:]
        if c == c2.swapcase():                                                                                                                                                                                                         
            result = result[:-1]
        else:
            result += c
    return result

collapsed = react(polymer)
print len(collapsed)
print min(map(len, [react(collapsed.replace(l[0], '').replace(l[1], '')) for l in zip(lower, upper)]))

Didn't make the leaderboard, but I immediately thought of the stack solution since I studied computational linguistics and this is a classic context-free language that begs to be parsed by a pushdown automaton. I used an array as a stack at first though, but Python's string operations are cheap so that simplifies things (I don't need a special case for the empty stack, for example).

1

u/skarlso Dec 05 '18

Go (Golang) solution. Short and sweet:

package main

import (
	"fmt"
	"io/ioutil"
	"os"
	"unicode"
)

func main() {
	filename := os.Args[1]
	content, _ := ioutil.ReadFile(filename)
	runes := []rune(string(content))
	for i := 0; i < len(runes)-1; i++ {
		curr := runes[i]
		next := runes[i+1]
		if curr != next && (unicode.ToUpper(curr) == next || unicode.ToLower(curr) == next) {
			runes = append(runes[:i], runes[i+2:]...)
			if i > 0 {
				i -= 2
			} else {
				i--
			}
		}
	}
	fmt.Println(len(runes))
}

1

u/chrispsn_ok Dec 05 '18 edited Dec 05 '18

JavaScript:

// Setup
function compress(str) {
    let o = str;
    for (let i = 0; i < o.length-1; i++) {
        const [a, b] = o.slice(i, i+2);
        if ((a.toLowerCase() === b.toLowerCase()) && (a !== b)) {
            o = o.replace(RegExp(a+b, "g"), "");
            i = Math.max(-1, i-2);
        }
    }
    return o;
}

// Part 1
console.log("Answer 1:", compress(input).length);

// Part 2
let shortest = input.length;
for (let c of "ABCDEFGHIJKLMNOPQRSTUVWXYZ") {
    let output = compress(input.replace(RegExp(c, "ig"), ""));
    if (output.length < shortest) shortest = output.length;
}
console.log("Answer 2:", shortest);

1

u/21_cribbage Dec 05 '18

Python 3, using a stack and just ignoring the removed chars for star2 (instead of replacing them in the string).

import sys
import re
from string import ascii_lowercase

def annihilates(first, second):
    # Does this pair of chars annihilate with eachother?
    if first.lower() == second.lower():
        # Same base char
        if (first.isupper() and second.islower()) or \
           (first.islower() and second.isupper()):
           # Polarised
           return True
    return False

def react_polymer(polymer, ignored_chars=''):
    stack = []
    for char in polymer:
        if char in ignored_chars:
            # Star2: We're acting as if these don't exist
            continue
        if len(stack) == 0:
            stack.append(char)
        elif annihilates(stack[-1], char):
            stack.pop()
        else:
            stack.append(char)
    return stack

polymer = sys.stdin.readline()

 # Star 1
stack = react_polymer(polymer)
print("Star1: Polymer of length {} reacts to become length {}".format(len(polymer), len(stack)))

# Star 2
min_ = len(stack)
for char in ascii_lowercase:
    length = len(react_polymer(polymer, ignored_chars=char+char.upper()))
    if length < min_:
        min_ = length
        min_char = char

print("Star2: After removing pair {}, the polymer reacts to become length {}".format(min_char + min_char.upper(), min_))

1

u/JakDrako Dec 05 '18 edited Dec 05 '18

Vb.Net in LINQPad

Used the fact that (UPPERCASE xor lowercase) = 32 to match the letters. Felt that the second part was a bit slow, so I run it in parallel.

Sequential version did both parts in ~1.3 secs, the parallel one does both in ~425ms.

Sub Main
	
	Dim input = GetDay(5)

	Dim letters = Enumerable.Range(-1, 27).ToArray()
	Dim partitions = Partitioner.Create(0, letters.Length, (letters.Length \ Environment.ProcessorCount) + 1)
	Dim lengths() = New Integer(letters.Length) {}
	Parallel.ForEach(partitions, Sub(range, loopState)
									 For i = range.Item1 To range.Item2
										 lengths(i) = React(input, i).Length
									 Next
								 End Sub)
	lengths.max.Dump("Part 1")
	lengths.min.Dump("Part 2")

End Sub

Function React(polymer As String, Optional remove As Integer = -1) As String

	If remove > -1 Then polymer = polymer.Replace(Chr(Asc("A") + remove), "") _
										 .Replace(Chr(asc("a") + remove), "")

	Dim lst = polymer.ToCharArray.ToList

	Dim ptr = 0
	Do
		If ptr < lst.Count - 1 Then
			If (asc(lst(ptr)) Xor asc(lst(ptr + 1))) = 32 Then
				lst.RemoveRange(ptr, 2)
				If ptr > 0 Then ptr -= 1
			Else
				ptr += 1
			End If
		End If
	Loop Until ptr >= lst.Count - 1

	Return String.Concat(lst)

End Function

EDIT Oops, 1st version of the code wasn't using the partitionner correctly... runs in about ~340ms too.

EDIT 2 Using a stack is a much better idea (not mine, unfortunately...) Replacing the "React" function with this one:

Function React(polymer As String, Optional remove As Integer = -1) As String

	Dim ignore = If(remove > -1, {Chr(Asc("A") + remove), Chr(Asc("a") + remove)}, {})

	Dim stk = New Stack(Of Char)
	For Each c In polymer
		If Not ignore.Contains(c) Then
			If stk.Count = 0 Then
				stk.Push(c)
			ElseIf (asc(stk.First) Xor asc(c)) = 32 Then
				stk.Pop
			Else
				stk.Push(c)
			End If
		End If
	Next

	Return String.Concat(stk)

End Function

Brings the runtime for both part down to ~45ms.

1

u/HokieGeek Dec 05 '18

Pretty happy with my solutions in Rust today

use std::iter::FromIterator;

fn super_compressed_polymer(uncompressed: &String) -> String {
    let mut units = Vec::from_iter(uncompressed.chars()
                                   .map(|c| (c.to_lowercase().to_string(),
                                             c.to_uppercase().to_string())));
    units.sort();
    units.dedup();
    units.iter()
        .map(|c| compressed_polymer(&uncompressed.replace(&c.0, "").replace(&c.1, "")))
        .min_by_key(|c| c.len())
        .expect("*shrug*")
}

fn compressed_polymer(uncompressed: &String) -> String {
    let are_destroyed = |a: &char, b: char| a.eq_ignore_ascii_case(&b) && *a != b;

    uncompressed.chars()
        .fold(Vec::new(), |mut compressed, u| {
            if are_destroyed(compressed.last().unwrap_or(&' '), u) {
                compressed.pop();
            } else {
                compressed.push(u);
            }
            compressed
        })
        .iter()
        .collect()
}

1

u/semir321 Dec 05 '18

MATLAB ~2.4 seconds

A = cell2mat(importdata('input5.txt'));
alphabet = ['ABCDEFGHIJKLMNOPQRSTUVWXYZ' ;'abcdefghijklmnopqrstuvwxyz'];
A = react(A,alphabet);
length(A)   %part1
for ii=1:26
    L1 = alphabet(1,ii);
    L2 = alphabet(2,ii);
    B = strrep(strrep(A,L1,''),L2,'');
    C(ii) = length(react(B,alphabet));
end
min(C)  %part2

function A = react(A,alphabet)
l=0;
while l~=length(A)
    l = length(A);
    for ii=1:26
        L1 = alphabet(1,ii);
        L2 = alphabet(2,ii);
        A = strrep(strrep(A,strcat(L2,L1),''),strcat(L1,L2),'');
    end
end
end

1

u/jgoewert Dec 05 '18 edited Jun 28 '23

Ok Then -- mass edited with redact.dev

1

u/meepys Dec 05 '18

Kotlin Day 5 (Bitbucket)[https://bitbucket.org/meepy/adventofcode2018/src/master/src/Day5.kt]

This one was pretty easy. Could probably make a very short solution that would be less readable

class Day5(rawInput: List<String>) : Day(rawInput) {

    private fun solvePart1(input: String): Int {
        var currPolymer = input
        val nextPolymer = StringBuilder()

        while (currPolymer.length >= 2) {
            var i = 0
            while (i < currPolymer.length - 1) {
                if (currPolymer[i] != currPolymer[i + 1] &&
                    currPolymer[i].toLowerCase() ==
                    currPolymer[i + 1].toLowerCase()
                ) {
                    i += 2
                } else {
                    nextPolymer.append(currPolymer[i])
                    i++
                }
            }
            if (i == currPolymer.length - 1)
                nextPolymer.append(currPolymer[i])


            if (nextPolymer.length != currPolymer.length) {
                currPolymer = nextPolymer.toString()
                nextPolymer.clear()
            } else
                break
        }
        return currPolymer.length
    }

    override fun part1() {
        println("part1: ${solvePart1(rawInput.first())}")
    }

    override fun part2() {
        val lengths = mutableListOf<Int>()
        for (letter in 'a'..'z') {
            val filtered = rawInput.first().filter { it.toLowerCase() != letter }
            lengths.add(solvePart1(filtered))
        }
        println("part2: ${lengths.min()}")
    }
}

1

u/emagdnim2100 Dec 05 '18

Python3, 300ms runtime for parts 1 + 2. I believe this would throw an exception if the very last pair reacted, but mine didn't, and that would be easy to handle in any case.

input = list(open('./5_input.txt', 'r').read().rstrip('\n'))

def detect_reaction(a, b):
  if abs(ord(a) - ord(b)) == 32:
    return True

def process_polymer(p):
  polymer = p[:]
  for i in reversed(range(0, len(polymer) - 1)):
    if detect_reaction(polymer[i], polymer[i+1]):
      del polymer[i:i+2]
  return polymer

initial = process_polymer(input)

for letter in range(ord('A'), ord('Z')+1):
  polymer = initial[:]
  for j in reversed(range(0, len(polymer) - 1)):
    char = ord(polymer[j].upper())
    if char == letter:
      del polymer[j]
  result = process_polymer(polymer)
  print(chr(letter), len(result))

1

u/philophilo Dec 05 '18

Swift Solution. One function for both parts. Just walk the array and:

  1. Eliminate units that we're skipping for part 2.

  2. Eliminate units with opposite polarity (infix operator >-<) and move back one space.

  3. Move forward.

Not the most efficient, but I like it:

import Foundation
import LineReader

infix operator >-<

enum Unit {
    case negative(String)
    case positive(String)

    var type: String {
        switch self {
        case .negative(let x):
            return x
        case .positive(let x):
            return x
        }
    }
    
    static func from(_ value: Character) -> Unit {
        return from(String(value))
    }
    
    static func from(_ value: String) -> Unit {
        let lowerCased = value.lowercased()
        
        if value == lowerCased {
            return .negative(lowerCased)
        } else {
            return .positive(lowerCased)
        }
    }
    
    static func >-< (lhs: Unit, rhs: Unit) -> Bool {
        switch (lhs, rhs) {
        case (.negative(let x), .positive(let y)):
            return x == y
        case (.positive(let x), .negative(let y)):
            return x == y
        default:
            return false
        }
    }

}

extension Unit: CustomStringConvertible {
    var description: String {
        switch self {
        case .negative(let x):
            return x
        case .positive(let x):
            return x.uppercased() 
        } 
    }
}

struct Chain { let units: \[Unit\]

    init(value: String) {
        units = value.map(Unit.from)
    }
    
    func react(skipping: String = "") -> String {
        var units = self.units
        var head = 0
        
        while head < units.count - 1 {
            let one = units[head + 0]
            let two = units[head + 1]
            
            if two.type == skipping {
                units.remove(at: head + 1)
            } else if one.type == skipping {
                units.remove(at: head)
            } else if one >-< two {
                units.remove(at: head)
                units.remove(at: head)
                
                head -= 1
                
                if head < 0 {
                    head = 0
                }
            } else {
                head += 1
            }
        }
        
        return units.map { $0.description }.joined()
    }
}

// Get the sequence let stdin = FileHandle.standardInput let reader = LineReader(handle: stdin)
guard let sequenceString = reader.readLine() else { fatalError("Could not read the sequence line") }

// Part 1, just react let chain = Chain(value: sequenceString) let part1Result = chain.react()
print("Part 1: (part1Result) ((part1Result.count))")

// Part 2, skip a letter sequence var bestLetter = "" var bestLetterCount = Int.max
print("\\nPart 2:") for l in "abcdefghijklmnopqrstuvwxyz" { let letter = String(l)

    let result = chain.react(skipping: String(letter))
    print("- \(letter) -> \(result.count)")
    
    if result.count < bestLetterCount {
        bestLetter = letter
        bestLetterCount = result.count
    }

}

print("Best: (bestLetter) -> (bestLetterCount)")

1

u/minichado Dec 05 '18 edited Dec 05 '18

Python 3

I am freakishly excited that I got this done in minimal time today! mostly because yesterday kicked my ass..

I added a timer to my code and removed an unnecessary array for my commit, it runs in ~3.2s (neither of those changes are shown here)

import numpy as np
from datetime import datetime as dt

filename='aoc 2018 d5 input.txt'

for line in open(filename):
	code=line

limit =len(code)
code2=code
i=0
count=0
while i < (limit-count):
	if code[i].casefold()==code[i+1].casefold() and ((code[i].isupper() and code [i+1].islower()) or (code[i+1].isupper() and code [i].islower())):
		code = code[:i]+code[i+2:]
		i-=2
		count=limit-len(code)
	i+=1
	if i==-1:
		i+=1
	answer1=len(code)
	count=limit-len(code)+1
	
print ('The deconstructed length of the polymer is ', answer1)
#~~~~~~~~~ part 2
alphabet='abcdefghijklmnopqrstuvwxyz'
lenalph=len(alphabet)

answer2array=np.array((26,2),dtype=object)
j=0
answer2=50000
answer2b=0
for j in range(lenalph):
	i=0
	code=code2
	code=code.replace(alphabet[j],"")
	code=code.replace(alphabet[j].capitalize(),"")
	while i < (limit-count):
		if code[i].casefold()==code[i+1].casefold() and ((code[i].isupper() and code [i+1].islower()) or (code[i+1].isupper() and code [i].islower())):
			code = code[:i]+code[i+2:]
			i-=2
			count=limit-len(code)
		i+=1
		if i==-1:
			i+=1
		answer2b=len(code)
		count=limit-len(code)+1
	if answer2b < answer2:
		answer2 = answer2b
	
print("The min length without bad apple letter is", answer2)

1

u/chicagocode Dec 05 '18

Kotlin - [Blog/Commentary] | [GitHub Repo]

Fold to the rescue!

class Day05(private val input: String) {

    fun solvePart1(): Int =
        input.react().length

    fun solvePart2(): Int =
        ('A'..'Z')
            .map { input.react(it).length }
            .min()
            ?: throw IllegalStateException()

    private fun String.react(ignoring: Char? = null): String =
        this.fold(mutableListOf<Char>()) { done, char ->
            when {
                ignoring != null && char.equals(ignoring, true) -> Unit
                done.firstOrNull() matches char -> done.removeAt(0)
                else -> done.add(0, char)
            }
            done
        }
            .reversed()
            .joinToString(separator = "")

    private infix fun Char?.matches(other: Char): Boolean =
        when {
            this == null -> false
            this.toUpperCase() != other.toUpperCase() -> false
            else -> this != other
        }

}

1

u/AbdussamiT Dec 05 '18 edited Dec 05 '18

Not quite a fun day at work today, struggled with the if conditions at first but then discovered ord() and chr() which helped, in C++ it would've been easier for me but well here goes Part-I (Python 3)

polymer = open('input.txt', 'r').read().split('\n')[0]
keepgoing = True

print("start: \"%s\"" % polymer)

while keepgoing:
    keepgoing = False
    for i in range(len(polymer)):
        if i < len(polymer) - 1:
            # aA or Aa
            if ord(polymer[i]) - ord(polymer[i + 1]) == 32 or ord(polymer[i + 1]) - ord(polymer[i]) == 32:
                keepgoing = True
                polymer = polymer[:i] + polymer[i + 1:]
                polymer = polymer[:i] + polymer[i + 1:]

print("end \"%s\"" % polymer)
print("length %d" % len(polymer))

Ah! Also learnt about slicing, had to remove a character at a certain index in the polymer.

1

u/mylivingeulogy Dec 05 '18

Here is my Java code. I had a tougher time with yesterdays getting it to work, i did get the wrong answer a few times but in the end I figured it out.

import java.io.File;
import java.util.Scanner;

public class day5Part1
{
	public static void main(String[] args)
		throws java.io.FileNotFoundException
	{
		Scanner input = new Scanner(new File("data.txt"));
		String s;
		String temp = null;
		String removed = null;
		Boolean looping = true;
		int charRem = 999999999;
		String best = null;

		s = input.nextLine();

		for (char alphabet = 'A'; alphabet <= 'Z'; alphabet++)
		{
		    temp = s;
		    removed = Character.toString(alphabet);
			temp = temp.replaceAll(removed,"");
			removed = Character.toString(Character.toLowerCase(alphabet));
			temp = temp.replaceAll(removed,"");
			System.out.println(alphabet + " " + Character.toLowerCase(alphabet) +  " removed size before reacting: " + temp.length());

			do
			{
				looping = false;
				for(int i = 0; i < temp.length() - 1; i++)
				{
					if(Character.isLowerCase(temp.charAt(i)) && temp.substring(i,i+1).toUpperCase().equals(temp.substring(i+1, i+2)))
					{
						removed = temp.substring(i, i+2);
						looping = true;
						if(removed.substring(0,1).equals(removed.substring(1,1)))
						{
							System.out.println("ERROR ***********************");
							break;
						}
						temp = temp.replace(removed,"");
					}

					else if(Character.isUpperCase(temp.charAt(i)) && temp.substring(i, i+1).toLowerCase().equals(temp.substring(i+1, i+2)))
					{
						removed = temp.substring(i, i+2);
						looping = true;
						if(removed.substring(0,1).equals(removed.substring(1,1)))
						{
							System.out.println("ERROR ***********************");
							break;
						}
						temp = temp.replace(removed,"");
					}
				}
			}while(looping);

			System.out.println(alphabet + " " + Character.toLowerCase(alphabet) +  " removed size after reacting: " + temp.length() + "\n");

			if(temp.length() < charRem)
			{
				charRem = temp.length();
				best = removed;
			}
		}

		System.out.println("best is " + best + " with a size of: " + charRem);
	}
}

1

u/itsjeremeh Dec 05 '18

JavaScript (Node) - This one is terribly inefficient (taking 14 seconds to do part 1 and 2) but it works

const doFilter = (chars) => {
	let resp = chars.map((char, index) => {
		if (char === null) {
			return null;
		}
		
		if (chars[index + 1] && char !== chars[index + 1] && char.toLowerCase() === chars[index + 1].toLowerCase()) {
			chars[index + 1] = null;
			return null;
		}
		
		return char;
	});
	
	if (resp.indexOf(null) !== -1) {
		return doFilter(resp.filter(char => char !== null))
	}
	
	return resp;
}


const findShortest = (chars) => {
	const alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');
	let smallest = chars.length;
	
	alphabet.forEach(char => {
		let newChars = chars.filter(c => c.toLowerCase() !== char);
		let filteredResult = doFilter(newChars);
		
		smallest = Math.min(smallest, filteredResult.length);
	})

	return smallest;

}

console.log('part one', doFilter(input.split('')).length);
console.log('part two', findShortest(input.split('')));

1

u/gamed7 Dec 05 '18

Kind of late to the party but I'm really happy how clean and simple my code ended up.

Here's my solution in:

HASKELL

import Data.Char (ord, chr, toUpper)
import Data.Set (Set)
import qualified Data.Set as S

{-
    Advent of code - Day 5: Alchemical Reduction
    1st Part:
        How many units remain after fully reacting the polymer you scanned?
-}

cancel :: Char -> String -> String
cancel x [] = [x]
cancel x (y:ys) | ord x == ord y + 32 || ord x == ord y - 32 = ys
                | otherwise = x:y:ys

part1 :: String -> Int
part1 = length . foldr cancel ""

main1 = do
        input <- readFile "input.txt"
        putStrLn . show . subtract 1 . part1 $ input -- subtract 1: Because of \n

{-
    2nd Part:
        What is the length of the shortest polymer you can produce by removing all units of exactly one type and fully reacting the result?
-}

constructSet :: String -> Set Char
constructSet = foldr (\c s -> S.insert (toUpper c) s) S.empty

checkLength :: Char -> String -> Int
checkLength c = part1 . filter (\x -> toUpper x /= c && x /= '\n')

part2 :: String -> Set Char -> Int
part2 s = minimum . map (`checkLength` s) . S.toList

main2 = do
        input <- readFile "input.txt"
        putStrLn . show . part2 input $ constructSet input

1

u/aschafu Dec 05 '18

Hm, you all have super elegant solutions that are apparently the correct ones, but I'm still wondering why mine is wrong. It produces the shown result on the brief example, but a different one on the input I was given. -- The difference seems to be that I see my polymer as an entity where a number of reactions occur in parallel in subsequent timesteps (probably a misunderstanding due to the fact that I'm a chemist... ;-) ). Therefore, I first work out all reacting momomer pairs in the molecule I'm given, let them react and then go to the next iteration. -- My question is: 1. can that be the reason for the difference I see and 2. does the problem statement really explain that the solutions I see here where the reactions seem to occur from one end of the molecule to the other are the correct ones?

→ More replies (2)

1

u/saik0 Dec 05 '18

Rust. Pretty much a naiive interpretation of the problem. For part 2 i just remove the characters and react it 26 times.

fn react(polymer: String) -> String {
    let mut polymer = polymer.into_bytes();
    let mut left = 0;

    while left + 1 < polymer.len() {
        if polymer.has_reaction(left, left+1) {
            polymer.remove(left);
            polymer.remove(left);
            left = left.saturating_sub(1);
        } else {
            left += 1;
        }
    }

    String::from_utf8(polymer).expect("output polymer was not valid utf8")
}

// Helpers
// =======

fn diff_abs(a: u8, b: u8) -> u8 {
    if a > b {
        a - b
    } else {
        b - a
    }
}

const REACTION_DIFFERENCE: u8 = 'a' as u8 - 'A' as u8;

trait  HasReaction {
    fn has_reaction(&self, left: usize, right: usize) -> bool;
}

impl HasReaction for [u8] {
    fn has_reaction(&self, left: usize, right: usize) -> bool {
        diff_abs(self[left] as u8, self[right] as u8) == REACTION_DIFFERENCE
    }
}

1

u/Aehmlo Dec 05 '18 edited Dec 05 '18

[Card] chars

I loved day 5! Rust solution:

//! Day five (Alchemical Reduction)

/// Returns whether a pair of monomers is reactive (will annihilate).
pub fn pair_reacts(one: &char, other: &char) -> bool {
    one != other && one.to_ascii_lowercase() == other.to_ascii_lowercase()
}

/// Simulates the polymerization reaction.
pub fn polymerize(structure: &str) -> String {
    let mut polymer = String::new();
    for c in structure.chars() {
        if let Some(l) = polymer.chars().last() {
            if pair_reacts(&l, &c) {
                polymer.pop();
            } else {
                polymer.push(c);
            }
        } else {
            polymer.push(c);
        }
    }
    polymer
}

/// Returns all primary structures resulting from removing all monomers of one type.
pub fn mutate(reference: &str) -> Vec<String> {
    let mut structures = Vec::new();
    for i in 0..26 {
        let c = (97u8 + i) as char;
        let structure = reference
            .chars()
            .filter(|e| e.to_ascii_lowercase() != c)
            .collect();
        structures.push(structure);
    }
    structures
}

/// Try mutating the input, seeing what gives the shortest resultant polymer.
pub fn shortest_len(reference: &str) -> usize {
    let others = mutate(&reference);
    let mut shortest = reference.len();
    for p in others {
        let p = polymerize(&p);
        let len = p.len();
        if len < shortest {
            shortest = len;
        }
    }
    shortest
}

/// Solve the puzzle using the input in `puzzles/5.txt`.
///
/// Solutions are printed to stdout.
pub fn solve() {
    let input = include_str!("../puzzles/5.txt");
    let input = input.lines().next().expect("No lines in input file.");
    let polymer = polymerize(&input);
    println!(
        "Day five solutions: {}, {}",
        polymer.len(),
        shortest_len(&input)
    );
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn polymerization() {
        assert_eq!(polymerize("aA"), "");
        assert_eq!(polymerize("abBA"), "");
        assert_eq!(polymerize("abAB"), "abAB");
        assert_eq!(polymerize("aabAAB"), "aabAAB");
        assert_eq!(polymerize("dabAcCaCBAcCcaDA"), "dabCBAcaDA");
    }
    #[test]
    fn optimization() {
        assert_eq!(shortest_len("dabAcCaCBAcCcaDA"), 4);
    }
}

Edit: For the curious, here's my solution repo on GitHub.

→ More replies (1)

1

u/NeilNjae Dec 05 '18

Haskell, on Github. Over-complicated, but I wanted to have a play with using unfold to do the reductions (I unfold the starting polymer into the list of reductions, then take the last of the list for the final product).

import Data.List
import Data.Char (toLower)

main :: IO ()
main = do 
        text <- readFile "data/advent05.txt"
        print $ part1 text
        print $ part2 text

part1 = reactedLength

part2 polymer = minimum finalLengths
    where finalLengths = map (\u -> reactedLength $ removeUnit polymer u) units
          units = unitsPresent polymer


react :: String -> Char -> Char -> String -> (String, String)
react prefix a b suffix = 
    if willReact a b
    then (prefix, suffix)
    else ((b:a:prefix), suffix)

willReact :: Char -> Char -> Bool
willReact a b = (a /= b) && (toLower a == toLower b)


reactHere :: (String, String) -> Maybe ((String, String), (String, String))
reactHere (prefix, suffix) = 
    if canContinue prefix suffix
    then Just ((prefix'', suffix''), (prefix'', suffix''))
    else Nothing
    where (prefix', a, b, suffix') = reactionSite prefix suffix
          (prefix'', suffix'') = react prefix' a b suffix'


canContinue (_:_) (_:_) = True
canContinue [] (_:_:_) = True
canContinue _ _ = False

reactionSite (a:prefix) (b:suffix) = (prefix, a, b, suffix)
reactionSite [] (a:b:suffix) = ([], a, b, suffix)


reactedLength polymer = length prefix + length suffix
    where (prefix, suffix) = last $ unfoldr reactHere ("", polymer)


unitsPresent = nub . sort . map toLower 

removeUnit polymer unit = filter (\c -> toLower c /= unit ) polymer 

1

u/dr0buds Dec 05 '18

Python

with open('input.txt', 'r') as data:
      # part 1
      long_string = data.read().strip()
      long_string_copy = long_string
      i = 0
      while i < len(long_string) - 1:
          if abs(ord(long_string[i]) - ord(long_string[i + 1])) == 32: # lowercase and uppercase differ by 32
              long_string = long_string[:i] + long_string[i+2:]
              i = max(0, i - 1)
          else:
              i += 1
      min_len = len(long_string)
      print(min_len)
  
      # part 2
      for i in range(ord('A'), ord('Z')):
          test_string = long_string_copy.replace(chr(i), '')
          test_string = test_string.replace(chr(i + 32), '')
          j = 0
          while j < len(test_string) - 1:
              if abs(ord(test_string[j]) - ord(test_string[j + 1])) == 32:
                  test_string = test_string[:j] + test_string[j + 2:]
                  j = max(0, j - 1)
              else:
                  j += 1
          min_len = min(min_len, len(test_string))
      print(min_len)

1

u/tclent Dec 05 '18 edited Dec 06 '18

My solution in Rust (full context on Github):

use std::collections::HashSet;

// Spent hours not realizing the input must be trimmed or the \n at the end will add 1 to the result
pub fn parse_input(input: &str) -> &str {
  input.trim()
}

pub fn find_part_one_solution(polymer: &str) -> usize {
  let final_polymer = fully_react_polymer(polymer);
  final_polymer.len()
}

pub fn find_part_two_solution(polymer: &str) -> usize {
  let polymer_units: HashSet<char> = polymer.chars().map(|c| c.to_ascii_lowercase()).collect();
  polymer_units
    .iter()
    .map(|&removed_unit| {
      fully_react_polymer(&polymer.replace(|c: char| c.to_ascii_lowercase() == removed_unit, ""))
        .len()
    })
    .min()
    .expect("No solution found")
}

fn fully_react_polymer(polymer: &str) -> String {
  let mut current_polymer = polymer.to_owned();
  let mut previous_polymer: Option<String> = None;
  while previous_polymer.is_none() || *previous_polymer.unwrap() != current_polymer {
    previous_polymer = Some(current_polymer.clone());
    current_polymer = current_polymer
      .chars()
      .fold(String::new(), |mut result, unit| {
        match result.chars().last() {
          Some(previous_unit) if is_reacting_pair(unit, previous_unit) => {
            result.pop();
          }
          _ => {
            result.push(unit);
          }
        };
        result
      });
  }
  current_polymer
}

fn is_reacting_pair(a: char, b: char) -> bool {
  a != b && a.to_ascii_lowercase() == b.to_ascii_lowercase()
}

// My original working solution before improving with fold and looking back instead of peeking
#[allow(dead_code)]
fn find_part_one_solution_peek(units: &str) -> usize {
  let mut current_units = units.to_owned();
  let mut previous_units: Option<String> = None;
  while previous_units.is_none() || *previous_units.unwrap() != current_units {
    previous_units = Some(current_units.clone());
    let mut result = String::new();
    {
      let mut iter = current_units.chars().peekable();
      while let Some(c) = iter.next() {
        if iter.peek().is_some() && is_reacting_pair(c, *iter.peek().unwrap()) {
          iter.next(); // do nothing with c and skip next c
        } else {
          result.push(c);
        }
      }
    }
    current_units = result;
  }
  current_units.len()
}

#[cfg(test)]
mod tests {
  use super::*;

  #[test]
  fn it_removes_newline() {
    assert_eq!(parse_input("aA\n").len(), 2);
  }

  #[test]
  fn it_finds_correct_part_one_solution() {
    let sample_input = "dabAcCaCBAcCcaDA";
    assert_eq!(find_part_one_solution(sample_input), 10);
  }

  #[test]
  fn it_finds_correct_part_two_solution() {
    let sample_input = "dabAcCaCBAcCcaDA";
    assert_eq!(find_part_two_solution(sample_input), 4);
  }
}

1

u/dvirus1023 Dec 05 '18

c#

public static class Day5

{

public static void Run()

{

var input = File.ReadAllLines(@"../../../../Input/Day5.txt");

var line = input.First();

var newLine = Condense(line);

Console.WriteLine($"Answer 1 : {newLine.Length}");

var alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();

var counts = new List<(char Letter, int Count)>();

foreach(var a in alpha)

{

var condensed = Condense(line.Replace(a.ToString(), "", StringComparison.OrdinalIgnoreCase));

counts.Add((a, condensed.Length));

}

Console.WriteLine($"Answer 2 : {counts.OrderBy(x => x.Count).First().Count}");

}

static string Condense(string line)

{

for (var i = 0; i < line.Length - 1; i++)

{

if (line[i] != line[i + 1] && char.ToUpper(line[i]) == char.ToUpper(line[i + 1]))

{

line = line.Remove(i, 2);

i = i - 2;

if (i <= 0) i = -1;

}

}

return line;

}

}

1

u/tslater2006 Dec 05 '18 edited Dec 05 '18

Day 5 in PeopleCode

import TS_AOC2018:Day;

class Day5 extends TS_AOC2018:Day
   method Day5();
   
   property string Description get;
   method SolvePart1() Returns string;
   method SolvePart2() Returns string;
   
private
   method ParseInput();
   method ReactChain(&charList As array of number, &omitLetter As number) Returns array of number;
   method IsLower(&s As number) Returns boolean;
   method GetLetter(&s As number) Returns integer;
   
   instance array of number &chars;
   
end-class;

method Day5
   %Super = create TS_AOC2018:Day("TS_AOC_DAY5_INPUT");
   
   %This.ParseInput();
   
end-method;

method ParseInput
   Local integer &x;
   /* Convert the input string into an array of characters */
   Local array of string &charList = Split(%This.Lines [1], "");
   
   /* Create a number array the same size as the character count */
   &chars = CreateArrayRept(0, &charList.Len);
   
   /* Convert the characters to their ascii code */
   For &x = 1 To &charList.Len
      &chars [&x] = Code(&charList [&x]);
   End-For;
   
end-method;

method ReactChain
   /+ &charList as Array of Number, +/
   /+ &omitLetter as Number +/
   /+ Returns Array of Number +/
   /* Create empty array to hold the resulting chain */ 
   Local array of number &result = CreateArrayRept(0, 0);
   Local integer &x;

   /* process each character */
   For &x = 1 To &charList.Len
      /* This is to support Part2 where we want to ignore entire class of letters */
      If (%This.GetLetter(&charList [&x]) = %This.GetLetter(&omitLetter)) Then
         Continue;
      End-If;

      /* If we have a previous value to compare against */
      If (&result.Len > 0) Then
         /* If they are the same letter, ignoring case */
         If (%This.GetLetter(&charList [&x]) = %This.GetLetter(&result [&result.Len])) Then
            /* If they are different cases */
            If (%This.IsLower(&charList [&x]) <> %This.IsLower(&result [&result.Len])) Then
               /* Ignore this new letter, and remove the previous from the list */
               &result.Pop();
            Else
               /* No reason to delete the pair, so push this char to the result */
               &result.Push(&chars [&x]);
            End-If;
         Else
            /* No reason to delete the pair, so push this char to the result */
            &result.Push(&chars [&x]);
         End-If;
      Else
         /* No reason to delete the pair, so push this char to the result */
         &result.Push(&chars [&x]);
      End-If;
   End-For;
   
   /* all done, return the array */
   Return &result;
end-method;

method SolvePart1
   /+ Returns String +/
   /+ Extends/implements TS_AOC2018:Day.SolvePart1 +/
   
   /* Process the chain as-is, no characters omitted, convert length to string */
   Return String(%This.ReactChain(&chars, 0).Len);
   
end-method;

/* This exploits knowledge that we don't exceed a frequency value of 200,000 */
method SolvePart2
   /+ Returns String +/
   /+ Extends/implements TS_AOC2018:Day.SolvePart2 +/
   Local integer &smallestChain;
   Local integer &bestLetter;
   Local integer &x;
   
   &smallestChain = %This.ReactChain(&chars, 97).Len;
   &bestLetter = 97;
   
   For &x = 98 To (97 + 25)
      
      Local integer &currentChainLen = %This.ReactChain(&chars, &x).Len;
      If (&currentChainLen < &smallestChain) Then
         &smallestChain = &currentChainLen;
         &bestLetter = &x;
      End-If;
      
   End-For;   
   Return String(&smallestChain);
end-method;

method IsLower
   /+ &s as Number +/
   /+ Returns Boolean +/
   
   If (&s >= 65 And
         &s <= 90) Then
      Return False;
   Else
      If (&s >= 97 And
            &s <= 122) Then
         Return True;
      Else
         Return False;
      End-If;
   End-If;
   
end-method;

method GetLetter
   /+ &s as Number +/
   /+ Returns Integer +/
   If (&s = 0) Then
      Return 0;
   End-If;
   If %This.IsLower(&s) Then
      Return &s - 96;
   Else
      Return &s - 64;
   End-If;
end-method;

get Description
   /+ Returns String +/
   Return "Alchemical Reduction";
end-get;

1

u/Schaulustiger Dec 05 '18

Ruby from the command line

ruby -ne 'puts ([""]+(?a..?z).to_a).reduce($_.size){|m,u|b=$_.dup.gsub(/#{u}|#{u.swapcase}/,"");loop{break unless b.sub!(/(.)(?!\1)(?i:\1)/,"")};p b.strip.size if u=="";b.strip.size<m ? b.strip.size : m}' input.txt

1

u/[deleted] Dec 05 '18 edited Dec 05 '18

super late C

#define _POSIX_SOURCE
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>

#define to_lower(a) ((a)|0x20)
#define test(a, b) (to_lower(a) == to_lower(b) && a != b)

int react(char *p, char *buf, size_t len, char skip) {
    size_t j = 0;
    for (size_t i = 0; i < len; i++) {
        if (to_lower(p[i]) == skip)
            continue;
        if (j && test(p[i], buf[j-1]))
            j--;
        else
            buf[j++] = p[i];
    }
    return j;
}

int main(void) {
    ssize_t len;
    char *p = 0;
    size_t cap = 0;
    if ((len = getline(&p, &cap, stdin)) == -1) return 1;
    if (p[len-1] == '\n') p[--len] = 0;
    char *buf = malloc(len);
    printf("%zd\n", len = react(p, buf, len, 0));
    int min = INT_MAX, n;
    for (char a = 'a'; a <= 'z'; a++)
        if ((n = react(buf, p, len, a)) < min)
            min = n;
    printf("%d\n", min);
}

1

u/NabrenX Dec 05 '18
with open("advent5_input.txt") as input_file:
  source_input = input_file.read()

def collapse(polymer_string):
  idx = 0
  current = polymer_string
  while idx < len(current) - 1:
    diff = abs(ord(current[idx]) - ord(current[idx + 1]))
    if diff == 32:
      current = current[:idx] + current[idx+2:]
      
      if idx > 0:
        idx -= 1
    else:
      idx += 1

  return len(current)

print 'Part One: ', collapse(source_input)

shortest_len = len(source_input)
for upperOrd in xrange(ord('A'), ord('Z') + 1):
  upperChar = chr(upperOrd)
  lowerChar = chr(upperOrd + 32)
  replaced_string = source_input.replace(upperChar, '').replace(lowerChar, '')
  shortest_len = min(shortest_len, collapse(replaced_string))

print 'Part Two: ', shortest_len

1

u/RusskiEnigma Dec 05 '18

Here's my day 5 part 1 and 2 solution. I write it in the most readable format I can think of, so if you're new to coding you can understand exactly what's going on. There's plenty of very elegant and compact solutions already in this thread, but I like to really stretch it out by parts. Uncomment out "print(tempPoly)" to watch the polymer grow and contract as the program runs, or keep it commented out for instant solutions.

import string

polymer = ''
f = open('polymer.txt','r+') #your polymer string, but in a text file
for i in f:
    polymer += str(i) #creates the polymer string
f.close()

def collapse(p):
    tempPoly = '' #we'll place our result into this string, and compare as we go.
    for i in p:
        #print(tempPoly) #Fun to watch!
        if tempPoly == '': #intial case, tempPoly is blank, so nothing to compare, throw that letter in!
            tempPoly += i #add i to the tempPoly string
            p = p[1:] #remove what we just compared from our polymer string
        elif tempPoly[-1].isupper(): #we're checking polymer input for capitalization, so ZZ doesn't get deleted.
            if i.isupper(): #if the character we're comparing it to is already capitalized, it doesn't matter even if it is the same
                tempPoly += i
                p = polymer[1:]
            elif tempPoly[-1] == i.upper(): #if it's not a capital letter, then we need to compare, so let's compare with i as capital...
                tempPoly = tempPoly[:-1]    #...since we already know that tempPoly[-1] is capital
                p = p[1:]
            else:
                tempPoly += i
                p = p[1:]
        elif tempPoly[-1].islower(): #same idea as upper, just backwards
            if i.islower():
                tempPoly += i
                p = p[1:]
            elif tempPoly[-1] == i.lower(): #since what we're comparing is already lowercase, we're turning i lowercase to compare if it's the same
                tempPoly = tempPoly[:-1]
                p = p[1:]
            else:
                tempPoly += i
                p = p[1:]
    return tempPoly
part1 = collapse(polymer) #part1 solution is retrieved just by placing the polymer string through the function
print("Polymer length after initial collapse, Part 1: ")
print(len(part1))
print("Starting part 2")

def removechar(c): #removes upper and lowercase character from the polymer string
    global part1
    tp = part1
    tp = tp.replace(c.lower(), '')
    tp = tp.replace(c, '')
    return tp

part2sort = []
alpha = string.ascii_uppercase #essentially a list of the entire alphabet in capital letters (these are the polymer possibilities)
for i in alpha: 
    test = removechar(i)
    result = collapse(test) #runs the modified polymer string through the collapse function
    part2sort.append([len(result),i]) #records the results for later sorting / comparison
part2sort.sort() #sorts our dictionary least to greatest, first entry will be the solution
print("Removing "+part2sort[0][1]+" is best result with: "+str(part2sort[0][0]))

1

u/mini_feebas Dec 05 '18

~70 lines of c++ (60 of those are actual code i think)

#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>


using namespace std;

int reducedStringSize(string* originalStringPointer){
    string originalString = *originalStringPointer;
    string replacing = "aA";
    string replacing2 = "Aa";
    string::size_type i;
    bool finished;
    while (true){
        finished = true;
        for (int j = 0; j < 26; ++j) {
            i = originalString.find(replacing);
            if (i != string::npos)
                originalString.erase(i, replacing.length());
            i = originalString.find(replacing2);
            if (i != string::npos)
                originalString.erase(i, replacing2.length());
            replacing[0]++;
            replacing[1]++;
            replacing2[0]++;
            replacing2[1]++;
        }
        replacing = "aA";
        replacing2 = "Aa";
        for (int j = 0; j < 26; ++j) {
            i = originalString.find(replacing);
            if (i != string::npos)
                finished = false;
            i = originalString.find(replacing2);
            if (i != string::npos)
                finished = false;
            replacing[0]++;
            replacing[1]++;
            replacing2[0]++;
            replacing2[1]++;
        }
        replacing = "aA";
        replacing2 = "Aa";
        if (finished){
            *originalStringPointer = originalString;
            return originalString.size();
        }
    }
}

int removeAndReduce(string originalString, char a){
    originalString.erase(remove(originalString.begin(), originalString.end(), a), originalString.end());
    originalString.erase(remove(originalString.begin(), originalString.end(), char(a-32)), originalString.end());
    return reducedStringSize(&originalString);
}
int main() {
    fstream input("input.txt");
    string inputstring;
    input >> inputstring;
    cout << reducedStringSize(&inputstring) << endl;
    vector<int> stringSizes;
    int stringSize;
    for (char a = 'a'; a <= 'z'; ++a) {
        stringSize = removeAndReduce(inputstring, a);
        stringSizes.push_back(stringSize);
    }
    auto mostReduced = min_element(begin(stringSizes),end(stringSizes));
    cout << *mostReduced << endl;
    return 0;
}

1

u/mal607 Dec 05 '18 edited Dec 05 '18

Python 2 solution: (runs in 1.5 sec)

import re

def boom(a, b):
	return a != b and a.upper() == b.upper()

def solve(s):
	i = 0
	while (i < len(s) - 1):
		if boom(s[i], s[i+1]):
			s = s[:i] + s[i+2:]
			i-=1
		else:
			i+= 1
	return s


with open('./data/Day05') as f:
	s = f.read()
	print "Part 1:", len(solve(s))
	li = []
	for c in list('abcdefghijklmnopqrstuvwxyz'):
		length = len(solve(re.sub(r"["+ c + c.upper() + ']', '', s)))
		li.append(length)
	print "Part 2:", min(li)

1

u/bruceadowns Dec 05 '18

golang/go using a doubly linked list. old school.

const caseDiff rune = 'a' - 'A'

type node struct {
	next *node
	prev *node
	data rune
}

type list struct {
	first *node
	last  *node
}

func (l *list) String() string {
	var sb strings.Builder
	for n := l.first; n != nil; n = n.next {
		sb.WriteRune(n.data)
	}
	return sb.String()
}

func (l *list) insertAfter(n *node, nn *node) {
	nn.prev = n
	if n.next == nil {
		l.last = nn
	} else {
		nn.next = n.next
		n.next.prev = nn
	}
	n.next = nn
}

func (l *list) insertBefore(n *node, nn *node) {
	nn.next = n
	if n.prev == nil {
		l.first = nn
	} else {
		nn.prev = n.prev
		n.prev.next = nn
	}
	n.prev = nn
}

func (l *list) insertBeginning(nn *node) {
	if l.first == nil {
		l.first = nn
		l.last = nn
	} else {
		l.insertBefore(l.first, nn)
	}
}

func (l *list) insertEnd(nn *node) {
	if l.last == nil {
		l.insertBeginning(nn)
	} else {
		l.insertAfter(l.last, nn)
	}
}

func (l *list) remove(n *node) {
	if n.prev == nil {
		l.first = n.next
	} else {
		n.prev.next = n.next
	}
	if n.next == nil {
		l.last = n.prev
	} else {
		n.next.prev = n.prev
	}
}

func react(a, b rune) bool {
	if a > b {
		return a-b == caseDiff
	}
	return b-a == caseDiff
}

func build(s string) (res list) {
	for _, v := range s {
		res.insertEnd(&node{data: v})
	}

	return
}

func part1(l list) int {
	for n := l.first; n != nil && n.next != nil; {
		if react(n.data, n.next.data) {
			r := n

			// go back or skip forward
			if n.prev == nil {
				n = n.next.next
			} else {
				n = n.prev
			}

			l.remove(r.next)
			l.remove(r)
		} else {
			n = n.next
		}
	}

	return len(l.String())
}

func part2(s string) (res int) {
	res = math.MaxInt32
	for i := 'A'; i <= 'Z'; i++ {
		in := strings.NewReplacer(
			fmt.Sprintf("%c", i), "",
			fmt.Sprintf("%c", i+caseDiff), "").Replace(s)
		l := part1(build(in))
		if l < res {
			res = l
		}
	}

	return
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	for scanner.Scan() {
		line := scanner.Text()
		log.Printf("reduced polymer length: %d", part1(build(line)))
		log.Printf("shortest reduced polymer length: %d", part2(line))
	}
}

1

u/morfi717 Dec 05 '18 edited Dec 05 '18

Ruby

F = File.read("#{__dir__}/data/day5.txt").strip.each_char.to_a

ξ = F.uniq.sort.each_slice(26).reduce(&:zip).append(['Ω']).map { |ϵ|
     (F - ϵ).each_with_object([]) { |Ξ, ϕ|
          ϕ.last && (Ξ.ord - ϕ.last.ord).abs == 32 ? ϕ.pop : ϕ << Ξ
     }.size
}

puts "Ans 1: %s" % ξ.max
puts "Ans 2: %s" % ξ.min

1

u/orgodemir Dec 05 '18

Python 3, pretty quick run time with ~1 pass:

inp = Input(5).read()[:-1]
ll = 'abcdefghijklmnopqrstuvwxyz'
lu = letters.upper()

def d5p1(inp):
    inp = list(inp)
    i = 0
    while True:
        if i+1==len(inp): break
        if inp[i] == inp[i+1].swapcase():
            inp.pop(i)
            inp.pop(i)
            i = max(i-2,-1)
        i+=1
    return len(inp)

print(d5p1(inp))
print(min([d5p1(inp.replace(ll[i],'').replace(lu[i],''))] for i in range(26)))

1

u/djbft Dec 05 '18

My solution in Kotlin. Can anyone explain to me why doFold needs to be a separate function? If I inline it as a lamda:

polymer.fold("") { acc, c ->
     ...exactly the same content as 'doFold'...
}

then it stops working. The 'fold' only goes through one iteration, which returns in the if(acc.isEmpty()) line, and then it stops early. aA becomes a.

fun doFold(acc: String, c: Char): String {
		if(acc.isEmpty()){
			return "${c}"
		}
		val lastChar = acc.last()
		if(lastChar.equals(c, ignoreCase = true)){
			if(lastChar.isUpperCase() != c.isUpperCase()){
				return acc.dropLast(1)
			}
		}
		return acc + c
}

fun process(polymer: String): String {
	return polymer.fold("") { acc, c -> doFold(acc, c) }
}

override fun part1(input: List<String>): String {
	return process(input[0]).length.toString()
}

override fun part2(input: List<String>): String {
	val baseInput = input[0]

	val results = mutableMapOf<Char, Int>()
	for( c in baseInput.toLowerCase().asIterable().distinct() ){
		val candidate = process(baseInput.replace(Regex("[$c${c.toUpperCase()}]"), ""))
		println("$c -> ${candidate.length}")
		results.put(c, candidate.length)
	}
	return results.values.min().toString()
}

2

u/ephemient Dec 05 '18 edited Apr 24 '24

This space intentionally left blank.

→ More replies (1)

1

u/Plastix Dec 05 '18

Kotlin:

object Day5 {

    fun part1(input: String): Int = input.asSequence()
            .react()
            .size

    private fun Sequence<Char>.react(): Stack<Char> =
            fold(Stack()) { stack, char ->
                if (stack.isNotEmpty() && stack.peek().opposites(char)) {
                    stack.pop()
                } else {
                    stack.push(char)
                }
                stack
            }

    private fun Char.opposites(other: Char): Boolean = equals(other, ignoreCase = true) &&
            ((isUpperCase() && other.isLowerCase()) || (isLowerCase() && other.isUpperCase()))

    fun part2(input: String): Int = input.asSequence()
            .distinctBy { it.toLowerCase() }
            .map { char ->
                input.replace(char.toString(), "", ignoreCase = true).asSequence()
                        .react().size
            }.min() ?: 0

}

1

u/chrisgedrim Dec 05 '18

TypeScript - no external packages.

Code is executed by a runner (which loads the input from ` .txt` file as an array, and passes it to `run1`/`run2` via `parse`)

Has complete unit tests written with [ava](https://github.com/avajs/ava)

export const parse = (rawInputs: string[]): any => {
    return rawInputs[0];
};

export const run1 = (input: string): number => {
    return reactPolymer(input);
};

const reactPolymer = (input: string) => {
    let i = 0;
    const split = input.split('');

    while (i < split.length) {
        switch (true) {
            case split[i] === split[i + 1]:
                i++;
                break;
            case split[i].toUpperCase() === split[i + 1]:
            case split[i].toLowerCase() === split[i + 1]:
                split.splice(i, 2);
                i = Math.max(i - 1, 0);
                break;
            default:
                i++;
                break;
        }
    }

    return split.length;
}

export const run2 = (input: string): number => {
    const charsInPolymer = invert({
        ...input.toLowerCase()
            .split('')
            .filter((value, index, self) => self.indexOf(value) === index)
            .sort()
    });

    for (const char in charsInPolymer) {
        const strippedInput = input.replace(new RegExp(`${char}`, 'ig'), '');
        charsInPolymer[char] = reactPolymer(strippedInput);
    }

    const smallestPolymer = Object.keys(charsInPolymer)
        .reduce((a, b) => charsInPolymer[a] < charsInPolymer[b] ? a : b);

    return charsInPolymer[smallestPolymer];
};

const invert = (obj) => {
    const inverted = {};

    for (const prop in obj) {
        if (obj.hasOwnProperty(prop)) {
            inverted[obj[prop]] = prop;
        }
    }

    return inverted;
};

1

u/chunes Dec 05 '18

Factor

: react ( seq -- seq' ) [
        [ length ] [
            dup 2 <clumps> [ first2 - abs 32 = ] find drop
            [ dup 2 + rot [ delete-slice ] keep ] when*
        ] over tri rot = not
    ] loop ;

"input5.txt" utf8 file-contents but-last-slice >sbuf
[ react length . ]
[
    [ 26 ] dip <repetition> CHAR: A CHAR: Z [a,b]
    [
          [ clone ] dip 2dup 32 + [ [ = ] curry reject! ] 2bi@ drop
    ] 2map [ react length ] map infimum .
] bi

1

u/wleftwich Dec 06 '18 edited Dec 06 '18

A stack, in python:

def reduce(s):
    stack = []
    for c in s:
        try:
            b = stack[-1]
        except IndexError:
            stack.append(c)
            continue
        if b.lower() == c.lower() and b != c:
            stack.pop()
        else:
            stack.append(c)
    return stack

answer_1 = len(reduce(data))

L = []
for letter in sorted(set(x.lower() for x in data)):
    red = reduce(x for x in data if x not in (letter, letter.upper()))
    L.append((letter, len(red)))

answer_2 = min(y for (x,y) in L)

1

u/sotsoguk Dec 06 '18

as always wrong timezone and late to the party ...

class Stack:
    def __init__(self):
        self.items = []
    
    def isEmpty(self):
        return self.items ==[]
    
    def push(self, item):
        self.items.append(item)
        
    def pop(self):
        return self.items.pop()
    
    def peek(self):
        return self.items[len(self.items)-1]
    
    def size(self):
        return len(self.items)
    
import operator

input=[]
#input = open("input.txt").read().splitlines()[0]
with open('input.txt') as f:
    input = f.readlines()

input = input[0].strip()
stack = Stack()
for c in input:
    if stack.isEmpty():
        stack.push(c)
    elif str.swapcase(c) == stack.peek():
        stack.pop()
    else:
        stack.push(c)

# speed up by using the collapsed polymer output of part1 as input for part2
input = stack.items
print('Part1:\t')
print(stack.size())

polyList = []
values = {}
for i in range(ord('a'),ord('z')+1):
    polyList.append(''.join([chr(i),chr(i).upper()]))
stack = Stack()
for deletePoly in polyList:
    stack = Stack()
    for c in input:
    # print(stack.items)
        if c in deletePoly:
            pass
        elif stack.isEmpty():
            stack.push(c)
        elif str.swapcase(c) == stack.peek():
            stack.pop()
        else:
            stack.push(c)
    #print(deletePoly + " " + str(stack.size()))
    values[deletePoly] = stack.size()

minLength = min(values.items(),key=operator.itemgetter(1))[1]
print("Part2:\t")
print(minLength)

1

u/cartogram Dec 06 '18 edited Dec 06 '18

[Card] On the fifth day of AoC / My true love gave to me / Five isomorphic rings

Scala with the left fold

def checkReact(a:Char, b:Char): Boolean  = {
     (a != b) && (a.toUpper == b.toUpper) && (a.toLower == b.toLower)
}

def foldPolymer(polymer:String) : String = { 
  polymer.foldLeft("") {
    case (ls, e) if (ls.isEmpty || !checkReact(ls.last, e)) => ls + e
    case (ls, e) => ls.dropRight(1)
  } 
}

val filterPolymer = (polymer:String, chr:Char) => str.filter((c:Char) => c != (chr.toLower) && c != (chr.toUpper))

val part1 = foldPolymer(puzzleInput).size
val part2 = ('a' to 'z').map(filterPolymer(puzzleInput,_)).map(foldPolymer).map(_.size).min

1

u/hilesm Dec 06 '18

JS solution with some Ramda. Didn't get around to doing it until almost 24 hours after it opened.

const { pipe, reduce, last, init, map, reject, range, length } = require('ramda')

const simplifyPolymer = (acc, val) => last(acc).charCodeAt(0) === val.charCodeAt(0) - 32 || last(acc).charCodeAt(0) === val.charCodeAt(0) + 32 ? init(acc) : acc + val

const solution1 = reduce(simplifyPolymer, '')
const alphabet = range(65, 91)
const matchesChar = (char) => (val) => val.charCodeAt(0) === char || val.charCodeAt(0) === char + 32 
const solution2 = (input, abcs) => pipe(map(matchesChar), map((fn) => reject(fn, input)), map(reduce(simplifyPolymer, '')), map(length))(abcs)

console.log(solution1(rawInput).length)
console.log(solution2(rawInput, alphabet))

1

u/wjholden Dec 06 '18

This one was really difficult in Mathematica. I wished for ordinary stacks and linked lists the whole time. The code shown below is actually my second effort to solve the problem using a different approach.

After thinking about the problem for a while I realized that we are actually contracting the vertices of a graph. I handled this by constructing a sparse matrix as an edge set to represent letters that can get skipped. My matrix is (n+1) by (n+1) to implicitly include a sentinel value. To find the final polymer count you just compute the shortest path from v[1] to v[n+1] (the sentinel) and subtract 2. That -2 thing isn't perfect and doesn't correctly handle degenerate cases like "a" and "aA".

reduceGraph2L[s_String] := Module[{e, i, j, a, b},
  (* initialize the edge set (a n+1 * n+1 matrix) with u\[Rule]{u-1,
  u+1} *)
  e = SparseArray[Union[
     Map[{#, # + 1} -> 1 &, Range[StringLength[s]]],
     Map[{# + 1, #} -> 1 &, Range[StringLength[s]]],
     {{1, 1} -> 1}]];
  i = 1;
  j = 2;
  While[j <= StringLength[s],
   a = First[ToCharacterCode[StringTake[s, {i}]]];
   b = First[ToCharacterCode[StringTake[s, {j}]]];
   (* if the letters at positions s[i] and s[
   j] are equal with opposite case *)
   If[Abs[a - b] == 32,
    (* create an edge between the predecessor to vertex i (which is \
still i if i\[Equal]1) and successor to vertex j *)
    i = Min[e[[i]]["NonzeroPositions"]];
    j = Max[e[[j]]["NonzeroPositions"]];
    e[[i]][[j]] = e[[j]][[i]] = 1,
    (* otherwise move to position j and continue *)
    i = j;
    j = Max[e[[j]]["NonzeroPositions"]]];
   ];
  e]
Timing[s = Import["day5.txt"];
 m = reduceGraph2L[s];
 g = AdjacencyGraph[m, VertexLabels -> "Name"];
 Length[FindShortestPath[g, 1, StringLength[s] + 1]] - 2 ]
(* -2 because we do not count the first and last elements. There is \
room for error here with lists like "a" and "aA" so this algorithm \
isn't perfect. *)

Here is how the matrix looks on ToString[MatrixForm[reduceGraph2L["dabAcCaCBAcCcaDA"]]]. There is an edge for all v[i]->v[i+1] and v[i+1]->v[i]. We also have an edge v[1]->v[1].

1   1   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0

1   0   1   0   0   0   0   0   0   0   0   0   0   0   0   0   0

0   1   0   1   0   0   0   1   0   0   0   0   0   0   0   0   0

0   0   1   0   1   0   1   0   0   0   0   0   0   0   0   0   0

0   0   0   1   0   1   0   0   0   0   0   0   0   0   0   0   0

0   0   0   0   1   0   1   0   0   0   0   0   0   0   0   0   0

0   0   0   1   0   1   0   1   0   0   0   0   0   0   0   0   0

0   0   1   0   0   0   1   0   1   0   0   0   0   0   0   0   0

0   0   0   0   0   0   0   1   0   1   0   0   0   0   0   0   0

0   0   0   0   0   0   0   0   1   0   1   0   1   0   0   0   0

0   0   0   0   0   0   0   0   0   1   0   1   0   0   0   0   0

0   0   0   0   0   0   0   0   0   0   1   0   1   0   0   0   0

0   0   0   0   0   0   0   0   0   1   0   1   0   1   0   0   0

0   0   0   0   0   0   0   0   0   0   0   0   1   0   1   0   0

0   0   0   0   0   0   0   0   0   0   0   0   0   1   0   1   0

0   0   0   0   0   0   0   0   0   0   0   0   0   0   1   0   1

0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   1   0

2

u/[deleted] Dec 06 '18

I wished for ordinary stacks

Wish grated! I used the following for my react step.

push[x_] := stack[[sptr++]] = x;
pop[] := stack[[--sptr]];
head[] := stack[[sptr - 1]];

react[polymer_String] :=
 Block[{stack = ConstantArray[0, StringLength@polymer], sptr = 1},
  Do[If[sptr != 1 && BitXor[head[], c] == 32, pop[], push[c]],
   {c, ToCharacterCode[polymer]}];
  sptr - 1]
→ More replies (1)

1

u/alexgand Dec 06 '18

python!

import numpy as np
import pandas as pd
from pandas import DataFrame, Series

file = 'C:/code/advent_of_code_2018/day05data.txt'

data = pd.read_csv(file,header=None)
input = data[0].iloc[0]

text = input

def react(text):
    #just to initialize it:
    destroy=[1]
    while len(destroy) > 0:
        destroy = []
        for i in range(len(text)-1):
            #letras iguais, upper or lower:
            if text[i] == text[i+1]:
                pass
            #letras diferentes, independente de upper or lower:
            elif text[i] != text[i+1].upper() and text[i].upper() != text[i+1]:
                pass
            #destroi them:
            else:
                if i-1 in destroy:
                    pass
                else:
                    destroy.append(i)
                    destroy.append(i+1)
        text = ''.join([text[i] for i in range(len(text)) if i not in destroy])
        print('\nqtd destroyed:',len(destroy))
        print('len text:',len(text))
    return len(text)
    
print('\nanswer:',react(text))

#part 2:

import string

results = {}

for letter in string.ascii_lowercase:
    #remove letter:
    new_text = input.replace(letter,'')
    new_text = new_text.replace(letter.upper(),'')
    results[letter] = react(new_text)
    print(letter,'done.')

print('part #2 answer:', Series(results).sort_values().iloc[0])

1

u/IlliterateJedi Dec 06 '18 edited Dec 06 '18

Python 3 solution. Part 1 came in around 75 ms on my computer, and part 2 was around 2300 ms. Edit: After reading through this thread, using the output from part 1 as the input for part 2 reduced the time to 492 ms. So that's not too shabby.

from collections import deque

def same_type(char1: str, char2: str):
    return char1.lower() == char2.lower()


def opposite_polarity(char1: str, char2: str):
    if char1.islower():
        if char2.isupper():
            return True
        else:
            return False
    elif char1.isupper():
        if char2.islower():
            return True
        else:
            return False


def shrink_polymer(polymer_in):
    polymer_out = deque(polymer_in.popleft())
    while polymer_in:
        if same_type(polymer_out[-1], polymer_in[0]) and opposite_polarity(polymer_out[-1],
                                                                       polymer_in[0]):
            polymer_out.pop()
            polymer_in.popleft()
            if not polymer_out:
                polymer_out.append(polymer_in.popleft())
        else:
            polymer_out.append(polymer_in.popleft())
    return len(polymer_out)


def find_shortest_polymer_length(polymer_in):
    letters = set()
    shortest_len = int(float("1e7"))
    for i in polymer_in:
        if i.lower() not in letters:
            letters.add(i.lower())
            test_set = deque([letter for letter in polymer_in if letter.lower() != i.lower()])
            n = shrink_polymer(test_set)
            if n < shortest_len:
                shortest_len = n
    return shortest_len


if __name__ == '__main__':
    file_in = r"input/5.txt"

    with open(file_in, "r") as f:
        polymer = f.read().split("\n")[0]

    polymer_dq = deque(polymer)
    print(shrink_polymer(polymer_dq)) # part 1 value
    polymer_dq = deque(polymer)
    print(find_shortest_polymer_length(polymer_dq)) # part 2 value

1

u/Tinnittin Dec 06 '18 edited Dec 06 '18

[Python 3] (22 lines for both parts)

Part 1: 3.8s

Part 2: 116s

High school student here. I know this is massively inefficient, but I went with my first guess and it took me about 10 minutes to write. I then condensed it as much as I could to shorted the number of lines. If you have any ideas on how to shorten it further, I'd love to hear them. The first entry in the values dictionary is a space which finds the solution for the first part. Here it is:

with open('input.txt') as f:
    full_input = f.readlines()[0]
def collapse(working_input):
    length = len(working_input)
    i = 0
    while i <len(working_input):
        if i == len(working_input) - 1:
            break
        elif working_input[i].upper() == working_input[i+1].upper() and working_input[i] != working_input[i+1]:
            working_input = (working_input[:i] if i+2 == length -1 else working_input[:i] + working_input[i+2:])
        else:
            i += 1
    return working_input
values = {' ': 0, 'a': 0, 'b': 0, 'c':0, 'd':0, 'e':0, 'f':0, 'g':0, 'h':0, 'i':0, 'j':0, 'k':0, 'l':0, 'm':0, 'n':0, 'o':0, 'p':0, 'q':0, 'r':0, 's':0, 't':0, 'u':0, 'v':0, 'w':0, 'x':0, 'y':0, 'z':0}
for i in values:
    working_input = full_input.replace(i, '').replace(i.upper(), '')
    while 1:
        length = len(working_input)
        working_input = collapse(working_input)
        if length == len(working_input):
            values[i] = length
            break

1

u/RockyAstro Dec 06 '18

Icon Part 1 & 2

procedure main()

    l := trim(read())
    # Part 1
    write(process(l))

    # Part 2
    min := *l
    every c := !&lcase do {
        min >:= process(l,c||swapcase(c))
    }
    write(min)

end
procedure process(l,c)
    i := 1
    until i = *l do {
        if \c & any(c,l[i]) then {
            l[i] := ""
            i -:= 1
        }
        else if l[i+1] == swapcase(l[i]) then {
            l[i+:2] := ""
            i -:= 1
        }
        else i+:=1
    }

    return *l
end
procedure swapcase(c)
    return map(c,&lcase||&ucase,&ucase||&lcase)
end

1

u/cptwunderlich Dec 06 '18

Oh man, these days I don't have much time and after working out after work, I just couldn't finish it yesterday. I didn't want to use explicit loops, but wanted something "functional", without finding the right function in python. I cheated a little and the top answer here for Haskell "inspired" me, i.e., I ripped it off ;)

Python foldr implementation taken from https://www.burgaud.com/foldl-foldr-python

import functools

if __name__ == "__main__":
    input = [line.strip() for line in open("input.txt", 'r')]
    foldr = lambda f, acc, xs: functools.reduce(lambda x, y: f(y, x), reversed(xs), acc)
    reduce = lambda poly: foldr(lambda x, ys: ys[1:] if len(ys) > 0 and (x != ys[0] and x.swapcase() == ys[0]) else x + ys, '', poly).strip()
    res = reduce(input[0])
    print('Part1:', len(res))
    
    scores = []
    alphabet = map(chr, range(ord('a'), ord('z')+1))
    for letter in alphabet:
      scores.append((letter, len(reduce(list(filter(lambda l: letter != l.lower(), input[0]))))))

    print('Part2:', (min(scores, key=lambda t: t[1])[1]))

1

u/sparklingtwilight Dec 07 '18

My solution in PHP:

<?php

function fully_react($polymer) {
    do {
        $polymer = preg_replace('/(.)(?!\1)(?i)(\1)/', '', $polymer, -1, $count);
    } while ($count);
    return $polymer;
}

function reduce($polymer, $unit) {
    return preg_replace("/$unit/i", '', $polymer);
}


$input = trim(stream_get_contents(STDIN));
$reacted_input = fully_react($input);
echo strlen($reacted_input) . PHP_EOL;

$unit_types = array_unique(str_split(strtolower($input)));
$lengths = [];
foreach ($unit_types as $unit) {
    $lengths[] = strlen(fully_react(reduce($reacted_input, $unit)));
}
echo min($lengths) . PHP_EOL;

(https://github.com/hckr/adventofcode/blob/master/2018/PHP/5.php)

And an analogue in Perl, but unfortunately it takes 5 times more – I'd be happy for suggestions. Perl is a cryptic langauge for me :P

use List::Util 'min';

sub fully_react {
    my ($polymer) = @_;
    do {
        $count = $polymer =~ s/(.)(?!\1)(?i)(\1)//g;
    } while ($count);
    return $polymer;
}

sub reduce {
    my ($polymer, $unit) = @_;
    $polymer =~ s/$unit//gi;
    return $polymer;
}


my $input = <>;
$input =~ s/^\s+|\s+$//g;

my $reacted_input = fully_react $input;
say length $reacted_input;

my @unit_types = split //, (lc $input) =~ s/(.)(?=.*?\1)//rg;
my @lengths;
for my $unit (@unit_types) {
    push @lengths, length(fully_react(reduce($reacted_input, $unit)))
}
say min @lengths

(https://github.com/hckr/adventofcode/blob/master/2018/Perl/5.pl)

1

u/Kosi_i Dec 07 '18

Hello,

I have just started learning python and I have done the first part for the day number 5. The code is not well optimised and it runs for around 60 sec.

Although I have a question. My code is not working properly if I don't use break. When I use break it start looping from my string again, but if I don't use it, it should still provide me the same result because strings at the end should be the same length.

What did I miss?

from itertools import islice

cnt, myString = 0, ''

with open('input5.txt','r') as f:
    for line in f.readlines():
        myString += line
        

while 1:
    OldmyString = myString
    for one, two in zip(myString, islice(myString, 1, None)):
        cnt += 1
        
        # if the polarity is different and char is the same we delete them
        if (one.islower() and two.isupper()) or (one.isupper() and two.islower()):
            if one.lower() == two.lower():
                myString = myString[:cnt-1]+myString[cnt+1:]
                
                # if I don't use break I only go through list 1x, IDK why
                break
               
    # at the end of the string we check length of a new string and an old one            
    if len(OldmyString) == len(myString):
        print(f'Sum of char in a string: {len(myString)}')
        break
    else:
        cnt = 0

1

u/ekiMbot Dec 07 '18

Python3. Fairly concise at least.

import string
all_pairs = [pair[0] + pair[1] for pair in
             list(zip(
                 string.ascii_lowercase + string.ascii_uppercase,
                 string.ascii_uppercase + string.ascii_lowercase))]

def part_one(polymer):
    prev_len = None
    while len(polymer) != prev_len:
        prev_len = len(polymer)
        for pair in all_pairs:
            polymer = polymer.replace(pair, '')
    return prev_len

def part_two(polymer):
    return min(
        part_one(polymer.replace(unit, '').replace(unit.upper(), ''))
        for unit in string.ascii_lowercase)

1

u/pepoluan Dec 07 '18 edited Dec 07 '18

Python3

I try to optimize but keep things readable.

#!python3

from typing import Set, List
import time


def reduce(polymer):  # type: (str) -> str
    polymer = polymer.strip()
    lowers = sorted(set(polymer.lower()))  # type: List[str]
    uppers = [c.upper() for c in lowers]
    prev = None
    while prev != polymer:
        prev = polymer
        for p, q in zip(lowers, uppers):
            polymer = polymer.replace(p + q, '')
        for p, q in zip(uppers, lowers):
            polymer = polymer.replace(p + q, '')
    return polymer    


def part1(polymer):  # type: (str) -> int
    return len(reduce(polymer))


def part2(polymer):  # type: (str) -> int
    atoms = set(polymer.strip().upper())  # type: Set[str]
    result = min(
        part1(polymer.replace(a, '').replace(a.lower(), '')) for a in atoms
    )
    return result


if __name__ == '__main__':
    with open('../tests/aoc2018/day_05.txt') as fin:
        ln = fin.readline().strip()
    start = time.perf_counter()
    print('part1:', part1(ln))
    print('part2:', part2(ln))
    end = time.perf_counter()
    print('elapsed:', end - start)

The whole shebang took about 9.6 seconds in PyCharm on my MBP 2017 with a 2,3 GHz Intel Core i5.

EDIT: Whoops, just realized that I don't need to sort there. Oh well.

EDIT2: Strange... testing with timeit says that sorted() is somewhat faster than list(). That's news to me...

EDIT3: More timeit experiments, and actually string comparison is even faster than string-length comparison! I assume that this is because .replace() is smart enough to simply return the same object when no replacement happens, and this results in prev and polymer pointing to the same object == really fast equality test. Editing the source code above to reflect this.

1

u/GraveKill Dec 10 '18

My golang solution. I'm still learning go, so I am taking my time solving each one.

https://github.com/afonsojramos/advent-of-code-2018

package main

import (
	"bytes"
	"fmt"
	"utils"
)

const capDist = 'a' - 'A'
const aCode = 'A'
const zCode = 'Z'

func reactPoly(chars []byte) []byte {
	changes := true

	for changes {
		changes = false
		for i := 0; i < len(chars)-1; i++ {
			if utils.Abs(int(chars[i])-int(chars[i+1])) == capDist {
				chars = append(chars[:i], chars[i+2:]...)
				changes = true
			}
		}
	}

	return chars
}

func main() {
	// Part 1
	line := utils.ReadLines("day-5/5.input")
	chars := []byte(line[0])
	fmt.Println(len(reactPoly(chars)))

	// Part 2
	min := 100000000000000
	for charCode := aCode; charCode < zCode+1; charCode++ {
		newChars := []byte(line[0])
		newChars = bytes.Replace(newChars, []byte{byte(charCode)}, nil, -1)
		newChars = bytes.Replace(newChars, []byte{byte(charCode + capDist)}, nil, -1)

		if x := len(reactPoly(newChars)); x < min {
			min = x
		}
	}
	fmt.Println(min)
}

1

u/pindab0ter Dec 10 '18

Kotlin - Always trying to solve as functionally as possible just to train with the concept. I think this one turned out pretty good.

fun shortestPolymer(input: String): Int = ('a'..'z').fold(emptyList<String>()) { acc, unit ->
    acc + reduce(input.filter { it.equals(unit, true).not() })
}.minBy { it.length }!!.length

fun reduce(input: String): String = input.fold("") { acc: String, c: Char ->
    if (acc.isBlank() || acc.last().formsPairWith(c).not()) acc + c
    else acc.dropLast(1)
}

fun Char.formsPairWith(other: Char): Boolean = equalsCase(other).not() && equals(other, true)

fun Char.equalsCase(other: Char): Boolean = isUpperCase() == other.isUpperCase()

1

u/lib20 Dec 11 '18

In Red, part 1, naive implementation, execution time: 0:00:06.985548

Red []

time-start: now/time/precise
input-txt: read %input.txt

reacted: true
new-polymer: make string! length? input-txt
size-last: length? input-txt

while [reacted] [

	either ((first input-txt) <> (second input-txt))
		and (((first input-txt) = (uppercase second input-txt))
			or ((uppercase first input-txt) = (second input-txt))) [
		; same type and opposite polarity
		input-txt: next next input-txt	
		if tail? input-txt [
			size-last: length? head new-polymer
			input-txt: copy head new-polymer
			new-polymer: copy ""
		]
	][

		; not (same type and opposite polarity)
		append new-polymer copy/part input-txt 1
		input-txt: next input-txt

		if tail? next input-txt [
			append new-polymer copy/part input-txt 1
			either (length? new-polymer) < size-last [
				size-last: length? new-polymer
			][
				reacted: false
			]
			input-txt: copy head new-polymer
			new-polymer: copy ""
		]
	]

]

input-txt: trim/all input-txt
print rejoin ["Execution time: " now/time/precise - time-start]
probe length? input-txt

1

u/lib20 Dec 11 '18

In Red, part 2, naive implementation, execution time: 0:06:04.394584

Red []

time-start: now/time/precise
input-txt: read %input.txt
input-txt: trim/all input-txt


get-polymer: func [input-str [string!]
					/local reacted
							new-polymer
							size-last
][
	reacted: true
	new-polymer: make string! length? input-str
	size-last: length? input-str
	
	while [reacted] [

		either ((first input-str) <> (second input-str))
			and (((first input-str) = (uppercase second input-str))
				or ((uppercase first input-str) = (second input-str))) [
			; same type and opposite polarity
			input-str: next next input-str	
			; case when QqS, two similar were removed just before the last type
			if tail? next input-str [
				append new-polymer copy/part input-str 1
				input-str: copy head new-polymer
				new-polymer: copy ""
				if (length? input-str) <= 1 [reacted: false]
			]
			if tail? input-str [
				size-last: length? head new-polymer
				input-str: copy head new-polymer
				new-polymer: copy ""
			]
		][
	
			; not (same type and opposite polarity)
			append new-polymer copy/part input-str 1
			input-str: next input-str
	
			if tail? next input-str [
				append new-polymer copy/part input-str 1
				either (length? new-polymer) < size-last [
					size-last: length? new-polymer
				][
					reacted: false
				]
				input-str: copy head new-polymer
				new-polymer: copy ""
			]
		]
	
	]
	input-str
] 



chrs: copy []
repeat i 26 [append chrs #"`" + i]
minimum-reacted: length? input-txt
removed-unit: #"?"

foreach ch chrs [
	units: copy ""
	append units to-string ch append units to-string uppercase ch
	trimmed-input: copy input-txt
	trimmed-input: trim/with trimmed-input units
	good-polymer: get-polymer trimmed-input
	if (length? good-polymer) < minimum-reacted [
		removed-unit: ch
		minimum-reacted: length? good-polymer
	]	
]

print rejoin ["Execution time: " now/time/precise - time-start]
print rejoin ["Removing units: " removed-unit uppercase removed-unit "   produces a minimum length polymer of length: " minimum-reacted]

1

u/NotVeryCleverOne Dec 12 '18 edited Dec 12 '18

Part 1 in Objective - C

    #import <Foundation/Foundation.h>
    
    int main(int argc, const char * argv[]) {
        @autoreleasepool {
            // Log text for timing purposes
            NSLog(@"Starting now...");
            
    
            NSString *myPath = @"/Users/home.directory/tmp/advent_day5.txt";
            NSString *myFile = [[NSString alloc]initWithContentsOfFile:myPath encoding:NSUTF8StringEncoding error:nil];
    
            NSMutableString *myString = [[NSMutableString alloc]initWithString:myFile];
            NSInteger i = 0;
            
            NSLog(@"Starting string count is %ld",[myString length]);
            
            while (i <[myString length]-1) {
                NSString *currentLetter = [myString substringWithRange:NSMakeRange(i, 1)];
                NSString *nextLetter = [myString substringWithRange:NSMakeRange(i+1, 1 )];
                
                if ([[NSCharacterSet lowercaseLetterCharacterSet] characterIsMember:[currentLetter characterAtIndex:0]] && [currentLetter uppercaseString] == nextLetter ) {
                        [myString deleteCharactersInRange:NSMakeRange(i, 2)];
                        if (i != 0) {
                            i = i -1;
                        }
                } else if ([[NSCharacterSet uppercaseLetterCharacterSet] characterIsMember:[currentLetter characterAtIndex:0]] && [currentLetter lowercaseString] == nextLetter ) {
                    [myString deleteCharactersInRange:NSMakeRange(i, 2)];
                    if (i != 0) {
                        i = i -1;
                    }
                } else {
                    i++;
                }
    
            }
                NSLog(@"%@,%ld",myString,[myString length]);
                
                
                
                
                return 0;
                
            }
            
        }
→ More replies (1)

1

u/vini_2003 Dec 17 '18

C++ (part I):

#include <iostream>
#include <string>
#include <regex>
#include <fstream>
#include <sstream>

using namespace std;

string input_path = "PATH_TO_INPUT_FILE";

void read() {
	bool boolybool = false;
	string storage;
	ifstream input(input_path);
	while (!boolybool) {
		getline(input, storage);
		boolybool = true;
	}
	bool something = false;
	int reactions = 0;
	while (!something) {
		for (int i = 0; i < storage.length(); i++) {
			if (isupper(storage[i]) && islower(storage[i + 1]) && tolower(storage[i]) == storage[i + 1]) {
				storage.erase(storage.begin() + i, storage.begin() + i + 2);
				i--;
				reactions++;
			}
			if (islower(storage[i]) && isupper(storage[i + 1]) && toupper(storage[i]) == storage[i + 1]) {
				storage.erase(storage.begin() + i, storage.begin() + i + 2);
				i--;
				reactions++;
			}
		}
		if (reactions > 0) {
			reactions = 0;
		}
		else {
			something = true;
			cout << "Elements: " << storage.length() << endl;
		}
	}
}

int main() {
	read();
}

1

u/vini_2003 Dec 17 '18

C++ (part II):

#include <iostream>
#include <string>
#include <algorithm>
#include <fstream>

using namespace std;

void read() {
	ifstream input("PATH_TO_INPUT_FILE");
	string phrase;
	getline(input, phrase);
	string alphabet = "abcdefghijklmnopqrstuvwxyz";
	int sizes[26] = { 0 };
	int s = 0;
	for (char c : alphabet) {
		string tmpPhrase = phrase;
		tmpPhrase.erase(remove(tmpPhrase.begin(), tmpPhrase.end(), tolower(c)), tmpPhrase.end());
		tmpPhrase.erase(remove(tmpPhrase.begin(), tmpPhrase.end(), toupper(c)), tmpPhrase.end());
		for (int p = 0; p < tmpPhrase.size();) {
			if (p >= 0 && tolower(tmpPhrase[p]) == tolower(tmpPhrase[p + 1]) && ((islower(tmpPhrase[p]) && isupper(tmpPhrase[p + 1])) | (isupper(tmpPhrase[p]) && islower(tmpPhrase[p + 1])))) {
				tmpPhrase.erase(p, 2);
				p = 0;
			}
			else {
				p++;
			}
		}
		sizes[s] = tmpPhrase.size();
		s++;
	}
	cout << "Result: " << *min_element(begin(sizes), end(sizes)) << endl;
}

int main() {
	read();
}

1

u/thefalse Dec 17 '18 edited Dec 17 '18

My Mathematica solution. This was a really nice opportunity to learn about the StringReplace and RegularExpression functions in Mathematica. They work exactly how you want them to and made this quite simple. No complaints from me on that. Smooth.

I also spent a good bit of time trying to make the free groups approach work in Mathematica. The TL;DR idea of that post is that you can treat the entire string as an algebraic expression in which capital letters are inverses of lower case letters, that way any symbolic system worth its salt can do its automatic reductions for you. The issue I ran into here is that Mathematica's built in * operator is commutative, so it not only cancels nearby upper-lower case letters, but it reorders letters until they cancel. It turns out that the entire string just reduces down to 1 when you do that. I spent a bit of time trying to figure out how to get the non-commutative operator ** to do the thing, but I wasn't able to get it to perform inverses (setting A = Log[a,1] just reduces A to 0, which gives an inverse for all symbols, which is overkill). I didn't get that much deeper into defining non-standard algebraic operators. I had fun thinking about it though.

Solution:

adventString = 
  Import["day5.txt", "String"];
ReactString[string_] := Module[
  {mappings = 
    Map[RegularExpression[#] -> "" &, 
     Join[Map[StringJoin[#, ToUpperCase[#]] &, 
       CharacterRange["a", "z"]],
      Map[StringJoin[#, ToLowerCase[#]] &, 
       CharacterRange["A", "Z"]]]]},
  FixedPoint[StringReplace[#, mappings] &, string]
  ]
Print["Part 1 Answer: ", StringLength@ReactString[adventString]]
t = Map[
   StringLength@
     ReactString@
      StringReplace[adventString, {# -> "", ToUpperCase[#] -> ""}] &, 
   CharacterRange["a", "z"]];
Print["Part 2 Answer: ", Min[t]]

1

u/juzmark Dec 20 '18 edited Dec 20 '18

Ruby - Looking for feedback. Thank you!

input_array = File.read('input.txt').chomp.split("")

def scan_and_delete_array(a)
  result = []
  a.each do |c|
    if result[-1] == c.swapcase
      result.pop
    else
      result << c
    end
  end
  result.length
end

# Part 1
puts scan_and_delete_array(input_array)

# Part 2
scanned_char = []
result_lengths = input_array.map do |c|
  if scanned_char.include?(c)
    next
  else
    scanned_char << c
    scan_and_delete_array(input_array - [c.downcase] - [c.upcase])
  end
end

puts result_lengths.compact.min

1

u/cerrosafe Dec 21 '18

Lua

I'm still behind by a lot. Still enjoying myself and learning Lua. My solution is a brute-force approach that repeatedly reacts the input until nothing happens. I did figure out the part 2 optimization of using the reacted string.

I stripped all the comments.

input = "inputs/day5.txt"

function is_upcase(charcode)
   return charcode > 64 and charcode < 91
end

function is_lowcase(charcode)
   return charcode > 96 and charcode < 123
end

function do_characters_match(lcharcode, rcharcode)
   return math.abs(lcharcode - rcharcode) == case_difference
end

function select_characters(lastbyte, thisbyte)
   return
      ((is_upcase(thisbyte) and is_lowcase(lastbyte)) or
       (is_lowcase(thisbyte) and is_upcase(lastbyte)))
      and
      do_characters_match(lastbyte, thisbyte)
end

function chunk_string(str)
   local increment = 5000
   local start = 1
   local strings = {}
   repeat
      local bytes = { string.byte(str, start, start+increment) }
      for index, charcode in ipairs(bytes) do
         table.insert(strings, charcode)
      end
      start = start+increment+1
   until start > #str
   return strings
end

function filter_bytes_table(tbl)
   repeat
      local deleted = 0
      for index, charcode in ipairs(tbl) do
         local nextcharcode = tbl[index+1] or 0
         if select_characters(charcode, nextcharcode) then
            table.remove(tbl, index)
            table.remove(tbl, index)
            deleted = deleted + 1
         end
      end
   until deleted == 0
end

do
   local line = ""
   for inline in io.lines(input) do
      line = inline
   end

   local tbl = chunk_string(line)
   local case_difference = 32

   filter_bytes_table(tbl)

   local reduced_string = ""
   for index, charcode in ipairs(tbl) do
      reduced_string = reduced_string .. string.char(charcode)
   end

   part1 = reduced_string
   print("Part 1: " .. #reduced_string)
end

do
   local bestlen, bestpair = nil, nil
   letters = { "Aa"; "bB"; "cC"; "dD"; "eE"; "fF"; "gG"; "hH"; "iI"; "jJ"; "kK"; "lL";
               "mM"; "nN"; "oO"; "pP"; "qQ"; "rR"; "sS"; "tT"; "uU"; "vV"; "wW"; "xX";
               "yY"; "zZ"; }
   local filtered = ""
   for index, pair in ipairs(letters) do
      local filtered_str = string.gsub(part1, "[" .. pair .. "]", "")
      local filtered_tbl = chunk_string(filtered_str)
      filter_bytes_table(filtered_tbl)
      filtered = ""
      for index, charcode in ipairs(filtered_tbl) do
         filtered = filtered .. string.char(charcode)
      end
      if bestlen == nil then bestlen, bestpair = #filtered, pair
      elseif #filtered < bestlen then bestlen, bestpair = #filtered, pair
      end
   end
   print("Part 2: " .. bestlen)
end

1

u/LegendaryB3ast Dec 25 '18

Python 3

"""Day 5: Alchemical Reduction"""
from aoctools import Data, print_ans

import itertools
import re
from string import ascii_lowercase as letters

data = Data.fetch(day=5, year=2018)

def pairwise(x):
    """Returns sequence (s0, s1), (s1, s2)..."""
    a, b = itertools.tee(x)
    next(b, None)
    return zip(a, b)

def react(seq):
    last_polymer = seq
    while True:
        if last_polymer in polymer_dict:
            polymer = polymer_dict[last_polymer]
        else:
            sequence = iter(pairwise(last_polymer))
            reduced = []
            for pair in sequence:
                if pair[0] == pair[1].swapcase():
                    next(itertools.islice(sequence, 1, 1), None)
                else:
                    reduced.append(pair[0])
            else:
                reduced.append(pair[1])
            polymer = ''.join(itertools.chain(*reduced))
            polymer_dict[last_polymer] = polymer
        if polymer == last_polymer:
            break
        last_polymer = polymer
    return len(last_polymer)
result = react(data)
print_ans('5a', result)

min_length = float('inf')
for letter in letters:
    to_remove = letter + letter.upper()
    start = re.sub(f'[{to_remove}]', '', data)
    length = react(start)
    if length < min_length:
        min_length = length
print_ans('5b', min_length)

[Card] : Five golden strings!

1

u/lucbloom Dec 30 '18

Ok, sorry. Must’ve been measuring wrong. Still glad to see C programmers being concerned about performance :-)

1

u/usesbiggerwords Oct 26 '21

Not terribly clever, but fast on my potato (Python 3):

reactions = {x: x.upper() for x in 'abcdefghijklmnopqrstuvwxyz'}
reactions.update({x.upper(): x for x in reactions})

def react(sample, reactions):
start = 0
width = 2
end = start + width
while sample:
    window = sample[start:end]
    rxn = reactions[window[0]]
    if window[1] == rxn:
        sample = sample[:start] + sample[end:]
        start = max(start - 1, 0)
        end = start + width
    else:
        start += 1
        end = start + width
    if end > len(sample):
        break
return len(sample)

for polymer in polymers:
    start = 0
    width = 2
    end = start + width
    sample = polymer[:]
    print('part 1: ', react(sample, reactions))
    reductions = [(k, sample.replace(k, '').replace(v, '')) for k, v in reactions.items()]
    final = [react(sample[1], reactions) for sample in reductions]
    print('part 2: ', min(final))

1

u/lucbloom Dec 05 '18 edited Dec 05 '18

C implementation. Executes Part 2 in 0.13 msec.

static char* readFile(const char* fileName)
{
	char* buffer = nullptr;
	FILE* file = fopen(fileName, "rb");
	if (file)
	{
		fseek(file, 0, SEEK_END);
		size_t siz = ftell(file);
		buffer = (char*)malloc(siz+1);
		if (buffer)
		{
			fseek(file, 0, SEEK_SET);
			fread(buffer, 1, siz, file);
			buffer[siz] = '\0';
		}
		fclose(file);
	}
	return buffer;
}

static uint64_t getTime()
{
#define WINDOWS_TICK (100*100) // ns to ms
#define MSEC_TO_UNIX_EPOCH (1000*60*60*24*134774ULL) // 134774 days
	FILETIME fileTime;
	::GetSystemTimeAsFileTime(&fileTime);
	uint64_t windowsTicks = static_cast<__int64>(fileTime.dwHighDateTime) << 32 | fileTime.dwLowDateTime;
	windowsTicks = windowsTicks / WINDOWS_TICK - MSEC_TO_UNIX_EPOCH;
	return windowsTicks;
}

int main()
{
	uint64_t t1 = getTime();

	char* inputStart = readFile("C:/development/zooi/bgtools/input.txt");
	char* output = (char*)malloc(50000+1);
	int remains = MAX_INT;
	for (int i = 0; i < 1000; ++i)
	{
		for (int c = 'a'; c <= 'z'; ++c)
		{
			char* input = inputStart;
			char* cur = output;
			char e;
			while ((e = *input))
			{
				if (e != c && e != c - 'a' + 'A')
				{
					if (cur <= output || abs(*(cur-1) - e) != 0x20)
					{
						*cur = e;
						++cur;
					}
					else
					{
						--cur;
					}
				}
				++input;
			}
			if (cur - output < remains)
			{
				remains = cur - output;
			}
		}
	}
	uint64_t t2 = getTime();
	uint64_t t = t2 - t1;
	free(output);
	free(inputStart);

	printf(str, "Time: %I64u/1000 ms. Remains: %d", t, remains);

	return 0;
}
→ More replies (2)