Skip to content

Instantly share code, notes, and snippets.

@SLaks
Last active January 1, 2016 18:48
Show Gist options
  • Save SLaks/8185771 to your computer and use it in GitHub Desktop.
Save SLaks/8185771 to your computer and use it in GitHub Desktop.
How not to use LINQ to solve Project Euler #14
// http://projecteuler.net/problem=14
Enumerable.Range(1, 1000000).Select(s =>
Enumerable.Repeat(new List<long>(32) { s }, 1)
.First(list =>
Enumerable.Range(0, Int32.MaxValue)
.TakeWhile(i => list.Last() > 1)
.Aggregate(0, (index, unused) => {
list.Add(list.Last() % 2 == 0 ? list.Last() / 2 : 3 * list.Last() + 1);
return 0;
}) != 42
)
)
.Aggregate((list, result) => list.Count <= result.Count ? result : list)
// About twice as fast, and less evil
Enumerable.Range(1, 1000000).Select(s =>
Enumerable.Repeat(new [] { new { Current = (long)s, Count = 1, Start = s } }, 1)
.Select(c =>
Enumerable.Range(0, int.MaxValue)
.TakeWhile(i => c[0].Current > 1)
.Aggregate (c[0], (t, index) => c[0] =
new { Current = t.Current % 2 == 0 ? t.Current / 2 : 3 * t.Current + 1,
Count = t.Count + 1, t.Start })
).First()
)
.Aggregate((t, result) => t.Count < result.Count ? result : t)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment