public int Roll(int NumberOfDice, int Faces)
{
int Sum = 0;
List<int> Rolls = new List<int>();
for (int i = 0; i < NumberOfDice; i++)
{
Rolls.Add(Die.Next(0, Faces));
}
IEnumerator<int> Enumerator = Rolls.GetEnumerator();
while (Enumerator.MoveNext())
{
Sum += Enumerator.Current;
}
return Sum;
}
it would have been nice to simply say Rolls.Sum();
i guess i could have used a for loop as well.
whats really the best way to accomplish this, in your opinions?
[C#] Summing a list
hey whats good?
im implementing a d20 dice system where i have a method that rolls the dice and adds the results to a list<int> type
im trying to decide what the best way to sum the results would be. i have read about a sum method that is an extension of ienumerable types added to lists and arrays by LINQ but in the example i saw he references system.linq; while the closest match i have is system.data.linq;
so i implemented it like this:
If you're using .NET 3.5, you can use the extension method like you mentioned. It's included in the System.Core DLL, and is located under the System.Linq namespace as a member of the static Enumerable class as an extension method to IEnumerable<T>.
The main Linq assembly is System.Core, I believe. Try adding a reference to that and you should be able to use the Sum method.
edit: damnit, long dogged by 14 secs! damn you, hard cat! [razz]
edit: damnit, long dogged by 14 secs! damn you, hard cat! [razz]
Am I missing something? Why not this:
public int Roll(int numDice, int numFaces){ int Sum = 0; for(int i=0; i<numDice; ++i){ Sum += Die.Next(0, numFaces); } return Sum;}
Or at least:public int Roll(int numDice, int numFaces){ int Sum = 0; List<int> Rolls; for(int i=0; i<numDice; ++i){ int roll = Die.Next(0, numFaces); Sum += roll; Rolls.Add(roll); } return Sum;}
if you intend to actually use all the values later.
i wasn't thinking about it that way, in addition to being rusty :) thanks ocelot. thanks mike and chaos too. i didn't realize i needed to reference system.core.
:)
:)
okay. okay.
okay.
this'll do
:]
okay.
public int Roll(int NumberOfDice, int Faces) { int Sum = 0; for (int i = 0; i < NumberOfDice; i++) { Sum += Die.Next(0, Faces); } return Sum; } public List<int> Roll(int NumberOfDice, int Faces, out int Sum) { List<int> Rolls = new List<int>(); for (int i = 0; i < NumberOfDice; i++) { Rolls.Add(Die.Next(0, Faces)); } Sum = Enumerable.Sum(Rolls); return Rolls; }
this'll do
:]
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement