Created
August 3, 2020 13:37
-
-
Save sparlampe/4523d87930c9bc90bc50aad0ad6cbddf to your computer and use it in GitHub Desktop.
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
def maxShared(friendsNodes: Int, friendsFrom: Array[Int], friendsTo: Array[Int], friendsWeight: Array[Int]): Int = { | |
val allNodesFrom = friendsFrom ++ friendsTo | |
val allWeights = friendsWeight ++ friendsWeight | |
val allNodesTo = friendsTo ++ friendsFrom | |
val nodeToNodeOverInterest = allNodesFrom | |
.zipWithIndex | |
.foldLeft(Map[Int, Map[Int, Set[Int]]]())((acc, p) => { | |
val interest = allWeights(p._2) | |
val peer = allNodesTo(p._2) | |
val currentConnections = acc.getOrElse(p._1, Map[Int, Set[Int]]()) | |
val currentConnectionsOverInterest = currentConnections.getOrElse(interest, Set.empty) | |
val newConnectionsOverInterest = interest -> (currentConnectionsOverInterest + peer) | |
val newConnections = currentConnections + newConnectionsOverInterest | |
acc + (p._1 -> newConnections) | |
}) | |
def isNodeConnectedOverInterest(n1: Int, n2: Int, interest: Int, intermediatePeers: Set[Int]): Boolean = { | |
val connections = nodeToNodeOverInterest(n1).getOrElse(interest, Set.empty) | |
connections.contains(n2) match { | |
case true => true | |
case false if connections.subsetOf(intermediatePeers) => false | |
case _ => | |
val possiblePaths = connections -- intermediatePeers | |
possiblePaths.foldLeft(false)((acc, p) => acc || isNodeConnectedOverInterest(p, n2, interest, intermediatePeers ++ connections)) | |
} | |
} | |
val pairsWithNumberOfConnections = (1 to friendsNodes) | |
.combinations(2) | |
.toList | |
.map(p => { | |
val firstNode = p(0) | |
val secondNode = p(1) | |
val numberOfConnections = friendsWeight.toSet.toList.map(intr => isNodeConnectedOverInterest(firstNode, secondNode, intr, Set.empty)).filter(p => p).size | |
(p, numberOfConnections) | |
}) | |
val maxConnections = pairsWithNumberOfConnections.map(_._2).max | |
val pairsWithMaxNumOfConnections = pairsWithNumberOfConnections.filter(_._2 == maxConnections).map(_._1) | |
pairsWithMaxNumOfConnections.map(p => p(0) * p(1)).max | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment