Files
AdventOfCode2020/Day5-1.cpp

128 lines
2.5 KiB
C++

//Fun/AdventCalendar2020/Day5-1.cpp
//Matthew Ellison
// Created: 12-05-20
//Modified: 12-05-20
//Find the highest sead ID on a boarding pass
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include "Stopwatch.hpp"
#include "Algorithms.hpp"
struct boardingPass{
std::string passString;
int rowNumber;
int columnNumber;
int seatId;
void setPassString(std::string newPass){
int minRow = 0;
int maxRow = 127;
//Set the whole string
passString = newPass;
//Determine the row the seat is in
for(int cnt = 0;cnt < 7;++cnt){
char half = newPass[cnt];
//Keep the smaller half
if(half == 'F'){
maxRow = (minRow + maxRow) / 2;
}
//Keep the larger half
else if(half == 'B'){
minRow = ((minRow + maxRow) / 2) + 1;
}
else{
std::cout << "ERROR! half must == F or B" << std::endl;
exit(1);
}
}
if(newPass[6] == 'F'){
rowNumber = maxRow;
}
else{
rowNumber = minRow;
}
int minSeat = 0;
int maxSeat = 7;
//Determine the column the seat is in
for(int cnt = 7;cnt < 10;++cnt){
char half = newPass[cnt];
if(half == 'L'){
maxSeat = (minSeat + maxSeat) / 2;
}
else if(half == 'R'){
minSeat = ((minSeat + maxSeat) / 2) + 1;
}
else{
std::cout << "ERROR! half must == R or L" << std::endl;
exit(1);
}
}
if(newPass[9] == 'L'){
columnNumber = maxSeat;
}
else{
columnNumber = minSeat;
}
//Determine the seatId
seatId = (rowNumber * 8) + columnNumber;
}
};
std::vector<boardingPass> importData(){
std::vector<boardingPass> boardingPasses;
std::ifstream inputFile("inputs/Day5.txt"); //Open the input file
//Go through every element in the file and set it in the vector
int cnt = 1;
while(!inputFile.eof()){
boardingPass pass;
std::string currentPass;
inputFile >> currentPass;
if(!currentPass.empty()){
pass.setPassString(currentPass);
}
++cnt;
boardingPasses.push_back(pass);
}
return boardingPasses;
}
int main(){
mee::Stopwatch timer;
std::vector<boardingPass> passes = importData();
boardingPass maxPass;
//Start the timer
timer.start();
//Find the largest seatId in the vector
for(boardingPass currentPass : passes){
if(currentPass.seatId > maxPass.seatId){
maxPass = currentPass;
}
}
//Stop the timer
timer.stop();
//Print the results
std::cout << "The highest seatId = " << maxPass.seatId
<<"\nIt took " << timer.getStr() << " to finish this problem" << std::endl;
return 0;
}
/* Results:
The highest seatId = 813
It took 0.000 nanoseconds to finish this problem
*/