Last active
August 29, 2015 14:06
-
-
Save kamiyaowl/59fa3116f18cc4e1012f to your computer and use it in GitHub Desktop.
連続する数値を識別
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[TestFixture] | |
static class Extensions { | |
public static string RangeString(this IEnumerable<int> src) { | |
var grouped = src.RangeGroup() | |
.Select(x => x.Item1 == x.Item2 ? | |
x.Item1.ToString() : | |
string.Format("{0} ... {1}", x.Item1, x.Item2)); | |
var create = grouped.Aggregate("", (s, x) => string.Format("{0}{1},", s, x)); | |
return create.Substring(0, create.Length - 1);//deliminator | |
} | |
/// <summary> | |
/// 連続する数値の開始と終了の数値のタプルを返します | |
/// </summary> | |
/// <param name="src"></param> | |
/// <returns></returns> | |
public static IEnumerable<Tuple<int, int>> RangeGroup(this IEnumerable<int> src) { | |
int start = int.MinValue; | |
int recent = int.MinValue; | |
foreach (var ch in src.OrderBy(x => x).Distinct()) { | |
if (start == int.MinValue) { | |
//開始点 | |
start = ch; | |
recent = ch; | |
} else if (recent == ch - 1) { | |
//中間 | |
recent = ch; | |
} else { | |
//終点 | |
yield return new Tuple<int, int>(start, recent); | |
start = ch; | |
recent = ch; | |
} | |
} | |
yield return new Tuple<int, int>(start, recent); | |
} | |
[Test] | |
public static void RangeStringTest() { | |
var str = new[] { 1, 5, 6, 7, 10, 15, 16, 17, 18, 19 }.ChannelString(); | |
Console.WriteLine(str); | |
Assert.AreEqual("1,5 ... 7,10,15 ... 19", str); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment