Created
September 25, 2014 20:54
-
-
Save DarranShepherd/d987bffe3b69e519b510 to your computer and use it in GitHub Desktop.
Trello challenge performance comparison
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
namespace TrelloTest | |
{ | |
using System; | |
using System.Collections.Generic; | |
using System.Diagnostics; | |
using System.Globalization; | |
public class Program | |
{ | |
private const long ChallengeHash = 956446786872726; | |
private const string ChallengeWord = "trellises"; | |
private const string Letters = "acdegilmnoprstuw"; | |
public static void Main(string[] args) | |
{ | |
const int Iterations = 1000000; | |
var repeats = 1; | |
if (args.Length > 0) | |
{ | |
if (!int.TryParse(args[0], out repeats)) | |
{ | |
repeats = 1; | |
} | |
} | |
for (var repeat = 0; repeat < repeats; repeat++) | |
{ | |
Time("Analytical", () => Analytical(ChallengeHash), Iterations); | |
Time("Heuristic", () => Heuristic(ChallengeHash), Iterations); | |
} | |
} | |
private static void Time(string name, Func<string> func, int iterations) | |
{ | |
var stopwatch = Stopwatch.StartNew(); | |
for (var i = 0; i < iterations; i++) | |
{ | |
if (func() != ChallengeWord) | |
{ | |
throw new Exception("Didn't calculate expected word"); | |
} | |
} | |
stopwatch.Stop(); | |
Console.WriteLine( | |
"{0}: {1} iterations took {2}ms. {3} ticks per iteration", | |
name, | |
iterations, | |
stopwatch.ElapsedMilliseconds, | |
stopwatch.ElapsedTicks / iterations); | |
} | |
private static string Analytical(long encoded) | |
{ | |
var result = new List<char>(); | |
var remaining = encoded; | |
while (remaining > 7) | |
{ | |
var current = (int)(remaining % 37); | |
result.Insert(0, Letters[current]); | |
remaining = (remaining - current) / 37; | |
} | |
return new string(result.ToArray()); | |
} | |
private static string Heuristic(long desiredOutput) | |
{ | |
var input = "aaaaaaaaa"; | |
var pos = 0; | |
for (var i = 0; i < 9; i++) | |
{ | |
var bestMatch = long.MaxValue; | |
var bestChar = 'a'; | |
foreach (var letter in Letters) | |
{ | |
input = input.Remove(pos, 1).Insert(pos, letter.ToString(CultureInfo.InvariantCulture)); | |
var difference = desiredOutput - Hash(input); | |
if (Math.Abs(difference) < bestMatch) | |
{ | |
bestMatch = difference; | |
bestChar = letter; | |
} | |
} | |
input = input.Remove(pos, 1).Insert(pos, bestChar.ToString(CultureInfo.InvariantCulture)); | |
pos++; | |
} | |
return input; | |
} | |
private static long Hash(string s) | |
{ | |
long result = 7; | |
foreach (char c in s) | |
{ | |
result = (result * 37 + Letters.IndexOf(c)); | |
} | |
return result; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment