[Solved] How to add indexes with a for loop from a multidimensional array using C#?


You need one more array, instead of four separate variables. This will make it easy to pick only (the right) one of the totals to update in the inner loop. Otherwise, all four scores will always get the score of the final golfer, since the inner loop currently sets all four variables. It will look like this:

int[] holePars = { 4, 3, 4, 4, 5, 4, 5, 3, 4, 4, 3, 5, 4, 4, 5, 4, 3, 4};
int[,] holeScores = new int[18, 4];// 18 holes, 4 golfers
int[] totals = {0, 0, 0, 0};

var randomScores = new Random();

Console.WriteLine("Hole Par Golfer 1 Golfer 2 Golfer 3 Golfer 4");

for (int i = 0; i < 9; i++)
{
    Console.Write($"  {i + 1}{holePars[i],4}     ");

    for (int j = 0; j < 4; j++)
    {
        holeScores[i,j] = randomScores.Next(holePars[i] - 2, holePars[i] + 3);
        Console.Write($"{holeScores[i,j],-9}");
        totals[j] += holeScores[i,j];
    }
    Console.WriteLine();
}

Console.WriteLine($"Front {totals[0]} {totals[1]} {totals[2]} {totals[3]}");

See it work here:

https://dotnetfiddle.net/6XSLES


I like what you’ve done with the deviation from par for getting the random scores. If you really want to make this look more like a real golf game, you could also create weights for the scores, so golfers are more likely to end up closer to par. That might look like this:

https://dotnetfiddle.net/qoUOWf

The code at the above link makes you more than 4 times as likely to hit a par over a double eagle, where the original was purely random.

Additionally, it would be fun to also weight golfer skills once at the beginning, so you’re less likely to have the same golfer get both triple bogeys and eagles.

1

solved How to add indexes with a for loop from a multidimensional array using C#?