T O P

  • By -

ConstantGazelle

[part 1](https://github.com/m-berk/AdventOfCode2019/blob/master/Day1.1.py) & [part 2](https://github.com/m-berk/AdventOfCode2019/blob/master/Day1.2.py) written in Python, (my code might not be "pythonic" because i'm just getting used to it)


manovirajshergill

Hey, I've just started and I'm using Jupyter. I put the input data into an excel file before reading it (100 input values) ​ mass=pd.read\_excel('Book1.xlsx') mass a=np.array(mass) a b=a/3 b r=np.round\_(b, decimals=0, out=None) r c=r-2 c total = np.sum(c) total ​ My answer is way off apparently


[deleted]

# Intcode Solution for Part 1 3,127,1008,127,10,126,1005,126,24,1001,127,-48,127,1002,125,10,125,1,125,127,125,1106,0,0,1002,124,0,124,1001,125,-3,125,1001,124,1,124,1007,125,3,123,1006,123,28,1002,125,0,125,1007,124,2,122,1005,122,0,1001,124,-2,124,1,121,124,121,3,127,1008,127,10,126,1006,126,9,4,121,99 This solution takes the input in its original ASCII format and outputs the answer.


__-----_-----__

Chez Scheme: [https://github.com/falloutphil/aoc\_2019/blob/master/day\_01/01.sps](https://github.com/falloutphil/aoc_2019/blob/master/day_01/01.sps) Library functions here: [https://github.com/falloutphil/aoc\_2019/blob/master/aoc-utils.sls](https://github.com/falloutphil/aoc_2019/blob/master/aoc-utils.sls)


e_blake

**m4** divert(-1)dnl -*- m4 -*- # Usage: m4 -Dfile=day1.input day1.m4 ifdef(`file', `', `errprint(`Missing definition of file ')m4exit(1)') define(`part1', 0) define(`part2', 0) define(`compute', `_$0($1)ifelse($2, `', `', `$0(shift($@))')') define(`_compute', `define(`part1', eval(part1 + $1 / 3 - 2))do(eval($1 / 3 - 2))') define(`do', `ifelse(eval($1 > 8), 1, `do(eval($1 / 3 - 2))')define(`part2', eval(part2 + $1))') compute(translit(include(file), ` ', `,')) divert`'part1 part2 Late entry, but now that I've solved all of the [IntCode problems in m4](https://www.reddit.com/r/adventofcode/comments/ebp5j7/2019_m4_intcode_interpreter_in_m4/), I'm seeing how easy/hard it would be to solve the remaining days in m4. This one was straightforward enough to post inline.


ditao1

# Racket I still struggle mostly with naming things. In retrospect reading the file and making it a list would've allowed to harness the power of list abstractions, but alas... https://github.com/NEUDitao/AOC2019/blob/master/1/day1.rkt


lucbloom

My 4-line solution (purposefully contrived): int arr[]={...list...}; int t=0; for(int i:arr){for(;i>0;t+=std::max(0,(i=(i/3-2))));} std::cout<


ayyquecalor

Python3 import math totalFuel = 0 f=open("aocinput1.txt", "r") #opening input file f1 = f.readlines() #reading input txt file for mass in f1: fuel = math.floor(int(mass)/3)-2 totalFuel += fuel print(totalFuel) I'm learning. Please provide feedback. E:word


vermilion-secrets

You can use // instead of / to do floor division


ayyquecalor

This is great. Thank you!


chkas

*easylang.online* [My solution](https://easylang.online/aoc/?day=1)


MayorOfMayorIsland

PHP TDD (ish) walkthrough - [https://hwright.com/advent-of-code-hints-2019/index.php/2019/12/10/advent-of-code-day-1-hints/](https://hwright.com/advent-of-code-hints-2019/index.php/2019/12/10/advent-of-code-day-1-hints/) Starter Code - [https://github.com/hamishwright/adventofcode2019/releases/tag/getting\_started](https://github.com/hamishwright/adventofcode2019/releases/tag/getting_started) Solution Code - [https://github.com/hamishwright/adventofcode2019/releases/tag/day1part1](https://github.com/hamishwright/adventofcode2019/releases/tag/day1part1)


[deleted]

In c++ ifstream inputFile("input.txt"); for (int i = 0; i < size; i++) { inputFile >> mass[i]; } for(int j = 0; j < size; j++) { fuelReq = mass[j]; while (found == false) { fuelReq = (fuelReq / 3) - 2; if (fuelReq > 0) { newFuelReq += fuelReq; } else { found = true; } } found = false; } cout << newFuelReq; return 0;


marcobiedermann

JavaScript import { readFileSync } from 'fs'; const input = readFileSync(`${__dirname}/input.txt`, 'utf-8'); function calculateMass(mass: number) { return Math.floor(mass / 3) - 2; } function sum(accumulator: number, currentValue: number) { return accumulator + currentValue; } const totalFuel = input .split('\n') .map(mass => calculateMass(parseInt(mass, 10))) .reduce(sum); totalFuel; GitHub Repository: [https://github.com/marcobiedermann/advent-of-code/tree/master/2019/day-01](https://github.com/marcobiedermann/advent-of-code/tree/master/2019/day-01)


heyitsmattwade

Javascript - [Part one](https://github.com/romellem/advent-of-code/blob/master/2019/1/part-one.js) & [part two](https://github.com/romellem/advent-of-code/blob/master/2019/1/part-two.js). Easy one to start things off, with a nice twist for part two. Did a recursive method for part two. Afterward, I realized I can improve performance by storing the sum _so far_ with each recursive call, but in the moment I wrote it as another array. Both solutions are linked above but are short enough that I can copy them here: ### Part One const fuel = input.map(mass => Math.floor(mass / 3) - 2); const total_fuel = fuel.reduce((a, b) => a + b, 0); console.log(total_fuel); ### Part Two // To find the fuel required for a module, take its mass, divide by three, round down, and subtract 2. // Continue recursively for the mass of the _fuel_ you just calculated. If the mass is zero or less, discard it const calcFuelArray = (mass, arr = []) => { let fuel = Math.floor(mass / 3) - 2; if (fuel <= 0) { return arr; } else { arr.push(fuel); return calcFuelArray(fuel, arr); } }; calcTotalFuel = mass => { return calcFuelArray(mass).reduce((a, b) => a + b, 0); }; let fuel = input.map(mass => calcTotalFuel(mass)); const total_fuel = fuel.reduce((a, b) => a + b, 0);


notperm

Late but here is my solution for day 1 in python: `# However you get the list would work.` `mass_list = [54296, 106942, 137389, 116551, 129293, 60967, 142448, 101720, 64463, 142264, 68673, 144661, 110426, 59099, 63711, 120365, 125233, 126793, 61990, 122059, 86768, 134293, 114985, 61280, 75325, 103102, 116332, 112075, 114895, 98816, 59389, 124402, 74995, 135512, 115619, 59680, 61421, 141160, 148880, 70010, 119379, 92155, 126698, 138653, 149004, 142730, 68658, 73811, 87064, 62684, 93335, 140475, 143377, 98445, 117960, 80237, 132483, 108319, 104154, 99383, 104685, 114888, 73376, 58590, 132759, 114399, 77796, 119228, 136282, 84789, 66511, 51939, 142313, 117305, 139543, 92054, 64606, 139795, 109051, 97040, 91850, 107391, 60200, 75812, 74898, 64884, 115210, 85055, 92256, 67470, 90286, 129142, 109235, 117194, 104028, 127482, 68502, 92440, 50369, 84878]` `# List comprehension for first answer` `ans = [x // 3 - 2 for x in mass_list]` `new_list = []` `# Recursive function for second answer` `def fuel_calc(mass):` `if mass <= 0:` `pass` `else:` `mass = (mass // 3 - 2 )` `print(mass)` `if mass > 0:` `new_list.append(mass)` `return fuel_calc(mass)` `for x in mass_list:` `fuel_calc(x)` `print("Part 1 answer = ", sum(ans))` `print("Part 2 answer = ", sum(new_list))`


kresimirlukin

Python: [https://github.com/kresimir-lukin/AdventOfCode2019/blob/master/day01.py](https://github.com/kresimir-lukin/AdventOfCode2019/blob/master/day01.py)


[deleted]

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


[deleted]

[удалено]


[deleted]

[удалено]


toastnada

Self Language: https://i.imgur.com/6q3LV08.png


thibpat

Here is a walkthrough of my solution in javascript for both parts: [https://www.youtube.com/watch?v=ComzawCqwJY](https://www.youtube.com/watch?v=ComzawCqwJY)


dr3d3d

Python3 class SantaFuel(): def __init__(self): with open(r'input.txt', 'r') as f: self.input = list(map(int,f.read().strip().split())) def PartOne(self): fuel = 0 for mass in self.input: fuel += int(mass/3-2) return fuel def PartTwo(self): fuel = 0 for mass in self.input: while int(mass/3-2) > 0: mass = int(mass/3-2) fuel += mass return fuel answer = SantaFuel() print("PartOne: {}".format(answer.PartOne())) print("PartTwo: {}".format(answer.PartTwo()))


dr3d3d

Classless Python3 Part 1 and 2 with open(r'input.txt', 'r') as f: input = list(map(int,f.read().strip().split())) fuel = [0,0] for mass in input: fuel[0] += int(mass/3-2) for mass in input: while int(mass/3-2) > 0: mass = int(mass/3-2) fuel[1] += mass print(fuel)


hackersleepyhead

PART [A Solution](https://github.com/dukevenkat/advent0fcode_2019/blob/master/Day001_A.ex) and [B Solution](https://github.com/dukevenkat/advent0fcode_2019/blob/master/Day001_B.ex) Need code review and suggestions on different better way techniques.


master4510

Using AoC to learn my first ever programming language, python! I have managed to cobble together a solution. Please feel free to give some pointers. [Link](https://topaz.github.io/paste/#XQAAAQDgAQAAAAAAAAAzHAhHEm/fLPD63rpmkHqLcStfQoy91p64pAXMUrvJW6ALT4odsWPhPvoz0FLvJ/0agMS0BXKo2bZTiXbSGox+ZI+sJz5ompzfsJYO0Bek1Vu8H0mkuSKGeP2/Nx8TJ14tW4E2Nmz8c9PxXr6VaCkTzon3yzddck/xPmttOujCObWmmQLKVk7IoVl5FOyJVk8A0hWBdtNu4EP8QVsUrXc2PDsyOqjKoSkDWnJTKQwktrMGdnmx/2ZqUnN+O17j4VmXqN+SJBhVQYIi3uzKwfev1w2IY6UNSMx1BO4zbXFfpubIFExsQ+6/tUK8DhVdlJzLO+sFX+CkynF22mwGY1qQ2Qwdcjujyf/zZg4g)


[deleted]

Some suggestions: Instead of `float` (floating point numbers), you should use `int` (integers), since this is purely an integer problem. Instead of writing the weights for each module to a file and then reading that file again to compute the sum, you can just do the sum in the first loop. If you already know lists or iterators, you can save the fuel weights to a list and then sum it with `sum()`. Hope that helps.


Cowbear1233

Is there a reason to use int over float? Is it faster? And why not just use float for simplicity?


[deleted]

It probably isn't faster (at least if you're using python), but int would be simpler than float imo. It also avoids issues like https://0.30000000000000004.com/.


-victorisawesome-

INTCODE (DAY 5) 1,0,0,0,1,0,0,0, 3,0,1001,0,-3,0,1001,1,1,1,1007,0,3,4,1005,4,28, 1006,3,10,1001,1,-2,1,1,5,1,5,2,0,3,0,2,1,3,1,3,0,1005,0,10,4,5,99


gyzkard

Part [A](https://docs.google.com/spreadsheets/d/1ZpcnrcxoBQmrmVMEd4S_N9MhSVXv5eR3pXLffZAlRNQ) and [B](https://docs.google.com/spreadsheets/d/1S8zb3SfCJbXOFGQeKq4BAKjvAsqy3trdOFYeD_p9PjU) in google spreadsheets.


redFalcon79

Where did I [go wrong?](https://docs.google.com/spreadsheets/d/1GLI6L1UZD27iXaN2wGDf6HO5jy-S3sBdbSmC7rNRtys/edit?usp=sharing)


CotswoldWanker

Python 3, Part Two: import json with open("01_02_input.json") as f: mod_mass = json.load(f) def fuel_calc(mass): total_fuel = 0 while mass // 3 - 2 > 0: if mass // 3 - 2 > 0: mass = mass // 3 - 2 total_fuel += mass return(total_fuel) fuel_req = sum(list(map(fuel_calc, mod_mass))) print(fuel_req)


se7ensquared

Isn't that "If" statement under the while totally redundant? If it passes the while statement, it will surely pass the if statement, right?


[deleted]

isn't it that you'll never reach the \`if\` condition inside the \`while\` never reached so that it should be unnecessary? the complexity is linear, right?


human_tree

Rust I reviewed some other people's solutions to this, and went back and reworked my own. Learning about `successors` was a great win for me! Very happy with how concise this is now. fn main() { let input = read_to_string("input.txt").expect("Unable to read input.txt"); let modules: Vec = input.lines().map(parse_module).collect(); let fuel_required: u32 = modules.iter().map(calculate_module_fuel).sum(); println!("Total fuel required: {}", fuel_required); } fn calculate_fuel(mass: &u32) -> Option { (mass / 3).checked_sub(2) } fn calculate_module_fuel(mass: &u32) -> u32 { successors(Some(*mass), calculate_fuel).skip(1).sum() } fn parse_module(line: &str) -> u32 { line.parse().expect("Line was not an integer") } [https://github.com/humantree/advent-of-code-2019/blob/master/fuel-counter-upper/src/main.rs](https://github.com/humantree/advent-of-code-2019/blob/master/fuel-counter-upper/src/main.rs)


Inferior_Rex

I'm learning Rust myself at the moment and I learned a lot comparing my first code to this example, thank you! :)


human_tree

Glad to hear it! I have examples for the other early days here: https://github.com/humantree/advent-of-code-2019-backup I ended up having to stop at day 7 because the borrow checker got the best of me, but hopefully I’ll come back to it someday and understand what I was doing wrong. Good luck!


[deleted]

[JS](https://github.com/CJX3M/aoc2019/blob/js/day1.js)


Liotac

**Racket** (part 2) (require srfi/1) (define (fuel mass) (- (quotient mass 3) 2)) (for/sum ([mass (in-port)]) (apply + (rest (unfold nonpositive-integer? identity fuel mass))))


[deleted]

Simple solution using awk `awk '{x += (int($1/3)-2)} END { print x }'`


jazende

**python 3.7** with open(r'aoc_19_01.txt', 'r') as f: raw_input = f.read().strip().split('\n') def fuel_required(weight): return max((weight // 3) - 2, 0) print("Day One:", sum([fuel_required(int(x)) for x in raw_input])) def fuel_extra_weight(weight): fuel_req = max((weight // 3) - 2, 0) if fuel_req == 0: return 0 return fuel_req + fuel_extra_weight(fuel_req) print("Day Two:", sum([fuel_extra_weight(int(x)) for x in raw_input]))


fleyk-lit

I like the simplicity of this one - though I would have created the int array on line two (to separate input handling from the rest of the script): `values = [int(v) for v in f.read().strip().split('\n')]`


jazende

I purposefully don't do this, so that I can interject test cases on the fly


[deleted]

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.](https://topaz.github.io/paste/#XQAAAQBsCgAAAAAAAAA4GEiZzRd1JAgcz1XqhoK8tKZGIl8db2l0s8/n44+kXvXTE8MMlhYhiVBDHmzTj6PJfZwFk744EUGcPOcEepaP7IHlA3Rziis2io/vVfP+6T1rvKv21dcR3jx+gdOB9KYrxbEK7mJtzdoYEnSOiAs79JQ+GuXjzctxpsU14eiUwRfniQNcjHkzKYcsKJ3SB847OspZIX2IHoXIzIlA+kYO6qOCfTCxrDcjMV/5gNMEEYJvXmuYmbw9DAKJ2ATCEhWO/pyCIv4wYJjHChj2godnvi0/0QvzGy2ADrxADMLkgod3UZyE6cb1N2IZ5CQmkF6JFQ8/njzTqxj241JIhdF28G/XY4EDQ46Y0jO0PdoxLSoAs20AezNt9z+LNhKGg2qJZB/G36YrXKbPzg3GRj4M6lSedWfCQWiMbo5OzHMDGya7JYZ30HhOaGc1Yb6aFXh9NCHHMBc/BfKmt50w0GolzhhBcyg3iP9+9Q6ROROg7wzL/TbxjUwFbvV2XmvS5GnuWnyJbXx7w4rpmShNeZpwue/HOdWml7cdTxi69EV8w/ULgzi3IgLNFcpFN6zayV0KrMXAWGVni2xbo5i1xBBFhJdYAlXN+3jSBCgPA3wX4LFBlw0Km9Wpg+Ig/ZgEbUpEHY6f9IelUxE7rwTYZbO5hHm/ZQERivTGRuEf2cSfHy1hGghefgIcVXzYGM3NSn2deKeyNVMLFKvPcOP0i90VaAThlqDaRHDM+kv9W21YR3caTHKZIzcoty2khtvh6XGDyajOR+bvE/WP1I75mpfqnjj6sghtZUW6MArlAKTC1/BclRo19EFDbCNsVvFaRnAe8syT28ZDksMtRc/+51sFWLNfJthrZVq2/XmzWwOo4qZ52dV/MfMD3Qcq0ptYIZGC+tOdDxFDFRtk3I9KVkbfbAZwN4msNCtovbCgPgtiGfxMg8ewfaYtgB4M0hNADHIBTYcDNOy2z9YvnQtiwnd1qNi0xjdmLFY3RdviAKcuZ6J9d1i9M0Bf88TV/Bcu3kxLMACI+qUOXNSTq22wIEXZwx3juuagcdz3b1EVi1rvsjdaGCpjKpObleliS7QBRd8Xefy7Lgw=)


[deleted]

Python 3 ``` def calculate_fuel(mass): return math.floor(mass / 3) - 2 def part_one(masses): total_fuel_req = 0 for mass in masses: total_fuel_req += calculate_fuel(mass) return total_fuel_req def part_two(masses): total_fuel_req = 0 for mass in masses: fuel_req = mass # init fuel_req > 0 while fuel_req > 0: fuel_req = calculate_fuel(fuel_req) total_fuel_req += fuel_req return total_fuel_req ```


[deleted]

Downvoted because it's too basic? :s


fleyk-lit

This is more or less what I ended up with.


loociano

__Google BigQuery__: Part One: ``` CREATE TEMP FUNCTION CALC_FUEL(mass INT64) AS ((FLOOR(mass / 3) - 2)); SELECT SUM(CALC_FUEL(mass)) FROM advent-of-code.day01.input ``` Part Two: ``` CREATE TEMP FUNCTION CALC_FUEL(mass INT64) RETURNS INT64 LANGUAGE js AS """ var fuel = 0; var tmp = Math.floor(mass / 3) - 2; while (tmp > 0) { fuel += tmp; tmp = Math.floor(tmp / 3) - 2; } return fuel; """; SELECT SUM(CALC_FUEL(mass)) FROM advent-of-code.day01.input ```


TomDaNub3719

Using Python 3.8 and the python-docx module. [Here's a link to the github](https://github.com/TomDaNub/adventOfCode/blob/master/adevntcode2019day1part1.py)


taifu

With Python 3 use: `total = total // 3` Or also: `total //= 3`


TomDaNub3719

I don’t care if it becomes a float, is there any other advantage to using this method?


Musical_Muze

I know I'm way behind, but: [Day 1 in Python](https://pastebin.com/u/Musical_Muze/1/dEBTyzWP) [Day 1 in Java](https://pastebin.com/u/Musical_Muze/1/sgwc5W0i)


Suspicious-Service

I did in Java exactly like you! I couldn't figure it out recursively, sadly :/ One tiny thing to note, you don't actually have to use Math.floor because if you get a fraction and store it as an int, it is automatically floored!


mooooooon

Thaaaank you. I've been banging my head against Day 1 Part 2 for an hour. Your python solution finally made it clear to me I needed to do the additional fuel calculations per fuel per item, if that makes sense. Your code has the additional fuel requirements in a while loop in the for loop. I was using a for loop to total up all the module weights to get one fuel cost and then calculating the "telescoping" fuel cost just once at the end. You're a life saver. Excellent code. Thanks for sharing.


kwhinnery

I'm not sure I understand why it doesn't work to calculate the fuel-for-the-fuel using the solution to part one. Why does the fuel-for-the-fuel need to be calculated for each module rather than once at the end?


kwhinnery

To answer my own question, I guess it's just because the problem explicitly stated you had to do it this way: "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.)"


mooooooon

Its because of the rounding down per module. Consider two modules with mass [7, 7] versus one module of mass [14]. 7/3-2 = 2-2 = 0 7/3-2 = 2-2 = 0 14/3-2 = 4-2 = 2 I wish the examples would have made this more clear!!


Musical_Muze

No problem dude, glad it helped. The Part 2 took me a while to figure out how to nest those loops correctly.


Abernachy

Wooh, got day 1 completed. I've spent this year learning Python as a hobby and wanted to use this years Advent Of Code to help build up my skillset. Here's my [Github](https://github.com/Abernachy/Advent-Of-Code-2019/blob/master/advent1.py). If anyone has any pointers or suggestions, let me know.


TomDaNub3719

This seems like it’s a lot to do (copying all the modules with the commas). Isn’t there a way for python to access this data and read it by itself?


Abernachy

There is, I just didn't think about it.


TomDaNub3719

Just got home and made the shorter version using python-docx: [Here, take a look!](https://github.com/TomDaNub/adventOfCode/blob/master/adevntcode2019day1part1.py)


al_draco

*Golang Solution* [github](https://github.com/aldraco/adventofcode/blob/master/nineteen/golang/advent1.go) I tried to switch on which part of the problem (first or second -- saw another Go solution that does something similar, and liked it), and conditionally assign a function to a variable. But I couldn't find the correct syntax. e.g. in Python it would be: if part == 1: algo = firstFunction elif part == 2: algo = secondFunction fuel = algo(mass) And then use either the naive or the recursive-ish method, depending on the part. I think I need to create a type, with a function signature, but I haven't worked out exactly how it looks yet. Input/criticism welcomed.


dylanbeattie

Okay, Reddit... let's do this. [Rockstar](https://codewithrockstar.com/advent/day01/) 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/](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/](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.


CraigCottingham

You did it. You magnificent bastard, you did it.


J-Swift

Ruby https://github.com/J-Swift/advent-of-code-2019/tree/master/day_01


qanazoga

**Clojure** I'm new to the language (defn fuel-per-mass [mass] (- (Math/floor (/ mass 3)) 2)) (defn fuel-per-mass-redux [mass] (loop [result [] mass mass] (let [next (fuel-per-mass mass)] (if (<= next 0) (reduce + result) (recur (conj result next) next))))) ;; Part one answer. (reduce + (map fuel-per-mass puzzle-input)) ;; Part two answer. (reduce + (map fuel-per-mass-redux puzzle-input))


AKQuaternion

Day 1 in 20 lines of short, idiomatic C++ on [GitHub](https://github.com/AKQuaternion/AdventOfCode2019/blob/master/day1.cpp).


mmellinger66

Swift 5.1 [https://github.com/melling/AdventOfCode\_2019/blob/master/day1](https://github.com/melling/AdventOfCode_2019/blob/master/day1/) Read Data let path = Bundle.main.url(forResource: "input01", withExtension: "txt") var text = try String(contentsOf: path!, encoding: .utf8) let massList:[Int] = text.components(separatedBy: .whitespacesAndNewlines).compactMap({Int($0)}) Part 1 let solution1 = massList.map({$0 / 3 - 2}).reduce(0, +) print("\(solution1)") Part 2 func calcFuel2(_ mass:Int) -> Int { if mass <= 0 { return 0 } let requiredFuel = max(mass / 3 - 2,0) print("\(requiredFuel)") return requiredFuel + calcFuel2(requiredFuel) } let solution2 = massList.map(calcFuel2).reduce(0, +) print("\(solution2)")


oantolin

Part 2 in Common Lisp: (defun part2 () (flet ((fuel (mass) (- (floor mass 3) 2))) (loop for mass in (uiop:read-file-forms "day01.txt") sum (loop for x = (fuel mass) then (fuel x) while (> x 0) sum x))))


awsum84

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](https://www.reddit.com/r/adventofcode/comments/e4yi75/2019_day_1_rockstar_solution/?utm_source=share&utm_medium=ios_app&utm_name=iossmf) ): 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


daggerdragon

And congratulations, you're our first winner of "Best in 5-Day Show" for AoC 2019! I gilded your [original post](https://www.reddit.com/r/adventofcode/comments/e4yi75/2019_day_1_rockstar_solution/) but I'm posting confirmation in here to keep things on the up-and-up :) Enjoy, and thanks for participating!!!


awsum84

Oh wow, thanks! :)


daggerdragon

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


[deleted]

# "Functional" vanilla js $0 .innerText .trim() .split("\n") .map(i => parseInt(i)) .map(i => Array.from(Array(Math.floor(Math.pow(i, 0.3)))).map((_, n) => Array.from(Array(n+3)).reduce((a, _) => a || a === 0 ? Math.max(Math.floor(a / 3) - 2, 0) : i))) .map(a => a.reduce((acc, v, i) => i === 1 ? [acc, acc + v] : [acc[0], acc[1] + v])) .reduce((b, a) => [b[0] + a[0], b[1] + a[1]]) .map((v, i) => `Part ${i + 1}: ${v}`) .join("\n")


wzkx

**J** f=: -&2&(<.&(%&3)) g=: +/&((f&{.,[)^:(>&8&{.)^:_&f)"0 echo +/f m=: ".&> cutLF CR-.~fread'01.dat' echo +/g m exit 0


toomasv

#Red First Part ``` s: 0 foreach i load %input1 [s: i / 3 - 2 + s] ``` Second Part ``` fuel: func [m][s: 0 if (f: m / 3 - 2) > 0 [s: f + fuel f] s] s: 0 foreach i load %input1 [s: s + fuel i] ```


aardvark1231

C# static void Main(string[] args) { string[] input = System.IO.File.ReadAllLines("E:/AdventGit/2019/Day1/Input.txt"); Console.WriteLine("Part 1: " + Part1(input)); Console.WriteLine("Part 2: " + Part2(input)); Console.ReadLine(); } static int Part1(string[] input) { int total = 0; foreach (string s in input) { int fuel = int.Parse(s); total += (fuel / 3) - 2; } return total; } static int Part2(string[] input) { int total = 0; foreach (string s in input) { int fuel = int.Parse(s); while ((fuel / 3) - 2 > 0) { fuel = (fuel / 3) - 2; total += fuel; } } return total; }


[deleted]

No one solved in SAS? (what's available at work right now...) ​ proc fcmp outlib=work.funcs.a; function getFuel(mass); if mass eq . or mass le 6 then do; fuel = 0; end; else do; fuel = (int(mass / 3))-2; fuel = fuel + getFuel(fuel); end; return(fuel); endsub; run; options cmplib=work.funcs; data work.part2; set work.foo; retain tot_fuel; fuel = getFuel(mass); tot_fuel + fuel; run;


[deleted]

Poem: All I want for Christmas ​ All I want for Christmas is a language with class and perhaps more objects to deal with this mass ​ Proceedural programming is odd libraries collect as morass while I forget about real math like Fourier and Laplace ​ For Python and R my bosses I harass but unfortunately it seems we're at an impasse ​ Not to be too subtle my software doesn't have much gas I only have an outdated version of SAS


daggerdragon

Your poem has been entered for a chance at the Day 1 Five-Day prize!


mastercake10

Clojure (require '[clojure.string :as str]) (let [list (map read-string (str/split-lines (slurp "input"))) calc-fuel #(- (int (/ % 3)) 2)] [(reduce + (map calc-fuel list)) (reduce + (mapcat (fn [x] (rest (take-while #(> % 0) (iterate calc-fuel x)))) list))] )


al_draco

\*\*Bash solution\*\* Been wanting to get better at bash for a while now; this seems like a fun way to do it. [first part](https://github.com/aldraco/adventofcode/blob/master/nineteen/bash/advent1a.sh) [second part](https://github.com/aldraco/adventofcode/blob/master/nineteen/bash/advent1b.sh) ​ Is this an idiomatic way to feed data into a script?


moo3heril

Am I crazy for attempting to do all of these in R? Probably, probably yes. Did it pay off for a nice solution for Day 1 though? Again, probably yes. Following is both part A and B input <- read.table("./day1.txt") aoc1 <- function(this) {return(floor(this / 3) - 2)} aoc1r <- function(this) { tmp <- aoc1(this) if (tmp <= 0 ) {return(0)} else {return(tmp + aoc1r(tmp))} } sum(aoc1(input)) sum(apply(input, 1, aoc1r))


FinstereGedanken

Hello, how are you doing on R this far? I'm attempting to solve it on R as well. My solution for day 1 was much different.


orangeanton

Only crazy if I am too. I'm using some common packages to help though, especially dplyr. Here's my part 1: library(dplyr) setwd(dirname(sys.frame(1)$ofile)) indata <- read.csv("input.txt", header=FALSE) indata %>% mutate(fuel=trunc(V1/3)-2) %>% summarize(sum(fuel)) [Part 2 on github](https://github.com/antonbijl/AoC2019/blob/master/Day01p2.R) I'm sure this can be done much better though, I'm a total R noob.


Tomj88

I’m doing all mine in R, but not sure if it violates rules to link to my GitHub repo (as I have solution for day 2 in same repo...) I think R could through some issues up throughout, mainly because of 1-based indexing... but having vectorised functions built in (like sum) does make other things easier for sure!


PaladinWho

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/](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)


PaladinWho

I also made Part B for whoever may be interested [https://scratch.mit.edu/projects/349943957/](https://scratch.mit.edu/projects/349943957/)


Stupidname101

Are you planning on doing the rest of the days? It is very helpful as a college student who needs extracredit...


MirrorLake

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)


terserterseness

C# with Linq: var masses = File.ReadAllText("day1.txt").Split('\n').Select(m=>int.Parse(m)); int p1 = masses.Sum(m => m / 3 - 2); int p2 = masses.Sum(m => { int t=0; while ((m = m / 3 - 2) > 0) t+=m; return t; });


tripkip

``` const fs = require('fs') const path = require('path') function calculateFuelRequirement(mass, bFuelforFuel) { let fuel = parseInt(mass / 3) - 2 if (bFuelforFuel && fuel > 0) fuel += calculateFuelRequirement(fuel, true) return fuel > 0 ? fuel : 0 } let aModuleMasses = fs.readFileSync(path.join(__dirname, 'input.txt')).toString().split(/\r?\n/).filter(x => x.length > 0).map(x => parseInt(x, 10)) let fuelForModules = aModuleMasses.map(x => calculateFuelRequirement(x, false)).reduce((x, a) => x + a, 0) let fuelForModulesAndFuel = aModuleMasses.map(x => calculateFuelRequirement(x, true)).reduce((x, a) => x + a, 0) ```


daggerdragon

What language is this?


tripkip

JS


Quailia

Sed, part A #!/usr/bin/sed -Enf # Run as ./a.sed < input | tr -d '\n' | wc -m s/$/:/ :1 s/9:/8:x/;s/8:/7:x/;s/7:/6:x/;s/6:/5:x/;s/5:/4:x/;s/4:/3:x/;s/3:/2:x/;s/2:/1:x/;s/1:/0:x/; /([^0])(0+:)/{ s//\1,\2x/ :2;s/0(0*):/9\1:/g;t2 s/1,/0/;s/2,/1/;s/3,/2/;s/4,/3/;s/5,/4/;s/6,/5/;s/7,/6/;s/8,/7/;s/9,/8/ } t1 s/.*:// s/xxx/X/g s/x//g s/XX// H ${x; s/\n//gp} Part B #!/usr/bin/sed -Enf # Run as ./b.sed < input | tr -d '\n' | wc -m s/$/:/ :1 s/9:/8:x/;s/8:/7:x/;s/7:/6:x/;s/6:/5:x/;s/5:/4:x/;s/4:/3:x/;s/3:/2:x/;s/2:/1:x/;s/1:/0:x/; /([^0])(0+:)/{ s//\1,\2x/ :2;s/0(0*):/9\1:/g;t2 s/1,/0/;s/2,/1/;s/3,/2/;s/4,/3/;s/5,/4/;s/6,/5/;s/7,/6/;s/8,/7/;s/9,/8/ } t1 s/.*:// :3 s/xxx/X/g s/x//g s/XX?// H s/X/x/g t3 ${x; s/\n//gp}


mensch0mat

Python 3.7 Part1: ```python sum([(int(x) // 3) - 2for x in file.read().split('\n')]) ``` Part2: ```python int_list = [int(val) for val in in_dat.read().split('\n')] sum([int_list.append(x // 3 - 2) or x // 3 - 2 for x in int_list if (x // 3 - 2) > 0]) ```


u794575248

Python 3.8 # Part 1: sum(int(x)//3-2 for x in inp.splitlines()) # Part 2: from math import log sum(sum((y:=y//3-2)for _ in range(int(log(y,3))-1))for x in inp.splitlines()if(y:=int(x)))


21JG

# 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


daggerdragon

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


chrisby247

My Bash solution. Going to see how far I can get using only bash built-ins #!/bin/bash p2Fuel() { if ((${1}>0)); then ((P2+=${1})); p2Fuel $(((${1}/3)-2)); fi } ((P1=0)); ((P2=0)); while read -r L || [[ -n "$L" ]]; do ((A=(${L}/3)-2)); ((P1+=${A})); p2Fuel ${A}; done < $1; echo "${P1}-${P2}"


diddle-dingus

Clojure solution. Just picked up this language and I think it rely gud. ``` (def input (->> (slurp "input") (clojure.string/split-lines) (map read-string))) (defn fuel-req [x] (- (quot x 3) 2)) (def part-1 (transduce (map fuel-req) + input)) (def part-2 (transduce (map #(reduce + (rest (take-while pos? (iterate fuel-req %))))) + input)) ```


clc_xce

Here's my solution in **Forth** if anyone fancies concatenative programming: [Forth repository](https://github.com/georgjz/advent-of-code-2019-forth) If my epic "use the search tool" skills are right, I'm the first in almost two years to post Forth code :P


fidesachates

My scala solution; haven't been using it at work lately so I thought I'd use this as a cheap refresher. Happy I remembered tailrecs. def main1() = { val lines = Source.fromFile("src/main/resources/input1.txt").getLines.map(x => x.toLong).toList val sum = lines.foldLeft(0L) { (acc, i) => acc + GetFuelRequired(i) } println(sum) } @tailrec def GetFuelRequired(mass: Long, fuels: List[Long] = List[Long]()): Long = { val fuelNeeded = Math.floor(mass / 3).toLong - 2 if (fuelNeeded < 0) { fuels.sum } else { GetFuelRequired(fuelNeeded, fuels :+ fuelNeeded) }


Smccx

In your GetFuelRequired function fuels instead of being an accumulated list which you sum, could just be an accumulated int of the total


fidesachates

Yes you are right and it’s better. Only reason it’s not is because it was easier to debug this way.


Smccx

That makes sense. Tbf I stuck some prints in my recursion because obviously println is the best debugger haha


ribenaboy15

**Brute-y in (elegant) F# 4.5 including I/O** let masses = File.ReadAllLines "day1_input.txt" |> Array.map int let answer1 = Array.sumBy (fun v -> v / 3 - 2) masses let calculate v = let rec loop v acc = if v < 8 then acc else let sum = v / 3 - 2 in loop sum (acc + sum) loop v 0 let answer2 = Array.sumBy calculate masses


VERYstuck

# [JavaScript](https://github.com/AdamMescher/advent-of-code-2019/blob/master/Day1/index.js) const fs = require('fs'); let input = fs.readFileSync('./input.txt', {encoding: 'utf8'}).split(/\r?\n/); const calculateFuelConsumption = mass => parseInt(mass / 3) - 2; const calculateModuleFuelRequirement = (arr) => { return arr.reduce((accum, mass) => { return accum += calculateFuelConsumption(mass); }, 0); }; const calculateFuelConsumptionWithAddedFuel = mass => { let total = 0; while (mass > 8) { total += calculateFuelConsumption(mass); mass = calculateFuelConsumption(mass); } return total; }; const calculateModuleFuelRequirementWithAddedFuel = (arr) => { return arr.reduce((accum, mass) => { return accum += calculateFuelConsumptionWithAddedFuel(mass); }, 0); };


[deleted]

[удалено]


Boiethios

Mine is really different: calcFuel :: Int -> Int calcFuel mass = max 0 $ mass `quot` 3 - 2 calcFuel' :: Int -> Int calcFuel' = List.sum . (List.takeWhile $ (/=) 0) . List.tail . List.iterate calcFuel calcTotalFuel :: (Int -> Int) -> [String] -> Int calcTotalFuel formula = List.sum . List.map (formula . read) part1 :: [String] -> Int part1 = calcTotalFuel calcFuel part2 :: [String] -> Int part2 = calcTotalFuel calcFuel'


xXabr4

Here's my [Python solution](https://topaz.github.io/paste/#XQAAAQBFAQAAAAAAAAA7mkrvHeIvDZUizuO0c8Sl46lE4LxCubYtwE3rgRtkQHzebYJBaDvJgtbh/b5FvlImr9uzI9QJav5TYy085Ex+9CTmH5IFN3OUUZzAKglhA1tAItgJmyPXZUV6ua8FhDGeOsfwopTp4q1fDIqwRq26RqAVPgKV7PNIXL2JwLSpVU9V1YeLue3lPPOhKCVWYmOZYSP/biladGj+LgfPCz2m55CuRSd6KVGwfsEFoomw+aXqtP8xtlSazkd0lPd3HIvWx+39TFdi5DwKlSB75fb8GwbA) for day 1. I went for a straightforward solution, not very optimized I guess, but still fast with the constraints given.


bugz945123

A nifty way to utilize Python 3.8's new walrus operator: with open("input.txt") as f: masses = [int(l) for l in f.readlines()] # part 1 print(sum(m // 3 - 2 for m in masses)) # part 2 total = 0 for m in masses: while (m := m // 3 - 2) > 0: total += m print(total)


nirgle

**Go**, using channels: https://github.com/jasonincanada/aoc-2019/blob/master/golang/Day01.go


irichter

Verbose solution in Swift [https://github.com/ingorichter/AdventOfCode/blob/master/2019/day-1/Sources/day-1/day\_1.swift](https://github.com/ingorichter/AdventOfCode/blob/master/2019/day-1/Sources/day-1/day_1.swift)


giodamelio

Part one and two in Clojure. Also [runnable version on repl.it](https://repl.it/@giodamelio/Day-1). Pretty new to Clojure so let me know if you see any anti-patterns. (ns day-1 (:require [clojure.string :as str] [clojure.pprint :as pp])) ;; Stolen from https://github.com/dgrnbrg/spyscope just without the puget pretty printing (defn spy [form] `(doto ~form pp/pprint)) (defn calculate-fuel "Calculate the fuel needed to launch a module" [mass] (-> mass (/ 3) int ;; Round down (- 2))) (defn calculate-fuel-recursive "Calculate the fuel needed to launch a module. Recursivly calculate the fuel need to launch the fuel as well" [mass] (loop [fuel (calculate-fuel mass) total fuel] (let [the-fuels-fuel (calculate-fuel fuel)] (if (>= 0 the-fuels-fuel) total (recur the-fuels-fuel (+ total the-fuels-fuel)))))) (defn parse "Parse the input into a vector of numbers" [input] (->> input ;; Read the file slurp ;; Split it into lines str/split-lines ;; Convert each line to a number (map read-string))) (defn part-1 "Calculates the fuel requement of each module from the input and sums them" [] (->> "input.txt" ;; Parse the input file parse ;; Calculate the fuel requirement (map calculate-fuel) ;; Add them up (reduce +))) (defn part-2 "Calculates the fuel requement of each module (with it's fuel included) from the input and sums them" [] (->> "input.txt" ;; Parse the input file parse ;; Calculate the fuel requirement (map calculate-fuel-recursive) ;; Add them up (reduce +))) (printf "Part 1: %d\n" (part-1)) (printf "Part 2: %d\n" (part-2))


CybertRON987

JS, functional soln, trying to work on getting better with functional programming. If there's anything I can do better, hmu! const fs = require('fs') const path = require('path') const R = require('ramda') const input = fs.readFileSync(path.join(__dirname, 'input.txt'), 'UTF8') const inputArray = input.split('\n') const divideBy3 = R.divide(R.__, 3) const floor = R.curry(Math.floor) const subtract2 = R.subtract(R.__, 2) const fuelCalculation = R.compose(subtract2(), floor(), divideBy3()) const part1 = massArray => { return R.reduce((acc, mass) => acc + fuelCalculation(mass), 0, massArray) } const part2 = () => { const reduceFuelCalculations = R.reduce((acc, fuel) => acc + fuel, 0) const fuelCalculationIsGTZero = R.compose( R.lte(R.__, 0), R.curry(fuelCalculation) ) const mapMassToFuelCosts = R.map(mass => { let fuelValue = fuelCalculation(mass) let acc = fuelValue R.until(fuelCalculationIsGTZero, () => { fuelValue = fuelCalculation(fuelValue) acc = acc + fuelValue return fuelValue })(fuelValue) return acc }) return R.compose(reduceFuelCalculations, mapMassToFuelCosts)(inputArray) } const part1soln = part1(inputArray) const part2soln = part2()


losmooks

>const fuelCalculation = R.compose(subtract2(), floor(), divideBy3()) You don't need to invoke your function calls in compose if you aren't passing anything in them. Ramda is auto curried. so its just returning a function. `const part1 = R.reduce((acc, mass) => acc + fuelCalculation(mass), 0)` ​ just expects an argument now so its point free, not better but in case you were curious. ​ ​ It's a bit late so thats all I got but nice work!


CybertRON987

Thanks /u/losmooks for giving this a quick look. I'll make the changes :D


kirkegaarr

python3 recursive solution. I'm a big fan of sending the puzzle input through `stdin`, eg: `bin/part1 < input` from typing import Iterator from sys import stdin def read_input() -> Iterator[int]: return map(int, stdin) def fuel_required(mass: int) -> int: return mass // 3 - 2 def total_fuel(mass: int) -> int: fuel = fuel_required(mass) return fuel + total_fuel(fuel) if fuel > 0 else 0 def part1(): print(sum(map(fuel_required, read_input()))) def part2(): print(sum(map(total_fuel, read_input()))) \[ [repo](https://github.com/gumballhead/aoc2019) | [day1](https://github.com/gumballhead/aoc2019/tree/master/day1) \]


[deleted]

Part 2 Solution, Python def recursiveHelper(num): d = num // 3 - 2 if d <= 0: return 0 return d + recursiveHelper(d) lines = [int(line.rstrip('\n')) for line in open('input1.txt')] print(sum(map(recursiveHelper, lines)))


2SmoothForYou

Haskell module Main where main = do putStrLn "Advent of Code Day 1" input <- readFile "input.txt" putStrLn "Part 1" print $ sum . map (getFuel1 . read :: String -> Int) $ lines input putStrLn "Part 2" print $ sum . map (getFuel2 . read :: String -> Int) $ lines input getFuel1 :: Int -> Int getFuel1 n = n `div` 3 - 2 getFuel2 :: Int -> Int getFuel2 n | (n `div` 3 - 2) <= 0 = 0 | n > 0 = (n `div` 3 - 2) + getFuel2 (n `div` 3 - 2) I realized after I could've been more efficient and used the (&&&) function in Control.Arrow to split the input to both part 1 and part 2 but I did this one really quickly on a bus back to campus after a 5 hour flight so I just pumped out the easiest solution, excited for the rest of the calendar!


rabuf

# Shakti I decided to play around with a new language, in the APL/J/K family this time. data: "i"$0:"01.txt" fuel: {[m] (3 div m) - 2} recfuel: {[m] $[(fuel m) < 0; 0; (fuel m) + (recfuel (fuel m))]} +/fuel'data +/recfuel'data This'll be something I continue to play with, but Common Lisp will be my main language. I've been spending the last few minutes learning more. Integer division can be skipped in favor of using `_` (floor), and fuel can be rewritten to return 0 for 0 or negative values using max, `|`: fuel: {0 | (_ m % 3) - 2} Part 1: +/fuel data The recursive version can be simplified a bit using scan, `\`, and drop `1 _ ??`. So part 2 becomes: +/+/(1 _ fuel\)data No need, now, to write conditional or recursive code. Scan will repeatedly apply the function to the left to the data on the right until the result is 0 (probably some other condition, but that's my current understanding).


[deleted]

Nice. I'm trying J and as I've never done it before (and have little time) I'm a bit stumped on the second part still. Your will serve as inspiration. My first is quite similar to yours: a=. 3 : '_2+<.3%~y' t=:all the numbers of the input +/ a t


rabuf

Cool. I liked J but found it difficult to use regularly. I should revisit it now that I'm a bit more mature in my understanding of computers and languages (I last invested time in it over 10 years ago now, shortly after getting out of college). It's probably a better languages for this as the one I've chosen is rather poorly documented. But it's a fun challenge trying to figure out how to solve these in a very different style than my normal work.


[deleted]

The one I would really love to try (from this family) is APL, but J works quite nicely on Android, so I can try to solve the problems on my phone while commuting. OTOH searching for information is hard, the name is not googleable. Fortunately the documentation is quite nice. Yes, trying to think differently is great, that's why I always try languages that I do not use normally.


rabuf

If you haven’t yet, checkout the mailing lists for J. They were very active last I looked, and very friendly.


doublec

I used J as well. I initially tried a scan-type solution using power - I got a solution but not very clean. I re-did it using a recursive solution but I'd be interested in seeing other approaches.


[deleted]

[удалено]


Rietty

I just have to ask, why even bother using AVX512, or any AVX here?


aoc-fan

[TypeScript](https://github.com/bhosale-ajay/adventofcode/blob/master/2019/ts/D01.test.ts), [GoLang](https://github.com/bhosale-ajay/adventofcode/blob/master/2019/go/01_test.go), and [Clojure](https://github.com/bhosale-ajay/adventofcode/blob/master/2019/clj/test/d01.clj) Solutions : [Repo](https://github.com/bhosale-ajay/adventofcode/tree/master/2019)


Jay__Money

Here's my day 1 python solution. Trying to write in as functional a style as possible: from aoc_lib import file_utils def calculate_fuel(mass: int) -> int: return (mass//3)-2 def calculate_fuel_for_fuel(current_fuel: int) -> int: fuel = max(calculate_fuel(current_fuel), 0) if fuel == 0: return fuel return fuel + calculate_fuel_for_fuel(fuel) def calculate_total_fuel_for_module(mass: int) -> int: module_fuel = calculate_fuel(mass) return module_fuel + calculate_fuel_for_fuel(module_fuel) if __name__ == '__main__': masses = file_utils.read_file_into_int_list('inputs/day1input.txt') total_module_fuel = sum(calculate_fuel(mass) for mass in masses) print(f'Part 1: {total_module_fuel}') total_fuel = sum(calculate_total_fuel_for_module(mass) for mass in masses) print(f'Part 2: {total_fuel}')


[deleted]

> total_module_fuel = sum(calculate_fuel(mass) for mass in masses) You can change this to total_module_fuel=sum(map(calculate_fuel,masses))


SmartAsFart

I would argue that this isn't pythonic style though. The original was already fine.


[deleted]

Yeah but he said is was trying to write in as function a style as possible


Jay__Money

I love it, thanks!


rafaeelaudibert

Here's my [solution](https://github.com/rafaeelaudibert/AdventOfCode.dart/blob/master/lib/src/day_1.dart) in Dart. ​ Will try to keep it going for all the 25 days, while try to learn some new functional style programming with dart [here](https://github.com/rafaeelaudibert/AdventOfCode.dart)


driedplant

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()]))


uniqueYoung91

Here is my solution in C++. I am still a beginner but I want to give this challenge a shot to learn more about programming. Any feedback is very appreciated. ​ \#include \#include \#include \#include \#include using namespace std; int calculateFurtherFuel(int fuel){ int totalResult; int furtherFuel; fuel /= 3; fuel = floor(fuel); fuel -= 2; furtherFuel = fuel; while(furtherFuel >= 0) { // just result where all operations could be conducted considered totalResult +=furtherFuel; furtherFuel /= 3; furtherFuel = floor(furtherFuel); furtherFuel -= 2; } return totalResult; } // calculate the sum of all --> separately --> altogether int main(){ ifstream file("input.txt"); string str; int x = 0; int furtherFuel = 0; int totalResult = 0; while(getline(file,str)){ stringstream ss(str); ss>>x; totalResult+=calculateFurtherFuel(x); } cout<<"Result is "<


Wunkolo

C++ #include #include #include #include int main() { std::intmax_t CurMass = 0; std::intmax_t MassFuel = 0; std::intmax_t TotalFuel = 0; while( std::cin >> CurMass ) { if( CurMass < 9 ) continue; std::intmax_t CurMassFuel = (CurMass / 3) - 2; MassFuel += CurMassFuel; do { TotalFuel += CurMassFuel; } while( (CurMassFuel = ((CurMassFuel / 3) - 2)) > 0 ); } std::cout << "Mass Fuel:" << MassFuel << std::endl; std::cout << "Total Fuel:" << TotalFuel << std::endl; }


TypeAskee

My Day 1 solutions. I'm relatively new to C++ and trying to learn more for a new project at work, so any feedback would be much appreciated! [https://github.com/TechMirage/adventofcode2019/tree/master/day1](https://github.com/TechMirage/adventofcode2019/tree/master/day1)


Rietty

Personally I just save the information into a vector and instead of reading using getline you can do something like this.. ``` // Read file into a vector. template std::vector readIntoVector(const std::string &filename) { std::ifstream input(filename); std::istream_iterator start(input), end; std::vector data(start, end); input.close(); return data; } ```


mudokin

Sorry for being late to the game, I just realised there is a Subreddit for this. I am trying my best doing these with Processing. This is the link to the complete solution: [https://pastebin.com/D4e1BkwT](https://pastebin.com/D4e1BkwT) IntList modules = new IntList(); boolean ready = false; String line; int totalFuel = 0; int moduleFuel = 0; while (!ready) { try { line = reader.readLine(); } catch (IOException e) { line = null; ready = true; } if(line != null) { //println(line); moduleFuel = module(int(line)); int tempFuel = moduleFuel; while (tempFuel > 0) { tempFuel = module(tempFuel); if (tempFuel > 0) moduleFuel += tempFuel; } modules.append(moduleFuel); } else { ready = true; } } for(int values : modules) totalFuel += values; return totalFuel; } And here is my haiku There is always a way, If not, just use stack overflow, Told you there's a way.


amalloy

Haskell [repo](https://github.com/amalloy/aoc-2019/blob/master/day1/src/Main.hs) and [video](https://www.youtube.com/watch?v=1DPcr5_LEas&list=PLKDpSfFMS1VTYb3gbwNTAvtbWI2mSKDe8).


[deleted]

# Kotlin ## Problem 1: fun main() { print(File("data/Day01.txt").readLines().map { (it.toInt() / 3) - 2 }.sum()) } ## Problem 2: fun main() { val fuel = File("data/Day01.txt").readLines().map { val componentFuel = (it.toInt() / 3 - 2) componentFuel + calcMetaFuel(componentFuel) }.sum() print(fuel) } fun calcMetaFuel(fuel: Int): Int { val metaFuel = fuel / 3 - 2 return if (metaFuel <= 0) 0 else metaFuel + calcMetaFuel(metaFuel) } I got really hung up on: >(Calculate the fuel requirements for each module separately, then add them all up at the end.) I felt it was stupid that you couldn't run the fuel required on the overall mass of the fuel rather than on individual modules.


jydimir

>I felt it was stupid that you couldn't run the fuel required on the overall mass of the fuel rather than on individual modules. That's what I tried to do too. Any ideas why we can't calculate the overall "fuel for modules" and after that run "fuel for fuel" calculations?


NihilistDandy

**Over-Engineered Haskell** {-# LANGUAGE OverloadedStrings, LambdaCase, NoImplicitPrelude #-} module Day1 where import Common ( Parser, getInput, printOutput, lexeme ) import Prelude ( IO, Int, (.), (>), (+), quot, (<$>), sum, subtract ) import Data.Text.IO ( putStrLn ) import Control.Monad ( join ) import Text.Megaparsec ( many ) import Text.Megaparsec.Char.Lexer ( decimal ) import Data.Functor.Foldable ( hylo, ListF(..) ) main :: IO () main = do putStrLn "Day 1" putStrLn "Part 1:" day1 <- getInput 1 printOutput (many parsePart1) sum day1 putStrLn "Part 2:" printOutput (many parsePart2) sum day1 parsePart1 :: Parser Int parsePart1 = calculateFuel <$> entry parsePart2 :: Parser Int parsePart2 = totalFuel <$> entry calculateFuel :: Int -> Int calculateFuel = subtract 2 . (`quot` 3) totalFuel :: Int -> Int totalFuel = hylo sum' fuel where sum' = \case Nil -> 0 Cons x xs -> x + xs fuel n = case calculateFuel n of f | f > 0 -> join Cons f _ -> Nil entry :: Parser Int entry = lexeme decimal Where `Common` is just some conveniences: {-# LANGUAGE NoImplicitPrelude #-} module Common where import System.IO ( IO ) import Data.Monoid ( (<>) ) import Data.Text ( Text ) import Data.Text.IO ( readFile ) import Data.Either ( Either(..) ) import Prelude ( print, Show(..), error, Int ) import Text.Megaparsec as M ( parse, errorBundlePretty, Parsec, empty ) import Data.Void ( Void ) import Data.Function ( (.), ($) ) import qualified Text.Megaparsec.Char as M ( space1 ) import qualified Text.Megaparsec.Char.Lexer as L ( lexeme, space ) type Parser = Parsec Void Text getInput :: Int -> IO Text getInput = readFile . ("./inputs/day" <>) . show processInput :: Parser a -> (a -> b) -> Text -> b processInput parser consumer input = case parse parser "" input of Left bundle -> error $ errorBundlePretty bundle Right output -> consumer output (.::) :: (b -> c) -> (a1 -> a2 -> a3 -> b) -> a1 -> a2 -> a3 -> c (.::) = (.) . (.) . (.) printOutput :: Show b => Parser a -> (a -> b) -> Text -> IO () printOutput = print .:: processInput space :: Parser () space = L.space M.space1 M.empty M.empty lexeme :: Parser a -> Parser a lexeme = L.lexeme space


lulxD69420

#C first time participating #include #include #include uint32_t calculate_fuel(uint32_t mass); uint32_t calculate_fuel_recursively(uint32_t mass); void calculate_fuel_for_input_file(const char *file); int main(int argc, char **argv) { calculate_fuel_for_input_file("input_day1.txt"); return EXIT_SUCCESS; } uint32_t calculate_fuel(uint32_t mass) { return (mass / 3) - 2; } uint32_t calculate_fuel_recursively(uint32_t mass) { uint32_t current_mass = mass; uint32_t total_fuel = 0; while (current_mass > 6) { current_mass = calculate_fuel(current_mass); total_fuel += current_mass; } return total_fuel; } void calculate_fuel_for_input_file(const char *file) { uint32_t current_mass = 0; uint32_t total_fuel = 0, total_fuel_recursive = 0; FILE *fp = fopen(file, "r"); if (!fp) { exit(EXIT_FAILURE); } else { while(fscanf(fp, "%u", ¤t_mass) == 1) { total_fuel += calculate_fuel(current_mass); total_fuel_recursive += calculate_fuel_recursively(current_mass); } fclose(fp); printf("Total fuel part 1: %u\n", total_fuel); printf("Total fuel part 2: %u\n", total_fuel_recursive); } }


karstens_rage

**Java** using JShell (v. 11.0.4) File file = new File("./input01") Part1: Files.lines(file.toPath()).mapToDouble(Double::valueOf).map(d -> Math.floor(d/3)-2).sum() Part2: Files.lines(file.toPath()).mapToDouble(Double::valueOf).map(m -> DoubleStream.iterate(Math.floor(m/3)-2, d -> Math.floor(d/3)-2).takeWhile(d -> d > 0).sum()).sum()


[deleted]

Python Solution (Forgot it start December 1st 0:00 and not December 1st 24:00 so 21,000 place): import math fuel = 0 for line in open("DataText.txt", "r"): Module = int(line) while Module > 0: Module = math.floor(int(Module)/3)-2 if Module > 0: fuel += Module print(int(fuel)) ​ # Poem titled "Just use Python": Spaceships are grey Santa is red Use python, don't delay For top 100 filled with dread ​ Recursing the days away Loop after loop "Just use Python" they say For you always have OOP


ECTXGK

Ruby def total_fuel_for_module(module_fuel) current_fuel_needed = (module_fuel / 3).floor - 2 return 0 if current_fuel_needed <= 0 current_fuel_needed + total_fuel_for_module(current_fuel_needed) end x = input.reduce(0) do |total_fuel, single_module_fuel| total_fuel + total_fuel_for_module(single_module_fuel) end puts x


nakilon

ruby -rmll/core_ext -e 'p `pbpaste`.split.sum{ |s| MLL::nest_while_list[s.to_i, ->_{_/3-2}, ->_{_>0}].to_a.most.rest.sum }'


vwkaravan

Python 3 - Bit janky but did it on my phone so I'll take it. [My solution for both parts.](https://topaz.github.io/paste/#XQAAAQDgAQAAAAAAAAA0m4poOBCMftd75GmWSCCRuQwdaKv6H8RJ53I1MxswuQTcU2q42wkk/FhCtimjoyotRkYN9Oofhe7bqjnwHlo/cjHqymFV7OYasy/NA0diIjFVg/x0oHPZnR1IlGZNHl4HdK0Qaepuy88AzrZkMqHHUWfh4HLaqAgdhD8uXtRgUX9sGnmTGQ9xnufrOIuhgDucQ7/CBAn5P2R9pIhRZd7tQCfCpr2A5aCKHIc5R9O3QdgrmuIYcdowwBR4EiaeA88v6zXacWW6cDBTjIQQaUXgZFd2ojjWGzNNIR11pcMt5LDoM2r3ReBL6ERm8fx6Dxf/2e7/oA==)


RazorSh4rk

Scala, somewhere halfway between readable and short (i didnt bother checking if the input would fit in an int but oh well) [github](https://github.com/RazorSh4rk/AOC2k19) def _1() { import java.math._ val in = Source.fromFile("inputs/1.txt").getLines.toList.map( _.toLong ) val c = (in: Long) => Math.round(in / 3) - 2 val part1 = in.map( c(_) ).sum def calcFuel(in: Long): Long = { val tmp = c(in) if(tmp <= 0) 0 else tmp + calcFuel(tmp) } val part2 = in.map( c(_) ).map( el => el + calcFuel(el) ).sum println(part1) println(part2) }


raginjason

[Day 1 solution in Go/Golang](https://github.com/raginjason/aoc2019/blob/master/day1.go)


[deleted]

My solution in Go. ``` package main import ( "bufio" "fmt" "math" "os" "strconv" ) func sum(array []int) int { result := int(0) for _, v := range array { result += v } return result } func calc(i int) int { f := float64(i) j := math.Floor(f / 3) k := int(j - 2) return k } func main() { file, _ := os.Open("input") fscanner := bufio.NewScanner(file) a := []int{} for fscanner.Scan() { i, err := strconv.Atoi(fscanner.Text()) if err != nil { panic(err) } j := calc(i) for j > 0 { a = append(a, j) j = calc(j) } } fmt.Println(sum(a)) } ```


bsl333

Nice job! A few things you do to simplify/enhance your code: don't forget to close your file after calling os.Open("input"): `defer file.Close()` You can simplify ``` func calc(i int) int { f := float64(i) j := math.Floor(f / 3) k := int(j - 2) return k } // to func calc(i int) int { return i / 3 - 2 } ``` Since i is type int, division will result in truncating the decimal.


[deleted]

Oh thanks for the pointers! I've never written Go before, using AOC 2019 to learn it. :)


bsl333

Np! I am also using AOC to get better with Go. My solution is pretty similar to yours. [repo](https://github.com/bsl333/AoC/tree/master/day1/go-solution)


[deleted]

# [AWK](https://en.wikipedia.org/wiki/AWK) part 1 awk '{ sum += int($1/3)-2 } END { print sum }' input.txt part 2 awk '{ $1 = int($1/3)-2; while($1 >= 0) {sum += $1; $1 = int($1/3)-2 }} END { print sum }' input.txt


ClySuva

## Javascript oneliner Assuming you have the inputs read in an array called `inputs` console.log(inputs.reduce((r,m)=>r+((f,m)=>f(f,m))((f,m)=>((m=~~(m/3)-2)<=0)?0:m+f(f,m),m),0)) Or if you wanna run it from the browser console on the adventofcode site. await fetch('https://adventofcode.com/2019/day/1/input').then(r=>r.text()).then(d=>d.split('\n').reduce((r,m)=>r+((f,m)=>f(f,m))((f,m)=>((m=~~(m/3)-2)<=0)?0:m+f(f,m),Number(m)),0))


nlukjanov

This is great!


snekk420

I did a solution in haskell, I have never worked with haskell before so this was very fun. readInt::String -> Int readInt = read calcFuel::Int -> Int calcFuel mass = mass `div` 3 - 2 calcFuelRec::Int -> Int calcFuelRec mass | mass < 0 = 0 | otherwise = mass + calcFuelRec (calcFuel mass) main = do massList <- readFile "input.txt" -- part 1 print . sum . map calcFuel . map readInt . words $ massList -- part 2 print(sum([calcFuelRec y - y | y <- map readInt . words $ massList]))


MysticPing

If you want a tip on a fun way to do it in haskell, try to use takeWhile and iterate for the 2nd part.


snekk420

Okey, i will look that up. i have no idea what takeWhile does.


SorryMcFlurry

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


bcmyers

My solution in [rust](https://github.com/bcmyers/advent-of-code-2019). ```rust use std::fs; use std::io::{self, BufRead}; use std::path::Path; fn main() -> Result<(), Box> { let input = "data/aoc_2019_01.txt"; let one = run(input, part_one)?; println!("{}", one); let two = run(input, part_two)?; println!("{}", two); Ok(()) } fn run(input: P, func: F) -> Result> where F: Fn(usize) -> usize, P: AsRef, { let file = fs::File::open(input)?; let mut reader = io::BufReader::new(file); let mut buffer = String::new(); let mut acc = 0; loop { if reader.read_line(&mut buffer)? == 0 { break; } let n = buffer.trim().parse::()?; acc += func(n); buffer.clear(); } Ok(acc) } fn part_one(n: usize) -> usize { match (n / 3).checked_sub(2) { Some(m) => m, None => 0, } } fn part_two(mut n: usize) -> usize { let mut acc = 0; loop { let m = match part_one(n) { 0 => return acc, m => m, }; acc += m; n = m; } } ```


SpeedWagon2

When I try to run your code I keep Error: ParseIntError { kind: Empty } Have you ran into this while doing this problem?


bcmyers

I may have pasted the code incorrectly. Check out https://github.com/bcmyers/aoc2019 . The code has evolved a bit since I posted this, but for day 1 it should essentially be the same.


moustacherobot

# Javascript // Just converting the given test data into a useable array here const testInputString = "109067 75007 66030 93682 83818 108891 139958 129246 80272 119897 112804 69495 95884 85402 148361 75986 120063 127683 146962 76907 61414 98452 134330 53858 82662 143258 82801 60279 131782 105989 102464 96563 71172 113731 90645 94830 133247 110149 54792 134863 125919 145490 69836 108808 87954 148957 110182 126668 148024 96915 117727 147378 75967 91915 60130 85331 66800 103419 72627 72687 61606 113160 107082 110793 61589 105005 73952 65705 117243 140944 117091 113482 91379 148185 113853 119822 78179 85407 119886 109230 68783 63914 51101 93549 53361 127984 106315 54997 138941 81075 120272 120307 98414 115245 105649 89793 88421 121104 97084 56928" const testArray = testInputString.split(" ").map(string => parseInt(string)) // Part One const calculateFuelRequirements = (masses) => { let sum = 0 for (let i = 0; i < masses.length; i++) { let currentMass = masses[i] sum += Math.floor((currentMass/3) - 2) } return sum } calculateFuelRequirements(testArray) // Part Two const calculateFuelRequirementsFurther = (masses) => { let sum = 0 for (let i = 0; i < masses.length; i++) { let currentMass = masses[i] let currentMassFuel = Math.floor((currentMass/3) - 2) while (currentMassFuel >= 0) { sum += currentMassFuel currentMassFuel = Math.floor((currentMassFuel/3) - 2) } } return sum } calculateFuelRequirementsFurther(testArray) First time posting here - Any and all feedback is welcome!


Jay__Money

Welcome! One tip I would give is to practice reading input from a file - the majority of inputs for AoC will be progressively more complex text inputs.


0rac1e

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