Skip to content

Instantly share code, notes, and snippets.

@dylanbeattie
Created July 1, 2022 13:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dylanbeattie/d8a023edea302aba495e32446faa36b1 to your computer and use it in GitHub Desktop.
Save dylanbeattie/d8a023edea302aba495e32446faa36b1 to your computer and use it in GitHub Desktop.
while() {} vs do {} while() loops using Roadrunner and Wile E. Coyote
abstract class Animal {
public int distanceFromEdge = 1;
protected bool edge => distanceFromEdge <= 0;
protected void run() {
distanceFromEdge--;
}
public abstract void go();
}
class Roadrunner : Animal {
public Roadrunner(int startingPosition) {
this.distanceFromEdge = startingPosition;
}
public override void go() {
while(!edge) {
run();
}
}
}
class Coyote : Animal {
public Coyote(int startingPosition) {
this.distanceFromEdge = startingPosition;
}
public override void go() {
do {
run();
} while (! edge);
}
}
class Program {
static void Run(int startingPosition) {
Console.WriteLine($"Starting positions: {startingPosition}");
var coyote = new Coyote(startingPosition);
var runner = new Roadrunner(startingPosition);
coyote.go();
runner.go();
Console.WriteLine("Final positions:");
Console.WriteLine($"Coyote: {coyote.distanceFromEdge}");
Console.WriteLine($"Roadrunner: {runner.distanceFromEdge}");
Console.WriteLine(String.Empty.PadRight(30, '-'));
}
static void Main() {
Run(2);
Run(1);
Run(0);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment