13 votes

Day 1: Report Repair

Today's problem description: https://adventofcode.com/2020/day/1


Join the Tildes private leaderboard! You can do that on this page, by entering join code 730956-de85ce0c.

Please post your solutions in your own top-level comment. Here's a template you can copy-paste into your comment to format it nicely, with the code collapsed by default inside an expandable section with syntax highlighting (you can replace python with any of the "short names" listed in this page of supported languages):

<details>
<summary>Part 1</summary>

```python
Your code here.
```

</details>

22 comments

  1. Deimos
    Link
    Not my solution, but a fun one from a guy whose blog I follow: I solved Advent of Code 2020, day 1, part 1 in pure AmigaShell. No ARexx! No cheating! Not sure if he's going to continue trying to...

    Not my solution, but a fun one from a guy whose blog I follow: I solved Advent of Code 2020, day 1, part 1 in pure AmigaShell. No ARexx! No cheating!

    It does take a while to run on my 14 MHz Amiga 1200. I didn't bother timing it, but probably at least a minute.

    Not sure if he's going to continue trying to do the whole thing (or if it'll even be feasible if the first one runs that slowly), but I thought it was neat.

    6 votes
  2. Gyrfalcon
    Link
    I won't be winning any speed records since I'm just getting to Day 2 now, but here's my solution for day 1, in Julia. I noticed that I didn't use any loops, so I am going to try to keep doing that...

    I won't be winning any speed records since I'm just getting to Day 2 now, but here's my solution for day 1, in Julia. I noticed that I didn't use any loops, so I am going to try to keep doing that since it was a fun challenge. I'll also have everything up in a repo.

    Parts 1 and 2
    function main()
    
        # Initialize array and read in input
        open("Day1/input.txt") do fp
            nums = map(x -> parse(Int, x), readlines(fp))
        end
    
        # Using sets, calculate remainders from 2020 and then intersect to find numbers in both
        nums = Set(nums)
        remainders = Set(2020 .- nums)
        targets_1 = intersect(nums, remainders)
        
        # Calculate and display what we need
        result_1 = prod(targets_1)
        println("Part 1 result is ", result_1)
    
        # Use implicit expansion to subtract the numbers
        second_remainders = Set(collect(remainders) .- collect(nums)')
        targets_2 = intersect(nums, second_remainders)
    
        # Calculate and display what we need
        result_2 = prod(targets_2)
        println("Part 2 result is ", result_2)
    end
    
    main()
    

    Performance wise, both parts together take 342 milliseconds on the first run, so that includes compilation. Subsequent runs are in the 40-50 millisecond range.

    5 votes
  3. [3]
    blitz
    Link
    Copied at request of Deimos: In these early days I usually like to make things more difficult for myself. I'm doing these in Rust. My solution to Day 1 is generalized to any sum and number of...

    Copied at request of Deimos:

    In these early days I usually like to make things more difficult for myself. I'm doing these in Rust.

    My solution to Day 1 is generalized to any sum and number of terms:

    Day 1
    use std::io;
    use std::process;
    use std::env;
    
    fn recursive_sum(remaining_entries: &[i32], considered: &mut Vec<i32>, target_num_terms: i32, target_sum: i32) {
        if considered.len() as i32 == target_num_terms - 1 {
            for x in remaining_entries {
                if considered.iter().sum::<i32>() + x == target_sum {
                    let product: i32 = considered.iter().product::<i32>() * x;
                    println!("{}", product);
                    process::exit(0);
                }
            }
        } else {
            for x in 0..remaining_entries.len() {
                considered.push(remaining_entries[x]);
                recursive_sum(&remaining_entries[x+1..], considered, target_num_terms, target_sum);
                considered.pop();
            }
        }
    }
    
    fn main() -> io::Result<()> {
        let args: Vec<String> = env::args().collect();
    
        let target_num_terms: i32 = args[1].parse().unwrap();
        let target_sum: i32 = args[2].parse().unwrap();
    
        let mut entries = Vec::new();
        let mut buffer = String::new();
        let mut considered = Vec::new();
    
        let stdin = io::stdin();
    
        while let Ok(_) = stdin.read_line(&mut buffer) {
            let new = buffer.trim().parse::<i32>().unwrap();
            buffer.clear();
    
            entries.push(new);
    
            if entries.len() >= target_num_terms as usize {
                recursive_sum(&entries, &mut considered, target_num_terms, target_sum);
    	    considered.clear();
            }
        }
    
        Ok(())
    }
    

    It's extremely slow, and I haven't been able to figure out why yet. If anyone has any ideas, let me know!

    4 votes
    1. [2]
      wirelyre
      Link Parent
      I have some bugs/suggestions. I've given hints in case you want to think about them yourself first. You try some combinations over and over… because in main, recursive_sum is called in the loop!...

      I have some bugs/suggestions. I've given hints in case you want to think about them yourself first.

      You try some combinations over and over…

      because in main, recursive_sum is called in the loop!

      The program behaviour is the same if all entries are read, then recursive_sum is called on the whole list.

      Parsing stdin fails if you reach the end…

      because Stdin::read_line returns Ok(0) at the end of the file!

      It's more idiomatic to write

      use std::io::{self, BufRead};
      
      let stdin = io::stdin();
      
      for line in stdin.lock().lines() {
          
      }
      
      The sum is computed repeatedly and needlessly…

      because you can keep a running sum at each level of the recursion! That is, you can pass an extra parameter running_sum, where running_sum == considered.sum().

      The considered vector is not necessary…

      because it is only ever used for push(), pop(), sum(), and product()! As above, you can keep a running sum and product at each level of recursion, obviating the vector entirely!

      The base case of the recursion is at target_num_terms - 1

      but it could be at target_num_terms! Then no loop is necessary in the base case.

      The recursive function could return a value…

      namely, the product if one was found. You could represent this as an Option<i32>.

      Extra work is done computing sums that are too large…

      because the recursion doesn't stop early if the sum is greater than the target!

      You can do even better — if the entries list is sorted, you can stop the loop early once you know that everything else in remaining_entries will produce a sum that is too large.


      I made all those changes in this new version, if you want to compare to what you have:

      use std::env;
      use std::io::{self, BufRead};
      
      // All integers upgraded to i64 to account for overflow.
      
      fn recursive_sum(
          remaining_entries: &[i64],
          num_entries_left: usize, // Recursion variable now goes down to 0, instead of up.
          target_sum: i64,
          running_sum: i64,     // Keep running sum...
          running_product: i64, // and product.
      ) -> Option<i64> {
          if num_entries_left == 0 {
              if running_sum == target_sum {
                  return Some(running_product); // Success!
              } else {
                  return None;
              }
          }
      
          for (idx, entry) in remaining_entries.iter().enumerate() {
              if running_sum + entry > target_sum {
                  // If this entry produces a partial sum that is too large, all the remaining entries
                  // will too!
                  return None;
              }
      
              match recursive_sum(
                  &remaining_entries[idx + 1..],
                  num_entries_left - 1,
                  target_sum,
                  running_sum + entry,
                  running_product * entry,
              ) {
                  None => continue,
                  Some(product) => return Some(product),
              }
          }
      
          None
      }
      
      fn main() {
          let args: Vec<String> = env::args().collect();
      
          let target_num_terms: usize = args[1].parse().unwrap();
          let target_sum: i64 = args[2].parse().unwrap();
      
          let mut entries = Vec::new();
      
          let stdin = io::stdin();
      
          for line in stdin.lock().lines() {
              let entry = line.unwrap().parse::<i64>().unwrap();
              entries.push(entry);
          }
      
          entries.sort();
      
          let product = recursive_sum(&entries, target_num_terms, target_sum, 0, 1).unwrap();
          println!("{}", product);
      }
      

      On my computer, in release mode, this new version can run to depth 5 in under 15 seconds (the target sum needs to be high enough).

      7 votes
      1. blitz
        Link Parent
        This is a fantastic code review. Thank you! I like to think some of these mistakes are due to working in an unfamiliar language, but I also haven't written recursive code since probably last...

        This is a fantastic code review. Thank you! I like to think some of these mistakes are due to working in an unfamiliar language, but I also haven't written recursive code since probably last year's AOC :)

        3 votes
  4. unknown user
    (edited )
    Link
    Here are my Day One solutions in Python Part 1 I'm there's a smarter way to do this... lol #!/usr/bin/python3 with open("expensereport","r") as file: lines = file.readlines() for i in lines: for j...

    Here are my Day One solutions in Python

    Part 1 I'm there's a smarter way to do this... lol
    #!/usr/bin/python3
    
    with open("expensereport","r") as file:
        lines = file.readlines()
    
    
    for i in lines:
        for j in lines:
            if int(i) + int(j) == 2020:
                print(int(i) * int(j))
    
    Part 2 I tried what I thought would be a slightly cleverer way of figuring out the answer... I'm not sure if it is any better. I also re-did part 1 here with the new method.
    #!/usr/bin/python3
    with open("expensereport","r") as file:
        lines = file.readlines()
        lines = [int(line.replace("\n","")) for line in lines]
    
    
    
    # part 1
    for i in lines:
        if 2020 - i in lines:
            print(i * (2020 - i))
    
    # part 2
    for i in lines:
        for j in lines:
            if 2020 - i - j in lines:
                print(i * j * (2020 - i - j))
    

    Any feedback is welcome :)

    4 votes
  5. 3d12
    Link
    Another late-comer here, I expect to have more time over the weekend but wanted to get a head start on it tonight. Since I'm learning Javascript currently, I'm planning to do the whole AoC event...

    Another late-comer here, I expect to have more time over the weekend but wanted to get a head start on it tonight. Since I'm learning Javascript currently, I'm planning to do the whole AoC event in Javascript. (Functionally, in Node, since I'm creating them as .js files and running them on a CLI, but trying to keep it as vanilla as possible) Here's my Day 1 solution, and my repository is here

    Part 1
    const fs = require('fs');
    const readline = require('readline');
    
    let numArr = [];
    
    async function openFileForReading(file) {
    	const fileStream = fs.createReadStream(file);
    
    	const rl = readline.createInterface({
    		input: fileStream,
    		crlfDelay: Infinity
    	});
    
    	for await (const line of rl) {
    		try {
    			numArr.push(parseInt(line));
    		} catch(e) {
    			console.error(e);
    		}
    	}
    }
    
    (async function mainExecution() {
    	await openFileForReading('input.txt');
    	//test: 1667
    	// find the entries that sum to 2020
    	for (const num1 of numArr) {
    		const num2 = 2020 - num1;
    		if (numArr.includes(num2)) {
    			console.log("Answer found! " + num1 + " * " + num2 + " = " + (num1 * num2));
    			break;
    		}
    	}
    })();
    
    Part 2
    const fs = require('fs');
    const readline = require('readline');
    
    let numArr = [];
    
    async function openFileForReading(file) {
    	const fileStream = fs.createReadStream(file);
    
    	const rl = readline.createInterface({
    		input: fileStream,
    		crlfDelay: Infinity
    	});
    
    	for await (const line of rl) {
    		try {
    			numArr.push(parseInt(line));
    		} catch(e) {
    			console.error(e);
    		}
    	}
    }
    
    (async function mainExecution() {
    	await openFileForReading('input.txt');
    	// find the entries that sum to 2020
    	for (const num1 of numArr) {
    		for (const num2 of numArr) {
    			const num3 = 2020 - num1 - num2;
    			if (num3 <= 0) continue;
    			if (numArr.includes(num3)) {
    				console.log("Answer found! " + num1 + " * " + num2 + " * " + num3 + " = " + (num1 * num2 * num3));
    				return;
    			}
    		}
    	}
    })();
    
    4 votes
  6. clone1
    Link
    MIT scheme solution Part 1 & 2 (define (get-lines parse-line) (with-input-from-file "input" (lambda () (let loop ((line (read-line)) (lines '())) (if (eof-object? line) (reverse lines) (loop...

    MIT scheme solution

    Part 1 & 2
    (define (get-lines parse-line)
      (with-input-from-file "input"
        (lambda ()
          (let loop ((line (read-line))
                     (lines '()))
            (if (eof-object? line)
                (reverse lines)
                (loop (read-line)
                      (cons (parse-line line) lines)))))))
    
    (define lines (get-lines string->number))
    
    (define (2sum target numbers)
      (let ((passed (make-weak-eq-hash-table)))
        (let loop ((numbers numbers))
          (if (null? numbers) #f
              (let* ((x (car numbers))
                     (complement (- target x)))
                (if (and (>= complement 0)
                         (hash-table/get passed complement #f))
                    (* x complement)
                    (begin
                      (hash-table/put! passed x #t)
                      (loop (cdr numbers)))))))))
    
    (define (3sum target numbers)
      (if (null? numbers) #f
          (let* ((x (car numbers))
                 (complement (- target x))
                 (remaining (cdr numbers)))
            (if (>= complement 0)
                (let ((complement-product (2sum complement remaining)))
                  (if complement-product
                      (* x complement-product)
                      (3sum target remaining)))
                (3sum target remaining)))))
    
    (define (one numbers) (2sum 2020 numbers))
    (define (two numbers) (3sum 2020 numbers))
    (one lines)
    (two lines)
    
    3 votes
  7. Crestwave
    Link
    Simple AWK solutions Part 1 #!/usr/bin/awk -f { arr[i++] = $0 } END { for (j = 0; j < i; ++j) for (k = j; k < i; ++k) if (arr[j] + arr[k] == 2020) print arr[j] * arr[k] } Part 2 #!/usr/bin/awk -f...

    Simple AWK solutions

    Part 1
    #!/usr/bin/awk -f
    { arr[i++] = $0 }
    
    END {
            for (j = 0; j < i; ++j)
                    for (k = j; k < i; ++k)
                            if (arr[j] + arr[k] == 2020)
                                    print arr[j] * arr[k]
    }
    
    Part 2
    #!/usr/bin/awk -f
    { arr[i++] = $0 }
    
    END {
            for (j = 0; j < i; ++j)
                    for (k = j; k < i; ++k)
                            for (l = k; l < i; ++l)
                                    if (arr[j] + arr[k] + arr[l] == 2020)
                                            print arr[j] * arr[k] * arr[l]
    }
    
    3 votes
  8. [5]
    spit-evil-olive-tips
    Link
    Very lazy, brute force solution in Python. Fun example of how O(n^2) vs O(n^3) doesn't matter when N is small enough, though. Part 1 takes 25 milliseconds on my laptop, part 2 took 700...

    Very lazy, brute force solution in Python.

    Fun example of how O(n^2) vs O(n^3) doesn't matter when N is small enough, though. Part 1 takes 25 milliseconds on my laptop, part 2 took 700 milliseconds.

    Part 1 & 2
    import sys
    
    def main():
        input_path = sys.argv[1]
    
        with open(input_path) as input_file:
            lines = input_file.readlines()
            numbers = [int(line) for line in lines]
    
        for x in numbers:
            for y in numbers:
                for z in numbers:
                    if x + y + z == 2020:
                        print(f'{x} * {y} * {z} = {x * y * z}')
    
    
    if __name__ == '__main__':
        main()
    
    2 votes
    1. [4]
      spit-evil-olive-tips
      (edited )
      Link Parent
      Even though my brute-force completely unoptimized O(n^3) solution only takes ~700 ms on the given input data, I felt like making it faster. much faster import time def main(): with open('001.txt')...

      Even though my brute-force completely unoptimized O(n^3) solution only takes ~700 ms on the given input data, I felt like making it faster.

      much faster
      import time
      
      
      def main():
          with open('001.txt') as input_file:
              lines = input_file.readlines()
              numbers = [int(line) for line in lines]
      
          results1 = brute_force(numbers)
          results2 = better(numbers)
          if results1 != results2:
              print('Better algorithm is wrong:')
              print(results1)
              print(results2)
      
      
      def timer(func):
          def wrapper(*args):
              start = time.perf_counter_ns()
              result = func(*args)
              end = time.perf_counter_ns()
              duration = (end - start) / 1_000_000
              print(f'{func.__name__}: {duration:.06f} milliseconds')
              return result
          return wrapper
      
      
      @timer
      def better(numbers):
          results = []
      
          lookup_set = set(numbers)
      
          for i, x in enumerate(numbers):
              for j, y in enumerate(numbers, i + 1):
                  z = 2020 - x - y
                  if z in lookup_set:
                      results.append((x, y, z))
      
          return results
      
      
      @timer
      def brute_force(numbers):
          results = []
      
          for x in numbers:
              for y in numbers:
                  for z in numbers:
                      if x + y + z == 2020:
                          results.append((x, y, z))
      
          return results
      
      
      if __name__ == '__main__':
          main()
      

      Two pretty straightforward improvements:

      First, once we pick our first candidate value (x, at index i), we only need to consider second values that come after index i. Values before that in the list would already have been considered once, just the other way around.

      Second, once we've picked two values, we can simply calculate what the third value would need to be, in order to add up to 2020. Then check if that value was present in the input using a set as a lookup table that we only have to compute once.

      I also considered sorting the list and doing the check for the existence of z as a binary search from j to the end of the list. That'd be a tiny bit more complicated but have the benefit of not requiring any extra memory for the lookup table.

      Results on my laptop:

      brute_force: 646.317135 milliseconds
      better: 4.223847 milliseconds
      

      It varied a bit among multiple runs but ~650ms vs. ~4-5ms was consistent.

      3 votes
      1. [3]
        ali
        Link Parent
        that @timer stuff looks really cool I should look into that. I code tons of python for my AI nowadays but my coding interviews usually were always in python. I knew this type of problem and I...

        that @timer stuff looks really cool I should look into that. I code tons of python for my AI nowadays but my coding interviews usually were always in python.
        I knew this type of problem and I tried it using a sort and then going through the array from both ends

        Using your timer code it takes 0.386325 milliseconds. And your solution takes about the same amount of time for me

        brute_force: 654.206014 milliseconds
        better: 4.215089 milliseconds

        are you also using a macbook pro 2017?

        heres my solution: https://tildes.net/~comp.advent_of_code/to5/day_1_report_repair#comment-5x8u

        2 votes
        1. Deimos
          (edited )
          Link Parent
          The built-in timeit library is really useful for timing pieces of code as well, including running it many times and averaging it to avoid the possibility of outlier results when you're just timing...

          The built-in timeit library is really useful for timing pieces of code as well, including running it many times and averaging it to avoid the possibility of outlier results when you're just timing one call.

          4 votes
        2. spit-evil-olive-tips
          Link Parent
          Nope, I've got a Lenovo X1 Carbon, but appears to have a very similar CPU - Core i5 7200U in mine vs. 7360U in yours. And the "start at both ends and work towards the middle" algorithm is a neat...

          are you also using a macbook pro 2017?

          Nope, I've got a Lenovo X1 Carbon, but appears to have a very similar CPU - Core i5 7200U in mine vs. 7360U in yours.

          And the "start at both ends and work towards the middle" algorithm is a neat trick, I hadn't considered that at all. I went from O(n^3) to O(n^2) and now your solution is O(n). (I guess O(n log n) considering the initial sort)

          2 votes
  9. PapaNachos
    Link
    I'm using Python using Anaconda and Jupyter Notebook. I love Advent of Code because it's a great chance to stretch my coding muscles. Day 1 A For this one I just brute forced it. This rechecks...

    I'm using Python using Anaconda and Jupyter Notebook. I love Advent of Code because it's a great chance to stretch my coding muscles.

    Day 1 A For this one I just brute forced it. This rechecks several time, both 'A' + 'B' = 2020 and 'B' + 'A' = 2020 show up as valid results. If you wanted to be more efficient, you could make sure that each combination only gets checked once.
    test_data = '''1721
    979
    366
    299
    675
    1456'''
    
    numbers = test_data.split('\n')
    
    for i in range(0, len(numbers)): 
        numbers[i] = int(numbers[i]) 
        
        
    for num1 in numbers:
        for num2 in numbers:
             if num1 != num2 and num1 + num2 == 2020:
                    print(f"Match Found: {num1} + {num2} = 2020")
                    print(f"{num1} * {num2} = {num1 * num2}")
    
    Day 1 B This is basically the same as part A, but with an added layer. So instead of checking 'A' + 'B', you're checking 'A' + 'B' + 'C'. This is far, far less efficient because of that added step, but with a data set this small it didn't really matter.
    test_data = '''1721
    979
    366
    299
    675
    1456'''
    
    numbers = test_data.split('\n')
    
    for i in range(0, len(numbers)): 
        numbers[i] = int(numbers[i]) 
        
        
    for num1 in numbers:
        for num2 in numbers:
            for num3 in numbers:
                if num1 != num2 and num1 != num3 and num2 != num3 and num1 + num2 + num3 == 2020:
                    print(f"Match Found: {num1} + {num2} + {num3} = 2020")
                    print(f"{num1} * {num2} * {num3} = {num1 * num2 * num3}")
    
    2 votes
  10. ali
    (edited )
    Link
    Here's my Python solution. It's very fast ( 0.268495 milliseconds on my laptop) - but it uses a sort at the start Part 1 import time start = time.perf_counter_ns() f = open("input.txt", "r") input...
    Here's my Python solution. It's very fast ( 0.268495 milliseconds on my laptop) - but it uses a sort at the start Part 1
    import time
    start = time.perf_counter_ns()
    
    
    f = open("input.txt", "r")
    input = f.readlines()
    input_arr = [int(i) for i in input]
    input_arr.sort()
    i = 0
    j = len(input_arr)-1
    while i<j:
        left_number = input_arr[i]
        right_number = input_arr[j]
        result = left_number+right_number
        if result == 2020:
            # result
            print(left_number*right_number)
            break
        elif result < 2020:
            i+=1
        elif result > 2020:
            j-=1
    
    end = time.perf_counter_ns()
    duration = (end - start) / 1_000_000
    print(f' {duration:.06f} milliseconds')
    
    I didn't realize there was a part 2 and I have to work a bit so I just brute forced it Part 1 ```python def prob_2(input_arr): for i in input_arr: for j in input_arr[1:]: for k in input_arr[2:]: if i+j+k == 2020: return i*j*k ```
    2 votes
  11. tomf
    (edited )
    Link
    With Google Sheets. I'm trying to do most of these with one formula, which as of now (day three) has been successful. We'll see what the future holds. Part 1 =ARRAYFORMULA( TRANSPOSE( QUERY(...

    With Google Sheets. I'm trying to do most of these with one formula, which as of now (day three) has been successful. We'll see what the future holds.

    Part 1
    =ARRAYFORMULA(
      TRANSPOSE(
       QUERY(
        SPLIT(
         FLATTEN(
          IF(ISBLANK(A2:A),,
           (A2:A+TRANSPOSE(FILTER(A2:A,A2:A<>""))&"|"&
           A2:A&"|"&TRANSPOSE(FILTER(A2:A,A2:A<>""))))),
         "|"),
        "select Col2, Col3 
         where Col1 = 2020 
         limit 1")))
    
    
    Part 2
    =ARRAYFORMULA(
      UNIQUE(
       QUERY(
        FLATTEN(
         IF(ISBLANK(A2:A),,
          IFERROR(
           VLOOKUP(
            2020-
             (A2:A+TRANSPOSE(FILTER(A2:A,A2:A<>""))),
            A2:A,1,FALSE)))),
        "select Col1 
         where Col1 is not null")))
    
    
    2 votes
  12. heady
    Link
    I haven't really coded anything since the last advent and my lack of improvement shows Day 1 expensereport = open("day1input", 'r') entries = [] for line in expensereport:...

    I haven't really coded anything since the last advent and my lack of improvement shows

    Day 1
    expensereport = open("day1input", 'r')
    entries = []
    
    for line in expensereport:
        entries.append(int(line))
    
    def findtriumvirs(entries, value1):
        for entry in entries:
            value2 = findpair(entries, (entry + value1))
            if value2 == (2020 - (entry + value1)):
                values = [value1, value2, entry]
                return values
    
    def findpair(entries, value1):
        value2 = 2020 - value1
        for entry in entries:
            if entry == value2:
                return entry
        #this saves some time on part 1
        #entries.remove(entry)
        return None
    
    for entry in entries:
        values = findtriumvirs(entries, entry)
        if values:
            break
    
    product = values[0] * values[1] * values[2]
    
    print("values are " + str(values) + " and product is " + str(product))
    
    2 votes
  13. 0d_billie
    Link
    Bit behind, but I finally got my solution for Day 1! Part 1 runs in 0.0022 seconds #!/usr/bin/env python # Create empty list and import data into it as integers expenses = [] with...

    Bit behind, but I finally got my solution for Day 1!

    Part 1 runs in 0.0022 seconds
    #!/usr/bin/env python
    # Create empty list and import data into it as integers
    expenses = []
    with open("day_01_input.csv", "r") as input:
        for line in input.readlines():
            expenses.append(int(line))
            
    # Set target number, length of input list, and starting index i
    target = 2020
    length = len(expenses)
    
    # Two numbers summing to target
    i = 0 
    while i < length:
        for n in range(i+1, length):
            if expenses[i] + expenses[n] == target:
                print(expenses[i] * expenses[n])
        i+=1
    
    Part 2 runs in 0.12 seconds
    #!/usr/bin/env python
    # Create empty list and import data into it as integers
    expenses = []
    with open("day_01_input.csv", "r") as input:
        for line in input.readlines():
            expenses.append(int(line))
            
    # Set target number, length of input list, and starting index i
    target = 2020
    length = len(expenses)
    
    # Three numbers summing to target
    i = 0
    while i < length:
        for n in range(i+1, length):
            for m in range(n+1,length):
                if expenses[i] + expenses[n] + expenses[m] == target:
                    print(expenses[i] * expenses[n] * expenses[m])
        i+=1
    
    2 votes
  14. jwong
    Link
    I'm surprised at the lack of Java here Part 1 - 2.025 ms import java.io.BufferedReader; import java.io.FileReader; import java.io.File; import java.io.IOException; import java.util.ArrayList;...

    I'm surprised at the lack of Java here

    Part 1 - 2.025 ms
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.File;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.HashMap;
    
    public class ReportRepair {
      public static void main (String[] args) {
        long startTime = System.nanoTime();
        ArrayList<Integer> input = new ArrayList<>();
    
        // get input
        BufferedReader reader;
        try {
          String filePath = new File("").getAbsolutePath();
          filePath = filePath.concat("/input.txt");
          reader = new BufferedReader(new FileReader(filePath));
          String line = reader.readLine();
          while (line != null) {
            input.add(Integer.parseInt(line));
            line = reader.readLine();
          }
          reader.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
        // end get input
    
        // Create a hashmap of the complement, then we can look for the complement afterwards
        HashMap<Integer, Boolean> complements = new HashMap<>();
        int answer = 0;
        for(int i : input) {
          if (complements.containsKey(i)) {
            answer = i * (2020 - i);
            break;
          }
          int complement = 2020 - i;
          complements.put(complement, true);
        }
        if (answer != 0) {
          System.out.println( answer );
        } else {
          System.out.println( "No answer found" );
        }
        long endTime   = System.nanoTime();
        long totalTime = endTime - startTime;
        System.out.println("Time completed: " + totalTime + " nanoseconds");
      }
    }
    
    Part 2 - 12.69 ms
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.File;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.HashMap;
    
    public class ReportRepairPt2 {
      public static void main (String[] args) {
        long startTime = System.nanoTime();
        ArrayList<Integer> input = new ArrayList<>();
    
        // get input
        BufferedReader reader;
        try {
          String filePath = new File("").getAbsolutePath();
          filePath = filePath.concat("/input.txt");
          reader = new BufferedReader(new FileReader(filePath));
          String line = reader.readLine();
          while (line != null) {
            input.add(Integer.parseInt(line));
            line = reader.readLine();
          }
          reader.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
        // end get input
    
        // Create a hashmap of the complement, then we can look for the complement afterwards
        HashMap<Integer, Integer> complements = new HashMap<>();
        for(int i : input) {
          int partialSum = 2020 - i;
          complements.put(partialSum, i);
        }
    
        int answer = 0;
    
        for(int i : input) {
          for(int j : input) {
            int comboSum = i + j;
            if (complements.containsKey( comboSum )) {
              int thirdValue = complements.get( comboSum );
              answer = thirdValue * i * j;
              break;
            }
          }
        }
    
        if (answer != 0) {
          System.out.println( answer );
        } else {
          System.out.println( "No answer found" );
        }
        long endTime   = System.nanoTime();
        long totalTime = endTime - startTime;
        System.out.println("Time completed: " + totalTime + " nanoseconds");
      }
    }
    
    2 votes
  15. knocklessmonster
    Link
    I thought i was doing the wrong one, didn't realize there were two parts. I'm doing this in C# because it's harder, Python's almost made for this sort of stuff. Entry 1 using System; using static...

    I thought i was doing the wrong one, didn't realize there were two parts. I'm doing this in C# because it's harder, Python's almost made for this sort of stuff.

    Entry 1
    using System;
    using static System.Console;
    using System.IO;
    //It's all in one block because I'm basically adding them all in line.  200^3 is a *lot* of numbers, though.
    class Advent1 {
        
        static void Main() {
            string[] lines = System.IO.File.ReadAllLines(Path.Combine(Directory.GetCurrentDirectory(), "input"));
            string doublemult = "";
            string tripmult = "";
            foreach (string line in lines)
            {
                int int1 = Convert.ToInt32(line);
                foreach (string line2 in lines)
                {
                    int int2 = Convert.ToInt32(line2);
                    if (int1 + int2 == 2020)
                    {
                        doublemult = (int1 * int2).ToString();
                    }
                    foreach (string line3 in lines)
                        {
                            int int3 = Convert.ToInt32(line3);
                            if (int1 + int2 + int3 == 2020)
                            {
    
                                tripmult = (int1 * int2 * int3).ToString();
                            }
                        }
                }
            }
            WriteLine("The multiple of two numbers that add up to 2020 is: {0}", doublemult);
            WriteLine("The multiple of three numberst that add up to 2020 is: {0}", tripmult);
            ReadKey();
    
        }
    }
    
    1 vote
  16. [2]
    Comment deleted by author
    Link
    1. Deimos
      Link Parent
      Whoops, thanks. The join code is still the same though, right?

      Whoops, thanks. The join code is still the same though, right?

      3 votes