How to resolve the algorithm Self-describing numbers step by step in the Swift programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Self-describing numbers step by step in the Swift programming language
Table of Contents
Problem Statement
There are several so-called "self-describing" or "self-descriptive" integers. An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to N-1, the digit in each position is equal to the number of times that that digit appears in the number. For example, 2020 is a four-digit self describing number:
Self-describing numbers < 100.000.000 are: 1210, 2020, 21200, 3211000, 42101000.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Self-describing numbers step by step in the Swift programming language
Source code in the swift programming language
import Foundation
extension BinaryInteger {
@inlinable
public var isSelfDescribing: Bool {
let stringChars = String(self).map({ String($0) })
let counts = stringChars.reduce(into: [Int: Int](), {res, char in res[Int(char), default: 0] += 1})
for (i, n) in stringChars.enumerated() where counts[i, default: 0] != Int(n) {
return false
}
return true
}
}
print("Self-describing numbers less than 100,000,000:")
DispatchQueue.concurrentPerform(iterations: 100_000_000) {i in
defer {
if i == 100_000_000 - 1 {
exit(0)
}
}
guard i.isSelfDescribing else {
return
}
print(i)
}
dispatchMain()
You may also check:How to resolve the algorithm The Twelve Days of Christmas step by step in the Seed7 programming language
You may also check:How to resolve the algorithm Forest fire step by step in the Raku programming language
You may also check:How to resolve the algorithm Show ASCII table step by step in the 8086 Assembly programming language
You may also check:How to resolve the algorithm Filter step by step in the Pascal programming language
You may also check:How to resolve the algorithm Filter step by step in the OCaml programming language