Require c# Normalising Math Formula based on attached array which generates bar chart % value output?

StackOverflow https://stackoverflow.com/questions/21102307

  •  27-09-2022
  •  | 
  •  

Frage

Problem:

So I am looking to create bar chart values based on a comparison to an array of values.

Data: array = [25 , 35 , 55 , 5 , 60 , 200 , 18 , 18 , 30 , 10]

Requirements:

I have a working Bar graph creation using CSS which loads the bar width value 'xx' as a percentage.

I want to allocate the lowest array item value to a percentage value of 100% (full width of CSS bar) The above example would be the fourth array item '5' Likewise the sixth item in the array is the highest number and I want to allocate 0% to the highest. (Think of the numbers in the array as time - shortest being the best)

So lowest (fourth) array item '5' = bar width value 100% and the

Highest array item '200' = bar width value 0%

The spread between the highest and lowest values in the array is 195

There are 10x items in the array.

The average value across the array is 45.6 which would for example generate a bar chart value of 50% if represented in the bar chart.

I am struggling to create a formula which dynamically generates the reverse percentage values from the varied array values above into a representational percentage bar chart value of any of the items in the array.

Specific Help Needed:

Can you see the solution in C# so that I can generate percentage bar values based on the requirements outlined above ?

[EDIT] (Including my code which partly works)

int[] array = { 25 , 35 , 55 , 5 , 60 , 200 , 18 , 18 , 30 , 10 };
int selectdVal = 5;  //example selection from array

int ratioSpread = 100; //used as 100% CSS width
int responseSlow = array.Max();  //The slowest val within array

decimal ratioAdjust = (ratioSpread / responseSlow);
decimal maxBar = 100 - (selectdVal * ratioAdjust );
int renderBar = Convert.ToInt16(maxBar <= 0 ? 1 : maxBar ); //show min 1% bar width

The above is relatively ok, but I'd prefer to have the shortest time (Min.value) of 5 above actually return 100 for the renderBar, whereas in this example it returns 97.5

War es hilfreich?

Lösung

int[] array = { 25, 35, 55, 5, 60, 200, 18, 18, 30, 10 };
int selectdVal = 5;

int barMin = 1;
int barMax = 100;

decimal rangeMin = array.Min();
decimal rangeMax = array.Max();

decimal ratio = (barMax - barMin) / (rangeMax - rangeMin);

int bar = barMax - (int)(ratio * (selectdVal - rangeMin));
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top