C algorithm design for 1000 bottles of water problem

  • 2020-12-26 05:50:57
  • OfStack

An example of C# algorithm for 1000 bottles of water is presented in this paper. Share to everybody for everybody reference. The details are as follows:

The title is as follows: Suppose you have an N bottle of water (N, of course > 0?)
An empty bottle for every 1 drunk
And for every three empty bottles you get one more bottle of water, and when you drink it you get one more empty bottle,

How many bottles of water can you drink, and how many empty bottles are left?

The code is as follows:


private int Water(int n, int emptyQty)
{
 Console.WriteLine(" drank " + n + " Bottles of water , more " + emptyQty + " A bottle is empty .");

 if (n + emptyQty < 3) // If you finish drinking water + The empty bottle is not there yet 3 If so, drink it up 
 {
 Console.WriteLine(" more " + (n + emptyQty) + " A bottle is empty .");
 return n;
 }

 int a = (n + emptyQty) / 3; // A replaceable a Bottles of water 
 int b = (n + emptyQty) % 3; // A few empty bottles left 

 return n + Water(a, b);
}

Let's say I start with 1,000 bottles, and I call the method


int sum = Water(1000,0);
Console.WriteLine(" drank " + sum + " Bottles of water ");

Hopefully this article has helped you with your C# programming.


Related articles: