blob: 6bde4f3bb419ba4ae5874f95057bba4113a02c4f (
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
|
import Foundation
/*
Week 139:
https://theweeklychallenge.org/blog/perl-weekly-challenge-139
Task #1: JortSort
You are given a list of numbers.
Write a script to implement JortSort. It should return true/false depending if the given list of numbers are already sorted.
*/
enum ParamError: Error {
case missingList
case invalidList
}
do {
let paramCount:Int = Int(CommandLine.argc)
if paramCount <= 1 {
throw ParamError.missingList
}
let l:String = CommandLine.arguments[1]
if isValidList(l) {
let n = l.components(separatedBy: ",")
var s = n
s.sort()
var status:Int = 1
for i in 0...n.count-1 {
let _n:Int = Int(n[i])!
let _s:Int = Int(s[i])!
if _n != _s {
status = 0
break
}
}
print(status)
}
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
}
}
|