我如何使用c#解决下面的场景 [英] How I solve a scenario like below using c#

查看:59
本文介绍了我如何使用c#解决下面的场景的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一对乒乓球得分。

在多少方面可以达到最终得分。



例如

输入是

10 11 14 12



其中10是player1当前得分,11是player2当前得分

14是玩家1的最终得分,12是玩家2的最终得分。



因此2种方式是:

10:11 - > 11:11-> 12:11-> 12:12-> 13:12 - > 14:12

10:11 - > 11:11-> 11:12-> 12:12-> 13:12-> 14:12




被PIEBALDconsult感动



我尝试了以下代码,但它只是迭代。

我无法找到一个条件,我可以找到方法的数量可以超过一个。

代码:



Given a pair of table tennis score.
In how many ways final score can be achieved.

for e.g
input is
10 11 14 12

where 10 is player1 current score , 11 is player2 current score
14 is player1 final score , 12 is player2 final score.

Thus the 2 ways are:
10:11 -> 11:11-> 12:11-> 12:12-> 13:12 ->14:12
10:11 -> 11:11-> 11:12-> 12:12-> 13:12-> 14:12


Moved by PIEBALDconsult

I tried the following code but it just iterates .
I am not able to look for an condition where I can find that the number of ways can be more than one.
Code :

class Program
{
static void Main(string[] args)
{
int T = 0;
T = Convert.ToInt32(Console.ReadLine());
String[] values = new String[4];
List listScore = new List();

int caseNo=0;
for(int i=0;i 2 && (s.player1Final >= 11 || s.player2Final >= 11)))
{
while (!(s.player1Initial== s.player1Final && s.player2Initial==s.player2Final))
{
if(((s.player1Initial+1) -s.player2Initial) <=2 && s.player1Initial!=s.player1Final)
{
s.player1Initial = s.player1Initial + 1;
}
if (((s.player2Initial + 1) - s.player1Initial) <= 2 && s.player2Initial != s.player2Final)
{
s.player2Initial = s.player2Initial + 1;
}
if (s.player1Initial == s.player2Initial && ((s.player1Initial + 1) - s.player2Initial <= 2) && ((s.player2Initial + 1) - s.player1Initial) <= 2)
{
countWays = countWays + 1;
}
}
}

Console.WriteLine("Case {0}: {1}", caseNo, countWays);
}

Console.ReadLine();
}

}
class Score
{
public int player1Initial { get; set; }
public int player2Initial { get; set; }
public int player1Final { get; set; }
public int player2Final { get; set; }
}

推荐答案

这不是编程问题,而是数学问题( Combinatorics [ ^ ])问题。

问题:玩家1从10变为14,玩家2从11变为12.

分析可能的解决方案:

This is not a programming problem but a mathematical (Combinatorics[^]) problem.
Problem: Player 1 goes from 10 to 14, player 2 from 11 to 12.
Analysis of the possible solutions:


  1. 您有以下可能的个人匹配结果

    a1)10:11

    a2)10:12



    b1)11:11

    b2)11:12



    c1)12:11

    c2)12:12



    d1)13:11

    d2)13:12



    e1)14:11

    e2)14:12

  2. 找到一种方法来检查给定情况的所有可能(有意义的)匹配结果,例如



    < TBODY> < tr>
    b'/次> C d 电子
    1 1 1 1 1 2
    1 1 1 1 2 2
    1 1 1 2 2 2
    1 1 2 2 2 2
    1 2 2 2 2 2

  3. 推导出给定方法的通用算法来遍历所有有意义的结果(迭代或递归)。这留给你作为锻炼。 ;-)



    好​​的,不是真的。在BillWoodruff的评论之后,我提供了一个基于递归的解决方案。


  1. you have the following possible individual match results
    a1) 10:11
    a2) 10:12

    b1) 11:11
    b2) 11:12

    c1) 12:11
    c2) 12:12

    d1) 13:11
    d2) 13:12

    e1) 14:11
    e2) 14:12
  2. Find an way to go over all possible (meaningful) match results for the given situation, e.g.

    abcde
    11111 2
    1111 22
    111 222
    11 2222
    1 22222

  3. deduce a general algorithm for the given approach to traverse all meaningful results (iterative or recursive). This is left for you as exercise. ;-)

    Ok, not really. After BillWoodruff's comments, I provide a solution here that is based on recursion.
static void playMatches(string[] scores, int iToPlay, int iCurr1, int iCurr2, int iEnd1, int iEnd2)
{
    // play this match
    scores[scores.Length - iToPlay] = string.Format("{0}:{1}", iCurr1, iCurr2);
    // play the rest...
    // ...1st: all possible scores from this point on
    // when applying here all remaining permutations of player 1 scores
    for(int i = iCurr1+1; i <= iEnd1; ++i)
    {
        playMatches(scores, iToPlay-1, i, iCurr2, iEnd1, iEnd2);
    }
    // ...2nd: all possible scores from this point on
    // when applying here all remaining permutations of player 2 scores
    for (int i = iCurr2+1; i <= iEnd2; ++i)
    {
        playMatches(scores, iToPlay-1, iCurr1, i, iEnd1, iEnd2);
    }
    // last match: write whole score sequence
    if (iToPlay == 1)
    {
        Console.WriteLine(string.Join(" -> ", scores));
    }
}

这样称呼:

int iScore1 = ...;
int iScore2 = ...;
int iEnd1 = ...;
int iEnd2 = ...;
int iMatches = iEnd1 + iEnd2 + 1 - iScore1 - iScore2;
string[] scores = new string[iMatches];
playMatches(scores, iMatches, iScore1, iScore2, iEnd1, iEnd2);

给定数据的结果输出为

10:11 -> 11:11 -> 12:11 -> 13:11 -> 14:11 -> 14:12
10:11 -> 11:11 -> 12:11 -> 13:11 -> 13:12 -> 14:12
10:11 -> 11:11 -> 12:11 -> 12:12 -> 13:12 -> 14:12
10:11 -> 11:11 -> 11:12 -> 12:12 -> 13:12 -> 14:12
10:11 -> 10:12 -> 11:12 -> 12:12 -> 13:12 -> 14:12

[/编辑]

[/EDIT]



干杯

Andi


Cheers
Andi


冒着描述使用C#的某些功能的解决方案的风险,许多该语言的新手可能没有遇到或理解如何使用,我将在这里提供一些代码:
At the risk of describing a "solution" that uses some features of C# that many newcomers to the language may have not encountered, or understood how to use, I'm going to offer some code here:
// required in addition to whatever else is required
using System.Collections.Generic;
using System.Linq;

// data for one Match
public struct MatchData
{
    public int ID;

    public int player1Score;
    public int player2Score;

    public MatchData(int id, int s1, int s2)
    {
        ID = id;
        player1Score = s1;
        player2Score = s2;
    }
}

// given parameters that specify starting scores for two players
// and number of possible additional points that can be made
// create a Dictionary whose Key is an integer Match ID
// and whose Value is an instance of the struct 'MatchData
private Dictionary<int,> CalculatePossibleMatches(int p1Start, int p1MaxPointsToAdd, int p2Start, int p2MaxPointsToAdd)
{
    IEnumerable<int> player1Scores = Enumerable.Range(p1Start, p1MaxPointsToAdd + 1);
    IEnumerable<int> player2Scores = Enumerable.Range(p2Start, p2MaxPointsToAdd + 1);

    var dctMatchIDToScores = new Dictionary<int,>();

    int currentMatchID = 0;

    foreach (int score1 in player1Scores)
    {
        foreach (int score2 in player2Scores)
        {
            dctMatchIDToScores.Add(++currentMatchID, new MatchData(currentMatchID, score1, score2));
        }
    }

    return dctMatchIDToScores;
}

现在:通过在某些方法或EventHandler中执行此代码进行测试:

Now: test by executing this code in some Method, or EventHandler:

Dictionary<int,> Matches = CalculatePossibleMatches(10, 4, 11, 1);

foreach (var kvp in Matches)
{
    MatchData scores = kvp.Value;

    Console.WriteLine("Match: #{0} Player 1: {1} Player2: {2}", kvp.Key, scores.player1Score,
        scores.player2Score);
}

在输出窗口(WinForms)或控制台中观察结果。在'foreach循环之前在测试代码中放置一个断点,并检查从'CalculatePossibleMatches返回的Dictionary对象的值。



评论:



1.在给定输入数据的情况下,我们使用Linq的强类型IEnumerable来保存可能得分的范围。 Enumerable.Range方法返回一个序列;该序列必须存储在IEnumerable类型的变量中...不要问我原因,请问微软:)



2.一个'foreach循环在另一个' foreach循环可以访问每一对可能的分数。



3.创建'MatchData结构的新实例,插入每个匹配的数据通过它的构造函数进入它,并在Dictionary中创建一个新条目,Key设置为Match ID号,Value设置为MatchData实例。



要问的好问题:



1.构建字典有什么好处,使用'Struct?


a。然后我们可以以非常强大的方式使用Linq来查询该词典,并生成任何类型的摘要结果,或者根据一个或多个标准选择项目。



湾imho,这里显示的技术清楚地表达了代码的意图,即需要解决问题的本质。

Observe the result in the 'Output window (WinForms), or Console. Put a break-point in the test code before the 'foreach loop and examine the value of the Dictionary object returned from 'CalculatePossibleMatches.

Comments:

1. we use Linq's strongly typed IEnumerable here to hold a Range of possible scores, given the input data. The Enumerable.Range method returns a sequence; that sequence must be stored in a variable of Type IEnumerable ... don't ask me why, ask Microsoft :)

2. one 'foreach loop inside another 'foreach loop does the right thing to access every possible pair of scores.

3. a new instance of the 'MatchData struct is created, the data for each Match is inserted into it via its constructor, and a new entry is made in the Dictionary with the Key set to the Match ID number, and the Value set to the instance of MatchData.

Good questions to ask:

1. what are the benefits of building a Dictionary, and using a 'Struct ?

a. we can then use Linq in very powerful ways to query that Dictionary, and produce summary results of any type, or select items based on one, or many, criteria.

b. imho, the techniques shown here clearly express the "intent" of the code, that is the "nature" of problem-solving required.


这里我创建了一个简单的控制台应用程序来获取你的输出。希望这可以帮到你:-)



Here i have created a simple console application to get your output.Hope this helps you :-)

bool minCurrScoreIsP1 = false;
            
            Console.WriteLine("Enter Player1 Current Score...");
            int currP1 = int.Parse(Console.ReadLine());
            Console.WriteLine("Enter Player2 Current Score...");
            int currP2 = int.Parse(Console.ReadLine());

            Console.WriteLine("Enter Player1 Final Score...");
            int lastP1 = int.Parse(Console.ReadLine());
            Console.WriteLine("Enter Player2 Final Score...");
            int lastP2 = int.Parse(Console.ReadLine());
            

            int P1PointDiff = lastP1 - currP1;
            int P2PointDiff = lastP2 - currP2;

            int minDiffP = -1;
            int MinCurrIter = -1;

            int maxDiffP = -1;
            int MaxCurrIter = -1;

            if(currP1 < currP2)
            {
                minDiffP = currP1;
                maxDiffP = currP2;
                MinCurrIter = lastP1 - currP1;
                MaxCurrIter = lastP2 - currP2;
                minCurrScoreIsP1 = true;
            }
            else
            {
                minDiffP = currP2;
                maxDiffP = currP1;
                MinCurrIter = lastP2 - currP2;
                MaxCurrIter = lastP1 - currP1;
                minCurrScoreIsP1 = false;
            }
             

            for (int k = 0; k <= MinCurrIter; k++)
            {
                for (int i = 0; i <= MaxCurrIter; i++ )
                {
                    if ((minDiffP + k + 1) == maxDiffP && (i + 1 + maxDiffP) == maxDiffP)
                    {
                        break;
                    }
                    else
                    {
                        if (minCurrScoreIsP1)
                            Console.WriteLine("Combinations >> " + "P1 " + (minDiffP + k) + ":" + "P2 " + (i + maxDiffP));
                        else
                            Console.WriteLine("Combinations >> " + "P2 " + (minDiffP + k) + ":" + "P1 " + (i + maxDiffP));
                    }
                }
            }
            Console.ReadLine();


这篇关于我如何使用c#解决下面的场景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆