Oleg Gordiichuk
Oleg Gordiichuk

Reputation: 15512

Int array to Int standard method

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())!

Upvotes: 2

Views: 115

Answers (3)

Idan
Idan

Reputation: 5450

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
}

Upvotes: 1

Martin R
Martin R

Reputation: 539745

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

Upvotes: 7

Efi Weiss
Efi Weiss

Reputation: 650

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

Upvotes: 1

Related Questions