-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMissingElements.cs
More file actions
32 lines (27 loc) · 793 Bytes
/
MissingElements.cs
File metadata and controls
32 lines (27 loc) · 793 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
using System;
using System.Linq;
using System.Collections.Generic;
class Program
{
static void Main()
{
int[] missing = {0,1,3,5,7,18,34,57,77,59,79,98,99};
Console.WriteLine(ToRangeString(missing));
}
public static string ToRangeString(int[] missing)
{
var sorted = missing.OrderBy(x => x).ToList();
var substrings = new List<string>();
substrings.Add(getRange(-1,sorted[0]));
for (int ii = 1; ii < sorted.Count - 1; ii++)
substrings.Add(getRange(sorted[ii], sorted[ii+1]));
substrings.Add(getRange(sorted[sorted.Count - 1], 100));
return String.Join(",", substrings.Where(x => x != null));
}
private static string getRange(int a, int b)
{
if(b-a<2) return null;
if(b-a==2) return (b-1).ToString();
return (a+1) + ((b-a==3) ? "," : "-") + (b-1);
}
}