Skip to content

Instantly share code, notes, and snippets.

@swegner
Last active August 29, 2015 14:18
Show Gist options
  • Save swegner/5299832379eab09b3de1 to your computer and use it in GitHub Desktop.
Save swegner/5299832379eab09b3de1 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
public class Flight
{
public string FeatureArea { get; private set; }
public int TrafficPercent { get; private set; }
public Flight(string featureArea, int trafficPercent)
{
FeatureArea = featureArea;
TrafficPercent = trafficPercent;
}
}
public class User
{
public Guid Id { get; private set; }
public User() { Id = Guid.NewGuid(); }
}
public class FlightAssignment
{
private Dictionary<string, Flight[]> _flightAssignments = new Dictionary<string, Flight[]>();
public void Add(Flight flight)
{
Flight[] trafficBuckets;
if (!_flightAssignments.TryGetValue(flight.FeatureArea, out trafficBuckets))
{
trafficBuckets = new Flight[100];
_flightAssignments.Add(flight.FeatureArea, trafficBuckets);
}
int trafficToAssign = flight.TrafficPercent;
for (int i = 0; i < 100; i++)
{
if (trafficBuckets[i] == null)
{
trafficBuckets[i] = flight;
trafficToAssign--;
if (trafficToAssign == 0) break;
}
}
}
public void Remove(Flight flight)
{
var trafficBuckets = _flightAssignments[flight.FeatureArea];
var buckets = trafficBuckets;
for (int i = 0; i < 100; i++)
{
if (buckets[i] == flight)
buckets[i] = null;
}
}
public ISet<Flight> GetFlights(User user)
{
int trafficBucket = Math.Abs(user.Id.GetHashCode()) % 100;
var assignments = new HashSet<Flight>();
foreach (var trafficBuckets in _flightAssignments.Values)
{
var flight = trafficBuckets[trafficBucket];
if (flight != null)
assignments.Add(flight);
}
return assignments;
}
}
[TestClass]
public class FlightAssignmentTests
{
private FlightAssignment _assignmentService = new FlightAssignment();
private User _user = new User();
[TestMethod]
public void BasicAssignment()
{
Assert.AreEqual(0, _assignmentService.GetFlights(_user).Count);
var flight = new Flight("UI", trafficPercent: 100);
_assignmentService.Add(flight);
var assignments = _assignmentService.GetFlights(_user);
Assert.AreEqual(1, assignments.Count);
Assert.AreEqual(flight, assignments.Single());
}
[TestMethod]
public void MultipleAssignment()
{
_assignmentService.Add(new Flight("backend", trafficPercent: 100));
_assignmentService.Add(new Flight("frontend", trafficPercent: 100));
var assignments = _assignmentService.GetFlights(_user);
Assert.AreEqual(2, assignments.Count);
}
[TestMethod]
public void MutualExclusiveFeatureFlights()
{
_assignmentService.Add(new Flight("UI", trafficPercent: 50));
_assignmentService.Add(new Flight("UI", trafficPercent: 50));
var assignments = _assignmentService.GetFlights(_user);
Assert.AreEqual(1, assignments.Count);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment