Last active
December 4, 2017 19:53
-
-
Save archer884/e00747ec71c978a5ac50262417f6b1e8 to your computer and use it in GitHub Desktop.
AOC/4 (C#)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Diagnostics; | |
using System.Linq; | |
namespace cs_day_4 | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
// Note: 'Resource' is a class which contains the input for the puzzle and the | |
// integer value of 'a'. | |
var time = Stopwatch.StartNew(); | |
Console.WriteLine(CountValidPassphrases(Resource.Input)); | |
time.Stop(); | |
Console.WriteLine(time.ElapsedMilliseconds); | |
} | |
static int CountValidPassphrases(string input) | |
{ | |
var lines = input.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries); | |
return lines.AsParallel().Count(IsValid); | |
} | |
static bool IsValid(string input) | |
{ | |
var words = input.Split(' '); | |
var set = new HashSet<WordMap>(); | |
for (var i = 0; i < words.Length; i++) | |
{ | |
var map = new WordMap(words[i]); | |
if (!set.Add(map)) | |
{ | |
return false; | |
} | |
} | |
return true; | |
} | |
struct WordMap | |
{ | |
public byte[] Counts; | |
public WordMap(string word) | |
{ | |
Counts = new byte[26]; | |
for (var i = 0; i < word.Length; i++) | |
{ | |
var idx = word[i] - Resource.AOffset; | |
++Counts[idx]; | |
} | |
} | |
// This one isn't black magic, but it sure as hell is slow. | |
override public bool Equals(object obj) | |
{ | |
return obj is WordMap && ((WordMap)obj).Counts.SequenceEqual(Counts); | |
} | |
// Black magic from: | |
// https://stackoverflow.com/questions/3404715/c-sharp-hashcode-for-array-of-ints | |
override public int GetHashCode() | |
{ | |
var hc = Counts.Length; | |
for (var i = 0; i < Counts.Length; i++) | |
{ | |
hc = unchecked(hc * 17 + Counts[i]); | |
} | |
return hc; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment