Skip to content

Instantly share code, notes, and snippets.

@debasishg
Created September 16, 2021 17:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save debasishg/73410f5914a65b9c572bbeed970af524 to your computer and use it in GitHub Desktop.
Save debasishg/73410f5914a65b9c572bbeed970af524 to your computer and use it in GitHub Desktop.
Phone numbers out of chess moves
package interview
object DominoInterview extends App {
/**
|1|2|3|
|4|5|6|
|7|8|9|
|*|0|#|
Problem:
Given a chess piece and a starting position
Making only legal chess moves find all valid 7 digit phone numbers
Example: Knight starts at 1
Some possible prefixes: 167, 183, 161, etc.
*/
val validMoves = Map(
1 -> List(6, 8),
2 -> List(9, 7),
3 -> List(4, 8),
4 -> List(3, 9, 0),
5 -> List(),
6 -> List(7, 1),
7 -> List(2, 6),
8 -> List(3, 1),
9 -> List(4, 2),
0 -> List(4, 6)
)
// I guess by passing a different Map we can generalize over all pieces
def getPhoneNo(start: Int, acc: List[Int]): List[Int] = {
if (acc.size == 7) acc
else {
val l: List[Int] = validMoves.get(start).get
l.flatMap { e => getPhoneNo(e, acc :+ e) }
}
}
def group(list: List[Int], acc: List[List[Int]]): List[List[Int]] = {
if (list.isEmpty) acc
else {
group(list.slice(7, list.length), list.take(7) :: acc)
}
}
group(getPhoneNo(1, List()), List.empty[List[Int]]).foreach(println)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment