我有一个我无法弄清楚的问题。有没有更简单的方法将数组分成其他数组。在下面的代码中,我执行跟踪路由并过滤除ping速率之外的所有内容。
然后我将该数组分解为单个节点。唯一的缺点是,如果只需要2个跳,那么我会收到错误,#34;致命错误:索引超出范围。"因为我已经设置了创建15个节点数组。我也尝试过..
let count = pingRate.count
if count < 15 {
aNodeArray += pingRate[14]
}
有更简单的方法吗?我希望有一种方法可以执行.count,然后填充每个节点上需要的Int。
let task = Process()
task.launchPath = "/bin/sh"
task.arguments = ["-c", "traceroute -nm 15 -q 1 8.8.8.8"]
let pipe = Pipe()
task.standardOutput = pipe
task.launch()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output = NSString(data: data, encoding: String.Encoding.utf8.rawValue) as! String
var array = output.components(separatedBy: " ")
array = array.filter({ $0.contains(".")})
let pingRate: [[Double]] = array.enumerated().filter({ index, _ in
index % 2 != 0
}).map { [Double($0.1)!] }
let aNode = pingRate[0]
let bNode = pingRate[1]
let cNode = pingRate[2]
let dNode = pingRate[3]
let eNode = pingRate[4]
aNodeArray += aNode
bNodeArray += bNode
cNodeArray += cNode
dNodeArray += dNode
eNodeArray += eNode
完成后我会排序并找到最小值,最大值和平均值。
let sorted = aNodeArray.sorted()
let numbers = sorted
print(numbers)
let min = numbers[0]
var sum = 0 as Double
for number in numbers {
sum += number
}
let mean = Double(sum) /
Double (numbers.count)
let x = mean
let avg = round(1000.0 * x) / 1000.0
let maxBR = numbers.last! as Double
let max = round(1000.0 * maxBR) / 1000.0
print(min)
print(max)
print(avg)
修改的
我偶然发现了大块的事情并且大步走了...... Swift: what is the right way to split up a [String] resulting in a [[String]] with a given subarray size?
我正试图找到一种方法来实现我的需求
修改
看着那段代码。任何人都可以告诉我为什么我得到彩色旋转轮,直到过程()完成?
答案 0 :(得分:0)
我知道有更高效的算法来计算您的ping率统计数据,但下面的代码应该可以胜任。
let task = Process()
task.launchPath = "/bin/sh"
task.arguments = ["-c", "traceroute -nm 15 -q 1 8.8.8.8"]
let pipe = Pipe()
task.standardOutput = pipe
task.launch()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
guard
let pingRates = String(data: data, encoding: .utf8)?
.components(separatedBy: " ")
.filter({ $0.contains(".") })
.flatMap({ Double($0) }),
pingRates.count > 0
else {
return
}
print("ping rate(min) = \(pingRates.min()!.rounded())")
print("ping rate(max) = \(pingRates.max()!.rounded())")
print("ping rate(avg) = \((pingRates.reduce(0, +) / Double(pingRates.count)).rounded())")
消除输出中IP地址的技巧是让Double.init
失败,然后flatMap
将删除这些nil值。