Home
C# Summary Of Ranges In An Array
Blog Date 12 June 2023
The idea is - given an array of numbers in numerical order - find and record the sequential ranges.
To clarify - given the array of numbers [1,2,3,4,7,8,9] we can see we have sequential numbers 1,2,3,4 - then a gap of more than one - then 7,8,9.
Given the array thus [4,5,6,9,11,45,46,47,99] we would fine we have 4,5,6 then a single number of 9, then a single number of 11, then a sequence of 45,46,47 then a single number of 99.
We need to return 4->6, 9, 11, 45-> 47 and 99.
You know - I can see where this might be used - compression. If you have a massive list of numbers and many of them are sequential (but not all) you might say "1 through 66, then a 74, then 82 through 144, a 152, a 174, then 201 through 450"
Anyhow...
public class Program
{
//https://leetcode.com/problems/summary-ranges/
static void Main()
{
while (true)
{
Console.WriteLine("Enter Array");
string qwe = Console.ReadLine();
qwe = qwe.Replace("[", "");
qwe = qwe.Replace("]", "");
string[] allStrings = qwe.Split(',');
int[] allInts = new int[allStrings.Length];
if (allStrings.Length > 0)
{
for (int i = 0; i < allStrings.Length; i++)
{
allInts[i] = int.Parse(allStrings[i]);
}
}
IList<string> myRange = new List<string>();
myRange = SummaryRanges(allInts);
foreach (string str in myRange)
{
Console.WriteLine(str);
}
}
}
public static IList<string> SummaryRanges(int[] nums)
{
IList<string> result = new List<string>();
if (nums == null || nums.Length == 0)
{
return result;
}
int rangeStart = nums[0];
for (int i = 0; i < nums.Length - 1; i++)
{
if (nums[i] == nums[i + 1] - 1)
{
}
else
{
if (rangeStart != nums[i])
{
result.Add(rangeStart + "->" + nums[i]);
}
else
{
result.Add(rangeStart.ToString());
}
rangeStart = nums[i + 1];
}
}
if (rangeStart != nums[nums.Length - 1])
{
result.Add(rangeStart + "->" + nums[nums.Length - 1]);
}
else
{
result.Add(rangeStart.ToString());
}
return result;
}
}
Reader's Comments
Name
Comment
Add a RELEVANT link (not required)
Upload an image (not required)
Uploading...
Home