Created
July 1, 2022 13:20
-
-
Save dylanbeattie/d8a023edea302aba495e32446faa36b1 to your computer and use it in GitHub Desktop.
while() {} vs do {} while() loops using Roadrunner and Wile E. Coyote
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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