I tried to solve a programming contest problem in Scala, but I have a feeling, that it could be done in a more functional way. I compared it with the solution written in imperative style and it is not shorter or less complex at all. Do you have any idea how to "impove" or approach the problem in a more functional way?
Here is my solution:
object Sunshine extends App {
def tanning(bedNumber:Int, part1 : List[Char], part2: List[Char], inBed: List[Char], tanned:Int, walkedAway: Int) : Int = {
val actCustomer =part2.head
val tanningTuple=(part1.indexOf(actCustomer),inBed.indexOf(actCustomer),bedNumber>inBed.length,part2.tail)
tanningTuple match {
case(_,_,_,Nil) => walkedAway
// enter,can be tanned
case (-1,-1,true,_) =>
tanning(bedNumber,actCustomer::part1,part2.tail,actCustomer::inBed,tanned,walkedAway)
// enter, can not be tanned
case (-1,-1,false,_) =>
tanning(bedNumber,actCustomer::part1,part2.tail,inBed,tanned,walkedAway)
//leave, not in bed
case (x ,-1,_,_) if x>=0 =>
tanning(bedNumber,actCustomer::part1,part2.tail,inBed,tanned,walkedAway+1)
//leave, in bed
case (x,y,_,_) if x>=0 && y>=0 =>
tanning(bedNumber,actCustomer::part1,part2.tail,inBed-actCustomer,tanned+1,walkedAway)
}
}
println(tanning(2,List(),"ABBAJJKZKZ".toList,List(),0,0))
println(tanning(3,List(),"GACCBDDBAGEE".toList,List(),0,0))
println(tanning(3,List(),"GACCBGDDBAEE".toList,List(),0,0))
println(tanning(1,List(),"ABCBCA".toList,List(),0,0))
}