/aocg/ - Advent of Code 2018 General #5

Previous thread: Spot the Difference edition

adventofcode.com/
>Advent of Code is a series of small programming puzzles for a variety of skill levels. They are self-contained and are just as appropriate for an expert who wants to stay sharp as they are for a beginner who is just learning to code. Each puzzle calls upon different skills and has two parts that build on a theme.
You need to register with an account but you can appear as anonymous.

Private leaderboard join code: 368748-e33dcae3
People who are inactive for 5 days will be kicked, but other leaderboards can be made if desired.

Attached: 1514128266816.png (1394x768, 661K)

Using combinations (as opposed to products, permutations, or double-for-loops) will reduce the number of iterations by nearly half.
theta(n!/2(n-2)!)

That private leaderboard is full. [OK]

>nearly
over half. 31125 < 31250

that's nice.

meanwhile I have an 8 core 4GHz jewtel CPU

edit from other thread

Attached: aoc2_2.png (800x602, 389K)

STEP AWAY FROM THE BOXES AND NOBODY GETS HURT

Attached: 1537840186638.jpg (583x439, 35K)

We need to replace his head. Also,

Brainlet Kotlin solution for Part 2
fun partTwo(items: Array) : String {

for (currentChar in 0 until items[0].length) {
val workingItems = Array(items.size) { i ->
items[i].removeRange(currentChar, currentChar + 1)
}

for (i in 0 until workingItems.size) {
for (j in i + 1 until workingItems.size) {
if (workingItems[i] == workingItems[j])
return workingItems[i]
}
}
}

return "couldn\'t find it"
}

ok

Attached: Annotation 2018-12-02 012043.jpg (1811x751, 262K)

Reminder that string manipulation isn't real programming. No important programming problems today are solved by finding the common letter subset of two strings. These problems aren't intellectual nor require programming knowledge in the slightest.

Someone started another one in the last thread, would be good to add to the OP pasta
208834-4a1a9383

in =: > cutLF fread 'input'
*/ +/ (2 3 e. #/.~)"1 in
(=/ # {.) ({~ 1 i.~ +/@:~:/"2) ,/ ,:"1/~ in

That's why I IMMEDIATELY converted the strings to a matrix for part 2.

>26 people who haven't done either day yet

i get that not everyone is going full try hard with this shit, but if you aren't going to even try and do the puzzle when it releases, why take up a leaderboard spot?

Seconded

This, please remove people who don't actually try. I'm half asleep and have to study for exams but even I can try these are really not that bad.

>spent so long writing garbage code and shitposting that my coffee is ice cold
Just adds insult to injury.

I think the person in charge of that leaderboard said they will kick anyone that has 5 days of inactivity

guess i gotta wait 5 days then zzzzzz

fucking kek my code is shit

Which is better?

from collections import Counter
from operator import mul
from functools import reduce
reduce(mul,(sum(n in Counter(line).values() for line in data) for n in [2, 3]), 1)

from collections import Counter
(lambda x, y: x*y)(*(sum(n in Counter(line).values() for line in data) for n in [2, 3]))

i think its worse than the hat version

Attached: aoc2_3.png (836x602, 380K)

>he's still using Vim
Get with the times, grandpa. Modern coders use VSCode!

Attached: vscode.png (537x860, 45K)

the second problem is literally hamming distances. You just aren't using the actual distance in the optimized version

>die();
Exactly how I feel whenever I read PHP.

i'm squeezing it
def advent2():
from itertools import compress
tab = open("adventofcode_data.txt").readlines()
# part 1
t = [set([s.count(i) for i in s]) for s in tab]
print(sum([2 in e for e in t])*sum([3 in e for e in t]))
# part 2
for i in range(len(tab)):
for j in range(i):
s = ''.join(compress(tab[i], [tab[i][k]==tab[j][k] for k in range(len(tab[i]))]))
if(len(s) == len(tab[0])-1):
print(s)

Most of my job is string manipulation and automating execution of other scripts.

I don't understand how any of this is helping us fix anomalies. Was the fabric being lost an anomaly? It really doesn't make sense. This story is bullshit.

guys seriously this isn't fuckin funny

Attached: wahtnowpyfags.gif (640x420, 792K)

Why are 3/4 of the replies here python? I thought it wasn't THAT popular.

As thoroughly discussed last puzzle, the magic of hashing

read the first response to this thread.
It's not much different from
for (int i = 0; i

this is O(n) and written in javascript

let fs = require('fs')
fs.readFile('input.txt', 'utf8', (err, data) => {
if (err) return console.log(err)
let ids = data.trim().split("\n")

for (let i = 0; i < ids[0].length; i++) {
let clippedIds = ids.map((val, idx, arr) => {
return val.slice(0, i) + val.slice(i+1)
})
let ans = clippedIds.filter((val, idx, arr) => {
return arr.lastIndexOf(val) !== idx
})
console.log(ans)
}
})

>itertools.compress
Nice.

i'm guessing they'll introduce a villain at some point who is responsible for fucking with the fabric/other shit

i don't even read that stuff til after i'm finished

neither are readable, hence unmaintainable, hence useless

>look ma one line!

Attached: chinese-girl-skeptical-face.jpg (479x435, 45K)

It's written by some guy from SF, what do you expect?

>itertools.compress
Nice.

Put the Boomer in the background mowing the lawn while zoomer wagecucks his Amazon boxes

i may be a bit late

Attached: good.png (111x27, 639)

>boomer
>zoomer

Attached: 1502850674657.jpg (341x544, 44K)

You way overdid it in part 2. At least, it's fucking hard to read.
def p2(data):
for a, b in combinations(data, 2):
l = ''.join([x for x, y in zip(a, b) if x == y])
if len(l) == len(a)-1:
return l

That's an anti-mactoddlers feature

Or millennial I suppose since he doesn't have the zoomer undercut and glasses

srsly could not laughing this moment, I have the needful for to make my python work to achieve leaderboard

Attached: aoc2_4.png (836x602, 386K)

I'm sure the guy putting together the calendar image can come up with something better than this. At least we're compiling ideas.

>for a, b in combinations(data, 2):
i'm borrowing it
i've been doing previous year's aoc and i learned more python in those 2 days than in the past 3 years

Attached: 1537817455115.jpg (400x400, 12K)

I'm not feeling the bommer/zoomer in this pucture, it's kind of forced

I hope you've optimized your for loops.

Attached: Annotation 2018-12-02 013918.jpg (628x486, 17K)

Hearty kek

part 2:

type result struct {
matches int
index [2]int
}

func partTwo() {
f, err := os.Open("data")
check(err)
defer f.Close()

scanner := bufio.NewScanner(f)
boxes := make([][]rune, 250)
for i := 0; scanner.Scan(); i++ {
boxes[i] = []rune(scanner.Text())
}

var matches *result
var wg sync.WaitGroup
wg.Add(len(boxes))
for i := 0; i < len(boxes); i++ {
go func(idx int) {
for j := 0; j < len(boxes); j++ {
if idx == j {
continue
}

sameRuneCount := 0
for iL := 0; iL < len(boxes[idx]); iL++ {
if boxes[idx][iL] == boxes[j][iL] {
sameRuneCount++
}
}

if matches == nil || sameRuneCount > matches.matches {
s := &result{
matches: sameRuneCount,
index: [2]int{idx, j},
}
matches = s
}
}

wg.Done()
}(i)
}

wg.Wait()
var res []rune
for i := 0; i < len(boxes[matches.index[0]]); i++ {
if boxes[matches.index[0]][i] == boxes[matches.index[1]][i] {
res = append(res, boxes[matches.index[0]][i])
}
}

fmt.Println(string(res))

}

pic related, how i feel

Attached: serveimage.png (842x792, 82K)

this

Fair enough

see or or suggest?

I still prefer the original hat

me too desu

fuggg lads, making a constexpr version of today is turning out to be harder than expected. Doing the naive double for loops will eat through your RAM so fucking fast.
I only have 8gigs so I allocated 16gigs of swap on my SSD but it's slow as fuck and won't compile. I need to find a way to remove strings from the list

Same.

Can you do combinations instead of double for loops?

what. its only 250 lines

I did one as well.

Attached: zoomer.png (800x602, 373K)

Post the code. I have 32GB of ram.

>so many people have chimneys
>This is, in fact, roughly when chimneys became common in houses.

D E E P E S T L O R E

It's the hover text easter egg

is anyone else here taking it slow and writing unit tests?
cargo test
Compiling day2 v0.1.0 (./2018/day2)
Finished dev [unoptimized + debuginfo] target(s) in 0.87s
Running target/debug/deps/day2-aeb7019a93a0782a

running 4 tests
test test_parse ... ok
test test_find_counts ... ok
test test_p2 ... ok
test test_p1 ... ok

test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

who here / $sort input.txt > input.txt /

assuming I'm not too brainlet yes, I'll try it but with constexpr it's hard to do some things

250^2 = 62500 and every comparison I need to check every char of the strings, g++ does not like that

#include
#include
#include

int main() {
constexpr std::string_view lines[] {

};

constexpr auto find_if = [](auto first, auto last, auto p) {
for (; first != last; ++first) {
if (p(*first)) {
return first;
}
}
return last;
};

constexpr auto part1 = [=] {
int threes = 0, twos = 0;
for (auto const& line: lines) {
int count[256] = {0};
for (auto c: line)
count[static_cast(c)]++;

if (find_if(std::begin(count), std::end(count),
[](auto const& p){return p == 3;}) != std::end(count))
threes++;
if (find_if(std::begin(count), std::end(count),
[](auto const& p){return p == 2;}) != std::end(count))
twos++;
}
return threes * twos;
};

constexpr int res1 = part1();
std::cout std::pair {
for (size_t i = 0; i < std::size(lines); i++) {
for (size_t j = 0; j < std::size(lines); j++) {
if (i == j) continue;
if (diff_one(lines[i], lines[j])) {
auto p = lines[i].find_first_not_of(lines[j]);
return {lines[i], p};
}
}
}
return {};
};

constexpr auto res2 = part2();
constexpr auto s1{res2.first.substr(0, res2.second)};
constexpr auto s2{res2.first.substr(res2.second+1)};

std::cout

Cursed solution from blebbit


#! /usr/bin/perl

local $/; $_ = ;

my @s = map { join "", sort split "" } split "\n";
my $part1 = (grep { m/(?:^|(.)(?!\1))(.)\2(?!\2)/ } @s) *
(grep { m/(?:^|(.)(?!\1))(.)\2\2(?!\2)/ } @s);
my $part2 = s/.*?\b(\S*)\S(\S*)\b.*?\1\S\2.*/$1$2/sr;
print "Part 1: $part1\n";
print "Part 2: $part2\n";

looks good but people are hatin on the memes it seems

there's no reason for zoomer boomer monster shilling, aoc should come up with OC

You need to go back

I just don't get why (b|z)oomer should be included at all. What's it referencing specific to this problem?

>not even in top 50 anymore
I blame my alarm
starone(lists) took 0.15765695356619355 for 100 loops at 0.0015765695356619355 per loop
startwo(lists) took 6.585960080846631 for 100 loops at 0.06585960080846631 per loop

Solution in rust pt1:
#[aoc_generator(day2)]
pub fn input_generator(input: &str) -> Vec {
input
.lines().map(|s| String::from(s).chars().collect())
.collect()
}

#[aoc(day2, part1)]
pub fn solve_part1(input: &[Vec]) -> i32 {
let mut count_2 = 0;
let mut count_3 = 0;
let mut memory:[u32; 26] = [0; 26];
let mut is_2 = false;
let mut is_3 = false;
for val in input.iter() {

for c in val.iter(){
let count = memory[(*c as u32 -97) as usize]+1;
memory[(*c as u32 -97) as usize] = count;
}
for (i, value) in memory.iter_mut().enumerate() {
if *value == 2 {
is_2=true;
}
if *value == 3 {
is_3=true;
}
*value = 0;
}
if is_2 {
count_2 +=1;
}
if is_3 {
count_3 +=1;
}
is_2 = false;
is_3 = false;
}
count_2*count_3
}

you implyin last year's calendar didn't have memes? pretty sure one day had the chad vs. virgin thing in it for example

Solution in rust part 2:
#[aoc(day2, part2)]
pub fn solve_part2(input: &[Vec]) -> String {
for val in input.iter() {
for val2 in input.iter() {
match calculate_hamming(val, val2) {
Ok((distance, common)) => {
if distance == 1{
return common.iter().collect();
}
},
Err(why) => panic!("{:?}", why)
}
}
}
String::from("No match found")
}

fn calculate_hamming(input1: &Vec, input2: &Vec) -> Result

Day 2. My code still looks like C.

Attached: 2018-12-02-135424_1366x768_scrot.png (1366x768, 131K)

It did, but not thrown into an otherwise unrelated image iirc.

yeah but that was probably tailored to suit the context. shoving in a boomer and a brand beverage isn't a meme

chad/virgin is always relevant if you're comparing two things.

Performance:
AOC 2018
Day 2 - Part 1 : 6225
generator: 156.1µs,
runner: 13.1µs

Day 2 - Part 2 : revtaubfniyhsgxdoajwkqilp
generator: 143µs,
runner: 11.2655ms

Haskell
main = do
input Int
soln1 x = (*) (countTwos (lines x)) (countThrees (lines x))

soln2 :: String -> String
soln2 x = findCommon (findDiff1 (lines x) (lines x))

extractKey :: Eq a => a -> [(a, b)] -> [b] -> [b]
extractKey _ [] acc = acc
extractKey x (y:ys) acc = extractKey x ys (if (fst y) == x then (snd y):acc else acc)

extractByKey' :: Eq a => [(a, b)] -> [a] -> [(a, [b])]
extractByKey' [] _ = []
extractByKey' (x:xs) seen
| elem (fst x) seen = extractByKey' xs seen
| otherwise = (fst x, extractKey (fst x) xs [snd x]):extractByKey' xs ((fst x):seen)
extractByKey :: Eq a => [(a, b)] -> [(a, [b])]
extractByKey x = extractByKey' x []

reduceByKey :: Eq a => [(a, b)] -> ([b] -> b) -> [(a, b)]
reduceByKey x f = map (\y -> (fst y, f (snd y))) (extractByKey x)

countLetters :: String -> [(Char, Int)]
countLetters s = reduceByKey (map (\x -> (x, 1)) s) sum

hasTwo :: [(Char, Int)] -> Bool
hasTwo [] = False
hasTwo (x:xs) = if (snd x == 2) then True else hasTwo xs

countTwos :: [String] -> Int
countTwos x = sum (map (\y -> if (hasTwo . countLetters) y then 1 else 0) x)

hasThree :: [(Char, Int)] -> Bool
hasThree [] = False
hasThree (x:xs) = if (snd x == 3) then True else hasThree xs

countThrees :: [String] -> Int
countThrees x = sum (map (\y -> if (hasThree . countLetters) y then 1 else 0) x)

countDiff :: String -> String -> Int
countDiff s0 s1 = sum (map (\x -> if (fst x == snd x) then 0 else 1) (zip s0 s1))

findDiff1 :: [String] -> [String] -> (String, String)
findDiff1 [] [] = ("", "")
findDiff1 (x:xs) [] = findDiff1 xs xs
findDiff1 (x:xs) (y:ys) = if (countDiff x y) == 1 then (x, y) else findDiff1 (x:xs) ys

findCommon :: (String, String) -> String
findCommon ([], []) = []
findCommon x
| (head (fst x)) == (head (snd x)) = (head (fst x)):findCommon ((tail (fst x)), (tail (snd x)))
| otherwise = findCommon ((tail (fst x)), (tail (snd x)))

Another rust solution

Attached: day2.png (544x890, 67K)

I figured because of the Amazon wagecage box sorting meme, and the Boomer for waking up early to do the Advent challenge, but it was just a loose brainstorming idea

Part 2 is absolutely awful in C++ when you dont know what you are doing

had to do it in Python

Attached: feelsbadman.jpg (800x762, 69K)

BEHOLD
I HAVE TRANSCENDED
def p1(data):
counts = (set(Counter(s).values()) for s in data)
twos, threes = zip(*map(lambda v: (int(2 in v), int(3 in v)), counts))
return sum(twos) * sum(threes)

def p2(data):
for a, b in combinations(data, 2):
l = ''.join([x for x, y in zip(a, b) if x == y])
if len(l) == len(a)-1:
return l

Attached: 1489398523334.jpg (1000x1000, 314K)

Dafuq part 2 is unironically easier than part 1 if you do it in C++. I had to write pseudo memcmp in python like some sort of savage.

Functional is so weird, I have no idea if I'm doing this properly or if I'm generating some bizarre exp(n) abomination.

It runs fast enough though --
$ time ./soln
8610
"iosnxmfkpabcjpdywvrtahluy"

real 0m0.055s
user 0m0.048s
sys 0m0.007s

problem is it takes forever to write.

Haskell bros, is there a library of higher order functions (reduceByKey, flatMap, aggregate, etc) that I should be importing?

While I have used very little C++, I'm pretty sure it can be easily broken down into steps to simple even ASM shouldn't be much of a problem.

>to simple
*so simple.
If I had an emulator for a TTL computer design I'm working on functional yet, I'd probably try to do it on that in ASM just for the hell of it.

The int() calls should be unnecessary as python's boolean is a subclass of int or something. Basically sum on a list of bools treats them like ones and zeroes.

Was this puzzle supposed to make me understand the pitfalls of premature ejaculation?

sweet it works

By the way, there is no need to use combinations, you can but pic related will only do 31125 loops max and you don't need to generate a new list
Also you don't need to check i == j in the loop because it's always false

Attached: Screenshot_2018-12-02_08-08-15.png (486x43, 6K)

neither as you need to import and both are unreadable