Sort a string array in Swift using a function

Asked

Viewed 424 times

1

I am in need of a help to solve the following programming logic problem on Swift.

The task is to arrange the array below downwards using a function.

Description: You must implement an algorithm that receives a list of strings with a specific format and returns it in a descending order. Each string will be one month in which TAG delivered their boxes to the club members (ex: "January/2017", "March/2018", "April/2016"). The sort must be done in descending form (more recent to older) Its algorithm must be a function, written in Swift 4.x, whose call must be made as follows:

let mesesTag = [ "janeiro/2018", "novembro/2017", "fevereiro/2018", "março/2017", "julho/2016", "março/2018" ]

let mesesTagOrdenados = ordenar(mesesTag)

print(mesesTagOrdenados)

// resultado para este exemplo deve ser: // [ "março/2018", "fevereiro/2018", "janeiro/2018", "novembro/2017", "março/2017", "julho/2016" ]
  • 2

    Rodrigo, please add the code of your solution and explain what is not working. As described the question currently sounds like "Solve my programming task".

3 answers

5

Caro Rodrigo,

The activity developed by your instructor aims to improve your knowledge and will for me dear that is very important in our area. Do not feel satisfied to receive the solution of a problem, so you learn nothing and become a developer Ctr+c, Ctr+v, man, try to do, put the code here we will gladly help you, but try to do....

3

Try it like this:

import UIKit

// MARK: - Funções

func ordenar(_ meses: [String]) -> [String] {

    let df = DateFormatter(dateFormat: "MMMM/yyyy")
    let mesesEmData = meses.map { (mes) -> Date? in df.date(from: mes) }
    let mesesEmDataSemNulos = mesesEmData.flatMap { $0 }

    let mesesOrdenados = mesesEmDataSemNulos.sorted(by: { (mes1, mes2) -> Bool in
        mes1.compare(mes2) == .orderedAscending
    })

    return mesesOrdenados.map { df.string(from: $0) }
}

extension DateFormatter {
    convenience init(dateFormat: String) {
        self.init()
        self.dateFormat = dateFormat
        self.locale = Locale(identifier: "pt_BR")
    }
}

// MARK: - Questão

let mesesTag = [ "janeiro/2018", "novembro/2017", "fevereiro/2018", "março/2017", "julho/2016", "março/2018" ]

let mesesTagOrdenados = ordenar(mesesTag)

print(mesesTagOrdenados)

Log:

["julho/2016", "março/2017", "novembro/2017", "janeiro/2018", "fevereiro/2018", "março/2018"]

0

I agree with Rafael Leão that you should put your code so we can help you solve your problem, but since you had free time, here goes:

let mesesTag = [ "janeiro/2018", "novembro/2017", "fevereiro/2018", "março/2017", "julho/2016", "março/2018" ]       
let mesesTagOrdenados = ordenar(mesesTag)
print(mesesTagOrdenados)

enum months: String {
    case janeiro, fevereiro, marco, abril, maio, junho, julho, agosto, setembro, outubro, novembro, dezembro
}

func ordenar(_ meses: [String]) -> [String] {
    var splittedArray = [[String]]()
    for mes in meses {
        let splitted = mes.split(separator: "/")
        let first = String(splitted[0])
        let second = String(splitted[1])
        splittedArray.append([first, second])
    }

    let yearOrdered = splittedArray.sorted(by: sortByYear)
    let monthOrdered = yearOrdered.sorted(by: sortByMonth)

    let result = monthOrdered.map { (item) -> String in
        item.joined(separator: "/")
    }

    return result
}

func sortByYear(_ s1: [String], _ s2: [String]) -> Bool {
    let anoS1 = s1.last!
    let anoS2 = s2.last!

    if anoS1 > anoS2 {
        return true
    } else {
        return false
    }
}

func sortByMonth(_ s1: [String], _ s2: [String]) -> Bool {
    let mesS1 = months(rawValue: s1.first!.lowercased().replacingOccurrences(of: "ç", with: "c"))!.hashValue
    let mesS2 = months(rawValue: s2.first!.lowercased().replacingOccurrences(of: "ç", with: "c"))!.hashValue
    let anoS1 = s1.last!
    let anoS2 = s2.last!

    if mesS1 > mesS2 && anoS1 >= anoS2 {
        return true
    } else {
        return false
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.