/aocg/ - Advent of Code 2018 General #7

Codeshare edition

Previous thread: 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.

Alternative leaderboard for those waiting for inactives to be kicked from the first: 208834-4a1a9383

Attached: 1517895038887.png (800x602, 404K)

Other urls found in this thread:

docs.python.org/3/tutorial/datastructures.html#list-comprehensions
github.com/Unihedro/workout/blob/master/adventofcode2018/day01.rb
mediafire.com/file/6vrqbvk9tbo7kjx/newerinput.txt/file
reddit.com/r/adventofcode/comments/5hoia9/2016_day_11_solutions/db1v1ws/
youtube.com/watch?v=D1sXuHnf_lo
twitter.com/NSFWRedditGif

Python is the most powerful programming language

hASKELL FAGGOTS use one letter function names that won't make sense next week

>They are self-contained
Reminder that it's a lie

I represent the OCaml team.
>I won't stop till I get to the top - Becky G

No joke
>python code: Correct answer in 0.392ms
>c code: Correct answer in 6m42s
Why can't the C compiler optimize my shitty fucking code?

>brainlets don't know that recursive common table expressions are turing complete

with recursive r (i1, i2, idx, diff) as (
select i1.id, i2.id, 0, array[0, 0]
from ids i1, ids i2
where i1.id < i2.id
union
select
i1, i2, idx + 1,
case
when substr(i1, idx, 1) = substr(i2, idx, 1)
then diff
else array[diff[1] + 1, idx]
end
from r
where idx < length(i1) and diff[1] in (0, 1)
)
select
substr(i1, 0, diff[2]) || substr(i1, diff[2] + 1)
from r
where idx = length(i1) and diff[1] = 1

r is the recursive table?

Man I can't be arsed to do something smaller than O(n^2) with such a small output.

>6m42s
user wut r u doing

t. Java Enterprise-Certified Programmer

str.parse() is cool.

use std::{ fmt, result, error };
use std::str::FromStr;

pub type Result = result::Result;

pub fn parse_lines(input: &str) -> Result
where T: FromStr, T::Err: error::Error
{
parse_input::(input, "\n")
}

pub fn parse_input(input: &str, delimiter: &str) -> Result
where T: FromStr, T::Err: error::Error
{
type Err = ::Err;
type ResultVec = result::Result;

input.split(delimiter)
.map(|line| line.parse::())
.collect::()
.map_err(ParseError)
}

#[derive(Debug)]
pub struct ParseError(T);

impl fmt::Display for ParseError
where T: error::Error
{
fn fmt(&self, f: &mut fmt::Formatter) -> result::Result
{
fmt::Display::fmt(&self.0, f)
}
}

impl error::Error for ParseError
where T: error::Error
{

}

MATLAB fags report in.

Attached: Kong_Frederik_IX.jpg (602x892, 209K)

16 ms. Good enough.

main :: IO ()
main = do
--filename[Char]
finder [] = []
finder (x:xs)
|(length(filter (==False) (cmpr x)))==1 = beautify x
|otherwise = finder xs

cmpr :: [(Char,Char)] -> [Bool]
cmpr x = (map (comparetuple) x)

comparetuple :: (Char,Char) -> Bool
comparetuple x
|(fst x)==(snd x) = True
|otherwise = False

beautify :: [(Char,Char)]->[Char]
beautify [] = []
beautify (x:xs)
|comparetuple x = [fst x] ++ beautify xs
|otherwise = beautify xs

It was for day 1. I wanted to use C for whatever reason and I was constantly looping through the gigantic array of unique numbers checking for duplicates. That took too long so I just started checking for duplicates every 500 numbers or so but it gave inaccurate results. Switched to python and solved it in 15 lines in milliseconds using the built-in set() data type which quickly checks for duplicates.

>babby can't implement a hash set

Same. O(n^2) here as well but with a runtime of half a second there's really no reason to optimize beyond that unless you're autistic. I just want my gold star

pretty close to the truth actually

The choice was either re-implement a shitty hash set data type in C specifically just to solve an easy as fuck problem or just use a language that has it built-in

perl part 2, ~15ms

Attached: ss.png (719x492, 59K)

r8 me, i'm learning pythong
boxes = [list(line.strip()) for line in open(filename)]

have3 = 0
have2 = 0

for id in boxes:
counts = []

for letter in set(id):
counts.append(id.count(letter))

if counts.count(2) >= 1:
have2 += 1
if counts.count(3) >= 1:
have3 += 1

print('Part1: ', have2*have3)

for id1 in boxes:
for id2 in boxes:
final = []
for i in range(len(id1)):
final.append(ord(id1[i]) - ord(id2[i]))

if final.count(0) == len(id1)-1:
for i, ele in enumerate(final):
if ele != 0:
del id1[i]
print('Part2: ', ''.join(id1))
exit(0)

At least you are not the "over an hour" guy.

Here user

Attached: you get a gold star pepe.jpg (477x768, 56K)

the problem is that the computer does exactly what you tell it to do.
when given "move this pointer here", "iterate over all this shit" it doesn't have the leeway to understand that what you ultimately want is a hash set.
The """solution""" would have been to implement a hash set in C. Or pull one in from a library.
You just make a fixed size array (max 150,000 * sizeof(int)), write a hash function for your numbers which summarizes them into a single integer (they are ints already), and then try to add them to the array.
If the space is already taken, you need a strategy to add them anyway. Maybe move over one space. If it's taken, maybe move over three spaces. Or five. Or nine.
If the hash set is almost full you need to make it bigger and copy all the values over.
If the hash set is almost empty you need to make it smaller and copy all the values over.
If you constantly switch between bigger and smaller, you end up with thrashing so you need to make that gap bigger.

>boxes = [list(line.strip()) for line in open(filename)]

You don't need list() here. List comprehension already creates a list.

see
docs.python.org/3/tutorial/datastructures.html#list-comprehensions

for these computing challenge-type problems I'd forgo writing a hash set by hand when possible and just make a big array and pray they don't bring in INT_MAX.
For other problems, like hashing strings, your only option is to write a real hash set, because with strings you are bound to have collisions anyway.

In that particular case, list() breaks up the line into a list of the line's characters, so you get a list of lists. No idea if that's what user intended.

Oh, and retrieval is easy. You just compute the hash again and perform the move-over strategy if it's the wrong one. Or if it's an empty space then the value isn't in the set.

how come the leaderboard is full of people who are using haskell all over their github?

I never thought it was that popular im currently learning elm for frontend stuff is Haskell going to be an easier transition for me

haskell is pretty much made for these kinds of problems anyway

I doubt they are really using Haskell to solve these problems. Functional programming is easy to read but takes a certain amount of effort and wizardry to get to that point, since recursion can be fraught with difficulty.

These are people who are simply excited about programming and do it as a hobby. It's entirely unsurprising that they have tried out Haskell.
It's entirely unsurprising that they want to show off.

Have you seen how small some haskell programs anons post are? If you become proficient with it, you can write obscure alien shit in a few lines that will find the cure for cancer.

I've been solving in haskell because it's fun but if I was going for the leaderboard I'd reach for python in a heartbeat.

>day 2
>7th threads
wat, can't we just have 1 thread per day?

How new are you?

Attached: 1300044776986.jpg (600x600, 34K)

Part 2 seems overly complicated and you're checking the same two boxes more than once. Nothing wrong with the python code in particular, more of a logic thing.

Though I'm not sure about the ord(id1[i]) - ord(id2[i]) part. I get what you're doing but it seems strange. I had something like:
def has_single_point_diff(ID1, ID2):
diff_count = 0
for n in range(len(ID1)):
if(ID1[n] != ID2[n]):
diff_count += 1
if(diff_count == 1):
return True
return False

I find that more readable.

Attached: 1500019141205.jpg (278x319, 52K)

4 years
and it irritates me every year

Jow Forums bump limit is like 300, this shit is too active to keep to one a day

it will definitely slow down in the next few days tho

why do you require one and only one thread per day?

it's too much to ask for a hotpocket to wait until the stroke of midnight to unsticky threads and make new stickies for 25 days straight

Danke Herr Froschenplakat

then just don't waste it on stupid garbage like this bait, problem solved

wait for the brainlet filter day, there will be a spike of activity because of salty brainlets then they will be gone and the activity will slowly die off

why in the fuck would you want a sticky. have you ever been in a sticky thread that wasn't pure cancer/spam?

jokes on you guys, I was only pretending to be retarded

stop posting anytime m8, you're just bumping it :^)

>brainlet filter day
There is such thing?

and what did you just do idiot

you don't have to reach for O(1), you can reach for transcendence code golfing is always more fun and interesting than spamming out the fastest solution in the least amount of time.

see

So it's either write all that which solves a different problem than the one you're actually trying to solve or:
hist = set()
if(val in hist):
print(val)
else:
hist.add(val)

Well, you're the one trying to solve the challenges in a language with no standard library, not me.

kek that was the hexagons wasn't it? that was a really good thread, complete dumpster fire of "FUCK"

look at this code
github.com/Unihedro/workout/blob/master/adventofcode2018/day01.rb

some of the most obscure shit i've ever seen and it's in fucking ruby of all languages this guy is 9th

#!ruby
# part 1
p$

If the mods actually cared they'd sticky the thread instead of forcing users to constantly have to remake the exact same thread over and over for the duration of the month

What he's doing isn't obscure, it's just hard to read because he's a faggot and Ruby is a very Apple-like language where they make a lot of minor differences in syntax, with no basis in prior art, which build up to be a huge pain in the ass.

it is, so that ord(id1[i]) - ord(id2[i]) is possible without converting it to a list each time

yeah i just learned about Combination and I'll try and rewrite it to that later.

That was my original post. Python is more powerful than C because in C you have to mess around with stupid shit. Then someone called me a baby cause I can't re-implement something I shouldn't actually need to re-implement

I prefer to have an organic structure where users decide what interest them, rather than having something like reddit
Making threads is not that difficult, so this is a non-issue

The """original""" post was about some guy crying that C can't optimize his shit code that ran for like 5 minutes because he doesn't know what a hash set is.

>tfw too brainlet for sub-O(n^3)

Attached: file.png (1300x986, 1011K)

>NO I FORGOT TO CHANGE THE FILE LOADER TO DAY 2 INSTEAD OF 1 MY CODE WORKED FINE FUCKING KILL ME
I was running my program against my source code instead of the input file for a few times and wondered wtf I managed to do.

What happens if you submit a wrong answer to the site? Does it just say it's wrong and lets you try again?

yeah if you submit someone else's answer it calls you out on being a cheater
if you submit numeric answer that's too low/high you will get a hint (few first times)
with each wrong answer you get a bigger reply cooldown though

copy paste chads win again

This, but too many wrong answers and the puzzle is locked indefinitely

but user Python already treats Strings as Lists.

>wrote a Python script to scrape the Jow Forums leaderboard
>every time someone gets a star, my buttplug vibrates

This is so exciting! It's just buzzes every now and then right now, but I'll probably cum when you guys start solving day 3.

Attached: eclipsa_excited.png (522x528, 272K)

Attached: 1535067169140.gif (459x258, 3.99M)

>someone called me a baby because I cannot prepare my own food but then I told them that restaurants are more powerful than preparing your own food

Attached: 1524936238071.jpg (600x525, 42K)

please for the love of god put this post on the calendar

Extra problem based on this problem. Find 2 strings that differ at 2 places in this input mediafire.com/file/6vrqbvk9tbo7kjx/newerinput.txt/file

/sepples/ part 1
int part1(std::vector &data) {
int dubs = 0, trip = 0;
for (std::string &line : data) {
int cnt[26]{0};
std::for_each(line.begin(), line.end(),
[&cnt](char &c) { ++cnt[c - 'a']; });
dubs += std::any_of(std::begin(cnt), std::end(cnt),
[](int n) { return n == 2; })
? 1
: 0;
trip += std::any_of(std::begin(cnt), std::end(cnt),
[](int n) { return n == 3; })
? 1
: 0;
}
return dubs * trip;
}

>File size: 495.91 MB
I'm not doing it

Attached: pepe nuhuhuhuh.jpg (1543x1360, 74K)

haha just make the input bigger

>his algorithm isn't O(n!!)
Who here /until-the-end-of-the-universe/ ?

Attached: 1541383092824-0.jpg (800x640, 108K)

O(n) Haskell coming through
import Data.Set hiding (map, filter, drop, take, foldl)

counts :: String -> [Int]
counts xs = (\c -> (length $ filter (==c) xs)) ['a'..'z']

reps :: [String] -> Int -> Int
reps xs a = length $ filter (elem a) $ map counts xs

pt1 :: [String] -> Int
pt1 xs = reps xs 2 * reps xs 3

rmOne :: String -> [String]
rmOne s = map (\x -> take x s ++ drop (x + 1) s) [0..(length s - 1)]

pt2 :: [String] -> Set String -> String
pt2 (x:xs) s = if dups /= [] then head dups
else pt2 xs $ union s $ fromList subs
where
subs = rmOne x
dups = filter (flip member s) subs

main = do
input

post script

Friendly reminder to update the calendar because I won't do it this time.

>Please don't make frequent automated requests to this service.

well done

This is my first time ever doing Advent of Code.
I realize now that I am a brainlet.
I don't want to be a brainlet. Help

How would you even solve that one?
You've got 10 items which are paired, and two halves are mutually exclusive when not grouped in a set with their pairs.
It sounds like a breadth first search problem but how are you supposed to enumerate the available number of moves at any given point?

get a book, get some documentation but more importantly.. never stop trying

That's why do things like Advent of Code to learn. When AoC ends, keep learning daily.

See: reddit.com/r/adventofcode/comments/5hoia9/2016_day_11_solutions/db1v1ws/
It was a tough one, it took 3 hours to cap the global leaderboard as opposed to usualy 2-5 minutes.

>buttplug with an API
Truly we have reached the apex of humanity.

I'm trying it, it's taking a while

The base picture was so big I actually had to increase the size of today's picture

Attached: 1543770542792.png (10000x10000, 2.81M)

Save it as a png-8 with 256 colors.

Also, I'm not sure the picture will stay under 4MB with every day filled

It's been a thing for a while: youtube.com/watch?v=D1sXuHnf_lo

out of memory on my linear-but-space-heavy one, trying with my space efficient but quadratic time one

Which is better:
>Create a single hashmap and clear it every loop iteration
>Create a new hashmap inside the loop every iteration

I would say the first.

daily letter user here, I completed my bash solution but FUCK is it slow to run. Is it supposed to be like that? I went for the general n^2 approach, but still...

Try posting your implementation.

Attached: Screenshot 2018-12-02 at 19.45.08.png (1022x660, 101K)

My n^2 script completes in 100 ms. It shouldn't take much longer.

>task 17 from aoc 2017
that was FUN

Attached: aoc1717.png (276x47, 2K)