Skip to content

Instantly share code, notes, and snippets.

@Immerseit
Created September 5, 2012 14:46
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 Immerseit/3637697 to your computer and use it in GitHub Desktop.
Save Immerseit/3637697 to your computer and use it in GitHub Desktop.
PageFlowSplitter
using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Linq;
namespace PageflowBreaker
{
[TestClass]
public class UnitTest1
{
// Sample real output: a a b b c c c d d d d
// Expected after managed: a a | b b | c c c | d d d | d
// Incorrect after managed: a a b b | c c c | d d d d
[TestMethod]
public void NoFlow()
{
List<string> pageBreaks = new List<string>
{ "a", "a", "b", "b", "c", "c", "c", "d", "d", "d", "d" };
IEnumerable<ItemRow> breakPositions = AnalyzePageflow(pageBreaks);
// Tests
CollectionAssert
.AreEqual(new List<int> { 1, 3, 6, 9, 10 },
breakPositions.Select(d => d.Pos).ToList());
CollectionAssert
.AreEqual(new List<int> { 3, 6, 8 },
breakPositions.Select(d => d.Pos).ToList());
// End tests
}
protected IEnumerable<ItemRow> AnalyzePageflow(IEnumerable<string> pageBreaks)
{
int magicNumber = 3;
var splitted = (from p in pageBreaks
group p by new { Breaker = p } into gr
select new ItemRow {
Letter = gr.Key.Breaker,
Qty = gr.Count()
}).ToList();
foreach (var item in splitted.Where(d => d.Qty > magicNumber).ToArray())
{
int remainder = magicNumber;
while (item.Qty > 0)
{
if (item.Qty < remainder)
remainder = item.Qty % magicNumber;
splitted.Add(new ItemRow() { Qty = remainder, Letter = item.Letter });
item.Qty -= remainder;
}
splitted.Remove(item);
}
int position = -1; // Position start index with base = 0 due to requirement
foreach (var item in splitted)
{
position += item.Qty;
item.Pos += position;
}
return splitted;
}
public class ItemRow
{
public string Letter { get; set; }
public int Qty { get; set; }
public int Pos { get; set; }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment