Created
October 15, 2019 01:10
-
-
Save Farini/fc1c3c86e2b5c37cbb584a9ca947f8d5 to your computer and use it in GitHub Desktop.
Friends suggestions implementation
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 UIKit | |
// MARK: - Friends | |
class Person:Equatable{ | |
static func == (lhs: Person, rhs: Person) -> Bool { | |
return lhs.name == rhs.name | |
} | |
var name:String | |
var friends:[Person] //= [] | |
init(name:String) { | |
self.name = name | |
self.friends = [] | |
} | |
func suggestFriends() -> [Person]?{ | |
var suggestions:[Person] = [] | |
var visited:[Person] = [] | |
var stack = friends | |
while !stack.isEmpty { | |
guard let next = stack.first else { return nil } | |
// print("Next: \(next.name) + \(next.friends.count) friends") | |
// Add (non-visited) persons to stack | |
for person in next.friends.filter({$0 != self && !visited.contains($0)}){ | |
stack.append(person) | |
visited.append(person) | |
} | |
// Suggest friend | |
if !friends.contains(next){ | |
suggestions.append(next) | |
} | |
stack.removeFirst() | |
} | |
return suggestions | |
} | |
} | |
var angie = Person(name: "Angie") | |
var betty = Person(name: "Betty") | |
var conrad = Person(name: "Conrad") | |
var dan = Person(name: "Dan") | |
var eva = Person(name: "Eva") | |
var fred = Person(name: "Fred") | |
var gabe = Person(name: "Gabe") | |
var helen = Person(name: "Helen") | |
var isabel = Person(name: "Isabel") | |
angie.friends = [betty, conrad] | |
betty.friends = [angie, conrad, dan] | |
conrad.friends = [angie, betty] | |
dan.friends = [betty, eva, fred] | |
eva.friends = [dan, helen, isabel] | |
fred.friends = [dan] | |
gabe.friends = [helen] | |
helen.friends = [isabel, eva, gabe] | |
isabel.friends = [helen, eva] | |
print("\n --- FRIENDS SUGGESTIONS ---\n") | |
let angiesSuggestions = angie.suggestFriends() | |
print("For Angie:") | |
for p in angiesSuggestions ?? []{ | |
print("\t Name: \(p.name) has \(p.friends.count) friends") | |
} | |
print("---") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment