Created
September 22, 2017 00:56
-
-
Save KaiCode2/dee2997db20d9b65fa1c09ccc4d3893b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//: Playground - noun: a place where people can play | |
import UIKit | |
func closestPermutation(forNumber number: Int) -> Int { | |
guard number.digits().sorted(by: <) != number.digits() else { return number } | |
var currentPurmutation = number | |
var lastN: Float = 2 | |
while true { | |
for i in 1...Int(powf(2, lastN - 1)) { | |
var newPurmutation = currentPurmutation.digits() | |
newPurmutation.swapAt(number.digits().count - 1, number.digits().count - i) | |
currentPurmutation = newPurmutation.intFromDigits()! | |
if currentPurmutation < number { | |
return currentPurmutation | |
} | |
} | |
lastN += 1 | |
} | |
} | |
extension Int { | |
func digits() -> [Int] { | |
return "\(self)".characters.flatMap({ (char) -> Int? in | |
return Int(String(char)) | |
}) | |
} | |
} | |
extension Array where Element == Int { | |
func intFromDigits() -> Int? { | |
let returnValue = flatMap({ number -> String in return String(number) }).reduce("", +) | |
return Int(returnValue) | |
} | |
} | |
closestPermutation(forNumber: 1234) | |
closestPermutation(forNumber: 1834) | |
closestPermutation(forNumber: 1842) | |
closestPermutation(forNumber: 2381) | |
closestPermutation(forNumber: 100) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment