Skip to content

Instantly share code, notes, and snippets.

@archer884
Last active Dec 4, 2017
Embed
What would you like to do?
AOC/4 (C#)
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