1
0
Fork 0
mirror of https://gitlab.com/mfocko/CodeWars.git synced 2024-11-09 02:59:06 +01:00
CodeWars/4kyu/human_readable_duration_format/solution.cs

40 lines
999 B
C#
Raw Normal View History

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;
}
}
}