Quantcast
[ 3 / biz / cgl / ck / diy / fa / g / ic / jp / lit / sci / tg / vr / vt ] [ index / top / reports / report a bug ] [ 4plebs / archived.moe / rbt ]

Due to resource constraints, /g/ and /tg/ will no longer be archived or available. Other archivers continue to archive these boards.Become a Patron!

/g/ - Technology


View post   

[ Toggle deleted replies ]
File: 139 KB, 483x542, advent of code.png [View same] [iqdb] [saucenao] [google] [report]
63650759 No.63650759 [Reply] [Original] [archived.moe] [rbt]

Are you gonna participate this year? http://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.
/g/ has it's own private leaderboard join code: 194764-c554ff91
(You need to register with an account but you can appear as anonymous)

>> No.63650783

previous thread: >>63627886

>> No.63650785

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

>> No.63650829

>>63650785
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.

>> No.63650845

>>63650829
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

>> No.63651213

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)

>> No.63651560

>>63651213
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

>> No.63651854

>>63650845

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.

>> No.63651863
File: 142 KB, 686x441, 1488470771220.png [View same] [iqdb] [saucenao] [google] [report]
63651863

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

>> No.63651873

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.

>> No.63651884
File: 86 KB, 500x500, 1438038628425.jpg [View same] [iqdb] [saucenao] [google] [report]
63651884

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

>> No.63651893

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

>> No.63651905

>>63651893
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

>> No.63651922

>>63651905
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.63651925

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

>> No.63651961

>>63651925
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?

>> No.63651986

>>63651854
>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

>> No.63651991

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

>> No.63652019

>>63651991
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?

>> No.63652021

>>63651961
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

>> No.63652040

>>63651961
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

>> No.63652059

>>63652040
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

>> No.63652066

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

>> No.63652067

>>63652019
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.

>> No.63652136

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))
}

>> No.63652142

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.

>> No.63652144

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

>> No.63652156

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

>> No.63652170

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

>> No.63652181

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;
}

>> No.63652197

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

you should have one anyway, why are you even on /g/?

>> No.63652201

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

>> No.63652207

>>63652201
Just search the old thread for "fn main"

>> No.63652212
File: 997 KB, 261x391, 1504702852580.gif [View same] [iqdb] [saucenao] [google] [report]
63652212

>>63650759
FIFTEEN MINUTES, BOYS

>> No.63652242

>>63651213
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

>> No.63652261

>>63652212
GIVE MILKY

>> No.63652266

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

Although I prefer to handle it with rstrip().

>> No.63652315

TWO MINUTES

>> No.63652357

what a disappointment i thought it would be more challenging

>> No.63652382

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

>> No.63652436

done with part one :3

>> No.63652462

>>63652436
okay i don't understand part 2

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

>> No.63652469

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)

>>63652462
3 divides into 6

>> No.63652477

>>63652469
oh you're right im a dummy ty

im too slow i wanted to be the top of the /g/ leaderboards ><

>> No.63652483
File: 80 KB, 256x273, 2017-12-02-001352_256x273_scrot.png [View same] [iqdb] [saucenao] [google] [report]
63652483

>>63650759
who the FUCK is this autist

>> No.63652495

>>63651863
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.

>> No.63652532

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)

>> No.63652533

>>63652469
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)

>> No.63652536

>>63652197

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.

>> No.63652558
File: 498 KB, 262x200, 1498739548066.gif [View same] [iqdb] [saucenao] [google] [report]
63652558

>>63652533
>>63652532
>timestamp and solution match

>> No.63652575

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

>> No.63652586
File: 18 KB, 300x300, fuckmyshitup.jpg [View same] [iqdb] [saucenao] [google] [report]
63652586


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

>> No.63652589

>>63652536
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

>> No.63652595

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 << checksum << std::endl;
}


and

void solve() {
int checksum = 0;
for (int i = 0; i < 16; i++) {
int arr[16];
for (int j = 0; j < 16; j++)
std::cin >> 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 << checksum << std::endl;
}

>> No.63652607

>>63652142
make a RADDITZ account

>> No.63652614

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

>> No.63652634

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);
}

>> No.63652635

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.

>> No.63652639

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

>> No.63652641

>>63652634
>>63652635
rust?

>> No.63652668

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

>> No.63652677

>>63650759
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))))

>> No.63652685

these are fucking dumb

why even bother with this easy bullshit?

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

>> No.63652688

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

>> No.63652699

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

>> No.63652700

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

>> No.63652707

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

>> No.63652714

>>63652685
It's all about getting it right quickly

>> No.63652726

>>63652641
Go

>> No.63652729

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?

>> No.63652730
File: 70 KB, 540x716, kawaii~.jpg [View same] [iqdb] [saucenao] [google] [report]
63652730

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

>> No.63652743

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

>> No.63652748

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

>> No.63652750
File: 613 KB, 500x374, 1470659985143.gif [View same] [iqdb] [saucenao] [google] [report]
63652750

Is there any linear or nlogn algorithm for d2p2.

Writing n^2 algorithms makes me sick.

>> No.63652753

>>63652743
And probably all the rest.

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

>> No.63652769
File: 451 KB, 640x480, WHY DOUSHITE.gif [View same] [iqdb] [saucenao] [google] [report]
63652769

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

>> No.63652770
File: 534 KB, 500x374, 1470662268030.gif [View same] [iqdb] [saucenao] [google] [report]
63652770

>>63652750
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

>> No.63652790
File: 728 KB, 960x776, Distressed Miku.png [View same] [iqdb] [saucenao] [google] [report]
63652790

>>63652635
>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

>> No.63652798

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

>> No.63652825

>>63652790
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.

>> No.63652829

>>63652634
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.

>> No.63652855

>>63652790
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 [email protected] Both parts was easy after.

>> No.63652861
File: 68 KB, 848x480, 158261381.jpg [View same] [iqdb] [saucenao] [google] [report]
63652861

Microsounds chan pls notice me

>> No.63652876

>>63652829
thing*

>> No.63652883

>>63652769
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.

>>63652750
>>63652770
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

>> No.63652904

>>63652883
Does mine count as O(n)? >>63652829

>> No.63652910

>>63652861
hes so smart and so fast uwu

>> No.63652931

>an hour late
>still in top 10
explain yourselves /g/

>> No.63652936

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

>> No.63652940

>>63652936
>converting files into variables is hell
?

>> No.63652947

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

>> No.63652948

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

>> No.63652951

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

>> No.63652956

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

>> No.63652967

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

>> No.63652973

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

>> No.63652989

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

>> No.63652990

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

>> No.63652993

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

>> No.63652998

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

>> No.63653001

>>63652993
AHHH FUNCTIONAL NIGGERS GET OUT GET OUT GET OUT

>> No.63653007
File: 84 KB, 1000x928, 1456205750415.jpg [View same] [iqdb] [saucenao] [google] [report]
63653007

>>63653001
Don't worry, hopefully C++20 will get ranges

>> No.63653021

>>63653007
maybe one day functional fags will be able to get a job :^)

>> No.63653041

>>63653021
That's not even functional. For example,
map => std::transform
sort is self explanatory
These are not pure.

>job
I got better paying one than that of an average programmer :^^)

>> No.63653055

>>63653041
>if it ain't pure it ain't functional
oh fuck off, you functional faggots are unbearable about your purism

>> No.63653065

Is it just me or was this one substantially easier than yesterday's?
bigDif :: [Int] -> Int
bigDif xs = maximum xs - minimum xs

evenDiv :: [Int] -> Int
evenDiv xs = case [x | x <- drop 1 xs, ((head xs) `mod` x) == 0] of
[] -> evenDiv $ drop 1 xs ++ [head xs]
[y] -> head xs `div` y

main = do
contents <- getContents
let matrix = [[read x :: Int | x <- words xs] | xs <- lines contents]
putStrLn $ "Part 1: " ++ (show $ sum $ map bigDif matrix)
putStrLn $ "Part 2: " ++ (show $ sum $ map evenDiv matrix)

>> No.63653075
File: 42 KB, 495x810, 15894523_758.jpg [View same] [iqdb] [saucenao] [google] [report]
63653075

>>63653055
Why do you keep calling me functional? OwO
I'm not even pure

Ask this one, and he'll explain why purism is important for functional fags >>63653065

>> No.63653076

>>63652973
Here's how I did it in clojure
(map (partial map int) (split-lines input))


>>63653001
make me

>> No.63653083

>>63653076
>lisp
>functional

>> No.63653096

>>63653083
Clojure is very much functionally opinionated. As much so as any modern ML.

>> No.63653125

not sure what I'm doing wrong(day 2)
#!/usr/bin/python3
from sys import argv

checksum = []
with open(argv[1], 'r') as spreadsheet:
for line in spreadsheet:
data = line.split()
checksum.append(abs(int(max(data)) - int(min(data))))
print(sum(checksum))

>> No.63653127

My Day 2 solution in Python:
from itertools import combinations

def main():
input = []
with open('D2.txt') as handle:
input = [list(map(int, row.split())) for row in handle.read().strip().split('\n')]

def sum_min_max(row):
return max(row) - min(row)

def sum_divisible(row):
for (x, y, ) in combinations(row, 2):
if x % y == 0:
return int(x / y)

if y % x == 0:
return int(y / x)

return 0

def solve(input, fun):
total = 0
for row in input:
total += fun(row)

return total

print('P1 Result: {}'.format(solve(input, sum_min_max)))
print('P2 Result: {}'.format(solve(input, sum_divisible)))

if __name__ == '__main__':
main()

>> No.63653154

>>63653125
For starters, you don't need the abs since max - min guarantees a positive answer for this input.
That and you're casting the wrong thing to int here. You need
data = [int(x) for x in line.split()]

>> No.63653177

>>63652589

Gonna be honest, never been fired for being unsociable. But then again, I'm a researcher, and socializing is not expected of me.

>> No.63653185

>>63652536
> I don't want my github to be associated with this guy's shit
when I logged in via google it gave me the option to participate anonymously, so my email address doesn't show up on a leaderboard or anything

>> No.63653190

>>63653125
nevermind, found the error

>> No.63653199

>Noko hasn't done part two yet
kek

>> No.63653201
File: 457 KB, 698x1025, 1509452284799.png [View same] [iqdb] [saucenao] [google] [report]
63653201

eh these challenges arent that tricky
im glad im cute enough to complete them

>> No.63653231

>>63653185

Why the hell does this guy want us to log in with accounts? Why can't he just give us the files directly with no authentication?

>> No.63653250

>>63653231
just make a throw away github with a cockli email you autist

>> No.63653256

>>63653231
They're randomly generated and persistent for each account

>> No.63653276

>>63653256

Right, but you can randomly generate a file without associating it with an account, and I don't need it to be persistent because I don't intend to show up on any leaderboards.

>> No.63653281

>>63653231
I think it's to prevent scrapers from raping the site too much.

>> No.63653288

>>63653281

Then don't allow a given IP to make more than a certain amount of accesses in a given time period?

>> No.63653298

>>63653288
Fuck man, I don't know.

>> No.63653333

>>63653298

Author's just a faggot who wants to datamine us.

I just wish there was a github repository somewhere with a bunch of the input files so we can make a program without interacting with his website at all.

>> No.63653354

>>63653333
well you can always use the simple inputs he provides
though you're going to miss out on the second half of each problem

>> No.63653359

>>63653231
Why don't you go complain on the official subreddit?
The creator answers every post, I'm sure you'll get his attention before getting ass raped by the mods with your rude demeanor.

>> No.63653366

>>63653231
Because there's a set of inputs, you get one assigned to your account, this way you can't cheese top 100 places on the leaderboard.

>> No.63653428

Solved day 2 with Excel, 200iq here.

>> No.63653440

>>63653333
I'm certain if he wanted to make this 100% anonymous he could, he just didnt want to. I think he's going for a social event of sorts

>> No.63653451

>>63653366
don't log anonymous solutions on the leaderboard?

>> No.63653485

>>63653451
dude fuck off, just make a cock.li github, it's not gonna hurt you

>> No.63653494

I feel like this whole advent of code idea should be cloned. But with no leaderboard, no accounts, and make it in July when no one has finals to study for or term projects to finish up.

>>63653359

Reddit is cancer and I'm not going to make an account on that site.

>>63653366

I'm talking about receiving a dataset that will have no chance of landing you anywhere on the leaderboard whatsoever.

>> No.63653512

Is there a solution to the second puzzle of day two that isn't O(n^2)?

>> No.63653515

>>63653494
if you don't wanna play, that's fine

stop throwing a shitfit and go make your own if you want nobody gives a shit

>> No.63653525

>>63653494
>But with no leaderboard
Why do you care? If you do not care about the leaderboards just solve them at your own pace.

>no accounts
Why? Literally takes 2 seconds to make a throwaway.

>and make it in July
If you do not care about the leaderboards then you can solve them in July, just wait 6 months and solve the current challenges then.

>no one has finals to study for or term projects to finish up.
lol

>> No.63653529

>>63653512
for (i = 0; i < n; i++)
for (j = i; j < n; j++)

>> No.63653533

def div(list):
for i, j in enumerate(list):
for k in range(len(list)):
if k != i and j % list[k] == 0:
return j / list[k]

with open('d2.txt') as f:
checksum = 0
for line in f:
nums = line.split()
temp = []
for num in nums:
temp.append(int(num))
checksum += div(temp)
temp.clear()
print("Checksum:", checksum)

Tried my best, I guess. Any tips on how I could optimize this?

>> No.63653549

>>63653529
>posts the O(n^2) solution

>> No.63653570

>>63653512
Post the puzzle. I don't want to log in.

>> No.63653573

>>63653570
nah

>> No.63653592
File: 125 KB, 918x732, file.png [View same] [iqdb] [saucenao] [google] [report]
63653592

>>63653570
Pic related. By O(n^2) I mean the complexity of finding the two numbers that divide evenly in a row, not the complexity of the entire solution.

>> No.63653593

>>63653570
16x16 matrix of integers
find for each row the unique even division between two numbers on that row (n % m == 0)
sum the divisions

>> No.63653627

>>63652748
Clearly none of the puzzles are intended to be about text processing, you should have just done a search and replace on the text to turned it into a 2D-array or whatever, and hardcoded it into your program.

>> No.63653656

These brain teasers are pure autism.

Like the kids that could add several 5 digit numbers instantly... but none of them advanced much past basic arithmetic, forget about calculus and linear algebra. stick to the parlor tricks /g

>> No.63653671

>>63653656
??

>> No.63653689

Can we start kicking people off the leaderboard if they haven't even gotten a single star?

>> No.63653762

>>63653593
>>63653512
I think you could perform integer factorization and then look for duplicate prime factors.

>> No.63653768

>>63653512
This is how I solved it. I don't know if it's what you're looking for, but it's ~twice as fast as looping through every value.

val.Sort();
for (int i = 0; i < val.Count - 1; i++) {
for (int j = i + 1; j < val.Count; j++) {
if (val[j] % val[i] == 0) {
sum += val[j] / val[i];
goto Next;
}
}
}
Next:;

>> No.63653805

>>63653768
This is just n + (n - 1) + (n - 2) + ... + 2 + 1 = n*(n + 1) / 2 which is still O(n^2). Your optimization is not doing both a % b and b % a, which is indeed faster, but still same complexity.

>> No.63653817

>>63653762
That's still O(n^2) though because for each factorization you have to check every other factorization.

>> No.63653840

>>63653762
Yeah I actually thought about this too, but it sounded too time consuming, so I dropped the idea. Doing prime factors would increase complexity in strange ways though, for example, it could make your program fast if you have an array of a million small numbers, but would be very slow if you had ten 19 digit numbers.

>>63653768
I did essentially the same thing as far as I can tell, but that's not really better than O(n^2), because it's like n*(n-1)/2 or something, which still counts as O(n^2).

>> No.63654026
File: 53 KB, 970x478, z.png [View same] [iqdb] [saucenao] [google] [report]
63654026

ohio

>> No.63654081

>>63652589
Bullies defending data farming now? This world needs a fourth reich to oust people like you

>> No.63654100

>>63654026
What font is that?

>> No.63654103

>>63652714
Fuck deadlines as a professional programmer. No greater bliss than taking your time with a program you believe in

>> No.63654114

>>63654081
I really don't see the point in whining when you can just make a throwaway.

>> No.63654124
File: 124 KB, 500x500, benis.png [View same] [iqdb] [saucenao] [google] [report]
63654124

>>63654100
DejaVu Sans Mono, I think

>> No.63654128

>>63654081
>datafarming
>reddit literally requires an account name and a password without any verification so there's nothing tying you to the account
>takes like 2 seconds to register and link your account
sure is data mining

>> No.63654182

>>63653817
I don't think that's actually the case. You could:

1: factor each number - O(n)
2: collect all factors to one list - O(n)
3: sort the list - O(n lg n)
4: iterate over each number (O(n) and check that each of its factors has duplicates in the list (binary search - O(lg n)), any number that meets this condition must divide some other number in the row - O(n lg n)
5: iterate over the row and find which number it divides - O(n)

>>63653840
Is correct though. I think you can do better than O(n^2) in the number of integers but factorization is sensitive to the size of the integers themselves.

>> No.63654191

My Node.js solution:
var data = require('fs')
.readFileSync('input')
.toString()
.trim()
.split('\n')
.map(line => line.split('\t').map(a => +a))

console.log(data
.map(line => Math.abs(Math.min(...line) - Math.max(...line)))
.reduce((a, b) => a + b))

console.log(data
.map(line => line
.map(n1 => n1 / line.filter(n2 => n1 != n2 && n1 % n2 == 0))
.filter(n => n != Infinity)
).reduce((l1, l2) => l1 + l2[0], 0))

>> No.63654210

>>63654191
>Math.abs min - max
Just do max - min.

>> No.63654239
File: 38 KB, 513x442, 1486968232425.png [View same] [iqdb] [saucenao] [google] [report]
63654239

>>63652635
>>63652668
>>63652790
>The hardest part was getting the input into a usable format

It depends on the language. Pic related, parsing the input is super easy in Rust

>> No.63654270

Day 2 kode, brainlets. I'm starting to like python, very nice.
def checksum(evenly=False):
with open("input.txt", 'r') as input:
checksum = 0
for line in input.readlines():
row = list(map(int, line.split()))
if evenly:
checksum += next((x // y for x in row for y in row if x != y and x % y == 0), 0)
else:
checksum += max(row) - min(row)
return checksum


print(checksum())
print(checksum(evenly=True))

>> No.63654309

My C++ cancer:

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>

using revit_t = std::reverse_iterator<std::vector<int>::iterator>;

int main()
{
std::fstream file("aoc2017_01_0.txt", file.in);
if (!file.is_open())
{
std::cout << "error opening file\n";
}
else
{
int cs = 0;
std::string line;
while(std::getline(file, line)) {
std::stringstream ss(line);
std::vector<int> v;
int i;
bool found = false;
while (ss >> i) v.push_back(i);
std::sort(v.begin(), v.end(), std::greater<int>());
for (auto f = v.begin(); f != v.end(); ++f)
{
for (auto b = v.rbegin(); b != --revit_t(f); ++b)
{
int fval = *f;
int bval = *b;

if ( fval / bval == 0 ) break;
if ( fval % bval == 0 ) {
cs += fval / bval;
found = true;
break;
}
}
if (found) break;
}
}
std::cout << cs << '\n';
}
return 0;
}

>> No.63654323

>>63654309
>for (auto f = v.begin(); f != v.end(); ++f)
Why not for (auto f : v)?

>> No.63654325

result1 :: [[Int]] -> Int
result1 xs = sum [ maximum x - minimum x | x <- xs ]

evenly :: [Int] -> (Int,Int)
evenly xs = head [ (x,y) | x <- xs, y <- xs, x `mod` y == 0, x /= y ]

result2 :: [[Int]] -> Int
result2 xs = sum [ x `div` y | (x,y) <- map evenly xs ]

>> No.63654334

>>63654323
hes probably learning

>> No.63654338

>>63654323
I'm using iterator f as end condition for the inner loop.

>> No.63654346
File: 7 KB, 147x246, wim.png [View same] [iqdb] [saucenao] [google] [report]
63654346

tfw everyone cares about runtime complexity and I'm just glad when my code does not segfault and yields the right solution.

https://pastebin.com/yyPnRJ75

//convervative estimate lol
unsigned* numbers = malloc(sizeof(unsigned)*strlen(line));


people like me should not be allowed to program in c

>> No.63654392

>>63654239
>not posting the whole solution
don't be a fag

>> No.63654394

>>63654346
why are C solutions always so :puke: even haslel looks better

>> No.63654403

>>63654323
nvm, you're right, I can use it:

// ...
for (auto fval : v)
{
for (auto b = v.rbegin(); ; ++b)
{
int bval = *b;
if ( fval / bval == 0 || fval == bval ) break;

>> No.63654421

>>63654392
My actual solution is rather simple:
pub fn checksum(list: Vec<Vec<u64>>) -> u64 {
list.into_iter()
.map(|row| {
let mut min = <u64>::max_value();
let mut max = 0;

for v in row {
if v < min {
min = v;
}
if v > max {
max = v;
}
}

max - min
})
.sum()
}

pub fn even_checksum(list: Vec<Vec<u64>>) -> u64 {
list.into_iter()
.map(|row| {
for (i, m) in row.iter().enumerate() {
for n in row.iter().skip(1 + i) {
if m % n == 0 {
return m / n;
}
if n % m == 0 {
return n / m;
}
}
}
0
})
.sum()
}

>> No.63654451

>>63654421
>just as verbose as C++
Can you do better?

>> No.63654480

>tfw yoy probably could be in the leaderboard, but you refuse to wake up everyday at 6 AM for it

>> No.63654489

>>63654480
Who cares about that, just solve the problem and submit it

>> No.63654519

How to spot brainlet (in imperative languages):
His solutions for part 1 and part 2 differs more than just single parameter

>> No.63654715

Any lambda fags around?
Tell me how can I make it prettier:

static void Main(string[] args)
{
var file = File.ReadAllLines(@"N:\array.txt"); int sum = 0; int sum2 = 0;
for (int i = 0; i < file.Length; i++)
{
int[] numbers = file[i].Split('\t').Select(ch => Convert.ToInt32(ch)).ToArray();
sum = sum + Day2P1(numbers);
sum2 = sum2 + Day2P2(numbers);
}
Console.WriteLine($"part1: {sum}, part2: {sum2}");
Console.ReadKey();
}

static int Day2P1 (int[] array) { return (array.Max() - array.Min());}
static int Day2P2 (int[] array)
{
var len = array.Length; var result = 0;
for (int i = 0; i < len; i++)
{
var cur = array[i];
for (int j = 0; j < len; j++)
{
if (cur > array[j] && cur % array[j] == 0) { result = cur / array[j]; break; }
}
if (result > 0) { break; }
}
return result;
}

>> No.63654720

>>63654519
Number of params stay the same, you are reading one file and that's it.

>> No.63654845

>>63654715
Best thing I've come up with as an alternative to part2:

tatic int Day2P2 (int[] array)
{
var result = from i in array
orderby i descending
from i2 in array
where i > i2 && i % i2 == 0
select i / i2;
return result.FirstOrDefault();
}


Barely best tho, sameshit, probably slower.

>> No.63654852

>>63654715
What shitlang is this? Java?
eww

>> No.63654857

Superior Rust solution coming through: https://play.rust-lang.org/?gist=b030970626917e4f0a87685b29f7bbee&version=stable

>> No.63654878

>>63654852
c#

>> No.63654887

>>63654878
>Java 2.0 (Microsoft version)
No wonder

>> No.63654895

>>63654857
Now this is good. Although you should've been reading a file instead

>> No.63654903

>>63654852
pajeeet :-----DDD

>> No.63654908

>>63654895
https://play.rust-lang.org/?gist=c02e8e7c5bebd034f6bc4aa695d2458d&version=stable

>> No.63654967
File: 6 KB, 226x94, 1507128170150.png [View same] [iqdb] [saucenao] [google] [report]
63654967

>>63654908
Nice

>> No.63654995

Here is my solution:
https://raw.githubusercontent.com/Smatchcube/Advent-of-Code-2017/master/day2.py
I'm a beginner and i only use the python doc (no stackoverflow cheat).
My code is so shit but i'm to lazy to clean my code.

>> No.63655009

anyone here solving the calendar in J?

>> No.63655014

>>63654967
Open a file, don't just read the stdin

>> No.63655025

>>63655014
why?

>> No.63655037
File: 60 KB, 1253x759, 2017-12-02-121837_1253x759_scrot.png [View same] [iqdb] [saucenao] [google] [report]
63655037

Does this look bad?

>> No.63655052

>>63655037
wats this

>> No.63655062

>>63654519
How to spot a brainlet (you): his solution for the first part is O(n^2) and not O(n).

>> No.63655083
File: 74 KB, 1592x822, Screenshot from 2017-12-02 22-27-12.png [View same] [iqdb] [saucenao] [google] [report]
63655083

>>63655025
>>63654857
I wanted to benchmark

>> No.63655098

>>63655083
Isn't result wrong?

>> No.63655112

>>63655098
Every participant gets different value sets

>> No.63655118

>>63655083
I didn't write that Rust code to be extremely fast. I only wanted somthing without loops that runs <1ms

>>63655098
Everyone has different inputs

>> No.63655121

>>63655112
ah ok

>> No.63655124

>>63654995
For working with files use 'with', something like this:
with open("input", "r") as file:
spreadsheet = file.read()

It closes the file automatically

>> No.63655153

>>63655124
The OS is going to take care of it.

>> No.63655166
File: 11 KB, 254x240, 1439893983472.jpg [View same] [iqdb] [saucenao] [google] [report]
63655166

>>63655153
>trusting your OS

>> No.63655176

>>63655166
I use RedoxOS. Of course I trust it.

>> No.63655196

>>63655176
based

>> No.63655223

>>63653512
O(n) through integer factorization.

(use '[clojure.string :only [split split-lines]])
(def input "5 9 2 8\n9 4 7 3\n3 8 6 5")

(defn str->ints [s] (map read-string (split s #" ")))

(defn stat-range [nums] (- (apply max nums) (apply min nums)))

(defn divides? [a b] (zero? (mod a b)))
(defn factor [n] (filter (partial divides? n) (range 1 n)))

(defn find-division [nums]
(let [d (first (filter (set (mapcat factor nums)) nums))
n (first (filter #(and (not= d %) (divides? % d)) nums))]
(int (/ n d))))

(defn check-sum [input row-fn]
(->> (split-lines input) (map (comp row-fn str->ints)) (reduce +)))

(check-sum input stat-range)
(check-sum input find-division)

>> No.63655230
File: 5 KB, 174x75, 1482477763580.png [View same] [iqdb] [saucenao] [google] [report]
63655230

>>63655014
>>63655025
Not the original author, i modified it to read a file with a given name
use std::io::Read;
use std::fs::File;
use std::env::args;

fn main() {
let fname = args().last().unwrap();
let instant = std::time::Instant::now();
let contents = File::open(fname)
.and_then(|mut f| {
let mut contents = String::new();
f.read_to_string(&mut contents)?;
Ok(contents)
})
.unwrap();
let (a, b) = contents
.lines()
.map(|l| {
let mut vec: Vec<u32> = l.split_whitespace().map(|s| s.parse().unwrap()).collect();
vec.sort_unstable();

(
vec.last().unwrap() - vec.first().unwrap(),
vec.iter()
.enumerate()
.filter_map(|(i, b)| {
vec.iter().skip(i + 1).find(|&a| a % b == 0).map(|a| a / b)
})
.next()
.unwrap(),
)
})
.fold((0, 0), |acc, v| (acc.0 + v.0, acc.1 + v.1));
let d = instant.elapsed();

println!(
"Part 1: {}\nPart 2: {}\nTime: {} ms",
a,
b,
(d.as_secs() as f64 + d.subsec_nanos() as f64 / 1000000000.0) * 1000.0
);
}

>> No.63655248

>>63655118
>Everyone has different inputs
Not completely, at least it wasn't the case 2 years prior. There was just a set of inputs that you could draw from but some people could still get the same. This was to ensure that rather than generating random inputs and ending up with some edge cases that will fuck people over you have a set of inputs that are guaranteed to work.

>> No.63655258

>>63655230
I made it better: https://play.rust-lang.org/?gist=c02e8e7c5bebd034f6bc4aa695d2458d&version=stable

>> No.63655277

>>63655258
Shit wrong link
https://play.rust-lang.org/?gist=75fdabe43f0295c59d2959dce33b771a&version=stable

>> No.63655308
File: 13 KB, 708x423, linq.png [View same] [iqdb] [saucenao] [google] [report]
63655308

C# doesn't really make this kind of stuff pretty ...

>> No.63655315

>>63655277
Nice

>> No.63655333

>>63655223
clojure is not a LISP

>> No.63655337

>>63655308
> + "7 5 3" + Environment.NewLine

kek, is that really idiomatic C# for doing multi line strings?

>> No.63655347
File: 924 KB, 600x336, 1512172073836.webm [View same] [iqdb] [saucenao] [google] [report]
63655347

>>63651213
>i = -1
> digitSum = 0
> while i < len(inputList) - 1:
> if inputList...
shall it inputlist[-1]
or there some hidden magic in python?

>> No.63655351

>>63655333
I don't understand this meme

>> No.63655357

>>63655337
and I thought std::endl was bad... lol

>> No.63655364
File: 407 KB, 995x1181, 1507417662754.jpg [View same] [iqdb] [saucenao] [google] [report]
63655364

Haven't used clojure since the last AoC.

(ns Day1
(:require [clojure.string :as s]))

(def file-path "input/day1.txt")

(defn parse-input [input-file]
(map #(Integer/parseInt %)
(-> (slurp input-file)
s/trim
(s/split #""))))

(defn index-value-is-valid [input-list, index]
(let [num (nth input-list index :invalid)
next-number-index (-> (+ index 1) (mod (count input-list)))
next-number (nth input-list next-number-index)]
(= num next-number)))

(defn find-valid-numbers [input-list]
(let [is-valid (partial index-value-is-valid input-list)
indices (range (count input-list))
valid-indices (filter is-valid indices)]
(map #(nth input-list %) valid-indices)))

(defn sum-of-digits-matching-next-in-list [input-list]
(reduce + (find-valid-numbers input-list)))

(defn print-result []
(println
(-> (parse-input file-path)
sum-of-digits-matching-next-in-list)))

(ns Day2
(:require [clojure.string :as s]))

(def day2-file "input/day2.txt")

(defn parse-input [filepath]
(let [lines (s/split-lines (slurp filepath))
parse-line (fn [line] (map #(Integer/parseInt %) (s/split line #"\t")))]
(map parse-line lines)))

(defn difference-between-max-min [coll]
(- (apply max coll) (apply min coll)))

(defn check-sum [filepath]
(->> filepath
parse-input
(map difference-between-max-min)
(reduce +)))

(defn print-result []
(println (check-sum day2-file)))

>> No.63655367

>>63655347
Python accepts negative indice and returns the value from the back of the iterable.
So for instance -1 will return the last element, -2 the one before the last, and so on.

>> No.63655379

>>63652495
this is pretty bad practice desu just use a try and except statement otherwise the list of numbers is just going to get huge

>> No.63655389

>>63655367
Rust does this way better:
let lel = [0, 1, 2];
assert_eq!(lel[0], 0);
assert_eq!(lel[1], 1);
assert_eq!(lel[2], 2);
assert_eq!(lel.iter().rev().nth(0).unwrap(), &2);
assert_eq!(lel.iter().rev().nth(1).unwrap(), &1);
assert_eq!(lel.iter().rev().nth(2).unwrap(), &0);

Notice how in both cases the indexing is zero based?

>> No.63655396

>>63655379
>try and except
just use modulo

>>63655389
notice how I was simply explaining to him what happened there since he asked instead of arguing which flavor of the month language does it better?

>> No.63655400

>>63655364
nice, we have very similar solutions for day 2
>>63655223

How do you get /g/ to not fuck up your syntax highlighting? Is the namespace required??

>> No.63655405

>>63655347
as >>63655367 said, [-1] will return last element, so basically I just wrapped it right at the start to check the last and first digit easily

>> No.63655415

>>63655400
this is because your script has an apostrophe at the very beginning and since the syntax highlighter here is generic it treats the rest of your program as a string that doesn't end

>> No.63655423

>>63655396
Dude calm down. It isn't my fault that Python sucks. If Python would be smart enough to relise that 0 != -0 you could get the last element like this: lel[-0]. That would be fucking amazing because it is still zero based.

>> No.63655427
File: 12 KB, 688x385, linq_filth_version.png [View same] [iqdb] [saucenao] [google] [report]
63655427

>>63655337
depends how dirty you want it.

>> No.63655463

>>63655379
Don't use exceptions for control-flow. The best way to avoid "index out of bounds" is to simply make sure the index stays in bounds

>> No.63655466

>>63655423
If it bothers you so much you can simply do: iterable[::-1][index] which will do what you want except without so much verbosity:
>>> v = [1, 2, 3, 4]
>>> v[::-1][0] == 4
True
>>> v[::-1][1] == 3
True


Then again, I'm not arguing whether Python is good or not and how it compares to Rust. Neither language is objectively superior and to make such a claim would be idiotic.

>> No.63655477

>>63655466
>Neither language is objectively superior
But that is where you are wrong, kiddo. Rust is better in literally every aspect. Prove me wrong.
Protip: **you can't**

>> No.63655489

>>63655230
>unwrap everywhere
Rust is not for you nigger.

>> No.63655495

>>63655477
And oranges are better than apples. What's your point?

>> No.63655511

>>63655230
This is Rust, gentlemen. Gaze at it as despair at it's stupidity.

>> No.63655518

>>63655489
Lol kill yourself. Why bother with better error handling for a simple challenge?

>> No.63655527

>>63655511
>stupidity
how?

>> No.63655530

>>63655511
explain

>> No.63655536

>>63655308
>sheet
>not simple aray
>no part 2

see
>>63654715
>>63654845

>> No.63655545

>>63655511
Rust is like a bastard child of C++ and Perl.

>> No.63655548

>>63654852
if it was java he could have use Scanners to parse strings, handy stuff

>> No.63655554

>>63655548
The microsoft version is worse than the oracle version at times as it seems

>> No.63655556

>>63655548
There is crapload of useful stuff to parse shiut in C# sharp too I just dont know nay of them and did not want to google much

>> No.63655569

fuck you guy who just bumped me off the top20

>> No.63655579

>>63655554
>>63655556
didn't know C# had Scanners, wish more languages had it though, haven't really looked into it at all for other languages, almost feels like cheating when using Scanners

>> No.63655586

>>63655545
How is that related to perl? I understand C++ for RAII

>> No.63655592

What's the best global score you guys ever managed to get?
Last year I got as high as 87th place but I could never get any higher, these people are just too fast.

>> No.63655603

>>63655586
C++ - verbosity.
Perl - ugliness.
Rust - both.

>> No.63655606

>>63654346
>https://pastebin.com/yyPnRJ75
ewwwwwwwwwwwwwwwwwwwwww

>> No.63655615

>>63652947
This is from my solution:
#include <string>
#include <sstream>
#include <vector>

int main(int argc, char *argv[])
{
std::string line;
while (std::getline(std::cin, line)) {
std::stringstream ss(line);
int temp;
std::vector<int> nums;
while (ss >> temp) {
nums.push_back(temp);
}
// now you have a std::vector<int> containing the line
}
}

std::getline reads each line from std::cin into line, stripping the newline char at the end. The next line creates a stringstream, which you can use to extract each number into a vector<int> using the inner while loop. Extracting it from a sstream ignores the whitespace around each group of digits and also converts it into an int. The reason I did it this way is it's more compact to operate on each line as you parse it, rather than putting it all into a vector<vector<int>> and processing it that way.

>> No.63655619

>>63655592
15 in 2015

>> No.63655620
File: 47 KB, 645x968, 1481916546254.jpg [View same] [iqdb] [saucenao] [google] [report]
63655620

>>63655603

>> No.63655635

>>63655620
It's alright buddy, you don't have to be so hard on yourself for not getting the joke without having it explained. It happens.

>> No.63655643

>>63650759
Thanks for posting this OP, seems like a good challenge

>> No.63655674
File: 21 KB, 600x647, 4ab.jpg [View same] [iqdb] [saucenao] [google] [report]
63655674

>tfw I'm taking, on average, 10x more time to solve a challenge in comparison to the first places on the leaderboard

so this 10x programmer shit is really a thing, huh?

>> No.63655707

>>63655674
>10x
You cannot possibly be serious right? Especially not on the very first few challenges each year which are fairly simple.

>> No.63655750

>>63655707
it took me 10 minutes to solve both parts of the second day.

>> No.63655772

>>63655750
I assume that includes not just solving the problem but preparing to solve it and understanding?
If you want to actually get a decent time on the leadboard make sure to actually skip the garbage story text when reading the challenge and have a text editor/terminal/input file prepared already.

>> No.63655812
File: 583 KB, 1920x493, file.png [View same] [iqdb] [saucenao] [google] [report]
63655812

Less pajeet code today, times are in microseconds.

>> No.63655833 [DELETED] 

Part 1:
<code>
import sys

a = []
f = open(sys.argv[1], 'r')

for line in f:
a.append(line.strip())

f.close()
b = []
for i in range(len(a)):
b.append([int(k) for k in a.split()])
result = 0
for i in range(len(b)):
maxi = max(b)
mini = min(b)
result += (maxi-mini)

print(result)
</code>

Part 2:
<code>
import sys

a = []
f = open(sys.argv[1], 'r')

for line in f:
a.append(line.strip())

f.close()
b = []
for i in range(len(a)):
b.append([int(k) for k in a.split()])
result = 0
for i in range(len(b)):
for j in range(len(b)):
for k in range(len(b)):
if(j != k and b[j]%b[k] == 0):
result+= (b[j]//b[k])

print(result)
</code>

I feel like a retard doing that triple for loop, but it works

>> No.63655848

>>63655812
Turns out I just got lucky and my stupid H div X + X div H hack doesn't work when H is equal to X.

>> No.63655850

>>63655750
>tfw took me a hour

>> No.63655860

>>63655812
Part 1:
import sys

a = []
f = open(sys.argv[1], 'r')

for line in f:
a.append(line.strip())

f.close()
b = []
for i in range(len(a)):
b.append([int(k) for k in a[i].split()])
result = 0
for i in range(len(b)):
maxi = max(b[i])
mini = min(b[i])
result += (maxi-mini)

print(result)


and part 2:
import sys

a = []
f = open(sys.argv[1], 'r')

for line in f:
a.append(line.strip())

f.close()
b = []
for i in range(len(a)):
b.append([int(k) for k in a[i].split()])
result = 0
for i in range(len(b)):
for j in range(len(b[i])):
for k in range(len(b[i])):
if(j != k and b[i][j]%b[i][k] == 0):
result+= (b[i][j]//b[i][k])

print(result)

I feel like a retard doing that triple for loop, but it works

>> No.63655866

>>63655848
Aren't you supposed to filter out H == X cases since those are invalid combinations (checking against itself isn't a valid action).

>> No.63655907

>>63655866
No, I only compare numbers to other numbers that are after them in the list, so I don't ever compare anything against itself. By X == H, I meant cases like [2, 3, 55, 3, 7], where the only elements evenly divisible by each other have the same value. This is allowed by the rules of the game as far as I can tell, because they don't say repeating numbers aren't allowed, only that there is exactly one pair of numbers that are evenly divisible.

>> No.63655959

>>63655860
There's nothing wrong with a triple loop in this case, although I guess sorting the list and doing
for k in range(j + 1, len(b[i])):

would have been more elegant. You could also have used functools.reduce() to save one for loop.

>> No.63655962

>>63655850

Which language?

>> No.63655986

>>63655962
c# but it is not related to language, just me being brainlet
c# has all the tools to solev it super-fastand write microcode

>> No.63655989

Pythonfriend from >>63643907 here.

Just woke up, this is my take:
import itertools

def checksum(p):
rows = [[int(x) for x in r.split()] for r in p.splitlines()]
return sum(max(r) - min(r) for r in rows)

def checksum2(p):
rows = [sorted([int(x) for x in r.split()]) for r in p.splitlines()]
return sum(next(b // a for a, b in itertools.combinations(r, 2) if b % a == 0) for r in rows)


Not a huge fan of the efficiency of this one, but too lazy to figure out integer factorisation. At least it doesn't consider any duplicate combinations.

>> No.63655998

>>63655083
Bit better, wasting time in nicely formatting the duration though
void main(string[] args)
{
import std.stdio, std.conv, std.string, std.array, std.algorithm,
std.datetime;

auto t0 = Clock.currTime;

uint sum1, sum2 = 0;
foreach (string row; File(args[1], "r").lines)
{
auto x = row.strip().splitter().map!(to!uint).array().sort!"a<b"().array();

sum1 += x[$ - 1] - x[0];
line: foreach (i, a; x[0 .. $ - 1])
{
foreach (b; x[i + 1 .. $ - 1])
{
if (b % a == 0)
{
sum2 += b / a;
break line;
}
}
}
}

writefln("Part 1: %s\nPart 2: %s\nTime: %s", sum1, sum2, (Clock.currTime - t0));
}

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

auto t0 = Clock.currTime;

uint sum1, sum2 = 0;
foreach (string row; File(args[1], "r").lines)
{
auto x = row.strip().splitter().map!(to!uint).array().sort!"a<b"().array();

sum1 += x[$ - 1] - x[0];
line: foreach (i, a; x[0 .. $ - 1])
{
foreach (b; x[i + 1 .. $ - 1])
{
if (b % a == 0)
{
sum2 += b / a;
break line;
}
}
}
}

writefln("Part 1: %s\nPart 2: %s\nTime: %s", sum1, sum2, (Clock.currTime - t0));
}

>> No.63655999

Part 1 and 2 in Java

package DayTwo;

import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import java.util.Arrays;


public class DayTwo {
private static final String FILENAME = "src\\DayTwo\\input.txt";
private static Scanner scanner;
private static int result = 0;
private static int result2 = 0;

public static void main(String[] args) throws IOException{
scanner = new Scanner(new File(FILENAME));
checksumSolver();
System.out.println(result);
System.out.println(result2);
scanner.close();
}

public static void checksumSolver() {
String input = scanner.nextLine();
String[] split = input.split("\t");
int[] array = new int[split.length];
for (int i = 0; i < split.length; ++i) {
array[i] = Integer.parseInt(split[i]);
}

Arrays.sort(array);
result += array[array.length - 1] - array[0];

for (int i = 0; i < array.length; ++i) {
for (int j = 0; j < array.length; ++j) {
if (i != j && array[i] % array[j] == 0) {
result2 += array[i] / array[j];
}

}
}

if (scanner.hasNextLine()) {
checksumSolver();
}
}
}

>> No.63656000

const checksum = (p, c) => {
var row = c.split("\t");
return p + row.reduce(max) - row.reduce(min)
}

const min = (p, c) => {
var a = Number(p) || 0;
var b = Number(c) || 0;

if(b < a) {
return b;
}
return a;
};

const max = (p, c) => {
var a = Number(p) || 0;
var b = Number(c) || 0;

if(b > a) {
return b;
}
return a;
};

const spreadsheet = `
5 1 9 5
7 5 3
2 4 6 8
`;

spreadsheet.split("\n").reduce(checksum);

>> No.63656001

>>63655989
Nice.

>> No.63656060

>>63653065
my nigga
import Data.List.Split
import Data.List
import Data.Maybe

nums = map (map read . splitOn "\t") . lines <$> readFile "day2input.txt" :: IO [[Int]]

prob1 :: IO Int
prob1 = sum . map difference <$> nums
where difference l = maximum l - minimum l

prob2 :: IO Int
prob2 = sum . map (uncurry div) . mapMaybe f <$> nums
where f l = find (\(a, b) -> mod a b == 0 && a /= b) [(i, j) | i<-l, j<-l]

>> No.63656233

Pajeet++
#include <iostream>
#include <fstream>
#include <vector>
#include <sstream>
using namespace std;

int solve1(vector<vector<int>> tab)
{

int sum=0;
int big;
int numberLet;
for(int i=0;i<tab.size(); i++)
{
big=tab[i][0];
numberLet=tab[i][0];
for (int j=1;j<tab[i].size(); j++)
{
if(numberLet>tab[i][j])
{
numberLet=tab[i][j];
}
else if(big<tab[i][j])
{
big=tab[i][j];
}
}
sum+=(big-numberLet);
}
return sum;
}


int solve2(vector<vector<int>> tab)
{
int sum=0;
int n1;
int n2;
for(int i=0;i<tab.size(); i++)
{
n1=0;
n2=0;
for (int j=0;j<tab[i].size(); j++)
{
for(int k=j+1;k<tab[i].size(); k++)
{
if((tab[i][j] % tab[i][k]) == 0)
{
n1=tab[i][j];
n2=tab[i][k];
j=tab[i].size();
break;
}
else if((tab[i][k] % tab[i][j]) == 0)
{
n1=tab[i][k];
n2=tab[i][j];
j=tab[i].size();
break;
}
}
}
sum+=(n1/n2);
}
return sum;
}
int main() {
vector<vector<int>> tab;
ifstream outputFile("day2.txt");
if(!outputFile.is_open())
{
cout<<"You're a faggot"<<endl;
}
else
{
int a=0;
string temp;
while(getline(outputFile,temp))
{
stringstream st(temp);
vector<int> v;
tab.push_back(v);
while(st){
int n;
st>>n;
tab[a].push_back(n);
}
a++;
}
outputFile.close();
cout<<solve1(tab)<<endl;
cout<<solve2(tab)<<endl;
}
}

>> No.63656300

>>63655223
This is O(n^2) though, you're applying a filter to the [1..n] range for every number n in the row.

>> No.63656443

This one was quite easy.
Part 1:
def checksum(sheet):
checksum = 0
sheet = sheet.split("\n")
if "\t" in sheet: #Optional but copy/pasting stuff from the website has \t
sheet = sheet.replace("\t"," ")
for i in sheet:
i = list(map(int,i.split()))
checksum += (max(i)-min(i))
return checksum

>> No.63656454

>>63656443
Part 2:
def checksum(sheet):
checksum = 0
sheet = sheet.split("\n")
if "\t" in sheet: #Optional but copy/pasting stuff from the website has \t
sheet = sheet.replace("\t"," ")
for i in sheet:
i = list(map(int,i.split()))
for num in range(len(i)):
for num2 in range(len(i)):
if num==num2: #Checking if we're doing the same number on the sheet
continue
else:
if not i[num]%i[num2]:
checksum += i[num]/i[num2]
return int(checksum) #Gets calculated as float originally

>> No.63656484

My solution for day 2 in one line of python:

import sys; print reduce(lambda s,ints: s+max(ints)-min(ints), [[ int(c) for c in line.split() ] for line in sys.stdin], 0)

Pretty simple.

>> No.63656521

>>63656484
>reduce when you could be using sum

>> No.63656525
File: 44 KB, 470x466, 1500995813946.jpg [View same] [iqdb] [saucenao] [google] [report]
63656525

python3 02.py
Part 1 checksum equals: 44216, time: 1.5549994714092463e-06s
Part 2 checksum equals: 320, time: 1.2900018191430718e-06s
Program took: 0.0006362860003719106s

>> No.63656600

>>63656525
Source?

>> No.63656632

>>63655986
>me being brainlet
>C#
Why am I not surprised?

>> No.63656653

>>63656600
https://ghostbin.com/paste/r6ahm

>> No.63656656
File: 35 KB, 100x75, skull.gif [View same] [iqdb] [saucenao] [google] [report]
63656656

>tfw top 50
Is it much easier this year or did I git gud?

>> No.63656676

>>63656521
Is this more to your liking, anon?
import sys; print sum(max(ints)-min(ints) for ints in [[ int(c) for c in line.split() ] for line in sys.stdin])

I think the other is a tad more readable but to each their own.

>> No.63656696

>>63656600
it's slightly faster if you do
for index, num in enumerate(digits[:-1]):
for ref in digits[index+1:]:

in 5,6 line instead

>> No.63656730

not sure if there's a better way to convert all the numbers into int
inputLines = []
diffs = []
with open("input", "r") as file:
for line in file:
line = line.replace("\n", "")
line = line.split("\t")
intLine = []
for num in line:
intLine.append(int(num))
maxNum = max(intLine)
minNum = min(intLine)
diff = maxNum - minNum
diffs.append(diff)

print(sum(diffs))

>> No.63656817

i optimized my divisions for the second part, not like it matters in fucking python.
also, didn't want to use itertools
def all_pairs(l):
pairs = []
i = j = 0
while i < len(l):
while j < len(l):
if i != j:
pairs.append((l[i], l[j]))
j += 1
i += 1
j = 0
return pairs

def checksum2(mat):
acc = 0
for row in mat:
for a, b in all_pairs(row):
quotient, remainder = divmod(a, b)
if remainder == 0:
acc += quotient
break
return acc

>> No.63656966

Better than my sed solution from yesterday.

#!/usr/bin/env node

let rows = require('fs')
.readFileSync('./' + process.argv.slice(2)[0])
.toString()
.trim()
.split('\n')
.map(line => line.split('\t')
.map(x => +x));

// Part 1
console.log("Part 1: " + rows
.reduce(function(acc, row) {
return acc + Math.max(...row) - Math.min(...row);
}, 0));

// Part 2
console.log("Part 2: " + rows
.reduce(function(acc, row) {
return acc + row
.map(i => i / row
.filter(j => i != j && i % j == 0))
.filter(n => n != Infinity)[0];
}, 0));


JS is comfy <3

>> No.63656967
File: 20 KB, 668x658, MUH_COSY_CODING.png [View same] [iqdb] [saucenao] [google] [report]
63656967

I don't like the if after the loop but it works.

>> No.63657000

>>63656966
I like your use of reduce(), nice!

>> No.63657004

>>63656967
>part1

>> No.63657019

>>63650759
>To play, please identify yourself via one of these services:

I refuse to use any of this social media shit. Too bad.

>> No.63657032

>>63657004
Ah yes, I should have indicated that it's just part1, I'm doing part2 in a sec, just waiting for my tea.

>> No.63657074

>>63650759
I'm surprised the solutions for #1 are so elaborate. You can solve this with one or two lines using regular expressions. You guys do know how to regex, don't you?

>> No.63657095

>>63657074
I know regex, but I usually use it for parsing, not calculating things. I'm interested in your regex solution though, please show it.

>> No.63657096

>>63657074
They don't use regexes in the industry anymore, grandpa.

>> No.63657203
File: 35 KB, 775x1054, part2.png [View same] [iqdb] [saucenao] [google] [report]
63657203

>>63657004
>>63656967
Adjusted to work for part 2 too.

>> No.63657238

APLfag reporting in, hasty code.
check ← (+/⌈/-⌊/)
divcheck ← (+/(÷⌈÷⍨)/)∘(⊢(/⍤1)⍨(=/0∘=)∘(∘.(∣∧∣⍨)⍤1⍨))

>> No.63657287

>>63657095
Not that guy, but from the top of my head for part 1:
eval(re.sub(r'(\d)(?!\1)', '+', '2112234')+'0')

>> No.63657444

Here's my day 2. I must say, using the ... spread operator is much nicer than doing Math.max.apply(none, array).

>>63657238
I have no idea what I'm looking at here...

>>63657287
Pretty fuckin' neato.

>> No.63657453

awk for 2nd
{
# chsum 1
min = 999999; max = -999999
for (i = 1; i <= NF; i++) {
if ($i < min) min = $i
if ($i > max) max = $i
}
chsum1 += max - min
# chsum 2
for (i = 1; i <= NF; i++) {
for (j = i+1; j <= NF; j++) {
if ($i % $j == 0) chsum2 += $i / $j
if ($j % $i == 0) chsum2 += $j / $i
}
}
}
END {
print chsum1
print chsum2
}

>> No.63657461
File: 16 KB, 745x545, day2.png [View same] [iqdb] [saucenao] [google] [report]
63657461

>>63657444
Of course I forgot the pic.

>> No.63657468

>>63657238
>←÷⍨∘⊢∧⍤
how does one even type that?

>> No.63657546

Absolute shit-tier python solution for day 2:
from math import *
import sys
import re

s = 0
for line in sys.stdin:
line = line.strip()
parts = list(map(int, line.split()))
if not parts:
continue
for i in range(len(parts)):
for j in range(len(parts)):
if i == j:
continue

x = parts[i]
y = parts[j]
if x % y == 0:
s += x / y
elif y % x == 0:
s += y / x
print(s // 2)

>> No.63657605
File: 6 KB, 240x240, good_work.jpg [View same] [iqdb] [saucenao] [google] [report]
63657605

The guy that organizes this event has some neat posts about lambda calculus using JS for examples:

http://hexatlas.com/entries/7

Pretty neat.

>> No.63657766

:^3
def main():
divSum = 0
with open("input", "r") as file:
for line in file:
line = line.replace("\n", "")
line = line.split("\t")
line = list(map(int, line))
line.sort()
i = len(line) - 1
br = False
while i >= 0:
index = findMid(line, line[i])
while index >= 0:
if line[i] % line[index] == 0:
divSum += line[i] // line[index]
br = True
break
else:
index -= 1
if br == True:
break
i -= 1
print(divSum)


def findMid(line, val):
midVal = val // 2
i = len(line) // 2
if line[i] < midVal:
while i < len(line):
if line[i] <= midVal:
i += 1
else:
break
elif line[i] > midVal:
while i >= 0:
if line[i] > midVal:
i -= 1
else:
break
return i

if __name__ == "__main__":
main()

>> No.63657843

>no-one posted the O(n*log(log n)) solution yet
hmmmm.....

>> No.63657972

2-1 wasn't too hard:

import Control.Applicative (liftA2)

main :: IO ()
main = print =<< checksum . map (map read . words) . lines <$> getContents

checksum :: [[Int]] -> Int
checksum = sum . map (liftA2 (-) maximum minimum)

>> No.63658074

>>63657843
pleb, there is O(n) solution (((with massive constant)))

>> No.63658080

>>63650759
Sorry I'm too busy being a productive member of society to finish your homework.

>> No.63658127

>>63657972
And here's 2-2, nowhere near as clean, but I got to try out using pattern guards which I found out about recently

main :: IO ()
main = print =<< checksum . map (map read . words) . lines <$> getContents

checksum :: [[Int]] -> Int
checksum = sum . map checksum'

checksum' :: [Int] -> Int
checksum' [] = error "No evenly divisible values in list!"
checksum' (x:xs)
| (Just result) <- evenDivisor x xs = result
| otherwise = checksum' xs

evenDivisor :: Int -> [Int] -> Maybe Int
evenDivisor _ [] = Nothing
evenDivisor x (y:ys)
| x `rem` y == 0 = Just (x `div` y)
| y `rem` x == 0 = Just (y `div` x)
| otherwise = evenDivisor x ys

>> No.63658249

>>63658127
Eh, thought of a better way with list comprehensions, much nicer now:

main :: IO ()
main = print =<< checksum . map (map read . words) . lines <$> getContents

checksum :: [[Int]] -> Int
checksum = sum . map checksum'

checksum' :: [Int] -> Int
checksum' xs = head [x `div` y | x <- xs, y <- xs, x /= y, x `rem` y == 0]

>> No.63658333

New thread: >>63658328

>> No.63659249

>>63656967
doesn't the loop perform an out of bounds check

>> No.63659372

>>63659249
You're right, I could have used the for (car i in arr) format.

>> No.63659409

>>63656300
>>>63655223
>This is O(n^2) though, you're applying a filter to the [1..n] range for every number n in the row.

Incorrect. The filter is not nested, just multiple linear passes of each row is made.

>> No.63659439

>>63659372
Lol, if you do the let i in arr the i will be a string, not an number. WAT?

>> No.63659482

>>63659439
Arrays in javascript are indexed with strings

>> No.63659511

>>63656300
You are comparing two different n's. The size of each individual integer is not the number of integers in the list.

The algorithm is linear time in the latter input.

>>
Name (leave empty)
Comment (leave empty)
Name
E-mail
Subject
Comment
Password [?]Password used for file deletion.
Captcha
Action