简体   繁体   中英

Compare items from two arrays to see if they sum to 10

I want to compare two "Dice" arrays to see how many ways the sum of 10 can be created using two dice, then add the number of "10 pairs" to another variable.

This is what I have so far, I'm not sure how to start the forEach loop (or if that's even what I want to use):

            {
                //Store 10-pairs in a new variable
                int tenPairs = 0;

                // Need variables to define the dice - arrays starting at 1?
                int[] die1 = Enumerable.Range(1, num1).ToArray(); 

                int[] die2 = Enumerable.Range(1, num2).ToArray();

                //Compare each item from die1 to each value from die2 to see if they
                //add up to 10.




                //return a string with the message: "There are X total ways to get the sum 10."
                string resultMsg = "There are " + tenPairs +" total ways to make 10.";
                
                return resultMsg ;
            } 

If I understand correctly you can set num1 and num2 manually?

You should use two loops one nested in another. Then in nested loop there should be if statement that checks if numbers sum up to 10.

I wont give you code - try to figure it out yourself and let me know if you have succeeded :)

If you haven't figured out the solution, here it is:

private static string NumberOfTens(int number1, int number2)
    {
      //Store 10-pairs in a new variable
      int tenPairs = 0;

      // Need variables to define the dice - arrays starting at 1?
      int[] die1 = Enumerable.Range(1, number1).ToArray();

      int[] die2 = Enumerable.Range(1, number2).ToArray();

      //Compare each item from die1 to each value from die2 to see if they add up to 10.

      for (int i = 0; i < die1.Length; i++)
      {
        for (int j = 0; j < die2.Length; j++)
        {
          if (die1[i] + die2[j] == 10)
          {
            tenPairs++;
          }
        }
      }

      //return a string with the message: "There are X total ways to get the sum 10."
      string resultMsg = "There are " + tenPairs + " total ways to make 10.";

      return resultMsg;
    }

here is how to use it :

Console.WriteLine(NumberOfTens(5, 15));

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