Question

I'm working on a random number guessing game as a c# console program. It's done with the code and working. However, there is a part that I want to make better: I declared an instance of a Guess class I created, now how to make this part more efficient?

int counter = 0;
do
{
    myGuess.UserGuess = GetUserGuess(); //read user guess
    if (myGuess.Compair() == "match")
    {
        Console.WriteLine("\n\t Correct!You WIN !");
    }


    else if (myGuess.Compair() == "high")
    {
        if (counter < 3)
            Console.WriteLine("\n\tTry a lower number,");
        else
            Console.WriteLine("\n\tSorry you LOSE !, The right number is " + myGuess.RndNum);

        counter++;
    }

    else if (myGuess.Compair() == "low")
    {
        if (counter < 3)
            Console.WriteLine("\n\tTry a higher number,");
        else

            Console.WriteLine("\n\tSorry you LOSE !, The right number is " + myGuess.RndNum);
        counter++;
     }


} while (myGuess.Compair() != "match" && counter < 4);

Thanks in advance.

Was it helpful?

Solution

What does "Compair()" function look like? It seems like that could return an integer rather than a string for a simpler function. An example of that looks like:

// just an example implementation
public int Compair() {
   if (UserGuess < actualValue) return -1;
   if (UserGuess > actualValue) return 1;
   return 0;
}

And then your routine becomes:

int counter = 0;
bool success = false;

do
{
    myGuess.UserGuess = GetUserGuess();
    int compair= myGuess.Compair()
    switch (compair) {
      case 0:
        Console.WriteLine("\n\t Correct!You WIN !");
        success = true;
        break;
      case 1:
      case -1:
        if (counter < 3) Console.WriteLine("\n\tTry a {0} number,", compair == -1 ? "lower" : "higher");
        break;
    }

    counter++;
    if (counter >= 3 && !success)
      Console.WriteLine("\n\tSorry you LOSE !, The right number is " + myGuess.RndNum);
  } while (!success && counter < 4);

That should do it! This should be faster because it isn't using string comparisons, it might be a bit easier to read and it should have fixed a few logical issues.

Note - I made a few assumptions about the use of properties so this example might not compile out of the get but it should get you most of the way there. Best of luck!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top