Skip to content

Instantly share code, notes, and snippets.

@primaryobjects
Last active August 15, 2019 18:31
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 primaryobjects/ac6f609ab1aa58a18a4fb0327aec08f8 to your computer and use it in GitHub Desktop.
Save primaryobjects/ac6f609ab1aa58a18a4fb0327aec08f8 to your computer and use it in GitHub Desktop.
Counting valleys hiked, a programming exercise in C# .NET.

Gary is an avid hiker. He tracks his hikes meticulously, paying close attention to small details like topography. During his last hike he took exactly steps. For every step he took, he noted if it was an uphill, , or a downhill, step. Gary's hikes start and end at sea level and each step up or down represents a unit change in altitude. We define the following terms:

A mountain is a sequence of consecutive steps above sea level, starting with a step up from sea level and ending with a step down to sea level. A valley is a sequence of consecutive steps below sea level, starting with a step down from sea level and ending with a step up to sea level. Given Gary's sequence of up and down steps during his last hike, find and print the number of valleys he walked through.

For example, if Gary's path is DDUUUUDD, he first enters a valley 2 units deep. Then he climbs out an up onto a mountain 2 units high. Finally, he returns to sea level and ends his hike.

Function Description

Complete the countingValleys function in the editor below. It must return an integer that denotes the number of valleys Gary traversed.

UDDDUDUU 1

static int countingValleys(int n, string s) {
var valleyCount = 0;
var elevation = 0;
var isValley = false;
foreach (var ch in s) {
elevation += Char.ToUpper(ch) == 'U' ? 1 : -1;
if (elevation < 0)
{
isValley = true;
}
else if (elevation == 0 && isValley)
{
valleyCount++;
isValley = false;
}
}
return valleyCount;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment