Skip to content

Instantly share code, notes, and snippets.

@gingemonster
Created December 4, 2016 07:50
Show Gist options
  • Save gingemonster/c94a02cd6e22c9970a0fc35d5517e1b0 to your computer and use it in GitHub Desktop.
Save gingemonster/c94a02cd6e22c9970a0fc35d5517e1b0 to your computer and use it in GitHub Desktop.
Adventofcode Day 4 - Challenge 2
using System;
using System.IO;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Linq;
namespace ConsoleApplication
{
public class Program
{
public static void Main(string[] args)
{
using(var input = File.OpenText("input.txt")){
string line;
while((line = input.ReadLine()) != null)
{
var room = new Room(line);
if(room.IsValidRoomName() && room.Name.ToLower().Contains("north")){
Console.WriteLine(room.Name + " " + room.SectorId);
}
}
}
}
}
public class Room{
public Room(string encryptedname){
this.parseEncryptedName(encryptedname);
this.Name = DecryptUsingShiftedCypher(this.EncryptedName, this.SectorId);
}
public string EncryptedName{
get;
set;
}
public string Name{
get;
set;
}
public int SectorId{
get;
set;
}
public string CheckSum{
get;
set;
}
private string DecryptUsingShiftedCypher(string input, int shift){
return String.Join("", input.Select(i => this.ShiftChar(i, this.SectorId)).ToArray());
}
private char ShiftChar(char letter, int shift){
var fixedshift = shift % 26;
if(letter==' ') return letter;
var result = (char)(letter + fixedshift);
// Subtract 26 on overflow.
// Add 26 on underflow.
if (result > 'z')
{
result = (char)(result - 26);
}
else if (letter < 'a')
{
result = (char)(result + 26);
}
return result;
}
public bool IsValidRoomName(){
return this.CheckSum == this.CalculateCheckSum();
}
private string CalculateCheckSum(){
return String.Join("",this.GetGroupsOfLetters(this.EncryptedName.Replace(" ", "")));
}
private char[] GetGroupsOfLetters(string input){
var groups = input.GroupBy(c => c).OrderByDescending(g => g.Count()).ThenBy(g => g.Key).Select(g=>g.Key).Take(5).ToArray();
return groups;
}
private void parseEncryptedName(string encryptedname){
var pattern = new Regex(@"(.*)\-(\d*)\[(\w*)\]");
var match = pattern.Match(encryptedname);
this.EncryptedName = match.Groups[1].Value.Replace("-"," ");
this.SectorId = Int32.Parse(match.Groups[2].Value);
this.CheckSum = match.Groups[3].Value;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment