3

I have a double[]and I have another IEnumerable<double> and another List<double> and also a ObservableCollection<double>.

All of these contain some double values.

I want to create a function which can take any of these as these collection as arguements, and that it will proportionate the values of each element in the collection so that they add to 1.

For e.g. - if array has 0.5, 1.0 and 0.5, then I can call ProportionateIt(mycollection), it should modify the values to 0.25, 0.5 and 0.25 because now they sum up to 1.

So far I have tried this:

    private IEnumerable<double> ProportionateIt(IEnumerable<double> input)
    {
        double sum = 0;
        var newCollection = input.ToList();
        foreach (double d in newCollection)
        {
            sum+= d;
        }

        for (int i=0; i < input.Count(); i++)
        {
            newCollection[i] = newCollection[i]*(1/sum);
        }

        input = newCollection as IEnumerable<double>;
        return input;
    }

It has some problems

  • It does not take all the types that I stated above as arguments.
  • it returns a new collection, instead of modifying the original one.

Can somebody create a ProportionateIt(....) function for me?

4

1 回答 1

4

你可以这样做

    private static void ProportionateIt(IList<double> input)
    {
        double sum = input.Sum(d => d);

        for (int i = 0; i < input.Count; i++)
        {
            input[i] = input[i] / sum;
        }
    }

编辑:进行了一些小改动 -List按照IList@Rawling 的建议更改

于 2013-05-28T10:55:38.827 回答