I came across a leetcode like problem - one swap[1]. The solution I found using sort plus for loop to solve that problem, for which I understand it is not the best solution for that problem. I feel it’s a bit interested, so I spent some time coding with Scala. The code is as below. But it seems to me there are rooms to improve (to be more Scala style because I feel my code is seemingly verbose) but I am not aware of. So I appreciate if any suggestions regarding this. By the way, I am not looking for the correct solution, nor cryptic effective (or imperative) way for this problem. I am merely looking for more Scala/ readable style approaching to such question. Many thanks.
def oneSwap(list: List[Int]): Boolean = {
def isOneSwap(newList: List[Int]): Boolean = newList.sliding(2).find{ case pair =>
val prev = pair(0)
val current = pair(1)
if (current < prev) true else false
} match {
case Some(_) => false
case None => true
}
case class Acc(count: Int = 0, first: Int = 0, second: Int = 0)
val acc = list.sliding(2).zipWithIndex.foldLeft(Acc()){
case (acc, (List(prev, current), idx)) =>
if(current < prev) {
val newAcc = acc.copy(count = acc.count + 1)
if(newAcc.first == 0) newAcc.copy(first = idx + 1)
else newAcc.copy(second = idx + 1)
} else acc
}
acc.count match {
case cnt if cnt > 2 => false
case cnt if cnt == 0 => true
case cnt if cnt == 2 =>
val newList = list.
updated(acc.first-1, list(acc.second)).
updated(acc.second, list(acc.first-1))
isOneSwap(newList)
case cnt if cnt == 1 =>
val newList = list.
updated(acc.first-1, list(acc.first)).
updated(acc.first, list(acc.first-1))
isOneSwap(newList)
}
}
[1]. Check if array can be sorted with one swap - GeeksforGeeks