|
2 | 2 |
|
3 | 3 | public static class ResistorColorTrio |
4 | 4 | { |
5 | | - private const int KiloOhms = 1_000; |
6 | | - private static readonly string[] AllColors = new[] { "black", "brown", "red", "orange", "yellow", "green", "blue", "violet", "grey", "white" }; |
7 | | - public static string Label(string[] colors) => $"{(GetValue(colors) is int _value && _value >= KiloOhms ? _value / KiloOhms : _value)} " + GetUnit(_value); |
8 | | - private static int GetValue(string[] colors) => ((ResistorValue(colors[0]) * 10) + ResistorValue(colors[1])) * (int)Math.Pow(10, ResistorValue(colors[2])); |
9 | | - private static string GetUnit(int value) => (value >= KiloOhms ? "kilo" : "") + "ohms"; |
10 | | - private static int ResistorValue(string color) => Array.IndexOf(AllColors, color); |
| 5 | + private static readonly string[] Colors = ["black", "brown", "red", "orange", "yellow", "green", "blue", "violet", "grey", "white"]; |
| 6 | + private static readonly string[] Units = ["", "kilo", "mega", "giga"]; |
| 7 | + |
| 8 | + public static string Label(string[] colors) |
| 9 | + { |
| 10 | + var ohms = Ohms(colors); |
| 11 | + |
| 12 | + for (var i = 0; i < Units.Length; ++i) |
| 13 | + if (ohms <= Math.Pow(1000, i + 1)) |
| 14 | + return $"{ohms / Math.Pow(1000, i)} {Units[i]}ohms"; |
| 15 | + |
| 16 | + throw new InvalidOperationException(); |
| 17 | + } |
| 18 | + |
| 19 | + private static ulong Ohms(string[] colors) => |
| 20 | + (Value(colors[0]) * 10 + Value(colors[1])) * (ulong)Math.Pow(10, Value(colors[2])); |
| 21 | + |
| 22 | + private static ulong Value(string color) => (ulong)Array.IndexOf(Colors, color); |
11 | 23 | } |
0 commit comments