言葉で表現する方法はよくわかりませんが、コードが役立つはずです。
var People = [
.init(name: "Sam", friends: ["James", "Tom", "Rick"]),
.init(name: "Tom", friends: ["Callum", "Steve", "Sam"]),
.init(name: "Adam", friends: ["Harry", "Diane", "William"]),
.init(name: "William", friends: ["Rodger", "Adam", "Bill"]),
.init(name: "Guy", friends: ["Zack", "Frank", "Cody"])
]
印刷するアラートを生成したい
" Sam is in the same social circle as Tom " / " Tom is in the same social circle as Sam "
そして
" Adam is in the same social circle as William " / " William is in the same social circle as Adam "
そして
" Guy has no common social circles "
私がこれを試みた方法は、最初に名前の配列を作成することです:[String]、次に友人に対して同じことを行い、次の関数を使用して[[String]]を[String]に変換します...
func loadNamesArray() -> [String] {
return self.People.map { $0.name }
}
func loadFriendsArray() -> [String] {
let arrayOfFriends = self.People.map { $0.friends }
let friends = arrayOfFriends.flatMap { $0 }
return friends
}
次に、2つの配列を相互比較して、この関数を使用している一般の人々に警告します...
func loadCommonInteractingArray() -> [String] {
let output = loadNamesArray().filter{ loadFriendsArray().contains($0) }
return output
}
しかし、これは["Sam"、 "Tom"、 "Adam"、 "William"]を返すだけであり、ここから目的の結果を得るためにどこに行けばよいかわかりません。つまり、単なるリストではなく、一致するペアを特定します。一致するもの。
ありがとう
struct Person {
let name: String
let friends: [String]
}
var people: [Person] = [
.init(name: "Sam", friends: ["James", "Tom", "Rick"]),
.init(name: "Tom", friends: ["Callum", "Steve", "Sam"]),
.init(name: "Adam", friends: ["Harry", "Diane", "William"]),
.init(name: "William", friends: ["Rodger", "Adam", "Bill"])]
func loadCommonInteracting(in people: [Person]) -> [String] {
var connections: [String] = []
people.forEach { person in
let friends = people.filter{ $0.friends.contains(person.name) }
for friend in friends {
connections.append("\(person.name) is in the same social circle as \(friend.name)")
}
}
return connections
}
let connections = loadCommonInteracting(in: people)
for connection in connections {
print(connection)
}
これは印刷されます
サムはトムと同じ社会的サークルにいます
トムはサムと同じ社会的サークルにいます
アダムはウィリアムと同じ社会的サークルにいます
ウィリアムはアダムと同じ社会的サークルにいます
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加