Hackerrank Challenge - Problem Solving Part 6 - Plus Minus (Swift)

preview_player
Показать описание
HackerRank Challenge Problem Solving Part 6 in Swift Programming Language.
Рекомендации по теме
Комментарии
Автор

How did you learn how to do these challenges? I want to learn.

kutigbolahan
Автор

I want to share my code...
import Foundation

func getRatios(arreglo A: [Int]) -> (x: Double, y: Double, z: Double) {
var resX: Double = 0.0, resY: Double = 0.0, resZ: Double = 0.0;
let cuantos = Double(A.count) // here we avoid so many conversions
for elem in A {
if elem < 0 {
resX += 1
} else if elem > 0 {
resZ += 1
} else {
resY += 1
}
}
resX = resX / cuantos; resY = resY / cuantos; resZ = resZ / cuantos;
return (resX, resY, resZ)
}

func leaArregloInt(nombre nomArreglo: String?) -> [Int] {
guard let aTemp = "\\s+$", with: "", options: .regularExpression)
else {
fatalError("Mal ingreso de datos")
}

let resultado: [Int] = aTemp.split(separator: " ").compactMap {
if let entero = Int($0) {
return entero
} else {
if nomArreglo == nil {
fatalError("Mal ingreso con el arreglo desconocido")
}
fatalError("Mal ingreso con el arreglo \(nomArreglo!)")
}
}
return resultado
}

let arreglo = leaArregloInt(nombre: "arreglo")
let ratios = getRatios(arreglo: arreglo)
let strX = String(format: "%.6f", ratios.x)
let strY = String(format: "%.6f", ratios.y)
let strZ = String(format: "%.6f", ratios.z)
print("Ratios: X: \(strX) Y: \(strY) Z: \(strZ)")

/// Otra manera mediante formateo
let frmNum = NumberFormatter() /// creamos la clase
frmNum.numberStyle = .decimal; frmNum.maximumFractionDigits = 6;

if let xF = frmNum.string(from: NSNumber(value: ratios.x)),
let yF = frmNum.string(from: NSNumber(value: ratios.y)),
let zF = frmNum.string(from: NSNumber(value: ratios.z)) {
print("Ratios: X: \(xF), Y: \(yF), Z: \(zF)")
} else {
fatalError("Alguna joda pasó")
}

let testingDouble = frmNum.string(from: NSNumber(value: 2432423.23234))
print("\(testingDouble!)")

edgarrod