Unable to load image

Advent of code day 4 :marseysad:

This is the advent of code day 4 thread for bragging about your solution and bullying people who haven't gotten it yet :marseyill:

35
Jump in the discussion.

No email address required.

I ranked (((109))) on the global leaderboard for the first star. So close :marseygiveup:

![](/images/1670132950937097.webp)

Jump in the discussion.

No email address required.

Most of the top 100 are probably AI at this point.

Jump in the discussion.

No email address required.

this was the number one for the first few days, https://github.com/nim-ka

the top players according to the guy who runs it are people with pre-optimied libraries that don't even read the prompt and guess what they have to build, lots of them are involved with maintaining the site.

Jump in the discussion.

No email address required.

I'm currently 17 years old. I'm transgender and go by she/her pronouns. I'm starting my 2nd year of a computer science associate's at my local community college.

The west has fallen

![](/images/16701920805629456.webp)

Jump in the discussion.

No email address required.

17 years, Speedrunner, Train

:#marseytrain:

no brakes on the train!

Jump in the discussion.

No email address required.

Even "people" can't pass the turing test, these days

Jump in the discussion.

No email address required.

Man that string parsing functionality makes shit so easy.

Jump in the discussion.

No email address required.

lol, i have a life - i don't have time to sit around waiting for the clock to tick past to pound it out right that second.

Jump in the discussion.

No email address required.

my solution was so bad that im gonna rewrite it before posting so i dont look like even more of a mouthbreather than ppl already know i am

Jump in the discussion.

No email address required.

:#marseycheerup:

Jump in the discussion.

No email address required.

I do this :marseyderp:

Jump in the discussion.

No email address required.

I'm just not gonna post mine at all!

Jump in the discussion.

No email address required.

here was mine. i was off on a goose :marseygoose: chase for about 40 minutes finding a off by one error :marseybug2: (yes i was missing :marseymissing2: a + 1 in range())

from y2022.scaffold import *

class Day04(Day):
	def __init__(self):
		super()
	
	@property
	def day(self): return :marseymonke: 4

	def prepare_data(self) -> Any:
		data = self.get_data().splitlines()
		for i in range(0, len(data)):
			data[i] = data[i].split(',')
			data[i][0] = range(int(data[i][0].split('-')[0]), int(data[i][0].split('-')[1]) + 1)
			data[i][1] = range(int(data[i][1].split('-')[0]), int(data[i][1].split('-')[1]) + 1)
		return data

	def a(self):
		data = self.prepare_data()
		cnt = 0
		i = 0
		for x in data:
			if set(x[0]).issuperset(set(x[1])) or set(x[1]).issuperset(set(x[0])):
				cnt += 1
			i += 1
		print(cnt)
		print(len(data))
	
	def b(self):
		data = self.prepare_data()
		cnt = 0
		for x in data:
			if any(y for y in x[0] if y in x[1]): cnt += 1
		print(cnt)
Jump in the discussion.

No email address required.

(yes i was missing :marseymissing2: a + 1 in range())

C++ doesn't have this problem :marseynails:

Jump in the discussion.

No email address required.

This day was a bit boring but here's my sir, do the needful solution

![](/images/1670132903554569.webp)

Jump in the discussion.

No email address required.

:#marseycheerup:

Jump in the discussion.

No email address required.

Hi mimwee

Jump in the discussion.

No email address required.

Hey bud!

Jump in the discussion.

No email address required.

i would have finished both parts in a couple minutes but ranges excluding the end fucked me up for so goddamn long, i just couldn't figure out what was wrong :marseyraging:

with open("day4input.txt") as f:
    pairs = [line for line in f]

# part 1

full_overlaps = 0

for pair in pairs:
    pair = pair.split(",") # [1-2, 2-3] 
    pair = [elf.split("-") for elf in pair] # [(1,2), (2,3)]
    elf1 = set(range(int(pair[0][0]), int(pair[0][1])+1))
    elf2 = set(range(int(pair[1][0]), int(pair[1][1])+1)) 
    if elf1.issubset(elf2) or elf2.issubset(elf1):
        full_overlaps += 1

print(full_overlaps)

# part 2 

overlaps = 0

for pair in pairs:
    pair = pair.split(",") # [1-2, 2-3] 
    pair = [elf.split("-") for elf in pair] # [(1,2), (2,3)]
    elf1 = set(range(int(pair[0][0]), int(pair[0][1])+1))
    elf2 = set(range(int(pair[1][0]), int(pair[1][1])+1)) 
    if elf1.intersection(elf2) != set():
        overlaps += 1

print(overlaps)
Jump in the discussion.

No email address required.

this got me for... way too long :marseyfedpostglow: as well :marseyclapping:

Jump in the discussion.

No email address required.

i lost 10 minutes because python didn't parse out the \n :marseyrope:

Jump in the discussion.

No email address required.

hint: use splitlines() instead of split('\n')

Jump in the discussion.

No email address required.

:marseycheerup: it's python's fault, not ours

Jump in the discussion.

No email address required.

Not difficult yet. Misread the problem per usual and sunk 20 minutes into a problem that didnt exist though.

Part 1

subSets = 0

elfAssignments = []

with open('input', 'r') as f:

for line in f:

    cur_pair = line.split(',')

    first_assign = range(int(cur_pair[0].split('-')[0]), int(cur_pair[0].split('-')[1])+1)

    second_assign = range(int(cur_pair[1].split('-')[0]), int(cur_pair[1].split('-')[1])+1)

    l1 = set(list(first_assign))

    l2 = set(list(second_assign))

    if (l1.issubset(l2)) or l2.issubset(l1):

        subSets += 1

print(subSets)

Part 2:

overlaps = 0

elfAssignments = []

with open('input', 'r') as f:

    for line in f:

        cur_pair = line.split(',')

        first_assign = range(int(cur_pair[0].split('-')[0]), int(cur_pair[0].split('-')[1])+1)

        second_assign = range(int(cur_pair[1].split('-')[0]), int(cur_pair[1].split('-')[1])+1)

        l1 = set(list(first_assign))

        l2 = set(list(second_assign))

        if not l1.isdisjoint(l2) or not l2.isdisjoint(l1):

            overlaps += 1

print(overlaps)
Jump in the discussion.

No email address required.

#include <iostream>
#include <regex>
#include <string>

struct Range
{
	long low;
	long upper;

	bool inline isContainedIn(const struct Range &larger) const
	{
		return larger.low <= low and larger.upper >= upper;
	}

	bool inline isIntersectionEmptySet(const struct Range &r) const
	{
		return upper < r.low or low > r.upper;
	}
};

// G-d forgive me bc I used C++ Slowpoke regex
std::regex ranges_reg("(\\d+)\\-(\\d+),(\\d+)\\-(\\d+)");

int main()
{
	std::string line;
	unsigned card_pairs = 0;

	while(getline(std::cin, line))
	{
		std::smatch match;
		std::regex_search(line, match, ranges_reg);

		Range elf1 = {std::stol(match.str(1)), std::stol(match.str(2))};
		Range elf2 = {std::stol(match.str(3)), std::stol(match.str(4))};

		// PART A
		//if(elf1.isContainedIn(elf2) or elf2.isContainedIn(elf1))
		//	card_pairs ++;

		// PART B
		if(not elf1.isIntersectionEmptySet(elf2))
			card_pairs ++;
	}

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

No email address required.

Ranges

Regex

:marseysick::marseysick::marseysick:

Jump in the discussion.

No email address required.

Very nice, let's see your implementation

![](/images/16701585682228355.webp)

Jump in the discussion.

No email address required.

felt to unmotivated to join this contest thing :marseygiveup:

Jump in the discussion.

No email address required.

Jump in the discussion.

No email address required.

had to think hard and draw a diagram to figure out overlaps(), ngmi

![](/images/16701339038140712.webp)

Jump in the discussion.

No email address required.

Anyone else doing Rust?

![](/images/16701799855292351.webp)

Jump in the discussion.

No email address required.

Why even use rust at this point? folds without named functions make code almost unreadable (readable, but you have to spend more time to understand it)

Anyway, here's mine:

use std::fs::File;
use std::io::{BufRead, BufReader};
use std::str::FromStr;


struct Range {
    start: i32,
    finish: i32,
}


impl Range {
    fn includes(&self, other: &Range) -> bool {
        return self.start <= other.start && self.finish >= other.finish;
    }

    fn overlaps(&self, other: &Range) -> bool {
        return self.finish >= other.start && self.start <= other.finish
    }
}


impl FromStr for Range {
    type Err = &'static str;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let (start, finish) = s.split_once('-').ok_or_else(|| "no '-' in range")?;
        let start = start.parse::<i32>().map_err(|_| "invalid start")?;
        let finish = finish.parse::<i32>().map_err(|_| "invalid finish")?;
        Ok(Range{start, finish})
    }
}


fn main() {
    let file = File::open("input.txt").expect("Can't open input file");
    let reader = BufReader::new(file);

    let result = reader.lines().filter(|line| {
        let line = line.as_ref().expect("Can't read a line from file");
        let (left, right) = line.split_once(',').expect("No ',' in line");
        let left = left.parse::<Range>().expect("Can't convert");
        let right = right.parse::<Range>().expect("Can't convert");
        left.overlaps(&right) // left.includes(&right) || right.includes(&left)
    }).count();

    println!("{}", result);
}
Jump in the discussion.

No email address required.

Why even use rust at this point?

I like the language

folds without named functions make code almost unreadable (readable, but you have to spend more time to understand it)

for loops are evil

Jump in the discussion.

No email address required.

I'm not a masochist, it felt like I was staring at black boxes hidden in more boxes looking at stdlib. might just be r-slurred though

Jump in the discussion.

No email address required.

Filtered

:#marseyitsover:

Jump in the discussion.

No email address required.

with range and set its easy. Don't care about performance

with open('input04.txt') as file:
    lines = [line.split(',') for line in file]

# a and b
count_a = 0
count_b = 0
for pair in lines:
    lower,upper = pair[0].split('-')
    id_set_1 = set(range(int(lower),int(upper)+1))
    lower,upper = pair[1].split('-')
    id_set_2 = set(range(int(lower),int(upper)+1))
    if id_set_1.issubset(id_set_2) or id_set_1.issuperset(id_set_2): # a
        count_a += 1
    if len(id_set_1.intersection(id_set_2)) > 0: # b
        count_b += 1
print("Part a:", count_a)
print("Part b:", count_b)
Jump in the discussion.

No email address required.

sets in python are so unoptimized it's hilarious how slow they are in basically anything

Jump in the discussion.

No email address required.

r←⊢⎕FIO[49] 'day4raw.txt'
v←⍎¨¨¨('-'≠¨r⊂¨⍨','≠¨r)⊂¨¨r⊂¨⍨','≠¨r ⋄ f←{(1⌷⍵){1-⍨⍺+⍳1+⍵-⍺}2⌷⍵}
d1←{f↑1⌷⍵}¨v ⋄ d2←{f↑2⌷⍵}¨v ⋄ +/d1{+/1∊+/¨(⍺⍷⍵)(⍵⍷⍺)}¨d2 ⋄ ↑+/⍉⊃0≠⍴¨d1∩¨d2
Jump in the discussion.

No email address required.

:#marseyrick:

Jump in the discussion.

No email address required.

c++


struct Elf {
    int min;
    int max;

    bool inline isContainedOrContains(const Elf& b) const {
        return (min >= b.min and max <= b.max) || (b.min >= min && b.max <= max);
    }

    bool inline intersect(const Elf& b) const {
        return (min <= b.max && b.min <= max);
    }
};



std::tuple<int int=""> solution()
{
    std::cout << "Day 4" << '\n';

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

    int p1{ 0 };
    int p2{ 0 };

    while (std::getline(file, line)) {

        int a{ 0 };
        int b{ 0 };
        Elf elf1{};
        Elf elf2{};

        std::string buffer;
        for (char c : line) {
            if (c == '-') {
                a = std::stoi(buffer);
                buffer = "";
            }
            else if (c == ',') {
                b = std::stoi(buffer);
                elf1 = { a, b };
                buffer = "";
            }
            else buffer += c;
        }
        elf2 = { a, std::stoi(buffer)};

        if (elf1.isContainedOrContains(elf2)) ++p1;
        if (elf1.intersect(elf2)) ++p2;
    }

    file.close();

    return { p1, p2 };
}
</int>
Jump in the discussion.

No email address required.

Mommy is soooo proud of you, sweaty. Let's put this sperg out up on the fridge with all your other failures.

Jump in the discussion.

No email address required.

import * as fs from 'fs'

console.log(
  fs.readFileSync(process.argv[2], 'utf-8').split('\n').reduce((p, l) => {
      const m = l.match(/\d+/g)?.map(s => Number(s));
      return [ 
        p[0] + (m && (m[0] <= m[2] && m[1] >= m[3] || m[2] <= m[0] && m[3] >= m[1]) ? 1 : 0),
        p[1] + (m && (m[0] <= m[2] && m[1] >= m[2] || m[2] <= m[0] && m[3] >= m[0]) ? 1 : 0)
      ]
    }, [0,0])
);
Jump in the discussion.

No email address required.

Part 1:

with open('input.txt') as f:
    lines = f.readlines()
  
total_overlap = 0
any_overlap = 0
  
for line in lines:
    elf1, elf2 = line.strip().split(',')
    elf1_start, elf1_end = elf1.split('-')
    elf2_start, elf2_end = elf2.split('-')
    
    elf1_start = int(elf1_start)
    elf1_end = int(elf1_end)
    elf2_start = int(elf2_start)
    elf2_end = int(elf2_end)
    
    if elf1_start <= elf2_start and elf1_end >= elf2_end:
        total_overlap += 1
    elif elf1_start >= elf2_start and elf1_end <= elf2_end:
        total_overlap += 1
        
    if elf1_start <= elf2_end and elf1_start >= elf2_start:
        any_overlap += 1
    elif elf2_start <= elf1_end and elf2_end >= elf1_start:
        any_overlap += 1


print("There are " + str(total_overlap) + " total overlapping sets")
print("There are " + str(any_overlap) + " overlapping sets")
Jump in the discussion.

No email address required.

Solution with no comparisons, only bitflips and abuse of casting :marseytroll:

def to_unary(number):
    to_return = 0
    for i in range(int(number)):
        to_return+=2**i
    return to_return

# PART 2 BITWISE
matcher = re.compile(R"([0-9]*)-([0-9]*),([0-9]*)-([0-9]*)")
score = 0
for pair in lines:
    result = matcher.search(pair)
    a_min = to_unary(result.group(1))
    a_max = to_unary(result.group(2))
    b_min = to_unary(result.group(3))
    b_max = to_unary(result.group(4))
    #print(f"A MIN: {a_min:b} A MAX: {a_max:b} B MIN: {b_min:b} B MAX: {b_max:b}")
    
    score+=int(bool(((a_max ^ a_min) | ((a_min+1) >> 1)) & ((b_max ^ b_min) | ((b_min+1) >> 1))))
Jump in the discussion.

No email address required.

Please keep yourself safe

Jump in the discussion.

No email address required.

Why?

Jump in the discussion.

No email address required.

yes I stole the intersection function, no I don't care


package four

import (
	"bufio"
	"os"
	"strconv"
	"strings"
)

func grabRange(line string) (map[string]int, map[string]int) {
	a := make(map[string]int)
	b := make(map[string]int)

	pair := strings.Split(line, ",")

	left := strings.Split(pair[0], "-")
	right := strings.Split(pair[1], "-")

	a["min"], _ = strconv.Atoi(left[0])
	a["max"], _ = strconv.Atoi(left[1])

	b["min"], _ = strconv.Atoi(right[0])
	b["max"], _ = strconv.Atoi(right[1])

	return a, b
}

func One() int {
	var deliver int

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

	rd := bufio.NewScanner(fp)

	for rd.Scan() {
		left, right := grabRange(rd.Text())

		if (left["min"] <= right["min"] && right["max"] <= left["max"]) ||
			(left["min"] >= right["min"] && right["max"] >= left["max"]) {
			deliver++
		}
	}

	return deliver
}

func Two() int {
	var deliver int

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

	rd := bufio.NewScanner(fp)

	for rd.Scan() {
		var a, b []int
		left, right := grabRange(rd.Text())

		for i := left["min"]; ; i++ {
			a = append(a, i)

			if i >= left["max"] {
				break
			}
		}

		for i := right["min"]; ; i++ {
			b = append(b, i)

			if i >= right["max"] {
				break
			}
		}

		intersection := func(a, b []int) bool {
			var c []int
			m := make(map[int]bool)

			for _, item := range a {
				m[item] = true
			}

			for _, item := range b {
				if _, ok := m[item]; ok {
					c = append(c, item)
				}
			}
			return (len(c) > 0)
		}

		if intersection(a, b) {
			deliver++
		}

		a = nil
		b = nil
	}

	return deliver
Jump in the discussion.

No email address required.

I don't know what you said, because I've seen another human naked.

Jump in the discussion.

No email address required.

Ban all pythoncels from Advent of Code, we can't trust them

![](/images/1670172286690226.webp)

Jump in the discussion.

No email address required.

>doesnt even limit the search space to sqrt(n)

it never even began for bots

Jump in the discussion.

No email address required.

Do they get harder at some point? Since the timing format is very euromisic I'm just aiming to complete every challenge before the next one drops.

import re
foo = []
with open('day4_input.txt', 'r') as inp:
    foo = inp.read().split('\n')
total1, total2 = 0, 0
for f in foo:
    f = [eval(x) for x in re.split(',|-', f)]
    if (f[0] <= f[2] <= f[3] <= f[1]) or (f[2] <= f[0] <= f[1] <= f[3]):
        total1 += 1
    if not (f[2] > f[1] or f[0] > f[3]):
        total2 += 1
print(total1, total2)
Jump in the discussion.

No email address required.

had important business to attend to today sorry I'm late boss here's the homework. Bodged together at 11:30pm as usual

file = open("input.txt")
cc = 0
co = 0
for line in file:
    line = line.rstrip()
    h_i = [i for i, x in enumerate(line) if x == '-']
    c_i = [i for i, x in enumerate(line) if x == ',']
    e1_min = int(line[0:h_i[0]])
    e1_max = int(line[h_i[0]+1:c_i[0]])
    e2_min = int(line[c_i[0]+1:h_i[1]])
    e2_max = int(line[h_i[1]+1:len(line)])
    if ((e1_min <= e2_min and e1_max>=e2_max) or (e2_min <= e1_min and e2_max>=e1_max)):
        cc += 1
    if not ((e1_max < e2_min) or (e2_max < e1_min)):
        co += 1
print(cc)
print(co)
Jump in the discussion.

No email address required.

I'm never sure if calling the same function with the same args twice in the same line makes it compute twice of if it's optimized away, so added another functional composition layer on top. This way is faster for part 2 than just intersecting ranges. in matlab (:gigachad2:)

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

comp1 = @(x) ((x(1)>=x(3))&&(x(2)<=x(4)))||((x(1)<=x(3))&&(x(2)>=x(4)));
comp2 = @(x) ((x(1)>=x(3))&&(x(1)<=x(4)))||((x(2)>=x(3))&&(x(2)<=x(4)));
aux = @(u) comp2(u)||comp2([u(3:4) u(1:2)]);

iterfunc = @(u) [comp1(u); aux(u)];
iterfunc2 = @(i) iterfunc(sscanf(i,'%d-%d,%d-%d'));

res = sum(cell2mat(arrayfun(iterfunc2,A,'UniformOutput',false)),2);

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

No email address required.

@Jinglevann now it's emotes that are broken (in preview) when you have a code block in the post :marseytroll:

![](/images/16701870064056458.webp)

Jump in the discussion.

No email address required.

CLEAN IT UP CODEJANNY

Jump in the discussion.

No email address required.

Wait I can just do comp2 = @(x) ~((x(2)<x(3))||(x(1)>x(4))); and chuck out the aux lmao

Jump in the discussion.

No email address required.

with open("./input4.txt") as infile:
    ct = 0
    for line in map(str.strip, infile):
        a, b = line.split(',')
        a_min, a_max = map(int, a.split("-"))
        b_min, b_max = map(int, b.split("-"))
        a_set = set(range(a_min, a_max +1))
        b_set = set(range(b_min, b_max +1))
        u = a_set & b_set

        # part one
        # if len(u) in {len(a_set), len(b_set)}:
        #     ct += 1
        
        # part two
        # if u:
        #     ct += 1
    print(ct)
Jump in the discussion.

No email address required.

set(range(b_min, b_max+1))

>tfw I didn't think of this

:#marseyitsover:

Jump in the discussion.

No email address required.

Frick me I keep forgetting to do these each day :marseybangfast:

Jump in the discussion.

No email address required.

People always talk about how poorly written and unrealistic female characters are but even in real life women are poorly written

Jump in the discussion.

No email address required.

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