Skip to content

Instantly share code, notes, and snippets.

@thillerson
Created March 10, 2016 15:45
Show Gist options
  • Save thillerson/5cd6b24caebed9f43f66 to your computer and use it in GitHub Desktop.
Save thillerson/5cd6b24caebed9f43f66 to your computer and use it in GitHub Desktop.
segment problem
case class RoadSegment(id:Int, segType:String)
case class Leg(begin:RoadSegment, end:Option[RoadSegment])
val segments = Seq(
RoadSegment(1, "D"),
RoadSegment(2, "D"),
RoadSegment(3, "D"),
RoadSegment(4, "W"),
RoadSegment(5, "B"),
RoadSegment(6, "B"),
RoadSegment(7, "W")
)
// 1. Close to what I'd conceived in the interview
segments.foldLeft(List[Leg]()) { (acc, seg) =>
if (acc == Nil) {
acc ++ List(Leg(seg, None))
} else {
if (acc.head.begin.segType == seg.segType) {
Leg(acc.head.begin, Some(seg)) :: acc.tail
} else {
Leg(seg, None) :: acc
}
}
}.reverse
// 2. With less logic for nil
segments.tail.foldLeft(List[Leg](Leg(segments.head, None))) { (acc, seg) =>
if (acc.head.begin.segType == seg.segType) {
Leg(acc.head.begin, Some(seg)) :: acc.tail
} else {
Leg(seg, None) :: acc
}
}.reverse
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment