24 votes

Day 1: Calorie Counting

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

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>

32 comments

  1. [3]
    tomf
    (edited )
    Link
    Another year of Sheets because I didn't learn shit in any of the previous years. Anyway, I first did this with a vlookup with a filter all wrapped with a QUERY -- but that is ugly. Not that this...

    Another year of Sheets because I didn't learn shit in any of the previous years. Anyway, I first did this with a vlookup with a filter all wrapped with a QUERY -- but that is ugly. Not that this is much prettier.

    both parts ``` =ARRAYFORMULA( BYCOL( LARGE( BYROW( SPLIT(TRANSPOSE(SPLIT(CONCATENATE(A1:A&"|"),"||",FALSE,TRUE)),"|"), LAMBDA(x,SUM(x))), {1,1;1,2;1,3}), LAMBDA(x,SUM(UNIQUE(x))))) ```
    5 votes
    1. [2]
      cfabbro
      Link Parent
      I'm sure you learned plenty, but perhaps you're just a masochist? ;)

      I'm sure you learned plenty, but perhaps you're just a masochist? ;)

      2 votes
      1. tomf
        Link Parent
        haha. i’ve leaned more spreadsheet stuff. i was hoping to learn a little python or something

        haha. i’ve leaned more spreadsheet stuff. i was hoping to learn a little python or something

        2 votes
  2. [2]
    tjf
    Link
    I'm using Python again this year, but going for a better balance of concision and readability. Last year I code golfed my solutions, rendering them totally unreadable to present me. I might also...

    I'm using Python again this year, but going for a better balance of concision and readability. Last year I code golfed my solutions, rendering them totally unreadable to present me. I might also attempt a handful of the days in either Haskell or a Scheme, but we'll see if that pans out.

    Part 1
    #!/usr/bin/env pypy3
    
    import sys
    
    def main():
        elves = [map(int, elf.split('\n')) for elf in sys.stdin.read()[:-1].split('\n\n')]
        print(max(map(sum, elves)))
    
    if __name__ == '__main__':
        main()
    
    Part 2
    #!/usr/bin/env pypy3
    
    import sys
    
    def main():
        elves = [map(int, elf.split('\n')) for elf in sys.stdin.read()[:-1].split('\n\n')]
        print(sum(sorted(map(sum, elves))[-3:]))
    
    if __name__ == '__main__':
        main()
    
    4 votes
    1. bhrgunatha
      (edited )
      Link Parent
      The main reason (after lack of ability) I can't get into code golf. I'd try to improve some code and get completely lost trying to decrypt my thinking and not understand it from the code.

      totally unreadable to present me

      The main reason (after lack of ability) I can't get into code golf.
      I'd try to improve some code and get completely lost trying to decrypt my thinking and not understand it from the code.

      3 votes
  3. [4]
    bhrgunatha
    (edited )
    Link
    Function composition ftw Santa's little helpers (define groups (curryr string-split "\n\n")) (define lines (curryr string-split "\n")) Slurping data (define elves (groups (file->string...

    Function composition ftw

    Santa's little helpers
    (define groups (curryr string-split "\n\n"))
    (define lines (curryr string-split "\n"))
    
    Slurping data
    (define elves (groups (file->string "day01.input")))
    (define calories (compose (curry apply +)
                              (curry map string->number)
                              lines))
    (define elf-calories (sort (map calories elves) >))
    
    Barfing result
    (printf "Part 01: ~a\n" (first elf-calories))
    (printf "Part 02: ~a\n" (apply + (take elf-calories 3)))
    

    This would have been so much more elegant in Haskell or using the threading library.


    Speedrun

    Once I have a solution, I like to make them as fast as I can.
    Here's the 1st improvement ~20% elapsed time.

    (with-input-from-file "day01.input"
       (thunk
        (define elves
          (for/fold ([elves null]
                     [elf 0]
                     #:result (sort elves >))
                    ([line (in-lines)])
            (if (string=? line "")
                (values (cons elf elves) 0)
                (values elves (+ elf (string->number line))))))
        (list (first elves) (apply + (take elves 3)))))
    
    4 votes
    1. [3]
      thorondir
      Link Parent
      That's... much more elegant than what I did. From how the story went, I was sure there was going to be something more difficult for part two, so I set it up in a broader way, which then turned out...

      That's... much more elegant than what I did.

      From how the story went, I was sure there was going to be something more difficult for part two, so I set it up in a broader way, which then turned out to be unnecessary...

      Input parsing
      ;; function to make input usable
      (define (sanitize-input input)
        (define elf-strings (string-split input "\n\n"))
        (for/list ([e elf-strings])
          (define inventory (map string->number (string-split e "\n")))
          (elf (apply + inventory) inventory)
        ))
      ; returns a list of elves, each with their own inventory and the sum of calories as its own thing, for easy access
      

      Given that, parts one was actually a simple one-liner.

      Part 1
      (define (part-1 input)
        (elf-calories (argmax elf-calories input)))
      

      Part two was a bit more complicated, because I have to tell it how to sort the elves, but it's not rocket science.

      Part 2
      (define (part-2 input)
          (apply + (map elf-calories (take (sort input (lambda (a b) (> (elf-calories a) (elf-calories b)))) 3))))
      

      For starting with racket not all that long ago, I'm quite happy about how it turned out.

      2 votes
      1. [2]
        bhrgunatha
        Link Parent
        That looks elegant to me, just a different approach. I usually use iterators and sequences because I think they are easier to reason about when the problem is more complex. It's a unique thing...

        That looks elegant to me, just a different approach. I usually use iterators and sequences because I think they are easier to reason about when the problem is more complex.

        It's a unique thing about AoC, it makes you second guess yourself in part 1 for what's coming in part 2. Sometimes the gamble pays off, sometimes it doesn't.

        small tip

        The #:key selector is used to extract a value for comparison - perfect for this situation:

        (sort input > #:key elf-calories)
        
        2 votes
        1. thorondir
          Link Parent
          Oh, nice! That does make it much more readable. xD Thank you so much!

          Oh, nice! That does make it much more readable. xD

          Thank you so much!

          3 votes
  4. [3]
    kari
    Link
    Decided to try out nim literally minutes before I started (I've done like half of nim by example before and no other nim) so it was actually a bit of a struggle. My solution kinda sucks, though....

    Decided to try out nim literally minutes before I started (I've done like half of nim by example before and no other nim) so it was actually a bit of a struggle. My solution kinda sucks, though.

    Both parts
    import std/strutils
    import std/sequtils
    
    proc day1*() = 
      var 
        elves = newSeq[int]()
        currentElf = 0
        topThreeSum = 0 
    
      for line in lines("inputs/day1.in"):
        if line != "":
          currentElf += parseInt(line)
        else:
          elves.add(currentElf)
          currentElf = 0
    
      for _ in countup(1,3):
        let idx = elves.maxIndex()
        topThreeSum += elves[idx]
        elves.delete(idx)
    
      echo(topThreeSum)
    
    2 votes
    1. [2]
      petrichor
      Link Parent
      Nice, love to see Nim! A few tips: You don't need to explicitly initialize the sequence: var elves: seq[int] works just as well You can use 1..3 instead of countup(1, 3), or 1 ..< 4 imports can be...

      Nice, love to see Nim! A few tips:

      • You don't need to explicitly initialize the sequence: var elves: seq[int] works just as well
      • You can use 1..3 instead of countup(1, 3), or 1 ..< 4
      • imports can be on one line like import std/[strutils, sequtils]
      • sequtils is your friend for Advent of Code - there are so many helpful functions in there
      • and if you end up using sequtils' functional programming functions: try out the anonymous function syntax in std/sugar
      2 votes
      1. kari
        Link Parent
        Thank you!! That's super helpful :) I admittedly didn't see this until after I finished day 2, but I'll keep all of that in mind for the rest of the challenges (and if I ever do any non-aoc nim...

        Thank you!! That's super helpful :) I admittedly didn't see this until after I finished day 2, but I'll keep all of that in mind for the rest of the challenges (and if I ever do any non-aoc nim programming)

        1 vote
  5. soks_n_sandals
    Link
    I am doing these challenges in bash this year. a+b #!/usr/bin/env bash file=day1.dat part=2 lastline=$(tail -n 1 $file) if [[ ! -z ${lastline} ]]; then echo >> $file fi if [[ ${part} -eq 2 ]];...

    I am doing these challenges in bash this year.

    a+b
    #!/usr/bin/env bash
    
    file=day1.dat
    part=2
    lastline=$(tail -n 1 $file)
    if [[ ! -z ${lastline} ]]; then
        echo >> $file
    fi
    
    if [[ ${part} -eq 2 ]]; then
    # /////////////////////////////////////////////////////////////////////////////
    #part 2 0m0.505s
    #this solves both parts since we didn't need to store number of elves or number of food items for pt2...
    intCals=()
    backpack=() #just calorie counts
    while read -r line || [[ -n "${line}" ]]; do
    
    #   -- check whether we hit a blank line. If so, sum calories
    
        if [[ -z ${line} ]]; then
            backpack+=("$(echo "${intCals[@]/%/+}0" | bc)")
            intCals=()
        else
            intCals[${#intCals[@]}]=${line}
        fi
       
    done < ${file}
    
    IFS=$'\n' 
    sortedBackpack=($(sort --numeric-sort -r <<< "${backpack[*]}"))
    unset IFS
    echo Anwer to part 1: ${sortedBackpack[0]}
    echo Answer to part 2: $(echo "${sortedBackpack[0]/%/+}" "${sortedBackpack[1]/%/+}" "${sortedBackpack[2]/%/+}0" | bc)
    
    # /////////////////////////////////////////////////////////////////////////////
    fi
    
    2 votes
  6. jzimbel
    Link
    Elixir Doing Elixir again this year. I usually last until the problems get into pathfinding algorithms and such. I use a project that provides some conveniences for fetching the problem inputs, so...

    Elixir

    Doing Elixir again this year. I usually last until the problems get into pathfinding algorithms and such.

    I use a project that provides some conveniences for fetching the problem inputs, so each solution I post will always come in the form of a module with two functions, part1 and part2, which receive the input string.

    Both parts
    defmodule AdventOfCode.Solution.Year2022.Day01 do
      def part1(input) do
        input
        |> String.split("\n\n", trim: true)
        |> Enum.map(&sum_inventory/1)
        |> Enum.max()
      end
    
      def part2(input) do
        input
        |> String.split("\n\n", trim: true)
        |> Enum.map(&sum_inventory/1)
        |> Enum.sort(:desc)
        |> Enum.take(3)
        |> Enum.sum()
      end
    
      defp sum_inventory(s) do
        s
        |> String.split("\n", trim: true)
        |> Enum.map(&String.to_integer/1)
        |> Enum.sum()
      end
    end
    
    2 votes
  7. Crespyl
    Link
    Working in Clojure this time around, also probably not going to try and stay up all night so much this year. Parts 1 & 2 (defn parse-elves [input] (->> (str/split input #"\n\n") (map...

    Working in Clojure this time around, also probably not going to try and stay up all night so much this year.

    Parts 1 & 2
    (defn parse-elves [input]
      (->> (str/split input #"\n\n")
          (map #(str/split-lines %))
          (map #(map parse-long %))
          (map vec)))
    
    (defn sort-elves [elves]
      (->> elves
           (sort-by #(reduce + %))
           (reverse)))
    
    (defn part-1 [input]
      (->> input
           parse-elves
           sort-elves
           first
           (reduce +)))
    
    (defn part-2 [input]
      (let [elves (sort-elves (parse-elves input))
            first (nth elves 0)
            second (nth elves 1)
            third (nth elves 2)]
        (reduce + (concat first second third))))
    
    2 votes
  8. Eabryt
    Link
    Last year I used this to try to learn Rust and ended up giving up around Day 11 (oddly enough, right around my last day of work for the year) This year I've decided to stick with Python as I'm...

    Last year I used this to try to learn Rust and ended up giving up around Day 11 (oddly enough, right around my last day of work for the year)

    This year I've decided to stick with Python as I'm pretty familiar with the language and I'm hoping it'll keep me going through the end.

    Full Solution
    def part1(input):
        elves = []
        index = 0
        elves.append(0)
        for line in input:
            if line != "\n":
                elves[index] += int(line)
            else:
                index += 1
                elves.append(0)
        print(f"Max Calories: {max(elves)}")
        return elves
    
    
    def part2(input):
        input.sort()
        print(f"Sum: {sum(input[-3:])}")
    
    
    def openfile():
        return open("input.txt", "r").readlines()
    
    
    def main():
        f = openfile()
        elves = part1(f)
        part2(elves)
    
    
    if __name__ == '__main__':
        main()
    

    I probably could have done it simpler, but my goal isn't to try to find the fanciest solution, just a simple one that would be reasonable to use in a professional setting.

    2 votes
  9. [2]
    asterisk
    Link
    Python, nothing special. with open("input.txt") as file: elves = [0] for line in file: line = line.strip() if line: elves[-1] += int(line) else: elves.append(0) elves = sorted(elves)...

    Python, nothing special.

    with open("input.txt") as file:
        elves = [0]
    
        for line in file:
            line = line.strip()
            if line:
                elves[-1] += int(line)
            else:
                elves.append(0)
    
    elves = sorted(elves)
    print(elves[-1])  # Part One: 68442
    print(sum(elves[-3:]))  # Part Two: 204837
    
    1 vote
    1. 0d_billie
      Link Parent
      It looks like we landed on a broadly similar approach, although yours is considerably neater I think! Answer #!/usr/bin/python3 with open('input_proper_1') as input: elves = [] calories = 0 for...

      It looks like we landed on a broadly similar approach, although yours is considerably neater I think!

      Answer
      #!/usr/bin/python3
      
      with open('input_proper_1') as input:
          elves = []
          calories = 0
          for line in input:
              line = line.strip()
              if line == "":
                  elves.append(calories)
                  calories = 0
              else:
                  calories += int(line)
          elves.append(calories)
      
      elves = sorted(elves)
      print(elves[-1])
      print(sum(elves[-3:]))
      
      1 vote
  10. MeckiSpaghetti
    (edited )
    Link
    solution in Ruby Both parts s = File .read("input.txt") .split("\n\n") .map{ _1.split.map(&:to_i).sum } .sort .reverse p s.first # Part #1 p s.take(3).sum # Part #2

    solution in Ruby

    Both parts
    s = File
         .read("input.txt")
         .split("\n\n")
         .map{ _1.split.map(&:to_i).sum }
         .sort
         .reverse
    
    p s.first # Part #1
    p s.take(3).sum # Part #2
    
    1 vote
  11. [4]
    vord
    (edited )
    Link
    I'm on a journey to start writing services in node, so that means learning Javascript. Thankfully coming in new, I can try to avoid all the broke old methods. Advice welcome. My biggest learning...

    I'm on a journey to start writing services in node, so that means learning Javascript. Thankfully coming in new, I can try to avoid all the broke old methods. Advice welcome.

    My biggest learning moment was that parseInt() was critical to avoid string concatenation.

    Code
    "use strict";
    
    import * as fs from 'node:fs/promises';
    
    async function main() {
      let elf_number = 0;
      let elf_list = []; 
      elf_list[elf_number] = 0;
    
      const file = await fs.open("input/input");
    
      for await (const line of file.readLines()) {
        if (line.length === 0) {
          elf_number++;
          elf_list[elf_number] = 0 
        }   
        else {
          elf_list[elf_number] += parseInt(line);
        }   
      }
    
      elf_list.sort();
      let max_elf = elf_list.pop();
      console.log("Max Elf Calories: ", max_elf);
    
      /* Part 2 */
      let top_three = max_elf;
      for (let i = 1; i < 3; i++) {
        top_three += elf_list.pop();
      }
      console.log("Top Three: ", top_three);
    
    }
    
    main();
    
    1 vote
    1. [2]
      jzimbel
      Link Parent
      I think strict mode is used by default in modules (which node should pick up on since you used import)...

      I think strict mode is used by default in modules (which node should pick up on since you used import)

      https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode#strict_mode_for_modules

      You can double-check this by adding a line like undefinedVariable = 1; to the file and seeing if it throws an error (strict mode) or not (sloppy mode).

      2 votes
      1. vord
        Link Parent
        Good to know!

        Good to know!

        1 vote
    2. Macil
      Link Parent
      The elf_number variable is unnecessary, and I'd usually recommend against using an explicit index variable like that if you don't need it because it's an easy source of errors in more complex...

      The elf_number variable is unnecessary, and I'd usually recommend against using an explicit index variable like that if you don't need it because it's an easy source of errors in more complex programs if it gets out of sync with the list size (as it does after you start popping items from the list) and you keep using it. You can append an item to the end of a list with the push method (elf_list.push(0)), and access the last item of the list with elf_list[elf_list.length-1].

      1 vote
  12. csos95
    (edited )
    Link
    I'm giving Haxe another try and using it for this advent of code (at least for now). I made a comment in early 2021 when I last tried it out and the reasons I gave still hold true. I think the...

    I'm giving Haxe another try and using it for this advent of code (at least for now).
    I made a comment in early 2021 when I last tried it out and the reasons I gave still hold true.
    I think the reason I didn't end up doing much with it last time was mainly due to lacking documentation (in the project itself and third party libraries), so hopefully that's gotten a bit better since then.

    Code
    using Lambda;
    using Std;
    using StringTools;
    
    class Day1 {
    	static public function main() {
    		var input = sys.io.File.getContent('input/day1');
    		part1(input);
    		part2(input);
    	}
    
    	static function part1(input: String) {
    		var max_calories = input
    			.trim()
    			// split into groups of calorie counts
    			.split("\n\n")
    			// calculate calorie count of each group
    			.map(group ->
    				group.split("\n")
    					.map(calories -> calories.parseInt())
    					.fold((calories, total) -> calories + total, 0)
    			)
    			// find the max calorie count
    			.fold((calories, max_calories) ->
    				if (calories > max_calories)
    					calories
    				else
    					max_calories
    			, 0);
    
    		Sys.println('day1 part1: $max_calories');
    	}
    
    	static function part2(input: String) {
    		var calories = input
    			.trim()
    			// split into groups of calorie counts
    			.split("\n\n")
    			// calculate calorie count of each group
    			.map(group ->
    				group.split("\n")
    					.map(calories -> calories.parseInt())
    					.fold((calories, total) -> calories + total, 0)
    			);
    
    		// sort in reverse order
    		calories.sort((a, b) -> b - a);
    
    		// print the sum of the top three calorie counts
    		Sys.println('day1 part2: ${calories[0] + calories[1] + calories[2]}');
    	}
    }
    

    Edit: I added a Common module with various extensions that I need that aren't included in the standard library.
    Right now it's a few iterator/math functions.
    I went back and changed my solution for this day to be a bit more compact/use the Common module.

    Day1
    using Common.IterTools;
    using Lambda;
    using Std;
    using StringTools;
    
    class Day1 {
    	static public function run(input: String) {
    		part1(input);
    		part2(input);
    	}
    
    	static function part1(input: String) {
    		var max_calories = calculateCalories(input).max();
    
    		Sys.println('day1 part2: $max_calories');
    	}
    
    	static function part2(input: String) {
    		var calories = calculateCalories(input);
    
    		// sort in reverse order
    		calories.sort((a, b) -> b - a);
    
    		Sys.println('day1 part2: ${calories[0] + calories[1] + calories[2]}');
    	}
    
    	static function calculateCalories(input: String): Array<Int> {
    		return input
    			.trim()
    			// split into groups of calorie counts
    			.split("\n\n")
    			// calculate calorie count of each group
    			.map(group ->
    				group.split("\n")
    					.fold((calories, total) -> calories.parseInt() + total, 0)
    			);
    	}
    }
    
    Common
    import haxe.ds.Option;
    using Lambda;
    
    class IterTools {
    	public static function sum(it: Iterable<Int>): Int {
    		return it.fold((n, acc) -> n + acc, 0);
    	}
    
    	public static function sumf(it: Iterable<Float>): Float {
    		return it.fold((n, acc) -> n + acc, 0);
    	}
    
    	public static function max(it: Iterable<Int>): Int {
    		return it.fold((n, max) -> if (n > max) n else max, 0);
    	}
    
    	public static function min(it: Iterable<Int>): Int {
    		return it.fold((n, min) -> if (n < min) n else min, 0);
    	}
    
    	public static function maxf(it: Iterable<Float>): Float {
    		return it.fold((n, max) -> if (n > max) n else max, 0);
    	}
    
    	public static function minf(it: Iterable<Float>): Float {
    		return it.fold((n, min) -> if (n < min) n else min, 0);
    	}
    
    	public static function filter_map<A, B>(it: Iterable<A>, f:(item: A) -> Option<B>): Array<B> {
    		return it.map(f)
    			.filter(item -> switch (item) {
    				case Some(_): true;
    				case None: false;
    			})
    			.map(item -> switch (item) {
    				case Some(item): item;
    				// should never occur
    				case None: null;
    			});
    	}
    }
    
    1 vote
  13. spit-evil-olive-tips
    Link
    part 1 with open('01.txt') as input_file: contents = input_file.read() total_calories = list() elves = contents.split('\n\n') for elf in elves: calories = [int(line) for line in elf.split('\n')]...
    part 1
    with open('01.txt') as input_file:
    	contents = input_file.read()
    
    total_calories = list()
    
    elves = contents.split('\n\n')
    
    for elf in elves:
    	calories = [int(line) for line in elf.split('\n')]
    	total_calories.append(sum(calories))
    
    print(max(total_calories))
    
    part 2
    --- aoc01a.py   2022-12-01 15:54:12.468426455 -0800
    +++ aoc01b.py   2022-12-01 15:54:16.174470842 -0800
    @@ -9,5 +9,7 @@
            calories = [int(line) for line in elf.split('\n')]
            total_calories.append(sum(calories))
     
    -print(max(total_calories))
    +total_calories.sort()
    +
    +print(sum(total_calories[-3:]))
    
    neat trick

    with this sort of input (newline-delimited, with blank lines separating groups) you can split by \n\n in order to get the groups, and then split each group by \n to get the items.

    1 vote
  14. Gyrfalcon
    Link
    I had hoped to try out Rust this year, but I haven't gotten around to actually learning much of it so I settled on Python, since my new work uses it a lot and it would be good to brush up. I am...

    I had hoped to try out Rust this year, but I haven't gotten around to actually learning much of it so I settled on Python, since my new work uses it a lot and it would be good to brush up. I am also going hard on organizing code, adding at least semi real tests for the provided test cases, etc. Anyway, solution:

    Parts 1 and 2
    import os
    from aoc2022.common import load_file
    
    current_dir = os.path.realpath(os.path.dirname(__file__))
    INPUT_FILE = "/".join([current_dir, "input.txt"])
    TEST_FILE_1 = "/".join([current_dir, "test1.txt"])
    TEST_RESULTS_1 = (24000, 45000)
    
    
    def parse_elves(lines: list[str]) -> list[list[int]]:
        elves = []
        elf: list[int] = []
        for line in lines:
            if line == "\n":
                elves.append(elf)
                elf = []
            else:
                elf.append(int(line))
    
        elves.append(elf)
    
        return elves
    
    
    def count_calories(elves: list[list[int]]) -> list[int]:
        return [sum(elf) for elf in elves]
    
    
    def main(filepath: str) -> int:
        lines = load_file.load_lines(filepath)
        elves = parse_elves(lines)
    
        calorie_totals = count_calories(elves)
        calorie_totals.sort(reverse=True)
        return (calorie_totals[0], sum(calorie_totals[:3]))
    
    
    if __name__ == "__main__":
        part1, part2 = main(INPUT_FILE)
    
        print(part1)
        print(part2)
    

    And the common file which will hopefully fill out a bit as time goes on:

    def load_lines(filename: str) -> list[str]:
        with open(filename, "r") as fp:
            return fp.readlines()
    
    1 vote
  15. Crestwave
    Link
    POSIX AWK as usual. Maybe I'll try another language mid-way. Part 1 #!/usr/bin/awk -f /^$/ { i += 1 } { arr[i] += $1 } END { for (i in arr) if (arr[i] > max) max = arr[i] print(max) } Part 2...

    POSIX AWK as usual. Maybe I'll try another language mid-way.

    Part 1
    #!/usr/bin/awk -f
    /^$/ { i += 1 }
    { arr[i] += $1 }
    
    END {
    	for (i in arr)
    		if (arr[i] > max)
    			max = arr[i]
    
    	print(max)
    }
    
    Part 2
    #!/usr/bin/awk -f
    /^$/ { i += 1 }
    { arr[i] += $1 }
    
    END {
    	for (i in arr) {
    		if (arr[i] > max[0]) {
    			max[2] = max[1]
    			max[1] = max[0]
    			max[0] = arr[i]
    		} else if (arr[i] > max[1]) {
    			max[2] = max[1]
    			max[1] = arr[i]
    		} else if (arr[i] > max[2]) {
    			max[2] = arr[i]
    		}
    	}
    
    	print(max[0] + max[1] + max[2])
    }
    
    1 vote
  16. wycy
    Link
    Rust Rust use std::env; use std::io::{self}; fn solve(input: &str) -> io::Result<()> { // Input let input_str = std::fs::read_to_string(input).unwrap(); let input_str = input_str.trim(); let...

    Rust

    Rust
    use std::env;
    use std::io::{self};
    
    fn solve(input: &str) -> io::Result<()> {
        // Input
        let input_str = std::fs::read_to_string(input).unwrap();
        let input_str = input_str.trim();
        let input: Vec<_> = input_str.split("\n\n").collect();
    
        // Get each Elf's calories
        let mut elf_snacks: Vec<usize> = input
            .iter()
            .map(|x| x
                .split("\n")
                .map(|y| y.parse::<usize>().unwrap())
            .sum())
            .collect();
        elf_snacks.sort_by(|a, b| b.cmp(a));
    
        // Calculate answers
        let part1 = elf_snacks.iter().max().unwrap();
        let part2 = elf_snacks.iter().take(3).sum::<usize>();
    
        println!("Part 1: {}", part1); // 72602
        println!("Part 2: {}", part2); // 207410
    
        Ok(())
    }
    
    fn main() {
        let args: Vec<String> = env::args().collect();
        let filename = &args[1];
        solve(&filename).unwrap();
    }
    
    1 vote
  17. fazit
    (edited )
    Link
    All my Javascript friends do oneliners with map and reduce, so I had to give it a try in python: Python oneliners print(max([reduce(lambda tot, cal: int(int(tot)+int(cal)), map(int,...

    All my Javascript friends do oneliners with map and reduce, so I had to give it a try in python:

    Python oneliners
    print(max([reduce(lambda tot, cal: int(int(tot)+int(cal)), map(int, elv.split('\n'))) for elv in input_str.split('\n\n')]))
    print(sum(sorted([reduce(lambda tot, cal: int(int(tot)+int(cal)), map(int, elv.split('\n'))) for elv in input_str.split('\n\n')])[-3:]))
    
    1 vote
  18. Toric
    Link
    Decided to use rust. Ive gon through rust by example and the rust book, so I 'know' rust, but I dont really feel fully comfortable in it, and I find Advent Of Code a really good way to get...

    Decided to use rust. Ive gon through rust by example and the rust book, so I 'know' rust, but I dont really feel fully comfortable in it, and I find Advent Of Code a really good way to get comfortable with a language.

    Driver
    mod parse;
    mod part1;
    mod part2;
    
    fn main() {
        let _input = include_str!("./input.txt");
        let _structured_input = parse::parse(_input);
    
        println!("Part One");
        println!("Result: {}", part1::part1(&_structured_input));
    
        println!("Part Two");
        println!("Result: {}", part2::part2(&_structured_input));
    }
    
    Parser
    #[derive(Debug, PartialEq, Eq)]
    pub struct Elf(pub Vec<usize>);
    
    pub fn parse(input: &str) -> Vec<Elf> {
        input
            .trim()
            .split("\n\n")
            .map(|group| {
                Elf(group
                    .split('\n')
                    .map(|line| line.parse().unwrap())
                    .collect())
            })
            .collect::<Vec<Elf>>()
    }
    
    Part 1
    use crate::parse;
    
    pub fn part1(input: &[parse::Elf]) -> usize {
        input
            .iter()
            .map(|elf| elf.0.iter().sum::<usize>())
            .max()
            .unwrap()
    }
    
    Part 2
    use crate::parse;
    
    pub fn part2(input: &[parse::Elf]) -> usize {
        let mut input = input
            .iter()
            .map(|elf| elf.0.iter().sum::<usize>())
            .collect::<Vec<usize>>();
        input.sort_unstable();
        input[input.len() - 3..].iter().sum()
    }
    
    1 vote
  19. balooga
    Link
    Here's my TypeScript solution type InputData = number[][]; function formatInput(input: string): InputData { return input.split('\n\n').map(e => e.split('\n').map(f => Number(f))); } export...
    Here's my TypeScript solution
    type InputData = number[][];
    
    function formatInput(input: string): InputData {
      return input.split('\n\n').map(e => e.split('\n').map(f => Number(f)));
    }
    
    export function run(input: string): string[] {
      const data = formatInput(input);
    
    Part 1
      const findLargestCalorieTotal = (elves: InputData): number => {
        let largestTotal = 0;
        elves.forEach(elf => {
          const elfTotal = elf.reduce((total, current) => {
            return total + current;
          }, 0);
          if (elfTotal > largestTotal) {
            largestTotal = elfTotal;
          }
        });
        return largestTotal;
      };
    
    Part 2
      const findTopThreeCalorieTotal = (elves: InputData): number => {
        const topThree = [0, 0, 0] as [number, number, number];
    
        const addToTopThree = (elfTotal: number): void => {
          topThree.reduce((prevTotal, currentTotal, index) => {
            if (prevTotal > currentTotal) {
              topThree[index] = prevTotal;
              return currentTotal;
            }
            return prevTotal;
          }, elfTotal);
        };
    
        elves.forEach(elf => {
          const elfTotal = elf.reduce((total, current) => {
            return total + current;
          }, 0);
          addToTopThree(elfTotal);
        });
    
        return topThree[0] + topThree[1] + topThree[2];
      };
    
      return [`${findLargestCalorieTotal(data)}`, `${findTopThreeCalorieTotal(data)}`];
    }
    
    1 vote
  20. whispersilk
    Link
    I'm using Rust this year, and hoping to keep it std-only throughout the month. Part 1 use std::error::Error; use std::fs::File; use std::io::Read; fn main() -> Result<(), Box<dyn Error>> { let mut...

    I'm using Rust this year, and hoping to keep it std-only throughout the month.

    Part 1
    use std::error::Error;
    use std::fs::File;
    use std::io::Read;
    
    fn main() -> Result<(), Box<dyn Error>> {
    	let mut file = File::open("input_1.txt")?;
    	let mut contents = String::new();
    	file.read_to_string(&mut contents)?;
    	let max_elf: u64 = contents
    		.trim()
    		.split("\n\n")
    		.map(|one_elf|
    			one_elf.split('\n')
    				.map(|line| u64::from_str_radix(line, 10).unwrap())
    				.fold(0, |acc, x| acc + x))
    		.max()
    		.unwrap();
    	println!("{max_elf}");
    	Ok(())
    }
    
    Part 2
    use std::error::Error;
    use std::fs::File;
    use std::io::Read;
    
    fn main() -> Result<(), Box<dyn Error>> {
    	let mut file = File::open("input_1.txt")?;
    	let mut contents = String::new();
    	file.read_to_string(&mut contents)?;
    	let elves: (u64, u64, u64) = contents
    		.trim()
    		.split("\n\n")
    		.map(|one_elf|
    			one_elf.split('\n')
    				.map(|line| u64::from_str_radix(line, 10).unwrap())
    				.fold(0, |acc, x| acc + x))
    		.fold((0, 0, 0), |acc, x| {
    			if x > acc.0 {
    				(x, acc.0, acc.1)
    			} else if x > acc.1 {
    				(acc.0, x, acc.1)
    			} else if x > acc.2 {
    				(acc.0, acc.1, x)
    			} else {
    				acc
    			}
    		});
    	println!("{}", elves.0 + elves.1 + elves.2);
    	Ok(())
    }
    
    1 vote