001 Count the Digit/Codewars — Daily challenge

Shin Yulin
iOS 雛鳥學飛之路
2 min readJun 14, 2021

Description:

Take an integer n (n >= 0) and a digit d (0 <= d <= 9) as an integer.

Square all numbers k (0 <= k <= n) between 0 and n.

Count the numbers of digits d used in the writing of all the k**2.

Call nb_dig (or nbDig or ...) the function taking n and d as parameters and returning this count.

Examples:

n = 10, d = 1
the k*k are 0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100
We are using the digit 1 in: 1, 16, 81, 100. The total count is then 4.

nb_dig(25, 1) returns 11 since
the k*k that contain the digit 1 are:
1, 16, 81, 100, 121, 144, 169, 196, 361, 441.
So there are 11 digits 1 for the squares of numbers between 0 and 25.

TryCode:

func nbDig(_ n: Int, _ d: Int) -> Int {
var count = 0
for i in 0...n {
let square = "\\(i*i)"
for digit in square{
if "\\(digit)" == "\\(d)"{
count += 1
}
}
}
return count
}

BetterCode:

func nbDig(_ n: Int, _ d: Int) -> Int {
return (0...n).map{"\\($0 * $0)".filter { $0 == Character("\\(d)")}}.flatMap { $0 }.count
}

Note:

Map(_:)

func map<T>(_ transform: (Element) throws -> T) rethrows -> [T]
  • transform 表示傳入的一個 function 或 closure,用來轉換陣列裡的元素。輸入參數與回傳結果型別可以不同。
  • map() 回傳結果為陣列。

Filter(_:)

func filter(_ isIncluded: (Character) throws -> Bool) rethrows -> (__owned String)
  • includeElement 表示傳入的一個 function 或 closure,判斷陣列個元素是否符合條件,符合則則進行回傳。
  • filter() 回傳結果為陣列。

FlatMap

func flatMap<SegmentOfResult>(_ transform: (Element) throws -> SegmentOfResult) rethrows -> [SegmentOfResult.Element] where SegmentOfResult : Sequence

  • transform 表示傳入的一個 function 或 closure,用來轉換陣列裡的元素。輸入參數與回傳結果型別可以不同。
  • 等同於先執行map()在執行Flatten將元素取出來形成一個新陣列

“$0” In closures

“Swift automatically provides shorthand argument names to inline closures, which can be used to refer to the values of the closure’s arguments by the names $0, $1, $2, and so on.”

--

--