To ensure that the code outputs each value only once, we can use a HashSet to eliminate duplicates before sorting and formatting the ranges. Here is the revised version of the FormatIntegerRanges function that accounts for duplicates:
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
public class RangeFormatter
{
public static string FormatIntegerRanges(List<int> numbers)
{
if (numbers == null || numbers.Count == 0)
{
return string.Empty;
}
// Use HashSet to remove duplicates and then convert it back to a sorted list
var uniqueNumbers = new HashSet<int>(numbers).ToList();
uniqueNumbers.Sort();
var stringBuilder = new StringBuilder();
int start = uniqueNumbers[0];
int end = start;
for (int i = 1; i < uniqueNumbers.Count; i++)
{
if (uniqueNumbers[i] == end + 1)
{
// Extend the range to include the current number
end = uniqueNumbers[i];
}
else
{
// Append the current range and start a new range
AppendRangeToStringBuilder(stringBuilder, start, end);
start = uniqueNumbers[i];
end = start;
}
}
// Append the last range
AppendRangeToStringBuilder(stringBuilder, start, end);
// Remove the trailing comma and space
if (stringBuilder.Length > 0)
{
stringBuilder.Length -= 2;
}
return stringBuilder.ToString();
}
private static void AppendRangeToStringBuilder(StringBuilder stringBuilder, int start, int end)
{
if (start == end)
{
// Append the single number
stringBuilder.Append(start);
}
else
{
// Append the range
stringBuilder.AppendFormat("{0}-{1}", start, end);
}
// Add a comma and space to separate the ranges
stringBuilder.Append(", ");
}
}
class Program
{
static void Main()
{
List<int> numbers = new List<int> { 1, 2, 2, 3, 5, 7, 7, 8, 10, 11, 12, 12 };
string formattedRanges = RangeFormatter.FormatIntegerRanges(numbers);
Console.WriteLine(formattedRanges);
}
}
When you run the updated program with the input list that includes duplicates, such as [1, 2, 2, 3, 5, 7, 7, 8, 10, 11, 12, 12], it will output:
1-3, 5, 7-8, 10-12
This output correctly shows each number only once and represents the sorted and formatted ranges of the input list without duplicates.