gpt4 book ai didi

swift - 识别范围重叠

转载 作者:可可西里 更新时间:2023-11-01 01:03:48 24 4
gpt4 key购买 nike

我有一本描述一个人的名字、出生日期和死亡日期的字典。

var people = [ "Michael": [ "birth": 1900, "death" : 1975 ], "John": [ "birth": 1973, "death" : 2000 ], "Julian": [ "birth": 1950, "death" : 1985 ] ]

我想确定所有成员同时还活着的年份。

这是我相当粗暴且不可扩展的实现:

var years = [Int]()
var overlap = [Int]()
var overlapTwice = [Int]()
var overlapThree = [Int]()

for life in people.values {
var birth = Int(life["birth"]!)
var death = Int(life["death"]!)

for year in birth..<death {
if !years.contains(year) {
years.append(year)
} else {
overlap.append(year)
}
}
}

for x in overlap {
if !overlapTwice.contains(x) {
overlapTwice.append(x)
} else {
overlapThree.append(x)
}
}
print(overlapThree)

我想知道解决这个问题的正确方法,因为我显然需要为每个额外的范围编写一个循环

最佳答案

有一种更简单的方法可以解决这个问题。做一个循环。跟踪最大出生年份和最小死亡年份。那将是你的范围。

如果最大出生数最终大于最小死亡数,则没有重叠。

由于我对 Swift 不是很流利,因此以下内容主要是作为伪代码编写的:

var maxBirth = 0 // start with small value
bar minDeath = 9999 // start with large value
for life in people.values {
var birth = Int(life["birth"]!)
var death = Int(life["death"]!)

if birth > maxBirth {
maxBirth = birth
}
if death < minDeath {
minDeath = death
}
}

您的重叠范围将从 maxBirth 到 minDeath。

关于swift - 识别范围重叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32894734/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com