-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathCounting Sort 1.swift
39 lines (29 loc) · 1.15 KB
/
Counting Sort 1.swift
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
import Foundation
/*
* Complete the 'countingSort' function below.
*
* The function is expected to return an INTEGER_ARRAY.
* The function accepts INTEGER_ARRAY arr as parameter.
*/
func countingSort(arr: [Int]) -> [Int] {
var array: [Int] = Array(repeating: 0, count: 100)
arr.forEach {
array[$0] += 1
}
return array
}
let stdout = ProcessInfo.processInfo.environment["OUTPUT_PATH"]!
FileManager.default.createFile(atPath: stdout, contents: nil, attributes: nil)
let fileHandle = FileHandle(forWritingAtPath: stdout)!
guard let n = Int((readLine()?.trimmingCharacters(in: .whitespacesAndNewlines))!)
else { fatalError("Bad input") }
guard let arrTemp = readLine()?.replacingOccurrences(of: "\\s+$", with: "", options: .regularExpression) else { fatalError("Bad input") }
let arr: [Int] = arrTemp.split(separator: " ").map {
if let arrItem = Int($0) {
return arrItem
} else { fatalError("Bad input") }
}
guard arr.count == n else { fatalError("Bad input") }
let result = countingSort(arr: arr)
fileHandle.write(result.map{ String($0) }.joined(separator: " ").data(using: .utf8)!)
fileHandle.write("\n".data(using: .utf8)!)