Day 2

Previous: Day 01 | Next: Day 03
###AUTO-ACQUIRED DATA FOLLOWS…
cheesewheel/day02-1.cs
cheesewheel/day02-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 horPos = 0;
                int verPos = 0;
                int movement;
                char action;
                string[] lineSplit;
    
                foreach (string line in System.IO.File.ReadLines("../../input.txt")) {
                    action = line[0];
                    lineSplit = line.Split(' ');
                    movement = int.Parse(lineSplit[1]);
    
                    switch (action) {
                        case 'd':    
                            verPos += movement;
                            Console.WriteLine("The submarine went down {0} units", movement);
                            break;
    
                        case 'f':
                            horPos += movement;
                            Console.WriteLine("The submarine went forward {0} units", movement);
                            break;
    
                        case 'u':
                            verPos -= movement;
                            Console.WriteLine("The submarine went up {0} units", movement);
                            break;
    
                    }
                }
    
                Console.WriteLine("The submarine ends at a depth of {0} units and a horizontal position of {1} units", verPos, horPos);
                Console.WriteLine("Multiplying them gives {0}", verPos \* horPos);
                Console.ReadLine();
            }
        }
    }
    
cheesewheel/day02-2.cs
cheesewheel/day02-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) {
                int horPos = 0;
                int verPos = 0;
                int aim = 0;
                int movement;
                char action;
                string[] lineSplit;
    
                foreach (string line in System.IO.File.ReadLines("../../input.txt")) {
                    action = line[0];
                    lineSplit = line.Split(' ');
                    movement = int.Parse(lineSplit[1]);
    
                    switch (action) {
                        case 'd':
                            aim += movement;
                            Console.WriteLine("The submarine adjusted the aim down with {0} units, it is now {1}", movement, aim);
                            break;
    
                        case 'f':
                            horPos += movement;
                            verPos += movement \* aim;
                            Console.WriteLine("The submarine moved {0} units with an aim of {1}, reaches a depth of {2}", movement, aim, verPos);
                            break;
    
                        case 'u':
                            aim -= movement;
                            Console.WriteLine("The submarine adjusted the aim up with {0} units, it is now {1}", movement, aim);
                            break;
                    }
                }
                Console.WriteLine("Answer: {0}", horPos \* verPos);
                Console.ReadLine();
            }
        }
    }
    
crystanon/day02.cr
crystanon/day02.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
    
    instructions = File.read(file).lines.map {|line| line.split(" ")}
    
    def getFirstAnswer(instructions)
      horizontal = 0
      depth = 0
      instructions.each do |instruction|
        command = instruction[0]
        argument = instruction[1].to_i
        case command
          when "forward"
            horizontal += argument
          when "up"
            depth -= argument
          when "down"
            depth += argument
        end
      end
      horizontal \* depth
    end
    
    def getSecondAnswer(instructions)
      horizontal = 0
      aim = 0
      depth = 0
      instructions.each do |instruction|
        command = instruction[0]
        argument = instruction[1].to_i
        case command
          when "down"
            aim += argument
          when "up"
            aim -= argument
          when "forward"
            horizontal += argument
            depth += aim \* argument
        end
      end
      horizontal \* depth
    end
    
    puts "The first answer is: #{getFirstAnswer instructions}"
    puts "The second answer is: #{getSecondAnswer instructions}"
    
day-02/day02.cmake
day-02/day02.cmake
file(STRINGS "input.txt" day2_input)
    
    set(horizontal 0)
    set(depth 0)
    set(aim 0)
    
    string(REGEX REPLACE "\n" ";" contents "${contents}")
    
    foreach (line ${day2_input})
        string(REPLACE " " ";" arguments ${line})
        list(GET arguments 0 direction)
        list(GET arguments 1 value)
    
        message("${direction} ${value}")
        if (direction STREQUAL "forward")
            math(EXPR horizontal "${horizontal} + ${value}" OUTPUT_FORMAT DECIMAL)
            math(EXPR depth "${depth} + ${aim} \* ${value}" OUTPUT_FORMAT DECIMAL)
        elseif (direction STREQUAL "down")
            math(EXPR aim "${aim} + ${value}" OUTPUT_FORMAT DECIMAL)
        elseif (direction STREQUAL "up")
            math(EXPR aim "${aim} - ${value}" OUTPUT_FORMAT DECIMAL)
        endif ()
    endforeach ()
    
    math(EXPR part1 "${horizontal} \* ${aim}" OUTPUT_FORMAT DECIMAL)
    math(EXPR part2 "${horizontal} \* ${depth}" OUTPUT_FORMAT DECIMAL)
    
    message("Part 1: ${part1}")
    message("Part 2: ${part2}")
    
day-02/day02.cpp
day-02/day02.cpp
#include <iostream>
    #include <fstream>
    #include <vector>
    
    int main(int argv, const char \*argc[]) {
        std::ifstream inputFile(argc[1]);
    
        int64_t horizontalPosition = 0, depth = 0, aim = 0;
    
        std::string string;
        int64_t amount;
    
        while (inputFile >> string >> amount) {
            if (string == "forward") {
                horizontalPosition += amount;
                depth += aim \* amount;
            } else if (string == "down") {
                aim += amount;
            } else if (string == "up") {
                aim -= amount;
            }
        }
    
        inputFile.close();
    
        std::cout << "Part 1: " << horizontalPosition \* aim << std::endl;
        std::cout << "Part 2: " << horizontalPosition \* depth << std::endl;
    
        return 0;
    }
    
day-02/day02.cs
day-02/day02.cs
using System;
    using System.IO;
    using System.Collections.Generic;
    
    namespace AOC_21_D02
    {
        class Program
        {
            public static void Solve(List<string> sList)
            {
                int x = 0;
                int y1 = 0;    //aim for part_b
                int y2 = 0;
    
                foreach (string s in sList)
                {
                    var temp = int.Parse(s.Split()[1]);
                    if (s.Contains("forward"))
                    {
                        x += temp;
                        y2 += y1 \* temp;
                    }
                    else if (s.Contains("down")) y1 += temp;
                    else if (s.Contains("up")) y1 -= temp;
                }
    
                Console.WriteLine("Part A: {0}", x \* y1);
                Console.WriteLine("Part B: {0}", x \* y2);
            }
    
            static void Main(string[] args)
            {
                var fin = new StreamReader("../../input.txt");
                var dataset = new List<string>();
                using (fin) while (!fin.EndOfStream) dataset.Add(fin.ReadLine());
    
                Solve(dataset);
            }
        }
    }
    
day-02/day02.el
day-02/day02.el
(setq path "./input.txt")
    (setq data (split-string (with-temp-buffer
                   (insert-file-contents path)
                   (buffer-string)) "\n"))
    
    
    (defun multiply-position (inputs)
      (let ((h 0) (v 0) (aim 0) (input nil) (command nil) (value 0))
        (while inputs
          (setq input (split-string (pop inputs) " "))
          (setq command  (pop input))
          (setq value (string-to-number (pop input)))
          (cond
           ((string= command "up")
        (setq aim (- aim value)))
           ((string= command "down")
        (setq aim (+ aim value)))
           (t (setq h (+ h value)
            v (+ v (\* aim value))))))
        (list (\* h v) (\* h aim))))
    
    (multiply-position data)
    
day-02/day02.nim
day-02/day02.nim
import strscans
    
    let input = "input/day02.txt"
    
    proc part1(input: string): int = 
        var
            dir: string
            mag,xpos,depth: int
    
        for command in input.lines:
            if command.scanf("$w $i", dir, mag):
                case dir:
                of "forward": xpos += mag
                of "down": depth += mag
                of "up": depth -= mag
        return xpos\*depth
    
    proc part2(input: string): int = 
        var
            dir: string
            mag,xpos,depth,aim: int
    
        for command in input.lines:
            if command.scanf("$w $i", dir, mag):
                case dir:
                of "forward": 
                    xpos += mag
                    depth += (aim\*mag)
                of "down": aim += mag
                of "up": aim -= mag
        return xpos\*depth
    
    echo "Part 1: ", part1(input)
    echo "Part 2: ", part2(input)
    
day-02/day02.ods
day-02/day02.ods
day-02/p2day02.R
day-02/p2day02.R
din <- read.table(file.choose(), sep = "", header = F)
    hpos <- 0
    vpos <- 0
    #interesting idea proposed by someone online, really like the one line elegance
    hpos <- sum(din[din$V1 == 'forward', ]$V2)
    vpos <- sum(din[din$V1 == 'down', ]$V2)
    
    for (x in 1:length(din$V1)){
      if(din$V1[x] == 'forward'){
        hpos <- hpos + din$V2[x]
      }else if(din$V1[x] == 'down'){
        vpos <- vpos + din$V2[x]
      }else{
        vpos <- vpos - din$V2[x]
      }
    }
    print(hpos \* vpos)
    
day-02/pytonicanon-day02.py
day-02/pytonicanon-day02.py
aim, depth, horizontal_pos = 0, 0, 0
    
    '''
    Pretty standard, creates a new list
    out of splits [direction, num] from
    input data an then iterates through
    the array an updates the variables
    as it executes the necessary binary
    operations.
    '''
    
    for info in [info.split() for info in open("input.txt").readlines()]:
        if info[0] == "up": aim -= int(info[1])
        elif info[0] == "down": aim += int(info[1])
        else:
            depth += aim\*int(info[1])
            horizontal_pos += int(info[1])
    
    print(horizontal_pos\*aim, depth\*horizontal_pos)
    
munashe/munashe-day02.c
munashe/munashe-day02.c
// 2021-12-01
    // Advent of Code 2021 Day 2
    // Munashe
    
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    #define CAP 2000
    
    int main(void){
        char fileName[] = "input.txt";
        FILE \*fp = fopen(fileName, "r");
        int numbers[CAP] = {0};
        char commands[CAP][10] = {0};
        int count = 0;
        if(!fp) {
            fprintf(stderr, "Could not open %s\n", fileName);
        }
        while(fscanf(fp, "%s%d\n", commands[count], &numbers[count]) != EOF){
            ++count;
        }
        fclose(fp);
        
        int depth = 0;
        int dist = 0;
        for(int i = 0; i < count; ++i){
            if(commands[i][0] == 'f') { dist += numbers[i]; }
            if(commands[i][0] == 'u') { depth -= numbers[i]; }
            if(commands[i][0] == 'd') { depth += numbers[i]; }
        }
        printf("Part 1: %d\n", depth \* dist);
        
        depth = 0;
        dist = 0;
        int aim = 0;
        for(int i = 0; i < count; ++i){
            if(commands[i][0] == 'f') { dist += numbers[i]; depth += (numbers[i] \* aim); }
            if(commands[i][0] == 'u') { aim -= numbers[i]; }
            if(commands[i][0] == 'd') { aim += numbers[i]; }
        }
        printf("Part 2: %d\n", depth \* dist);
        
        return 0;
    }
    
smolheck/smolheck_day02.py
smolheck/smolheck_day02.py
#!/usr/bin/python
    
    course = [ [c,int(x)] for line in open('input').read().splitlines()
               for c,x in [line.split()] ]
    
    def solve(part):
        hor = 0
        depth = 0
        aim = 0
        for c,x in course:
            if c[0] == 'f':
                hor += x
                if part == 2:
                    aim += depth\*x
            elif c[0] == 'u':
                depth -= x
            elif c[0] == 'd':
                depth += x
        if part == 1:
            return hor\*depth
        else:
            return hor\*aim
    
    print("Part 1:", solve(1))
    print("Part 2:", solve(2))
    

Tags: