Last active
May 28, 2021 17:03
-
-
Save chygoz2/aadd848512e20879538d480631b26200 to your computer and use it in GitHub Desktop.
Algorithm week 7 challenge
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.Linq; | |
namespace minimumDifference | |
{ | |
class Program | |
{ | |
public static void Main(string[] args) | |
{ | |
Console.WriteLine(Program.getMinimumDifference(new string[] { "16:15", "16:00", "12:20" })); | |
} | |
public static int getMinimumDifference(string[] times) | |
{ | |
if (times.Length == 0) | |
{ | |
return 0; | |
} | |
var validTimes = times | |
.Where(time => Program.getTimeInMinutes(time).HasValue) | |
.Select(time => Program.getTimeInMinutes(time).Value) | |
.ToArray(); | |
if (validTimes.Length == 0) | |
{ | |
throw new InvalidOperationException("No valid input exists"); | |
} | |
if (validTimes.Length == 1) | |
{ | |
return validTimes[0]; | |
} | |
Array.Sort(validTimes); | |
int? minimumDifference = null; | |
for (var i = 0; i < validTimes.Length - 1; i++) | |
{ | |
var diff = validTimes[i+1] - validTimes[i]; | |
if (!minimumDifference.HasValue) { | |
minimumDifference = diff; | |
continue; | |
} | |
if (diff < minimumDifference) | |
{ | |
minimumDifference = diff; | |
} | |
} | |
return minimumDifference.GetValueOrDefault(); | |
} | |
private static int? getTimeInMinutes(string time) | |
{ | |
var parts = time.Split(":"); | |
if (parts.Length != 2) | |
{ | |
return null; | |
} | |
try | |
{ | |
var hour = Convert.ToInt32(parts[0]); | |
var mins = Convert.ToInt32(parts[1]); | |
if (hour < 0 || hour > 23 || mins < 0 || mins > 59) | |
{ | |
return null; | |
} | |
return hour * 60 + mins; | |
} | |
catch (FormatException) | |
{ | |
return null; | |
} | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you @meekg33k