Skip to content

Instantly share code, notes, and snippets.

@jeroenheijmans
Last active April 16, 2018 07:35
Show Gist options
  • Save jeroenheijmans/6a0a0e6ed70ebe5a58f3281170fddc46 to your computer and use it in GitHub Desktop.
Save jeroenheijmans/6a0a0e6ed70ebe5a58f3281170fddc46 to your computer and use it in GitHub Desktop.
CsharpBuddy
/* DISCLAIMER:
* This code is pure adhoc magic. NO WARRANTY or guarantees or
* whatsoever! Use at your own risk!!
*/
using System;
using System.Collections.Generic;
using System.Linq;
namespace CsharpBuddy
{
public class Input
{
public const string folks = @"
empgrid,john
empgrid,jane
halive,mattheus
halive,marcus
halive,marc
karp,mary
karp,michelle
karp,mickey
best bogus,mogthendahl
best bogus,nammus
best bogus,elfie
flex,ike";
public const int seed = 1337;
public const int groupSize = 2;
}
public class Program
{
static void Main(string[] args)
{
var seed = Input.seed;
var input = Buddy.GetCollection();
if (input.Count() % Input.groupSize != 0)
{
throw new InvalidOperationException("Input size not evenly divisible by group size!");
}
var groups = CreateGroups(input, seed++, Input.groupSize);
for (var i = 1; i <= 1000 && groups.Any(g => g.Contains(null)); i++)
{
Console.WriteLine($"Iteration {i}");
groups = CreateGroups(input, seed++, Input.groupSize);
}
Console.WriteLine(string.Join(Environment.NewLine, groups.Select(g => string.Join(" + ", g))));
Console.ReadKey();
}
private static List<List<Buddy>> CreateGroups(ICollection<Buddy> input, int seed, int groupSize)
{
var random = new Random(seed);
var groups = new List<List<Buddy>>();
var people = input.OrderBy(p => p.ToString()).ToList();
while (people.Any())
{
groups.Add(new List<Buddy>());
for (int i = 0; i < groupSize; i++)
{
var buddy = people.OrderBy(b => random.Next()).Where(p => !groups.Last().Select(b => b.Team).Contains(p.Team)).FirstOrDefault();
people.Remove(buddy);
groups.Last().Add(buddy);
}
}
return groups;
}
}
public class Buddy
{
public Buddy(string team, string name)
{
Team = team;
Name = name;
}
public string Team { get; set; }
public string Name { get; set; }
public override string ToString()
{
return $"{Name} ({Team})";
}
public static ICollection<Buddy> GetCollection()
{
return Input.folks
.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None)
.Where(s => !string.IsNullOrWhiteSpace(s))
.Select(s => s.Split(","))
.Select(x => new Buddy(x.FirstOrDefault()?.Trim(), x.LastOrDefault()?.Trim()))
.ToList();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment