0

我为 C# windows 窗体项目编写了一个事件处理程序,该项目模拟 100 次两个骰子的掷骰,并为每个掷骰返回两个骰子的总和。代码对这些总和中的每一个做了三件事,将其放在名为“rollDisplay”的 RichTextBox 中,将总和写入文本文件,并将总和添加到称为“rolls”的整数列表中。所有这些都工作正常,但现在我需要计算每个和的频率,并在 ListBox 中显示这些频率。正如下面的代码所示,我使用了 11 个不同的计数器变量和 11 个不同的字符串来添加到 ListBox。我在下面的工作,但它真的很丑陋,在我看来这是一种非常低效的方法。

我的问题是。任何人都可以提出一种更清洁的方法吗?作业要求我有 11 个单独的计数器来识别掷骰子的频率,所以我不能像其他几个问题所建议的那样使用 Linq,但我真的很不确定这是完成什么的最佳方法我需要。

private void Roll_Click(object sender, EventArgs e)
    {
        int roll = 0, hitTwo = 0, hitThree = 0, hitFour = 0, hitFive = 0, hitSix = 0, hitSeven = 0, hitEight = 0,
            hitNine = 0, hitTen = 0, hitEleven = 0, hitTwelve = 0;
        String freq1, freq2, freq3, freq4, freq5, freq6, freq7, freq8, freq9, freq10, freq11;
        StreamWriter file = new StreamWriter("dicerolls.txt", true);
        List<int> rolls = new List<int>();

        for (int i = 0; i < 100; i++)
        {
            dieUno.setSide(dieUno.roll());
            dieDuo.setSide(dieDuo.roll());

            int diceTotal = dieUno.getSide() + dieDuo.getSide();
            rolls.Add(diceTotal);
            rollDisplay.AppendText(diceTotal.ToString() + "\u2028");

            try
            {
                file.WriteLine(diceTotal.ToString());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        file.Close();  

        for (int i = 0; i < rolls.Count; i++)
        {
            roll = rolls[i];

                if(roll==2)
                { hitTwo++; }
                else if(roll==3)
                { hitThree++; }
                else if(roll==4)
                { hitFour++; }
                else if(roll==5)
                { hitFive++; }
                else if(roll==6)
                { hitSix++; }
                else if(roll==7)
                { hitSeven++; }
                else if(roll==8)
                { hitEight++; }
                else if(roll==9)
                { hitNine++; }
                else if (roll == 10)
                { hitTen++; }
                else if (roll == 11)
                { hitEleven++; }
                else if (roll == 12)
                { hitTwelve++; }
        }

        freq1 = " 2 Occurs: " + hitTwo + " times"; freq2 = " 3 Occurs: " + hitThree + " times"; freq3 = " 4 Occurs: " + hitFour + " times";
        freq4 = " 5 Occurs: " + hitFive + " times"; freq5 = " 6 Occurs: " + hitSix + " times"; freq6 = " 7 Occurs: " + hitSeven + " times";
        freq7 = " 8 Occurs: " + hitEight + " times"; freq8 = " 9 Occurs: " + hitNine + " times"; freq9 = " 10 Occurs: " + hitTen + " times";
        freq10 = " 11 Occurs: " + hitEleven + " times"; freq11 = " 12 Occurs: " + hitTwelve + " times";


        frequency.Items.Add(freq1); frequency.Items.Add(freq2); frequency.Items.Add(freq3); frequency.Items.Add(freq4); frequency.Items.Add(freq5);
        frequency.Items.Add(freq6); frequency.Items.Add(freq7); frequency.Items.Add(freq8); frequency.Items.Add(freq9); frequency.Items.Add(freq10);
        frequency.Items.Add(freq11);
    }
4

2 回答 2

1

Roll_Click做太多的工作。

首先,创建一个GatherSamples函数。

int[] GatherSamples()
{
    var rolls = new List<int>();

    // roll dice ...

    return rolls.ToArray();
}

然后一个DisplayRolls方法

void DisplayRolls(int[] rolls)
{
     // output to your control      
}

...和一种WriteToDisk方法

void WriteToDisk(int[] rolls, string file)
{
    using (var writer = new StreamWriter(file))  // research C# using if you don't understand this
    {
        ...
    }
}

...然后进行频率分析

string[] AnalyzeRolls(int[] rolls)
{
    // though I don't approve of 11 counters, use them here

    return new [] { "2 occurs " ... };
}

...然后这样称呼它:

foreach(var analysis in AnalyzeRolls(rolls))
{
    frequency.Items.Add(analysis);
}
于 2013-04-01T22:49:10.037 回答
0

干得好。一个 6 面骰子滚轮。它对用户界面一无所知。它几乎没有公开其内部实现。

class SixSidedDiceRoller
{
  private static readonly RandomNumberGenerator rng = RandomNumberGenerator.Create();
  private SortedDictionary<int,int> frequencyTable;
  private List<Tuple<int,int,int>> rollHistory;

  public int Count { get { return rollHistory.Count; } }

  public IEnumerable<Tuple<int , int , int>> RollHistory
  {
    get { return rollHistory.AsReadOnly(); }
  }

  public IEnumerable<Tuple<int,int>> FrequencyTable
  {
    get
    {
      return frequencyTable.Select(
        x => new Tuple<int,int>(x.Key,x.Value)
        ) ;
    }
  }

  public SixSidedDiceRoller()
  {

    rollHistory = new List<Tuple<int , int , int>>();

    // initialize the frequency table
    for ( int i = 2 ; i <= 12 ; ++i )
    {
      frequencyTable[i] = 0;
    }

    return;
  }

  public int RollDice()
  {
    int d1 = RollDie();
    int d2 = RollDie();
    int n  = d1 + d2;

    rollHistory.Add( new Tuple<int , int , int>( d1 , d2 , n ) );
    ++frequencyTable[n];

    return n;
  }

  private int RollDie()
  {
    byte[] octets = new byte[1];
    rng.GetBytes( octets );
    int die = 1 + ( octets[0] % 6 );
    return die;
  }

}

将它连接到 Windows 应用程序、wpf 应用程序、Web 应用程序、控制台应用程序等应该不会太难。

于 2013-04-01T23:02:30.397 回答