Is that possible to divide all elements in C# double list to that double list elements sum (which makes total = 1)

Go To StackoverFlow.com

5

Imagine a doube list like the follow

List<double> lstDouble=new List<double>{4,6,2,7,1,1};

So what i want is dividing all elements in this list to sum of the elements(21).

So the list becomes after dividing :

lstDouble = {4/21,6/21,2/21,7/21,1/21,1/21}

Which would mean that the new sum of the elements = 1

I can do that via iteration etc but i wonder are there any short way since Matlab has. And my assistant professor keep telling me that learn Matlab and use it but i don't want :D I love C#

Thank you.

C# 4.0 WPF application

2012-04-04 23:55
by MonsterMMORPG
Note that the sum will be approximately 1 afterwards, and not exactly 1. Depending on the values the approximation might be pretty bad - CodesInChaos 2012-04-05 00:01
That is not very important it will be close 1 though - MonsterMMORPG 2012-04-05 00:06
Do you want to modify the input array, or do you want to return a new, modified array - CodesInChaos 2012-04-05 00:06
I handled that lstTempDouble = lstTempDouble.Select(x => x / sum).ToList() - MonsterMMORPG 2012-04-05 00:07


9

var sum = lstDouble.Sum();
var result = lstDouble.Select(d => d / sum);
2012-04-04 23:59
by Rango


4

You can do this with LINQ:

var sum = lstDouble.Sum();
var newLst = lstDouble.Select( x => x/sum );
2012-04-04 23:59
by Ethan Brown


2

Use a lambda expression:

 lstDouble.ForEach(x => x = x/21);
2012-04-04 23:58
by Eugene Feingold
21 is a variable number that depends on the size and values of the array - kasavbere 2012-04-05 00:00


2

var sum = lstDouble.Sum();
var result = lstDouble.Select(v => v / sum);
2012-04-05 00:00
by RobIII
Your code has quadratic runtime.. - CodesInChaos 2012-04-05 00:02
@CodeInChaos Yeah, thought of that just after I posted. Corrected. Now I have the same answer as everybody else here :- - RobIII 2012-04-05 00:04


0

This is a pseudo code:

double sum = 0;
for(int i=0; i<array.length; i++)
   sum+=array[i];
for(int i=0; i<array.length; i++)
   array[i]=array[i]/sum;
2012-04-04 23:59
by kasavbere
down vote is supposed to mean the code would not work. So why the negative vote - kasavbere 2012-04-05 00:02
even that does not warrant a down vote. The poster could figure it out from there - kasavbere 2012-04-05 00:06
downvote means the answer is "not useful". the question states "I can do that via iteration", which is what this answer is doing, which makes this answer not useful in the context of the question - Ethan Brown 2012-04-05 00:15
Ads