Created
March 10, 2016 15:45
-
-
Save thillerson/5cd6b24caebed9f43f66 to your computer and use it in GitHub Desktop.
segment problem
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
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