Skip to content

Commit 6b56dd7

Browse files
resistor-color-trio: fix
1 parent aee74b5 commit 6b56dd7

File tree

1 file changed

+18
-6
lines changed
  • exercises/practice/resistor-color-trio/.meta

1 file changed

+18
-6
lines changed

exercises/practice/resistor-color-trio/.meta/Example.cs

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,22 @@
22

33
public static class ResistorColorTrio
44
{
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);
1123
}

0 commit comments

Comments
 (0)