Skip to content

Commit eee59be

Browse files
committed
[Scala-Way] Add greedy package and min refuel problem
1 parent db2e6d0 commit eee59be

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package greedy
2+
3+
/*
4+
Find the minimum stops for refueling required by a car on it's journey from point A to point B
5+
*/
6+
7+
object MinimumRefuels extends App{
8+
/*
9+
stops: Array of distances at which fuel stations are present from point A
10+
distanceToPointB: Distance to point B from current station
11+
maxDistanceOnFullTank: The max distance the car can cover when it's tank is full
12+
*/
13+
14+
def minimumRefuels(stops: Array[Int], distanceToPointB: Int)(implicit maxDistanceOnFullTank: Int): Option[Int] = stops match {
15+
case Array(stop1, _ *) if stop1 > maxDistanceOnFullTank => None
16+
case _ => stops.indices.find(index => stops(index) >= maxDistanceOnFullTank) match {
17+
case Some(stopIndex) =>
18+
val greedyHopIndex = if(stops(stopIndex) == maxDistanceOnFullTank) stopIndex else stopIndex - 1
19+
val distanceCovered = stops(greedyHopIndex)
20+
val updatedStops = stops.drop(stopIndex).map(_ - distanceCovered)
21+
minimumRefuels(updatedStops, distanceToPointB - distanceCovered).map(_ + 1)
22+
case None => Some(0)
23+
}
24+
}
25+
}
26+
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import org.scalatest.FunSuite
2+
import greedy.MinimumRefuels
3+
4+
class MinRefuelsTest extends FunSuite {
5+
6+
test("Should return the correct min refuels when solution is possible"){
7+
val stops = Array(10,40,70,80)
8+
val minRefuels = MinimumRefuels.minimumRefuels(stops = stops, distanceToPointB = 100)(maxDistanceOnFullTank = 30)
9+
assert(minRefuels == Some(3))
10+
}
11+
12+
test("Should return none if there solution is not possible"){
13+
val stops = Array(10,50,70,80)
14+
val minRefuels = MinimumRefuels.minimumRefuels(stops = stops, distanceToPointB = 100)(maxDistanceOnFullTank = 30)
15+
assert(minRefuels == None)
16+
}
17+
18+
test("Should return 0 when no stops are required"){
19+
val stops = Array(10,50,70,80)
20+
val minRefuels = MinimumRefuels.minimumRefuels(stops = stops, distanceToPointB = 100)(maxDistanceOnFullTank = 101)
21+
assert(minRefuels == Some(0))
22+
}
23+
24+
}

0 commit comments

Comments
 (0)