From 11f539ddd62c5707635c53a2fd14f176923a5f06 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Mon, 16 Sep 2024 19:53:03 +0200 Subject: [PATCH] =?UTF-8?q?cs:=20add=20=C2=AB539.=20Minimum=20Time=20Diffe?= =?UTF-8?q?rence=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- cs/minimum-time-difference.cs | 42 +++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 cs/minimum-time-difference.cs diff --git a/cs/minimum-time-difference.cs b/cs/minimum-time-difference.cs new file mode 100644 index 0000000..ab24580 --- /dev/null +++ b/cs/minimum-time-difference.cs @@ -0,0 +1,42 @@ +using System.Collections.Immutable; + +public class Solution { + private record Time(int hours, int minutes) { + public int Normalized { get => hours * 60 + minutes; } + + public static int Distance(Time a, Time b) => + Math.Abs(b.Normalized - a.Normalized); + + public static bool TryParse(string? s, out Time time) { + if (s == null) { + goto TimeFailedTryParse; + } + + var parts = s.Split(":"); + if (parts.Length != 2) { + goto TimeFailedTryParse; + } + + if (int.TryParse(parts[0], out var hours) && int.TryParse(parts[1], out var minutes)) { + time = new Time(hours, minutes); + return true; + } + +TimeFailedTryParse: + time = new Time(0, 0); + return false; + } + } + + public int FindMinDifference(IList timePoints) { + var times = timePoints.Select(t => { + Time.TryParse(t, out var time); + return time; + }).OrderBy(time => time.Normalized).ToImmutableList(); + + return Math.Min( + 24 * 60 - Time.Distance(times.Last(), times.First()), + times.Zip(times.Skip(1)).Select(pair => Time.Distance(pair.First, pair.Second)).Min() + ); + } +}