LOADING: An error occurred. Update Chrome, try Firefox, or visit this post for more details.

⚠️Reddit changed how removals work, which breaks Reveddit's website. Install the extension to track removed content:Add to chromeAdd to firefoxWhat changed?
✖︎
about reveddit
⚙F.A.Q.add-ons
r/
status
copy sharelink
[+] show filters
46
SOLUTION MEGATHREAD-🎄- 2021 Day 16 Solutions -🎄-(self.adventofcode)
submitted 4 years, 1 month ago* (edited 27 minutes after) by daggerdragon to /r/adventofcode (134.8k)
679 commentsredditother-discussionssubreddit-indexmessage modsop-focus

NEW AND NOTEWORTHY

DO NOT POST SPOILERS IN THREAD TITLES!

  • The only exception is for `Help...

... view full text

since 4 years, 1 month ago
5 of 5

Tip Reveddit Real-Time can notify you when your content is removed.

your account history
(check your username's removed content. why?)
Tip Check if your account has any removed comments.
view my removed comments
you are viewing a single comment's thread.
view all comments
[–][deleted]2 points4 years, 1 month ago* (edited 34 minutes after)

Pure Java

Recursive function with a global bit index. I used BiFunctions to list the mathematical operations so I didn't have to use an ugly switch statement. Be aware that this type of code is not thread-safe, I was going for conciseness.

For part 2 I got all the examples correct, but got a 'too low' answer on the real data. It turned out that you shouldn't use == on two Integer objects. I thought they would be auto-unboxed but I guess not? Anyway, lesson learned. Thank goodness IntelliJ warned me of the issue because I would have been searching forever.

https://github.com/arjanIng/advent2021/blob/main/src/advent/Day16.java

List<BiFunction<Long, Long, Long>> operations = new ArrayList<>();

public void day16(String filename) throws IOException {
    String input = Files.lines(Paths.get(filename)).collect(Collectors.toList()).get(0);

    operations.add(Long::sum);
    operations.add((a, b) -> a * b);
    operations.add((a, b) -> a < b ? a : b);
    operations.add((a, b) -> a > b ? a : b);
    operations.add((a, b) -> null);
    operations.add((a, b) -> a > b ? 1L : 0L);
    operations.add((a, b) -> a < b ? 1L : 0L);
    operations.add((a, b) -> a.equals(b) ? 1L : 0L);

    StringBuilder sbuilder = new StringBuilder(new BigInteger(input, 16).toString(2));
    if (input.startsWith("0")) {
        sbuilder.insert(0, "0000");
    }
    if (sbuilder.length() % 4 != 0) {
        int add = (sbuilder.length() / 4 + 1) * 4 - sbuilder.length();
        for (int i = 0; i < add; i++) sbuilder.insert(0, "0");
    }

    long result = calculate(sbuilder.toString());
    System.out.printf("Part 1: %d%n", versionSum);
    System.out.printf("Part 2: %d%n", result);
}

int versionSum = 0;
int pos = 0; // not thread safe!
public long calculate(String sbits) {
    int version = Integer.parseInt(sbits.substring(pos, pos + 3), 2);
    int typeId = Integer.parseInt(sbits.substring(pos + 3, pos + 6), 2);
    versionSum += version;
    pos += 6;
    if (typeId == 4) {
        boolean last = false;
        StringBuilder data = new StringBuilder();
        while (!last) {
            String part = sbits.substring(pos, pos + 5);
            if (part.startsWith("0")) last = true;
            data.append(part.substring(1));
            pos += 5;
        }
        return Long.parseLong(data.toString(), 2);
    } else {
        int lengthTypeId = Integer.parseInt(sbits.substring(pos, pos + 1), 2);
        int l = lengthTypeId == 0 ? 15 : 11;
        int length = Integer.parseInt(sbits.substring(pos + 1, pos + 1 + l), 2);
        pos += l + 1;
        List<Long> results = new ArrayList<>();
        if (lengthTypeId == 0) {
            while (length > 0) {
                int start = pos;
                results.add(calculate(sbits));
                length -= (pos - start);
            }
        } else {
            for (int i = 0; i < length; i++) {
                results.add(calculate(sbits));
            }
        }
        return results.stream().reduce((a, b) -> operations.get(typeId).apply(a, b)).orElseThrow();
    }
}
permalinkhide replies (1)as-of
[–]SadBunnyNL2 points4 years, 1 month ago

I'm curious. I am not well versed in all changes betwee modern Java versions, but for me,

Integer xxx = (Integer) Integer.valueOf(1);
Integer yyy = (Integer) Integer.valueOf(1);
// Integer xxx = new Integer(1); // or this way, same result
// Integer yyy = new Integer(1); // ...
System.out.println(System.getProperty("java.version"));
System.out.println(xxx == yyy);
System.out.println(xxx != yyy);
System.exit(0);

... returns 'true', then 'false' (as expected) for both jdk 11.0.13 and 17.0.1.

Although IntelliJ does indeed warn about the == and !=, it still works as you would expect for integers apparently.

Which version are you on? Maybe it's old behaviour?

Maybe more experienced Javans could elaborate.

permalinkparentcontexthide replies (2)author-focusas-ofpreserve
[–]Fyvaproldje3 points4 years, 1 month ago

Try Integer.valueOf(99999999)

AFAIR, Java preallocates boxed small numbers, so Integer.valueOf(1) indeed always returns the same result, but for bigger numbers it allocates a new one instead. As a side effect, by some magic tricks it's possible to change the value of an integer, and Integer.valueOf(1) will now return 2.

So in general case, it's not safe to compare them with ==

permalinkparentcontexthide replies (1)author-focusas-ofpreserve
[–]SadBunnyNL2 points4 years, 1 month ago

I tried it, and you're right. It works only from -128 to 127 (so, signed byte).

That's quite the gotcha. Good guy IntelliJ I guess :)

permalinkparentcontextauthor-focusas-ofpreserve
[–][deleted]1 point4 years, 1 month ago* (edited 55 minutes after)

Apparently it only works with small Integers due to caching, which is why the examples worked.

https://javarevisited.blogspot.com/2010/10/what-is-problem-while-using-in.html#axzz7FCcSsdE4

Oh, and pro-tip: learn to avoid using System.exit() unless you absolutely have no other choice. You can crash a server with that.

permalinkparentcontextas-of
r/revedditremoved.substack.com
🚨 NEWS 🚨
✖︎

Important: Reddit Changed How Removals Work

A recent Reddit update makes mod-removed content disappear from profile pages, which breaks Reveddit's website.

Install the browser extension to receive removal alerts.

Add to chromeAdd to firefox

What changed?

r/revedditremoved.substack.com