interpolating vector indices algorithm

Hello,

What I try to accomplish seems difficult to explain in abstract terms, so I'll jump right into the practical application:
Imagine a vector of colors and a percent value. As percent moves from 0 to 1 I need to pick two colors and mix them accordingly.

So I want to map the percent value to two indices and a ratio between these two.
Example:

colors [ red , blue , green , yellow ]
percent: 0.0 -> red 100%
percent: 0.25 -> red to blue 75%
percent: 0.5 -> blue to green 50%
percent: 0.75 -> green to yellow 25%

Please ignore the actual mixing of colors, I'm after a generic solution that yields indexA, indexB and a ratio value.
It should be fairly efficient.

Here's what I came up with. It works as intended, but I was wondering if there's a better/more efficient way of doing this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
inline void interpolateIndices( const int & indexMax , const float &percent , int *indexA , int *indexB , float *ratio ){

	if( percent == 0.0f ){
		
		*indexA = 0;
		*indexB = 1;
		*ratio  = 0.0f;
		
	}
	else if( percent >= 1.0f ){
		
		*indexA = indexMax;
		*indexB = indexMax;
		*ratio  = 1.0f;
		
	}
	else{

		*indexA = percent * indexMax;
		*indexB = *indexA + 1;
		
		const float step = 1.0f / indexMax;
		*ratio = mapValue( percent , (float)*indexA * step , (float)*indexB * step , 0.0f , 1.0f );
		
	}

}
inline float mapValue( const float &value , const float &inputMin , const float &inputMax , const float &outputMin , const float &outputMax ) {
	
	return ((value - inputMin) / (inputMax - inputMin) * (outputMax - outputMin) + outputMin);

}


// Usage example:
int indexA, indexB;
float ratio;

int indexMax = colors.size() - 1;
int numIterations = 100;

for( int i = 0; i < numIterations; i++ ){
	
	float percent = (float)i / (float)numIterations;
	
	interpolateIndices( indexMax , percent , &indexA , &indexB , &ratio );

	cout << "percent: " << percent << " indexA: " << indexA << " indexB: " << indexB << " ratio: " << ratio << endl;
	
}




I hope that makes sense. Any suggestions welcome!


Best regards,

Ci

Ps: Not a school assignment, but a real-world task for a personal project






Topic archived. No new replies allowed.