Created
April 3, 2019 08:49
-
-
Save ankit92ios/3fcb4ce9b4fd65a686523012cc87fa19 to your computer and use it in GitHub Desktop.
Day 0:weightMean
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 0:weightMean | |
func weightMean(numbers: [Int] , weights : [Int]) -> Double { | |
var sum = 0.0 | |
var totalWeights = 0 | |
for i in 0..<numbers.count { | |
sum += Double(numbers[i] * weights[i]) | |
totalWeights += weights[i] | |
} | |
let weightMean = sum / Double(totalWeights) | |
return weightMean | |
} | |
//let number = Int(readLine(strippingNewline: true)!)! | |
//let arrValue = readLine(strippingNewline: true)!.characters | |
// .split {$0 == " "} | |
// .map (Int.init) | |
//print(mean(numbers: arrValue)) | |
//print(median(numbers: arrValue)) | |
//print(mode(numbers: arrValue)) | |
//let arrValue = [1,1,1,2,2,2,3,3] | |
//print(mode(numbers: arrValue)) | |
//weightMean(numbers: [10, 40, 30, 50, 20], weights : [1, 2, 3, 4, 5]) | |
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 let arTemp2 = readLine() else { fatalError("Bad input") } | |
let ar2: [Int] = arTemp2.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 = weightMean(numbers: ar, weights : ar2) | |
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