advent of code day 3: i might be r-slurred edition

idk how to do multi line spoilers lol



letters = ['','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', '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']

total_score = 0

team = []

for line in open("input.txt"):
    team.append(line.strip())

for i in range(2, len(team), 3):
    for letter in team[i]:
        if letter in team[i-2] and letter in team[i-1]:
            total_score += letters.index(letter)
            break

print(total_score)

some real caveman shit but it works

80
Jump in the discussion.

No email address required.

here's my... verbose solution (debugging code :marseyscratch: removed)

from string :marseyyarn: import ascii_lowercase, ascii_uppercase
from y2022.scaffold import *

class Day03(Day):
	def __init__(self):
		super()
	
	@property
	def day(self): return :marseymonke: 3

	def prepare_data(self) -> Any:
		return [(take(x, int(len(x) / 2)), skip(x, int(len(x) / 2))) for x in self.get_data().split('\n')]

	def prepare_data2(self) -> Any:
		return self.get_data().split('\n')

	PRIORITIES = {}

	def a(self):
		data = self.prepare_data()
		y = 1
		for x in ascii_lowercase:
			self.PRIORITIES[x] = y
			y += 1
		for x in ascii_uppercase:
			self.PRIORITIES[x] = y
			y += 1
		sum = 0
		for sack in data:
			if len(sack[0]) == 0: continue
			item3 = None
			found = False
			for item in sack[0]:
				for item2 in sack[1]:
					if item == item2:
						item3 = item
						found = True
						break
				if found: break
			sum += self.PRIORITIES[item3]
		print(sum)
	
	def b(self):
		data = self.prepare_data2()
		i = 0
		sack1 = None
		sack2 = None
		sack3 = None
		item = None
		sum = 0
		for i in range(0, len(data) - 3, 3):
			sack1 = data[i]
			sack2 = data[i + 1]
			sack3 = data[i + 2]
			for x in sack1:
				if not x in sack2: continue
				if not x in sack3: continue
				item = x
				break
			sum += self.PRIORITIES[item]
		print(sum)
Jump in the discussion.

No email address required.

I love the marsify inserts lmao

rdrama turing complete when

Jump in the discussion.

No email address required.

function compile(program) {
  let tape       = Array(100).fill(0);
  let ptr        = 0;
  let isLooping  = false;
  let loopStack  = [];
  let innerLoops = 0;

  for( i = 0; i < program.length; i++ ) {

  const char = program[i];

    if(isLooping) {
      if(char === "[") innerLoops++;
        if(char === "]") {
          if(innerLoops === 0) isLooping = false;
          else innerLoops--;
        }
      continue;
    }

    switch(char){
      case ':marseylove:':
        tape[ptr]++;
        break;
      case ':marseyraging:':
        tape[ptr]--;
        break;
      case ':marseycry:':
        tape[ptr] = prompt()[0].charCodeAt()
        break;
      case ':marsey:':
        console.log(String.fromCharCode(tape[ptr]));
        break;
      case ':marseyhmmm:':
        ptr++;
        tape[ptr] = tape[ptr] || 0;
        break;
      case ':marseygigaretard:':
        ptr--;
        tape[ptr] = tape[ptr] || 0;
        break;
      case ':chudsey:':
        tape[ptr] === 0 
          ? isLooping = true
          : loopStack.push(i);
        break;
      case ':marseytrans2:':
        tape[ptr] !== 0
          ? i = loopStack[loopStack.length-1]
          : loopStack.pop();
        break;
      default:
        break;
      }
    }
}
Jump in the discussion.

No email address required.

Hello World:

:marseylove::marseylove::marseylove::marseylove::marseylove::marseylove::marseylove::marseylove::marseylove::marseylove::chudsey::marseyhmmm::marseylove::marseylove::marseylove::marseylove::marseylove::marseylove::marseylove::marseyhmmm::marseylove::marseylove::marseylove::marseylove::marseylove::marseylove::marseylove::marseylove::marseylove::marseylove::marseyhmmm::marseylove::marseylove::marseylove::marseyhmmm::marseylove::marseygigaretard::marseygigaretard::marseygigaretard::marseygigaretard::marseyraging::marseytrans2::marseyhmmm::marseylove::marseylove::marsey::marseyhmmm::marseylove::marsey::marseylove::marseylove::marseylove::marseylove::marseylove::marseylove::marseylove::marsey::marsey::marseylove::marseylove::marseylove::marsey::marseyhmmm::marseylove::marseylove::marsey::marseygigaretard::marseygigaretard::marseylove::marseylove::marseylove::marseylove::marseylove::marseylove::marseylove::marseylove::marseylove::marseylove::marseylove::marseylove::marseylove::marseylove::marseylove::marsey::marseyhmmm::marsey::marseylove::marseylove::marseylove::marsey::marseyraging::marseyraging::marseyraging::marseyraging::marseyraging::marseyraging::marsey::marseyraging::marseyraging::marseyraging::marseyraging::marseyraging::marseyraging::marseyraging::marseyraging::marsey::marseyhmmm::marseylove::marsey::marseyhmmm::marsey:

Jump in the discussion.

No email address required.

Does nobody know what a set is?

Jump in the discussion.

No email address required.

A set is a list that doesn’t have any duplicates in it.

Jump in the discussion.

No email address required.

Imagine not doing it in k you fucking retards:

l:0:"i.txt"
i:{x^x^y}
t:+/(58!-96+)'
t@(*i/2 0N#)'l
t@(*i/)'0N 3#l

Le edit: WHY DOES CODEBLOCKS HAVE EMOJIS ENABLED @Jinglevann YOU FUCKING RETARD NO WONDER YOU CODE IN PYTHON

Jump in the discussion.

No email address required.

fixed, rude BIPOC

Jump in the discussion.

No email address required.

Thank you cutie sorry I was drunk when I solved and then wrote that. :marseycapylove:

Jump in the discussion.

No email address required.

its okay bb :marseylove:

Jump in the discussion.

No email address required.

still borked in preview : shows shit like <img class="emoji " src="/e/3.webp">, but the post itself is fine

Jump in the discussion.

No email address required.

fixed king

Jump in the discussion.

No email address required.

:#chadthankskingcapy:

Jump in the discussion.

No email address required.

:#0:

Jump in the discussion.

No email address required.

:#marseycapymad:

Jump in the discussion.

No email address required.

what's the big O of that?

Jump in the discussion.

No email address required.

If you can't tell from just looking at it, Arthur Whitney will die. :marseysulk:

Jump in the discussion.

No email address required.

i really can't man, that's y I asked.

is this o(n) or worse?

cause if it's worse, alan will roll over in is grave WHEN WILL THE INHUMANITY EVER END?! :marseydizzy:

Jump in the discussion.

No email address required.

sum([' abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.find(asdasd) for asdasd in [next(iter(set(chuck[0]).intersection(chuck[1]))) for chuck in [(sneed[int(len(sneed)/2):], sneed[:int(len(sneed)/2)]) for sneed in [line.strip('\n') for line in open('input').readlines()]]]])

sum([" abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".find(chuck) for chuck in [next(iter(set(sneed[0]).intersection(sneed[1], sneed[2]))) for sneed in [open('input').read().split('\n')[:-1][i:i+3] for i in range(0, len(open('input').readlines()[:-1]), 3)]]])

:#marseyfuckyou:

Jump in the discussion.

No email address required.

Part 1:

print(sum([set([a - 0x60 if a > 0x60 else a - 0x26 for a in bytes(l[0:int(len(l)/2)],'ascii') if a in bytes(l[int(len(l)/2):],'ascii')]).pop() for l in open('resources/day3.txt').readlines()]))
Jump in the discussion.

No email address required.

did a :marseyfortuneteller: steal your enter key?

Jump in the discussion.

No email address required.

Part 2:

print(sum((ord(set([c for c in g[0] if c in g[1] and c in g[2]][:-1]).pop()) + 20) % 58 for g in [ open('eval/day3part2.txt').readlines()[blk:blk+3] for blk in range(0,len(open('eval/day3part2.txt').readlines()),3)]))

There's probably a one-liner for chunking file.readlines() while only reading the file once (probably somewhere in itertools), but I'm done for today.

Part 1 using modulus and removing a few unnecessary iterator-to-list conversions:

print(sum(set((a + 20) % 58 for a in bytes(l[0:int(len(l)/2)],'ascii') if a in bytes(l[int(len(l)/2):],'ascii')).pop() for l in open('eval/day3part1.txt').readlines()))
Jump in the discussion.

No email address required.

I'm glad I wasn't the only one who had to open the file twice. Felt like it was dumb just to get the file length :marseydunce: but I guess you gotta

Jump in the discussion.

No email address required.

Darn btfo my 1 liner

Jump in the discussion.

No email address required.

:marseynotes:

Jump in the discussion.

No email address required.

Basically the same as Geese's grugbrained tbh. … ALSO: Once again wondering who 986674 and 2339424 are :marseypregunta:

def _priority(self, itm):
    if ord(itm) > ord('Z'):
        return ord(itm) - ord('a') + 1
    return ord(itm) - ord('A') + 27

def run_a(self, data):
    acc = 0
    for l in data:
        sz = len(l) // 2
        ca, cb = l[0:sz], l[sz:len(l)]
        for x in ca:
            if x in cb:
                acc += self._priority(x)
                break
    return acc

def run_b(self, data):
    acc = 0
    for i in range(len(data) // 3):
        for x in data[3*i]:
            if x in data[3*i + 1] and x in data[3*i + 2]:
                acc += self._priority(x)
                break
    return acc
Jump in the discussion.

No email address required.

I keep setting ORD values using absolute numbers because I'm r-slurred and forget I can feed the char itself in. I'm hoping seeing you do it properly will shock some sense into me.

Jump in the discussion.

No email address required.

i am 2339424

Jump in the discussion.

No email address required.

:marseyno: ord() + offset

:marseyyes: letters = ['','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', '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']

Jump in the discussion.

No email address required.

i think ord is the wrong way around. caps are first in ASCII but in advent of code they are last.

theoretically you could do this

get_num = lambda letter : (ord(letter)-97 if letter.islower() else ord(letter)-65+26)+1
for i in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ':
    print(get_num(i))

result is numbers 1-52

Jump in the discussion.

No email address required.

it looks r-slurred but it was the first thing i thought of and I already have macros set up for the quoting and changing the case so it only really took as long as typing out the lowercase alphabet

looking back i should have just made it a string and saved on the commas

Jump in the discussion.

No email address required.

First 3 days in GNU APL:

⍝ ~~~ Day 1 ~~~ ⍝

r←⊢⎕FIO[49] 'day1raw.txt'
e←+/¨⍎¨¨r⊂⍨,⍉⊃0≠⍴¨r ⋄ ⌈/e ⋄ +/3↑e⌷⍨⊂⍒e

⍝ ~~~ Day 2 ~~~ ⍝

k←⊂(,'ABC'∘.{⍺' '⍵}'XYZ')⍳⊢⎕FIO[49]'2'
+/k⌷4 8 3 1 5 9 7 2 6 ⋄ +/k⌷3 4 8 1 5 9 2 6 7

⍝ ~~~ Day 3 ~~~ ⍝

r←⊢⎕FIO[49] 'day3raw.txt'
p←'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
+/p⍳↑¨({⍵↑⍨2÷⍨⍴⍵}¨r)∩¨{⍵↑⍨2÷⍨⍴⍵}¨⌽¨r ⋄ +/p⍳↑¨⊃∩/¨r⊂⍨3/⍳↑3÷⍨⍴r
Jump in the discussion.

No email address required.

genuinely keep yourself safe

Jump in the discussion.

No email address required.

What the god darn heck is going on here

Also whatever this is someone do it in Haskell so I spend five hours looking at it just to get more and more and more pissed off at having the wrong flavour of autism

Jump in the discussion.

No email address required.

:marseyrandom:

Jump in the discussion.

No email address required.

Sigh

There are people in the world who would look at that and say how beautiful and elegant it is

It just makes me seethe

I really don't know how they manage to visualise it all in their heads without getting lost

Jump in the discussion.

No email address required.

It's similar to people who think Common Lisp is pretty. It's really just a very acquired taste, and IMO i doubt many people these days really think it looks pretty and just fake it.

Lisp looks fricking ugly as heck lol, and it's unusable without a good text editor (Emacs usually), which, in my honest opinion, is a sign of an imperfect language if you need another tool to even write it effectively. Yet I see lots of neurodivergents saying it's like the Mona Lisa of programming languages (its functionally cool in theory, but it still looks fricking ugly)

Jump in the discussion.

No email address required.

:marseyrandom:

Jump in the discussion.

No email address required.

sexp lole! xD xP shits all over the carpet

Jump in the discussion.

No email address required.

>good text editor (Emacs usually)

Nice bait :marseyclapping:

Jump in the discussion.

No email address required.

it is a remarkable text editor :marseyhappytears:

Jump in the discussion.

No email address required.

I had to learn it for one of my classes it was so gay and Jewish

Jump in the discussion.

No email address required.

It isn't one I've encountered. I have a degree in Computer Science but I'm not rabidly enthusiastic about the subject enough to have tried every single language there is like some people seem to do.

To me, it's like... I'll pick from the box that will let me get the job done in the simplest and most effective manner. Most of the time that's going to be whatever's currently most popular in the sector you're targeting because that's where you'll find the most supportive/active community and the largest variety of libraries and examples. When you're pushing into performance limited areas or going from a prototype to something business you might want to refactor for something more performant or more optimised for that specific type of processing.

I don't really get these people who always want to be working with the absolute bleeding edge language and who are always evangelizing it. It just seems so exhausting.

Jump in the discussion.

No email address required.

:#marseysus: :#chadbasedcapy:

Jump in the discussion.

No email address required.

what the frick is ⍝

Jump in the discussion.

No email address required.

sus

Jump in the discussion.

No email address required.

How the FRICK do you and the K guy who posted earlier understand this shit?!

Jump in the discussion.

No email address required.

Just for you, day 3:

raw←⊢⎕FIO[49] 'day3raw.txt'     ⍝ Text file as array of strings.
priorities←'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

first←{⍵↑⍨2÷⍨⍴⍵}¨raw            ⍝ First half of each string.
last←{⍵↑⍨2÷⍨⍴⍵}¨⌽¨raw          ⍝ Last half of each string (flips the string and applies the same function).
both←last∩¨first                ⍝ Intersection ∩ to find char in both string halves.
a←+/priorities⍳↑¨both           ⍝ Map each char to index in priorities, find sum.

mask←3/⍳↑3÷⍨⍴raw                ⍝ Array 1 1 1 2 2 2 3 3 3 ... 100 100 100.
groups←mask⊂raw                 ⍝ Split raw into groups of 3 using mask array.
badges←↑¨⊃∩/¨groups             ⍝ Intersection to find char common to all group members.
b←+/priorities⍳badges           ⍝ Map each char to index in priorities, find sum.

a b                             ⍝ Print answers.

Evaluation is simple (right to left, no priority BS) so writing one-liners comes naturally. Much easier to keep track of than half the answers itt triggering longpostbot.

Jump in the discussion.

No email address required.

mine was similar

import string

TRANS_LIVES_MATTER = [None]
TRANS_LIVES_MATTER.extend(letter for letter in string.ascii_lowercase)
TRANS_LIVES_MATTER.extend(letter for letter in string.ascii_uppercase)

with open("day3input.txt") as f:
    rucksacks = f.read().split("\n")

# task 1

value = 0

for rucksack in rucksacks:
    i = int(len(rucksack)/2)
    compartments = (rucksack[:i], rucksack[i:])
    for item in compartments[0]:
        if item in compartments[1]:
            value += TRANS_LIVES_MATTER.index(item)
            break

print(value)

# task 2

value = 0

for i in range(0, len(rucksacks), 3):
    group = tuple(set(rucksack) for rucksack in rucksacks[i:i+3])
    badge = ("".join(group[0].intersection(group[1], group[2])))
    value += TRANS_LIVES_MATTER.index(badge)

print(value)
Jump in the discussion.

No email address required.

intersection()-cels rise up.

Jump in the discussion.

No email address required.

:#cap: :marseykneel#:

Jump in the discussion.

No email address required.

zoz

Jump in the discussion.

No email address required.

zle

Jump in the discussion.

No email address required.

zozzle

Jump in the discussion.

No email address required.

c++ Part one


int charToPriority(char c)
{
    if (c >= 'a' && c <= 'z') return c - 'a' + 1;
    if (c >= 'A' && c <= 'Z') return c - 'A' + 27;
}

char priorityToChar(int c) {
    if (c < 27) return c + 'a' - 1;
    return c + 'A' - 27;
}

int partOne()
{
    std::cout << "Day 3" << '\n';

    std::ifstream file("input.txt");
    std::string line;

    int score{ 0 };


    while (std::getline(file, line)) {
        std::unordered_map<char int=""> left;
        int n = line.size();
        for (int i{ 0 }; i < n / 2; i++) {
            if (!left[line[i]]) left[line[i]] = 1;
        }
        for (int j = n / 2; j < n; j++) {
            if (left[line[j]] > 0) {
                score += charToPriority(line[j]);
                left[line[j]]--;
            }
        }
    }

    file.close();
    
    return score;
}

</char>

Part two




int partTwo()
{
    std::cout << "Day 3 Part Two" << '\n';

    std::ifstream file("input.txt");
    std::string elf1;
    std::string elf2;
    std::string elf3;

    int score{ 0 };

    while (std::getline(file, elf1)std::getline(file, elf3)) {
        std::vector<int> storage(52);

        for (char c : elf1) storage[charToPriority(c) - 1] |= 0b001;
        for (char c : elf2) storage[charToPriority(c) - 1] |= 0b010;
        for (char c : elf3) {
            storage[charToPriority(c) - 1] |= 0b100;
            if (storage[charToPriority(c) - 1] == 0b111) {
                score += charToPriority(c);
                break;
            }
        }
    }

    file.close();

    return score;
}
</int>

Maybe i should just have just taken the o(n^2) pill and do it with 'in'.

Jump in the discussion.

No email address required.

congrats on using a sane language that dosent store everything in unicode by default :marseycry:

Jump in the discussion.

No email address required.

Dont initialize your integers like that, it makes you look like a total fu cking tool. Also, use size_t and ++i in your for loop.

Jump in the discussion.

No email address required.

>don't initalise your integers as reccomended by C++22

you're the reason c++ has namespaces

Jump in the discussion.

No email address required.

C++22

Dude, C++ is on a 3-year cycle, C++17, C++20, C++23. SMH my head plebs pretending to know shit.

Primitive initialization has different behaviors than classes, so there's no reason you need to treat them the same way, even stylistically.

Also, the bigger issue is that awful noob-like for loop that borders on being wrong, not just stylistic differences.

Jump in the discussion.

No email address required.

Amazing parsing of code

![](/images/16700643198100007.webp)

![](/images/16700643556568546.webp)

Jump in the discussion.

No email address required.

you're fricking bananas if you think I'm reading all that, take my downmarsey and shut up idiot

Jump in the discussion.

No email address required.

Still pretty easy, these get hard in week two right? I've usually forgotten that I've sworn that it was definitely happening this year by then. Can't get the code formatting right so I'm pasting the screenshot.

![](/images/16700515346424248.webp)

Jump in the discussion.

No email address required.

Me in week 1: "that was fun, my only regret is that it was a bit too short"

Me in week 3: "please make it stop I can't take it anymore"

Jump in the discussion.

No email address required.

LONG POST ALERT, I'm actually kind of proud of the "contains" subfunction


package three

import (
	"bufio"
	"bytes"
	"fmt"
	"os"
)

func pos(ch byte) int {
	var alph string = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

	return (bytes.IndexByte([]byte(alph), ch) + 1)
}

func One() int {
	var deliver int

	fp, _ := os.Open("three.txt")
	defer fp.Close()

	rd := bufio.NewScanner(fp)

	for rd.Scan() {
		line := rd.Text()
		item_len := len(line) / 2
		left := make([]byte, item_len)
		right := make([]byte, item_len)

		for i, v := range line {
			if i < item_len {
				left[i] = byte(v)
			} else {
				i %= item_len
				right[i] = byte(v)
			}
		}

		for i, v := range left {
			if bytes.ContainsRune(right, rune(v)) {
				deliver += pos(left[i])
				break
			}
		}
	}

	return deliver
}

func Two() int {
	var deliver int
	elf := make(map[int]string)

	fp, _ := os.Open("three.txt")
	defer fp.Close()

	rd := bufio.NewScanner(fp)

	for e := 0; rd.Scan(); e++ {
		elf[e] = rd.Text()
	}

	contains := func(a string, b string, c string) (byte, error) {
		var master string
		var children []string

		if len(a) > len(b) && len(a) > len(c) {
			master = a
			children = []string{b, c}
		} else if len(b) > len(a) && len(b) > len(c) {
			master = b
			children = []string{a, c}
		} else {
			master = c
			children = []string{a, b}
		}

		for _, v := range master {
			var a_common, b_common byte

			if bytes.ContainsRune([]byte(children[0]), v) {
				a_common = byte(v)
			}
			if bytes.ContainsRune([]byte(children[1]), v) {
				b_common = byte(v)
			}

			if a_common == b_common && a_common > 0 {
				return a_common, nil
			}
		}

		return 'a', fmt.Errorf("no common????")
	}

	var elf_head int

	for g := 0; g < (len(elf) / 3); g++ {

		common, err := contains(elf[elf_head], elf[elf_head+1], elf[elf_head+2])

		if err == nil {
			deliver += pos(common)
		}

		elf_head += 3
	}

	return deliver
}
Jump in the discussion.

No email address required.

Jesse what the frick are you talking about??

Jump in the discussion.

No email address required.

static inline unsigned getPriority(char elem)
{
	if(elem >= 'a' and elem <= 'z')
		return elem - 'a' + 1;
	
	if(elem >= 'A' and elem <= 'Z')
		return elem - 'A' + 27;
	
	abort();
	return 0;
}

static inline std::vector<char> toVec(const std::string &str)
{
	std::vector<char> t;

	for (char const &c: str)
		t.push_back(c);


	std::sort(t.begin(), t.end());
	t.erase( unique( t.begin(), t.end() ), t.end() );

	return t;
}

int main()
{
	std::string rucksack;
	unsigned long long points = 0;
	size_t index = 0;
	std::vector<char> group_sacks[3];

	while(std::cin >> rucksack)
	{
		group_sacks[index] = toVec(rucksack);
		auto secondComp = toVec(rucksack.substr(rucksack.length() / 2));

		if(index == 2)
		{
			std::vector<char> i1, i2;
			std::set_intersection(
				group_sacks[0].begin(), group_sacks[0].end(),
				group_sacks[1].begin(), group_sacks[1].end(), 
				std::back_inserter(i1));
			
			std::set_intersection(
				group_sacks[2].begin(), group_sacks[2].end(),
				i1.begin(), i1.end(), 
				std::back_inserter(i2));
			
			for(char c: i2)
				points += getPriority(c);

			index = 0;
		}
		else
			index ++;
	}

	std::cout << points << std::endl;
}
Jump in the discussion.

No email address required.

Lol imagine using (((python)))

#include <stdio.h>

int main(void){
	FILE *f = fopen("input.txt","r");
	char buffer1[1024],buffer2[1024],buffer3[1024];
	int sum = 0;
	while(fgets(buffer1,1024,f) != NULL){
	fgets(buffer2,1024,f);
	fgets(buffer3,1024,f);
		int end1=0,end2=0,end3=0;
		while(buffer1[end1] != '\n')
			end1++;
		while(buffer2[end2] != '\n')
			end2++;
		while(buffer3[end3] != '\n')
			end3++;
		int done = 0;
		for(int i=0;i<=end1 && done == 0;i++){
			for(int j=0;j<=end2 && done == 0;j++){
				for(int k=0;k<=end3 && done == 0;k++){
					if(buffer1[i] == buffer2[j] && buffer1[i] == buffer3[k]){
						char q = buffer1[i];
						if( q >= 'A' && q <= 'Z' )
							sum += q - 38;
						else
							sum += q - 96;
						done = 1;
					}
				}
			}
		}
		
	}
	printf("%d\n",sum);
	fclose(f);
	return 0;
}
Jump in the discussion.

No email address required.

the rankings are based on how quick u are, using a scripting language is the obvious choice

Jump in the discussion.

No email address required.

I hate scripting languages :marseysad:

Jump in the discussion.

No email address required.

is that even faster

Jump in the discussion.

No email address required.

No

Jump in the discussion.

No email address required.

just curious, I'm not really interested

Jump in the discussion.

No email address required.

:marseyill:

Jump in the discussion.

No email address required.

Jump in the discussion.

No email address required.

Allah help me I have once again done some retarded shit

def priority(c):
    if ord(c) < 91:
        val = ord(c) - 90 + 52
    else:
        val = ord(c) - 122 + 26
    return val


file = open("input.txt")
sumval = 0
sumbadge = 0
line_number = 0
group_arr = [[],[],[]]
for line in file:
    line.rstrip()
    sack = [line[0:int(len(line)/2)], line[int(len(line)/2):len(line)]]
    group_arr[line_number % 3] = line[0:len(line)-1]
    sumval+=priority((set(sack[0]) & set(sack[1])).pop())
    if (line_number % 3 == 2):
        sumbadge+=priority((set(group_arr[0]) & set(group_arr[1]) & set(group_arr[2])).pop())
    line_number += 1
print(sumval)
print(sumbadge)

Jump in the discussion.

No email address required.

alright guys, here's my enterprise grade, production ready, world deployable ts answer. notice how type safe it is.

import * as fs from 'fs'`;

console.log(
  fs.readFileSync(process.argv[2], 'utf-8')
    .split('\n')
    .reduce((pl, l) => {
      let h: any = {};
      let ch = l.split('')
        .reduce((pc,c,i) => i<l.length/2 ? ((h[c]=1)&&0) : (pc||(h[c]?c.charCodeAt(0):0)), 0);
      return pl+ch-(ch<=90?38:96)
    }, 0)
);

PART 2, no declared vars. so let's get crunk

import * as fs from 'fs'`;

console.log(
  fs.readFileSync(process.argv[2], 'utf-8')
    .split('\n')
    .reduce(([pl, h], l, i) => [
      pl + l.split('').reduce((pc,c) => (
        i % 3 === 0 ? ((h[c]=1) &&0) : 
        i % 3 === 1 ? ((h[c]&&=2) &&0) :
        pc || (h[c]===2&&(c.charCodeAt(0)-(c.charCodeAt(0)<=90?38:96)))
      ) || 0, 0),
      i % 3 === 2 ? {} : h
    ], [0, {} as any])
);
Jump in the discussion.

No email address required.

>assigning variables inside a ternary operator inside a reduce function

This is pretty cool.

:#lemindblown:

Jump in the discussion.

No email address required.

is it very cool.

for maximum coolness, make sure to do it whenever and wherever possible.

:marseyokay:

Jump in the discussion.

No email address required.

Anyone else doing javascript?

/* Part 1 */
function sackPriority(sack) {
    if (!sack.length) return 0;

    var count = Math.floor(sack.length/2);
    var left = sack.substr(0,count);
    var right = sack.substr(count);

    for (var i=0;i<count;i++) {
        var c = left.charAt(i);
        if (right.indexOf(c) >= 0) {
            return (left.charCodeAt(i) >= 97) 
                ? left.charCodeAt(i) - 96 : left.charCodeAt(i) - 38;
        }
    }
}


var total = sacks.reduce(function(acc,cur) {
    return acc + sackPriority(cur);
},0);


/* Part 2 */
function badgeType(sacks) {
    if (!sacks[0].length) return 0;
    for (var i=0;i<sacks[0].length;i++) {
        var c = sacks[0].charAt(i);
        if (sacks[1].indexOf(c) >= 0
                && sacks[2].indexOf(c) >= 0) {
            return (sacks[0].charCodeAt(i) >= 97) 
                ? sacks[0].charCodeAt(i) - 96 : sacks[0].charCodeAt(i) - 38;            
        }
    }
}


var total = 0;
for (var j=0;j<sacks.length;j+=3) {
    total += badgeType(sacks.slice(j,j+3));
}
Jump in the discussion.

No email address required.

trying to learn python

vals=0
with open("03RucksackReorganization.txt","r") as lines:
    for line in lines:
        dropN=line.rstrip("\n")
        first, second=dropN[:len(dropN)//2], dropN[len(dropN)//2:]
        letters=set(first)
        for ch in second:
            if ch in letters:
                vals+=(ord(ch.lower())-ord('a')+1 + (0 if ch.lower() else 26))
                break
print(vals) 

and part two:

vals=0
with open("03RucksackReorganization.txt","r") as lines:
    index=0
    seen=set()
    for line in lines:
        sansN=line.rstrip("\n")
        if(index==0):
            seen=set(sansN)
        else:
            seen=seen.intersection(set(sansN))
        if(index==2):
            ch=seen.pop()
            vals+=(ord(ch.lower())-ord('a')+1 + (0 if ch.islower() else 26))
            seen.clear()
        index=(index+1)%3
print(vals)
Jump in the discussion.

No email address required.

Frick me, man...

Shouldn't have used sets

![](/images/1670093305971079.webp)

Edit:

Fixed it up a bit

![](/images/16700975683533356.webp)

Jump in the discussion.

No email address required.

jeez, and this is what they want to write linux out of next?

Jump in the discussion.

No email address required.

It's not usually this bad, this is just me being r-slurred

Jump in the discussion.

No email address required.

yeah man, maybe u should have just used a lookup array? tho, idk wtf ur doing really, so yeah.

Jump in the discussion.

No email address required.

For every 3 lines:

  1. one by one split them in half, put each half's characters in a set, find the set intersection i.e. the character that's present in both halves and get its value

  2. take all 3 lines and find the character that's present in all 3 also using sets and get its value

  3. the values get summed up in their respective variables, sum and sum2

It's a bit difficult if you don't know functional programming.

Also cleaned it up a bit:

![](/images/16700975227873366.webp)

Jump in the discussion.

No email address required.

fuk man, i wrote my solution in about 10 lines using js split and reduce, with one hashmap. if that's not "functional", then idc for whatever functional is.

but what ur doing is ... u don't need to put the 2nd half in another hashmap just so u can use builtins to find the intersection between the two, lol. u can just iterate over the 2nd half and as soon as u find a character in the hashmap of the 1st half .... that's ur "intersetion". i suppose the built-ins do that for u, but it doesn't look easier to me, and ur creating excess data structures.

but (2) is even more mind boggling. once u have the set intersection, that should be one character, and why do u ever need to make sure it's present in all 3?

Jump in the discussion.

No email address required.

u can just iterate over the 2nd half and as soon as u find a character in the hashmap of the 1st half .... that's ur "intersetion".

Well yeah, I could've but at this point it's a difference of a couple of lines at most so w/e.

and why do u ever need to make sure it's present in all 3?

Because that's the point of the puzzle?

In their example 'r' was the solution but if I did what you say, I'd also get 'f'

![](/images/16701063296668978.webp)

Jump in the discussion.

No email address required.

if only the problem was a couple extra lines.

and the insection itself guarantees it's in both sets, already. are r u doing additional searches to find something already known?

Jump in the discussion.

No email address required.

I'm not doing any additional searches, after the first intersection, the resulting set only has a few characters. That set is then intersected with the third one. It's not like I'm doing a triple for loop.

Jump in the discussion.

No email address required.

More comments
Jump in the discussion.

No email address required.

Commented out code is from part 1. I'm gonna be so fricked if I keep writing code like this when it gets difficult lmao

![](/images/16700700787749321.webp)

Jump in the discussion.

No email address required.

Part 1:

with open('input.txt') as f:
    lines = f.readlines()
    
items = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
score = 0

for line in lines:
    first, second = line.strip()[:len(line)//2], line[len(line)//2:]
    for char in first:
        if char in second:
            score += items.index(char) 
            break
print(score)
Jump in the discussion.

No email address required.

Part 2:

with open('input.txt') as f:
    lines = f.readlines()
    
items = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
score = 0

line_position = 0

while line_position < len(lines):
    for char in lines[line_position]:
        if char in lines[line_position + 1]:
            if char in lines[line_position + 2]:
                score += items.index(char) + 1
                line_position += 3
                break                    
print(score)
Jump in the discussion.

No email address required.

Late submission, but I was recovering from a hangover from a party last night so meh.

with open('day3_input.txt', 'r') as inp:
    foo = inp.read().split('\n')

def check(n):
    for a in n[:len(n)//2]:
        if a in n[len(n)//2:]:
            return a

def convert(c):
    val = ord(c)
    if val < 97:
        return val-38
    return val-96

total = 0
for f in foo:
    total += convert(check(f))
print(total)

def check2(a, b, c):
    for x in a:
        if x in b and x in c:
            return x

total = 0
for g in range(0, len(foo), 3):
    total += convert(check2(foo[g], foo[g+1], foo[g+2]))
print(total)
Jump in the discussion.

No email address required.

Euro Times.... Cant compete but do it any way:

with open('input03.txt') as file:
    lines = [line.rstrip() for line in file]

def get_priority(item):
    if item >= 97:
        item -= 96
    else:
        item -= 38
    return item

#a
count = 0
for line in lines:
    half = int(len(line)/2)
    first = line[:half]
    second = line[half:]
    intersection = set(first).intersection(set(second))
    item = ord(intersection.pop()) # looked up. Only one item per intersect
    priority = get_priority(item)
    count += priority
print(count)

#b
index = 0
count = 0
while index < len(lines):
    intersection = set(lines[index]).intersection(set(lines[index+1])).intersection(set(lines[index+2]))
    item = ord(intersection.pop())
    priority = get_priority(item)
    count += priority
    index += 3
print(count)

@AverageMistletoeEnjoyer intersection() gang gang

Jump in the discussion.

No email address required.

import string
from itertools import islice

priority = {c:i for i, c in enumerate(string.ascii_letters,1)}

# part 1
with open('./input.txt') as infile:
    score = 0
    for line in map(str.strip, infile):
        n = len(line) // 2
        a, b = set(line[:n]), set(line[n:])
        item = a.intersection(b)
        score += priority[item.pop()]
print(score)

# part 2
with open('./input.txt') as infile:
    score = 0
    lines = map(str.strip, infile)
    while g := list(islice(lines, 3)):
        a, b, c = map(set, g)
        item = a.intersection(b,c)
        score += priority[item.pop()]
print(score)
Jump in the discussion.

No email address required.

that's a pretty cool way to iterate over chunks, will steal

Jump in the discussion.

No email address required.

ruby is a wonderful language and so much more pleasant to script in than python

def part_one()
  sacks = File.read("input.txt").split

  compartments = sacks.map do |sack|
    sack.chars.partition.with_index { |_, i| i < sack.length / 2 }
  end

  shared_letters = compartments.map { |c| c.reduce(&:&) }.flatten
  summed_priorities(shared_letters)
end

def part_two()
  groups = File.read('input.txt').split.each_slice(3).to_a

  badges = groups.map do |sacks|
    sacks.map(&:chars).reduce(&:&)
  end.flatten

  summed_priorities(badges)
end

def summed_priorities(list)
  letters = ('a'..'z').to_a + ('A'..'Z').to_a
  priorities = Hash[(1..letters.size).zip(letters)].invert

  list.map { |l| priorities[l] }.reduce(&:+)
end

![](https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fflamingtext.com%2Fnet-fu%2Fproxy_form.cgi%3Fimageoutput%3Dtrue%26script%3Dalien-glow-anim-logo%26text%3Di%2520love%2520!YOU!%26doScale%3Dtrue%26scaleWidth%3D480%26scaleHeight%3D240)

Jump in the discussion.

No email address required.

Cursed Perl

I only did the first bit for now. Enjoy

#!/usr/bin/env perl
use utf8;
use warnings FATAL=>q
    ⍂taint⍂;
$_ = <<'BUSSY';
# file var named by my cat when i went 2 take a piss
owopen my $gyh89, '<', 'input' owor die $!;
my ($睷,$睸) = qw𑄑𑄑;
my $towotal = oword(\0);
while (<$gyh89>) {
    ($睷,$睸) = (substr($_, 0, $z = length($_) /2), substr($_, $z, -1));
    ZOWOZZLE: foworeach my $d (split(//, $睷))
    { foworeach (split(//, $睸))
      {
          if ($d eq $_)
          { $towotal += oword($_)-(oword($_)-97 > -1 ? 96 : 38);
            last ZOWOZZLE;
          }

      }
    }
}
return "Result: $towotal\n";
BUSSY
s/owo/o/g;
print eval;
Jump in the discussion.

No email address required.

That's one genuinely cool woman.

Jump in the discussion.

No email address required.

didn't see the thread, here's my matlab code :marseytunaktunak:

A = readlines("input.txt","EmptyLineRule","skip")';

item = @(x) intersect(x(1:end/2),x(end/2+1:end));
iterfunc1 = @(x) item(char(x));
iterfunc2 = @(x,y,z) intersect(intersect(char(x),char(y)),char(z));

str1 = cell2mat(arrayfun(iterfunc1,A,'UniformOutput',false));
str2 = cell2mat(arrayfun(iterfunc2,A(1:3:end),A(2:3:end),A(3:3:end),'UniformOutput',false));

res1 = sum(str1,2)-sum(38-(38-96)*(str1>=97),2);
res2 = sum(str2,2)-sum(38-(38-96)*(str2>=97),2);

fprintf("Part 1 : %d\n",res1)
fprintf("Part 1 : %d\n",res2)
Jump in the discussion.

No email address required.

:#marseychartscatter:

Jump in the discussion.

No email address required.

numbers numbers numbers, business business, (is this working?)

Jump in the discussion.

No email address required.

Link copied to clipboard
Action successful!
Error, please refresh the page and try again.