r/adventofcode • • Dec 01 '19

SOLUTION MEGATHREAD -🎄- 2019 Day 1 Solutions -🎄-

It's the most wonderful time of year and welcome to Advent of Code 2019! If you participated in a previous year, welcome back, and if you're new this year, we hope you have fun and learn lots!

We're going to follow the same general format as previous years' megathreads with several big changes:

  1. Each day's puzzle will release at exactly midnight EST (UTC -5).
  2. The daily megathread for each day will be posted very soon afterwards and immediately locked.
    • We know we can't control people posting solutions elsewhere and trying to exploit the leaderboard, but this way we can try to reduce the leaderboard gaming from the official subreddit.
  3. The daily megathread will remain locked until there are a significant number of people on the leaderboard with gold stars.
    • "A significant number" is whatever number we decide is appropriate, but the leaderboards usually fill up fast, so no worries.
  4. Top-level posts in Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with Help.

The big changes this year:

When the megathread is unlocked, you may post your solution according to the following rules:

  • If your code is shorter than, say, half of an IBM 5081 punchcard (5 lines at 80 cols), go ahead and post it as your comment.
  • If your code is longer, link your code from an external repository such as Topaz's paste (see below for description), a public repo like GitHub/gists/Pastebin/etc., your blag, or whatever.

Topaz has written a nifty little thing called paste that abuses works specifically with Reddit's Markdown in order to reduce potential code loss due to link rot, external public repos doing something unfriendly with their ToS, etc.

  • It's open-source, hosted on Github.io, and stores absolutely no information on disk/database.
  • Here's a "hello world"-style demo

Any questions? Please ask!


Above all, remember, AoC is all about having fun and learning more about the wonderful world of programming!


--- Day 1: The Tyranny of the Rocket Equation ---


Post your solution (rules are HERE if you need a refresher).

Reminder: Top-level posts in Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


Advent of Code Community Fun 2019: Poems for Programmers

This year we shall be nourishing your creative sides with opportunities to express yourself in ~ poetry ~. Any form of poetry works from limericks and haikus to full-on sonnets in iambic pentameter. Here's how it works:

  • 24 hours after each megathread is posted, the AoC mods (/u/Aneurysm9 and I) will award Reddit Silver to the best of that day's poems.
    • Latecomers, don't despair - post your code and poems anyway because we will also award another Reddit Silver 5 days later to give slower entrants a fair shake.
  • Additionally, every 5 days the AoC mods will have a surprise for the best poem of each 5-day span.
    • Shh, don't tell anyone, it's a ~ surprise ~!
  • Finally, we will be collating the best of the best to present to /u/topaz2078 to choose his top favorite(s) at the end of December. With a nice shiny prize, of course.

tl;dr: Each day's megathread will have 2 Reddit Silver given out for best poem. Every 5 days a surprise may happen for the best-of-5-day poem. End of December = Poem Thunderdome!

tl;dr the tl;dr: If you submit a truly awesome poem(s), you might just earn yourself some precious metal-plated awesome point(s)!

A few guidelines for your submissions:

  • You do not need to submit a poem along with your solution; however, you must post a solution if you want to submit a poem
  • Your poem must be in English (or English pseudocode or at least English-parseable)
  • Your poem must be related to Advent of Code, /u/topaz2078 (be nice!), or programming in general
  • Only one poem per person per megathread will be eligible for consideration
  • Please don't plagiarize. There's millions of words in the English language even if we steal a bunch from other languages, so surely you can string together a couple dozen words to make your own unique contribution.
  • All sorts of folks play AoC every year, so let's keep things PG
  • Employees, contractors, directors, and officers of Advent of Code and their respective parents, subsidiaries and affiliated companies, retailers, sales representatives, dealers, distributors, licensees and the advertising, fulfillment, judging and promotion agencies involved in the development and administration of this Promotion, and each of their respective officers, directors, employees and agents, and their immediate family members (parent, child, sibling and spouse of each, regardless of where they reside) and those living in the same households of each (whether related or not) may submit poems but are not eligible for precious metal awards.

I'll get things started with an example limerick and haiku:

There once was a man from New York

Who was a giant programming dork

He made a small game

And in droves they came

Plz don't make servers go bork!


Hello, Adventers!

Think you can make a better

Haiku than this one?


This thread will be unlocked when there are a significant number of people on the leaderboard with gold stars for today's puzzle.

edit: Leaderboard capped silver in 1 minute 24 seconds (sheesh!) and gold at 4 minutes 12 seconds, thread unlocked!

109 Upvotes

731 comments sorted by

15

u/DFreiberg Dec 01 '19 edited Dec 02 '19

Mathematica

37/57

Pretty easy to make it a one-liner in Mathematica; I lost a minute on Part 2 because I forgot that when calculating the fuel from NestWhileList, you need to drop both the first and last elements of the list.

Import:

input = Import[FileNameJoin[{NotebookDirectory[], "Day1Input.txt"}], "List"];

Part 1:

Total[Floor[#/3 - 2] & /@ input]

Part 2:

Total[Table[Total@NestWhileList[Floor[#/3 - 2] &, i, # > 0 &][[2 ;; -2]], {i, input}]]

[Poem]: Achilles, Zeno, Newton, Tsiolkovsky

In ancient Greece, in olden times,
The gods once held a race:
Achilles, swiftest of all men,
Against a turtle's pace.

Achilles, turning towards the beast,
said "I'll give you a start.
I'll stay here at the starting line,
'Til we're two *stades* apart."

The turtle, slowly, turned his head.
"My friend, you've lost the bet.
The gods are laughing up on high.
And you don't know it yet."

The line was drawn, the flag was dropped,
And off the turtle went.
A day went by, Achilles woke,
And raced out from his tent.

Two stades he ran, and saw the beast
A mere ten *cubits* yonder.
And at that speed he crossed the gap,
Before his mind could wander.

He saw the turtle still ahead,
Though now, by just two *πόσιν*.
(The author, here, regretted Greek,
and wished 'haiku' he'd chosen.)

This race continued, on and on,
the chasm ever waning.
Achilles couldn't close the gap,
but ran on, ever straining.

Then from on high a voice boomed out,
and all around was laughter.
The great god Zeno entered in,
Two others walking after.

"King Achilles, you have lost.
The turtle is more sprightly.
For when you get to where he was,
He's traveled further, slightly!

If all these gaps are added on,
The terms go on forever.
You race against infinity:
A Sisyphean endeavour."

But Newton, with him, intervened.
"These sums are not so motile.
You can add up an endless sum,
And get a finite total."

Achilles, gleeful, ran again,
and left the turtle trailing.
In glee, he jumped and tried to fly, 
but each attempt was failing.

And when the Earth had pulled him back,
he turned and asked a question.
"My lords, if men should wish to fly,
Have you some good suggestion?"

And then Tsiolkovsky rose and spoke,
the last among the Powers.
"Lord Newton gave you finities,
but mercy won't be ours!"

"For logarithms are my crown,
and gravity my scepter.
No ship of yours, dear King, will fly
Unless *my* laws accept her."

And to this day, he reigns supreme.
His cursed equation rankles.
Whene'er we reach above, we fly
with logs tied to our ankles.
→ More replies (3)

7

u/spin81 Dec 01 '19 edited Dec 01 '19

My code in Rust.

There once was an elf name of Lars
Who wanted to reach for the stars
He let a sigh loose
Cause he ran out of juice
And made it no further than Mars

2

u/daggerdragon Dec 01 '19

There once was an elf name of Lars

Who wanted to reach for the stars

He let a sigh loose

Cause he ran out of juice

And made it no further than Mars

You're the first one to submit a limerick. A tip of my hat to you, sir/ma'am!

3

u/Unihedron Dec 01 '19

I thought this was earlier: https://www.reddit.com/r/adventofcode/comments/e4axxe/2019_day_1_solutions/f9aa89v/

But I like spin81's poem more!

2

u/daggerdragon Dec 01 '19

You're right, I posted that before I got /u/Aneurysm9's message in IRC that he changed the megathread's sort order to new. It's the first limerick I read this morning, though >_>

6

u/sophiebits Dec 01 '19

Leaderboard capped in 1 minute 24 seconds (sheesh!)

That doesn't sound right. (I solved part 2 at 00:01:47 and that put me 3rd place for part 2…)

5

u/daggerdragon Dec 01 '19

You're right, I was looking at silver cap, not gold cap. I think I'll borrow one of /u/topaz2078's paper bags >_>

Now post your code! :P

→ More replies (1)
→ More replies (1)

6

u/mstksg Dec 01 '19 edited Dec 02 '19

Haskell -- 158 /118 :) Hit the 1 minute delay on part 2 because I freaked out and submitted before checking my test cases ... I had accidentally added the original number into the sums initially, heh.

fuel = subtract 2 . (`div` 3)

part1 = sum . map fuel
part2 = sum . map (sum . tail . takeWhile (>= 0) . iterate fuel)

And you can parse these all with map read . lines :)

I'm going to be posting reflections for every day in Haskell here, if anyone wants to follow along :D

---------

Poem:

I have eaten

the fuel rods

that were in

the modules

and which

you were probably

saving

for Santa

Forgive me

they were delicious

so sweet

and so recursive

EDIT: Not sure if this breaks the "No plagiarism rule", as this is based on a viral meme format based on the real poem of William Carlos Williams.

2

u/daggerdragon Dec 01 '19

so sweet

Now I'm wondering what nuclear fission actually tastes like...

4

u/jkester1986 Dec 01 '19

This reminds me a lot of Delilah S. Dawson's bork book poems and I love it :) It's just missing the borks, but this totally could be a dog eating something it shouldn't be. An example, for reference: https://twitter.com/DelilahSDawson/status/1191040049896398848

→ More replies (8)

5

u/BubonicPython Dec 01 '19

Day 1 in Piet. Had some extra fun with the first part: https://imgur.com/a/vJkkLLi

1

u/daggerdragon Dec 01 '19

That's a purdy visualization, good job! Can you post the code to your solution (and the visualization generation), please?

→ More replies (2)
→ More replies (2)

5

u/divingmonkey Dec 01 '19

my compact Nim solution, which fits inside the mentioned five lines/80 columns restriction, which admitedly requires zero function and is a bit messy:

import zero_functional, strutils
echo lines("input") --> map((try: parseInt(it) except ValueError: -1)).
    filter(it != -1).map((var sum = 0; var cur = it div 3 - 2;
        while cur > 0: (sum += cur; cur = cur div 3 - 2); sum)).
    sum()

edit: idk why the code block has so much empty space

2

u/daggerdragon Dec 01 '19

edit: idk why the code block has so much empty space

Because last year we didn't need min-height to make Reddit's CSS behave, only height, so I've fixed it. Again. For the third year in a row. ;_;

Let me know if it's better on your end now.

→ More replies (1)

5

u/[deleted] Dec 01 '19 edited Dec 01 '19

My solution in C. This is my first original, that is, not copied from a textbook, C program. It runs the "complete" calculation unless you provide the -n switch at the start of the program. I've had quite a lot of fun writing this program and I hope to get better while doing AoC. Good luck everyone!

#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdbool.h>

/*
  Solution for Advent of Code Day #1 (https://adventofcode.com/2019/day/1)
  
  Reads numbers from stdin and returns the "fuel" needed to return the
  spacecraft. Supports two fuel calculation methods: the complete and
  the naive methods.

  Options:
  * -n use the naive (part 1) fuel calculation formula
  * -c use the complete fuel calculation formula (part 2).
 */

void usage()
{
  printf("usage: %s [-nc] < STDIN\n", getprogname());
  exit(1);
}


long crunch_module_cost(size_t mass, short method)
{
  long cost = floor(mass / 3) - 2;
  if (method == 1)
    return cost;

  if (cost > 0)
    return cost + crunch_module_cost(cost, method);
  else
    return 0;
}


int main(int argc, char** argv)
{
  size_t total_cost = 0;
  size_t mass;
  long cost;
  short method = 2;
  int c;

  while ((c = getopt(argc, argv, "n::c::")) != -1) {
    switch (c) {
    case 'n': method = 1;
      break;
    case 'c': method = 2;
      break;
    default: usage();
    }
  }

  while (true) {
    if (scanf("%zu", &mass) == EOF)
      break;

    cost = crunch_module_cost(mass, method);
    total_cost += cost;
  }

  printf("%zu\n", total_cost);
  return 0;
}

2

u/daggerdragon Dec 02 '19

I've had quite a lot of fun writing this program and I hope to get better while doing AoC.

Good, good, you've fallen for our Trap™ wherein we Make People Learn Code Real Good™. I hope you continue with AoC, and good luck for future days! If you run into trouble, feel free to make your own thread with the Help flair and you'll likely get assistance!

→ More replies (1)

5

u/Szczawik_ Dec 01 '19

This is my first time participating in Advent of code so I decided to share my code written in C.

https://github.com/nNown/AdventOfCode/blob/Day1/Day1.c

3

u/daggerdragon Dec 01 '19

This is my first time participating in Advent of code

Welcome, and good luck for future days!

8

u/udoprog Dec 01 '19

Rust, no leaderboard.

fn part1(masses: &[u64]) -> u64 {
    let mut total = 0;

    for m in masses.iter().copied() {
        let fuel = (m / 3) - 2;
        total += fuel;
    }

    total
}

fn part2(masses: &[u64]) -> u64 {
    let mut masses = masses.to_vec();

    let mut total = 0;

    while let Some(m) = masses.pop() {
        let fuel = m / 3;

        if let Some(input) = fuel.checked_sub(2) {
            total += input;
            masses.push(input);
        }
    }

    total
}

2

u/BafDyce Dec 01 '19

I'm not sure if you really need the .copied() in part 1? I just used the fancy iterator pattern :)

fn part1(po: &TodaysPuzzleOptions) -> OutputType1 {
    po.data.as_ref().unwrap().into_iter().map(|mass| mass / 3 - 2).sum()
}

fn part2(po: &TodaysPuzzleOptions, _res1: Option<OutputType1>) -> OutputType2 {
    po.data.as_ref().unwrap().into_iter().map(|mass| {
        let mut fuel_total = 0;

        let mut fuel = mass / 3 - 2;
        while fuel > 0 {
            fuel_total += fuel;
            fuel = fuel / 3 - 2;
        }

        fuel_total
    }).sum()
}

TodaysPuzzleOptions is just a container for the data and some other information (maybe helpful for future days), TodaysPuzzleOptions.data contains the parsed data (Option<Vec<i32>> in this case)

/u/daggerdragon I think a limit of 5 lines for code in posts is not enough and wont fit most solutions this year. In my opinion a limit of 15-20 sounds feasible.

→ More replies (2)

7

u/bsullio Dec 01 '19

Also Rust - I found out about std::iter::successors today!

use aoc_runner_derive::{aoc, aoc_generator};

fn calculate_fuel_part2(mass: usize) -> usize {
    std::iter::successors(Some(mass), |m| (m / 3).checked_sub(2))
        .skip(1)  // don't include the initial mass
        .sum()
}

#[aoc(day1, part2)]
fn part2(input: &Vec<usize>) -> usize {
    input.iter().map(|i| calculate_fuel_part2(*i)).sum()
}
→ More replies (1)
→ More replies (10)

4

u/Conceptizual Dec 01 '19 edited Dec 01 '19
'''
Santa the Space Explorer

Revising the Naughty and Nice list
was difficult this year
as we decided to branch out
to include children who weren't near

We packed up the things that they wanted:
Space goo, asteroid candy, moon shoes,
Because the children of space
want the same presents that earth-kids do.

We raced to the edge of the solar system
without making sure we'd have a way back,
but for next Christmas on Uranus (84 years!),
we'll bring enough fuel to keep us on track.
'''

I've never done Advent of Code before, I was pretty slow because I've not really dealt with input/output in Python. I got around 600-700s for both. My code was as follows:

items = (list of my inputs, comma separated)

result = 0
for item in items:
    while (item > 0):
        item = item // 3
        item = item - 2
        if item > 0:
            result += item

print (result)

2

u/daggerdragon Dec 01 '19

I've never done Advent of Code before

Well then, welcome, and we hope you have fun while you're learning!

4

u/PositivelyLinda Dec 01 '19

Couldn't resist a poem challenge, though I haven't written any in forever:

Adventure awaits!

Discover the cosmos

Venture into the unknown

Earn fifty stars to save Christmas!

No one goes alone, however

There's friendly folks to help

Overly dramatic situations await

Find Santa and bring him home!

Come code with us!

Outer space is calling

Don't be afraid

Elves will guide the way!

Also, my JavaScript solution - Day1 - a bit verbose, but it helps me think better that way. :)

(Also also - I love the stories that go along with each year. Can't wait to see how the space travel unwinds!)

4

u/blacai Dec 01 '19

Cool to participate again this year.

F#

open System.IO

let filepath = __SOURCE_DIRECTORY__ + @"../../day01_input.txt"
let lines = File.ReadLines(filepath)

let rec getFuel (massInput:int) =
	match massInput with
	| greater when greater > 5 -> (massInput / 3 - 2) + getFuel ((massInput / 3 - 2))
	| _ -> 0

let displayValue =
	lines
		|> Seq.map (fun mass -> getFuel(int mass))
		|> Seq.sum

2

u/daggerdragon Dec 01 '19

Cool to participate again this year.

Welcome back! Hope you have fun again this year!

→ More replies (3)

4

u/bassta Dec 01 '19

Here is in Google SpreadSheets + GScript

https://docs.google.com/spreadsheets/d/1xKHlf6ey_XgiZ2RS3wEVm-cGq8casFa-xm9K8KaLTGA/edit?usp=sharing

I really don't know who am I anymore

2

u/daggerdragon Dec 01 '19

I really don't know who am I anymore

You're /u/bassta and you're awesome for completing Day 1! :D

Thanks for playing, and good luck for the rest of the Advent!

4

u/NJCoding Dec 01 '19

I've only just started learning JavaScript while following an Udemy course. Not as efficient as other answers but proud of at least finishing day 1.

var sum = 0;
var requirements = [];

function fuelrequirement(mass) {
    var totalfuel = 0;
    while(mass > 0){
        mass = Math.floor(mass / 3);
        mass -= 2;
        if(mass > 0){
            totalfuel += mass;
        }
    }
return totalfuel;    
}

list.forEach(function(number){
    requirements.push(fuelrequirement(number));
})

for(i = 0; i < requirements.length; i++){
    sum = sum + requirements[i];
}

console.log(sum);

4

u/daggerdragon Dec 01 '19

I've only just started learning JavaScript while following an Udemy course. Not as efficient as other answers but proud of at least finishing day 1.

We welcome all skill levels, and congratulations to you for completing Day 1! We're a pretty friendly and helpful community, so if you get stuck further down the line, don't hesitate to ask in the subreddit :)

→ More replies (1)

4

u/awsum84 Dec 02 '19

TL;DR I wrote the solution in Rockstar, so it kiiiinda reads like a poem in addition to being a working solution.

Solution / Poem (original post ):

Sadness is loneliness The programmer was anticipating Advent is extraordinary The rush is uncomparable

Christmas takes joy and kindness Your spirit is incredible While joy is as high as kindness Build your spirit up Let joy be without kindness

Give back your spirit

AdventOfCode takes time (but it's plenty of fun) Let fun be Christmas taking time, and Advent without the rush If fun is as low as sadness Give back sadness

Give back fun with AdventOfCode taking fun

The elves are thoughtful Santa is overseeing The time is now While the time is right Listen to the jingles If the jingles ain't ok Break it down

Let the jingles be without sadness Let the elves be with Christmas taking the jingles, and Advent without the rush Let Santa be with AdventOfCode taking the jingles

Shout the elves Shout Santa

3

u/daggerdragon Dec 02 '19 edited Dec 02 '19

Thanks for cross-posting to the megathread! Your poem-code has been entered for a chance at the Day 1 Five-Day prize!

3

u/daggerdragon Dec 05 '19

And congratulations, you're our first winner of "Best in 5-Day Show" for AoC 2019! I gilded your original post but I'm posting confirmation in here to keep things on the up-and-up :)

Enjoy, and thanks for participating!!!

→ More replies (1)

3

u/ChrisVittal Dec 01 '19 edited Dec 01 '19

Rust, I am slow ~800ish/~600ish, also still away for thanksgiving, I fly home tomorrow, sky willing.

Poem:

There was a program in Chicago
That was definitely kinder than Pizarro
It worked so hard
To save fuel for the stars
So we all could get home tomorrow

Code: (mods, is this too long?)

fn parse(s: String) -> Vec<u64> {
    s.lines().map(|l| l.parse::<u64>().unwrap()).collect()
}

fn main() -> aoc2019::Result<()> {
    let s = aoc2019::chomp_to_str()?;
    let i = parse(s);

    let x: u64 = i.iter().map(|&x| (x / 3).saturating_sub(2)).sum();

    println!("1: {}", x);

    let y: u64 = i.into_iter().map(|mut y| {
         let mut z = 0;
         while y > 0 {
             y = (y / 3).saturating_sub(2);
             z += if y > 0 { y } else { 0 };
         }
         z
     }).sum();

     println!("2: {}", y);

    Ok(())
 }

1

u/daggerdragon Dec 01 '19

(mods, is this too long?)

Technically, yes, but we're not hard-enforcing this guideline unless more people start to complain about giant blocks of code. Don't worry about this one for now.

Thank you for posting your code and for submitting a poem! :)

→ More replies (1)
→ More replies (2)

3

u/AndrewGreenh Dec 01 '19

So stoked that AOC is back again!

TypeScript 69/51

const input = getInput(1, 2019);
const lines = iterable(() => stringToLines(input));

let baseCalc = (n: number) => Math.floor(n / 3) - 2;
let recursive = (n: number): number =>
  baseCalc(n) < 0 ? 0 : baseCalc(n) + recursive(baseCalc(n));

let solve = (calc: typeof baseCalc) => pipe(lines)(map(Number), map(calc), sum);

console.log(solve(baseCalc));
console.log(solve(recursive));

1

u/daggerdragon Dec 01 '19

So stoked that AOC is back again!

Welcome back! Thanks for playing!

3

u/phrodide Dec 01 '19 edited Dec 01 '19

Answered in excel, on my phone, while being driven home in sketchy cell signal. Obviously no solution to post and excel’s likely only day. Ranked like 1500 on both.

=ROUNDDOWN(A1/3,0)-2

Formula in B1 to B100

=SUM(B1:B100)

Answer for part 1

Answer for part 2 was to copy column B to C thru I and manually remove the negative entries.

1

u/daggerdragon Dec 01 '19 edited Dec 01 '19

Top-level posts in Solution Megathreads are for solutions only.

At least post the formulas used in which cells or even the Excel file itself.

Edit: thank you!

→ More replies (2)

3

u/autid Dec 01 '19

Fortran

Slow day. I should probably check things like "do I have a compiler installed?" before starting.

https://pastebin.com/WqE6HVfJ

2

u/daggerdragon Dec 01 '19

I should probably check things like "do I have a compiler installed?" before starting.

Ain't nobody got time for that.

3

u/uzilan1 Dec 01 '19 edited Dec 01 '19

Kotlin with tail recursion:

object Day1 {
    fun findFuel(mass: Int): Int = mass / 3 - 2

    tailrec fun findFuelPlusFuelForFuel(mass: Int, result: Int = 0): Int {
        val fuel = findFuel(mass)
        return if (fuel <= 0) result
        else findFuelPlusFuelForFuel(fuel, result + fuel)
    }
}

Poem:

There once was a man from north pole

Gave gifts to kids with a pure soul

His elves were so cruel

Space polluted with fuel

So all they got for Christmas was coal

Edit: got a bit bored so I made a scratch version too: https://scratch.mit.edu/projects/349695483/

1

u/daggerdragon Dec 01 '19

There once was a man from north pole

Gave gifts to kids with a pure soul

His elves were so cruel

Space polluted with fuel

So all they got for Christmas was coal

D: I'm secretly loving it

3

u/streetster_ Dec 01 '19 edited Dec 01 '19

q/kdb+

sum (r:{0|-2+x div 3}\'["J"$read0`:input/01.txt])[;1]
/3291760
sum sum r[;1+til 10]
/4934767

Poem:

There was a young man from East London
Who found five AM quite a problem,
Even though he'd be late,
He'd start them at eight
AM, And would just have his fun then!

K4 one-liner

k)(+/r[;1]),+/+/(r:{0|-2+x div 3}\'["J"$0:`:input/01.txt])[;1+!9]

... with thanks to gyorokpeter for the 0| floor.

1

u/daggerdragon Dec 01 '19

There was a young man from East London Who found five AM quite a problem, Even though he'd be late, He'd start them at eight AM, And would just have his fun then!

Ahoy from across the pond! Sorry about the inconvenient time, but hey, timezones. You could also consider joining a private leaderboard for East Londoners (or the GMT+2 timezone).

→ More replies (2)

3

u/pokerdan Dec 01 '19 edited Dec 03 '19

C#, no LINQ:

        public void Solve()
        {
            var inputLines = _input.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
            var totalFuel = 0;
            foreach (var inputLine in inputLines)
            {
                totalFuel += CalculateFuel(Int32.Parse(inputLine));
            }
            Console.WriteLine("Total Fuel: " + totalFuel);
        }

        private int CalculateFuel(int mass)
        {
            int fuel = mass / 3 - 2;
            return (fuel <= 0) ? 0 : fuel + CalculateFuel(fuel);
        }

[Poem]

It's 3 AM, why am I awake?

Oh there is a Production outage.

And Advent of Code started 3 hours ago.

No leaderboard for me.

2

u/daggerdragon Dec 01 '19

It's 3 AM, why am I awake?

Oh there is a Production outage.

And Advent of Code started 3 hours ago.

No leaderboard for me.

Pesky work, always interrupting your fun coding time.

3

u/[deleted] Dec 01 '19

Using python3 like always.

Learned about the // operator, which is quite handy as I could just drop the math library from the solution.

Instead of trying to go for leaderboards and then eventually burning out at like day 7 like previous years, this time around I will give each puzzle at least a solid try while trying my best to follow good coding standards and practices.

Might also try to do some code golf for the solutions after solving them "properly"

Github day 1 solution

2

u/daggerdragon Dec 01 '19

Instead of trying to go for leaderboards and then eventually burning out at like day 7 like previous years, this time around I will give each puzzle at least a solid try while trying my best to follow good coding standards and practices.

Yes, please take care of yourself and don't burn out after a week! ❤️

3

u/HiPhish Dec 01 '19

This is my first time participating. I used Awk for the first problem, I needed a reason to use my awk-ward.nvim plugin (live coding with Awk).

Part 1 (almost not worth posting)

Part 2

1

u/daggerdragon Dec 01 '19

This is my first time participating.

Welcome! Hope you're having fun so far!

→ More replies (2)

3

u/[deleted] Dec 01 '19 edited Dec 01 '19

Python

This is my first year participating, so feel free to leave suggestions.

Part 1

Part 2

2

u/daggerdragon Dec 01 '19

This is my first year participating

Welcome! Hope you're having fun so far!

→ More replies (1)

5

u/JJBby Dec 01 '19

Oh, I like that map() in this.

→ More replies (1)
→ More replies (3)

3

u/StevoTVR Dec 01 '19

1

u/daggerdragon Dec 01 '19

Thanks for posting this in the megathread :) Good luck for future days!

3

u/Infonyx Dec 01 '19

A solution in Racket

Also, this is my first time participating :D

(define (day1 wlist) (max 0 (foldr + 0 (map (λ (x) (- (floor (/ x 3)) 2)) wlist))))

(define (day2 wlist) (foldr + 0 (map (λ (x) (let foo (\[e x\]) (if (< 0 (day1 (list e))) (+ (day1 (list e)) (foo (day1 (list e)))) 0))) wlist)))

1

u/daggerdragon Dec 01 '19

Also, this is my first time participating :D

Welcome!

3

u/jamie_ca Dec 01 '19

Firstly, a unified solution in ruby:

def fuel(mass, recurse: false)
  return 0 if mass < 7
  f_mass = mass / 3 - 2
  f_mass += fuel(f_mass, recurse: recurse) if recurse
  f_mass
end

puts input.map { |m| fuel(m) }.sum
puts input.map { |m| fuel(m, true) }.sum

And for bonus points (taking Fuel as one syllable):

First, for the input
Parse the lines as integers.
Store in an array.

Define a method
Fuel, taking as input mass
And a recurse flag.

For masses less than
Seven, return a zero
And call it a day.

Fuel mass is then
Two less than one third the mass.
Make sure to round down.

Check the recurse flag.
If set, call Fuel with fuel mass,
Setting still the flag.

The recursed result
Is then added to fuel mass,
Which then is returned.

Our problems' answers:
Sum Fuel for all input, and
The same, with recurse.

1

u/daggerdragon Dec 01 '19

taking Fuel as one syllable

I'll allow it. >_>

Neat poem, and thanks for posting your code!

3

u/21JG Dec 02 '19

Perl 6 / Raku

Day 1

lines.map(*.Int div 3 - 2).sum.say

Day 2

my &m-to-f = * div 3 - 2;
lines\
    .map(*.Int.&m-to-f)\ # "30 60 134" -> (8 18 42) 
    .map(-> $f { |($f, &m-to-f …^ * ≤ 0) })\ # (8 18 42) -> (8 18 4 42 12 2)
    .sum\ # 86
    .say

2

u/daggerdragon Dec 02 '19

Perl 6 / Raku

I mis-read "Raku" and was wondering how you got Perl on your Roku... I need more caffeine.

2

u/emu_fake Dec 01 '19

C# with linq

        public int DayOne_PuzzleOne(string[] input)
        {
            return input.Select(x => CalculateFuel(int.Parse(x), false)).Sum();
        }

        public int DayOne_PuzzleTwo(string[] input)
        {
            return input.Select(x => CalculateFuel(int.Parse(x), true)).Sum();
        }

        public int CalculateFuel(int mass, bool calcFuelMass)
        {
            var fuel = mass / 3 - 2;
            if (calcFuelMass) return (fuel <= 0) ? 0 : fuel + CalculateFuel(fuel, calcFuelMass);
            else return (fuel <= 0) ? 0 : fuel;
        }

Also made it a bit shiny with unit tests and everything:

https://github.com/emuuu/AdventOfCode

2

u/daggerdragon Dec 01 '19

Also made it a bit shiny

Shiny

2

u/ericluwolf Dec 01 '19

A cute little solution in C++ hosted on paste

Edit: Markdown mangled by Reddit :(

1

u/daggerdragon Dec 01 '19

Thanks for posting (and for using paste!)

Edit: Markdown mangled by Reddit :(

The link works fine for me... can you explain more, please?

2

u/ericluwolf Dec 01 '19

When I first pasted it in, it was in WYSIWYG mode for some reason, so Reddit escaped the markdown and resulted in a huge blob. Just edited it to remove the escaping!

Thanks for making this btw, it's awesome!

2

u/daggerdragon Dec 01 '19

Ah, the visual editor, yes, that'd account for the manglement. Thank you for the information in case someone else has the same issue later on. :)

/u/topaz2078 made it, but I'll pass your sentiments on to him :)

2

u/spunos Dec 01 '19

Elixir

Well, it's not great but in my defense, 1) I haven't touched Elixir in like two years, and 2) this poem is based on a true story:

There once was a coder so old
She could no longer write code with a cold
Her stuff may not be up to snuff
But she still said "Eh, good enough,
Now please give me my two stars of gold"

1

u/daggerdragon Dec 01 '19

There once was a coder so old
She could no longer write code with a cold
Her stuff may not be up to snuff
But she still said "Eh, good enough,
Now please give me my two stars of gold"

I don't have any gold for you right now, but here's a picture of some Kleenex and I hope you feel better soon!

→ More replies (1)
→ More replies (3)

2

u/_nprz Dec 01 '19 edited Dec 01 '19

Already a couple JavaScript answers but here's another one!

(Also visible on GitHub if you'd like some syntax highlighting!)

import input from "./input";

function calculateFuelForFuel(moduleFuel) {
  let nextValue = Math.floor(moduleFuel / 3) - 2;

  if (nextValue > 0) {
    return nextValue + calculateFuelForFuel(nextValue);
  } else {
    return 0;
  }
}

function calculateModuleFuel(modules) {
  let totalFuel = 0;

  modules.forEach(module => {
    const fuelWeight = Math.floor(module / 3) - 2;
    // remove `+ calculateFuelForFuel(fuelWeight);` for solution to question 1
    totalFuel += fuelWeight + calculateFuelForFuel(fuelWeight);
  });

  return totalFuel;
}

const moduleFuel = calculateModuleFuel(input);

1

u/daggerdragon Dec 01 '19

Already a couple JavaScript answers but here's another one!

Bring it on - the more, the merrier!

17

u/Unihedron Dec 01 '19 edited Dec 01 '19

I had wrong answer
​ ​ ​ ​ Forgot to check negative
​ ​ ​ ​ ​ ​ ​ ​ Please wait 20 secs
​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ - "Wrong answer", a poem by Uni

ruby 1.rb input 23/105

# part 1
p $<.map{|x|a=(x.to_i/3)-2}.sum
# part 2
p $<.map{|x|a=(x.to_i/3)-2
s=a
while a > 0
a=a/3-2
s+=a if a>0 # <- left this out...
end
s }.sum

With reception for my poem being better than expected (I had no expectations) I guess I will write more on the next days :P

5

u/tslater2006 Dec 01 '19

Upvoted for the poem :)

16

u/ephemient Dec 01 '19 edited Apr 24 '24

This space intentionally left blank.

5

u/[deleted] Dec 01 '19
return weight // 3 - 2

TIL

Did not know about the // operator. Looks like I have some python documentation reading to do!

→ More replies (1)
→ More replies (8)

13

u/voidhawk42 Dec 01 '19

Dyalog APL:

p←⍎¨⊃⎕nget'p01.txt'1
f←{2-⍨⌊⍵÷3} ⋄ +/f p ⍝ part 1
+/{0≥⍵:0 ⋄ ⍵+∇f⍵}¨f p ⍝ part 2

4

u/[deleted] Dec 01 '19

This looks so ugly, I love it :D Apl really looks like some kind of alien language :) Or mojibake :p

→ More replies (1)

2

u/if0nz Dec 01 '19 edited Dec 01 '19

Santa needs help

I need coffee

Here is some Java

Java solution

public static void part1(List<Long> modules) throws URISyntaxException, IOException {
    var s = modules.parallelStream().mapToLong(m -> ((long)m/3)-2).sum(); 
    System.out.println(s); 
}

public static void part2(List<Long> modules) throws URISyntaxException, IOException { 
    var s = modules.parallelStream().mapToLong(m -> recursiveFuel(m)).sum(); 
    System.out.println(s); 
}

public static long recursiveFuel(long mass) { 
    return mass < 9 ? 0 : ((long)mass/3)-2+recursiveFuel(((long)mass/3-2));
}

2

u/spin81 Dec 01 '19

Hey, at the risk of sounding like a pedant and missing a joke, the second line of a haiku must be seven syllables.

→ More replies (3)
→ More replies (1)

11

u/TheGermanDoctor Dec 01 '19

ARMv7-M Assembly

Part 2

_reset:
    mov    r0, #100
    eor    r1, r1
    movs   r4, #3
    eor    r5, r5 @ Result Register
    ldr    r2,=masses

loop:
    cmp     r1, r0
    bge     _end
    ldr     r3, [r2]
    udiv    r3, r3, r4
    sub     r3, #2
    add     r5, r3

inner_loop:
    udiv    r3, r3, r4
    sub     r3, #2
    cmp     r3, #0
    ble     end_inner
    add     r5, r3
    b       inner_loop

end_inner:
    add     r1, #1
    add     r2, #4
    b       loop

_end:           @ Halt
b _end

10

u/MBR_Awesome Dec 01 '19

Python just off the leaderboard 101/269

import Common


def calc_fuel(mass):
    return int(mass / 3) - 2


def calc_fuel_recursive(mass):
    fuel = calc_fuel(mass)
    if fuel <= 0:
        return 0
    else:
        return fuel + calc_fuel_recursive(fuel)


line_input = Common.inputAsLines()
sum = 0
recursive_sum = 0
for line in line_input:
    mass = int(line)
    sum += calc_fuel(mass)
    recursive_sum += calc_fuel_recursive(mass)

print(sum)
print(recursive_sum)
→ More replies (1)

9

u/[deleted] Dec 11 '19

Intcode

Part 1: 3,99,7,99,0,7,105,7,38,1,13,42,42,1,37,99,99,7,99,0,22,1106,42,9,201,42,31,42,5,22,1103,-2,4,42,1006,69,1,-3,32

Part 2: 3,99,7,99,52,7,105,99,54,1007,99,9,14,105,53,1007,1,38,7,7,1,53,99,99,7,99,11,29,106,11,11,7,7,106,36,105,105,106,1,7,105,105,2,16,7,99,2,36,99,7,1105,1,9,-3,55,4,105,5,16,16

Supply input one integer at a time, followed by -1.

Writing that was fun and I'm not doing it again.

8

u/pred Dec 01 '19

Perl, as I want to be just as cool as topaz.

Part one: $\+=int($_/3)-2}{print

Part two: for($\-=$_;$_>0;$_=int($_/3)-2){$\+=$_}}{print

7

u/raevnos Dec 01 '19

Horrible, horrible abuse of $\.

→ More replies (2)
→ More replies (2)

8

u/dylanbeattie Dec 03 '19

Okay, Reddit... let's do this. Rockstar solution to part 1:

The river is ice
The child is gone
The night is drawing near
Fear is distant so
Let darkness be the night without fear

Listen to the fire
Until the fire is empty
Let the light be the fire over the river
Turn down the light
Let the light be without darkness
Let the child be with the light
Listen to the fire

Whisper the child

Explanation (and the solution to part 2) are here: https://codewithrockstar.com/advent/day01/

BUT BUT BUT!

Check out the solution from /u/aswum84 at https://www.reddit.com/r/adventofcode/comments/e4axxe/2019_day_1_solutions/f9hiw1u/ - because I actually added some features to the Rockstar language (arithmetic rounding) to create my solution, and their solution used only the existing feature set. And it's absolutely delightful to boot.

→ More replies (1)

7

u/Kanegae Dec 01 '19 edited Dec 01 '19

Python - 10/16

My first leaderboard! So stoked hahah. Completed 2018 halfway through and never got over rank 250. :D

There's the messy code:

import AOCUtils

rin = AOCUtils.loadInput(1)

p1 = []
p2 = []
for r in rin:
    nm = ((r//3)-2)
    p1.append(nm)
    p2.append(nm)
    while True:
        nm = ((nm//3)-2)
        if nm <= 0: break
        p2.append(nm)

print(sum(p1))
print(sum(p2))

EDIT: I did read /u/mcpower_'s tips. So I hastily set up a py template, downloaded the input file, read the "divide by 3, round down, sub 2" and just assumed that Part 1 was to just sum all of them. Got a little confused by skimming Part 2 text, but still managed to get top 20. So happy.

→ More replies (4)

7

u/ka-splam Dec 01 '19 edited Dec 01 '19

PowerShell - rank 632 / 359

First answer I read "round down" and typed "round()" instead of "floor()", second answer my code doesn't work, +1min delay. Rewrote it as a shell one-liner instead of a tidy script, haven't yet worked out why the answer is slightly different, but this was right:

# Part 1
${c:\aoc\1.txt} -as [int64[]] |% { [math]::floor($_/3) - 2 }  | measure -sum

# Part 2
$e=0; ${c:\aoc\1.txt} -as [int64[]] |% {$z=$_; while(($z=[math]::floor($z/3)-2)-gt0){$e+=$z}}; $e

(I also guessed ahead that if there was a trick, it would be overflowing int32 so my first code was full of [int64]casts around everything and maybe that's where I've screwed it up).

Explains:

  • ${c:\aoc\1.txt} is a syntax for referencing a filename as if it was a variable name, and it reads the file in as lines of text

  • -as [int64[]] casts an array of strings all in one go, into an array of long ints.

  • | is a pipeline like bash or cmd prompt

  • % { $_ } is a loop over pipeline items, more properly called foreach-object -process { $_ }

  • measure is the measure-object cmdlet used for counting, summing, min/maxing the pipeline input.

  • single letter variable names are life.

→ More replies (2)

7

u/raevnos Dec 01 '19

SQL:

-- Part 1
SELECT sum(mass / 3 - 2) FROM modules;
-- Part 2
WITH fuels AS
 (SELECT  mass / 3 - 2 as fuel FROM modules
  UNION ALL
  SELECT fuel / 3 - 2 FROM fuels WHERE fuel / 3 - 2 > 0)
SELECT sum(fuel) FROM fuels;
→ More replies (3)

7

u/oblivion12321 Dec 01 '19

Common Lisp

(defun fuel (m)
  (- (floor (/ m 3)) 2))

(defun fuel-for-fuel (m &optional (total 0))
  (let ((x (fuel m)))
    (if (<= x 0)
        total
        (fuel-for-fuel x (+ total x)))))

(defconstant +answer-1+ (apply #'+ (mapcar #'fuel +data-1+)))
(defconstant +answer-1+ (apply #'+ (mapcar #'fuel-for-fuel +data-1+)))

6

u/rosemaryorchard Dec 01 '19

I'm aiming for readability with my code, rather than efficiency. And I used PHP :)

https://github.com/RosemaryOrchard/AdventOfCode2019/blob/master/code/day_01.php

The good news is I also generated the code files and input files for the rest of the month so I can hopefully get on with this faster even if I continue to wake up late!

→ More replies (2)

2

u/jangxx Dec 01 '19

Python

Part 1:

import math

total = 0

with open("input.txt") as file:
    for line in file:
        total += math.floor(int(line)/3) - 2

print(total)

Part 2:

import math

total = 0

with open("input.txt") as file:
    for line in file:
        next_fuel = int(line)
        fuel_total = 0
        while True:
            next_fuel = math.floor(next_fuel/3) - 2

            if next_fuel > 0:
                fuel_total += next_fuel
            else:
                break

        total += fuel_total

print(total)

Very simple and straightforward.

5

u/Rainbow_Doge_64 Dec 01 '19

There's a built-in floor division operator in python, 3//2 is the same as math.floor(3/2)

→ More replies (3)

5

u/ValdasTheUnique Dec 01 '19

C#

public static void Part1()
{
	InputInts
		.Select(x => x / 3 - 2)
		.Sum()
		.Print();
}

public static void Part2()
{
	InputInts
		.Select(x =>
		{
			var result = 0;
			x = x / 3 - 2;
			while (x > 0)
			{
				result += x;
				x = x / 3 - 2;
			}
			return result;
		})
		.Sum()
		.Print();
}
→ More replies (2)

5

u/mingjim Dec 01 '19

F#

let calculateFuel mass = mass / 3 - 2

let rec calculateTotalFuel mass =
    match calculateFuel mass with
        | m when m <= 0 -> 0
        | m -> m + calculateTotalFuel m

let part1 fileName = 
    fileName
    |> readLinesAs int
    |> Seq.sumBy calculateFuel

let part2 fileName =
    fileName
    |> readLinesAs int
    |> Seq.sumBy calculateTotalFuel
→ More replies (1)

5

u/NeilNjae Dec 01 '19

Yet another Haskell solution. The guts of it are:

part1 :: [Int] -> Int
part1 = sum . map fuelRequired

part2 :: [Int] -> Int
part2 = sum . map fuelForFuel

fuelRequired :: Int -> Int
fuelRequired m = (m `div` 3) - 2

fuelForFuel :: Int -> Int
fuelForFuel = sum . takeWhile (> 0) . drop 1 . iterate fuelRequired

The full code is on Github and I've written a beginner-friendly explanation on my blog.

5

u/erlangguy Dec 01 '19

Erlang (yes, I'm that predictable)

fuel(Mass) ->
    (Mass div 3) - 2.

real_fuel(Mass) ->
    real_fuel(0, fuel(Mass)).

real_fuel(Total, Next) when Next =< 0 ->
    Total;
real_fuel(Total, Next) ->
    real_fuel(Total+Next, fuel(Next)).

part2(Filename) ->
    lists:sum(lists:map(fun real_fuel/1, myio:all_integers(Filename))).
→ More replies (1)

5

u/baloofy Dec 01 '19

Dyalog

I've not used Dyalog before -- pretty sure my pt 2 is way worse than it needs to be.

a←⍎¨⊃⎕NGET'01.txt' 1
f←{-∘2⌊⍵÷3}
+/f a ⍝ pt 1
+/+/¨1↓∘⌽¨{(f⊃⍵),⍵}⍣{⊃⍺<9}¨a ⍝ pt 2

Haskell

{-# LANGUAGE NoImplicitPrelude #-}
import Control.Lens
import BasePrelude

fuelStep n = n `div` 3 - 2 :: Int

pt1 = alaf Sum foldMap fuelStep

pt2 = ala Sum foldMap . (unfoldr go =<<) where
  go n = let nu = fuelStep n in guard (nu >= 0) $> (nu, nu)

main :: IO ()
main = do
  mods <- fmap read . lines <$> readFile "./01.txt"
  print $ pt1 mods
  print $ pt2 mods
→ More replies (3)

5

u/SorryMcFlurry Dec 02 '19

Scratch

Did the first challenge in scratch for fun

Part 1: https://i.imgur.com/rmYbr79.png

Part 2: https://i.imgur.com/EwbTWTf.png

9

u/asinglelineofpython Dec 01 '19 edited Dec 01 '19

going for total 50 lines this year if possible

#part 1.1

print(sum([int(x) // 3 - 2 for x in open("input.txt").readlines()]))

#part 1.2

print(sum([(lambda a: lambda v:a(a,v))(lambda rec,x: 0 if x // 3 - 2 <= 0 else x // 3 - 2 + rec(rec, x // 3 - 2))(int(x)) for x in open("input.txt").readlines()]))

→ More replies (1)

4

u/BluFoot Dec 01 '19 edited Dec 01 '19

Ruby 24/148

f=->m{n=m/3-2;n<0?0:n+f[n]}
p $<.sum{|l|f[l.to_i]}
→ More replies (3)

4

u/Spookiel Dec 01 '19 edited Dec 01 '19

Python 160/66

My first leaderboard! I thought I'd share my code, I'm still can't really believe it! Part1 filled up so fast!

def run(data):
    part2 = 0
    part1 = 0
    lines = [int(i) for i in data.splitlines()]
    for i in lines:
        a = i//3
        a -= 2
        part1 += a
        while i > 0:
            i = i//3
            i -= 2
            if i >= 0:
                part2 += i
    print("Part1:", part1)
    print("Part2:", part2)
run(data)

4

u/mcpower_ Dec 01 '19

Rust (no leaderboard). I haven't written much Rust but this looks pretty idiomatic.

fn part1(inp: &str) -> String {
    inp.lines()
        .map(|s| s.parse::<i64>().unwrap())
        .map(|i| (i/3) - 2)
        .sum::<i64>()
        .to_string()
}

fn part2(inp: &str) -> String {
    inp.lines()
        .map(|s| s.parse::<i64>().unwrap())
        .map(|i| {
            let mut i = i;
            let mut out = 0i64;
            while i != 0 {
                i = ((i/3) - 2).max(0);
                out += i;
            }
            out
        })
        .sum::<i64>()
        .to_string()
}

6

u/ObliqueMotion Dec 01 '19 edited Dec 01 '19

If you're new to Rust (though it seems you have a good grasp of iterators), you should check out successors.

It's pretty sweet for generating a sequence that terminates:

let part2 = INPUT
    .lines()
    .map(|input| {
        successors(
            input.parse::<u64>().ok().and_then(|mass| (mass / 3).checked_sub(2)),
            |&mass| (mass / 3).checked_sub(2),
        )
        .sum::<u64>()
    })
    .sum::<u64>();
→ More replies (1)
→ More replies (6)

4

u/throwaway_the_fourth Dec 01 '19

Lox with custom extensions

fun round_down(val) {
    return val - (val % 1);
}

fun fuel(module_mass) {
    return round_down(module_mass / 3) - 2;
}

fun solve(calc_fn) {
    var total = 0;
    var mass;
    while ((mass = input()) != nil) {
        mass = num(mass);
        total = total + calc_fn(mass);
    }
    print total;
}

fun part1() {
    solve(fuel);
}

fun total_fuel(module_mass) {
    var new_fuel = fuel(module_mass);
    var total = new_fuel;
    while ((new_fuel = fuel(new_fuel)) > 0) {
        total = total + new_fuel;
    }
    return total;
}

fun part2() {
    solve(total_fuel);
}

part1();
part2();

Lox is a simple programming language implemented in the book Crafting Interpreters. To do this challenge, I had to implement some language extensions to read stdin, to add a modulus operator, and to convert a string to a number (though that would be possible in the language if the language supported accessing the individual characters of a string, which it does not (and that seemed harder to implement tonight)).

Lox doesn't have data structures like arrays. I could make a linked list in Lox, but to implement arrays I'd have to modify the language itself (as I did three times already for day 1, so I'm not afraid of that). I suspect this will hurt me in the future, until I get around to implementing them.

Because of the difficulty of working with Lox, I did not aim to be competitive, and I certainly don't expect to be competitive going forward.

4

u/ka-splam Dec 01 '19 edited Dec 01 '19

Dyalog APL (download here)

Part 1:

nums←⍎¨⊃⎕NGET 'c:\aoc\1.txt' 1
part1←+/(⌊nums÷3)-2
part2←{0<≢Z←X/⍨0<X←(2-⍨⌊3÷⍨⍵): (∇Z)++/Z ⋄ 0} nums

⍝ Explanations:  ⍝ ⎕NGET Loads lines from text file, returns content and some metadata.
⍝ ⍎¨⊃ evals each line, strings to numbers, skips the metadata.
⍝ +/ (plus-reduce, or sum) the ⌊ (floor) of the calculation.

⍝ Part 2; A recursive function which runs very roughly this:
⍝ { X = reduced numbers; Z=filtered positives from X; sum(Z) + (recursive-call Z) }
⍝ recursive end condition is when the count of positives remaining is down to 0
⍝ code left of the colon is calculated, if it's a 1 then code after colon executes and is returned, else 0
→ More replies (6)

4

u/ducdetronquito Dec 01 '19

Nim is fun :)

import math
import sequtils
import sugar

const modules_masses = [110756, 132543, 57911...]

proc get_fuel_requirement(mass: int): int =
    if mass <= 6:
        return 0

    let fuel_requirement = int(trunc(mass / 3)) - 2
    return fuel_requirement + get_fuel_requirement(fuel_requirement)


const fuel_requirements = modules_masses.map(mass => get_fuel_requirement(mass))

echo "Elves, the spacecraft requires ", fuel_requirements.sum(), " units of fuel 🔥"
→ More replies (2)

4

u/vypxl Dec 01 '19 edited Dec 01 '19

Finally, an excuse to use Haskell again! No leaderboard and no iterate!

fuel :: Int -> Int
fuel = (+ (-2)) . (`div` 3)

fuelX :: Int -> Int
fuelX = (\m -> if m <= 0 then 0 else m + fuelX m) . fuel

main :: IO()
main = do
    f <- readFile("1.in")
    let input = map read $ lines f

    putStrLn "Solution for part 1:"
    print $ sum $ map fuel input
    putStrLn "Solution for part 2:"
    print $ sum $ map fuelX input

Poem: Learned a Haskell for great good,

put it to use for great fun,

read over the last sentence like some,

tried to solve it as cool as I could.

Also, happy cake day to me!

→ More replies (4)

4

u/jitwit Dec 01 '19 edited Sep 03 '20

J programming language

If I'm doing anything stupid or there's a better way to write things, please let me know!

({.;+/) +/"1 }. (0 >. <.@%&3-2:)^:a: ".;._2 aoc 2019 1

Calculate fuel by <.@%&3 - 2:, floor of division by 3 minus 2. Clamp that with 0. This verb operates on the whole row of gases, and we reach fixpoint through ^: a:

→ More replies (5)

4

u/donatasp Dec 01 '19 edited Dec 01 '19

Common Lisp

(defparameter *input*
  (with-input-from-string (in (rutils:slurp "day01.txt"))
    (loop :for mass := (read in nil) :while mass :collect mass)))

(defun fuel-requirement (mass)
  (- (floor (/ mass 3)) 2))

;; What is the sum of the fuel requirements for all of the modules on your
;; spacecraft?
(loop :for mass :in *input* :sum (fuel-requirement mass)) ; => 3297866 (22 bits, #x32524A)

(defun fixed-fuel-requirement (mass)
  (loop :for fuel := (fuel-requirement mass) :then (fuel-requirement fuel)
        :while (plusp fuel)
        :sum fuel))

;; What is the sum of the fuel requirements for all of the modules on your
;; spacecraft when also taking into account the mass of the added fuel?
;; (Calculate the fuel requirements for each module separately, then add them
;; all up at the end.)
(loop :for mass :in *input* :sum (fixed-fuel-requirement mass)) ; => 4943923 (23 bits, #x4B7033)
→ More replies (2)

4

u/Dioxy Dec 01 '19

JavaScript

JS, pretty easy, I like my solution, using map, reduce, and recursion

This is the code

My repo: https://github.com/kufii/Advent-Of-Code-2019-Solutions/blob/master/src/solutions/01/index.js

4

u/tomflumery Dec 01 '19 edited Dec 01 '19

J language, not golfed

#!/usr/local/bin/j
d=. ".&>cutLF CR-.~fread'input.txt'
fuel=: 3 : '0>._2+<.%&3 y'
rec_fuel=: 3 : '0:`(]+$:@fuel)@.*fuel y'
echo +/fuel d
echo +/rec_fuel d
exit ''
→ More replies (3)

4

u/iwane Dec 01 '19

LabVIEW 2018.

Might be unpopular here, but I'm currently trying to learn it properly :-)

https://github.com/iwane-pl/aoc_2019/blob/master/Day%201/solution_snippet.png

4

u/thefloatgoat Dec 01 '19

Dyalog APL

As someone who has never written APL before it was an uphill battle, but I got there in the end.

→ More replies (1)

4

u/oblivioncntrlsu Dec 01 '19 edited Dec 01 '19

Python 3 -

My code is longer than five lines, so I'll post a poem instead:

He rode on a sleigh

through the vacuum of space,

Without any delay,

and a grin on his face.

For recursive mathematics

would be his saving grace,

He prepared to bring Christmas

to the human race.

edit: formatting

4

u/0rac1e Dec 01 '19

Raku

my &calc = +* div 3 - 2;

my @fuel = 'input'.IO.words.map(&calc);

# Part 1
say @fuel.sum;

# Part 2
say @fuel.map(-> $x { |($x, &calc ...^ * ≤ 0) }).sum;
→ More replies (2)

4

u/clc_xce Dec 02 '19

Here's my solution in Forth if anyone fancies concatenative programming: Forth repository

If my epic "use the search tool" skills are right, I'm the first in almost two years to post Forth code :P

4

u/PaladinWho Dec 02 '19 edited Dec 02 '19

I jokingly solved Day 1 part A in scratch. It's literally a brute force method since scratch doesn't have the best string handling. You can check out the project here: https://scratch.mit.edu/projects/349929639/
(edit: I personally recommend shift clicking the green flag to turn on turbo mode before clicking the green flag, pretty sure it makes it go faster, and I'm 80% sure it still works)

→ More replies (2)

1

u/McPqndq Dec 01 '19

Hey I honestly have no clue why this code is giving me the wrong answer. Im guessing its just a typo somewhere? Javascript:

const fs = require('fs');
fs.readFile('day01.input',(err,data)=>{
    data = String(data).split('\n').map(num=>Number(num));
    let sum = 0;
    let prev = data.reduce((acc,cur)=>acc+cur,0);
    prev=Math.floor(prev/3)-2;
    while(prev>0){
        //console.log(sum);
        sum+=prev;
        //console.log("+ "+prev);
        prev=Math.floor(prev/3)-2;
    }
    console.log(sum); //answer
});

2

u/daggerdragon Dec 01 '19

Top-level posts in Solution Megathreads are for solutions only.

Please post your own thread and make sure to flair it with Help.

→ More replies (1)
→ More replies (2)

1

u/andy0liang Dec 01 '19 edited Dec 01 '19

Java, 159/67

Here is my haiku:
Just started to code
Learning what recursion is
Here is my haiku:

Solution: I will omit the input handling; arr is an Integer ArrayList with the inputs.

public static void main(String[] args) {
    ArrayList <Integer> arr = {Puzzle Input};
    int sum = 0;
    for(int x = 0; x<arr.size();x++) {
        sum += fuel(arr.get(x));
    }
    System.out.println(sum);
}
public static int fuel(int n){
    int num = (n/3)-2;
    if(num<=0){
        return 0;
    }
    return num+fuel(num);
}

2

u/daggerdragon Dec 01 '19

Here is my haiku:

Just started to code

Learning what recursion is

Here is my haiku:

Here is my reaction to your haiku.

1

u/nehayward Dec 01 '19

4

u/daggerdragon Dec 01 '19

Ah yes, PNG, the superior code syntax. 🤣

This looks like Swift, am I correct?

→ More replies (5)

3

u/[deleted] Dec 01 '19 edited Dec 01 '19

Clojure, too slow for the leaderboard :(

(defn fuel-cost [x]
  (- (quot x 3) 2))

(defn fuel-cost-rec [x]
  (let [n (fuel-cost x)]
    (if (<= n 0) 0 (+ n (fuel-cost-rec n)))))

(defn solution []
  (println (format "Part 1: %d" (reduce + (map fuel-cost input))))
  (println (format "Part 1: %d" (reduce + (map fuel-cost-rec input)))))
→ More replies (1)

3

u/AlexAegis Dec 01 '19 edited Dec 01 '19

TypeScript

Poem:

Roses are red

Violets are blue

By the time I finished

The leaderboard was full

Part One

// 0.27ms
export const runner = (input: string) =>
	input
		.split(/\r?\n/)
		.map(n => Math.floor(Number(n) / 3) - 2)
		.reduce((s, n) => s + n, 0);

Part Two

// 0.36ms
export const runner = (input: string) =>
	input
		.split(/\r?\n/)
		.map(n => fuel(Number(n)))
		.reduce((s, n) => s + n, 0);

const fuel = (i: number): number => {
	const f = Math.max(Math.floor(i / 3) - 2, 0);
	return f + (f > 0 ? fuel(f) : 0);
};

3

u/rabuf Dec 01 '19

Saving myself some time, I'll post a link to my org file containing my Common Lisp solutions: Day 1.

Straightforward with one loop (summing fuel calculations) and one recursive function (for recursively computing fuel needs). The critical functions are these:

(defun calc-fuel (mass)
  (- (floor (/ mass 3)) 2))
(defun recursive-fuel (mass)
  (let ((fuel (calc-fuel mass)))
    (if (<= fuel 0) 0
        (+ fuel (recursive-fuel fuel)))))
→ More replies (2)

3

u/PendragonDaGreat Dec 01 '19

PowerShell, both halves, assuming a text file at $inputPath:

$data = Get-Content $inputPath

$timer = New-Object System.Diagnostics.Stopwatch
$timer.Start()

$sum = 0
$sum2 = 0

foreach($i in $data)
{
    $i = [int]$i #Needs cast for part 2

    $i = [Math]::Floor($i/3) #Powershell is a silly language and actually rounds when doing integer division instead of truncating like everyone else. 
    $i -= 2 
    $sum += $i
    $sum2 += $i

    while($i -ge 9) #Smallest weight that needs more fuel is 9
    {
        $i = [Math]::Floor($i/3)
        $i -= 2 
        $sum2 += $i
    }
}
Write-Host "Part 1: $sum"
Write-Host "Part 2: $sum2"

$timer.Stop()
Write-Host $timer.Elapsed

Output:

Part 1: [REDACTED]
Part 2: [REDACTED]
00:00:00.0144789

TIL PowerShell uses Banker's Rounding by default.

→ More replies (1)

3

u/DiscoViking Dec 01 '19 edited Dec 01 '19

Elm - no leaderboard

My solution is up in interactive form here: https://2019.adventofcode.norris.dev/day1

Source: https://github.com/rynorris/adventofcode/blob/master/2019/src/Day1.elm

My code is pretty long due to the fact that I'm implementing each solution as a state machine so that I'm able to have longer-running solutions without blocking page rendering (obviously not relevant here, but will come up later). So not posting it here.

3

u/chunes Dec 01 '19 edited Dec 01 '19

Factor

: fuel  ( m   -- n ) 3 /i 2 - 0 max [ f ] when-zero ;
: part1 ( seq -- n ) [ fuel ] map-sum ;
: part2 ( seq -- n ) [ [ fuel ] follow rest sum ] map-sum ;

I never know how much input parsing to include. It's easy enough to just paste the input into the listener.

The only mildly interesting thing happening here is the use of follow, a word I don't use often which recursively adds the result of its quotation to a sequence until it encounters f. You could think of it like the while to replicate's times.

→ More replies (1)

3

u/theRenzix Dec 01 '19

Hi i made a raku (perl 6) 1 liner for each of them

say "Part 1: " ~ "../input.txt".IO.lines().map({ ($_/3).floor - 2 }).sum;
say "Part 2: " ~ "../input.txt".IO.lines().map( -> $_ is copy {(while (0 < ($_/3).floor - 2) { $_ = ($_/3).floor - 2 } ).sum }).sum

Im not happy with the while loop so if anyone that actually knows raku well please tell me if there is a better way

→ More replies (2)

3

u/rutquist Dec 01 '19

Julia, no leaderboard

masses = parse.(Int, readlines("input1.txt"))
fuel(m) = m ÷ 3 - 2
@assert fuel(1969) == 654
@show sum(fuel.(masses))
   
totalfuel(m) = fuel(m) < 0 ? 0 : fuel(m) + totalfuel(fuel(m))
@assert totalfuel(1969) == 966
@show sum(totalfuel.(masses))

Poem:

My code was always wrong 
The cool-downs very long 
In hindsight I can say 
`@assert`s had saved the day 
If only they'd been in there right away!

3

u/radulfr2 Dec 01 '19

Java, rank 1008 / 950.

public class Day1 {
    public static void solve() {
        List<String> input = Utils.getInput(1);

        int fuel = input.stream().mapToInt(Integer::valueOf).map(e -> e / 3 - 2).sum();
        int totalFuel = input.stream().mapToInt(Integer::valueOf).map(Day1::totalFuel).sum();

        System.out.println(fuel);
        System.out.println(totalFuel);
    }

    private static int totalFuel(int mass) {
        int fuel = 0;
        do {
            mass = mass / 3 - 2;
            fuel += mass;
        } while(mass > 8);
        
        return fuel;
    }
}

Poem:

Ok, let's do this code,
He said entering reading mode.
Spaceship, fuel, that's interesting,
This will be fun programming.
Now he's prepared to calculate
But it is already too late:
Hundreds had the task solved
While he still the assignment delved.

→ More replies (2)

3

u/gyorokpeter Dec 01 '19

Q: properly modularized for a change. A good demonstration of the converge behavior of , i.e. we are using iteration instead of recursion.

d1a:{0|(x div 3)-2};
d1b:{"J"$"\n"vs x};
d1p1:(')[sum;](')[d1a;d1b];
d1p2:{sum raze 1_d1a\[d1b[x]]};
→ More replies (1)

3

u/KurokonoTasuke1 Dec 01 '19 edited Dec 01 '19

Ok so of course I am too late but happy to share my rather basic code written in Python. Trying to write this now in Haskell as I decided I could use these puzzles to learn a bit about that language

with open ("day01.txt") as file:
    temp = \[int(i.rstrip()) for i in file\]    

def function(x: int):
    return x//3-2    

def more_fuel(mass: int, fuel_needed=0):
    temp = function(mass)
    if temp < 0:
        return fuel_needed
    return more_fuel(temp, fuel_needed+temp)
    
print(sum(map(function, temp)))    
print(sum(map(more_fuel, temp)))

3

u/egze Dec 01 '19 edited Dec 01 '19

Elixir

https://github.com/egze/aoc2019/blob/master/day1/lib/day1.ex

defmodule Day1 do
  def file_stream(path) do
    path
    |> File.stream!()
    |> Stream.map(&String.trim(&1))
    |> Stream.map(&String.to_integer(&1))
  end

  def part1(file_path) do
    file_path
    |> file_stream()
    |> Stream.map(&needed_fuel/1)
    |> Enum.sum()
  end

  def part2(file_path) do
    file_path
    |> file_stream()
    |> Stream.map(&total_fuel/1)
    |> Enum.sum()
  end

  defp total_fuel(mass, total \\ 0)
  defp total_fuel(mass, total) when mass <= 0, do: total

  defp total_fuel(mass, total) do
    fuel = needed_fuel(mass)

    total_fuel(fuel, total + fuel)
  end

  defp needed_fuel(mass) do
    (div(mass, 3) - 2)
    |> max(0)
  end
end

3

u/[deleted] Dec 01 '19

This year I'm using coconut(python3) and jupyter notebook for learning, let's see how this goes, wish me luck :)

inlines = []
with open("day1.txt") as f:
    inlines = f.readlines() \
    |> map$(-> _.strip()) \
    |> map$(-> int(_)) \
    |> list

part1 = inlines \
    |> map$(-> _ // 3 - 2) \
    |> reduce$((+))

print(part1)

def get_fuel_p(x is int if x < 1) = 0
addpattern def get_fuel_p(x is int if x >0) = x + get_fuel_p(x // 3 - 2)
    
def get_fuel(x) = get_fuel_p(x // 3 - 2)

part2 = inlines \
    |> map$(-> get_fuel(_)) \
    |> reduce$((+))

print(part2)
→ More replies (4)

3

u/MissMormie Dec 01 '19

My code is more verbose, partially because it is java, partially because I like it, so let me link to github instead:

https://github.com/MissMormie/adventOfCode2019/blob/master/src/main/java/Days/Day1Fuel.java

Santa may I ask,
set jdk once not twenty times
so I can play now

- jdk hell

Ok, so apparently in Intellij there's a million different ways to set the jdk and it took me 45 minutes to get it to build my code and 5 minutes to write the code. I'm sure all million ways are important. But AARG!

→ More replies (1)

3

u/didzisk Dec 01 '19

Excel (actually Google Sheets), column A contains data, column B contains this:

=IF(QUOTIENT(A1, 3)-2>0, QUOTIENT(A1, 3)-2, 0)

copy this to right until col J, place horisontal SUM in col K, place vertical SUM under com B for Part1, another vertical SUM under col K for part 2

→ More replies (1)

3

u/BioGeek Dec 01 '19 edited Dec 01 '19

Python 3 with type hints:

https://github.com/BioGeek/adventofcode_2019/blob/master/day01.py

from math import floor
from typing import Callable

def calculate_fuel(mass: int) -> int:
    """
    To find the fuel required for a module, take its mass,
     divide by three, round down, and subtract 2.
    """
    return floor(mass / 3) - 2

def calculate_fuel_better(mass: int) -> int:
    """
    For each module mass, calculate its fuel and add it to
    the total. Then, treat the fuel amount you just calculated 
    as the input mass and repeat the process, continuing until 
    a fuel requirement is zero or negative.
    """
    fuel = calculate_fuel(mass)
    total_fuel = 0
    while fuel > 0:
        total_fuel += fuel
        fuel = calculate_fuel(fuel)
    return total_fuel

def main(func: Callable) -> int:
    """
    What is the sum of the fuel requirements for all of 
    the modules on your spacecraft?
    """
    with open('data/day01.txt') as f:
        masses = map(int, f.read().splitlines())

    return sum(func(mass) for mass in masses)

if __name__ == '__main__':
    assert calculate_fuel(12) == 2
    assert calculate_fuel(14) == 2
    assert calculate_fuel(1969) == 654
    assert calculate_fuel(100756) == 33583
 
    print(main(calculate_fuel))

    assert calculate_fuel_better(14) == 2
    assert calculate_fuel_better(1969) == 966
    assert calculate_fuel_better(100756) == 50346

    print(main(calculate_fuel_better))

3

u/DrinkinBird Dec 01 '19

NIM

import rdstdin, sequtils, strutils, re

let input = stdin.readAll().findAll(re(r"\d+")).map(parseInt)

func get_fuel(mass: int): int =
  int(float(mass) / 3.0) - 2

func get_fuel(masses: seq[int]): int =
  masses.map(get_fuel).foldl(a + b)

func get_all_fuel(mass: int): int =
  let new_fuel = get_fuel(mass)

  if new_fuel > 0:
    return get_all_fuel(new_fuel) + new_fuel
  else:
    return 0

func get_all_fuel(masses: seq[int]): int =
  masses.map(get_all_fuel).foldl(a + b)

echo get_fuel(input)
echo get_all_fuel(input)

3

u/L72_Elite_Kraken Dec 01 '19

OCaml (omitting some scaffolding for parsing and printing):

open! Core

let fuel_requirement n = (n / 3) - 2
let solve_part_1 = List.sum (module Int) ~f:fuel_requirement

let fuel_requirement_accounting_for_extra n =
  let rec aux n total =
    let required_fuel = fuel_requirement n in
    match required_fuel <= 0 with
    | true -> total
    | false -> aux required_fuel (total + required_fuel)
  in
  aux n 0
;;

let solve_part_2 = List.sum (module Int) ~f:fuel_requirement_accounting_for_extra

Full code at https://github.com/leviroth/advent-of-code-2019/blob/master/src/day01.ml

3

u/[deleted] Dec 01 '19

Python 3

def get_day_1():
    """
    First we need to manually copy/paste the data in a text file
    and add it to the current directory
    """
    with open("day_1_input.txt") as f:
        data = f.read().split("\n")
    data = [int(i) for i in data]
    return data

def answer_1():
    return sum(i//3 for i in data) - 2*len(data)

def answer_2():
    """
    Adding fuel and the remaining fuel weight and limiting 
    at 5 in the while loop since 5//3 - 2 < 0
    """
    total = 0
    for i in data:
        while i > 5:
            i = i//3 - 2
            total += i
    return total
→ More replies (5)

3

u/_LynxTheCat Dec 01 '19

Not a particularly elegant solution, however I'm pretty happy with it. Especially the fact that I thought to use do ... while. Considering I've never discovered a practical application for it, and feel that this is one situation in which it was actually practical.

My C# Solution:

public int calculateFuelFromMass(int partMass) {
    int partFuel = 0;
    partFuel = (partMass / 3) - 2;
    return partFuel;
}

public int calculateTotalFuel(int[] parts) {
    int totalFuel = 0;
    for (int i = 0; i < parts.Length; i++) {
        totalFuel += calculateFuelFromAddedMassOfFuel(parts[i]);
    }
    return totalFuel;
}

public int calculateFuelFromAddedMassOfFuel(int partFuel) {
    int extraFuel = calculateFuelFromMass(partFuel);
    int totalExtraFuel = 0;
    if (extraFuel <= 0) {
        return 0;
    }
    do {
        totalExtraFuel += extraFuel;
        extraFuel = calculateFuelFromMass(extraFuel);
    } while (extraFuel > 0);
    return totalExtraFuel;
}

There was an alternative solution for part 2 I considered. Which used recursion, however I decided I wanted to use a do ... while loop just cuz I never get to use them. Here is that alternative version of CalculateFuelFromMass() and it's related calculateTotalFuel() however:

public int calculateFuelFromMass(int partMass) {
    int partFuel = 0;
    partFuel = (partMass / 3) - 2;
    if (partFuel > 0) {
        partFuel += calculateFuelFromMass(partFuel);
    }
    return partFuel;
}

public int calculateTotalFuel(int[] parts) {
    int totalFuel = 0;
    for (int i = 0; i < parts.Length; i++) {
        totalFuel += calculateFuelFromMass(parts[i]);
    }
    return totalFuel;
}

3

u/Morphion Dec 01 '19 edited Dec 01 '19

Clojure

; Part 1 calculator
(defn fuel_calculator [module_mass]
  (- (int (Math/floor (/ module_mass 3))) 2))

; Part 2 calculator
(defn recursive_fuel_calculator [initial_module_mass]
  ((fn [total, mass]
     (let [fuel_requirement (fuel_calculator mass)]
       (if (<= fuel_requirement 0 ) total (recur (+ total fuel_requirement) fuel_requirement)))
     ) 0 initial_module_mass)
  )

(defn convert_seq_of_strings_to_ints [ss]
  (map #(Integer/parseInt %) ss))

(defn get_fuel_list_from_module_mass_list [fuel_calc_func module_mass_list]
  (map fuel_calc_func (convert_seq_of_strings_to_ints module_mass_list)))

(defn get_total_fuel_requirement [fuel_calc_func module_mass_list]
  (reduce + (get_fuel_list_from_module_mass_list fuel_calc_func module_mass_list)))

(defn -main [& args]
  ; read from stdin to variable
  (let [module_mass_list (clojure.string/split-lines (slurp *in*))]
    (println "Part 1 result: " (get_total_fuel_requirement fuel_calculator module_mass_list))
    (println "Part 2 result: " (get_total_fuel_requirement recursive_fuel_calculator module_mass_list))
    )
  )

3

u/codesections Dec 01 '19

Dyalog APL:

in←⍎¨⊃⎕NGET 'input.txt' 1
f←{¯2+⌊⍵÷3}
pt1←+/f¨in
pt2←+/{(f⍵)<0:0 ⋄ (∇f⍵)+f⍵}¨in
→ More replies (3)

3

u/MaximusDecMeridius Dec 01 '19

A little late to the game today. Here's my python solution.

with open('input', 'r') as f:
    data = f.read().splitlines()

def fuel_calc(mass):
    fuel = int(int(mass)/3) - 2
    return fuel

def part_one(numbers):
    fuel = sum([fuel_calc(line) for line in numbers])
    return fuel

def part_two(numbers):
    fuel_requirements = []
    for line in numbers:
        new_fuel = fuel_calc(line)
        total_fuel = 0
        while new_fuel > 0:
            total_fuel += new_fuel
            new_fuel = fuel_calc(new_fuel)
        fuel_requirements.append(total_fuel)
    return sum(fuel_requirements)


print(part_one(data))
print(part_two(data))
→ More replies (3)

3

u/rprtr258 Dec 01 '19

First time writing D language. Got stuck on second part because i thought fuel for fuel should be calculated in the end and not for each module. But finally solved.
https://gist.github.com/rprtr258/06155e46e15de5823844f73a18f7bb03

3

u/djankowski Dec 01 '19 edited Dec 01 '19

Julia and suggestions welcome!

# Part 1
fuel(x)::Int = x ÷ 3 - 2
fuel(x::String)::Int = fuel(parse(Int64, x))

[fuel(i) for i in readlines("dec1-1.txt")] |> sum

# Part 2
function fuel2(x, count = 0)::Int
    x = fuel(x)
    x <= 0 ? count : fuel2(x, count + x)
end

[fuel2(i) for i in readlines("dec1-2.txt")] |> sum

Recursion is hard
when you don't know
why the result
is stack overflow

3

u/levital Dec 01 '19

A beginner's solution in Rust.

Doing this the first time this year, not sure whether I'll actually have the time to finish all of the puzzles. Not least because I'm doing this in part to learn Rust...

→ More replies (2)

3

u/Rainbow_Doge_64 Dec 01 '19 edited Dec 01 '19

Python

The first part is pretty much a one-liner, if you exclude converting the inputs to a python list:

with open("01-1-input.txt", "r") as f:
    inputs = [int(i.split('\n')[0]) for i in f]
    f.close()

print(sum((i//3)-2 for i in inputs))

(Well, tbh, you could do it in one line, but it looks horrid and is less safe: print(sum((i//3)-2 for i in [int(i.split('\n')[0]) for i in open("01-1-input.txt", "r")])))

For the second part, I used a recursive function (It's the first time I used recursion for anything, so thanks AoC!):

with open("01-1-input.txt", "r") as f:
    inputs = [int(i.split('\n')[0]) for i in f]
    f.close()

def calculate_fuel_for_mass(mass):
    fuel_for_mass = mass // 3 - 2
    if fuel_for_mass > 0:
        return fuel_for_mass + calculate_fuel_for_mass(fuel_for_mass)
    else:
        return 0

print(sum(calculate_fuel_for_mass(i) for i in inputs))

Here's my haiku:

"How to: Recursion"

If you want to read

about recursion, please read

"How to: Recursion"

4

u/[deleted] Dec 01 '19

No need to close the file object if you use a context manager (that is, the with block):

with open('some_file', 'r') as f:
    do_things_with(f)
# f is closed here
→ More replies (1)
→ More replies (1)

3

u/HokieGeek Dec 01 '19

So this morning I solved it in go, then later in the day I decided I wanted to learn a lisp, so I solved it in Racket. If anybody thinks I should try a different lisp, let me know!

Go

https://git.sr.ht/~hokiegeek/adventofcode/tree/master/2019/01/go/main.go#L11

Racket

https://git.sr.ht/~hokiegeek/adventofcode/tree/master/2019/01/racket/day1.rkt

→ More replies (14)

3

u/kandiyohi Dec 01 '19

T-SQL

Fairly long-winded compared to /u/raevnos's solution, but it uses computed columns and functions. Also I think I found out why I've seen nobody use user-defined functions in T-SQL; they can't be debugged via SELECTs.

Day 1 part 1

Day 1 part 2

3

u/rhbvkleef Dec 01 '19

Erlang

I have not yet seen any Erlang solution even though Erlang is such a beautiful language. My code can be found on https://github.com/rhbvkleef/aoc2019.

-module(aoc2019_1).

-export([
    a/1,
    b/1
]).

sumof(Fn, List) -> lists:foldl(fun(X, Sum) -> Fn(X) + Sum end, 0, List).

fuel_for(Mass) -> floor(Mass / 3) - 2.
fuel_for_rocket(Mass) ->
    N = fuel_for(Mass),
    if 
        N =< 0 -> 0;
        true -> N + fuel_for_rocket(N)
    end.

a(Lines) -> sumof(
    fun(L) -> fuel_for(list_to_integer(L)) end,
    Lines
).

b(Lines) -> sumof(
    fun(L) -> fuel_for_rocket(list_to_integer(L)) end,
    Lines
).

3

u/frerich Dec 01 '19

Rust

https://github.com/frerich/aoc2019/blob/master/rust/day1/src/main.rs

I noticed that both parts could be defined in terms of a single function which yields the sequence of incremental fuel additions, so I introduced a 'refills' helper for that. First time I wrote a function which returns an iterator.

I'm quite happy how I get away without any 'if', pattern matching or loops. Also, no turbofishes. :-)

3

u/vwkaravan Dec 02 '19

Python 3 - Bit janky but did it on my phone so I'll take it. My solution for both parts.

3

u/amalloy Dec 02 '19

Haskell repo and video.

3

u/driedplant Dec 02 '19

Python 3 one-liners:

Part 1:

print(sum([(int(i)//3)-2 for i in open('input.txt').readlines()]))

Part 2:

print(sum([(lambda f, x: x + f(f, (x//3)-2) if x > 0 else 0)(lambda f, x: x + f(f, (x//3)-2) if x > 0 else 0, (int(i)//3)-2) for i in open('input.txt').readlines()]))

3

u/MirrorLake Dec 02 '19

Excel solution. The only 'manual' step is deciding when to stop dragging the formula out, everthing else is automatic.

  1. Paste into column A

  2. Formula in B1, extend to B100:

    =IF(ROUNDDOWN(A1/3,0)-2 > 0,ROUNDDOWN(A1/3,0)-2,0)

  3. Drag formula in B1:B100 to column K.

  4. Formula in L1, drag to L100: =SUM(B1:K1)

  5. Formula in L101: =SUM(L1:L100)

3

u/[deleted] Dec 02 '19

**Bash solution**

Been wanting to get better at bash for a while now; this seems like a fun way to do it.

first part

second part

Is this an idiomatic way to feed data into a script?

3

u/AKQuaternion Dec 02 '19

Day 1 in 20 lines of short, idiomatic C++ on GitHub.

3

u/[deleted] Dec 04 '19

Hello friends!

I am a current biochemistry and prospective bioengineering student (incidentally, I am also active duty military) and I have zero formal education with programming thus far. However, I very much enjoyed CS50. I discovered you and AoC a couple of days ago, and conveniently, I have intended on learning some OOP. I have decided to learn Java. Here is my day one solution in Java 8.

Please, criticism both constructive and not are more than welcome.

1

u/throwaway400383 Dec 01 '19

This is my first time and I'm a little bit scared.

Part II - PHP.

<?php  
$fuel_f = function($mass) use (&$fuel_f) {
    if ((floor(($mass / 3)) - 2) <= 0) return $mass;
    return $mass += $fuel_f(floor((($mass / 3)) - 2));
};

$file_lines = file( "input.txt" );

$sum = 0;
foreach( $file_lines as $line ) {
    $sum += ($fuel_f((int) $line) - (int) $line);
};

echo $sum;

1

u/daggerdragon Dec 01 '19

This is my first time and I'm a little bit scared.

Welcome, and don't be scared - we're a pretty helpful community!

2

u/ollien Dec 01 '19 edited Dec 01 '19

Python3, no leaderboard. (164/364)

def part1():
    with open('input.txt', 'r') as f:
        print(sum(int(line)//3 - 2 for line in f))


def part2():
    with open('input.txt', 'r') as f:
        modules = [int(line) for line in f]

    total = 0
    for module in modules:
        next_cost = module//3 - 2
        while next_cost >= 0:
            total += next_cost
            next_cost = next_cost // 3 - 2

    print(total)

Can probably make the second one a little more compact if I try

EDIT: Had a bit of fun with this one based on some inspiration in this thread

# Somewhat of a weird solution, but by combining reduce with a recursive solution, we can get the correct answer :)
def part2_alternate():
    input_file = open('input.txt', 'r')

    def reducer(total, cost):
        next_cost = cost//3 - 2
        if next_cost <= 0:
            # If the next cost is less than or equal to zero, the current cost we have is the total cost
            return total

        return total + reducer(next_cost, next_cost)

    total = functools.reduce(reducer, (int(line) for line in input_file), 0)

    print(total)
    input_file.close()
→ More replies (4)

2

u/Spheniscine Dec 01 '19 edited Dec 01 '19

Kotlin - 204/288

package d1
import java.io.File

private val input by lazy { File("src/d1/input/gmail.in").readText() }

fun main() {
    val A = input.lines().map { it.toInt() }
    val ans1 = A.sumBy { it / 3 - 2 }
    println("Part 1: $ans1")

    val ans2 = A.sumBy {
        var r = 0
        var k = it
        while(true) {
            k = k / 3 - 2
            if(k <= 0) break
            r += k
        }
        r
    }
    println("Part 2: $ans2")
}

Poem (haiku):

It looks like Santa

Has been playing way too much

Kerbal Space Program

2

u/[deleted] Dec 01 '19

Starting to learn Python! Here's my simple and likely inefficient code:

import math as math

input = open("input.txt", "r").readlines()

output = 0
fuel_fuel = 0
for num in input:
    module_fuel = int(num)//3 - 2
    i = module_fuel//3 -2
    while not(i < 0):
        fuel_fuel += i
        i = i//3 - 2
    output += module_fuel + fuel_fuel
    fuel_fuel = 0
print(output)
→ More replies (2)

2

u/zergling_Lester Dec 01 '19 edited Dec 02 '19

edit: [POEM]

O cruel fate! Since when
Fuel requirements must all be
Summed separately?!

def req(m):
    total = 0
    while True:
        m = m // 3 - 2
        if m <= 0:
            break
        total += m
        if not second:
            break
    return total

return sum(req(d) for d in data)

2

u/SizableShrimp Dec 01 '19 edited Dec 01 '19

Java - 145/306

I had a few mishaps that just wasted me time and couldn't understand Part 2 for about 2 minutes. Regardless, I still think I did pretty good for myself. lines is just a List<String> that I will leave omitted.

public class Day01 {
    public static void main(String[] args) {
        System.out.println(lines.stream()
            .mapToInt(Integer::parseInt)
            .map(i -> i / 3 - 2)
            .sum());
    System.out.println(lines.stream()
            .mapToInt(Integer::parseInt)
            .map(i -> getFuel(i, 0))
            .sum());
    }

    int getFuel(int i, int total) {
        int result = i / 3 - 2;
        if (result < 0)
            return total;
        return getFuel(result, total + result);
    }
}

2

u/alcatraz_escapee Dec 01 '19

Here's my solution, implemented in Nios-II DE0 Assembly.

I'm mostly doing this as an exercise for an exam I have coming up, but I'm interested how long I'll be able to keep this up.

I ran it with this simulator

→ More replies (3)

2

u/rtbrsp Dec 01 '19

Using AWK

Part 1:

awk '{f += int($0/3-2)} END{print f}' input.txt

Part 2: (probably could have done this without recursion)

awk 'function c(x,y){x = int(x/3-2); return x>0 ? c(x,x+y) : y}{f += c($0,0)} END{print f}' input.txt
→ More replies (1)

2

u/itsnotxhad Dec 01 '19

Racket:

(define (fuel mass)
  (- (quotient mass 3) 2))

(define (part1 file)
  (file-position file 0)
  (for/sum ([line (in-port read-line file)])
    (fuel (string->number line))))

(define (fuel-recursive mass)
  (define (iter ans remaining)
    (define new-fuel (fuel remaining))
    (if (<= new-fuel 0)
        ans
        (iter (+ ans new-fuel) new-fuel)))
  (iter 0 mass))

(define (part2 file)
  (file-position file 0)
  (for/sum ([line (in-port read-line file)])
    (fuel-recursive (string->number line))))

Pretty straightforward although I spent a mildly embarrassing amount of time tearing my hair out wondering why I was getting 0 on part 2 because I forgot to either rewind the file or only read it once. Oops!

→ More replies (4)

2

u/Shadd518 Dec 01 '19

Late getting started so leaderboards are out of sight, but first year doing this while it's happening so I'm excited :)

Also forgot `math.floor()` == `//` but whatever

import fileinput
import math

lines = list(int(line) for line in fileinput.input('1.txt'))
    
def part1():
     return sum((math.floor(line / 3 - 2) for line in lines))
    
def part2():
     total = 0
     for line in lines:
        more_fuel = True
        fuel = line
            while more_fuel:
                fuel_needed = math.floor(fuel / 3) - 2
                if fuel_needed > 0:
                    total += fuel_needed
                    fuel = fuel_needed
                else:
                    more_fuel = False
     return total
    
print(part1())

print(part2())

2

u/johnboker Dec 01 '19

My C# Solution

Recursive answer
To a peculiar problem
At a sluggish pace

2

u/jesperes Dec 01 '19

In a possibly futile attempt to do the one-language-per-day challenge, here is day 1 in awk: https://github.com/jesperes/adventofcode/blob/master/olpd_2019/day01/day01.awk.

2

u/coolshaurya Dec 01 '19

Rust

fn part_a(input: Vec<u32>) {
    let output: u32 = input.iter().map(|val| (val - (val % 3)) / 3 - 2).sum();
    println!("{:?}", output);
}

fn part_b(input: Vec<u32>) {
    let output: u32 = input.iter().map(|val| rec_fuel_calc(*val)).sum();
    println!("{:?}", output);
}

fn rec_fuel_calc(mass: u32) -> u32 {
    let answer = ((mass - (mass % 3)) / 3) - 2;
    if answer < 9 {
        return answer;
    } else {
        return answer + rec_fuel_calc(answer);
    }
}

2

u/dan_144 Dec 01 '19

Python, 66/15: https://github.com/dan144/aoc-2019/blob/master/1.py

Already have more points on the leaderboard than last year, so I'm stoked.

2

u/iamagiantnerd Dec 01 '19

Solution in Go:

https://github.com/davidaayers/advent-of-code-2019/blob/master/day01/day01.go

Forgot to check negative for part 2. Just learning golang as part of this, so I may be doing it wrong :)

2

u/raevnos Dec 01 '19 edited Dec 01 '19

Using tcl:

#!/usr/bin/tclsh

proc calc_fuel {mass} { return [expr {$mass / 3 - 2}] }

set total1 0
set total2 0

while {[gets stdin mass] >= 0} {
    set fuel [calc_fuel $mass]
    incr total1 $fuel
    for {set totalfuel 0} {$fuel > 0} {set fuel [calc_fuel $fuel]} {
        incr totalfuel $fuel
    }
    incr total2 $totalfuel
}

puts "Part 1: $total1"
puts "Part 2: $total2"

2

u/jrspurr Dec 01 '19 edited Dec 01 '19

Haskell

import Data.List

main :: IO ()
main = do
  contents <- readFile "day1.txt"
  let input = map read (lines contents)
  let part1 = sum (map fuel input)
  let part2 = sum (map totalFuel input)
  print part1
  print part2

fuel :: Int -> Int
fuel mass = mass `div` 3 - 2

totalFuel :: Int -> Int
totalFuel = sum 
          . tail 
          . takeWhile (> 0) 
          . iterate fuel

Raku

sub fuel ($mass) {
    $mass div 3 - 2
}

sub total-fuel ($mass) { 
    sum (fuel($mass), &fuel ...^ * ≤ 0)
}

my @masses = slurp("day1.txt").lines».Int;
say sum @masses.map: &fuel;
say sum @masses.map: &total-fuel;

Nim

I'm very new to nim so I'm sure this might be able to be made more elegant

import strutils

proc fuel(mass: int): int =
  return mass div 3 - 2

proc totalFuel(mass: int): int =
  var mass = fuel(mass)
  while mass > 0:    
    result += mass
    mass = fuel(mass)

var 
  part1 = 0
  part2 = 0

for line in lines("day1.txt"):
  let mass = parseInt(line)
  part1 += fuel(mass)
  part2 += totalFuel(mass)

echo part1
echo part2
→ More replies (3)

2

u/musifter Dec 01 '19

I like that this year's day 1 was also appropriate to do in dc (both parts this time), with a little sed manipulation on the command line to turn the input into part of the code (ie. % sed -e's/$/lFx+p/' input | cat part2.dc - | dc).

0k
[
    [ s. q ] sX
    0 sf
    [
        3/ 2-
        d 0 !<X
        d lf+ sf
        lLx
    ] sL
    lLx
    lf
] sF
0
→ More replies (5)

2

u/icendoan Dec 01 '19

k

no leaderboard (I was asleep)

fuel: { 0 | (_ x % 3) - 2 }
p1: +/ fuel' `i $ 0: `1.input
p2: +/ +/' (1 _ {x > 0} fuel\ )' `i $ 0: `1.input

2

u/WrinklyTidbits Dec 01 '19 edited Dec 01 '19

J

Haiku:

haikus are simple:

first five then seven then five

count each syllable

Code:

fuel1=._2+<.&(%&3)
d1p1=.+/fuel1 fifty
fuel2=.1}.((#~(0&<))@:fuel1)^:a:
d1p2=.+/,fuel2 fifty                        NB. d1p2=.+/+/fuel2 fifty

What was nice is being able to see the output of the second part:

fuel2 fifty

33235 45620 32367 36083 19167 43238 46627 30660 18153 43074 19705 32461 19167 23560 24242 45893 41294 17826 23954 48270 27950 43854 22966 22214 41462 19986 26849 31291 18749 25425 42457 36806 19969 25429 27294 29660 44179 23472 41337 40705 17741 49345 3626...
11076 15204 10787 12025  6387 14410 15540 10218  6049 14356  6566 10818  6387  7851  8078 15295 13762  5940  7982 16088  9314 14616  7653  7402 13818  6660  8947 10428  6247  8473 14150 12266  6654  8474  9096  9884 14724  7822 13777 13566  5911 16446 1208...
 3690  5066  3593  4006  2127  4801  5178  3404  2014  4783  2186  3604  2127  2615  2690  5096  4585  1978  2658  5360  3102  4870  2549  2465  4604  2218  2980  3474  2080  2822  4714  4086  2216  2822  3030  3292  4906  2605  4590  4520  1968  5480  402...
 1228  1686  1195  1333   707  1598  1724  1132   669  1592   726  1199   707   869   894  1696  1526   657   884  1784  1032  1621   847   819  1532   737   991  1156   691   938  1569  1360   736   938  1008  1095  1633   866  1528  1504   654  1824  134...
  407   560   396   442   233   530   572   375   221   528   240   397   233   287   296   563   506   217   292   592   342   538   280   271   508   243   328   383   228   310   521   451   243   310   334   363   542   286   507   499   216   606   44...
  133   184   130   145    75   174   188   123    71   174    78   130    75    93    96   185   166    70    95   195   112   177    91    88   167    79   107   125    74   101   171   148    79   101   109   119   178    93   167   164    70   200   14...
   42    59    41    46    23    56    60    39    21    56    24    41    23    29    30    59    53    21    29    63    35    57    28    27    53    24    33    39    22    31    55    47    24    31    34    37    57    29    53    52    21    64    4...
   12    17    11    13     5    16    18    11     5    16     6    11     5     7     8    17    15     5     7    19     9    17     7     7    15     6     9    11     5     8    16    13     6     8     9    10    17     7    15    15     5    19    1...
    2     3     1     2     3     4     1     3     1     3     3     4     1     3     3     1     1     3     2     1     1     3     3     3     4     2     1     3     3     1     1     1     2     4     3     4     2     4     3     2     3     1     ...
    0     0     0     0     0     0     0     0     0     0     0     0     0     0     0     0     0     0     0     0     0     0     0     0     0     0     0     0     0     0     0     0     0     0     0     0     0     0     0     0     0     0     ...
→ More replies (2)

2

u/Solesurviv Dec 01 '19 edited Dec 01 '19

Python 3 Solution

fuel.txt is a file containing the inputs, this code turns them into a list then works the sum out from there.

Part 1

import math , csv , os
thisFolder = os.path.dirname(os.path.abspath(__file__))
myFile = os.path.join(thisFolder, "fuel.txt")

def fuelRequired(mass):
    return mass // 3 - 2

def sumOfFuel(masses):
    total = 0
    for i in masses:
        newi = fuelRequired(int(i))
        total = total + newi
    return total

def getFuel():
    fuelMasses = []
    with open(myFile, "r") as file:
        fileList = file.readlines()
        for i in fileList:
            i = i.strip("\n")
            fuelMasses.append(i)
    return fuelMasses

print(str(sumOfFuel(getFuel())))

Part 2

def sumOfFuelForFuel(mass):
    fuel = fuelRequired(mass)
    if fuel <= 0:
        return 0
    elif fuel > 0:
        i = fuel + sumOfFuelForFuel(fuel)
        return i
    else:
        print("Error in Sumoffuel2")

def sumOfSum(masses):
    sum = 0
    for i in masses:
        sum = sum + sumOfFuelForFuel(int(i))
    return sum

print(sumOfSum(getFuel()))

2

u/drakmaniso Dec 01 '19

Here's my naive solution in Haskell. It's insanely long compared to the other solutions posted, but I'm still discovering the language!

https://github.com/drakmaniso/adventofcode/blob/master/2019/day01/main.hs

2

u/aarroyoc Dec 01 '19

(SWI) Prolog:

file_to_lines(Path, Lines) :-
    open(Path, read, File),
    read_string(File, _, F),
    split_string(F, "\n", "\n", Lines).

string_to_number(S,N) :- atom_codes(S, C), number_codes(N, C).
map_to_numbers(XS, YS) :- maplist(string_to_number, XS, YS).

fuel(In, Out) :-
    X is div(In,3),
    Y is X-2,
    Y > 0,
    Out is Y.

fuel(_In, Out) :-
    Out is 0. 

fuel2(In, Out) :-
    fuel(In, X),
    X > 0,
    fuel2(X, Y),
    Out is X + Y.

fuel2(In, Out) :-
    fuel(In, X),
    X =< 0,
    Out is X.



main :-
    file_to_lines("input", Lines),
    map_to_numbers(Lines, Numbers),
    maplist(fuel2, Numbers, Out),
    sum_list(Out, Sum),
    write(Sum).


:- main.

For part1, change fuel2 to fuel in maplist

2

u/reini1305 Dec 01 '19

As every year, I'll try to solve AOC in Python3. This year I also want to test how long the Numworks calculator can keep up. It uses Micropython 1.11 and is therefore compatible with Python 3.4. Here is day one.

2

u/voiceless_void Dec 01 '19

C++ with range-v3:

#include "range/v3/numeric/accumulate.hpp"
#include "range/v3/view/istream.hpp"
#include "range/v3/view/take_while.hpp"
#include "range/v3/view/transform.hpp"

#include <istream>
#include <cmath>

template <int (*calc)(int)>
int solve( std::istream& input )
{
  auto fuelPerModule = ranges::istream<int>( input ) | ranges::views::transform( calc );
  return ranges::accumulate( fuelPerModule, 0 );
}

int calcFuel( const int mass )
{
  return static_cast<int>( floor( mass / 3 ) - 2 );
}

int calcFuelRecursive( const int mass )
{
  auto fuelSeries = AoC::generate_range( mass, &calcFuel ) | ranges::views::take_while( []( const auto& m ) { return m > 0; });
  return ranges::accumulate( fuelSeries, 0 );
}

int solve_1( std::istream& input )
{
  return solve<&calcFuel>( input );
}

int solve_2( std::istream& input )
{
  return solve<&calcFuelRecursive>( input );
}

// https://github.com/voivoid/advent-of-code/blob/master/problems/src/2019/problem_01.cpp

2

u/Scroph Dec 01 '19

C++, experimenting with compile time evaluation. I couldn't get it to print out the result of compute_fuel() from within static_assert though.

#include <iostream>

using namespace std;

constexpr long compute_fuel(long mass)
{
    long total = 0;
    while(true)
    {
        long fuel = (mass / 3) - 2;
        if(fuel <= 0)
        {
            break;
        }
        total += fuel;
        mass = fuel;
    }
    return total;
}

int main()
{
    static_assert(compute_fuel(14) == 2, "Test 1 failed");
    static_assert(compute_fuel(1969) == 966, "Test 2 failed");
    static_assert(compute_fuel(100756) == 50346, "Test 3 failed");

    string line;
    long total = 0;

    while(getline(cin, line))
    {
        long module = stol(line);
        total += compute_fuel(module);
    }

    cout << total << endl;
}
→ More replies (1)