2

I am trying to convert an Int array to an Int number. What I am now doing is converting it to a String array and then use the joined() function. Is there a more efficient way to do this?

Example:

let sortedIntArray = String(number).characters.map{Int(String($0)) ?? 0}.sorted(by: { $0 > $1 })

let desOrder =  Int(sortedIntArray.map{String($0)}.joined())!
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
Oleg Gordiichuk
  • 15,240
  • 7
  • 60
  • 100

3 Answers3

7

In your case, sortedIntArray is an array of single-digit numbers, and then you can combine them without any conversion to strings:

let sortedIntArray = [4, 2, 1]
let result = sortedIntArray.reduce(0) { 10 * $0 + $1 }
print(result) // 421

Combined with the dfri's elegant solution to split the number into an integer array:

let number = 1439

let descDigits = sequence(state: number, next: { (num: inout Int) -> Int? in
    return num > 0 ? (num % 10, num /= 10).0 : nil
}).sorted(by: >)
print(descDigits) // [9, 4, 3, 1]

let descNumber = descDigits.reduce(0) { 10 * $0 + $1 }
print(descNumber) // 9431
Community
  • 1
  • 1
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
1

Use the reduce method instead of map and joined

let desOrder = Int(sortedIntArray.reduce("") { $0 + String($1) })

reduce(intialResult: Result, (Result, Any) throws -> Result) rethrows

Efi Weiss
  • 638
  • 6
  • 12
1

You asked about efficiency, as to this answer by Martin R, my guess is that is the most efficient answer

var number = 1992843
var arr = [Int]()

while number > 0 {
    arr.append(number % 10)
    number = number / 10
}

arr.sort() 
arr.reverse()

for n in arr {
    number = number * 10
    number += n
}
Community
  • 1
  • 1
Idan
  • 5,405
  • 7
  • 35
  • 52