Created
November 7, 2018 21:38
-
-
Save JL-Cox/82c0327d3bde319b3bd56c76b15b4bf3 to your computer and use it in GitHub Desktop.
CodeKata - RangeExtraction
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
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
/// <summary> | |
/// https://www.codewars.com/kata/51ba717bb08c1cd60f00002f | |
/// </summary> | |
namespace RangeExtraction | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
Extract(new[] { 1, 2 }); | |
} | |
public static string Extract(int[] args) | |
{ | |
string answer = ""; | |
int start; | |
int end; | |
for (int i = 0; i < args.Count(); i++) | |
{ | |
if (i == args.Count() - 1) | |
{ | |
answer += $"{args[i]}"; | |
Console.WriteLine($"Answer: {answer}"); | |
Console.ReadKey(); | |
return answer; | |
} | |
if (args[i] == (args[i + 1] - 1)) | |
{ | |
start = args[i]; | |
try | |
{ | |
while (args[i] == (args[i + 1] - 1)) | |
{ | |
i++; | |
} | |
end = args[i]; | |
if (end - start > 1) | |
{ | |
answer += $"{start}-{end},"; | |
} | |
else | |
{ | |
for (int n = start; n <= end; n++) | |
{ | |
answer += $"{n},"; | |
} | |
} | |
} | |
catch (IndexOutOfRangeException) | |
{ | |
end = args[i]; | |
if (end - start > 1) | |
{ | |
answer += $"{start}-{end}"; | |
} | |
else | |
{ | |
for (int n = start; n <= end; n++) | |
{ | |
if (n == end) | |
{ | |
answer += $"{n}"; | |
} | |
else | |
{ | |
answer += $"{n},"; | |
} | |
} | |
} | |
return answer; | |
} | |
} | |
else | |
{ | |
answer += $"{args[i]},"; | |
} | |
} | |
return answer; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment