All problems‎ > ‎

Color gradient

In painting programs, a popular notion is that of the "color gradient". By having two or more colors in a list, one can paint an object with the gradient and thus achieve a nice "rainbow" effect.

This is done by linear interpolation of all color component values. For example, the blended red component will be

blendedR = Blend(fromColor.Red, toColor.Red, fraction)

.. where fraction is a value between 0 and 1.

Problem A
Build a class ColorBlender that blends two colors A and B. An example test would be

colorBlender = ColorBlender(Colors.GREEN, Colors.MAGENTA)
blendedColor = colorBlender.ColorAt(0)
Assert.AreEqual(Colors.GREEN, blendedColor);

Some more tests would check the color at 1 and 0.5. And maybe outside of 0 and 1 too -- painting programs usually smear the "end color" to indefinitely beyond the edges.

Problem B
Generalize the color blender to a Gradient class, that accepts 1 or more colors. Example test:

gradient = Gradient(Colors.GREEN, Colors.MAGENTA, COLORS.RED)
blendedColor = gradient.ColorAt(0.5)
Assert.AreEqual(Colors.MAGENTA, blendedColor);

Difficulties in these problems
Doing ordinary equality comparison might prove difficult due to rounding-off errors. You might want to build a test helper function "SimilarColors" that uses color distance to compare the equality of two colors. The color distance is simply the distance between the colors seen as two points in 3D space:

dist = sqrt( dr^2 + dg^2 + db^2)

.. where dr, dg and db are the differences between the red, green and blue components of the colors (dr = color2.Red - color1.Red).

Another difficulty is also due to round-off errors, which will probably give you index errors in the gradient class (problem B). I'll leave the details of that to you!