Advent of Code 2017

Are you gonna participate this year? adventofcode.com/
Day 2's puzzle starts in 3 hours!
It's 25 days of code challenges, everyday at midnight!
Every puzzle gives you an input file, you provide the correct output, so there's no need to submit code.
Sup Forums has it's own private leaderboard join code: 194764-c554ff91
(You need to register with an account but you can appear as anonymous)

Other urls found in this thread:

stackoverflow.com/questions/729692/why-should-text-files-end-with-a-newline/729795
twitter.com/SFWRedditVideos

previous thread:

can you still get 2 stars for day 1 if day 2 starts?

You can start anytime, you can even go back to 2015 if you wanted to and still get stars.
The leaderboard scores you on how fast you solved it starting from the release date.
It rewards people who solved it that day, but really, there's no other way to do it, since there's no server-side code execution and everyone likes to share their solutions anyway.

ah that's fine by me, I don't really care about the leaderboard since I don't have the time to compete, just want to get the whole tree

Going to use this as Python practice
with open("input.txt", "r") as file:
rawInput = file.read()
inputList = list(rawInput)
inputList.remove("\n")
i = -1
digitSum = 0
while i < len(inputList) - 1:
if inputList[i] == inputList[i+1]:
digitSum += int(inputList[i])
i += 1

print(digitSum)

part 2
with open("input.txt", "r") as file:
rawInput = file.read()
rawInput = rawInput.replace("\n", "")
inputList = list(rawInput)
half = len(inputList) // 2

i = 0
digitSum = 0
while i < len(inputList):
idx = i + half
if idx >= len(inputList):
idx = idx - len(inputList)
if inputList[i] == inputList[idx]:
digitSum += int(inputList[i])
i += 1

print(digitSum)

This is fun

Which is a good move. I was happened to look at the countdown yesterday right when there was 15 seconds left.
So I thought fuck it, used Ruby because I know I'd solve it faster. No error checking, no tests, just rushed the code until I found the answer, and thought I had it pretty much straight away,
I was still about number 800, and only the first hundred get on the board.

>day 1 part 2 already fucking me up
WHY MUST MY BRAIN BE SO LET

sub day1part1 {
@arr = @_;
$sum = 0;
foreach (-1 .. $#arr-1) {
$sum += $arr[$_] if ($arr[$_] == $arr[$_+1]);
}
print $sum;
}
Choosing to do this in perl.
Haven't figured out the offsetting for part 2 yet, got mad, played rainbow 6 siege, got even more mad, so maybe I'll figure it out later.

At most you only need to change two calculations......

I know its a simple stepping problem but for whatever reason I cant get it right, I come up 12 short every time.

lol wut. I would assume you would be coming up with half of what your value should be. Please post what you have, I want to see how your able to get 12 off

well, I'm off by 12 from the answer to #1. But thinking about it, I shouldn't be getting the same result should I

no not at all. Did you get the new data set for part 2?

The input number doesnt change between parts.
>Although it hasn't changed, you can still get your puzzle input.
It works for the first 3 test cases, but 123123 yields 11 instead of 12.
arr = [1,2,3,1,2,3]
sum = 0
for i in range (-2, len(arr)/2):
if arr[i] == arr[i+(len(arr)/2)]:
sum += arr[i]
print sum

The fourth case (12131415) also yields off-by-one (3 instead of 4)
Am I just being retarded or something?

>thought I had it pretty much straight away,
>I was still about number 800
Really? I wasn't even waiting for the countdown and I didn't know the scoring was time sensitive and I still got #293

Your loop starts at indices -2, 1 instead of -3, 0. It skips the first element.

123123 yields the right number but 12131415 doesnt
Why would shifting back one more do that? Do I need to account for the length of the array for how much I shift backwards?

Here's a small fix to your code that makes it correct, efficient, and generalized

arr = [1,2,3,1,2,3]
sum = 0
for i in range(0, len(arr)/2):
if arr[i] == arr[i+(len(arr)/2)]:
sum += 2 * arr[i]
print sum

I feel retarded now, totally thought I read the input changed.

Also why are you starting your for loop at -2 it should be 0 and that will fix it somewhat. since your loop is only going through half of the array you will need to double the sum after the loop

Because I'm not a good programmer and am not smart enough to realize all I have to do is double the total halfway through

It's okay, I didn't think to stop halfway through and double the total in my first solution either

Yes, arr[0] needs to be compared to arr[len(arr)/2] so the distance between that second value and the end of the array will increase as the array increases.

Are they all gonna be this easy? I mean, I know it's day one, but common...
package main

import ("fmt"
"io/ioutil"
"strconv")

func check(e error) {
if e != nil {
panic(e)
}
}

func dupeSum(n []int, gap int) int {
sum := 0
for i, e := range n {
if n[(i+gap) % len(n)] == e {
sum += e
}
}
return sum
}

func byteToSlice(s []byte) []int {
var out []int
for _, d := range s {
D, err := strconv.Atoi(string(d))
check(err)
out = append(out, D)
}
return out
}

func main() {
input, err := ioutil.ReadFile("AdventOfCodeIn")
check(err)
n := byteToSlice(input[:len(input)-1])
fmt.Println(dupeSum(n, len(n)/2))
}

I'll start doing Advent of Code when it becomes possible to obtain the files for the puzzles anonymously -- that is, no need for an account. I don't care about leaderboards.

>Are they all gonna be this easy?
They increase in difficulty as they go on. This was the easiest one.

also, on a somewhat related note, is Go the best language for code-bowling?

I know, but this is literally one if-statement away from just summing an array.

int solve(std::string s) {
int n = s.size();
int out = 0;
for (size_t i = 0; i < n; i++)
out += (s[(i + n/2) % n] == s[i]) ? (s[i] - '0') : 0;
return out;
}

just make a github, you don't even need to confirm your email

you should have one anyway, why are you even on Sup Forums?

Any Rust homosexuals in here? I want to laugh at someone.

Just search the old thread for "fn main"

FIFTEEN MINUTES, BOYS

there were no newline characters you can remove that check, also for part 2, you can just iterate through half of the array and then double your result

GIVE MILKY

I had one at the end of my local input file too stackoverflow.com/questions/729692/why-should-text-files-end-with-a-newline/729795

Although I prefer to handle it with rstrip().

TWO MINUTES

what a disappointment i thought it would be more challenging

I fucked up the second star two different ways, but still made it to rank 19 for the day

done with part one :3

okay i don't understand part 2

why is the third row = 2? none divide into eachotherr evenly i dont understand

My day 2 part 2 solution, given the input as a 2D array

let d2p2 = s => s.map(w=>w.map((a,i,x)=>x.map(b=>(b==a||b%a)?0:b/a).reduce((a,b)=>a+b,0)).reduce((a,b)=>a+b,0)).reduce((a,b)=>a+b,0)

3 divides into 6

oh you're right im a dummy ty

im too slow i wanted to be the top of the Sup Forums leaderboards >

who the FUCK is this autist

Consider creating an array of digits that are your number twice. As in, for 1122 you want [1,1,2,2,1,1,2,2]. It really helps to avoid going out of index range.

4 minutes boys

sum = 0
for lines in open("in.txt").read().split("\n"):
numbers = [int(a) for a in lines.split(" ")]

for i in range(len(numbers)):
for j in range(len(numbers)):
if i != j and (numbers[i] % numbers[j]) == 0:
sum += numbers[i]//numbers[j]
print(sum)

Well shoot, my first pass isn't nearly that fancy-looking.

with open('input.txt', 'r') as myfile:
total = 0

for line in [s for s in myfile.readlines()]:
nums = list(map(int, line.split()))
for i in range(0, len(nums)):
for j in range(0, len(nums)):
if nums[i] % nums[j] == 0 and i != j:
total += nums[i] / nums[j]

print(total)

I do have a github. I don't want my github to be associated with this guy's shit. I just want to do the challenges. I don't want to participate in any social events.

>timestamp and solution match

i messed up and now i have to wait 2 minutes grr >:(

int main(){
int min, max;
int sum = 0;
for (int i = 0; i < 16; i++){
for (int j = 0; j < 16; j++){
for (int k = 0; k < 16; k++){
if(numarr[i][j] != numarr[i][k] && numarr[i][j] %numarr[i][k] == 0){
sum += (numarr[i][j]/numarr[i][k]);
printf("%d", (numarr[i][j]/numarr[i][k]));
}
}
}
}
printf("\n%d", sum);


}
no ragrets

sounds like you're unemployable then
nobody wants to hire a socially awkward loner who's probably gonna go postal after he gets fired for being difficult to talk to

Damn I forgot about this. Well here's my solution

void solve() {
int checksum = 0;
for (int i = 0; i < 16; i++) {
int max;
std::cin >> max;
int min = max;
for (int j = 1; j < 16; j++) {
int x;
std::cin >> x;
if (x > max)
max = x;
else if (x < min)
min = x;
}
checksum += (max - min);
}
std::cout arr[j];
for (int j = 0; j < 15; j++) {
for (int k = j + 1; k < 16; k++) {
int x = arr[j], y = arr[k];
if (y > x) std::swap(x, y);
if (x % y == 0)
checksum += x/y;
}
}
}
std::cout

make a RADDITZ account

total = 0
for x in str.split('\n'):
for c in x.split(' '):
for d in x.split(' '):
if c != d:
if int(c) % int(d) == 0:
total+=(int(c) / int(d))
print total

p1
void main(string[] args)
{
import std.stdio, std.conv, std.string, std.array, std.algorithm;

ulong sum = 0;
foreach (string row; File(args[1], "r").lines)
{
auto x = row.strip().split().map!(to!uint).array();
sum += x.maxElement - x.minElement;
}
writeln(sum);
}

The hardest part was getting the input into a usable format

package main

import ("fmt"
"io/ioutil"
"strconv")

func check(e error) {
if e != nil {
panic(e)
}
}

func checksum(a [][]int) int {
check := 0
for _, row := range a {
max, min := row[0], row[0]
for _, e := range row {
if e > max {
max = e
} else if e < min {
min = e
}
}
check += max - min
}
return check
}

func evenDiv(a, b int) int {
n, d := 0, 0
if a > b {
n, d = a, b
} else {
n, d = b, a
}
div := 0
if float64(n/d) == float64(n)/float64(d) {
div = n/d
}
return div
}

func evenDivSum(n [][]int) int {
sum := 0
for _, row := range n {
for i, a := range row {
for _, b := range row[i+1:] {
sum += evenDiv(a,b)
}
}
}
return sum
}

func byteToArray(s []byte) [][]int {
var (
out [][]int
row []int
)
i := 0
for i < len(s) {
if s[i] != ' ' && s[i] != '\t' && s[i] != '\n' {
str := string(s[i])
i += 1
for i < len(s) && s[i] != ' ' && s[i] != '\t' && s[i] != '\n' {
str += string(s[i])
i += 1
}
D, err := strconv.Atoi(str)
check(err)
row = append(row, D)
}
if s[i] == '\n' {
out = append(out, row)
row = []int{}
}
i += 1
}
return out
}

func main() {
input, err := ioutil.ReadFile("AdventOfCodeIn")
check(err)
n := byteToArray(input)
fmt.Println(evenDivSum(n))
}


Includes solutions to parts one and two.

>The hardest part was getting the input into a usable format
Sounds like par for the course for competition programming.

rust?

>The hardest part was getting the input into a usable format
this

After processing and sorting the input:
(: divides? (fixnum (list-of fixnum) -> (or boolean fixnum)))
(define (divides? n xs)
(call/cc (lambda (break)
(foldl (lambda (acc x)
(let ((divide (/ n x)))
(if (fixnum? divide)
(break divide)
#f)))
#f
xs))))

(: divider ((list-of (list-of fixnum)) -> fixnum))
(define (divider xs)
(call/cc (lambda (break)
(foldl (lambda (acc x)
(let ((does-it-divide? (divides? x acc)))
(if does-it-divide?
(break does-it-divide?)
(cdr acc))))
(cdr xs)
xs))))

these are fucking dumb

why even bother with this easy bullshit?

i'd way rather spend the time doing actually interesting and challenging problems

(apply + (map (lambda (x) (divider x)) sorted-input-list))

>t. brainlet who can't solve the problems quickly

My fucking eyes, I thought Go was supposed to be easy to read.

i think its fun it's like a race with you guys

It's all about getting it right quickly

Go

My (retarded) possible solution to day 2:
filename = input("Filename: ")

lines = [line.rstrip('\n') for line in open(filename)]

content = []
for c in lines:
content.append(list(map(int,c.split('\t'))))

summe1 = 0
summe2 = 0

for c in content:
summe1 += (max(c) - min(c))

for j in range(0,len(c)):
for k in range(j+1,len(c)):
if (c[j] % c[k] == 0):
summe2 += c[j] / c[k]
elif (c[k] % c[j] == 0):
summe2 += c[k] / c[j]

print(summe1)
print(summe2)

How fucked am I?

bourne shell~

#!/usr/bin/env sh

input="$(cat input.txt)"
p1sum=
p2sum=
IFS='
'
for line in $input; do
line="$(echo "$line" | tr ' \t' '\n' | sort -n)"

# part 1: sum of differences between
# largest and smallest number on every line
low=$(echo "$line" | head -1)
high=$(echo "$line" | tail -1)
p1sum=$((p1sum + (high - low)))

# part 2: sum of dividends between only 2
# evenly divisible numbers on every line
for i in $line; do
for j in $line; do
if [ $i -ne $j ]; then
if [ $(expr $i % $j) -eq 0 ]; then
p2sum=$((p2sum + (i / j)))
fi
fi
done
done
done

>The hardest part was getting the input into a usable format
just like the first one

I hope all the puzzles aren't about processing whitespace and strings. That would be fucking lame.

Is there any linear or nlogn algorithm for d2p2.

Writing n^2 algorithms makes me sick.

And probably all the rest.

Probably smart to start making some text-to-(some random data type) functions

>get both stars in 8 minutes: didn't even place >global fastest time for BOTH STARS: 1:15

Attaching muh code

def calc_checksum(spreadsheet):
calcr = 0
for row in spreadsheet:
v_min = float('inf')
v_max = float('-inf')
for v in row:
v_min = min(v, v_min)
v_max = max(v, v_max)
calcr += v_max - v_min
return calcr

# Lame n^2 algortihm. Is there something better?
def calc_divisibility_checksum(spreadsheet):
calcr = 0
for row in spreadsheet:
for v1, v2 in itertools.combinations(row, 2):
min_v = min(v1, v2)
max_v = max(v1, v2)
if max_v % min_v == 0:
calcr += max_v // min_v
continue
return calcr

>The hardest part was getting the input into a usable format
People have said it and I'll say it again...
This

I basically had to do two extra functions to get the text input into an array of ints.

After that it was really straightforward, but it's really getting down and dirty with some of the C standard library functions (although strspn and strcspan really should get better/more descriptive names. I can never remember which is which)

/* Almost nothing is done in main. Main program flow goes
main -> getLineNums (text ->ints) -> getDivision(checks for divisibility)
-> getChecksum (gets division for each line)
*/
int main()
{
FILE* s = fopen("Day2_input.txt", "r");
if(s == NULL)
{ printf("FILE_NOT_FOUND\n");
return 0;
}

getChecksum_PART2(s);
}


int getDivision(int* line, int length)
{
int a, b, i, j;
for(int i = 0; i < length; i++)
{
a = line[i];
for(j = i+1; j < length; j++)
{
b = line[j];
if(a % b == 0)
return a / b;
if(b % a== 0)
return b/a;
}
}
return 0;
}

int* getLineNums(char* str)
{
int curr_num, len = strlen(str);

int* line = malloc(sizeof(int) * ARRAY_SIZE);
int ind = 0;
while(*str != '\0')
{
curr_num = atoi(str);
line[ind] =curr_num;

/* Go to first numeric character */
str += strspn(str, NUMBERS);
/* skip any numeric characters */
str += strcspn(str, NUMBERS);
ind++;
}
return line;
}


int getChecksum_PART2(FILE* stream)
{
char line[LINE_LENGTH];
int checkSum = 0;
while(fgets(line, LINE_LENGTH, stream) != NULL)
{

int* temp = getLineNums(line);
checkSum += getDivision(temp, ARRAY_SIZE);
free(temp);
}
printf("CHECKSUM: %d\n", checkSum);
return checkSum;
}


>tfw most of my code is just formatting the input

I should add. This is Part 2 of today's problem

I was doing C last year, I used 2 nested instances of strtok to split strings by line and then individual integer tokens.
I was counting them ahead by making copies of strings and then doing a "dry run" of strtok to count how many tokens I needed to allocate space for.

Just write a vector, it saves you so much trouble.

Keyboard battery got finished. Good think I had a spare.
p2
void main(string[] args)
{
import std.stdio, std.conv, std.string, std.array, std.algorithm;

ulong sum = 0;
foreach (string row; File(args[1], "r").lines)
{
auto x = row.strip().split().map!(to!uint).array().sort().array();
line: foreach (i, a; x)
{
foreach (b; x[i .. $])
{
if (b > a && (b % a == 0))
{
sum += b / a;
break line;
}
}
}
}
writeln(sum);
}

That's D.

I used Sepples, but just hardcoded the array to save time. Used regex to replace the n spaces with a single comma, then used a vim macro qa^i{ESC$a},ESC^j then did 16@a. Both parts was easy after.

Microsounds chan pls notice me

thing*

And it's the same chink bastard who has come first in everything so far. Looks like he ended up coming 6th overall in last year's.

I'm thinking about this too. Maybe one way would be, on a per line basis:
>double the int you're looking at and add it to the list
>sort the list
>remove everything up to and including the doubled int, since none of those could be multiples and if the double was already present, the duplicate will remain
>check divisibility of remaining list

Does mine count as O(n)?

hes so smart and so fast uwu

>an hour late
>still in top 10
explain yourselves Sup Forums

>actual logic is almost trivial
>converting files into variables is hell
shoot me

>converting files into variables is hell
?

show me a simple way to turn the provided puzzle text into a 2D array of integers in C++

>not nigger rigging a solution as fast as possible
i go full POO for these desu

you spend more time writing boilerplate to tokenize your file and then parsing your inputs rather than actually comparing them.

I've never looked at D before, but is that everything except for the doubling step?

>C++
Oh I see where you are coming from.
gg, your STL sucks like shit and there isn't range yet.
>the doubling step
??
That's a fully working solution for problem 2 if that's what you are asking.

What language do you write your solution in? Please post the input portion of the code.

Yeah I meant it included what I outlined here , except for adding i*2 to the array and starting from there, since nothing below i*2 can be a multiple.

anyone else getting a connection error when trying to post shit?

auto x = row.strip().split().map!(to!uint).array();

Oh, for making it 2D to read the whole file into memory, prefix it with file.byline()