Created
April 3, 2019 08:59
-
-
Save ankit92ios/6cb5ae77949731b747d815a31a18f10b to your computer and use it in GitHub Desktop.
Day 1: Standard Deviation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
//Day 1: Standard Deviation | |
func StandardDeviation(numbers: [Int]) -> Double { | |
var sum = 0.0 | |
for eachNo in numbers { | |
sum += Double(eachNo) | |
} | |
let mean = sum / Double(numbers.count) | |
var sumOfSquare : Double = 0 | |
for eachNo in numbers{ | |
let diff = Double(eachNo) - mean | |
let square = pow(diff, 2) | |
sumOfSquare += square | |
} | |
let result = sqrt(sumOfSquare/Double(numbers.count)) | |
return result | |
} | |
//StandardDeviation(numbers: [10, 40, 30, 50, 20]) | |
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 arTemp = readLine() else { fatalError("Bad input") } | |
let ar: [Int] = arTemp.split(separator: " ").map { | |
if let arItem = Int($0.trimmingCharacters(in: .whitespacesAndNewlines)) { | |
return arItem | |
} else { fatalError("Bad input") } | |
} | |
guard ar.count == n else { fatalError("Bad input") } | |
let resultvalue = StandardDeviation(numbers: ar) | |
let result = String(format: "%.1f", resultvalue) | |
fileHandle.write(String(result).data(using: .utf8)!) | |
fileHandle.write("\n".data(using: .utf8)!) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment