Exercism - Resistor Color Trio
This post shows you how to get Resistor Color Trio exercise of Exercism.
Preparation
Before we click on our next exercise, let’s see what concepts of DART we need to consider

So we need to use the following concepts.
Lists and List.indexOf
Lists are ordered collections of items. The indexOf() method returns the index of an element, which represents its value.
void main() {
List<String> colors = [
'black', 'brown', 'red', 'orange', 'yellow',
'green', 'blue', 'violet', 'grey', 'white'
];
// Get value of a color
int brownValue = colors.indexOf('brown'); // 1
int orangeValue = colors.indexOf('orange'); // 3
// Use values to build base number
int baseValue = brownValue * 10 + orangeValue;
print(baseValue); // 13
}
Integer Arithmetic
You can perform arithmetic operations on integers to build multi-digit numbers from individual digits.
void main() {
int digit1 = 3;
int digit2 = 3;
// Build two-digit number
int baseValue = digit1 * 10 + digit2;
print(baseValue); // 33
// Example: orange (3) and orange (3) = 33
int orange = 3;
int result = orange * 10 + orange;
print(result); // 33
}
Power Function (dart:math)
The pow() function from dart:math calculates a number raised to a power. It’s useful for calculating multipliers (10^zeros).
import 'dart:math';
void main() {
// Calculate 10 raised to a power
num result1 = pow(10, 0); // 1
num result2 = pow(10, 2); // 100
num result3 = pow(10, 3); // 1000
print(result1); // 1
print(result2); // 100
print(result3); // 1000
// Convert to int
int multiplier = pow(10, 2).toInt();
print(multiplier); // 100
// Use for resistor values
int baseValue = 33;
int zeros = 2;
int totalValue = baseValue * pow(10, zeros).toInt();
print(totalValue); // 3300
}
Integer Division
The integer division operator (~/) divides two numbers and returns an integer result, truncating any decimal part. It’s useful for converting to larger units.
void main() {
int value = 33000;
// Convert to kiloohms (divide by 1000)
int kiloohms = value ~/ 1000;
print(kiloohms); // 33
// Convert to megaohms (divide by 1000000)
int megaohms = value ~/ 1000000;
print(megaohms); // 0 (33000 < 1000000)
int largeValue = 3300000;
int mega = largeValue ~/ 1000000;
print(mega); // 3
}
Conditional Logic
Conditional statements allow you to execute different code based on conditions. This is essential for choosing the appropriate metric prefix.
void main() {
int value = 33000;
// Choose appropriate unit
if (value >= 1000000000) {
print('${value ~/ 1000000000} gigaohms');
} else if (value >= 1000000) {
print('${value ~/ 1000000} megaohms');
} else if (value >= 1000) {
print('${value ~/ 1000} kiloohms');
} else {
print('$value ohms');
}
// Output: 33 kiloohms
}
String Interpolation
String interpolation allows you to embed expressions and variables directly within strings using ${expression} or $variable.
void main() {
int value = 33;
String unit = 'kiloohms';
// Basic interpolation
String result = '$value $unit';
print(result); // '33 kiloohms'
// Expression interpolation
int total = 33000;
String formatted = '${total ~/ 1000} kiloohms';
print(formatted); // '33 kiloohms'
// Multiple interpolations
String label = '${value} $unit';
print(label); // '33 kiloohms'
}
Final Variables
The final keyword creates a variable that can only be assigned once. It’s useful for constants that won’t change.
void main() {
// Final variable (can't be reassigned)
final colors = [
'black', 'brown', 'red', 'orange', 'yellow',
'green', 'blue', 'violet', 'grey', 'white'
];
// This would cause an error:
// colors = ['red', 'blue']; // Error!
// But you can still modify the list contents
// (though in this case, we don't want to)
}
Introduction
If you want to build something using a Raspberry Pi, you’ll probably use resistors. For this exercise, you need to know only three things about them:
- Each resistor has a resistance value.
- Resistors are small - so small in fact that if you printed the resistance value on them, it would be hard to read. To get around this problem, manufacturers print color-coded bands onto the resistors to denote their resistance values.
- Each band acts as a digit of a number. For example, if they printed a brown band (value 1) followed by a green band (value 5), it would translate to the number 15.
In this exercise, you are going to create a helpful program so that you don’t have to remember the values of the bands. The program will take 3 colors as input, and outputs the correct value, in ohms.
Color Encoding
The color bands are encoded as follows:
- black: 0
- brown: 1
- red: 2
- orange: 3
- yellow: 4
- green: 5
- blue: 6
- violet: 7
- grey: 8
- white: 9
How It Works
In Resistor Color Duo you decoded the first two colors. For instance: orange-orange got the main value 33. The third color stands for how many zeros need to be added to the main value. The main value plus the zeros gives us a value in ohms. For the exercise it doesn’t matter what ohms really are.
For example:
- orange-orange-black would be 33 and no zeros, which becomes 33 ohms.
- orange-orange-red would be 33 and 2 zeros, which becomes 3300 ohms.
- orange-orange-orange would be 33 and 3 zeros, which becomes 33000 ohms.
(If Math is your thing, you may want to think of the zeros as exponents of 10. If Math is not your thing, go with the zeros. It really is the same thing, just in plain English instead of Math lingo.)
Metric Prefixes
This exercise is about translating the colors into a label: ”… ohms”
So an input of “orange”, “orange”, “black” should return: “33 ohms”
When we get to larger resistors, a metric prefix is used to indicate a larger magnitude of ohms, such as “kiloohms”. That is similar to saying “2 kilometers” instead of “2000 meters”, or “2 kilograms” for “2000 grams”.
For example, an input of “orange”, “orange”, “orange” should return: “33 kiloohms”
What are metric prefixes?
Metric prefixes are used to indicate multiples or fractions of a base unit. Common prefixes include:
- kilo- (k): 1,000 (10³)
- mega- (M): 1,000,000 (10⁶)
- giga- (G): 1,000,000,000 (10⁹)
These prefixes make large numbers more readable. For example, 33,000 ohms is better expressed as 33 kiloohms.
— Metric System
How can we calculate resistor values with three colors?
To calculate resistor values with three colors:
- Get base value: Use the first two colors to form a two-digit number (tens and ones)
- Calculate multiplier: Use the third color to determine how many zeros to add (10^third_color_value)
- Calculate total value: Multiply the base value by the multiplier
- Format with metric prefix:
- If value >= 1,000,000,000 → use gigaohms
- Else if value >= 1,000,000 → use megaohms
- Else if value >= 1,000 → use kiloohms
- Else → use ohms
For example, with colors [‘orange’, ‘orange’, ‘orange’]:
- First color ‘orange’ → 3 (tens digit)
- Second color ‘orange’ → 3 (ones digit)
- Base value: 3 × 10 + 3 = 33
- Third color ‘orange’ → 3 (number of zeros)
- Multiplier: 10³ = 1000
- Total value: 33 × 1000 = 33000
- Format: 33000 >= 1000 → 33000 ÷ 1000 = 33 kiloohms
Solution
import 'dart:math';
class ResistorColorTrio {
final colors = [
'black', 'brown', 'red', 'orange', 'yellow',
'green', 'blue', 'violet', 'grey', 'white'
];
String label(List<String> selectedColors) {
// Get base value from first two colors
final digit1 = colors.indexOf(selectedColors[0]);
final digit2 = colors.indexOf(selectedColors[1]);
final baseValue = digit1 * 10 + digit2;
// Add zeros based on third color
final zeros = colors.indexOf(selectedColors[2]);
final value = baseValue * pow(10, zeros).toInt();
// Format with appropriate unit
if (value >= 1000000000) {
return '${value ~/ 1000000000} gigaohms';
} else if (value >= 1000000) {
return '${value ~/ 1000000} megaohms';
} else if (value >= 1000) {
return '${value ~/ 1000} kiloohms';
}
return '$value ohms';
}
}
Let’s break down the solution:
-
import 'dart:math';- Imports the math library:- Provides the
pow()function for calculating powers - Needed to calculate 10^zeros
- Provides the
-
class ResistorColorTrio- Defines a class for resistor color trio operations:- Encapsulates the color data and value calculation functionality
-
final colors = [...]- Stores all resistor colors in order:- Uses
finalto prevent reassignment - Colors are ordered from 0 to 9 (same as previous exercises)
- The list itself can be accessed to get all colors
- Uses
-
String label(List<String> selectedColors)- Calculates and formats the resistor value:- Takes a list of three color names as input
Step 1: Get base value from first two colors
digit1 = colors.indexOf(selectedColors[0])- Gets the value of the first colordigit2 = colors.indexOf(selectedColors[1])- Gets the value of the second colorbaseValue = digit1 * 10 + digit2- Combines them into a two-digit number- Example: orange (3) and orange (3) → 3 × 10 + 3 = 33
Step 2: Calculate total value with multiplier
zeros = colors.indexOf(selectedColors[2])- Gets the number of zeros from the third colorpow(10, zeros)- Calculates 10 raised to the power of zeros (e.g., 10³ = 1000).toInt()- Converts the result to an integervalue = baseValue * pow(10, zeros).toInt()- Multiplies base value by the multiplier- Example: 33 × 10³ = 33 × 1000 = 33000
Step 3: Format with appropriate metric prefix
- Checks the value against thresholds to determine the appropriate unit:
- If
value >= 1000000000→ divide by 1,000,000,000 and use “gigaohms” - Else if
value >= 1000000→ divide by 1,000,000 and use “megaohms” - Else if
value >= 1000→ divide by 1,000 and use “kiloohms” - Else → use “ohms” as-is
- If
- Uses integer division (
~/) to get the value in the larger unit - Returns a formatted string with the value and unit
The solution efficiently calculates resistor values by combining the first two colors into a base value, then multiplying by 10 raised to the power of the third color’s value. It then formats the result with the appropriate metric prefix for readability.
A video tutorial for this exercise is coming soon! In the meantime, check out my YouTube channel for more Dart and Flutter tutorials. 😉
Visit My YouTube Channel