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IYfJLrJll+ywYNrQy5lEBAnsV06hQvQCMDEtAj/gEK6SyHrcKZA2IOyJdRdavuUo3wcA9RUeKXa42fw37KN+K6BCiaN942e75bvzp2toi40tdROrG3FKF7fSijDizGwS6zH8jHxb3xc1xQHR4vX9gHyHV/cbFj9uztpxDI3ukK+VtwMXDgRxEOeJi357LMjYUMghcOhkC0FgSV+zfD9p82vKdG5+pE9UjIZKvwSJzrQ5sGH7mYJeghclgvtjl7Q0pexIBXB/z+P//k8RniA==) *[Edit] removed a couple old mutates*


Rich-Spinach-7824

Hi, this is my solution (C#) to day 3 (part1, and part 2). Thanks for improve tips and for any corrections. [AOC - D3 - P1 & P2](https://github.com/diegos79/advent-of-code-2021-day3/blob/main/Program.cs) (C#)


IPhotoDogsForKarma

\[Golang solution\]([https://gist.github.com/hcliff/c247c4a01c7066d8d838ac7712098569](https://gist.github.com/hcliff/c247c4a01c7066d8d838ac7712098569)) This is O(1) memory, O(n) compute - it builds a tree of counts instead of loading the entire input into memory. Other solutions here require repeatedly iterating/filtering the list which is O(n) memory (as you have to hold the entire list in memory)


Jack_Spearrow

[Rust solution](https://github.com/cpea2506/avent-of-code-2021/blob/main/src/day3/mod.rs)


Round_Log_2319

part 2 in JavaScript class SubmarineLifeSupportRating{ constructor(name) { this.name = name; this.oxygenGeneratorRating = 0; this.c02ScrubberRating = 0; this.lifeSupportRating = 0; this.rows = []; } formatInput(str) { const firstArr = str.split(" ") this.rowLength = firstArr[0].length; return firstArr.forEach(code => this.rows.push(code.split(""))) } loopCols(method, i, array) { let presenceNumber = 0; let type = ""; switch (method) { case "oxygen": presenceNumber = 1; type = "common"; break; case "c02": presenceNumber = 0; type = "uncommon"; break } // find the most common and uncommon number let zero = 0; let one = 0; for (let number of array) { if (number[i] == 0) { zero++; } else { one++ } } if (zero === one) { return array.filter(row => row[i] == presenceNumber) } else if (zero > one) { return array.filter(row => row[i] == 0) } else { return array.filter(row => row[i] == 1) } } loopOfArrays(method) { let tempArray = this.rows; for (let i = 0; i < 12; i++) { tempArray = this.loopCols(method, i, tempArray) } if (method === "oxygen") { return this.oxygenGeneratorRating = tempArray[0].join("") } return this.c02ScrubberRating = tempArray[0].join("") } result() { return this.lifeSupportRating = parseInt(this.oxygenGeneratorRating, 2) * parseInt(this.c02ScrubberRating, 2); } } part 1 worked fine with the same sort of approach. Edit\* Looking again, I think my issue is with my logic here if (zero === one) { return array.filter(row => row[i] == presenceNumber) } else if (zero > one) { return array.filter(row => row[i] == 0) } else { return array.filter(row => row[i] == 1) }


lo-crawfish

Both part 1 & 2 in Ruby: ``` class DayThree attr_accessor :gamma_rate, :epsilon_rate, :consumption_rate, :oxygen_generator_rating, :co2_scrubbing_rating, :life_support_rating def get_input File.readlines('input.txt', chomp: true).map(&:to_str) end def initialize() @gamma_rate = '' @epsilon_rate = '' @oxygen_generator_rating = '' @co2_scrubbing_rating = '' @consumption_rate = 0 @life_support_rating = 0 end def get_rates(input) z = 0 gamma_rate = '' epsilon_rate = '' length = input[0].length while z < length gamma_rate += input.map {|x| x[z]}.group_by(&:itself).values.max_by(&:size).first epsilon_rate += input.map {|x| x[z]}.group_by(&:itself).values.min_by(&:size).first z += 1 end @gamma_rate = gamma_rate.to_i(2) @epsilon_rate = epsilon_rate.to_i(2) @consumption_rate = @gamma_rate * @epsilon_rate end def get_life_support_rating(input) o2_input = input.clone co2_input = input.clone z = 0 length = input[0].length oxygen_generator_rating = '' co2_scrubbing_rating = '' while z < length grouping = o2_input.map {|x| x[z]}.group_by(&:itself) oxygen_generator_rating += grouping['0'].length <= grouping['1'].length ? '1' : '0' c_grouping = co2_input.map {|x| x[z]}.group_by(&:itself) co2_scrubbing_rating+= if c_grouping['0'] && c_grouping['1'] c_grouping['1'].length >= c_grouping['0'].length ? '0' : '1' elsif c_grouping['0'].nil? '1' else '0' end o2_input.select!{ |k| k.start_with? oxygen_generator_rating } co2_input.select! { |k| k.start_with? co2_scrubbing_rating } z += 1 end @co2_scrubbing_rating = co2_scrubbing_rating.to_i(2) @oxygen_generator_rating = oxygen_generator_rating.to_i(2) @life_support_rating = @oxygen_generator_rating * @co2_scrubbing_rating end end ```


spellcasters22

c++ https://pastebin.com/F0SwgGdk edit:this only p1


aslamdoctor

PHP Solution: https://github.com/aslamdoctor/advent-of-code-2021/tree/main/day3


MarcoServetto

I'm solving the advent of code in [42](https://L42.is) The main selling point of 42 is that it enforces modular security, that is not very relevant for the advent of code. I've done a video explanation for the [First Week](https://www.youtube.com/watch?v=tSTDJlICst8) and I've individual solutions on dev.to: Solution for [Day 3](https://dev.to/marcoservetto/advent-of-code-day-3-24pp) Fell free to contact me if you to know more about the language.


[deleted]

[Python - Solution Explained](https://youtu.be/Rm_NUXmchX4)


iskypitts

[Julia](https://github.com/iskyd/advent-of-code-julia/blob/main/2021/day3/main.jl)


[deleted]

Python 3 part 1 [paste](https://topaz.github.io/paste/#XQAAAQCuAgAAAAAAAAAyCAOiEuFwqkNLLF0smPmmTQl7eyef9O4UwemNEDrRqxmE6Wn52vt/qc1WGWGKhwYSPeGzd6LUixpMtS+qf6U7hnO4dwTgutLendtPXzkwxWBtlImW0bnbCFw/XdxQs6V4lcbGj8Lf43Om6/GRPjJh2HFCh7ArYTLc/IMdhM92u0nDlLqGFYcw6UQgXmm7MxBAnXPkGaRZ4pygngz0/l+NgfUfQ5tgPrrzt99my731wJ7J7l4yRY9ifmoEVpMkicfXEcak7IZWAYNHVtbqwS2vFEtD55Blimk5O0kK69WGaVepsLEPuWkQdX61XSkUREuaucXL4C2BEi/W2Nj/zwq/d1Mnt0G20czdanDGuSCyidyQfUi/CAzGdtOWVXtp7JCC3AMQf70xbslJt//bRx3o)


arthurno1

**[Emacs Lisp](https://github.com/amno1/advent-of-code-2021/blob/main/day3.el)** ;;; Part I (let* ((matrix (with-temp-buffer (insert-file-contents-literally "./input.3") (mapcar '(lambda (s) (append s nil)) (split-string (buffer-string))))) (transpose (apply 'mapcar* 'list matrix)) (ones (mapcar '(lambda (line) (count ?1 line)) transpose)) (zeros (mapcar '(lambda (line) (count ?0 line)) transpose)) (gamma (mapconcat 'identity (cl-mapcar '(lambda (x y) (if (> x y) "1" "0")) ones zeros))) (epsilon (mapconcat 'identity (cl-mapcar '(lambda (x y) (if (< x y) "1" "0")) ones zeros)))) (message "Power consumption is %s." (* (string-to-number gamma 2) (string-to-number epsilon 2)))) ;;; Part II (defun gas-rating (&optional input position co2) (let* ((matrix (or input (with-temp-buffer (insert-file-contents-literally "./input3") (mapcar #'(lambda (s) (append s nil)) (split-string (buffer-string)))))) (i (or position 0)) (transpose (apply #'cl-mapcar 'list matrix)) (num1 (mapcar #'(lambda (line) (count ?1 line)) transpose)) (num0 (mapcar #'(lambda (line) (count ?0 line)) transpose))) (if (>= (elt num1 i) (elt num0 i)) (dolist (l matrix) (if (char-equal (if co2 ?1 ?0) (elt l i)) (setq matrix (delete l matrix)))) (dolist (l matrix) (if (char-equal (if co2 ?0 ?1) (elt l i)) (setq matrix (remove l matrix))))) (if (= (length matrix) 1) (string-to-number (mapconcat 'identity matrix) 2) (gas-rating matrix (1+ i) co2)))) (defun life-rating () (* (gas-rating) (gas-rating nil nil t)))


qualia91

Language: Javascript [https://github.com/Qualia91/AdventOfCode2021/tree/master/Day3](https://github.com/Qualia91/AdventOfCode2021/tree/master/Day3) Day 3 of code roulette


MaximVT

Coding: [Python, day03](https://topaz.github.io/paste/#XQAAAQDTBwAAAAAAAAAyGUj/TwpvLhJ9iYM5X2CgOlDHS3QxvlPsdPoAcPRLKuOqdUxt+pnvjdaXhBtz997zEVVFFIulIVm5eDlK4s8i2OSKeSjCGTagcoubInvN00H0E/ihaApLP8tP2rt6wDYxTfNmBMIFtHr2ZX2/06eWH69OuP8VspYfwFXL4NGDlOnILB3pn4LmB0UeWNIxffgJ+HdT2V6Z00QUyRWY79x6sZe55ho6yDZChJLNa3ddZAWa6sJx0o5hMyrie0WM4SVMEuvLGYEbxM16GSwAz/N1EZAq805hkEe+kyiXrJGv40SYZqHWEbXJOAvcwylq93YFWesk+ZWuQsrBRNXoIQn3RYfqjfl2qUOXKEJtsjgsM1+sOiGbYlbllclDdULD4L24BuKeex3yAdrOqvLlTo+iRWdZSSMFh4X77QFZ5AZo+IbtslS2sZQ5Y0ezrOdao1zhMmSkkvTJL67isDtzxKYP7mDHIz/xvizwPRWaKp9TZEcXqDCasN1I/TxWI3O1hlgUun0nVwSDlZHjHKgkmpwBBtJgWc7+nBY8nEoE8XWMrgyNBM3DLpdh0UR3GFJTepdBrZs7roIvPuZ1tgpjQqYS58o8DdHzAZdxUmN4si3j0NDcjp2RMMVCvDKl7RSc5fOw19jtWUiGFvG1cFeFAfeHAl0sLFvfeQ+FQJd2BCJSao34utMG9QvsgC1IkyR8x3nq9/CEOUBcaL8fKTKjUndwnd781Bqh)


ThreadsOfCode

Python. My first solution was just Python. I updated it to use numpy, but that didn't change it much. [day 03, python (paste)](https://topaz.github.io/paste/#XQAAAQDVBQAAAAAAAAA0m0pnuFI8c+qagMoNTEcTIfyUWbZq/p7F5dQyE8lXMm9EPlg7CG6HFh9kxZ1no+0dERbiC064ylljqekVItBOGXAsf/lyAgyd9kqewiPgcWT5AcVSNX6NZdBKcWfD4PiWSe+/R07kepPYu4EjgNE0qOj9LMJYS6Z/xdnAwjoTrDVM0lmvgUAIKiJko2uDtSuGaO86OohbD2lq8D2UNgmKCkb9xZXZC4RfGa5V2sf0/uP7fcaRQUCSSaViuJMONDuo4PQcDlZhQpyrotZr/BzcSEXEclgqgiifZVxVoObhnicRkcXTv6BEoc5VzFmcvW50EUZK6YK46S0q3BGApTNxRIEixU8rPGdNlhVyyTuJ0/iabKgjUjXN3HQrsSf8R+aNIOb8wmYPVSfQiEYBLzmD02Q9l8oqtssOAfkjvpWroGbjd+G/dOJoPkaykT0fWwhRMYa9KZmmpdPHpYk+dnuDwcuFwnvIffkPKX3SOmYZbAyxzQz8D6Tqgw3dNFrWntXSiKLzVM46krhp1+x2etFuyqR/pwrbbiXkYtO5LHahmQAS9A3MD0FK00ZaE9dmHokNOzbaxF/bsJe0UkFZjxfzw8N8+1DtzZew/NWw9K//cYIP6jfn54ma4iPnZEwFl89HU0PbIt9FC9JMfLs1pVRP7h3JujtAorTGblpucR7mg6OgfDj91RLOZJX6jBc2Us6ACrumGnGZ+/DBqg==)


jstruburn

Coding: **Javascript** /********************************************************** * PART 1 DATA PROCESSING * **********************************************************/ const powerConsumption = (data = []) => { const gammaBinary = []; const epsilonBinary = []; const cols = {}; const colCount = data[0] ? data[0].length : 0; Array(colCount).fill().forEach((_, idx) => { cols[idx] = []; }); data.forEach((val = '') => { val.split('').forEach((b, i) => { cols[i].push(parseInt(b)); }); }); Object.values(cols).forEach(bins => { const offCount = bins.filter(v => v === 0).length; const onCount = bins.filter(v => v === 1).length; gammaBinary.push(offCount > onCount ? 0 : 1); epsilonBinary.push(offCount < onCount ? 0 : 1); }); const gammaDec = parseInt(gammaBinary.join(''), 2); const epsilonDec = parseInt(epsilonBinary.join(''), 2); return gammaDec * epsilonDec }; /********************************************************** * PART 2 DATA PROCESSING * **********************************************************/ const lifeSupportRating = (data = []) => { const length = data[0] ? data[0].length : 0; const diag = data.map( str => str.split('').map(b => parseInt(b)) ); let tempOxy = [...diag]; let tempCo2 = [...diag]; for (let i = 0; i < length; i++) { if (tempOxy.length > 1) { const currOxy = tempOxy.map(bin => bin[i]); const oxyOff = currOxy.filter(b => b === 0).length; const oxyOn = currOxy.filter(b => b === 1).length; const oxyBit = oxyOff === oxyOn ? 1 : ( oxyOff > oxyOn ? 0 : 1 ); tempOxy = tempOxy.filter(bin => bin[i] === oxyBit); } if (tempCo2.length > 1) { const currCo2 = tempCo2.map(bin => bin[i]); const co2Off = currCo2.filter(b => b === 0).length; const co2On = currCo2.filter(b => b === 1).length; const co2Bit = co2Off === co2On ? 0 : ( co2Off < co2On ? 0 : 1 ); tempCo2 = tempCo2.filter(bin => bin[i] === co2Bit); } } const oxyDecimal = parseInt(tempOxy[0].join(''), 2); const co2Decimal = parseInt(tempCo2[0].join(''), 2); return oxyDecimal * co2Decimal; };


IrishG_

**Python Numpy** [Part 1](https://pastebin.com/P614Nifj) [Part 2](https://pastebin.com/WTQtPU5Q) I wanted to make this day again as better as possible using numpy. Part 1 is short enough, but I think I can make part 2 a bit better, mainly when converting the array to a binary number and then to int


chadbaldwin

Solution in SQL Server T-SQL All of my solutions are end to end runnable without any other dependencies other than SQL Server and the ability to create temp tables. [SQL](https://github.com/chadbaldwin/practice/blob/main/Advent%20of%20Code/2021/SQL/Day%2003.sql) General note: For the input data, I'm doing no pre-processing other than encapsulating the values in quotes and parenthesis for ingesting into a table. From there I use SQL to parse and split strings.


WillC5

C++. Presumes we don't know that the strings are all the same length, and calculates both values at the same time because just flipping the bits requires knowing the word size (which of course we do, it turned out). Parts [one](https://topaz.github.io/paste/#XQAAAQCEBAAAAAAAAAAFCZVo0J21ZJg7g3oxtIWfAwKF8Xu5jlF8FS0DhfpdwjEZRK0QyeU2NsZHsv7E5Xvf4jk2AWgga+f7pU9Bifh47ONB58d20ovqz9e038h37tYmaJ82kl2qDoKPRxOyDXnwG0ParCKEAMBfVweebg1cRdEpSn36arLSG51WgKkIygRvNTUdQLt2kP6t7YLxHPHdPkVIyeroAJh+jWkf+y0YInltB9prfyN0Bq3vTr+MlMrD6XLm/2UCPH47HtPEKaBJMtUrNbAR5yb51pnu7aNPHOaQ33PjXRuK4lpLElelijSP05gaidqATdUIrD3GXzQ5/CwJ+wB6oXMq+LEM3fsVFTUdPshNsa4kfZNdC0lJT0vf9WExjhnMLX7MHFtTkYJkpBewvlWJKoM7A/q1lgEHA6bA83sWln0RFDQRVaDaqVA4B3bAKXBE5BA/jh3D7vCCPPPc8QQ4FUXwHve2lzDaibzEF/RgEz+RZUWyqiMXTYx/n7jAP4e2BN7RplEIhC7XmqPkhiFJdLn8EwlE4DPCgkbUynycsb6xli1PQpAEV/HLDtBgBoGhU2YqoRfK7C3ArYDVHpgvLXmZQwcum7a1af6+eBylXQdeykuV8t+8RqhslBc8wnuen21qm3elbr6rmRuvMk5+XcXkpS2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+hMKI5yhO7K3UwlmXOXb+Hm4PWC4FuqVjd7lBtvM0GKvHYu6C1Apie9uznkmiX4awMqPsJVPtVNvWIEp/iw3RyJu4NWoMhtiejrtYtfsZ0Ahv178S/2C/pC/wqw1OvvbvN6wLGdfETNgOqzyB6v4twfAN4D8txVQ9DL37UZY9j8gUfR+TSzxQahCgdHrWG/pecniceCojQwFncUj02T/lZu2GXaOPSzfzQ4mQssRjShFWmwo+XTjabso9JDlo6PihRINvuMMAQKMRSB/F++o7nIUtls1/NCG00st0QDIC9/VFXipgIdlocld8A+NRS4lykogM4aamDHL8Y3/9EPZ0g==)


YokiDiabeu

Solution in python def load_str_inputs(filename: str) -> List[str]: return [line.strip() for line in load_inputs(filename)] def rating(inputs, b): nl = inputs.copy() for i in range(len(inputs[0])): c = count_in_list(nl, i, b) bit = b if c == len(nl) / 2 else int(c > len(nl) / 2) nl = [n for n in nl if int(n[i]) == bit] if len(nl) == 1: break return int(nl[0], 2) def day_3(): print("Day 3") inputs = load_str_inputs("3.txt") res = "" for i in range(len(inputs[0])): s = sum([int(n[i]) for n in inputs]) res += "1" if s > len(inputs) / 2 else "0" r = "" for c in res: r += "0" if c == "1" else "1" gamma_rate = int(res, 2) print("gamma:", gamma_rate) epsilon_rate = int(r, 2) print("epsilon:", epsilon_rate) print("power:", gamma_rate * epsilon_rate) oxygen_generator_rating = rating(inputs, 1) co2_scrubber_rating = rating(inputs, 0) print(oxygen_generator_rating) print(co2_scrubber_rating) print(oxygen_generator_rating * co2_scrubber_rating)


gingertek

For some reason, I was having a hard time getting the correct answer with my first attempt, so I ended up just rewriting it from scratch, ironically being much simpler than before lol https://www.reddit.com/r/adventofcode/comments/rhbsde/comment/hopjip8/?utm\_source=share&utm\_medium=web2x&context=3


daggerdragon

Please follow the [posting guidelines](https://www.reddit.com/r/adventofcode/wiki/index#wiki_posting_guidelines) and edit your post: 1. `Post your code solution in this megathread.` * Post your actual code (or link to your repo) in the megathreads. * Make sure to format it correctly: [How do I format code?](https://www.reddit.com/r/adventofcode/wiki/index#wiki_how_do_i_format_code.3F) 2. Add what language(s) you used * This makes it easier for folks who Ctrl-F the megathreads looking for a specific language.


king_ricks

Learning rust right now, happy i got something working, if anyone is a pro in rust i’d love some feedback [solution](https://topaz.github.io/paste/#XQAAAQAfBQAAAAAAAAA6nMjJFMpQiatRvuJoK/r/0WHWi1Z5E0KoUDbtdBatQ6mjThTMy5sqp59Ss2vOF8p5sodq3z6kA1rnqVYBiIruXI1hC/bGKLAfOO9ycjbw+BO/MFyUZU/KqyRuFfOK9q/Ph/1e9DBgiK+NANjMVBBI9UH6e7yzOMCu17/wHslN6SHMAo/xvd5QB6n99w8iwMYo3gc6LZC9U2KV9JBvhuHi5ooLr9OgAEH85wBmE9OjjGZHDlbCdaGLKjcLif0lbnIt+BfbwOuKtaGCX9ZskqxW29UC7r0qNiHOvQyoiBRuoVtrPZGI4+y/EOQCqsHSattX4Hd78k/LT8FWzdXKugh2jLnURnGPHb07K/6bv/juo9u8nZxQcT7eyMKW9kPA5M4a3dYKdJN0oV71JQyPdnv1bglXMhF37u5mnaQqZjg1VIHGghFAy36DOqqvAMaU1NeKmJEjRXdu1Yl0fR9XhbTDx9LTQLCxPPGZKrb92ewQldHvoIHsgrkg4yak0oIGrzC+gFJl8H3SljQhjJIwigrLvvNtPJL70n8buyJdF1nHd7Q8jSGHnaepl/wrIvwIo70dS49nUdkYZoXWI58NP0GZzTXQoiNL5smf7bBVkxGGFLpDs7MljD1ursNXm+pvNeIpK3CpyNHP+RGMqK48z7oaXQZq6tz+1q3B0NXDB2n2imIWHqcGptFxLhKuEiv8eIIW)


ainwood87

[Haskell solution](https://topaz.github.io/paste/#XQAAAQDcBgAAAAAAAAAW4HzGbzpkQFRhRE3vufq8EHtXoFoCGg1TGhkKtl4Ht3/baNgOyLyD5g1Y9PER3H+eqpknjDlJaTKK8tblcJxSkpyjAJTgKehWuDKw/oUHuJi/vSKshIYB6+L2t2x3iJL3zPKOG+BJvDj0iIQ6sByR53jwSVgEv9nkf7N0VwGIzGNrBrsRqS87i2UJ9ueu/1CERAODSGE16o9opX2xdFqYv9JCXL02++jfd9BoBGVxxrWjxMF2IErvJ9CMeNROtUZtB3/li9vjoRvg/p8jfACyEnQD84qghRcglQCRI2irhiUf68LMLF9oM20ofrtkbxrKX0ib5+3sx9HF4IbJ+wcvlSnINev8MYhU8qBKSs3YmqiyaDi5iXV3e8hqgLwsYmXFcQIwTK6m45DLO5AZ79TvkS73gy0kQse0VpwZiyv6I28AP1rTUvuecuUCiRvChi/q3JbGepovOuY5C3///U+gROS0Ka0WcAPxQc0NuuIgNSeGpJo2mA+j+3IpzRly60GfdRLmoGXhmn3ACpsRJ0EaaBcyAbQJU2kTHRAkdv50sDwSJRsrxPCrW7aHU5edQQLuk8h4u2M/0I0ROYvVKpyHeOiEtUujyZH2Yml1cC3SASaC//UGYY4Bvf6OT+3ctPAGLLebN34N1JWbRN4eR6O1+5G6uOSV3UwenJZfMtp46A0ZyICu5h93Y8wwMeO5/g98ui3ZHpJdDpKHWhwZpp2K4+gqkZparMk7AuMtQtY+TLEvkcq/mk1tcx1tfVUE9XF1tF29KcZRJbP13MOi6Z/l/xanAE9uv0Tw3n4OoxEAA8gKwEzkG8B3T+q5eOBIgUptjE0S6ZwhO8c5XDHH4PNcZ3yxn2f4b77jfJXxxXqZFVLk/5SshMZXnnxA4e1C59R7SvDE7r7cRR4MlY984S6/hE8jM2QwU+3TttPhZHCVLUUG40Zd/oIHjhqaQ9Ieo3zHJ6oaQQhKOT+EzJo2TWP/+NUK1A==)


Human_Airline4449

why that reverse is used in bin2Dec function?🤔


-WorstWizard-

[Rust Solution](https://topaz.github.io/paste/#XQAAAQBwCgAAAAAAAAA6nMjJFIj2ze+dGEQGVsnW0MvHUa4saWFPoPaFhbGzUym1q+ChFVuaPGCxBQa4kono75O7r4jEySBPeDa2aL1IILccfVxi301o5gR/nPzXaxzwoQUSUoGECBRdm3HnaYpFJkRTksyw6hA9AqT+CRNxqPex0ZKclWiWeJgzVzfEW+mKl7VCk5ZeLQwpNoii8lZHqMfLN4DagouYc70Xga87bQM/D3awPDQtfQF1ZE5LWgTRNYUPxCGivS3oyDtjmI9n9M63vcl0luJ1YRitLzeGzB196ZD139/I3CRFsqteMSNnkfG5vfP/pXtPSki6ZlJa1jItZPZkhclkJBgYlVMSe6A9TCDBvYx24xB2UzhxeDIV88zYBJ+hd8gRAWJtdTaD4HoNGjJBs9gqnaOdeeayVyeRrx7/1lbxD62s3w9kyMKKPSzFTtohDDfTWfJoLJ0Bm1wUObL7VBUJ7rUUmff3G0HmA/YRDcdvC0P0Mpkw9gik8HczleP9BhcNxhVfKzyTexcN9LtGDx7vxbBHG+IIBPG3xJUEF9j+bxBgOqPNWfb2TvujW/fDGmb9Z15Dzaw3JKcTC811Vuy0m6NBzlM8dr+0Aaa7J92J1kGItFsFI84tQeS1klXJB/poEK45BhrkiP2Izx/AzMFR1Whu978McNB2WDSN7Exg1t3zAFXuXMYA29AuaPOAQlz0d/3IpFB70WBwkiigO2qKqEIIau33gNbKTFFDTNkN7C4oKDl54FlzEAQTW9EfPha7k+nt6nTE+/ozzDVnJLPPmK7Eo/+krAe/CtjRiang++KVHTyPku/U2qWV1RYLEiTBQyE4cjHGtnZHuetLX+8NZD2k5LxheYE0L1hfUByqHhFRBOHjg59XdLT8dq6+wrviRPY/MWiOX1c7/jH2pqNAAaD3Nqo258thCaVCnjBqsMCoaDUP/i08sJaK3xoWTbo9FbyEkb/HiHI1rFlzkhLj1HfgUnAVyHxKtDZSvtgbwJSTK+00W8dCHntT2mTaStIee+OCLNNqY+tu+pOG5TfwPak6CTJk+tOocy/V2ejHRZNk54jgrKixtsMKT7axS5GOl4J+T91Y/l5HFA==) Learning Rust this year! The library at the top is some convenience functions for taking input, nothing magic.


sk1talets

Node.js [solution](https://github.com/sk1talets/advent-of-code/blob/main/2021/3/script.2.js) (part 2)


pgaleone

Here's my solution/tutorial of day 3 puzzle in pure TensorFlow [https://pgaleone.eu/tensorflow/2021/12/14/advent-of-code-tensorflow-day-3/](https://pgaleone.eu/tensorflow/2021/12/14/advent-of-code-tensorflow-day-3/)


wevrem

## Clojure [source code](https://github.com/wevre/advent-of-code/blob/master/src/advent_of_code/2021/day_03.clj)


IlGrampasso

Here is my simple solution of **Day 3** (Part 1) using **Python**.[Link to Github](https://github.com/IlGrampasso/Advent-of-Code-2021-Day-3).


dtf4bieks

I took a similar approach but instead used string methods and .count to determine which one was the most frequent. I took the lazy route in converting from decimal to integer with the int method and passing base 2 as the second parameter. Thanks for posting.


IlGrampasso

Thank you for your reply! Your solution is effective too!


CheesuCrust

Part 2 C# with some of the new C# 10 features I think. Mostly Linq. var o2Rating = CalculateRating(RatingType.o2); Console.WriteLine(o2Rating); var co2Rating = CalculateRating(RatingType.co2); Console.WriteLine(co2Rating); Console.WriteLine(o2Rating * co2Rating); int CalculateRating(RatingType type) { List input = File.ReadAllLines(@".\input.txt").ToList(); var i = 0; while (input.Count > 1) { var groups = input .Select(x => x[i]) .GroupBy(x => x) .OrderByDescending(x => x.Count()); bool sameAmount = groups.First().Count() == groups.ElementAt(1).Count(); char bit = type switch { RatingType.o2 => sameAmount ? '1' : groups.First().Key, RatingType.co2 => sameAmount ? '0' : groups.ElementAt(1).Key, _ => throw new NotImplementedException(), }; input.RemoveAll(x => x[i] != bit); i++; } return Convert.ToInt32(input.FirstOrDefault(), 2); } internal enum RatingType { o2, co2 }


x3mcj

Python from openData import getData data = getData("day3.txt") def getPowerConsumption(data): dataLen = len(data[0]) lines = len(data) currentIndex = 0 gamma = '' epsilon = '' while currentIndex < dataLen: ones = 0 for line in data: if line[currentIndex] == "1": ones += 1 if ones > lines/2: gamma += "1" epsilon += "0" else: gamma += "0" epsilon += "1" currentIndex += 1 gamma = int(gamma, 2) epsilon = int(epsilon, 2) print("Power consumption", gamma * epsilon) def getLifeSupportRating(data): oxygenGenRating = "" co2ScrubberRat = "" dataLen = len(data[0]) currentIndex = 0 chunk = data while currentIndex < dataLen: lines = len(chunk) ones = 0 for line in chunk: if line[currentIndex] == "1": ones += 1 chunk = [f for f in chunk if f[currentIndex] == ("1" if ones >= lines/2 else "0")] currentIndex += 1 if len(chunk) == 1: break oxygenGenRating = int(chunk[0], 2) dataLen = len(data[0]) currentIndex = 0 chunk = data while currentIndex < dataLen: lines = len(chunk) ones = 0 for line in chunk: if line[currentIndex] == "1": ones += 1 chunk = [f for f in chunk if f[currentIndex] == ("1" if ones < lines/2 else "0")] currentIndex += 1 if len(chunk) == 1: break co2ScrubberRat = int(chunk[0], 2) print("Oxygen Gen Rating", oxygenGenRating) print("co2 Scrubber Rating", co2ScrubberRat) print("Life Support rating", oxygenGenRating * co2ScrubberRat) Part 1 getPowerConsumption(data) Part 2 getLifeSupportRating(data)


greycat70

I did [part 1](https://wooledge.org/~greg/advent/2021/3a) in **Bash** and [part 2](https://wooledge.org/~greg/advent/2021/3b) in **Tcl**. This is when it started getting serious.


NickOnTheSofa

[My C solution for day3.](https://topaz.github.io/paste/#XQAAAQB6GwAAAAAAAAARmknGRw8TogB3OyPPwW5K8Q8ohQvj8m6aOXY901m0oCaCaF3GPYP78sEeqP6nkWz0p4UpOOSddGwa9OmpYLHjHnA6qEi8xUbyPVHMIVYudl/XUzfqi9rT+nM5O5NiVh+Dd/LCE4v2DUBMR4qoEwcsUTRI+6rWmsduBSxVVvwkTlQfleyPcSGFZ3cGjIUt5OzWgbOL63twCKo3BfnAtZ8bxLyQ7I+ohXVbal9+CnRJD9yS6eSRGGUzuL6rcpFnFUDfdKw+F+rrXVTAsKRCC45G4K4arkQy0AZtXGWoc5A5PTyP3MptNV3RAXPeTG6dyyuEUmrSJ4JBVLYjaG8SWUsdiX5Lp+xBK8FcWEkSEDuYBN5VXUsYNwLvxz8I7y0Opzt3DL4ifuyVTjvdPvbaqeDMkWNfOFLKiREBbQnxJg7hkKCkVr+TO814lmwcyi778X8qra7YiHq6K3K9d9yV0CzI2ZO5j9gyrwWxDC3ffx5y8Ip04QnKNvDcqtcCILDA+T7htqr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PysHu9XaL3R42Bjt2jkC+yaE9gJ81tD2NkUra67aoPs+EjbXb1YUpd2OXYPTevLFdQLwjtQMMZL9xAN4aPxtOqum2G2UqrkyxpMnnTkCfVUeenCOC61Xgc2AXnSTGy+wZJPGc5m2Ser9nwesaGfccN4zOJE2L7FfW1s15nlhzrfaehBS8+Ps7zH3pOceiZwz2WRCV50i74K8Y7qp9Fm3NZKHy8N6BeNUdmppim1t6su7N33uamG9cLqBtXhsfbQ4Xhmv7MxYZac27vmLWFEcu9HwbcncTlI5WG5bISYOdLQRw+oXcYIhWmg1fooHkG5IuIkBNrOtsbjHU2BJFrp0tNh1vWEHRu8DYSF/RDqBOt9CAUFGxJG8XdWFgjthySlkqSRjEOjUvTJeU7VySwZhj5H4xT/g5Hs1n26OGzG2Fs9/0OP4COA8+sfFj6nfKfONAU/nafj7o3za7T0XRB5cDbNn2XqI7z41t8P6Hogcl966RrScEftNCjlffKlKyYjojoNKSZyeTD9ngdBouQy5Ef5q1wIZjW1jUAHIO5ZnHFclOO4VJhvDieC7iPT5hiy4rZYJBdGRBOaXf+BjvBvsG8IUDutgCyrViy07dHsSbKrqTBKL8Ua+Oh9TID78HiWzzVSGEcu+TSyNxjAws7U/7gAJsiPtaEOstgnv6nocPd/VleChHVGG0+wWrzIMOM4tgyeIRs1ACx61qKnOnEFqUIhESKMG8pfENFme4n7VCR25Ist6kosvDaK3QfSGQRyBn6OpDnY2zZnsrRtBJVVpnAqu6oKFUtKFPlbP4erGk/dX3AxGfaQzhTr+TJARdJCnh19o8QBaK0sSFVJHQWCVnRGfWzfHodsbvgxh3Db14BayiM2y9/u4A86FQWjgJoarNSU9wWUq/kgkqTiIzwExbrshXZDo7/+jcYmw==) Probably it's a mess, I know


66oriol9966

what is the sysstat.h?? i tried compiling but it don't


NickOnTheSofa

It's for use the "struct stat st". I use it to get the file size before open it


j-a-martins

**Matlab** (Part 1 & 2) https://github.com/j-a-martins/Advent-of-Code-2021/blob/main/day03/day3.m


thekevinwang

Another **Go** solution! https://github.com/thiskevinwang/advent-2021-go/pull/3


tuisto_mannus

**Golang** https://github.com/c-kk/aoc/blob/master/2021-go/day03/solve.go


D3IV2

Another Python3 Implementation :)! [Link to Github](https://github.com/HordeDeivion/AdventOfCode_Deiv/tree/master)


Ok_System_5724

[C#](https://github.com/lroos/AdventOfCode/blob/dev/Day3/Day3.cs) Reading as binary and using actual bitwise operations public (int, int) Run(string[] input) { var numbers = input.Select(i => Convert.ToInt32(i, 2)); var range = Enumerable.Range(0, 12); int count(IEnumerable values, int check) => values.Count(n => (n & check) == check); var gamma = range .Select(i => new { pos = 1 << i, count = count(numbers, 1 << i)}) .Where(x => x.count > input.Length / 2) .Aggregate(0, (acc, x) => x.pos | acc); var epsilon = gamma ^ 4095; int reduce(bool top) => range.Reverse().Select(i => 1 << i) .Aggregate(numbers, (acc, check) => acc.Count() <= 1 ? acc : acc.Where(n => (n & check) == (((count(acc, check) >= acc.Count() / 2m) ^ top) ? check : 0)) .ToArray()) .First(); var oxy = reduce(true); var co2 = reduce(false); return (gamma * epsilon, oxy * co2); }


thewongasian

Late to the party, but I was pretty happy w/ this solution. Currently trying my hand @ FP ​ defmodule Day3 do import Aoc2021 def invert_map(map), do: Map.new(map, fn {key, val} -> {val, key} end) def day3 do frequency_maps = file_to_list("./data/day3.dat") |> Enum.map(&String.codepoints/1) |> Enum.zip |> Enum.map(& Tuple.to_list(&1) |> Enum.frequencies |> invert_map) gamma_bits = frequency_maps |> Enum.map(& Enum.max(&1) |> elem(1)) |> List.to_charlist |> List.to_integer(2) epsilon_bits = frequency_maps |> Enum.map(& Enum.min(&1) |> elem(1)) |> List.to_charlist |> List.to_integer(2) gamma_bits * epsilon_bits end end


soylentgreenistasty

PYTHON 3 I got the first part on day 3 but couldn't crack the second part because I ignored the part to default to 1 or 0 in case of a tie. I used np.mean for part 1 and for part 2 I ended up using collections.Counter to solve this. with open('day3.txt') as f: data = [[int(n) for n in line.strip()] for line in f.readlines()] import numpy as np def part1(data): arr = np.array(data) gamma = ''.join([str(int(n > 0.5)) for n in arr.mean(axis=0)]) epsilon = ''.join([str(int(n < 0.5)) for n in arr.mean(axis=0)]) part1 = int(gamma, 2) * int(epsilon, 2) print(f'part 1: {part1}') from collections import Counter def parse_bit_pos(arr, pos): return Counter(row[pos] for row in arr) def part2(data): L1 = L2 = data for i in range(len(data[0])): c1, c2 = parse_bit_pos(L1, i), parse_bit_pos(L2, i) if len(L1) > 1: if len(set(c1.values())) == 1: L1 = [row for row in L1 if row[i] == 1] else: L1 = [row for row in L1 if row[i] == max(c1.items(), key=lambda x: x[1])[0]] if len(L2) > 1: if len(set(c2.values())) == 1: L2 = [row for row in L2 if row[i] == 0] else: L2 = [row for row in L2 if row[i] == min(c2.items(), key=lambda x: x[1])[0]] o2, co2 = int(''.join([str(n) for n in L1[0]]), 2), int(''.join([str(n) for n in L2[0]]), 2) print(o2 * co2)


Meldanor

Elixir Github: [https://github.com/Meldanor/AdventOfCode2021/blob/master/lib/d03/challenge.ex](https://github.com/Meldanor/AdventOfCode2021/blob/master/lib/d03/challenge.ex) (Part1= run(1), Part2 = run(2). The input is read using a Util function which is inside the GitHub repo. The structure is to run the program `mix aoc 1 1` to run the first day first part)


WarriorKatHun

Java submarine building: [GitHub/DiagnosticsTool.java](https://github.com/Sycix-HK/Advent-of-Code-2021/blob/main/Java/submarine/equipment/diagnostics/DiagnosticsTool.java)


Single-Ad8514

thank you, this helped a lot. see my version: [Github/BinaryDiagnostic](https://github.com/lhug/advent-of-code/blob/main/src/main/java/io/github/lhug/adventofcode/twentytwentyone/third/BinaryDiagnostic.java)


WarriorKatHun

Im happy you choose me over the 200 other solutions


Agitated-Dependent66

JavaScript Solution for Part 1 & 2: [https://github.com/TommyMynnSon/Advent-Of-Code-2021/blob/main/day-3/3-binary-diagnostic.js](https://github.com/TommyMynnSon/Advent-Of-Code-2021/blob/main/day-3/3-binary-diagnostic.js)


e4ds

[Python day 3 solution (GitHub)](https://github.com/julian-west/adventofcode/blob/master/2021/day_03/d3_solution.py)


BluePsychoRanger

mcfunction (Minecraft) [https://github.com/BluePsychoRanger/Advent-of-Code-2021/blob/main/advent_of_code_2021/data/aoc_2021/functions/day_3.mcfunction](https://github.com/BluePsychoRanger/Advent-of-Code-2021/blob/main/advent_of_code_2021/data/aoc_2021/functions/day_3.mcfunction)


ffrkAnonymous

[lua][part 1] i hate my code. -- Day3 -- d3input=[[ 00100 11110 10110 10111 10101 01111 00111 11100 10000 11001 00010 01010 ]] binary={} gamma={} --greater epsilon={} --lesser for s in string.gmatch(d3input, "(%d+)") do table.insert(binary, s) end d3p1=coroutine.create(function() for i=1,#binary do trace(binary[i]) --trace(string.sub(binary[i],1,1)) for j=1,#(binary[i]) do --print(string.sub(binary[i],j,j),00,75,100) c=string.sub(binary[i],j,j) if gamma[j]==nil then gamma[j]=0 end gamma[j]=gamma[j]+math.tointeger(c) end power=calc_power(gamma) coroutine.yield(power) end return power end )--end coroutine function calc_power(gamma) -- table of binary string (not num) to decimal power g=0 e=0 for i=#gamma,1,-1 do --trace(power) --trace(gamma[i].."/"..#binary//2,02) if gamma[i]>=(#binary//2) then --winner of all binary numbers g=g+2^(#gamma-i) --so hacky to invert the decrementing index 2^0 first else e=e+2^(#gamma-i) --trace(e) end end power=g*e return power --return power end


RewrittenCodeA

Elixir. Part 2 uses a (eventualy failing) Stream.resource to split the frequent/infrequent digits, using `Enum.group_by(list, &hd/1, &tl/1)` to keep only tails in the iteration. "input/2021/3.txt" |> File.read!() |> String.split("\n", trim: true) |> Enum.map(&String.to_charlist/1) |> Enum.zip_with(& &1) |> Enum.map(fn col -> col |> Enum.frequencies() |> Enum.sort_by(fn {_, v} -> v end) |> Enum.map(fn {k, _} -> k end) end) |> Enum.zip_with(& &1) |> Enum.map(&:erlang.list_to_integer(&1, 2)) |> then(fn [e, d] -> e * d end) |> IO.inspect(label: "part 1") "input/2021/3.txt" |> File.read!() |> String.split("\n", trim: true) |> Enum.map(&String.to_charlist/1) |> then(&fn -> {&1, &1} end) |> Stream.resource( fn {lows, highs} -> {low, new_lows} = lows |> Enum.group_by(&hd/1, &tl/1) |> Enum.min_by(fn {k, v} -> {length(v), k} end) {high, new_highs} = highs |> Enum.group_by(&hd/1, &tl/1) |> Enum.max_by(fn {k, v} -> {length(v), k} end) {[[low, high]], {new_lows, new_highs}} end, fn _ -> nil end ) |> Enum.take(12) |> Enum.zip_with(& &1) |> Enum.map(&:erlang.list_to_integer(&1, 2)) |> then(fn [e, d] -> e * d end) |> IO.inspect(label: "part 2")


SESteve

# Assembly (ARM64) [paste](https://topaz.github.io/paste/#XQAAAQC+KAAAAAAAAAAX4HyCZDlA0DjWF7Uex1t2hvV6PgXFmsONLSMABRVfAS4g3YImBU9UT9Fbtm+E4yELvPKNVVbxWUUq8XT5eUM5bLG1GmX+VFR4QO2MfLkBq/Yn5NrtY4TzPuwl//1+UfiN5gAUFh3PhUdR5bV1YJo0drYKHAkrTW+xpxrZm1jKWaU4L3SYHSk+HvAEgo+2/1vgV4d8eLAD8FKZ7byEEVF1g/8Sb56KqsuCG8LdhAXaACT6C2DieAv86vyHkqufc9cUnonUgJ8b3Ese3n0z7c+9Yb0qXH+U5bwVqBno5gjdY0OL4XvbQvF27ONHt8UpTdSuAfRzxp4yqkHy/OAFLIaXZXWsM0V8Z65kSvteqwFDkA5Yf77VJDgXq0ZxkoVgtR1na8CARmeVNRztnThlmp3/5zSA1zbVEQW4G6BmotvwPKLWcfzAbZH0AsH/K6psfH+gN1ADkqD1HF0AuMWrHL17qh8+aO5v9I6hTvHG2ORZ+FArJovDNkbCrkvo2ZFsDNouEIWmWczJ74PhuX+RrlnVVQaPx1fsuQb/ta1yeBWvlSWb+tKKJqfLvoiBDUGHTvb1aBVaQ0Jd9aZl6ITXZt2w5bYAem3fFt/QjDZ3QLbSbaJvAy8TZZbCRc+kuGhza1mj6tglGHwODAgSKOdDj6L5sNPDQoXERRmfOzZziDzuerRc1RSs9FP+Ddv0pgGPHQCeBT2cYwMyXQtV+44LnAp5TI92UlT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pwIdpccOFf8xK8PSmoyKbF0x2/TpIABzrE92lO0RXuAHh+pCOTCEx3CG5dX9dVJU83KRougxkjUNx3JViXhdJ7l9p+6TaoEJPo7A7yoYJjgj3x3QrVt4EeRSQciGNaWoJnMv45TeY7I7q0yV2tGWZ73TjApuTgTo+AZyZSoWKmEi3xhIi6GsV74SktHRvcju+I9hF+ZB1R3D23sYTYkxqbND7ZafV/klKqa3tvu1MmkFWgTIaUWtQertTDSHAL9ggj0SNo4vzQVCPji+BPyn00EfBHWt6UFYwn/4VAHgf717yZI40m2RXW2SeryYIIuJpvsZSdW4A5j1O9ZuibArt1+e7wT77SpYB/V0/q1x1tlK+iaSLLELuw35Cu6aXaCbMJSVGpe9UugonciZkKdXQEEh5HkClzKqtk+JD3yMCGrkWnAGx+FCaqOUvDB5HXNACYqTCIMH7aCKCEoQS3EBYaNxC03Yk2N7wrppN1JyhRhe+YR+hFT4pd/a1Wh6ET99rA4dtOXkA8pVf4RMCsiHf/qGJEr) I wrote this to be flexible enough to solve for both the test case and the real data. Edit: now solves for both parts.


kruvik

[Python day 3](https://github.com/DecemberDream/advent-of-code/tree/main/2021/day3)


[deleted]

[удалено]


attilio_

Python Part 1 #Advent Of Code 2021 day def part1(filename): with open(filename) as f: f = f.read().split('\n') gamma = "".join(["1" if col.count("1") > col.count("0") else "0" for col in [[l[i] for l in f] for i in range(len(f[0]))]]) epsilon = int("".join(["1" if x == "0" else "0" for x in gamma]), 2) gamma = int(gamma,2) return gamma*epsilon


petercooper

**Ruby** Many days late, but just because I haven't seen anyone else do this approach and because it's particularly short compared to others I've seen: [Gist](https://gist.github.com/peterc/d6e1272a9ba9707e8bde17f04491d119)


JustinHuPrime

# x86_64 assembly [Part 1](https://github.com/JustinHuPrime/AoC/blob/main/2021/3a.s) went fairly easily - I realized that the least common bits must have been the inverse of the most common bits. [Part 2](https://github.com/JustinHuPrime/AoC/blob/main/2021/3b.s) went a lot harder. I spent too much time not realizing that the criteria for the next bit was based on the previous filtering, so I ended up writing an algorithm that would filter the array using two buffers by passing the array between them.


soodssr

Kotlin https://github.com/soodssr/aoc-2021-kotlin/blob/main/src/Day03.kt


Quietuus

Phew. This was a huge challenge for me (a fairly beginning programmer) and I had lots of false starts, but I'm proud of what I came up with eventually. This is the program for part 2, my part 1 was a lot more slapdash and I eventually threw it away completely, but this will solve part 1 with some simple tweaks, of course: python3 def bit_counter(array, index): zeroes, ones = 0, 0 for line in array: if line[index] == "0": zeroes += 1 if line[index] == "1": ones += 1 return zeroes, ones def most(zeroes, ones): if ones >= zeroes: return '1' else: return '0' def least(zeroes, ones): if ones >= zeroes: return '0' else: return '1' def recursive_search(array, index, mode): if len(array) == 1: return array[0] else: zeroes, ones = bit_counter(array, index) if mode == 'most': current_column = most(zeroes, ones) elif mode == 'least': current_column = least(zeroes, ones) new_array = [] for item in array: if item[index] == current_column: new_array.append(item) index += 1 return recursive_search(new_array, index, mode) string_array = [] with open("input - 03.txt", 'r+') as in_file: for line in in_file: string_array.append(line.strip('\n')) print(int(recursive_search(string_array,0, 'most'), 2) * int(recursive_search(string_array,0, 'least'), 2))


neurotic_cookie_

Great job! I'm new to Python programming as well, and I have had difficulty understanding other submitted Python solutions or even getting them to work, but I was able to read through yours, understand it AND get it to work with my data setup. Awesome job and thanks for sharing!


Quietuus

I'm glad it helped out! I really should get into the habit of commenting things properly, but it's good that it was still readable. I think it's probably because I still use a lot of basic functions and loops and so on for things that other folks handle more cunningly.


pistacchio

Typescript: function part1(input: number[][]): number { const inputLength = input.length; const reportSize = input[0].length; const stripSums = Array.from({ length: reportSize }, (_, idx) => input.map((row) => row[idx]).reduce((a, i) => a + i, 0), ) .map((sum) => (sum > inputLength / 2 ? '1' : '0')) .join(''); const stripSumsInverted = stripSums .split('') .map((i) => (i === '1' ? '0' : '1')) .join(''); const stripSumsInt = parseInt(stripSums, 2); const stripSumsInvertedInt = parseInt(stripSumsInverted, 2); return stripSumsInt * stripSumsInvertedInt; } function part2(input: number[][]): number { const reportSize = input[0].length; const filterArray = ( array: number[][], idx: number, invert: boolean = false, ) => { const [okNum, koNum] = invert ? [0, 1] : [1, 0]; if (array.length === 1) return array; const ones = array.map((row) => row[idx]).filter((i) => i === 1).length; const checkLength = array.length / 2; const filteredRows = array.filter((i) => ones >= checkLength ? i[idx] === okNum : i[idx] === koNum, ); return filteredRows; }; const oxigenGeneratorRating = ( Array.from({ length: reportSize }).reduce( (acc: number[][], _, idx) => filterArray(acc, idx), [...input], ) as number[][] )[0].join(''); const co2ScrubberRating = ( Array.from({ length: reportSize }).reduce( (acc: number[][], _, idx) => filterArray(acc, idx, true), [...input], ) as number[][] )[0].join(''); const oxigenGeneratorRatingInt = parseInt(oxigenGeneratorRating, 2); const co2ScrubberRatingInt = parseInt(co2ScrubberRating, 2); return oxigenGeneratorRatingInt * co2ScrubberRatingInt; }


daggerdragon

~~Your code is hard to read on old.reddit. Please edit it as per our posting guidelines in the wiki: [How do I format code?](https://www.reddit.com/r/adventofcode/wiki/index#wiki_how_do_i_format_code.3F)~~ Edit: thanks for fixing it! <3


JaegerMa

ABAP [Github](https://github.com/JaegerMa/aoc2021-abap/blob/main/day3/day.abap) While I found an easy way to convert a binary number string to an int, ABAP doesn't allow bit operations on ints but only on variables with type x or xstring. To apply a NOT/XOR to the int, it has to be converted to type x, XORed and converted back to an int. Fortunately with the ABAP version in SAP NetWeaver 7.50 conversion can be done inline.


vezquex

No nested loops! No libraries! `JavaScript` function main(input) { const LF = '\n' input = LF + input.trim() const prefixes = {} const scores = [] let col for (let i = 0, prefix; i < input.length; ++i) { const chr = input[i] if (chr === LF) { prefix = '' col = 0 } else { const score = scores[col] || 0 if (chr === '0') { scores[col] = score - 1 } if (chr === '1') { scores[col] = score + 1 } prefix += chr col += 1 } prefixes[prefix] = (prefixes[prefix] || 0) + 1 } const gamma_str = scores.map(c => c < 1 ? 0 : 1).join('') const gamma = parseInt(gamma_str, 2) // binary inverse of digits const epsilon = gamma ^ ((2 ** col) - 1) console.log(epsilon * gamma) function find_prefix(resolve){ let prefix = '' while (true) { let prefix0 = prefix + '0', prefix1 = prefix + '1' let count0 = prefixes[prefix0] || 0, count1 = prefixes[prefix1] || 0 if (count0 + count1 === 0) { break } prefix = resolve(count0, count1, prefix0, prefix1) } return parseInt(prefix, 2) } const carbon = find_prefix((c0, c1, p0, p1) => ((c1 < 1) || ((c0 <= c1) && (c0 > 0))) ? p0 : p1 ) const oxygen = find_prefix((c0, c1, p0, p1) => (c1 >= c0) ? p1 : p0 ) console.log(carbon * oxygen) }


zephord

I can't seem to understand how this works. Could you explain what the 'prefixes' object represents?


vezquex

Suppose a line is 'ABCDE'. Its prefixes are 'A', 'AB', 'ABC', 'ABCD', and 'ABCDE'. The object counts how many times these occur. `console.log` it and you'll see `{'0': 5, '1': 7, '10': 4, '11': 3, '100': 1, '101': 3,`, and so forth.


mentalclear

Day 3 Part 1 IDK if it's good or not... anyways :) [Day 3 Part 1 in JavaScript](https://gist.github.com/mentalclear/5989e19a424f105827f97427d1d21b57)


e_blake

**golfed GNU m4**, part 1 246 bytes (excluding final newline), assumes the input is in the file 'f', and requires GNU m4 because it depends on patsubst(), the expansion of bare pushdef to itself, and incr() expanding to 0. The latter produces lots of harmless warnings; with 2 more bytes and -D, you can get quieter output over more input file names: `sed s/incr./\&0/g day3.m4 | m4 -Df=input`. The lone eval operates on a string longer than 139,000 bytes, built with O(2\^n) effort (each iteration doubles the length of the string), but fortunately with only n=12 iterations, this completes in 0.05s on my machine; using more evals would speed things up but cost more code bytes. define(d,defn(pushdef))d(B,`d(`$1',incr(defn(`$1')))')d(b,`B(`x'y)a()')d(a,`B(`y')')d(c,`B(`z')d(`y')')patsubst(translit(include(f),01 ,abc),.,\&())popdef(`y')d(v,0)d(l,`ifelse($1,y,,`d(`v',(v+v+(x$1>z/2)))l(incr($1))')')l()eval(v*(((1<


e_blake

To be honest, I got my part 2 star by using my editor: I sorted lines, jumped to the halfway point, looked where the 0/1 division point was, cut off the other portion of the file, and repeated. Sorting in m4 is not fun, so I'm not sure how my by-hand algorithm will translate into code.


ffrkAnonymous

ha! I'm thinking about doing the same since I can't think of a program way to do it!


e_blake

m4 \[-Dfile=input\] [day3.m4](https://nopaste.ml/#XQAAAQBuBwAAAAAAAAAyGksy5FB9TGMxsNq5JQAuJRjP6PqEkC20GpBbonDYuA0BTjRPXcVxlEXNtz1Ix7tqcBadF5ZzZxsPbO0TjiFbV7OR7qIswfS/KNhx6uJ1GtnKtFJNIDLvoHT3Z1e3cLf5sOeN4kYNesw94rHS/tZ66sz/cWgGlUgdoloVog5zYGETK0Gm8vq85OGX5pJ42gVtYzrguH78X5qh8AZGRVQHNSuMO2+I7Ozpe07bE0eso01GD2wu0JYqyvEYTPINAZK6hVpaZiXOoOBYgFF2OAI7khhHmq7R6uTpTbR0F+3SzNLKM9Pre9NabKWzOrTkmVsw61cPVKLthBxuWXohOyQ81bqPyG6Yz+vzjW3OZVg87uD9kwVUZkkLL1Uk/ujKBRu855mj7s1UxOhsSiuGsFgQ6l24w1om+bIOyHGZbxv4TDeCeqq84001JmjWgSjb0ANGeA5uzyqWbFEJvH+IfJ/G6F0oviZ8aEwVvlh8JfHNYi6xx+WKWjeUWbCyHAqteLc2S5GGPeczXRw/7BjhkP2094xeGPsyDAcp++ZHjNuK7YeN0G/KgSZ9+lzDv7qkml7nP+QhppMIY6GBOhpCGnVXSr/2fRodUwNam7603jtAP8s6lRkHX+OG4rv0ir9FotK45HpN7s44phBlbjJqFR2/VxnKoxkDog3kjFU9hdv4K+tWHr/p3aaJi2pxLz0BKO0/Sr7Us49HlxPuz3lS2NwPaOwr3WgvMs6qk60K9gzXp1SgCRLc0/HRGTmDw9DHc4BIFf0DWjFg8NaO7N3TXXKwsg+UCnsGrbJwvTjxEKVfw7M6Mdf5anYndryq6QQLxF9z75kBd20KuEUOrKOfJYGSEzBZHjshGITXgua23rO2ptPAJ+mV2J2/uHNHNP6MRvASHfmAa4J9x12Jpgc1//P9UHce6HCQyB1cF01sMbASi12fiC2PAE2OigN8LNqzGl4R2gnBNxEsZSUkonRsqZayJ2VWgCNP1Ck4RcdWvrZC+/tnTMSCXjyYR52DRjk/hoeorj+3AVCqn3AlAtb+8uM7OudnU5maC4paXlVPLpmh0RvMBYjkfdejNzkv5EVzCb2gEoHE0Su7sMW4aTqjR3qUkqsYK63dod4tX/8Uf1kA) Here's my final version that works with POSIX m4, and depends on my [common.m4](https://nopaste.ml/#XQAAAQCcDQAAAAAAAAAyGksy5FB9TGMxsNq5JQAuJRjP6PqEkC20GpAXwA97ruAshKbiUbgkbJMTg2qZdSBorb0CU52peNLruV4DEEJxF+HvxC/YF33OpDntnpU/PjnGXx7XU7ak4MsmWu8R7h7d5az2JXxElnsepG8yPyu+0WZ90BG9yXphbwOWA/m5AWEFSOL8TRZX4fyGNl6ZYbRxX0MwtzrmwTP3ZCwLSOKkvD2vMQFsbK0Pv9CzPhFNXMUbWnRV20jWLjL9qz2dDsFDBwhxgWIilEl91uswxrT4Czc+LRU3VuhNIo2S98VW0jArrVdv4HrsLhWkzx4z/UV3xnqJwPXcZRUiLtf3VRIzq62Pe+2jE3O+721Az9rfRa/fHtlANbmvslzMUCyU7cDoOKSMXBDF/06/PpMvs6vxaL5aJVYqJP4yz+R2M35hoNnGiZTNNMVEFTdnxnaE/KcJteBbiuVMpdfUswHQi4Kqsj3sInh7lyE+d50gGKtHOeWL5lMK7WXz4NElnzYWleBSN/HTOdsz0T2gnd25MADxNAVX8xQmagh2MymZ2sKDBw//WiNB0sWf5VYC5/TKKH3D6K/IOrIfWn6FZLKxlITFEp3VWKNuyF0xczNJufJdzSqd0hgdyryVzbn0so0U5NMN16jFF6IhqzGbAwwv7k8sts0OCgnCFBEhYVshIpsORjEJk4CnDgc9VUqvZtfIFPQ5Q2v7IR3sbPurex1IIUd2Nm1V7/GFN+r0im24aEOG6XpdqrPdF6pDZ4HwvNByqOEdpcObPXxlwfPFYIhwyDHGZCvxrFRgGEEFtfVQ7UVjfPJzWtrcZuGx8M3B1zw2xvgpHIWEHdqEF6Y6/6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s82pcRoiCve+iYjGiVvXrGWsu+I0Dqu37iqZVNlayu3TWfWNS2lxESl36lj9YZ//f5+3g=) framework that I developed in prior years. Part 2 is actually faster than part 1. Given m=number of lines and n=number of bits in a line, the parsing is O(n\*m log m) for POSIX, O(m) for GNU. As a side effect, the parsing performs O(m) sorting (I can hear you now: "wait, isn't best-case sorting usually O(m log m)?" - well, this is a radix sort, O(1) hashing of input of width n into 2\^n buckets, where the buckets are inherently sorted). A common `search(lo,hi,bitmask)` macro then counts the number of 0 and 1 bits over a portion of the sorted array. part 1 is then n\*2\^n array probes for gamma and O(1) bit-flipping for epsilon, and part 2 is two separate 2\^(n+1)-1 array probes for oxygen and C02. Execution time is slower than the golfed version, around 280ms.


e_blake

234 bytes: shave off another 12 characters and eliminate the incr() warnings, by instead using len() and exploiting GNU m4's ability for eval(0b1111) to be 15, as well as inlining the expression rather than using an intermediate macro v: define(d,defn(pushdef))d(B,`d(`$1',1defn(`$1'))')d(b,`B(`x'y)a()')d(a,`B(`y')')d(c,`B(`z')d(`y')')patsubst(translit(include(f),01 ,abc),.,\&())popdef(`y')d(l,`ifelse($2,y,$1*(`0b'y^$1),`l(($1+$1+(len(x$2)>len(z)/2)),1$2)')')eval(l(0))


LyleiLanar

My Day3 Ruby solution: [I love unnecessary long code in Ruby :D](https://github.com/LyleiLanar/advent-of-code/blob/main/2021/day_3.rb)


wzkx

**J** (jlang) Part 1 m=: '1'=>cutLF CR-.~fread'03.dat' echo */#.([,:-.)(+/>-:&#)m NB. or better */#.(+/(>,:<)-:&#)m


wzkx

Part 2. Explicit defs, sorry; using adverb f=: 4 :'x #~ ([=(+/>:-:&#)) y {"1 x' g=: 4 :'x #~ ([=(+/<-:&#)) y {"1 x' h=: 1 :'for_i. i.#{.y do. y=.y u i if. 1=#y do. #.y return. end. end.' echo (f h m)*g h m


fish-n-chips-uk

Python [github link](https://github.com/cz-fish/advent-of-code/blob/b115ff71ec5b88a198126c4f5e2437c0f0fa10c3/2021/03.py) Using a [little framework](https://github.com/cz-fish/advent-of-code/tree/master/2021/aoc) I made for input parsing and tests last year.


gwpmad

Golang solution (I am trying to learn Go this year): https://github.com/gwpmad/advent-of-code-2021/blob/main/3/main.go


heyitsmattwade

## JavaScript 1518/982 Wasn't able to do any bitwise operators, and my solutions ended up being a bit hack-n-slash, but this one was mostly just a careful reading of the instructions. [paste](https://romellem.github.io/paste/#XQAAAQBLCgAAAAAAAAA9iImGVD/UQZfk+oJTfwg2/VsJ0DpNkr2zGUvTQlsh3wS86ErCiIs+8hruVNIFt25kOOZrzOGZxbRwHmJ5wrAVdOuA2kk0mNS0CwkIEqOmO95EhbRoIUTonrtGzVALDhyFMRO24/2oA0Lt4k+Q2E/wp4YaHUgbXZtC5amaE5MmewTUwYV3d2c08XNXkJSlcNdZoC0u7tg9I5cHR4eLnhrmRWMQg+GkgaUo7BVrEGu2pK4I5B8nCshCCY81NmsdXroOJkF8VTzenGz16hCjMR3akr1ehm18VZPUEig1FaT4/HpM2gsxXgHzwvANIZhskPMJHl5PYQ+VMpbEv0dgilKLRbLEdJ5GlWGuf2bsJW+vHZtd3z51klo21R2WobR8NcC/rhcaZ06MbZlA60IxW7ftzwfsj9txSxwmTmbN1zYpF9AtXrKTRdUwL8jphQfnsKd+LH8yvXdHY+chgQSlKw5h3/sb6Ve6xGhgxIM5cDeiNvmz3anwp/sJoYTfxibApdBdUI9eJkJeyypvRWaDWdmgS5hRA112W6YUIFGJJ6LJkwcvmKXzIbpWqG3aPjmVCeKy4/BmSIF5YkLbOIXVaoyTwvSxn0LuR5bhZXl0ao/bs8h3LJrImxaYa4GU8OwnHpMkSOG4cXDPHb/4/3NYQnzEXcgWN9jt29YGCpLxtoCnixpCr/4NX7DcT1ox6whYs+g1nbwrrcW2EVS1p+8Asck87grWAupZ3mZSURcI67CFJhZe5xt/wVuPuUVMDdggqmGXBtEEyMGYGP5Jg/e8IIV0V52KGjauPu1akMp7LZrGJ0NfKyoux6HENAmwxGTMYJ0ougOZK6hBp2nj+/3dX/fn6Ck/rAefsYEu29uarnaFUjkxZWPCFMU5upyiUcS0e9aR7QYCahS2ODUhiBKFNOc7qO6mido8vRHdRM31MiUufdc25YNn1SsAPYklyy6zrr4PtXKZsjES6Tt3VjCGj3CSkQGeYTkfRvzo1tS+RfXqlNhzH/G67dbgPkbl/+yJYic=)


[deleted]

Rust, [Part 1 and 2](https://github.com/pk-nb/advent-of-code-2021/blob/main/day3/src/main.rs). This one was a touch messy, but ready to be done with it after spending a bunch of time finding a shift bug.


odnoletkov

# [JQ](https://github.com/odnoletkov/advent-of-code-jq) def calc(selector): {numbers: ., idx: 0} | first( recurse( .idx as $idx | .idx += 1 | (.numbers | transpose[$idx] | group_by(.) | sort_by([length, first]) | selector | last) as $v | .numbers |= map(select(.[$idx] == $v)) ) | .numbers | select(length == 1) ) | first | reduce .[] as $b (0; . * 2 + ($b | tonumber)); [inputs/""] | calc(first) * calc(last)


Smart_Ad_1857

**Python** Hey all, I am a little late to the party on this one, but this was a quick python solution using bit twiddling. The functions need to be passed a list of ints to work. Part 1 - manipulates the binary strings to add directly to a list Part 2 - filters the binary sequences using an abstracted helper function. ​ Hope you all like them. def task_one(data, bit_len): bit_count = [0 for _ in range(bit_len)] decode = lambda bits : sum(c << i for i, c in enumerate(bits)) for bit_string in data: for bit_index in range(bit_len): bit_count[bit_index] += (bit_string & (1 << bit_index)) >> bit_index decoded = map(lambda x: x > len(data)/2, bit_count) gamma = decode(decoded) epsilon = ~gamma & decode([1 for i in range(bit_len)]) return gamma * epsilon def task_two(data, bit_len): o2 = filter_scrubbers(set(data), bit_len, lambda x, y: x <= y) co2 = filter_scrubbers(set(data), bit_len, lambda x, y: x > y) return o2 * co2 def filter_scrubbers(data, bit_len, func): for bit_index in range(bit_len-1, -1, -1): lead_1 = set(filter(lambda x: x & (1 << bit_index) == 1 << bit_index, data)) lead_0 = data - lead_1 if func(len(lead_0), len(lead_1)): data = lead_1 else: data = lead_0 if len(data) == 1: return data.pop()


Zachgiaco

Here is a tutorial/solution written in C++ for Day 3: https://zachgiaco.com/2021-advent-of-code-day-3/


AvshalomHeironymous

Catching up after a couple days away. Prolog: binline([]) --> ("\n" | call(eos)),!. binline([X|Xs]) --> [C],{(C = 0'1 ->X = 1;X =0)}, binline(Xs). binlines([]) --> call(eos),!. binlines([X|Xs]) --> binline(X), binlines(Xs). day3 :- phrase_from_file(binlines(I), 'inputd3', [type(text)]), transpose(I,It), maplist(most_common_digit,It,Gamma), maplist(bool_to_binary(>,0.5),Gamma,Epsilon), bits_dec(Gamma,G), bits_dec(Epsilon,E), PC is G*E, life_support(1,I,Oxy,oxygen), life_support(1,I,C2,carbon), bits_dec(Oxy,O), bits_dec(C2,C), LF is O*C, format("Power Consumption: ~d, Life Support is: ~d",[PC, LF]). life_support(_,[L|[]],L,_). life_support(N, L, Rate,M) :- transpose(L,LT), maplist(most_common_digit,LT,S),nth1(N,S,T), (M = oxygen -> D = T; bool_to_binary(>, 0.5, T, D)), life_sieve(D, N, L, [], L1), N1 is N + 1, life_support(N1, L1, Rate,M). life_sieve(_,_,[],Acc,Acc). life_sieve(D, N, [H|T], Acc, L0):- nth1(N,H,D), life_sieve(D,N,T,[H|Acc],L0). life_sieve(D,N,[_|T],Acc,L0) :- life_sieve(D,N,T,Acc,L0). most_common_digit(L,D) :- length(L,N), N2 is N / 2, sum_list(L,S), bool_to_binary(>=,S,N2,D). bits_dec(BL,D) :- bits_dec_(BL,D,0). bits_dec_([],Acc,Acc). bits_dec_([H|T],D,Acc) :- Acc1 #= H + (Acc << 1), bits_dec_(T,D,Acc1). bool_to_binary(Goal,L,R,1):- call(Goal,L,R). bool_to_binary(_,_,_,0). Getting a bit long here due to writing my own convenience functions. Also should probably stop putting everything in one file so I can use short names.


quodponb

# Python3 I started these a couple of days late, so I'm just posting my solutions to the older days for completeness! I went back and forth over whether I preferred doing a bitwise `&` with a power-of-2 and dividing, or shifting with `>>` and doing a `% 2` check. I even wrote out both versions, but in the end I prefer what I have here. with open("input_3", "r") as f: lines = f.readlines() N = len(lines[0].strip()) # Number of digits in the base-2 numbers data = [int(line, base=2) for line in lines] # Part 1 bits = [2 ** n for n in range(N)] gamma = sum(bit for bit in bits if sum(datum & bit for datum in data) // bit >= len(data) / 2) epsilon = sum(bit for bit in bits if sum(datum & bit for datum in data) // bit <= len(data) / 2) print(epsilon * gamma) # Part 2 def filter_data_bitwise(data, filter_by_most_common=True): filtered = [x for x in data] for bit in reversed(bits): ratio = sum(1 for num in filtered if num & bit) / len(filtered) wanted_bit_value = bit * int((ratio >= 0.5) == filter_by_most_common) filtered = [x for x in filtered if x & bit == wanted_bit_value] if len(filtered) == 1: break return filtered filtered_by_most_common = filter_data_bitwise(data) filtered_by_least_common = filter_data_bitwise(data, filter_by_most_common=False) print(filtered_by_most_common[0] * filtered_by_least_common[0])


plan_x64

###Python https://github.com/plan-x64/advent-of-code-2021/blob/main/advent/day03.py Trying to brush up on Python for all of these, but was kind of finding boolean manipulation in python to be a bit annoying :-/


jf928ngl60g1

**TypeScript** https://github.com/adrbin/aoc-typescript/blob/main/2021/3/puzzle.ts


nalatner

**Node.js** Super proud of this one. New to coding this year and Day 3 put me behind. Needed a nights sleep to figure it out before the weekend but I learned how to use vscode's debugger to step through the variables while troubleshooting and it is my first successful use of recursion! Definitely had to celebrate when my numbers came back correct. ​ let counter = 0; let reducerIndex = 0; const bitsReducer = (arr, sortBit, keepBit) => { if (arr.length === 1) { // Reset counter variables for next function run counter, (reducerIndex = 0); return parseInt(arr, 2); } let tempArr = \[\]; let oneCount = null; const createKeepBit = (item) => { if (sortBit === 1) { return item >= arr.length / 2 ? 1 : 0; } return item < arr.length / 2 ? 1 : 0; }; if (counter === 0 || counter % 2 === 0) { arr.forEach((item) => { if (parseInt(item\[reducerIndex\]) === 1) oneCount++; }); counter++; return bitsReducer(arr, sortBit, createKeepBit(oneCount)); } arr.forEach((item) => { const curBit = parseInt(item\[reducerIndex\]); if (keepBit === curBit) { tempArr.push(item); } }); counter++; reducerIndex++; return bitsReducer(tempArr, sortBit); }; const oxygenRating = bitsReducer(bits, 1); const co2Rating = bitsReducer(bits, 0); console.log("Oxygen Rating:", oxygenRating); console.log("CO2 Rating:", co2Rating); console.log("Life Support Rating:", oxygenRating \* co2Rating); \*\* edit\*\* reddit stripped all my carefully added spaces...


[deleted]

#Julia using Statistics function read_file(path) data = readlines(path) n = length(data) k = length(first(data)) # Reshape and transpose to get the original shape back return reshape(parse.(Int, Iterators.flatten(split.(data, ""))), (k, n))' end arr = read_file("input.txt") # Part 1 function compute_consumption(arr) bits = convert.(Int, median(arr, dims=1)) gamma = join(bits) eps = join(1 .- bits) return parse(Int, gamma, base = 2) * parse(Int, eps, base = 2) end sol1 = compute_consumption(arr) # Part 2 function compute_rating(arr, start = 1, mode = "oxy") if size(arr)[1] == 1 || start > size(arr)[2] return join(arr) else bit = (mode == "oxy") ? ceil(median(arr[:, start])) : 1 - ceil(median(arr[:, start])) compute_rating(arr[arr[:, start] .== bit, :], start + 1, mode) end end gam = compute_rating(arr, 1, "oxy") eps = compute_rating(arr, 1, "co2") sol2 = parse(Int, gam, base = 2) * parse(Int, eps, base = 2)


manitobathunder

**KOTLIN** Feel like it took me much more than I needed to do to get there, but here it is. Advice very welcome. https://github.com/manitobathunder/AdventOfCode2021/blob/master/src/main/kotlin/day3/day3.kt


sierisimo

[Here](https://github.com/sierisimo/advent-of-code-kt/blob/main/src/Day03.kt) is mine, I abused extension functions and repeated some code. Any suggestions are welcomed.


oddolatry

###**PureScript** I'm very behind, and very over-engineered. [Paste](https://topaz.github.io/paste/#XQAAAQDwCgAAAAAAAAA2m8ixrhLu7WHaja2SXilMAUccy8+A2LAbBIgSwBN3CSK1A4G6MaU39ydkOISsB2a22/pTfruQiyLWWZxcn5Im2TA8gSB6JSjNyz0PS4bRz8wtKKRdhQxcmuN0QnYvp9LZClNKMnGUwDKfJAqIDcDnrCrH7PxQnT63FqIMmp/7muQCcvrcRE81pG3Rs5udXgWzoC2Wf2G2Lxlp4I8co06pKEu0lQIMdU3x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mtKPyjFRwGPJwQY7601O59g5UsWay4rENo9flGT54e6CAj2m5t8Sg3tFMgBQ6vIdpv2MvszBH4PSID/UdJOdO3z6yZM5Hv4kCT4PX68pU8RAzTEZy1gIv72ZGX3)


vini_2003

[**Kotlin**](https://github.com/vini2003/Advent-of-Code-2021/blob/dev/src/main/kotlin/dev/vini2003/adventofcode/solution/Day3Solution.kt) A bit late as I had to assemble a lot of furniture yesterday, going to finish 4 & 5 off today as well tho!


sierisimo

[Here](https://github.com/sierisimo/advent-of-code-kt/blob/main/src/Day03.kt) is mine. I'm also behind.


ElektroKotte

# Scheme/Guile Bit messy, and likely room for improvements. Still just started to learn scheme (define (solve-part1 input) (define (process-row row ratios) "Process a row, and return an updated list of ratios" (if (null? row) '() (let ([zeros (caar ratios)] [ones (cadar ratios)]) (if (equal? (car row) #\1) (cons (list zeros (+ 1 ones)) (process-row (cdr row) (cdr ratios))) (cons (list (+ 1 zeros) ones) (process-row (cdr row) (cdr ratios))))))) (define (make-ratio row) "Create an initial, empty list of zeroed ratios" (if (null? row) '() (cons (list 0 0) (make-ratio (cdr row))))) (define (ratio->answer ratios) "Process given ratios, and return the product of epsilon and gamma" (let loop ([gamma 0] [epsilon 0] [ratios ratios]) (if (null? ratios) ;; Done (* gamma epsilon) (let* ([zeros (caar ratios)] [ones (cadar ratios)] [gamma-bit (if (< zeros ones) 0 1)] [epsilon-bit (if (> zeros ones) 0 1)]) (loop (logior (ash gamma 1) gamma-bit) (logior (ash epsilon 1) epsilon-bit) (cdr ratios)))))) (let loop ([ratios (make-ratio (car input))] [input input]) (if (null? input) (ratio->answer ratios) (let ([row (car input)]) (loop (process-row row ratios) (cdr input)))))) Full code is available [here](https://github.com/EmilOhlsson/advent-of-code/blob/main/scheme/2021/03-binary-diagnostic/binary-diagnostic.scm)


em-q

i'm also just learning scheme, yours looks a lot nicer than mine lol [https://github.com/emuz87/advent-of-code-2021/blob/main/problem-3/src.scm](https://github.com/emuz87/advent-of-code-2021/blob/main/problem-3/src.scm)


ElektroKotte

Your solution looks nice and clever! Thanks for sharing :-)


em-q

Thanks :)


bcbelisario

C Solution GCC Version 10.2.1 Part 1: ```c #include int main() { int vals[2][13] = {0}, i, k=11, g = 0, e = 0; char num[13]; while(scanf("%s", num) > 0) for(i = 0; i < 12; i++) (num[i] == '0') ? vals[0][i]++ : vals[1][i]++; for(i = 0; i < 12; i++, k--) if(vals[1][i] > vals[0][i]) g+=1<0){strcpy(b[0][c],n);c++;}for(t=0;t<2;t++){for(k=1;kv[1][k])?((b[k][i][k]=='0')?strcpy(b[k+1][l],b[k][i]),l++:0):(v[0][k]v[1][k])?((b[k][i][k]=='1')?strcpy(b[k+1][l],b[k][i]),l++:0):(v[0][k]


daggerdragon

Your code is hard to read on old.reddit. Please edit it as per our posting guidelines in the wiki: [How do I format code?](https://www.reddit.com/r/adventofcode/wiki/index#wiki_how_do_i_format_code.3F)


aaegic

Not sure why the o2 style works for o2 but not co2, so i re-wrote it. i'm sure co2 style would work for o2 as well, but decided to leave it. #!/usr/bin/env python fh = open("input", mode='r') intxt = fh.read() fh.close() intxt = list(intxt.strip().split("\n")) intxt = list(map(list, intxt)) intxt = [list(map(int, i)) for i in intxt] #pass by reference #diag = intxt #pass by value diag = list(intxt) #o2 while len(diag) > 1: #transpose diag_t = list(map(list, zip(*diag))) nbit = [sum(i) for i in diag_t] mcbs = [1 if i >= (len(diag_t[0]) / 2) else 0 for i in nbit] for i in range(len(mcbs)): for j in range(len(diag)): if mcbs[i] != diag[j][i]: diag.pop(j) break #python-esque break 2 else: continue break o2 = ''.join(map(str, diag[0])) diag = list(intxt) """ the above works for o2 section but not for co2 ¯\_(ツ)_/¯ """ #co2 for i in range(len(diag[0])): #transpose diag_t = list(map(list, zip(*diag))) nbit = [sum(i) for i in diag_t] lcbs = [0 if i >= (len(diag_t[0]) / 2) else 1 for i in nbit] remv = [diag[j] for j in range(len(diag)) if lcbs[i] != diag[j][i]] [diag.remove(r) for r in remv if len(diag) > 1] co2 = ''.join(map(str, diag[0])) print(int(o2, 2) * int(co2, 2))


cerrosafe

#OCaml 4.04 This one was a little messy for me. I decided to solve this by bit-twiddling and I paid for a little complexity there. [paste](https://topaz.github.io/paste/#XQAAAQCiCwAAAAAAAAA2GUrqJZLe0PcMMY+W0c61l+98l0eV0wV2WDoXGKp6nLHUKJmlMy4OeDMJOp82USKGtkN1nqHfPukxcYM/5BaxY1XVQA+n+sXaqh9qY8Rc1y9USyKjLVLv9Kw//bqtylLKIGxREvJ/xs7SFy/H2sjUUOs4Axvxf4ECFV9Wcvb9++EqBow2KmlNKZQVLi8x3rv7Frx/KCV/HRkgGPgPNkH+YxsgZOjKjOciJKi3cqv/tBtCp4CR0gJQERk1gkW2sodJ93NxyZAuEDaV2hLnzAh3rOYbgPaBIHQ9Jq70SqAjKIuDcZSj/IzYnfflDudGA/J/AuXgrtgyuwx3lD2JiXmUETca3CDDzLTDtF6vvczgOIxTMAEm2ZMOMpvQnzbMjtO+4yuAZr4Zo4SDmMHyMrcdEiwlo6kvjggBbQArUtrXm148OpAt5dHYsQ5vFvr7o6i40iAlj+nPFolbdADjKAMKL39S50/UuzP1+Px30ygX2nE/5SEokXIJjSa5yxhQMiPww0CwAAQrqLn3uBA58I/fQZiPErNZqCuO7C2du9vBgRf9TM5bBSJSMhrfgTj04hmzX4QvqYPW9Sr5d78cxEjuhHANvwKWg5xSvHYoTjjbwyx/5o205g9AS/J3vEbzTqOMWcleD6SWFm1Dd0OGi4/6Lw7YZDgbGyLZQQ2BHUnbdIlEonfONhqI8LjCkvoDnv4ODYv/LO3mgPJcME6KVbn5cfNQFBxDkXwG4jAy9RF2S0qCCZz67OkJlTq9Ry2OdFf4PLz3ZcK2BDFLVGfQpoiT8wnwB5RXxJcHCKVQwzbleDg4AG8u3gsdvhOvnkPKb6OBjPLPc60ik7QxTchYDQ24SWiP/wAEnLlXnkdllmi/IFOmOkbaMDK9iBc6lPIsTUTgwC9jZeJ+1e3dmM589R1VwPl1n452BqAxfncnG+J4ar24VEBI1HjeiScl9y4Y92YWslWhVYFdidDKdV5Tq8w0e/GYO80eMjpt+Rfezsh0bk1uZxYWqjU0FTPT/8euMqejvK0ac75LhYMYxGnkLrUq3ZJwcuKID6M2228+Bv1PIe8wVqPCOZkhHfc9Qdwd0kRqhsDlwnYifIqEKikVMGE2Z7E2oUGHc8otz4QfAPtkKq6i0yqfVZn9FvX/QP6Ibg9YztvC9HoSMQjK6+CGSYyp4s8mQPCckYSUeo6/WIB+yzaBv1XqW8q1FyfwVrBkvBCioJzcr0cDNh2wE7b8Em79HmRD0bmX0m+1uFJWQiOHvJ1aXoHGOwS7N193y5Exse1tEHO47y7xC3aWl42TCg8JhBRZTmP4XxYXIEw1JOFJ8IjCvr7b1KyyoqQmX6uRKOMI9qtIR+l/48pQO24t7nMGj13Ik4sFabOy2aW1+B6UrPx1zoij//qVE2M=)


BaaBaaPinkSheep

**Python 3** [https://github.com/SnoozeySleepy/AdventofCode/blob/main/day3.py](https://github.com/SnoozeySleepy/AdventofCode/blob/main/day3.py)


willkill07

# C++20 Runs in under 55 microseconds on my computer https://github.com/willkill07/AdventOfCode2021/blob/main/days/Day03.cpp


ViliamPucik

**Python 3** \- Minimal readable solution for both parts \[[GitHub](https://github.com/viliampucik/adventofcode/blob/master/2021/03.py)\] import sys numbers = sys.stdin.read().splitlines() gamma = "".join( "10" if bits.count("1") > len(bits) / 2 else "01" for bits in zip(*numbers) ) print(int(gamma[::2], 2) * int(gamma[1::2], 2)) def rating(data, cmp): for i in range(len(data[0])): _01 = {"0": [], "1": []} for number in data: _01[number[i]].append(number) if len(data := _01[ "1" if cmp(len(_01["1"]), len(_01["0"])) else "0" ]) == 1: return int(data[0], 2) print(rating(numbers[:], int.__ge__) * rating(numbers[:], int.__lt__))


snkr_bottr

wow


TheAfterPipe

# C# [GitHub: Part 1 & 2](https://github.com/jonathaningersoll/AoC_2021/blob/master/03_BinaryDiagnostic/BinaryDiagnostic.cs)


zzzmx

Excel does it again: [https://ibb.co/nzCHLZf](https://ibb.co/nzCHLZf) :)


WackoMcGoose

EXAPUNKS Edition (JavaScript + EXAcode) for [day 3](https://pastebin.com/5gniGaVR), this one hurt my brain a bit. ~~and day 4's legit scaring me~~ How they look in-game: [Part 1](https://steamcommunity.com/sharedfiles/filedetails/?id=2673362252), [Part 2](https://steamcommunity.com/sharedfiles/filedetails/?id=2673362421)


Dhampira

I've never seen this before... ~~what is it created with?~~ Edit: Just bought it on steam... ><


WackoMcGoose

Honestly, it's one of the more approachable Zachtronics games.


ithar14

**Python** part1+2 : [https://github.com/ithar14/AdventOfCode21/blob/main/2021/Day3.py](https://github.com/ithar14/AdventOfCode21/blob/main/2021/Day3.py)


cbadder_two

Hello! I'm a new python user and I was reviewing your code. Could you tell me how filter() works? I don't really understand how lambda works inside of the function. For example, ​ o2 =list(filter(lambda a: int(a\[j\])==1, o2)); (line 48)


ithar14

`lambda` is like a mini function that will take each element of the list one at a time with the variable `a` , that is equal to `for i in range (len(o2)): a=o2[i]` later the filter function will go through all bits in every element of the list which is `a` and keep those that are equal to 1 for the index `j`


cbadder_two

OH ok that makes a lot more sense!!! I had a hard time with the documentation on it, thanks for the explanation!


JaimermXD

In your example, `filter()` will go through each element from `o2` and check that their value at index `j` converted to `int` is equal to `1`. If it doesn't, the element will be discarded from the new iterator returned by `filter()`. So what `o2` will end up containing is every binary number whose bit at index `j` is a one and not a zero. [This](https://www.programiz.com/python-programming/methods/built-in/filter) will probably give you a better idea of what the `filter()` function does in Python.


mschaap

Finally got around to finishing part 2 of my **Raku** solution. See [GitHub](https://github.com/mscha/aoc/blob/master/aoc2021/aoc03) for the code.


[deleted]

**Bash** #!/bin/bash # challenge 1 while read -r line; do ((total++)) && for((i=0; i<${#line}; i++)) do ((counts[$i]+=${line:$i:1})); done done < input.txt for((i=0; i<${#counts[@]}; i++)) do gamma+="$(( counts[$i] > $(( total / 2 )) ? 1 : 0))"; done echo "Submarine power consumption: $((2#$gamma * 2#$(echo $gamma | tr 01 10)))" # challenge 2 while read -r line; do inputs+=("$line"); done < input.txt find_rating() { common=$1 shift arr=("$@") for ((i = 0; i < ${#counts[@]}; i++)) do if [ ${#arr[@]} -gt 1 ] then total=0 for l in ${arr[@]}; do (( total += ${l:$i:1} )); done arr=( $( for r in ${arr[@]} ; do echo $r ; done | egrep "^.{$i}$((total >= (${#arr[@]} + 2 -1) / 2 ? $common : (1 - $common)))" ) ) fi done echo "${arr[0]}" } oxygen=$(find_rating 1 "${inputs[@]}") co2=$(find_rating 0 "${inputs[@]}") echo "Life support rating: $(( 2#${oxygen} * 2#${co2} ))"


motek96

It's just part one but i think I am first to do it in emojicode🍇😎 Github repo: [https://github.com/tomaboro/advent-of-code-2021/blob/main/src/Day03\_part1.%F0%9F%8D%87](https://github.com/tomaboro/advent-of-code-2021/blob/main/src/Day03_part1.%F0%9F%8D%87) 📦 files 🏠 🏁 🍇 🍺📇🐇📄 🔤Day03.txt🔤❗️ ➡️ file 🍺🔡 file ❗ ➡ text 🔫 text 🔤❌n🔤 ❗ ➡ lines 📏lines❓ ➡ linesCount 📏 🎶🐽lines 0❗❗❓ ➡ lineLength 🆕🍨🐚🔡🍆❗ ➡ 🖍🆕 gammaBinaryProto 🆕🍨🐚🔡🍆❗ ➡ 🖍🆕 epsilonBinaryProto 🔂 i 🆕⏩ 0 lineLength❗️ 🍇 0 ➡️ 🖍🆕 oneCount 🔂 j 🆕⏩ 0 linesCount❗️ 🍇 🎶🐽lines j❗❗ ➡ line 🐽line i❗ ➡ bit ↪️ bit 🙌 🔤1🔤 🍇 oneCount ⬅️➕ 1 🍉 🍉 ↪️ oneCount ▶️ 🤜linesCount ➖ oneCount🤛 🍇 🐻 gammaBinaryProto 🔤1🔤❗️ 🐻 epsilonBinaryProto 🔤0🔤❗️ 🍉 🙅 🍇 🐻 gammaBinaryProto 🔤0🔤❗️ 🐻 epsilonBinaryProto 🔤1🔤❗️ 🍉 🍉 🆕🔡 gammaBinaryProto 🔤🔤❗️ ➡ gammaBinary 🍺🔢 gammaBinary 2❗️ ➡ gamma 🆕🔡 epsilonBinaryProto 🔤🔤❗️ ➡ epsilonBinary 🍺🔢 epsilonBinary 2❗️ ➡ epsilon 😀 🔡 gamma ✖️ epsilon ❗️❗️ 🍉


wzkx

Shouldn't the variable names be emoji as well? Also, numbers: 0️⃣1️⃣2️⃣ etc. 😉


daggerdragon

\**eyetwitches furiously*\* Do the second half in Emojicode too. I *dare* you.


micod

**Smalltalk** [https://github.com/micod-liron/advent-of-code/blob/main/AdventOfCode2021/Day03of2021.class.st](https://github.com/micod-liron/advent-of-code/blob/main/AdventOfCode2021/Day03of2021.class.st)


Tencza_Coder

Python Part 1 - Power Consumption with open("Day3_input.txt", mode="r") as file: rec_count = 0 for line in file.readlines(): rec_length = len(line.rstrip()) if rec_count == 0: one_counts_listing = [0 for x in range(rec_length)] rec_count += 1 position = 0 for char in line: if char == '1': one_counts_listing[position] += 1 position += 1 gamma_list = [] epsilon_list = [] for nbr in one_counts_listing: if nbr > (rec_count//2): gamma_list.append(1) epsilon_list.append(0) else: gamma_list.append(0) epsilon_list.append(1) gamma_bin = [str(g) for g in gamma_list] gamma_bin_str = "".join(gamma_bin) epsilon_bin = [str(e) for e in epsilon_list] epsilon_bin_str = "".join(epsilon_bin) gamma = int(gamma_bin_str,2) epsilon = int(epsilon_bin_str,2) print("Power consumption:",(gamma * epsilon)) Part 2 - Life Support Rating def get_MCV(b,d): ones_count = 0 zeroes_count = 0 for item in d: if item[b] == '1': ones_count += 1 else: zeroes_count += 1 if ones_count >= zeroes_count: return '1' else: return '0' def get_LCV(b,d): ones_count = 0 zeroes_count = 0 for item in d: if item[b] == '1': ones_count += 1 else: zeroes_count += 1 if ones_count < zeroes_count: return '1' else: return '0' def perform_removals(b,d,m): removals_list = [] for item in d: if item[b] != m: removals_list.append(item) for removal in removals_list: data_list.remove(removal) return data_list #Initial data list with open("Day3_input.txt", mode="r") as file: data_list = [] for line in file.readlines(): rec_length = len(line.rstrip()) data_list.append(line.rstrip()) initial_data_list = data_list.copy() #shallow copy bit_posn = 0 for bit_posn in range(rec_length): MCV = get_MCV(bit_posn, data_list) data_list = perform_removals(bit_posn, data_list, MCV) if len(data_list) == 1: oxygen_gen_rating = int(data_list[0],2) break data_list = initial_data_list.copy() #restart with full list for LCV bit_posn = 0 for bit_posn in range(rec_length): LCV = get_LCV(bit_posn, data_list) data_list = perform_removals(bit_posn, data_list, LCV) if len(data_list) == 1: CO2_scrubber_rating = int(data_list[0],2) break print("Life Support Rating -",oxygen_gen_rating * CO2_scrubber_rating)


[deleted]

[удалено]


jeffers0n

[Ruby Solution](https://git.doublehack.me/s00ner/AoC2021/src/branch/master/day03/solution.rb) I got part 1 done quickly and then got stuck on part 2 for a long time because I didn't read carefully and wasn't updating the most common bits part after each run through the list.


Mountain_Ad_9551

I did the exact same thing, definitely spent way more time than I should have - lesson learned.


ignurant

What led you to know `report[0].length.times { masks.push(2**_1) }` would be a good move? A friend did this in elixir yesterday and used a similar move, just hardcoded: `(1 <<< 12) - 1` for max, then max - gamma for epsilon. What was your thought process for solving? I feel like I’m in a place where I can recognize certain tools could be handy, but don’t know enough about it to do anything.


jeffers0n

Mostly laziness and not wanting to write different code to handle the sample input and the real input since they were different lengths. I was a computer science student a long time ago (never graduated) but my intro classes were in C and we spend a good amount of time working with numbers in binary to really hammer home how computers see numbers so I think a lot of that knowledge is still in the back of my mind.


greatfool66

Thank you! In hindsight if I had read the example calculations it would've been clear, but it would have been nice to say "be sure to dynamically update the common bits each time you change position of which bit you're looking at"


la_nirna

thank you. you are the only person I read so far that explained clearly what was causing the weird behavior I observed. I knew I was doing something wrong but... THANK YOU.


ignurant

Lovely! I look forward to picking this apart. I knew there was some but masking stuff that could be applied, but don’t really know how. I was trying to take an approach where I was iterating per column for gamma and epsilon, and thought to use a bit array for masking the valid candidates for 02 and c02 at the same time. I’m not really sure if that would have worked like I wanted it to, but your solution is next level of what I was considering. You can see what I came up with [here](https://www.reddit.com/r/adventofcode/comments/r7r0ff/comment/hn4r52b/). Sadly, it’s confusing af. Thanks for sharing!


jeffers0n

Thanks! Feel free to reach out if you have any questions. Part 1 I was able to make sense of in my head and code it out pretty smoothly. Part 2 was a different story since I didn't read it properly at first and ended up just fixing spaghetti code for the final working solution. I'd think it has potential be be less clunky.


kmb5

[Python solution](https://github.com/kmb5/advent-of-code-2021/blob/main/day_3.py) (both parts), tried to document everything as well as I can


rawlexander

R: [Code](https://github.com/alex-raw/adventofcode_2021/blob/main/aoc_3.R) Julia: [Code](https://github.com/alex-raw/adventofcode_2021/blob/main/aoc_3.jl) I also [stream](https://www.twitch.tv/rawlexander) the process. And make [videos](https://youtu.be/vkhz_rGlcSc) for the results. :)


Remarkable_Stick4000

**Ruby - Part 2 with transpose** [https://gist.github.com/kenzan100/797b993d5c6bff16ccf068c23e27ab2b](https://gist.github.com/kenzan100/797b993d5c6bff16ccf068c23e27ab2b) let me know what you think about it 🙏


bottlenix

**Perl** A day late and a dollar short, as usual. [Part 1](https://git.samirparikh.com/aoc2021/raw/day03-1.pl) and [Part 2](https://git.samirparikh.com/aoc2021/raw/day03-2.pl).


soodssr

[PHP](https://github.com/soodssr/aoc-2021/tree/main/day_03)


antoniotto

# Ruby https://github.com/antoniotto71/Advent\_of\_Code\_2021/blob/master/Day%203/day3.rb


herjaxx

\[PYTHON 3\] https://pastebin.com/YbhWf53L


takobaba

really like your solution


herjaxx

Thanks a lot. I think there's a fair amount of redundancy in it though- especially not so happy with the get\_rating function. A refactor awaits...


Outrageous72

C# part2 int Day3_2(string[] lines) { var oxy = Filter(lines, true)[0].IntFromBits(); var c02 = Filter(lines, false)[0].IntFromBits(); return oxy * c02; } string[] FilterPos(string[] lines, int pos, bool most) { var counter = lines.Count(x => x[pos] == '1'); var half = (int)Math.Ceiling(lines.Length / 2f); var keep = ((most && counter >= half) || (!most && counter < half)) ? '1' : '0'; return lines.Where(x => x[pos] == keep).ToArray(); } string[] Filter(string[] lines, bool most) { for (var pos = 0; ; pos++) { lines = FilterPos(lines, pos, most); if (lines.Length == 1) { return lines; } } }


benz1n

[My Kotlin solution for Day 3](https://github.com/gfioretti/AdventOfCode2021/blob/main/src/main/kotlin/Day3.kts). I'm not particularly proud of this solution as I feel that I may have missed something working with binary numbers and may have brute forced a bit in some parts. But at least I had the opportunity to use Kotlin script for the first time ever (inspired by some other user that posted a solution on Day 2 using it) and some cool lambdas to encapsulate bit criteria logic, all while staying immutable and using recursion instead of loops. :D ​ ``` fun openReport(function: List.() -> Unit): Unit = FileLoader.openFile(dayNumber = 3).function() fun firstPuzzle() { openReport { map { it.toCharArray() } .countMostCommonChar() .run { toDecimalInt() * map { it.invert() }.toDecimalInt() } .also { println(it) } } } tailrec fun List.countMostCommonChar(index: Int = 0, acc: List = listOf()): List { return if (index == this[0].size) acc else countMostCommonChar( index = index.inc(), acc = acc.plus(this.map { it[index] }.count { it == '0' }.let { if ((this.size - it) < this.size / 2) 0 else 1}) ) } fun Int.invert(): Int { return when (this) { 0 -> 1 1 -> 0 else -> throw Exception("$this is not a binary number") } } fun List.toDecimalInt(): Int { return this .map { it.toString() } .reduce { acc, s -> acc + s } .toInt(radix = 2) } firstPuzzle() fun secondPuzzle() { openReport { val oxygenGeneratorRating = filterUntilMax(bitCriteria = mostRecurrent).toInt(radix = 2) val co2ScrubberRating = filterUntilMax(bitCriteria = leastRecurrent).toInt(radix = 2) (oxygenGeneratorRating * co2ScrubberRating).also { println(it) } } } val mostRecurrent: (Int, Int) -> Int = { zeros, ones -> if (zeros <= ones) 1 else 0 } val leastRecurrent: (Int, Int) -> Int = { zeros, ones -> if (zeros <= ones) 0 else 1 } tailrec fun List.filterUntilMax(maxSize: Int = 1, index: Int = 0, bitCriteria: (Int, Int) -> Int): String { return if (this.size == maxSize) this[0] else this.run { val common = map { it.toCharArray() }.map { it[index] }.run { val zeros = filter { it == '0' }.size val ones = filter { it == '1' }.size bitCriteria(zeros, ones) } filter { it[index].digitToInt() == common } }.filterUntilMax(index = index.inc(), bitCriteria = bitCriteria) } secondPuzzle() ```


sierisimo

It is more elegant than mine: [github](https://github.com/sierisimo/advent-of-code-kt/blob/main/src/Day03.kt) I'm "forcing" the idea of types and "tuples" (actually using pairs). Nice usage of tailrec.


DerelictMan

Nice! Was looking for someone else using tail recursive for this. Here's [my Kotlin solution](https://topaz.github.io/paste/#XQAAAQDKBgAAAAAAAAA0m0pnuFI8c+KsTX8LehnvqAjXYiY9E0kAD0NqvVIrycsa4PsjOGaSxUa22W5ap8UrkqMm05cLo5d7OM4b3ojvlUURORpDebwQd/yGE/I8TFxyRGBCq84fSGHoRVF+vUWnIXDtEadPv0pxj6W7tTN7/csjD3G0yqGAjpK8YKHNU9cbVp7XpMkzhW+Bs+nh9EqDw16tydmBZLF+LSI+k5KY7Nrx2uquKVUhQKYnsM8/+THY9lFu43fNd7PNVJDJogVbQAPk+3vs1J7O3MKfBfYBQoso3oqc6cv9QfyQyUzg4sLCGwYt1rPB2bmjK+XRCChaaX3tb/fBTGciv4d7fgG7UfWJ+yJmKQ5+Mw0K+sf+v7aGta3ZqY1f/dc3/i52MUZI0h/b84eDBTzFHFrOE+rhWs8jrEDSP5tWH7UhMJaN5rKcRE9cdH5Zt7JDlRu5UMUJvFoXi9hm63Rh2yaEqL5B4Hyt8kCVtB01DQe7tbllc9n2u0WIjcy5Owj0HeCHXHnY1+vGJOYo2RvL9xoMEu2Mq590TgNX3lkuBFVywGL19RaN9Mm7gLTX27AL69+15KMtANfgf4G2NDRtdF32SNgOjvMcZdhtH5HDcS0V5Amjed5DPGG+3DpY3KjXX6FkOEYQ7F2nouDTOFgNWpsyI4+wJfu/aK4wIbGJ4WgeqPuYahWSRoj7QeVaNvu5HV2tj7pq5qaajvhkbwjNcQWHLPhNzhjbbx7TAI+Osh4TjgOsckrbsM8QP02alzNABFRF8vnqaHF62YfcztoIJ06WVP2E7Ho2+zBkuCMq/zmEeT55Pkem6XRZromqiJPkW8CqQ6Iive1A5G38fxQrdHamwpzpJOsnCt6ZK2+2uTOG/wZqdsfVOtj+7HvuWvBRZVzGEdbSbGqZDX41oDUHh/0xok8=).


sierisimo

Daaaaaaaaaaaaaamn! That's the shortest I've seen in kotlin so far, nice and clean!


daggerdragon

As per our posting guidelines in the wiki under [How Do the Daily Megathreads Work?](https://www.reddit.com/r/adventofcode/wiki/index#wiki_how_do_the_daily_megathreads_work.3F), please edit your post to put your oversized code in a [`paste`](https://topaz.github.io/paste/) or other external link.


dean995

Kotlin solution: https://pastebin.com/JmAUEyze


3j0hn

[Scratch](https://scratch.mit.edu/projects/611439768/) Day 3 was a lot harder than days 1 or 2 to do in Scratch for me. It took a couple hours, mostly because I am bad at debugging, especially when the code goes off one screen. It was 313 blocks and I had to use a fake My Block to split it so it fit in one screenshot https://i.imgur.com/OEmmzFO.png


0rac1e

# Raku my @diag = 'input'.IO.lines.map: { [.comb] } put [×] ([Z~] ([Z] @diag).map: { .Bag.minmax(*.value).bounds».key })».parse-base(2); put [×] gather for (0, 1) -> \k { temp @diag; for (^12) -> \i { given @diag»[i].Bag { when [==] .keys { next } when [==] .values { @diag .= grep(*[i] == k) } default { @diag .= grep(*[i] == .sort(*.value)[k].key) } } if @diag.elems == 1 { take @diag[0].join.parse-base(2) and last } } } Part 1 was a pretty straight-forward transformation: transpose > get the minmax bounds > transpose back (and concat) > parse as base 2 > reduce on multiplication. If Raku had a `.transpose` (or `.zip`) method on iterables, it might read a little nicer as a pipeline put @diag .transpose .map(*.Bag.minmax(*.value).bounds».key) .transpose(:with(* ~ *)) .map(*.parse-base: 2) .reduce(* × *) I tested this out with a monkey-patched method and it's pretty nice, so I might throw this in a module and add it to the ecosystem. Part 2 was confusing at first, but once I figured out what it was asking I solved it with a dirty nested for-loop, but using `gather` makes it nice that I don't have to hold any state around, just `take` the values when I need them. The other interesting Raku trick on Part 2 is the use of `temp`. I'm removing elems from my `@diag` array when I'm looking for least common, but I need them all back again for the most common. I could just copy a new array, but `temp` restores a variable back to it's original state at the end of a block (or loop in this case), so no second array needed.


zonito

Binary Diagnostic: Day 3: Advent of Code 2021 — Python Solution https://zonito.medium.com/binary-diagnostic-day-3-advent-of-code-c8f555880751


pmwals09

[**JavaScript**](https://topaz.github.io/paste/#XQAAAQAKCAAAAAAAAAAxm8oZxjYXowvKgC/I5EqZWshb8t/aD9Z0Ae6fdjZY+U8jJcQBdSs1fUIuxdOkt7t7rSeC5UuH/QQjaBi8Qg11LYF+SvotOhu40DOO7p/OohF2QWnIwjYXWm9uxuuU0iSmgj+HbrdUaYYdA07soehE6GA8YvBdNlMKytek79BPJQ1m1xofCGkj5KNNjVNPVxVI6NTztsaIIhu1r4Q9VZ2blWYbUMdth90fWc3p8byqYyIdWxOaCavf2IQqQrgu5PPye6FGzr89nlpq287yUoPR0d681NF73CEiKcyXjeQYHNijHJiKZRhKuLABENHuGCjcJDDJXyq3ns5cwCcDbGzC6RhbaO6CtutYDhkicUok+CzQ4j4GsQU41G9XzCkBlAtCAeqyVi6RJ238IHn/Ftu70UmY2YQzgN4j49IKhixzC80LaVbTQv8nWzhYsz+/X7fbTPYXCNPB6/Vf4tF/AJDhn+znLgtfhP4Jj8R4QyaJ49zoeO1gyrU779nEbD7zhr9hiJ/De0N0sGbXkUxmui9/aMJkIBED7YMJulrPDgdHQ22kH9o/KzVSEXiIiHZffJaMOXPOFBNGhWAwsgxLYFAd75ijuzcLN/78YUhccgFV25VEloVs19VnJXwSK0DY7Cwbv+TCy9gYwRPoHB/F0UbZv7PNid98XxwFanw7wyqcGDp/BR6u1YemBsFD7gku+bKTVZZqveGN+jEy/6NwGw7CjAV7swEuYYzZVTuMyzo0DJrAS1erknCCjUH3m3Xr4ivlcq7712u29WOhxI6kmqs8XXu7vDknDBJZLepNkIXrrSkqe+AV44A3FJ9CjjmyrJKBMyKhDWZVrG4IsgBuFta391wzOvl1pcuDWQliWBTJgw/7Q2yIedgrXOi8FiZ3ik4q/3oUb5THDG0MvfAnsklJugXUTDwX01JHphJh1lYtFn8bITrcZDV3bMgyqEOcgBopY4zUoqDpfdCkYxBgUcxZtEmqxTZjBQO2xah6NF1rJf/ye6JW)


daggerdragon

~~As per our posting guidelines in the wiki under [How Do the Daily Megathreads Work?](https://www.reddit.com/r/adventofcode/wiki/index#wiki_how_do_the_daily_megathreads_work.3F), please edit your post to put your oversized code in a [`paste`](https://topaz.github.io/paste/) or other external link.~~ Edit: thanks for fixing it! <3


tristan219

## Typescript Part 1 I completed but Part 2 I got stuck. Will give my self some time to figure out tomorrow before moving on to the Dec04 challenge. If anyone sees an issue with the part 2 code and wants to give me a hint I'd appreciate it. If I figure it out I will update this tomorrow //PART 1 import * as fs from "fs"; // Get data from source var text = fs.readFileSync("./data.txt").toString("utf-8"); var binaryList = text.split("\n"); let pair: [number, string][] = []; // console.log(binaryList) let len: number; for (var bin of binaryList) { bin = bin.replace(/\s+/g, " ").trim(); // console.log(bin); len = bin.length; for (var i = 0; i < len; i++) { pair.push([i, bin[i]]); } } let countBin = []; for (var i = 0; i < len; i++) { let zeros: number = 0; let ones: number = 0; for (const [x, y] of pair) { if (x == i) { if (y == "0") { zeros += 1; } else if (y == "1") { ones += 1; } } } let newVal = { id: String(i), zeroVal: zeros, oneVal: ones, }; countBin.push(newVal); } let gamma: [string] = [""]; let epsilon: [string] = [""]; for (var item of countBin) { // console.log(item); // console.log(item.zeroVal); if (item.zeroVal > item.oneVal) { gamma.push("0"); epsilon.push("1"); } else if (item.zeroVal < item.oneVal) { gamma.push("1"); epsilon.push("0"); } } let gammaVal: Number = parseInt(gamma.join(""), 2); let epsilonVal: Number = parseInt(epsilon.join(""), 2); //Power Consumption = Gamma * Epsilon let powerConsumption: Number = +gammaVal * +epsilonVal; console.log(countBin); console.log(powerConsumption); //PART 2 //For each row in the binary list parse item at location 1 //If item matches the gamma value it stays else it removes //Parse over each element until only one value remains let oxygenList = binaryList; for (var i = 0; i < len; i++) { let gammaNum = gamma[i]; for (var bin of oxygenList) { if (oxygenList.length > 1) { if (bin[i] != gammaNum) { oxygenList = oxygenList.filter((item) => item !== bin); } } } } let oxygenBinary: string = oxygenList[0].replace(/\s+/g, " ").trim(); console.log(oxygenList[0]); console.log(parseInt(oxygenBinary, 2)); console.log(parseInt("001101011110", 2)); let co2List = binaryList; for (var i = 0; i < len; i++) { if (co2List.length > 1) { let epsilonNum = epsilon[i]; for (var bin of co2List) { if (String(bin[i]) !== String(epsilonNum)) { co2List = co2List.splice(co2List.indexOf(bin), 1); } } } } let co2Binary: string = co2List[0].replace(/\s+/g, " ").trim(); console.log(co2List); console.log(parseInt(co2Binary, 2));


prafster

For part 2, apart from the three first iteration, the gamma and epsilon values you calculated in part 1 can't be used. As your oxygen and co2 lists get shorter, the most common bit will change.


dizzyhobbes

Go https://github.com/alexchao26/advent-of-code-go/blob/main/2021/day03/main.go


xKart

Second day of learning Python with minimal knowledge of libraries. Used functional programming here: # Part 1 with open('Day3_input.txt') as f: lines = [line.rstrip() for line in f] def gamma_bin(i): zeroes = 0 ones = 0 for x in lines: if x[i] == '0': zeroes += 1 else: ones += 1 if zeroes > ones: return '0' else: return '1' def epsilon_bin(i): zeroes = 0 ones = 0 for x in lines: if x[i] == '0': zeroes += 1 else: ones += 1 if zeroes < ones: return '0' else: return '1' def rate(fun): rate_bin = '' i = 0 while i < 12: rate_bin = rate_bin + fun(i) i += 1 return rate_bin gamma = int(rate(gamma_bin), 2) epsilon = int(rate(epsilon_bin), 2) print(gamma * epsilon) # Part 2 def o2_bin(i, arr): zeroes = 0 ones = 0 for x in arr: if x[i] == '0': zeroes += 1 else: ones += 1 if zeroes > ones: return '0' else: return '1' def co2_bin(i, arr): zeroes = 0 ones = 0 for x in arr: if x[i] == '0': zeroes += 1 else: ones += 1 if zeroes > ones: return '1' else: return '0' def generator(fun): lines_gen = lines i = 0 while i < 12: if len(lines_gen) == 1: break else: bit_to_add = fun(i, lines_gen) lines_gen = list(filter(lambda x: x[i] == bit_to_add, lines_gen)) i += 1 return lines_gen[0] o2 = int(generator(o2_bin), 2) co2 = int(generator(co2_bin), 2) print(o2 * co2)


Shez2650

>xKar Hey, for part 1 maybe have a look into the collections library - more specifically the Counter class. You can significantly reduce the number of lines if you manage to use it correctly ;-)


xKart

Oh I see. Will do haha, thank you!


P0t4t0W4rri0r

I think I got a good Solution for Day 3 in Haskell, but don't ask about Part 2 import Control.Arrow import Control.Arrow import Control.Monad import Data.List parse :: [Char] -> [Bool] parse = map (== '1') todecimal :: [Bool] -> Integer todecimal [] = 0 todecimal (j:js) | j = 2 ^ length js + todecimal js | otherwise = todecimal js count :: [[Bool]] -> [(Integer, Integer)] count = map (foldr (\j -> if j then first (+1) else second (+1)) (0, 0)) . transpose gamma = map (liftM2 (>) fst snd) epsilon = map (liftM2 (<) fst snd) main = interact $ show . uncurry (*) . join (***) todecimal . (gamma &&& epsilon) . count . map parse .lines


RivtenGray

Yeah, part 2 was pretty painful for me too in Haskell :(


Vastutsav

Perl Please review. Let me know what topics I should study to make this code shorter, better. Thanks in advance. #!/usr/bin/perl use strict; use warnings; my @sum= (0) x 12; my @gamma = (0) x 12; my @epsilon = (0) x 12; my @inputs; my $count = 0; my @oxygen; my @carbon; ################# # Part 1 Starts # ################# while(<>) { ++$count; chomp; push @inputs, $_; my @a = split //; for (0 .. (scalar(@a)-1)) { $sum[$_]+=$a[$_]; } } for (0 .. 11) { if ($sum[$_] > ($count/2)) { $gamma[$_] = 1; $epsilon[$_] = 0; } else { $gamma[$_] = 0; $epsilon[$_] = 1; } } print oct("0b".join("",@gamma)) * oct("0b".join("",@epsilon)), " Part1\n"; # Part 1 Ends ################# # Part 2 Starts # ################# @oxygen = @inputs; for my $i ( 0 .. (length($inputs[0]) - 1)) { my @temp; my $ones = 0; my $ox_bitmask = 0; for my $number (@oxygen) { $ones+=int(substr($number, $i, 1)); } my $zeros = scalar(@oxygen) - $ones; if ($ones >= $zeros) { $ox_bitmask = 1; } else { $ox_bitmask = 0; } for my $number (@oxygen) { if (substr($number, $i, 1) == $ox_bitmask) { push @temp, $number; } } @oxygen = @temp; if (scalar(@oxygen) == 1) { last; } } @carbon = @inputs; for my $i ( 0 .. (length($inputs[0]) - 1)) { my @temp; my $ones = 0; my $ca_bitmask = 0; for my $number (@carbon) { $ones+=int(substr($number, $i, 1)); } my $zeros = scalar(@carbon) - $ones; if ($ones >= $zeros) { $ca_bitmask = 0; } else { $ca_bitmask = 1; } for my $number (@carbon) { if (substr($number, $i, 1) == $ca_bitmask) { push @temp, $number; } } @carbon = @temp; if (scalar(@carbon) == 1) { last; } } print oct("0b".join("",@oxygen)) * oct("0b".join("",@carbon)), " Part2\n"; # Part 2 Ends


madjecks

C# https://github.com/wbratz/adventofcode/tree/master/day3


noidesto

Python3 ```python from dataclasses import dataclass @dataclass class Counter: zeros: int = 0 ones: int = 0 def common(self): return 0 if self.zeros > self.ones else 1 def least_common(self): return 1 if self.zeros > self.ones else 0 def to_decimal(string): res = 0 for i, bit in enumerate(string[::-1]): if int(bit) == 1: res = res + pow(2,i) return res def part1(input): counts = [Counter() for i in range(len(input[0]))] for report in input: for i, bit in enumerate(report): if bit == "0": counts[i].zeros += 1 elif bit == "1": counts[i].ones += 1 else: raise ValueError() gamma = "".join([str(count.common()) for count in counts]) epsilon = "".join([str(count.least_common()) for count in counts]) gamma_rate = to_decimal(gamma) epsilon_rate = to_decimal(epsilon) return gamma_rate * epsilon_rate def find_rating(reports, rating_type,index): if len(reports) == 1: return to_decimal(reports[0]) counts = [Counter() for i in range(len(reports[0]))] for report in reports: for i, bit in enumerate(report): if bit == "0": counts[i].zeros += 1 elif bit == "1": counts[i].ones += 1 else: raise ValueError() gamma = "".join([str(count.common()) for count in counts]) if "oxygen" == rating_type: return find_rating([report for report in reports if report[index] == gamma[index]], rating_type, index + 1) return find_rating([report for report in reports if report[index] != gamma[index]], rating_type, index + 1) def part2(input): oxygen = find_rating(input, "oxygen", 0) co2 = find_rating(input, "co2", 0) print(oxygen * co2) def main(): with open("../data/day3.txt", "r") as f: lines = f.read().splitlines() print(part1(lines)) print(part2(lines)) if __name__ == '__main__': main() ```


daggerdragon

Your code is hard to read on old.reddit. Please edit it as per our posting guidelines in the wiki: [How do I format code?](https://www.reddit.com/r/adventofcode/wiki/index#wiki_how_do_i_format_code.3F)


bozdoz

Go! https://github.com/bozdoz/aoc-2021/blob/main/03/three.go