简体   繁体   中英

Iterating with foreach through a dictionary

Is there a way to iterate through this loop and:

var resAndNumber = new Dictionary<int, int>();
for (int i = 0; i < numberRepeats; i++)
{

    for (int n = 0; n < numberDice; n++)
    {

        rolledResult1 += diceRandomGenerate.Next(1, 7);
    }

    //if the sum was not thrown, entry in the dictionary
    if (!resAndNumber.ContainsKey(rolledResult1))
    {
        resAndNumber[rolledResult1] = 0;
    }

    // bisherige  Anzahl für diese Summe hochzählen
    resAndNumber[rolledResult1]++;
}
  • let the output for the console could be done with a single foreach, which i'm trying to understand. I'm still wacky with the basics, before I stuck into a cul de sac - could you give me any suggests or so?

For the fulfillness of the question/target, the user is allowed to decide how many dice shall be simulated. Thankfully, c#starter.

The output may look like this

Dictionary<T,S> implements IEnumerable<KeyValuePair<T, S>> so it can be enumerated:

foreach (var kv in dic) {
  Console.WriteLine($"({kv.Key}, {kv;.Value})");
}

But the whole idea of tracking how many rolls of each outcome can be more easily tracked with an array (where entries will default to zero):

var results = new int[6*diceCount + 1];
// Will ignore indicies 0 to diceCount-1 as easier than using
// non-zero based arrays.

for (var roll = 1; roll <= rollCount; ++roll) {
  var rollResult = Enumerable.Range(0, diceCount)
                             .Select(x => diceRandomGenerate.Next(1, 7))
                             .Sum();
  results[rollResult]++;
}

for (var roll = diceCount; roll <= diceCount*6; ++roll) {
  Console.WriteLine($"{roll:d2} " + new String('*', results[roll]));
}

Something like this?:

foreach (var keyValuePair in resAndNumber)
{
    Console.WriteLine($"Die eye {keyValuePair.Key} for the 1. die was {keyValuePair.Value} ties thrown");
}

Note that your don't store the results that are not rolled and the results will be in the order that they are first rolled. So if you roll 1, 6, 3, 6, 1, 3, 3 the results will be (1, 2), (6, 2) and (3,3).

You may want to fill the dictionary first like so:

var resAndNumber = new Dictionary<int, int> {{1, 0}, {2, 0}, {3, 0}, {4, 0}, {5, 0}, {6, 0}};

Then you can leave the check if the result is already in the dictionary.

Example:

var resAndNumber = new Dictionary<int, int> {{1, 0}, {2, 0}, {3, 0}, {4, 0}, {5, 0}, {6, 0}};

resAndNumber[1]++;
resAndNumber[6]++;
resAndNumber[3]++;
resAndNumber[6]++;
resAndNumber[4]++;

foreach (var keyValuePair in resAndNumber)
{
    Console.WriteLine($"Die eye {keyValuePair.Key} for the 1. die was {keyValuePair.Value} ties thrown");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM