/aocg/ - Advent of Code General #9

Chad eval() 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.

The new leaderboard with empty space is
join-code: 43046-941b8011

The old (full) leaderboard is
join-code: 194764-c554ff91

Other urls found in this thread:

hastebin.com/umarocayic.cs
github.com/Smatchcube/Advent-of-Code-2017/blob/master/day8.py
pastebin.com/raw/YAN9n3KY
pastebin.com/TE0sJeUk
twitter.com/NSFWRedditImage

Whoops this was supposed to be thread #10

Try to make the next one thread #11

>I know that this is exactly the witty remark you wanted to make, big boy
wtf stop projecting
I just wanted to know how you are building the tree

IT WAS SUPPOSED TO BE SWITCH NOT IF ELSE!

data = [x.rstrip().split() for x in open("d8.txt")]
data = [(x[0], x[4], '%s+=%c%selse 0' % (x[0], '+' if x[1] == 'inc' else '-', ' '.join(x[2:]))) for x in data]
regs = dict.fromkeys(sum(tuple(zip(*data))[0:2], ()), 0)
mx = 0

for x in data:
exec(x[2], {}, regs)
mx = max((mx, max(regs.values())))

print("P1:", max(regs.values()))
print("P2:", mx)

>tfw one of your registers is named 'for'
Just fuck me up senpai

Why does that matter

guess I'm virgin programmer, but it's not that terrible as on pic
fields := strings.Fields(line)
reg := fields[0]
shift, _ := strconv.Atoi(fields[2])
if fields[1] == "dec" {
shift *= -1
}
var cond bool
r := Registers[fields[4]]
n, _ := strconv.Atoi(fields[6])
switch fields[5] {
case "==":
cond = r == n
case "!=":
cond = r != n
case ">":
cond = r > n
case "=":
cond = r >= n
case "

he's executing every line as python code replacing only "inc" to "+="

that's cheating

I have to add a line to change it to something else, otherwise eval() throws an execption

:%s/for/fqqqr

If you try to sub in for inc/dec and then eval the whole line, it will interpret "for" as its reserved word.

good job you spotted that, I'd have wasted hours trying to debug that

Last night someone posted a C++ abomination that was attempting to parse the entire textfile 1 character at a time without even splitting it into tokens or even skipping ahead to the next space with some strstr() abuse.

OH MY GOSH I'M SO SORRY

Well shit, I guess I'm still a virgin.

tfw when switch virgin

It wouldn't matter if you made every register the keyword of a dict

>100 lines of code in java
should i switch something more usable?

Day 8 part 1
const fs = require('fs')
let s = fs.readFileSync('in8').toString().split('\n').slice(0,-1).map(a=>a.split(' '))

let ops = {
'==': (a,b) => a==b,
'!=': (a,b) => a!=b,
'': (a,b) => a>b,
'=': (a,b) => a>=b
}

console.log(Object.values(s.reduce((a,b)=>Object.assign(a,{[b[0]]:(a[b[0]]||0)+((ops[b[5]](a[b[4]]||0,+b[6]))?(+b[2]*(b[1]=='inc'?1:-1)):0)}),{})).sort().reverse()[0])

I'm 101% confident recursive functions will be slower

Here is my code for C#

hastebin.com/umarocayic.cs

The problem with "finding solution without extra loops" is that in 99% cases people who think they know the language suggest some built-in tools that are just syntactic sugar for same loop realized inside the extension method/helper func. When I mean "reduce the amount of loops" I mean some clever solution by logic juggling rather than "oh look at my super-short code I wrote with lambda and linq queries, who cares if it is the same amount of loops in general or more!"

Again, I know I can use recursion but in my experience in ALWAYS 2x or more slower. Classic Fibonacci chain is the example, loops is always faster.

use better data structures
t. did everything in 1 loop

LOL

After some effort, one line in lisp.
(day8)

pls no bully '-'

More data - more memory used.
You have to decide you want to use more memory or CPU
>lol I used less than 1Mb retard
yeah, now generate 1m-10m entries like that and process them. How many memory used now?

This one is even worse so it's funnier.

Im sure even an old pc could handle 10m entries.
Also i'm sure you will grow old while waiting for an 6 loops algorithm to finish

This looks pretty clean. I didn't know you could map functions, good to know.

When you say 6 loops, do you mean parsing 6 times through the input or something else?

When i say 6 loops, i mean 6 loops
>>tfw total amount of loops is 6 now
im assuming you are the same guy

I think you failed to understand my point.

6 loops total in whole solution. To process data only 1 loop, it never changed or transformed later.

Ok, to clarify:
6 loops - 6 loop sections, regardless of the type (for/foreach/while)
Not 6 ITERATIONS when loop only does 6 rounds

post code
also speaking of 10m entries, is there any file like this?

imbricated or separated?

No one r8'd my day 8.
pls no bully

My Code is here:
Total, including nested

6/10

why

>using a map
>not using a switch statement generated by a macro

put inc and dec in a map too

>tfw didn't start until a few hours into day 6
>tfw will never catch up on the leaderboard

>tfw no qemu advent's calendar this year

>Day 7 00:52:43 04:47:52
>~4 hours difference
pajeet spotted

Fuck problem 9 from AoC 2015. It's literally just traveling salesman. There's no easy way out. Unless you come up with some inspired new algorithm you're stuck with an O(2^n) solution. Last year had a lot of A* puzzles, 2015 was just plain wild.

If you think just the time difference is pajeet-tier, see how godawful my solution was.

I didn't have the insight that you could determine it while populating the tree with the cumulative weights.

I'm not reading this

>lambdas instead of std::greater, std::lower et al from functional header
>no curly braces in single statement blocks
>cout instead of printf
>typedef instead of using
you tried

who cares i bruteforced that one

Bruteforce it, it's not that big graph. There were 2 traveling salesmen in 2015, but some different graph/grid searches in 2016 where you had to apply A*.

it's "just" O(n!) since you only go through permutations

>some different graph/grid searches in 2016 where you had to apply A*.
Really? I'm doing the 2016 challenges, currently I'm at the 15th one, but I haven't see anything like that. Maybe later

day11, day13, day15, day17, day22, day24
how was your day11 part two? I remember having issues with this one

tiem to hit the leaderboard for day 8 i guess

The ones with the generator-chip pairs?
I first tried to do a simple BFS search, but implementing the constraints and the inheritance (sorry english is not my first language) was a bitch, so I searched for a representation of the data that suited the problem the most.
After that, I did a BFS, but it was WAY TOO SLOW : 10 minutes to compute 5 steps ahead. This forced me to look for ways to cut useless solutions. That's when I noticed that all pairs were interchangeable within a solution, and checking for equivalent solutions already computed led to reasonable times (a couple seconds for part 1)

Part 2 was just a little bit longer, but not very much

>day 13
This was a simple Dijkstra to me, no need to further complicate it

>day 15
I just bruteforced it and the computation time was still short

Here is my solution : github.com/Smatchcube/Advent-of-Code-2017/blob/master/day8.py

mfw codelet and finished 3a

the chad eval is defeated

d["for"] shouldn't have been a problem

I haven't done this kind of thing before. If I wanted to do more like this, what websites should I use?

That doesn't seem right, can you try it on my input?
pastebin.com/raw/YAN9n3KY

exercism.io is noice

Thanks

Fuck you, hopefully i run the code without permission.
Nice try though.

cheeky

>eval without globals set to {"__builtin__":{}}
user...

it just work

Explain

Shit, I meant {"__builtins__":{}}

oooh, you little tyke! *tsk* What are you like? ;)

lol

Actually this bait will never work because nobody run the script with sudo permissions.

what the fuck do you even mean sudo permissions
and why would you need sudo to nuke all of personal user-owned files?

Here's problem 8 again with exec and eval

Was pretty fun, but about half of my code was parsing strings, which whilst I don't mind isn't really challenging. Your solutions are a lot shorter than mine today.

pastebin.com/TE0sJeUk

What if any of the words is "words"?

Ah fuck I can do it way better if I split it into words first i'm retarded

>pastebin.com/TE0sJeUk
ewwwwwwwww

Doesn't matter because they're all embedded in R so it would just be R["words"]

OK I simplified it a lot, lots nicer now.

import Data.Map.Lazy (Map, empty, insert, adjust, elems, (!))
import Data.List (isInfixOf)

main :: IO ()
main = print = Int
getMaxRegisterVal input = processInstructions $ mkRegisters input
where mkRegisters = foldl insertRegister empty
processInstructions mapping = fst $
foldl processInstruction (0, mapping) input

insertRegister :: Map String Int -> String -> Map String Int
insertRegister mapping xs = insert secondReg 0 $ insert firstReg 0 mapping
where (firstReg, _, secondReg, _, _) = parseInstruction xs

processInstruction :: (Int, Map String Int) -> String -> (Int, Map String Int)
processInstruction (maxVal, mapping) instruction
| (mapping ! secondReg) `operator` secondNum = (newMaxVal, newMapping)
| otherwise = (maxVal, mapping)
where newMapping = adjust (+firstNum) firstReg mapping

newMaxVal = max (maximum $ elems newMapping) maxVal

(firstReg, firstNum, secondReg, operator, secondNum)
= parseInstruction instruction

parseOperator :: (Ord a) => String -> (a -> a -> Bool)
parseOperator ">=" = (>=)
parseOperator "" = (>)
parseOperator "

>simplified

let input = `...`;
let max = Number.NEGATIVE_INFINITY;

let regs = new Proxy ({}, {
get: (target, prop) =>target[prop] || 0
});

input
.split('\n')
.forEach(line => {
let [reg1, op, amount, , reg2, comp, num] = line.split(' ')

if (eval(`regs[reg2] ${comp} +num`)) {
regs[reg1] += op === 'inc' ? +amount : - +amount ;

if (regs[reg1] > max) {
max = regs[reg1];
}
}
});

console.log(Math.max(...Object.values(regs)), max);

ez pz year

That just means more people are involved, not that it's easier

>tfw on leaderboard for day 11, 2016

>pastebin.com/raw/YAN9n3KY
eval chads BTFO

>continuous graph for discrete data

>map.Add(temp[0].Split(' ').FirstOrDefault(), new KeyValuePair(Convert.ToInt32(temp[0].Split(' ').LastOrDefault().Replace('(', ' ').Replace(')', ' ')), kids.Split(',').ToArray()));

Jesus christ.

does C/++ have eval?

It looks terrible but I run multiple iterations with different variants and could not make it run faster.
Like, this looks better:

string s = "xcpuy (20)";
string justDigits = new string(s.Where(char.IsDigit).ToArray());


but runs slower when tested in 100000 loops

How would it? It's compiled.

templates

So C is for virgins

>2017
> not writing a combinatorial parser with test cases

Day 7 fucked my shit up because I spent all day writing a nom parser.. Made day 8 nice and comfy though.

>still haven't finished day 7 part 2

Day seven was the hardest so far imo, and I was unlucky enough to wake up late, so I didn't have a lot of time before I had to go work second shift at my wagie job. Pic related, day 7 in Erlang.

I need to catch up with my sleep schedule, going to bed now

>tfw I'll lost my top10 position in Sup Forums leaderboard

Day 8 was relatively easy, although formatting the input required me to use vim macros for the first time in my life, so it was a nice learning experience. I probably should have stored inc, dec, and > < >= etc. as atoms and not as strings, but I already had them formatted as strings, and I was too lazy to re-format the input in vim.
I kinda regret waking up so late and falling like 10 spots in the leaderboard, but I'm gonna work first shift next week, so my score is gonna suffer a lot anyway.

Did anyone do part 1 of 2015's day 23? If so, could you please tell me if b = 0 at the end of this?
jio a, +16
inc a
inc a
tpl a
tpl a
tpl a
inc a
inc a
tpl a
inc a
inc a
tpl a
tpl a
tpl a
inc a
jmp +23
tpl a
inc a
inc a
tpl a
inc a
inc a
tpl a
tpl a
inc a
inc a
tpl a
inc a
tpl a
inc a
tpl a
inc a
inc a
tpl a
inc a
tpl a
tpl a
inc a
jio a, +8
inc b
jie a, +4
tpl a
inc a
jmp +2
hlf a
jmp -7

I tried doing it by hand and the answer was 0. I wrote a program, and it answered back 0. I can't seem to find an error anywhere.

Nevermind, I forgot that jio is jump if ONE, not ODD. Why didn't I think of this earlier? The thing looked awfully like Collatz anyway.