aboutsummaryrefslogtreecommitdiff
path: root/challenge-063/mohammad-anwar/swift/ch-2.swift
blob: b6588a56523fd75cfa7e7c541ae129b2f8479744 (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
import Foundation

/*
Perl Weekly Challenge - 063

Task #2: Rotate String

https://perlweeklychallenge.org/blog/perl-weekly-challenge-063
*/

enum ParamError: Error {
    case missingWord
    case invalidWord
}

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

    if paramCount <= 1 {
        throw ParamError.missingWord
    }

    let word:String = CommandLine.arguments[1]

    if isValidWord(word) {
        let size:Int    = word.count;
        var temp:String = word
        var i:Int = 1
        var c:Int = 1

        while i <= size {
            let partA:String = String(temp.substring(to: i))
            let partB:String = String(temp.substring(from: i))
            temp = partB + partA
            print("[\(c)]: [\(temp)]")

            if temp == word {
                break
            }

            i = i + 1
            c = c + 1

            if i > size {
                i = 1
            }
        }

        print("Rotation: \(c)")
    }
    else {
        throw ParamError.invalidWord
    }
}
catch ParamError.missingWord {
    print("Missing word.")
}
catch ParamError.invalidWord {
    print("Invalid word.")
}
catch let error {
    print(error)
}

//
//
// Function

func isValidWord(_ word:String) -> Bool {

    let pattern = "^[xy]+$"
    let regex   = try! NSRegularExpression(pattern: pattern, options: .caseInsensitive)
    let range   = NSRange(location: 0, length: word.utf16.count)

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