4
\$\begingroup\$

Problem Statement:

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, he first enters a valley units deep. Then he climbs out an up onto a mountain 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.

countingValleys has the following parameter(s):

  • n: the number of steps Gary takes
  • s: a string describing his path

Input Format

The first line contains an integer, the number of steps in Gary's hike. The second line contains a single string, of characters that describe his path.

Output Format

Print a single integer that denotes the number of valleys Gary walked through during his hike.

My solution goes like this :

def countingValleys(n: Int, s: String): Int = {
  def rec(path: List[Char], counter: Int, valleys: Int): Int = {
    path match  {
      case Nil => valleys
      case x::xs if (x == 'U') && ((counter + 1) == 0) =>
        rec(xs, counter+1, valleys+1 )
      case x::xs if x == 'U' => rec(xs, counter +1, valleys)
      case x::xs if x == 'D' => rec(xs, counter -1, valleys)
    }
  }
  rec(s.toList, 0, 0)
}

Sample Input:

8
UDDDUDUU

Sample Output:

1

I wonder if there is a more idiomatic solution in functional programming style.

\$\endgroup\$

migrated from stackoverflow.com Jul 15 at 0:21

This question came from our site for professional and enthusiast programmers.

  • \$\begingroup\$ Side question about the problem - is the number of steps (n) redundant information? Won't that always be s.length? \$\endgroup\$ – Damon Jul 14 at 19:10
  • \$\begingroup\$ Yes, you are absolutely correct. Function was provided this way. I will report the question on Hacker-Rank. \$\endgroup\$ – Sandio Jul 15 at 5:10
  • \$\begingroup\$ @Sandio adding n as an additional information is necessary for languages like C++ that don't perform the same level of behind-the-scenes memory management as other languages \$\endgroup\$ – Vogel612 Jul 16 at 10:08
  • \$\begingroup\$ Oh. That makes sense. @Vogel612 Thank you for the information. \$\endgroup\$ – Sandio Jul 16 at 21:02
2
\$\begingroup\$

Your counter is a cumulative sum of elevation changes; elevation would be a more precise name for it.

Ultimately, the goal is to count the number of times the elevation changes from -1 to 0. To do that:

  1. Translate the 'U' and 'D' steps into +1 and -1, respectively.
  2. Obtain a sequence representing the elevation profile of the hike using Seq.scan.
  3. Count the number of times -1 is followed by 0 in the elevation profile, using Seq.sliding(2) and Iterator.count.
def countingValleys(n: Int, s: String): Int = s
  .map(_ match {case 'U' => +1; case 'D' => -1})
  .scan(0)(_+_)
  .sliding(2)
  .count(_ == Vector(-1, 0))
\$\endgroup\$
  • \$\begingroup\$ This is so out of the box. Thank you. \$\endgroup\$ – Sandio Jul 15 at 7:27
2
\$\begingroup\$

There's nothing wrong with or "not functional" about your approach. This might be opinion territory, but personally I would consider using foldLeft as it might be more readable and you can potentially eliminate some of the complexity of your cases.

(also I got rid of n here as it is completely irrelevant, I know it's a problem from a website so you have to follow the format they gave you)

def countingValleys (steps: String): Int = steps
  .foldLeft((0, 0)) {
    case ((valleys, elevation), 'D') => (valleys, elevation - 1)
    case ((valleys, -1), 'U') => (valleys + 1, 0)
    case ((valleys, elevation), _) => (valleys, elevation + 1)
  }
  ._1
\$\endgroup\$
  • \$\begingroup\$ Thank you for your solution. It is helpful. \$\endgroup\$ – Sandio Jul 15 at 7:29
  • \$\begingroup\$ Note that the original code's counter is what you call depth. That's a bit confusing, since positive depth represents higher elevation. Also, the original code's valleys is what you call counter. I think valleys was a clearer name. \$\endgroup\$ – 200_success Jul 16 at 5:40
  • \$\begingroup\$ @200_success good point on the naming, updated. \$\endgroup\$ – Damon Jul 16 at 12:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.