tags:

views:

645

answers:

2

I have a list of int values:

List<int> histogram;

How do I normalize all values so that the max value in the list is always 100?

+2  A: 

Iterate though, find the maximum value (call it MAXVAL), then iterate through once more and multiply every value in the list by (100/MAXVAL).

var ratio = 100.0 / list.Max();
var normalizedList = list.Select(i => i * ratio).ToList();
Amber
what about negative numbers?
Kobi
oh, and the max value can be 0, so you have 100/0.
Kobi
Yes, that boundary case should probably be checked for - though there's no real good way to 'normalize' a list which is all zero.
Amber
@Dav: Just because the max is zero does not mean that every entry in the list is zero.
Jason
Correct, Jason, but the solution I had given would only work for non-negative lists anyways. For lists that can include negative values, there's still a boundary case, it simply becomes when min == max instead of when max == 0.
Amber
+4  A: 

If you have a list of strictly positive numbers, then Dav's answer will suit you fine.

If the list can be any numbers at all, then you need to also normalise to a lowerbound.

Assuming an upper bound of 100 and a lower bound of 0, you'll want something like this ...

var max = list.Max();
var min = list.Min();
var range = (double)(max - min);
var normalised 
    = list.Select( i => 100 * (i - min)/range)
        .ToList();

Handling the case where min == max is left as an exercise for the reader ...

Bevan
Hm... That will give you a list of vales between 0 and 1...
Guffa
You're right - I will fix.
Bevan