Skip to content

Instantly share code, notes, and snippets.

@robhol
Created December 7, 2017 09:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robhol/18207d0d99617e577135f59adb23b773 to your computer and use it in GitHub Desktop.
Save robhol/18207d0d99617e577135f59adb23b773 to your computer and use it in GitHub Desktop.
int Part1(int[] array)
{
var set = new HashSet<string>();
var n = 0;
var d = array.GetDictionary();
while (true)
{
d = Redistribute(d);
n++;
var s = d.GetString();
if (set.Contains(s))
return n;
set.Add(s);
}
}
int Part2(int[] array)
{
var set = new HashSet<string>();
var list = new List<string>();
var n = 0;
var d = array.GetDictionary();
while (true)
{
d = Redistribute(d);
n++;
var s = d.GetString();
if (set.Contains(s))
return n - list.IndexOf(s) - 1;
set.Add(s);
list.Add(s);
}
}
IDictionary<int, int> Redistribute(IDictionary<int, int> banks)
{
var op = banks.Clone();
var top = op
.OrderByDescending(p => p.Value)
.ThenBy(p => p.Key)
.First();
var redist = top.Value;
op[top.Key] = 0;
foreach(var i in GetNaturalNumbers(top.Key + 1))
{
op[i % op.Count]++;
if (--redist == 0)
break;
}
return op;
}
static IEnumerable<int> GetNaturalNumbers(int start)
{
while (true) yield return start++;
}
static class ext
{
static IEnumerable<int> GetNaturalNumbers(int start)
{
while (true) yield return start++;
}
public static IDictionary<int, int> GetDictionary(this int[] d) => Enumerable.Range(0, d.Length)
.ToDictionary(k => k, k => d[k]);
public static string GetString(this IDictionary<int, int> d) => d.Select(x => x.Value).JoinString("-");
public static Dictionary<K, V> Clone<K,V>(this IDictionary<K,V> d) => d.ToDictionary(p => p.Key, p=> p.Value);
public static IDictionary<V, int> GetOccurrences<V>(this IEnumerable<V> e)
{
var output = new Dictionary<V, int>();
foreach (var p in e)
output[p] = output.GetOrDefault(p) + 1;
return output;
}
public static V GetOrDefault<K, V>(this IDictionary<K, V> d, K k, V def = default(V)) => d.TryGetValue(k, out V v) ? v : def;
public static string JoinString<T>(this IEnumerable<T> t, string delimiter = "") => string.Join(delimiter, t);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment