aboutsummaryrefslogtreecommitdiff
path: root/challenge-078/mohammad-anwar/swift/ch-1.swift
blob: 31e817c0503f1797e2ca06c9c10b90a178aefe02 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import Foundation

/*

Perl Weekly Challenge - 078

Task #1: Leader Element

https://perlweeklychallenge.org/blog/perl-weekly-challenge-078

*/

enum ParamError: Error {
    case missingList
    case invalidList
}

do {
    let paramCount:Int = Int(CommandLine.argc)

    if paramCount <= 1 {
        throw ParamError.missingList
    }

    let list:String = CommandLine.arguments[1]
    if isValidList(list) {
        let array = list.components(separatedBy: ", ")

        var index:Int = 0;
        var leaderElements = [Int]();
        while index < array.count - 1 {
            let max:Int     = findMax(array, index + 1)
            let current:Int = Int(array[index])!

            if current > max {
                leaderElements.append(current)
            }
            index += 1
        }
        leaderElements.append(Int(array[index])!)

        print(array)
        print(leaderElements)
    }
    else {
        throw ParamError.invalidList
    }
}
catch ParamError.missingList {
    print("Missing list.")
}
catch ParamError.invalidList {
    print("Invalid list.")
}
catch let error {
    print(error)
}

//
//
// Functions

func isValidList(_ list:String) -> Bool {

    let pattern = "^[\\-?\\d\\,?\\s?]+$"
    let regex   = try! NSRegularExpression(pattern: pattern)
    let range   = NSRange(location: 0, length: list.utf16.count)

    if regex.firstMatch(in: list, options: [], range: range) != nil {
        return true
    }
    else {
        return false
    }
}

func findMax(_ array: [String], _ start:Int) -> Int {

    var window = [Int]()
    for i in start...array.count-1 {
        window.append(Int(array[i])!)
    }

    return window.max()!
}