Day 1

Back to index | Next: Day 02

Beep beep

Below is an auto-generated list of EVERY entry with ‘day01’ in the title.
###AUTO-ACQUIRED DATA FOLLOWS…
archivist/day01.hs
archivist/day01.hs
biggerCount :: [Integer] -> Integer
    biggerCount l = if length(l) == 2
    then bigger (head l) (head (tail l)) 
    else bigger (head l) (head (tail l))  + (biggerCount (tail l))
    
    biggerCount2 :: [Integer] -> Integer
    biggerCount2 l = 
        let a = (l!!0 + l!!1 + l!!2) 
            b = (l!!1 + l!!2 + l!!3) 
        in if length(l) == 4
        then bigger a b 
        else bigger a b + (biggerCount2 (tail l))
    
    bigger :: Integer -> Integer -> Integer
    bigger a b = if a < b then 1 else 0
    
    main = interact nCount
        where nCount input = show (biggerCount2 (map read (lines input) :: [Integer]))
    
cheesewheel/cheesewheel-day01-1.cs
cheesewheel/cheesewheel-day01-1.cs
using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace Assignment_1 {
        class Program {
            static void Main(string[] args) {
                int increaseCounter = 0;
                int same = 0;
                int currentMes = 0;
                int lastMes = 0;
    
                foreach (string line in System.IO.File.ReadLines("../../input.txt")) {
                    currentMes = int.Parse(line);
                    string output = currentMes.ToString();
    
                    if (lastMes == 0) {
                        output += " (N/A - no previous measurement)";
                    }
                    else {
                        if (lastMes < currentMes) {
                            increaseCounter++;
                            output += " (increased)";
                        }
                        else {
                            if (lastMes > currentMes) {
                                output += " (decreased)";
                            }
                            else {
                                same++;
                            }
                            
                        }
                    }
    
                    Console.WriteLine(output);
                    lastMes = currentMes;
                }
    
                Console.WriteLine("Total amount measurement increased: " + increaseCounter + ". Total amount it stayed the same: " + same);
                Console.ReadLine();
    
            }
        }
    }
    
cheesewheel/cheesewheel-day01-2.cs
cheesewheel/cheesewheel-day01-2.cs
using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace Assignment_2 {
        class Program {
            static void Main(string[] args) {
                List<int> measureList = new List<int>();
                int currentSum = 0;
                int lastSum = 0;
                int increaseCounter = 0;
    
                foreach (string line in System.IO.File.ReadLines("../../input.txt")) {
                    measureList.Add(int.Parse(line));
                }
    
                for (int i = 0; (i+2) < measureList.Count(); i++) {
                    currentSum = measureList[i] + measureList[i+1] + measureList[i+2];
                    string output = currentSum.ToString();
    
                    if (lastSum == 0) {
                        output += " (N/A - no previous measurement)";
                    }
                    else {
                        if (currentSum > lastSum) {
                            increaseCounter++;
                            output += " (increased)";
                        }
                        else {
                            if (currentSum < lastSum) {
                                output += " (decreased)";
                            }
                            else {
                                output += " (no change)";
                            }
                        }
                    }
    
                    lastSum = currentSum;
                    Console.WriteLine(output);
                }
    
                Console.WriteLine("Total amount measurement increased: " + increaseCounter);
                Console.ReadLine();
            }
        }
    }
    
crystanon/day01.cr
crystanon/day01.cr
puts "What file would you like to solve for?"
    print "> "
    
    file = gets.not_nil!
    
    unless File.exists? file
      puts "You must provide a valid file!"
      exit
    end
    
    numbers = File.read(file).split("\n").map { |num| num.to_i }
    
    def getFirstAnswer(numbers)
      currentnum = numbers[0]
      count = 0
    
      numbers.each do |num|
        count += 1 if num > currentnum
    
        currentnum = num
      end
    
      count
    end
    
    def getSecondAnswer(numbers)
      previoussum = 0
      count = 0
    
      numbers.each_with_index do |num, index|
        unless (index + 2) >= numbers.size
          sum = num + numbers[index + 1] + numbers[index + 2]
          count += 1 if sum > previoussum
    
          previoussum = sum
        end
      end
    
      count - 1
    end
    
    puts "The first answer is: #{getFirstAnswer numbers}"
    puts "The second answer is: #{getSecondAnswer numbers}"
    
crystanon/day01-smol.cr
crystanon/day01-smol.cr
puts "What file would you like to solve for?"
    
    print "> "
    
    file = gets.not_nil!
    
    unless File.exists? file
      puts "You must provide a valid file!"
      exit
    end
    
    numbers = File.read(file).lines.map{|num| num.to_i}
    
    def getFirstAnswer(numbers)
      numbers.each.cons_pair.count{|x,y| y>x}
    end
    
    def getSecondAnswer(numbers)
      numbers.each.cons(3).cons_pair.count{|x,y| y.sum>x.sum}
    end
    
    puts "The first answer is: #{getFirstAnswer numbers}"
    puts "The second answer is: #{getSecondAnswer numbers}"
    
day-01/aoc-day01.py
day-01/aoc-day01.py
#pls no bully, left CS and haven't written a line of code outside of stats shit in ~4 years
    inF = open('input.txt', 'r')
    inputArray = inF.read().split()
    inputArray = list(map(int, inputArray))
    def Part1(inputArray):
        cnt = 0
        for x in range(1, len(inputArray)):
            if inputArray[x] - inputArray[x - 1] > 0:
                cnt += 1
        return cnt
    def Part2(inputArray):
        cnt = 0
        try:
            for x in range(0, len(inputArray)):
                set1 = inputArray[x] + inputArray[x + 1] + inputArray[x + 2]
                set2 = inputArray[x + 1] + inputArray[x + 2] + inputArray[x + 3]
                if set2 - set1 > 0:
                    cnt += 1
        except IndexError:
            return cnt
    print("Part 1:" + str(Part1(inputArray)))
    print("Part 2:" + str(Part2(inputArray)))
    
day-01/day01-1.lua
day-01/day01-1.lua
local previousDepth
    local increaseCount = 0
    
    for depth in io.lines("input.txt") do
        if previousDepth then
            if tonumber(depth) > tonumber(previousDepth) then
                print(depth, "(increased)")
                increaseCount = increaseCount + 1
            else
                print(depth, "(decreased)")
            end
        end
        previousDepth = depth
    end
    
    print("There are " .. increaseCount .. " increases in depth.")
    
day-01/day01-1.py
day-01/day01-1.py
#!/usr/bin/python3
    
    import json
    
    with open("input.txt", "r", encoding="utf-8") as f:
        nums = [int(n.strip()) for n in f.readlines()]
    
    def my_generator(ns: [int], size: int) -> int:
        i = 0
        for i in range(len(ns) - size + 1):
            yield tuple(ns[i:i + size])
    
    def my_generator2(ns: [int], size: int) -> int:
        s = sum(ns[:size])
        yield s
        for i, n in enumerate(ns[:-size]):
            s = s - n + ns[i + size]
            yield s
    
    inc = 0
    window_sums = my_generator2(nums, 3)
    last = next(window_sums)
    
    for n in window_sums:
        if n > last:
            inc += 1
        last = n
    
    print(inc)
    
day-01/day01-2.lua
day-01/day01-2.lua
--Create sums table (sliding window groups of 3)
    local sums = {}
    for depth in io.lines("input.txt") do
        for _, v in pairs(sums) do
            if #v < 3 then
                table.insert(v, tonumber(depth))
            end
        end
        table.insert(sums, {tonumber(depth)})
    end
    
    --Check for increases in sums
    local increaseCount = 0
    for i, v in pairs(sums) do
        if i ~= 1 and #v == 3 then
            local sum = v[1] + v[2] + v[3]
            local previousSum = sums[i - 1][1] + sums[i - 1][2] + sums[i - 1][3]
            if sum > previousSum then
                print(sum, ">", previousSum)
                increaseCount = increaseCount + 1
            end
        end
    end
    
    print("There are " .. increaseCount .. " increases in sums.")
    
day-01/day01-2.py
day-01/day01-2.py
#!/usr/bin/env python3
    
    depths = []
    
    while True:
        try:
            line = input()
            try:
                if line:
                    depths.append(int(line))
                else:
                    break
            except:
                pass
        except:
            break
    
    windowSums = [0] \* (len(depths) - 2 )
    for i, sum in enumerate(windowSums):
        windowSums[i] = depths[i] + depths[i+1] + depths[i+2]
    
    
    largerThanPrevSum = 0
    prevSum = None
    for sum in windowSums:
        if prevSum is None:
            prevSum = sum
            continue
        elif sum > prevSum:
            largerThanPrevSum = largerThanPrevSum + 1
        prevSum = sum
    
    print(largerThanPrevSum)
    
day-01/day01.apl
day-01/day01.apl
⍝ read input from file
    i¨⎕NGET'1-1.txt'1
    
    ⍝ print answer to part 1
    ≢⍸0(1i)-(¯1i) 
    
    ⍝ print answer to part 2
    j(¯2i)+(1¯1i)+(2i)
    ≢⍸0(1j)-(¯1j)
    
day-01/day01.cpp
day-01/day01.cpp
#include <iostream>
    #include <fstream>
    #include <vector>
    
    int main(int argv, const char \*argc[]) {
        std::ifstream inputFile(argc[1]);
    
        uint64_t resultPart1 = 0, resultPart2 = 0;
    
        uint64_t depthWindow[4];
        inputFile >> depthWindow[0];
        inputFile >> depthWindow[1];
        inputFile >> depthWindow[2];
    
        if (depthWindow[1] > depthWindow[0]) resultPart1++;
        if (depthWindow[2] > depthWindow[1]) resultPart1++;
    
        while (inputFile >> depthWindow[3]) {
            if (depthWindow[3] > depthWindow[2]) resultPart1++;
            if ((depthWindow[3] + depthWindow[2] + depthWindow[1]) > (depthWindow[2] + depthWindow[1] + depthWindow[0])) {
                resultPart2++;
            }
    
            depthWindow[0] = depthWindow[1];
            depthWindow[1] = depthWindow[2];
            depthWindow[2] = depthWindow[3];
        }
    
        inputFile.close();
    
        std::cout << "Part 1: " << resultPart1 << std::endl;
        std::cout << "Part 2: " << resultPart2 << std::endl;
    
        return 0;
    }
    
day-01/day01.cs
day-01/day01.cs
using System;
    using System.IO;
    using System.Collections.Generic;
    
    namespace AOC_21_D01
    {
        class Program
        {
            public static void Solve(List<int> iList)
            {
                var counter = new int[] { 0, 0 };    //counts number of increments
                for (int i = 1; i < iList.Count; i++)
                {
                    if (iList[i] > iList[i - 1]) counter[0]++;  //Part A
                    if (i > 3 && iList[i] > iList[i - 3]) counter[1]++; //Part B
                }
    
                Console.WriteLine("{0}, {1}", counter[0], counter[1]);
            }
            static void Main(string[] args)
            {
                var fin = new StreamReader("../../input.txt");
                var dataset = new List<int>();
                using(fin) while(!fin.EndOfStream) dataset.Add(int.Parse(fin.ReadLine()));
    
                Solve(dataset);
            }
        }
    }
    
day-01/day01.go
day-01/day01.go
package main
    
    import (
        "os"
        "fmt"
        "bufio"
        "strconv"
    )
    
    func main() {
        //open the file
        f, _ := os.Open("input.txt")
    
        // new scanner
        scanner := bufio.NewScanner(f)
    
        // read by word
        scanner.Split(bufio.ScanWords)
    
        // create counter
        counter := 0
    
            // iterate scanner to get array size
        for scanner.Scan() {
                    counter = counter + 1
        }
    
            // create a slice
            depths := make([]int, counter)
    
            // reset counter
            counter = 0
            f.Close()
            anotherf, _ := os.Open("input.txt")
            // new scanner
            anotherscanner := bufio.NewScanner(anotherf)
    
            // read by word
            anotherscanner.Split(bufio.ScanWords)
    
            // iterate scanner again to stuff everything into slice
        for anotherscanner.Scan() {
                // convert to int
                val, _ := strconv.Atoi(anotherscanner.Text())
                // add int at array position counter
    
                // add val to depths at counter
                depths[counter] = val
    
                // increment counter
                counter = counter + 1
            }
    
            // create counter for increases
            increases := 0
    
            // part 1
            // iterate the whole slice -1 so that it's not overflowing
            for j :=0; j < counter -1 ; j++ {
                    if depths[j] < depths[j+1] {
                            increases = increases + 1
                    }
            }
            fmt.Println(increases)
            increases = 0
    
            // part 2
            // iterate the whole slice -3 so that it's not overflowing
            for k :=0; k < counter - 3 ; k++ {
                firstmeasure := depths[k] + depths[k+1] + depths[k+2]
                secondmeasure := depths[k+1] + depths[k+2] + depths[k+3]
    
                if firstmeasure < secondmeasure {
                    increases = increases + 1
                }
            }
            fmt.Println(increases)
    }
    
day-01/day01.lisp
day-01/day01.lisp
(defun get-input (filename)
      (with-open-file (stream filename)
        (loop for line = (read stream nil)
              while line collect line)))
    
    (defun get-answer (input1 input2)
      (reduce #'+ (mapcar #'(lambda (x y) (if (> y x) 1 0)) input1 input2)))
    
    (defun print-answers ()
      (let ((input (get-input "input.txt")))
        (format t "~&Part 1 Answer: ~S~&Part 2 Answer: ~S~&"
                (get-answer input (cdr input)) (get-answer input (nthcdr 3 input)))))
    
    (print-answers)
    
day-01/day01.ml
day-01/day01.ml
(\* Cancer (2-nd program in ocaml) \*)
    
    (\* Dependency: core \*)
    
    let read_file filename =
        let file = Core.In_channel.create filename in
        let strings = Core.In_channel.input_lines file in
        Core.In_channel.close file;
        strings
    
    let day1 lines second_part = 
        let increased x y = x > y in
        let data = List.map int_of_string lines in
        let count a =
            let list = List.filter (fun x -> x) a in
            List.length list
        in
        let f = match second_part with
            | false ->
                (fun a -> 
                    let rec f a x = match a with
                        | [] -> []
                        | hd::tl ->
                            let value = increased hd x in
                            let next = f tl hd in
                            value :: next
                    in
                    let g a = match a with
                        | [] -> []
                        | hd::tl ->
                                f tl hd
                    in
                    g a
                )
            | true ->
                (fun a ->
                    let rec f a x1 x2 y = match a with
                        | [] -> []
                        | hd::tl ->
                            let sum = hd + x1 + x2 in
                            let value = increased sum y in
                            let next = f tl hd x1 sum in
                            value :: next
                    in
                    let g a = match a with
                        | [] -> []
                        | hd1::tl -> match tl with
                            | [] -> []
                            | hd2::tl -> match tl with
                                | [] -> []
                                | hd3::tl -> f tl hd2 hd3 (hd1 + hd2 + hd3)
                    in
                    g a
                )
        in
        count (f data)
    
    
    let () = 
        let file = read_file "data/day1.txt" in
        let o = day1 file true in
        print_int o
            
    
day-01/day01.nim
day-01/day01.nim
import strutils, sequtils
    
    let input = readFile("input/day01.txt").strip().splitLines().map(parseInt)
    
    proc increased(input: seq[int], winsize: int): int = 
        for i in 0..<input.len()-winsize:
            if input[i+winsize] > input[i]:
                inc result
    
    echo "Part 1: ", increased(input,1)
    echo "Part 2: ", increased(input,3)
    
day-01/day01.py
day-01/day01.py
from sys import argv
    with open(argv[1], "r") as f:
        lines = f.readlines()
    lines = [int(string) for string in lines]
    
    def count_increases(lst):
        prev_elem = None
        count = 0
        for elem in lst:
            if prev_elem != None:
                if elem > prev_elem:
                    count += 1
            prev_elem = elem
        return count
    
    lines_of_three = [0] \* (len(lines) - 2)
    for i in range(3):
        for j in range(len(lines) - 2):
            lines_of_three[j] += lines[j + i]
    
    print(count_increases(lines))
    print(count_increases(lines_of_three))
    
day-01/day01.rs
day-01/day01.rs
#![feature(array_windows)]
    use std::fs;
    
    /// AoC2021 Day 1, Rust 2021 nightly with array_windows
    fn main() {
        let mut input = fs::read_to_string("input")
            .unwrap().lines()
            .map(|x| x.parse().unwrap())
            .collect::<Vec<i32>>();
    
        println!("{}", puzzle1(&input));
        println!("{}", puzzle2(&input));
    }
    
    fn puzzle1(input: &[i32]) -> i32{
        input.array_windows()
             .fold(0, |acc, [a, b]|
                 { if a < b { acc + 1 }
                 else       { acc     } })
    }
    
    fn puzzle2(input: &[i32]) -> i32{
        input.array_windows()
             .fold(0, |acc, [a, b, c, d]|
                 { if a+b+c < b+c+d { acc + 1 }
                   else             { acc     } })
    }
    
day-01/macroman-day01.c
day-01/macroman-day01.c
#include <stdio.h>
    
    #define SECOND_PART
    
    int nextValue(int filt[3], int new);
    
    int main()
    {
        FILE\* f_input;
        f_input = fopen("input.txt","r");
    #ifndef SECOND_PART
        int depth;
        fscanf(f_input, "%i ", &depth);
        
        int oDepth = depth;
        int count = 0;
    
        while(fscanf(f_input, "%i ", &depth) > 0)
        {
            if(oDepth<depth)
            {
                count++;
            }
            oDepth = depth;
        }
    
        printf("%i \n", count);
    #endif
    #ifdef SECOND_PART
        int depths [3] = {0, 0, 0};
        int count = 0;
        int mes, depth, oDepth;
    
        fscanf(f_input, "%i ", &mes);
        depth = nextValue(depths, mes);
        fscanf(f_input, "%i ", &mes);
        depth = nextValue(depths, mes);
        fscanf(f_input, "%i ", &mes);
        depth = nextValue(depths, mes);
    
        oDepth = depth;
    
        while(fscanf(f_input, "%i ", &mes) > 0)
        {
            depth = nextValue(depths, mes);
            if(oDepth<depth)
            {
                count++;
            }
            oDepth = depth;
        }
    
        printf("%i", count);
    #endif
        return 0;
    }
    
    int nextValue(int depths[3], int newDepth)
    {
        depths[0] = depths[1];
        depths[1] = depths[2];
        depths[2] = newDepth;
    
        return depths[0] + depths[1] + depths[2];
    }
    
day-01/other-day01.py
day-01/other-day01.py
from sys import argv
    with open(argv[1], "r") as f:
        lines = f.readlines()
    lines = [int(string) for string in lines]
    
    def count_increases(lst):
        prev_elem = None
        count = 0
        for elem in lst:
            if prev_elem != None:
                if elem > prev_elem:
                    count += 1
            prev_elem = elem
        return count
    
    lines_of_three = [0] \* (len(lines) - 2)
    for i in range(3):
        for j in range(len(lines) - 2):
            lines_of_three[j] += lines[j + i]
    
    print(count_increases(lines))
    print(count_increases(lines_of_three))
    
day-01/p1day01.R
day-01/p1day01.R
in1 <- diff(strtoi(readLines(file.choose())))
    cnt <- 0
    for (i in in1){
      if(i > 0)
        cnt <- cnt + 1
    }
    print(cnt)
    
day-01/p2day01.R
day-01/p2day01.R
in2 <- strtoi(readLines(file.choose()))
    cnt <- 0
    p2list <- c()
    for (x in 1:length(in2)){
      newSet <- in2[x] + in2[x+1] + in2[x+2]
      p2list <- c(p2list, newSet)
    }
    p2list <- na.omit(p2list)
    for (y in diff(p2list)){
      if(y > 0)
        cnt <- cnt +1
    }
    print(cnt)
    
day-01/pythonicanon-day01.py
day-01/pythonicanon-day01.py
def increment_counter(list, w_size):
        '''
        Calculates number of increments by
        comparing the current window's first
        number to it's sucessor's last number.
    
        Example:
    
        window_a = a + b + c
        window_b = b + c + d
    
        window_b > window_a if d > a
        '''
        counter = 0
        for i in range(len(list)):
            if i > (len(list) - 1  - w_size): break # checks if it's the last window
            elif list[i] < list[i+w_size]: counter += 1
        return counter
    
    depths = [int(depth) for depth in open("input.txt", "r").readlines()]
    
    print(increment_counter(depths, 1), increment_counter(depths, 3))
    
dutchanon/dutchanon_day01-1.c
dutchanon/dutchanon_day01-1.c
#include <stdio.h>
    #include <stdlib.h>
    
    int calcDistance()
    {
        FILE \* fPointer = fopen("input.txt", "r");
        int line;
        int numList[2000];
        int larger = 0;
    
        // Making an array out of the input
        // Maakt een array van de input
        for (int i = 0; i < 2000; i++ )
        {
            fscanf(fPointer, "%d", &line);
            numList[i] = line;
        }
        for ( int j = 0; j < 2000; j++ )
        {
            // An if statement without actually using if, if left < right, than it will create 1 between parantheses, otherwise it will create 0. This increases the program slightly.
            // Een if statement zonder daadwerkelijk "if" te gebruiken. Als links < recht, dan maakt het een 1 tussen aanhalingstekens, anders maakt het een 0. Hierdoor is het programma net iets sneller
            larger = larger + 1\*(numList[j] < numList[j+1]);
        }
        return larger;
        fclose(fPointer);
    }
    
    int main()
    {
        printf("%d\n", calcDistance());
    }
    
dutchanon/dutchanon_day01-2.c
dutchanon/dutchanon_day01-2.c
#include <stdio.h>
    #include <stdlib.h>
    
    int calcDistance()
    {
        FILE \* fPointer = fopen("input.txt", "r");
        int line;
        int numList[2000];
        int larger = 0;
    
        // Making an array out of the input
        // Maakt een array van de input
        for (int i = 0; i < 2000; i++ )
        {
            fscanf(fPointer, "%d", &line);
            numList[i] = line;
        }
        for ( int j = 0; j < 2000; j++ )
        {
            // An if statement without actually using if, if left < right, than it will create 1 between parantheses, otherwise it will create 0. This increases the program slightly.
            // Een if statement zonder daadwerkelijk "if" te gebruiken. Als links < recht, dan maakt het een 1 tussen aanhalingstekens, anders maakt het een 0. Hierdoor is het programma net iets sneller
            larger = larger + 1\*(numList[j-2] + numList[j-1] + numList[j] < numList[j-1] + numList[j] + numList[j+1]);
        }
        return larger;
        fclose(fPointer);
    }
    
    int main()
    {
        printf("%d\n", calcDistance());
    }
    
munashe/munashe-day01.c
munashe/munashe-day01.c
// 2021-11-30
    // Advent of Code 2021 Day 1
    // Munashe
    
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <stdbool.h>
    #include <stdint.h>
    
    #define BUFF_CAP 2048
    
    int main(void){
        char fileName[] = "input.txt";
        FILE \*fp = fopen(fileName, "r");
        int numbers[BUFF_CAP] = {0};
        int lineCount = 0;
        if(!fp) {
            fprintf(stderr, "Could not open %s\n", fileName);
        }
        while(fscanf(fp, "%d", &numbers[lineCount++]) != EOF);
        fclose(fp);
        
        int part1 = 0;
        for(int i = 0; i < lineCount; ++i){
            part1 += numbers[i] < numbers[i+1] ? 1 : 0;
        }
        
        int part2 = 0;
        for(int i = 0; i < lineCount-2; ++i){
            int sum1 = numbers[i] + numbers[i+1] + numbers[i+2];
            int sum2 = numbers[i+1] + numbers[i+2] + numbers[i+3];
            if(sum1 < sum2){
                sum1 = numbers[i] + numbers[i+1] + numbers[i+2];
                part2++;
            }
        }
        printf("part1: %d\n", part1);
        printf("part2: %d\n", part2);
        return 0;
    }
    
smolheck/smolheck-day01.py
smolheck/smolheck-day01.py
win = 3 # window
    nums = [ int(line) for line in open('input').readlines() ]
    res = [ sum(nums[i+1:i+1+win]) > sum(nums[i:i+win]) for i in range(len(nums)) ]
    print(res.count(True))
    
smolheck/smolheck_day01.py
smolheck/smolheck_day01.py
#!/usr/bin/python
    
    nums = [ int(line) for line in open('input').readlines() ]
    def solve(n):
        return sum(y > x for x,y in zip(nums, nums[n:]))
    
    print("Part 1:", solve(1))
    print("Part 2:", solve(3))
    

Tags: log