比较C ++中变量的最有效方法

时间:2018-10-04 18:11:19

标签: c++

我有一个任务要为以下问题编写代码。

  

编写一个彩票游戏应用程序,该应用程序将生成三个随机数,每个随机数在0到9之间。用户应猜出三个数字,程序应将用户的猜想与三个随机数进行比较,并根据他们是否得到了显示适当的输出:

     
      
  • 任何人匹配
  •   
  • 两个匹配
  •   
  • 三个匹配项,不按顺序排列
  •   
  • 三个完全相同的匹配
  •   
  • 或完全没有匹配项
  •   

我一直在尝试不同的方法来执行此操作,我发现一种方法是使用if else if语句,但是代码效率很低。

我尝试做的另一种方法是使用for循环,但是这样做有逻辑错误。

我正在使用以下代码。

int inputarray[3];
int randomnumberarray[3];
//here goes simple if condition for checking case of all same numbers in exact order//
for ( int i = 0 ; i < 3 ; i ++ ) /*this condition is applied after checking the numbers to be equal in exact order*/
{
        for ( int j = 0 ; j < 3 ; j ++ )
        {
                if ( randomnumberarray[j] == inputarray[i] )
                        ++repition ;
        }
}

但是使用上述条件,如果用户输入相同的数字3次或随机数字相同,就会变得很奇怪。

任何帮助都会有所帮助。

2 个答案:

答案 0 :(得分:1)

如果您讨厌if-else-if阶梯,那么我对您问题的快速回答如下。 @Rao Ubaid 's answer几乎是正确的,但是我们必须丢弃已经匹配的猜测值,例如this demo,以避免重复计算:

int calcScore(
    const std::vector<std::size_t>& ans,
    std::vector<std::size_t> guess)
{        
    assert((ans.size() == 3) && (guess.size() == 3));

    if((ans[0] == guess[0]) && (ans[1] == guess[1]) && (ans[2] == guess[2])) {
        return 4;
    }

    auto score = 0;

    for (const auto ans_i : ans)
    {
        for (auto it = guess.begin(); it != guess.cend(); ++it)
        {
            if (*it == ans_i)
            {
                score += 1;
                guess.erase(it);
                break;
            }
        }
    }

    return score;    
}

接下来要考虑的是编写测试和性能调整。

答案 1 :(得分:0)

我找到了一种方法。 这是代码。

Phone1 = (808)555-1234
Phone2 = (808)555-9876
相关问题