/aocg/ - Advent of Code 2018 General #2

Previous thread: How do data structures work? 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: 1543652412172.png (1330x1477, 179K)

Other urls found in this thread:

ghostbin.com/paste/g43n7
twitter.com/NSFWRedditGif

first for O(N^2) masterrace

Calendar as of now

Attached: 1543652412172.png (10000x10000, 565K)

>tfw specifically stayed awake until midnight and still didn't make top 100 on either star because of my shitty reading comprehension
Feels like I'm free now tbqh; I can do them whenever and still get the same number of points.

Rate my first Python program!

input = open("input").readlines()

def part1():
freq = 0
for i in input:
freq += int(i)
print (freq)

def part2():
freq = 0
prev = []
while True:
for i in input:
freq += int(i)
if freq in prev:
print(freq)
return
else:
prev.append(freq)

part1()
part2()

Attached: gwen_border.png (500x424, 159K)

>prev = []
read OP's picture

I woke up early and completed it first thing over a cup of tea. Feels much more comfy than doing it at midnight.

Same advice as everyone else, use a set or dict instead of a list for prev. It will run many times faster.

O(N^2) / 10

i'm trying to learn cpp, I get a terminate called after throwing an instance of 'std::invalid_argument'
what(): stoi
Aborted (core dumped)

I think it's when I find it on the hashmap, am I doing something wrong that I don't see?

int part2(std::ifstream &inputFile2) {
std::unordered_map freqMap;
std::string frequency;
int aux = 0;
int sumFrequency = 0;
int repeatedFreq = 0;

while (!inputFile2.eof()) {
std::getline(inputFile2, frequency);
aux = std::stoi(frequency);
sumFrequency += aux;
if (freqMap.find(sumFrequency) == freqMap.end()) {
freqMap.insert(std::make_pair(sumFrequency, 0));
}
else {
inputFile2.close();
return sumFrequency;
}
}
return 0;

What is the first exercise?

Whoa, that's a high rating! Thanks!

So what's your excuse? ADHD?

Attached: rtfm.png (537x356, 29K)

Isn't it because std::getline will return the line with \n which won't be able to be converted to an int?

def advent1():
set_format("i")

print(sum(column(0)))

frequencies = set([])
result = 0
for freq in itertools.cycle(data):
result += freq[0]
if(result in frequencies):
raise Exception(result)
frequencies.add(result)
how can i reduce script size further? note that set_format(), column() and data are helpers for reading data, along with some other functions unused here

wrong, std::getline split on '\n' by default and removes the '\n'

eww yikes your solution doesn't even pass the test cases

my guess is one of the line in your input is empty so you're trying to stoi an empty string

Attached: Danko.jpg (511x513, 49K)

Well maybe then you have an empty trailing line in your input file?

In this case, it's
>opening the input file
>reading the examples
>jumping directly to code
to save time

>set([])
yikes

int arr[1017] = {/*input numbers*/};
int freq[1017];
int retval1 = 0;
int retval2 = 0;

for(int i = 0; i < 1017; ++i) {
retval1 = retval1 + arr[i];
freq[i] = retval1;
}
for(int i = 0; i < 1017; ++i) {
for(int j = 0; j < 1017 - i; ++j) {
if(freq[i] == freq[j]) {
retval2 = freq[i];
break;
}
}
}

pls bulli I want to improve

My day 2 solution:
data = map(int, open("Day 01 input.txt", "r").read().split("\n"))
freq = 0
freqs = {}
while True:
for f in data:
freq += f
if freq in freqs:
raw_input(freq)
freqs[freq] = 0

And day 1 is literally just:
print(sum(map(int, open("Day 01 input.txt", "r").read().split("\n"))))

>Jow Forums is actually leaving the browser tab for this
var res = 0; [].forEach.call(document.querySelector('body > pre:nth-child(1)').innerText.split('\n'), (i) => { res += Number(i) });
console.log(res);

you mean part1/2 not day hehe

That's how my brain works. I scan and let my intuition form connections. Many brains work similarly. Others are more focused on details and order. Neither are better than the other. It's just different approaches that have their pros and cons.

thenks brehs

Attached: 1537817323386.jpg (600x643, 53K)

I blame being tired.

my day1:2 solution
int solve_part_two(std::ifstream& ifs)
{
int freq = 0;
std::vector freq_changes;
std::unordered_map resulting_freqs{ {0, 1} };

for (int f = 0; ifs >> f;) {
freq += f;
freq_changes.push_back(f);
if (resulting_freqs[freq]++ > 0)
return freq;
}

while (true) {
for (auto const & f : freq_changes) {
freq += f;
if (resulting_freqs[freq]++ > 0)
return freq;
}
}
}

>colors are for children
>my programming language isn't
Come on now, Rob

Attached: 1406978796450.jpg (900x675, 85K)

no really though what's your output with +1 and -1 as input?

You've somehow managed to do worse than the list
I don't know C in detail, but surely there is something like hashtables or something

>I don't know C in detail, but surely there is something like hashtables or something
hahahahaha

>knowing js
yikes

#include
// part 1
int main()
{
int a =
#include "input.txt"
;
printf("%d\n",a);
}

big think

Attached: file.png (794x65, 2K)

Using C for AoC is retarded, and not just as a subset of the way using C for almost anything is retarded
>surely there is something like hashtables
8/8 b8; some Cnile will be along shortly to claim that writing hashtables over and over is an advantage of C

That's funny

After I was done, I realized I could have just pasted the text into LaunchBar's built-in calculator to solve the first half.

Attached: 1521636322806.png (1024x214, 58K)

int main(int argc, char **argv)
{
int device[2000];
int l_device = 0;
int frequency = 0;
int i;

FILE *pfile;
char tmp[20];
int len=20;

int found = 0;
int flist[1300000];
int l_flist = 0;


pfile = fopen("input", "r");

if(pfile == NULL) {
printf("Error opening the file.\n");
exit(1);
}

while ((fgets(tmp, len, pfile)) != NULL) {
device[l_device] = atoi(tmp);
l_device++;
}

fclose(pfile);

/*
for(i=0 ; i

Attached: _render__holo___spice_and_wolf_by_gintoki62-dae5yk1.png (847x943, 612K)

0 for part 1, 1 for part 2
i assumed first frequency (0) is not counted in part 2

Cfags shouldn't be allowed to post

>the absolute state of Cniles

Attached: 1519338139832.gif (220x212, 2.57M)

You inspired me
with open("input.txt", "r") as f:
print(eval(f.read().replace("\n","")))

Pasting it into the Windows calculator was my first thought. It was too long.

Attached: calc.png (480x277, 61K)

nice!

>over and over
Have you ever heard of this concept of libraries?

Python++
int part1(std::vector &data) { return std::accumulate(data.begin(), data.end(), 0); }

int part2(std::vector &data) {
std::unordered_set memo{};
int i{0}, sum{0};
while (memo.insert(sum += data[i++ % data.size()]).second);
return sum;
}

int main() {
std::vector data{std::istream_iterator{std::cin}, {}};
std::cout

ghostbin.com/paste/g43n7
On the off chance Jow Forums lets me post the chars:
data ¨ ((∼∊∘(UCS 13 10)) ⊂ ⊢) NREAD 'I:\\2018d1.txt' NTIE 0
NUNTIE ¯1
sum +/data
sum, 0 {(+≢)>≢T∪,:∩⋄T∇+sum} +\data

If only one could manage sets in the same way it does arrays. May be a fun project.

What the fuck are these?

Are you the guy who used APL last year?

The first is APL, the second is C++20

Dropped

Attached: EB081F03-309A-4931-8077-D285C0E3AC57.jpg (1136x172, 69K)

okay bye

>he doesn't recognize the first one
Wew lad.

Attached: chio_stunned2.png (561x538, 421K)

I think this is the _purest_ version I can end with

Attached: NP.png (582x557, 13K)

Other way around.

Libraries are for babies.

>cum
ah yes

you can play as user, it literally gives you the choice to while signing up

;)))))));)

WHY THE FUCK WILL YOU USE APL?

Every time I see eval in an AoC solution I'm reminded of the user who ran an rm -rf from a malicious input last year.
Didn't work due to permissions, but still a lesson in exploitation of eval.

let me get this clear, part 2. are you looking for a value the frequency lands on two times? the examples are messing me up

>over and over

yes, the first frequency which is repeated

yes

>tfw you didn't have to ask for help in Jow Forums to understand the instructions

Attached: 1492176027172.png (195x259, 6K)

yeah
when the example says
>+3, +3, +4, -2, -4 first reaches 10 twice.
it means loop through them
>+3, +3, +4, -2, -4, +3, +3, +4, -2, -4, +3, +3, +4, -2, -4 etc.

Okay, smartass. Is 0 the first input of part 2?

>Is 0 the first input of part 2?

Attached: 1519223063937.png (645x729, 105K)

>he put me in the screencap
>twice

just make a throwaway r*ddit, they'll ask for an email but you can just leave the box blank

i wondered how they generated frequency changes that could have the second part run long enough, especially when they have multiple sets of data for different users. then i saw that the resulting frequencies form a square wave. that's pretty clever.

>>+3, +3, +4, -2, -4 first reaches 10 twice.
but it only reaches 10 once? what am I missing...

from what i gathered they actually spend a lot of time on generating and testing decent inputs

literally read the rest of his post you brainlet retard

3. 6, 10, 8, 4, 7, 10

sure, but this data set actually has some though behind it. it's just not brute force. each loop over the frequency changes will shift all resulting freqeuencies by a certain amount (the sum of the frequency changes). by using a square wave it's easy to determine how many loops it will take until the first duplicate resulting frequency is achieved: the amplitude of the wave divided by the sum of the frequency changes

mybe ocaml just sucks

Yes. But the good thing is you can improve.

Shit, my code is very slow. Please Jow Forums be honest, am I a filthy code monkey?

Sorry for the repost, I forgot to censor answers.

Attached: aoc1.png (972x613, 38K)

Answers are different for everybody

Mate, everyone gets different inputs.

not completely though, there's a set of inputs that gets distributed

Seriously, I didn't know.

The chances are too low to worry though. Also, it'll call you out for cheating.

>stay up til midnight to do this shit
>wanna see if i can get on the global scoreboard or at least do well on the Jow Forums leaderboard
>know from last year people do this shit in like 30 seconds so i have to go fast
>open up prompt
>5 paragraphs of retarded story shit about santa's elves and time travel at the beginning
>skip to bottom
>crank out solution
>part 2
>looks like first paragrah is more dumb story solution
>skip to bottom
>crank out solution
>didn't work


i'm assuming this is how it went for most people, they're intentionally speedreading to get a good time because the prompt has a lot of pointless flavortext

Little improvement using hashtable instead of a set. Maybe I should code it in C++.

$ time ./aoc1
XXXXXXXXXXXXX
XXXXXXXXXXXXX

real 0m0.072s
user 0m0.068s
sys 0m0.004s

the series repeats r*tard

ok, gofag here
Replaced going over a fucking list with a map and it seems to work perfectly.
aoc$ time (./advent1 < input)
0m00.10s real 0m00.12s user 0m00.02s system

The first input is the first input?

so who here made the fastest solution?

The Fortran guy.

First time writing rust, anyone have any pointers for any bad stylistic things I did?

use std::fs;
use std::collections::HashSet;

fn main() {
let contents = fs::read_to_string("input.txt").unwrap();
let lines: Vec = contents.split("\n").collect();
let digits: Vec = lines.into_iter().map(|x| x.parse::().unwrap()).collect();
let mut cum_sum: i32 = 0;
let mut prev_vals = HashSet::new();
prev_vals.insert(cum_sum);


for xx in digits.iter().cycle() {
cum_sum += xx;
if !prev_vals.contains(&cum_sum) {
prev_vals.insert(cum_sum);
} else {
println!("The first repeating value is {}", cum_sum);
break;
}
}
}

Python is cheating.

Attached: gum_consider.png (540x540, 26K)

lol

Trying to learn CPP with this years AoC, spend most of the time reading docs...

int main()
{
mapOfSums.insert({0, true});
if (in_file.is_open()) {
while (!iterFile()) {
in_file.clear();
in_file.seekg(0, in_file.beg);
}
in_file.close();
}
std::cout

use an unordered set instead of that map silliness

No point in having `lines`. digits = contents.split(...).map(...).collect()
Otherwise looks fine to me