Created
December 14, 2015 14:07
-
-
Save xtrmstep/52b8dc770cc4106dfc08 to your computer and use it in GitHub Desktop.
Convert text ranges to int array and back
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
public static int[] ToIntArray(this string text) | |
{ | |
if (string.IsNullOrWhiteSpace(text)) | |
{ | |
return new int[] | |
{ | |
}; | |
} | |
List<int> result = new List<int>(); | |
string[] ranges = text.Split(','); | |
foreach (string range in ranges) | |
{ | |
string[] pair = range.Split('-'); | |
if (pair.Length == 1) | |
{ | |
result.Add(int.Parse(pair[0])); | |
} | |
if (pair.Length == 2) | |
{ | |
int min = int.Parse(pair[0]); | |
int max = int.Parse(pair[1]); | |
result.AddRange(Enumerable.Range(min, max - min + 1)); | |
} | |
} | |
return result.ToArray(); | |
} | |
public static string ToRanges(this int[] array) | |
{ | |
if (array == null || array.Length == 0) | |
{ | |
return string.Empty; | |
} | |
StringBuilder sb = new StringBuilder(); | |
Array.Sort(array); | |
int predItem = int.MinValue; | |
int seqLength = 0; | |
int nextInt = int.MinValue; | |
for (int index = 0; index < array.Length; index++) | |
{ | |
if (nextInt != array[index]) | |
{ | |
if (sb.Length == 0) | |
{ | |
sb.Append(array[index]); | |
} | |
else if (seqLength == 0) | |
{ | |
sb.AppendFormat(",{0}", array[index]); | |
} | |
else | |
{ | |
sb.AppendFormat("-{0},{1}", predItem, array[index]); | |
} | |
seqLength = 0; | |
} | |
else | |
{ | |
seqLength++; // sequence of items which goes 1 by 1 | |
if (index == array.Length - 1) | |
{ | |
sb.AppendFormat("-{0}", array[index]); | |
} | |
} | |
predItem = array[index]; | |
nextInt = array[index] + 1; | |
} | |
return sb.ToString(); | |
} | |
/// tests xUnit | |
[Theory] | |
[InlineData("1,2,3-5,7,9-14", new[]{1, 2, 3, 4, 5, 7, 9, 10, 11, 12, 13, 14})] | |
[InlineData("1", new[]{1})] | |
[InlineData("1,2", new[]{1,2})] | |
[InlineData("1-5", new[]{1, 2, 3, 4, 5})] | |
[InlineData("1,3,5,7", new[]{1, 3, 5, 7})] | |
[InlineData("1,5-7,9", new[]{1, 5, 6, 7, 9})] | |
public void ToIntArray_should_convert_rages_to_intArray(string ranges, int[] expected) | |
{ | |
int[] actual = ranges.ToIntArray(); | |
Assert.True(expected.SequenceEqual(actual)); | |
} | |
[Theory] | |
[InlineData(new[]{1, 2, 3, 4, 5, 7, 9, 10, 11, 12, 13, 14}, "1-5,7,9-14")] | |
[InlineData(new[]{1}, "1")] | |
[InlineData(new[]{1, 2}, "1-2")] | |
[InlineData(new[]{1, 3, 5, 7, 9}, "1,3,5,7,9")] | |
[InlineData(new[]{1, 5, 6, 7, 9}, "1,5-7,9")] | |
public void ToRanges_should_convert_intArray_to_ranges(int[] array, string expected) | |
{ | |
string actual = array.ToRanges(); | |
Assert.Equal(expected, actual); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment