DEV Community

Henry
Henry

Posted on • Edited on

Advent of Code - Day 1

I saw the post from @qmenoret and I will now participate in the Advent of Code challenge for December!

Here is my solution to day 1:

let array = (document.querySelector('body > pre:nth-child(1)').innerText).split('\n')
let target = 2020

// part 1
array.forEach(x => {
   const diff = target - x
   const result = array.find(y => y == diff)
   result !== undefined && console.log(x * result)
})

// part 2
array.forEach(x => {
 for (let i = 1; i < array.length; i++) {
   const diff = target - x - array[i]
   const result = array.find(y => y == diff)
   result !== undefined && console.log(x * array[i] * result)
 }
})
Enter fullscreen mode Exit fullscreen mode

Some thoughts when solving the problem:

  • This is just brute force, I could probably reduce the complexity by using other algorithms
  • I am learning Rust, I want to try to write the solution in Rust but I have no better way to import the numbers (pointers needed)

Top comments (2)

Collapse
 
saukha profile image
Sau K • Edited

The first post I read on dev.to was @qmenoret 's post for advent of code day 8. I joint the community then. Here is my python codes for day 1:

Dec 2020 Day 1 part two

from numpy import genfromtxt
arr = genfromtxt('day1.txt', delimiter='', dtype = 'int')

product = 0
for i in range(len(arr)):
#print('i', df.loc[i][0])
for j in range(i+1, len(arr)):
#print(df.loc[j][0])
if arr[i]+ arr[j] == 2020:
if arr[i] * arr[j] > product:
yi=arr[i]
yj=arr[j]
product = yi * yj
print('1st #:', yi)
print('2nd #:', yj)
print(yi, '+', yj, '= 2020')
print('product:', product)

Dec 2020 Day 1 part two

product = 0 # reset
for i in range(len(arr)):
#print('i', df.loc[i][0])
for j in range(i+1, len(arr)):
#print(df.loc[j][0])
for k in range(j+1, len(arr)):
if arr[i]+ arr[j] + arr[k] == 2020:
if arr[i] * arr[j] * arr[k] > product:
yi=arr[i]
yj=arr[j]
yk=arr[k]
product = yi * yj * yk

print('1st #:', yi)
print('2nd #:', yj)
print('3rd #:', yk)
print(yi, '+', yj, '+', yk,'= 2020')
print('product:', product)

Collapse
 
qmenoret profile image
Quentin Ménoret

Happy to see you took on the challenge! 😁 👏