1
0
Fork 0
mirror of https://gitlab.com/mfocko/CodeWars.git synced 2024-11-09 11:09:07 +01:00
CodeWars/4kyu/human_readable_duration_format/solution.cs
Matej Focko fc899b0b02
chore: initial commit
Signed-off-by: Matej Focko <mfocko@redhat.com>
2021-12-28 16:19:58 +01:00

39 lines
999 B
C#

using System;
using System.Collections.Generic;
using System.Linq;
public class HumanTimeFormat{
private static Dictionary<string, int> conversions = new Dictionary<string, int>() {
{"year", 31536000},
{"day", 86400},
{"hour", 3600},
{"minute", 60},
{"second", 1}
};
public static string formatDuration(int seconds){
if (seconds == 0) return "now";
var results = new List<string>();
foreach (var pair in conversions) {
var units = seconds / pair.Value;
seconds %= pair.Value;
if (units > 0) {
var part = $"{units} {pair.Key}";
if (units > 1) {
part += "s";
}
results.Add(part);
}
}
if (results.Count == 1) return results[0];
else {
var last = results.Last();
results.Remove(last);
var result = String.Join(", ", results);
return result + " and " + last;
}
}
}