Skip to content

Instantly share code, notes, and snippets.

@plaurin
Created December 30, 2013 02:30
Show Gist options
  • Save plaurin/8177119 to your computer and use it in GitHub Desktop.
Save plaurin/8177119 to your computer and use it in GitHub Desktop.
public Slice<T> GetSlice<T>(IEnumerable<Element<T>> elements, double totalSize, double sliceWidth)
{
if (!elements.Any()) return null;
if (elements.Count() == 1) return new Slice<T> { Elements = elements, Size = totalSize };
var sliceResult = GetElementsForSlice(elements, sliceWidth);
return new Slice<T>
{
Elements = elements,
Size = totalSize,
SubSlices = new[]
{
GetSlice(sliceResult.Elements, sliceResult.ElementsSize, sliceWidth),
GetSlice(sliceResult.RemainingElements, 1 - sliceResult.ElementsSize, sliceWidth)
}
};
}
private SliceResult<T> GetElementsForSlice<T>(IEnumerable<Element<T>> elements, double sliceWidth)
{
var elementsInSlice = new List<Element<T>>();
var remainingElements = new List<Element<T>>();
double current = 0;
double total = elements.Sum(x => x.Value);
foreach (var element in elements)
{
if (current > sliceWidth)
remainingElements.Add(element);
else
{
elementsInSlice.Add(element);
current += element.Value / total;
}
}
return new SliceResult<T>
{
Elements = elementsInSlice,
ElementsSize = current,
RemainingElements = remainingElements
};
}
public class SliceResult<T>
{
public IEnumerable<Element<T>> Elements { get; set; }
public double ElementsSize { get; set; }
public IEnumerable<Element<T>> RemainingElements { get; set; }
}
public class Slice<T>
{
public double Size { get; set; }
public IEnumerable<Element<T>> Elements { get; set; }
public IEnumerable<Slice<T>> SubSlices { get; set; }
}
public class Element<T>
{
public T Object { get; set; }
public double Value { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment