6 kyu

Linear Color Gradient

37 of 80aland97

Description:

You need to write a function that takes array of n colors and converts them to a linear gradient

for example gradient

from [r1, g1, b1] with position p1 to [r2, g2, b2] with position p2

in order to get the color of the gradient from p1 to p2, you need to find three functions Fr, Fg and Fb of the form f(x) = a + bx for red, green and blue with

[Fr(p1), Fg(p1), Fb(p1)] = gradient(p1) and [Fr(p2), Fg(p2), Fb(p2)] = gradient(p2)

gradient can contain more than two colors, in which case gradient (p) returns a color that is interpolated between two colors with positions p1 and p2 such that p1 < p < p2 (see usage)

Input

Array of colors in RGB format and its positions [[r, g, b], position]

r, g, b - float numbers from 0 to 255

position - float number from 0 to 1

Output

Function that map float number in range [0, 1] to color [r, g, b].

r, g and b is a float numbers
if there is no color with the position p < number return the color with the lowest position
if there is no color with the position p > number return the color with the highest position
if two or more colors has a same position take last
if array is empty gradient must return [0, 0, 0]

Usage

// red, yellow, green, etc. - [r,g,b] arrays
// for example red = [255, 0, 0]
let rainbowGradient = createGradient([
  [red, 0], 
  [yellow, 0.2],
  [green, 0.4],
  [blue, 0.8],
  [violet, 1]
])
// from 0 to 0.2 gradient between red and yellow
rainbowGradient(0.1) // orange = [255, 127, 0]

// from 0.4 to 0.8 gradient between green and blue
rainbowGradient(0.6) // [0, 127, 127]
Algorithms

Similar Kata:

More By Author:

Check out these other kata created by aland97

Stats:

CreatedApr 10, 2021
PublishedApr 10, 2021
Warriors Trained575
Total Skips6
Total Code Submissions1373
Total Times Completed80
JavaScript Completions37
C++ Completions17
Python Completions34
Total Stars17
% of votes with a positive feedback rating91% of 38
Total "Very Satisfied" Votes32
Total "Somewhat Satisfied" Votes5
Total "Not Satisfied" Votes1
Total Rank Assessments6
Average Assessed Rank
6 kyu
Highest Assessed Rank
6 kyu
Lowest Assessed Rank
7 kyu
Ad
Contributors
  • aland97 Avatar
  • JohanWiltink Avatar
  • MikChan Avatar
Ad