Skip to content

Instantly share code, notes, and snippets.

@phausler
Created September 10, 2016 17:56
Show Gist options
  • Save phausler/d8d5f33e7469aab491893fac4058c650 to your computer and use it in GitHub Desktop.
Save phausler/d8d5f33e7469aab491893fac4058c650 to your computer and use it in GitHub Desktop.
Numeric Progressions
/// - Note: this requires Swift 3.0 (Mac OS X or iOS, Linux currently crashes in locale fetching)
import Foundation
func permuteLetterCountCycles(_ start: Int, _ formatter: NumberFormatter) -> [String] {
var foundNumbers = Set<Int>()
var result = Array<String>()
var number = start
formatter.numberStyle = .spellOut
while true {
// convert the number into the string representation (and presume all locales have a string representation)
let str = formatter.string(from: NSNumber(value: number))!
// count the grapheme clusters for the number word
let count = str.characters.count
// add the progression of strings to the resultant array
result.append(str)
// if there is a cycle then terminate the permutation
if foundNumbers.contains(count) {
break
}
// record the number so that cycle detection can terminate before an infinite loop
foundNumbers.insert(count)
// the next input to the conversion is the resultant length
number = count
}
return result
}
let formatter = NumberFormatter()
var longestGlobalChain: [String]?
var longestGlobalLocale: Locale?
for locale in Locale.availableIdentifiers.map({ Locale(identifier: $0) }) {
formatter.locale = locale
var longestChain: [String]?
// iterating past 1000 can potentially be slow
for idx in 0..<1000 {
let chain = permuteLetterCountCycles(idx, formatter)
// record the longest chain of number to string representations for this locale
if let prevChain = longestChain {
if prevChain.count < chain.count {
longestChain = chain
}
} else {
longestChain = chain
}
}
// record the longest chain of number to string representations for all locales
if let prevChain = longestGlobalChain {
if prevChain.count < longestChain!.count {
longestGlobalChain = longestChain
longestGlobalLocale = locale
}
} else {
longestGlobalChain = longestChain
longestGlobalLocale = locale
}
print("\(Locale.current.localizedString(forIdentifier: locale.identifier)!) (\(longestChain!.count)) \(longestChain!)")
}
print("\(Locale.current.localizedString(forIdentifier: longestGlobalLocale!.identifier)!) \(longestGlobalChain!.count) \(longestGlobalChain!)")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment