Skip to content

Instantly share code, notes, and snippets.

@H-Ghadirian
Last active March 10, 2019 15:43
Show Gist options
  • Save H-Ghadirian/d2b136016d3a7584a2fa56037d9ca374 to your computer and use it in GitHub Desktop.
Save H-Ghadirian/d2b136016d3a7584a2fa56037d9ca374 to your computer and use it in GitHub Desktop.
//A standard phone number pad has the following layout.
//1 2 3
//4 5 6
//7 8 9
// 0
//Using this layout and a starting digit we can generate numbers as follows: The first digit is the
//starting digit and each subsequent digit is directly left, right, above or below the previous digit on
//the number pad. For example if the starting digit is 1, 1256 is a valid number, but 1289 is not
//valid because 8 is not directly next to 2. Write a function that takes a starting digit d and an
//integer n as input and returns a list of all unique numbers of length n generated in this way.
//Test cases:
//f(5, 1) = [5]
//f(1, 3) = [121, 123, 125, 141, 145, 147]
import Foundation
func printValidDigits(_ startDigit:Int, _ numberOfRemainingMoves:Int,_ moves:[Int]) {
if numberOfRemainingMoves <= 0 {
fatalError("invalid number of moves")
}
if numberOfRemainingMoves == 1 {
print(moves + [startDigit])
return
}
var options:[Int] = []
switch startDigit {
case 0:
options = [8]
case 9:
options = [6,8]
case 8:
options = [7,5,9,0]
case 7:
options = [4,8]
case 6:
options = [3,5,9]
case 5:
options = [4,2,6,8]
case 4:
options = [1,5,7]
case 3:
options = [2,6]
case 2:
options = [1,5,3]
case 1:
options = [2,4]
default:
fatalError("invalid number")
}
for option in options {
printValidDigits(option,numberOfRemainingMoves-1, moves + [startDigit])
}
}
func printValidSequences(_ startDigit:Int,_ numberOfRemainingMoves:Int){
printValidDigits(startDigit,numberOfRemainingMoves,[])
}
printValidSequences(1,3)
printValidSequences(5,1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment